diff --git a/.gitignore b/.gitignore index ea8c4bf..c41cc9e 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -/target +/target \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 07cb7e0..2af6dcb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "anyhow" +version = "1.0.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08f9b8508dccb7687a1d6c4ce66b2b0ecef467c94667de27d8d7fe1f8d2a9cdc" + [[package]] name = "atty" version = "0.2.14" @@ -80,6 +86,7 @@ checksum = "0bca1619ff57dd7a56b58a8e25ef4199f123e78e503fe1653410350a1b98ae65" name = "data_generator" version = "0.1.0" dependencies = [ + "anyhow", "clap", "colorful", "rand", diff --git a/Cargo.toml b/Cargo.toml index cd84ab5..a54560c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,4 +9,4 @@ edition = "2021" colorful = "0.2.1" clap = { version = "3.1.18", features = ["derive"] } rand = "0.8.5" - +anyhow = "1.0.57" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..bca70b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2022 Caviar-X + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..30404ce --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +TODO \ No newline at end of file diff --git a/src/cli.rs b/src/cli.rs deleted file mode 100644 index 6f60128..0000000 --- a/src/cli.rs +++ /dev/null @@ -1,13 +0,0 @@ -use clap::Parser; - -/// A simple DSL which allows you to create data simple and fast -#[derive(Parser,Debug)] -#[clap(author = "Caviar-X",version = "0.0.1",about,long_about = None)] -pub struct Args { - /// The generate times - #[clap(short, long, default_value_t = 10)] - count : u8, - /// The name of the file - #[clap(short, long)] - file : String -} diff --git a/src/lib.rs b/src/lib.rs index c54eeb4..b2819a7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1 @@ -pub mod cli; pub mod parser; \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index c80e1f7..a2a7af9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,34 @@ +use clap::Parser as ClapParser; +use colorful::*; use data_generator::parser::Parser; -fn main() { - let p = Parser::new_with_context("{int from 0 to 1e5}".into()); - println!("{:?}",p.next_token()); +use std::fs::File; +use std::io::Write; +/// A simple DSL which allows you to create data simple and fast +#[derive(ClapParser, Debug, Clone)] +#[clap(author = "Caviar-X",version = "1.0.0",about,long_about = None)] +pub struct Args { + /// The generate times + #[clap(short, long, default_value_t = 10)] + pub count: u8, + /// The name of the file + #[clap(short, long)] + pub file: String, +} +fn main() { + let params: Args = Args::parse(); + for i in 1..=params.count { + let mut data: File = File::create(format!("{}.in", i)).expect("Failed to create file"); + let mut parser: Parser = Parser::new(params.clone().file); + loop { + let clone = parser.clone(); + let token: Option> = parser.next_token(); + if token == None { + break; + } + if let Some(t) = token { + write!(data, "{} ", clone.parse(t).unwrap()).expect("Failed to write data"); + } + } + eprintln!("{}", format!("Generating file {}.in", i).color(Color::Blue)); + } } diff --git a/src/parser.rs b/src/parser.rs index 048fd81..dfd28c8 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1,9 +1,12 @@ +use anyhow::*; +use colorful::*; use rand::prelude::*; use std::fs::*; +use std::iter::repeat_with; #[derive(Clone, Debug)] pub struct Parser { pub file: Option, - position: usize, + pub position: usize, context: String, } impl Parser { @@ -22,45 +25,108 @@ impl Parser { } } pub fn next_token(&mut self) -> Option> { - if self.position == self.context.len() { + if self.position == (self.context.len() - 1) { return None; } let substr: &str = self .context - .get(self.position..self.context.len()) + .get(self.position..) .expect("Failed to get token"); let (l, r) = ( substr.find('{').expect("Failed to get token") + 1, substr.find('}').expect("Failed to get token"), ); - self.position += (r - l) + 2; + self.position += (r - l) + 2; //plus {} Some( substr - .get(l..r) + .get((l)..(r)) .expect("Failed to get token") .split_whitespace() .collect::>(), ) } - fn parse(&self, tokens: Vec<&str>) -> Option { + fn is_vailid_token(&self, token: &str) -> bool { + self.parse(vec![token]).is_ok() || token.parse::().is_ok() + } + pub fn parse(&self, tokens: Vec<&str>) -> Result { if tokens.len() != 1 { return self.parse_statements(tokens); } match tokens[0] { - "short" | "i16" => random::().to_string(), - "int" | "i32" => random::().to_string(), - "long long" | "i64" => random::().to_string(), - "int128_t" | "i128" => random::().to_string(), - "unsigned short" | "u16" => random::().to_string(), - "unsigned int" | "u32" => random::().to_string(), - "unsigned long long" | "u64" => Some(random::().to_string()), - "uint128_t" | "u128" => Some(random::().to_string()), - _ => { - None + "short" | "i16" => Ok(random::().to_string()), + "int" | "i32" => Ok(random::().to_string()), + "i64" => Ok(random::().to_string()), + "int128_t" | "i128" => Ok(random::().to_string()), + "u16" => Ok(random::().to_string()), + "u32" => Ok(random::().to_string()), + "u64" => Ok(random::().to_string()), + "uint128_t" | "u128" => Ok(random::().to_string()), + "bigint" => { + let mut iter = repeat_with(|| thread_rng().gen_range(48_u8..57_u8) as char) + .take(random::() as usize); + let num = iter.position(|x| x != '0'); + return Ok(if num == None { + "0".into() + } else { + iter.clone().collect::>()[num.unwrap() as usize..] + .iter() + .collect::() + }); } + "string" => Ok( + repeat_with(|| thread_rng().gen_range(20_u8..126_u8) as char) + .take(random::() as usize) + .collect::(), + ), + "char" => Ok(random::().to_string()), + _ => bail!( + "{}", + format!( + "failed to parse at position {} : read undeclared tokens", + self.position + 1 + ) + .color(Color::Red) + .bold() + ), } } - fn parse_statements(&self, tokens: Vec<&str>) -> String { - todo!() + pub fn parse_statements(&self, tokens: Vec<&str>) -> Result { + let mut ret: Result = Ok(String::new()); + for (c, i) in tokens.clone().into_iter().enumerate() { + if ret.is_err() { + break; + } + match i { + "to" => { + ret = Ok(thread_rng() + .gen_range( + tokens[c - 1].parse::().expect("Failed to parse") + ..tokens[c + 1].parse::().expect("Failed to parse"), + ) + .to_string()); + } + _ => { + if !self.is_vailid_token(i) { + ret = Err(anyhow!( + "{}", + format!( + "failed to parse at position {} : read undeclared tokens", + self.position + 1 + ) + .color(Color::Red) + .bold() + )); + } + } + } + } + ret + } +} +#[cfg(test)] +mod tests { + #[test] + fn test_parse() { + todo!(); } }