Using `ANY` is not working when picking up patterns using the Rust PEST parser

325 Views Asked by At

I am using the PEST parser and I am testing a simple example to get familiar with the syntax. I am trying to get every instance of ++ throughout the string but I am running into some issues. I think it may be an issue with the ANY keyword but I am not sure. Can anyone help point me in the right direction as to what is going wrong?

Here is my grammar.pest file

incrementing = {(prefix ~ ANY+ ~ "++" ~ suffix)}

prefix = {(NEWLINE | WHITESPACE)*}
suffix = {(NEWLINE | WHITESPACE)*}
WHITESPACE = _{ " " }

Here is my test case


//parses a file a matching rule and returns all instances of the rule
fn parse_file_contents_for_rule(rule: Rule, file_contents: &str) -> Option<Pairs<Rule>> {
    SolgaParser::parse(rule, file_contents).ok()
}

fn parse_incrementing(file_contents: &str) {
    //parse the file for the rule
    let targets = parse_file_contents_for_rule(Rule::incrementing, file_contents);

    //if there are matches
    if targets.is_some() {
        //iterate through all of the matches
        for target in targets.unwrap().into_iter() {
            println!("{}", target.as_str());
        }
    }
}


#[test]
fn test_parse_incrementing() {
    let file_contents = r#"
    index++;
    
    a_thing++;

    another_thing++;    
    
    should_not_match;

    should_match++;
    
    "#;

    parse_incrementing(file_contents);
}
1

There are 1 best solutions below

0
On

In your example, ANY+ is probably matching till the end of the line, so the ++ pattern is never matched, and therefore the whole incrementing rule is never matched.

Try changing it to (!"+" ~ ANY)+