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
//! Parsing via regular expressions using format syntax //! //! Deriving trait `Reformation` will also implement //! trait `FromStr`, with `Err=Box<Error>` //! //! Derive will require attribute reformation to specify format string, //! which will be treated as format string -> regular expression string //! //! Types implementing `Reformation` by default: //! //! + signed integers: `i8` `i16` `i32` `i64` `i128` `isize` //! + unsigned integers: `u8` `u16` `u32` `u64` `u128` `usize` //! + floats: `f32` `f64` //! + `String`, &str //! + `char` //! //! ## Structs //! //! ``` //! use reformation::Reformation; //! //! #[derive(Reformation, Debug)] //! #[reformation(r"{year}-{month}-{day} {hour}:{minute}")] //! struct Date{ //! year: u16, //! month: u8, //! day: u8, //! hour: u8, //! minute: u8, //! } //! //! fn main(){ //! let date = Date::parse("2018-12-22 20:23").unwrap(); //! //! assert_eq!(date.year, 2018); //! assert_eq!(date.month, 12); //! assert_eq!(date.day, 22); //! assert_eq!(date.hour, 20); //! assert_eq!(date.minute, 23); //! } //! ``` //! //! ## Tuple Structs //! //! ``` //! use reformation::Reformation; //! //! #[derive(Reformation)] //! #[reformation(r"{} -> {}")] //! struct Predicate(Empty, char); //! //! #[derive(Reformation, Debug, PartialEq)] //! #[reformation(r"Empty")] //! struct Empty; //! //! fn main(){ //! let p = Predicate::parse("Empty -> X").unwrap(); //! assert_eq!(p.0, Empty); //! assert_eq!(p.1, 'X'); //! } //! ``` //! //! ## Enums //! ``` //! use reformation::Reformation; //! //! #[derive(Reformation, Eq, PartialEq, Debug)] //! enum Ant{ //! #[reformation(r"Queen\({}\)")] //! Queen(String), //! #[reformation(r"Worker\({}\)")] //! Worker(i32), //! #[reformation(r"Warrior")] //! Warrior //! } //! //! fn main(){ //! let queen = Ant::parse("Queen(We are swarm)").unwrap(); //! assert_eq!(queen, Ant::Queen("We are swarm".to_string())); //! //! let worker = Ant::parse("Worker(900000)").unwrap(); //! assert_eq!(worker, Ant::Worker(900000)); //! //! let warrior = Ant::parse("Warrior").unwrap(); //! assert_eq!(warrior, Ant::Warrior); //! } //! ``` //! //! Old syntax: //! //! `r"(variant1|variant2|variant_with_value\({}\)|other_variant_with_value{})"` //! //! is deprecated //! //! ## Modes //! //! Order, in which modes are specified does not matter. //! //! ### no_regex //! //! Makes format string behave as regular string (in contrast with being regular expression), //! by escaping all special regex characters. //! //! ``` //! use reformation::Reformation; //! //! #[derive(Reformation, Debug)] //! #[reformation("Vec{{{x}, {y}}}", no_regex=true)] //! struct Vec{ //! x: i32, //! y: i32, //! } //! //! fn main(){ //! let v= Vec::parse("Vec{-1, 1}").unwrap(); //! assert_eq!(v.x, -1); //! assert_eq!(v.y, 1); //! } //! ``` //! //! ### slack //! //! Allow arbitrary number of spaces after separators: ',', ';', ':'. For separator to be recognized //! as slack, it must be followed by at least one space in format string. //! //! ``` //! use reformation::Reformation; //! //! #[derive(Reformation, Debug)] //! #[reformation(r"Vec\{{{x}, {y}\}}", slack=true)] //! struct Vec{ //! x: i32, //! y: i32, //! } //! //! fn main(){ //! let v = Vec::parse("Vec{-1,1}").unwrap(); //! assert_eq!(v.x, -1); //! assert_eq!(v.y, 1); //! //! let r = Vec::parse("Vec{15, 2}").unwrap(); //! assert_eq!(r.x, 15); //! assert_eq!(r.y, 2); //! } //! ``` //! //! Combination of no_regex and slack behaves as expected: //! //! ``` //! use reformation::Reformation; //! //! #[derive(Reformation, Debug)] //! #[reformation(r"Vec({x}; {y})", slack=true, no_regex=true)] //! struct Vec{ //! x: i32, //! y: i32, //! } //! //! fn main(){ //! let v = Vec::parse("Vec(-1;1)").unwrap(); //! assert_eq!(v.x, -1); //! assert_eq!(v.y, 1); //! //! let r = Vec::parse("Vec(15; 2)").unwrap(); //! assert_eq!(r.x, 15); //! assert_eq!(r.y, 2); //! } //! ``` //! //! ## Extra examples //! //! Format string behaves as regular expression, so special symbols needs to be escaped. //! Also they can be used for more flexible format strings. //! AVOID capture groups, since they would mess up with indexing of capture group //! generated by macro. use non-capturing groups `r"(?:)"` instead. //! //! ``` //! use reformation::Reformation; //! //! // '{' is special symbol in both format and regex syntax, so it must be escaped twice. //! // Say hello to good old escape hell. Good thing its only one. //! #[derive(Reformation, Debug)] //! #[reformation(r"Vec\{{{x},\s*{y},\s*{z}\}}")] //! struct Vec{ //! x: f64, //! y: f64, //! z: f64, //! } //! //! fn main(){ //! // spaces between coordinates does not matter, since any amount of spaces //! // matches to r"\s*" //! let v = Vec::parse("Vec{-0.4,1e-3, 2e-3}").unwrap(); //! //! assert_eq!(v.x, -0.4); //! assert_eq!(v.y, 0.001); //! assert_eq!(v.z, 0.002); //! } //! ``` #[macro_use] extern crate derive_more; pub use lazy_static::lazy_static; pub use reformation_derive::*; pub use regex::{CaptureLocations, Error as RegexError, Regex}; pub trait Reformation<'t>: Sized { /// regular expression for matching this struct fn regex_str() -> &'static str; /// number of used capture groups. // Can be calculated from regex_str, but // setting explicit value by hand avoids // any extra cost and can be inlined in nested structs, but // more error prone. fn captures_count() -> usize; /// create instance of function from captures with given offset fn from_captures<'a>(c: &Captures<'a, 't>, offset: usize) -> Result<Self, Error>; /// parse struct from str /// /// default implementation is not zero-cost abstraction, which must be kept in mind /// when implementing trait by hand. (This version uses generic_static to handle /// lazy initialization, which imply some extra costs, but for non-generic types it can be implemented with /// lazy_static!) fn parse(input: &'t str) -> Result<Self, Error>; } /// Marker trait allowing user to override inner regex of type via attribute /// /// ``` /// use reformation::Reformation; /// /// #[derive(Reformation)] /// #[reformation("{}")] /// struct A<'input>( /// #[reformation("[a-z_]+")] // now A will match every lowercase set of words, separated with underscores /// &'input str /// ); /// /// #[derive(Reformation)] /// #[reformation("{}")] /// struct B<'input>( /// // #[reformation("whatever")] // not allowed, because A does not implement ```ReformationPrimitive``` /// A<'input> /// ); /// /// fn main(){ /// let a = A::parse("one_more__").unwrap(); /// assert_eq!(a.0, "one_more__"); /// } /// ``` pub trait ReformationPrimitive {} pub fn assert_primitive<T: ReformationPrimitive>() {} macro_rules! group_impl_parse_primitive{ ($re: expr, $($name: ty),*) => { $(group_impl_parse_primitive!{@single $re, $name})* }; (@single $re: expr, $name: ty) => { impl<'t> Reformation<'t> for $name{ #[inline] fn regex_str() -> &'static str{ $re } #[inline] fn captures_count() -> usize{ 1 } #[inline] fn from_captures<'a>(c: &Captures<'a, 't>, offset: usize) -> Result<Self, Error>{ let res = c.get(offset) .ok_or_else(|| Error::DoesNotContainGroup(DoesNotContainGroup))? .parse::<$name>() .map_err(|e| Error::Other(e.to_string()))?; Ok(res) } #[inline] fn parse(input: &'t str) -> Result<Self, Error>{ let res = input.parse::<$name>().map_err(|e| Error::Other(e.to_string()))?; Ok(res) } } impl ReformationPrimitive for $name{} }; } #[derive(Copy, Clone)] /// Wrapper to get captures of regular expression pub struct Captures<'a, 't> { captures: &'a CaptureLocations, input: &'t str, } impl<'a, 't> Captures<'a, 't> { #[inline] pub fn new(captures: &'a CaptureLocations, input: &'t str) -> Self { Self { captures, input } } #[inline] /// Get string corresponding to `id` capture group pub fn get(&self, id: usize) -> Option<&'t str> { self.captures.get(id).map(|(a, b)| &self.input[a..b]) } } #[derive(Debug, Display, Eq, PartialEq)] pub enum Error { NoRegexMatch(NoRegexMatch), DoesNotContainGroup(DoesNotContainGroup), #[display(fmt = "{:?}", "_0")] Other(String), } #[derive(Debug, Display, Eq, PartialEq)] pub struct DoesNotContainGroup; #[derive(Debug, Display, Eq, PartialEq)] #[display( fmt = "No regex match: regex {:?} does not match string {:?}", format, request )] pub struct NoRegexMatch { pub format: &'static str, pub request: String, } group_impl_parse_primitive! {r"(\d+)", u8, u16, u32, u64, u128, usize} group_impl_parse_primitive! {r"([\+-]?\d+)", i8, i16, i32, i64, i128, isize} group_impl_parse_primitive! {r"((?:[\+-]?\d+(?:.\d*)?|.\d+)(?:[eE][\+-]?\d+)?)", f32, f64} group_impl_parse_primitive! {r"(.*)", String} group_impl_parse_primitive! {r"(.)", char} impl<'t, T: Reformation<'t>> Reformation<'t> for Option<T> { #[inline] fn regex_str() -> &'static str { T::regex_str() } #[inline] fn captures_count() -> usize { T::captures_count() } #[inline] fn from_captures<'a>(captures: &Captures<'a, 't>, offset: usize) -> Result<Self, Error> { if captures.get(offset).is_some() { T::from_captures(captures, offset).map(|x| Some(x)) } else { Ok(None) } } #[inline] fn parse(input: &'t str) -> Result<Self, Error> { match T::parse(input) { Ok(x) => Ok(Some(x)), Err(Error::DoesNotContainGroup(_)) => Ok(None), Err(e) => Err(e), } } } impl<T> ReformationPrimitive for Option<T> {} impl<'t> Reformation<'t> for &'t str { #[inline] fn regex_str() -> &'static str { "(.*?)" } #[inline] fn captures_count() -> usize { 1 } #[inline] fn from_captures<'a>(captures: &Captures<'a, 't>, offset: usize) -> Result<Self, Error> { let res = captures .get(offset) .ok_or_else(|| Error::DoesNotContainGroup(DoesNotContainGroup))?; Ok(res) } #[inline] fn parse(input: &'t str) -> Result<Self, Error> { Ok(input) } } impl<'a> ReformationPrimitive for &'a str {} #[cfg(test)] mod tests { use super::*; #[test] fn test_float_parse() { // test regular expression for floating point numbers let re = regex::Regex::new(&format!("^{}$", f32::regex_str())).unwrap(); // positive assert!(check_float_capture(&re, "10")); assert!(check_float_capture(&re, "10.2")); assert!(check_float_capture(&re, "10.")); assert!(check_float_capture(&re, "0.34")); assert!(check_float_capture(&re, "00.34")); assert!(check_float_capture(&re, ".34")); assert!(check_float_capture(&re, ".34e2")); assert!(check_float_capture(&re, ".34e+2")); assert!(check_float_capture(&re, ".34e-2")); assert!(check_float_capture(&re, "-0.34e-2")); assert!(check_float_capture(&re, "5e-2")); assert!(check_float_capture(&re, "5.e-2")); // should this pass? // negative assert!(!re.is_match("5..")); assert!(!re.is_match(".")); assert!(!re.is_match("--4.")); assert!(!re.is_match("-.0")); } fn check_float_capture(r: ®ex::Regex, s: &str) -> bool { r.captures(s) .map(|c| c.len() == 2 && c.get(1).map(|x| x.as_str()) == Some(s)) .unwrap_or(false) } }