2020-10-22 20:47:20 +00:00
|
|
|
use combine::parser::char::{char, digit, letter, spaces};
|
|
|
|
use combine::{many1, optional, Parser};
|
2020-10-15 16:52:08 +00:00
|
|
|
use thiserror::Error;
|
|
|
|
|
|
|
|
enum ParsedValue {
|
|
|
|
Valid(i32),
|
|
|
|
Invalid,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Error, Debug)]
|
|
|
|
pub enum VariableParsingError {
|
|
|
|
#[error("invalid variable value, must be a number")]
|
|
|
|
InvalidValue,
|
|
|
|
|
|
|
|
#[error("unconsumed input")]
|
|
|
|
UnconsumedInput,
|
2020-10-31 13:52:46 +00:00
|
|
|
|
|
|
|
#[error("parser error: {0}")]
|
|
|
|
InternalParseError(#[from] combine::error::StringStreamError),
|
2020-10-15 16:52:08 +00:00
|
|
|
}
|
|
|
|
|
2020-10-31 13:52:46 +00:00
|
|
|
pub fn parse_set_variable(input: &str) -> Result<(String, i32), VariableParsingError> {
|
2020-10-15 16:52:08 +00:00
|
|
|
let name = many1(letter()).map(|value: String| value);
|
|
|
|
|
2020-10-22 20:47:20 +00:00
|
|
|
let maybe_minus = optional(char('-')).map(|value: Option<char>| match value {
|
|
|
|
Some(minus_sign) => String::from(minus_sign),
|
|
|
|
_ => "".to_owned(),
|
2020-10-15 16:52:08 +00:00
|
|
|
});
|
|
|
|
|
2020-10-22 20:47:20 +00:00
|
|
|
let value = maybe_minus
|
|
|
|
.and(many1(digit()))
|
|
|
|
.map(|value: (String, String)| {
|
|
|
|
let number = format!("{}{}", value.0, value.1);
|
|
|
|
match number.parse::<i32>() {
|
|
|
|
Ok(num) => ParsedValue::Valid(num),
|
|
|
|
_ => ParsedValue::Invalid,
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2020-10-15 16:52:08 +00:00
|
|
|
let mut parser = name.skip(spaces().silent()).and(value);
|
|
|
|
let (result, rest) = parser.parse(input)?;
|
|
|
|
|
|
|
|
if rest.len() == 0 {
|
|
|
|
match result {
|
|
|
|
(variable_name, ParsedValue::Valid(value)) => Ok((variable_name, value)),
|
2020-10-31 13:52:46 +00:00
|
|
|
_ => Err(VariableParsingError::InvalidValue),
|
2020-10-15 16:52:08 +00:00
|
|
|
}
|
|
|
|
} else {
|
2020-10-31 13:52:46 +00:00
|
|
|
Err(VariableParsingError::UnconsumedInput)
|
2020-10-15 16:52:08 +00:00
|
|
|
}
|
|
|
|
}
|
2020-10-22 20:47:20 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn parse_postive_number() {
|
|
|
|
let result = parse_set_variable("myvar 5");
|
|
|
|
assert!(result.is_ok());
|
|
|
|
assert_eq!(("myvar".to_string(), 5), result.unwrap());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn parse_negative_number() {
|
|
|
|
let result = parse_set_variable("myvar -5");
|
|
|
|
assert!(result.is_ok());
|
|
|
|
assert_eq!(("myvar".to_string(), -5), result.unwrap());
|
|
|
|
}
|
|
|
|
}
|