Function lip::variable

source ·
pub fn variable<'a, S: Clone + 'a, F1, F2, F3>(
    start: &'a F1,
    inner: &'a F2,
    separator: &'a F3,
    reserved: &'a HashSet<String>,
    expecting: &'a str
) -> impl Parser<'a, Output = String, State = S>where
    F1: Fn(char) -> bool + Clone,
    F2: Fn(char) -> bool + Clone,
    F3: Fn(char) -> bool + Clone,
Expand description

Parse a variable.

If we want to parse a PascalCase variable excluding three reserved words, we can try something like:

let reserved = &([ "Func", "Import", "Export" ].iter().cloned().map(| element | element.to_string()).collect());
assert_succeed(
  variable(&(|c| c.is_uppercase()), &(|c| c.is_lowercase()), &(|_| false), reserved, "a PascalCase variable"),
  "Dict", "Dict".to_string()
);

If we want to parse a snake_case variable, we can try something like:

assert_succeed(
 variable(&(|c| c.is_lowercase()), &(|c| c.is_lowercase() || c.is_digit(10)), &(|c| c == '_'), &HashSet::new(), "a snake_case variable"),
 "my_variable_1", "my_variable_1".to_string()
);

The below uses the same snake_case variable parser. However, the separator _ appeared at the end of the name invalid_variable_name_:

assert_fail(
 variable(&(|c| c.is_lowercase()), &(|c| c.is_lowercase() || c.is_digit(10)), &(|c| c == '_'), &HashSet::new(), "a snake_case variable"),
 "invalid_variable_name_", "I'm expecting a snake_case variable but found `invalid_variable_name_` ended with the separator `_`."
);