Parser combinator: how to abort repetition by keyword

I am trying to figure out how to interrupt the repetition of words using a keyword. Example:

class CAQueryLanguage extends JavaTokenParsers {
    def expression = ("START" ~ words ~ "END") ^^ { x =>
        println("expression: " + x);
        x
    }
    def words = rep(word) ^^ { x =>
        println("words: " + x)
        x
    }
    def word = """\w+""".r
}

When i do

val caql = new CAQueryLanguage
caql.parseAll(caql.expression, "START one two END")

It prints words: List(one, two, END), indicating that the parser is wordsconsuming a keyword ENDin my input, preventing the expression parser from being unable to match. I would like it ENDnot to be consistent words, which will make it possible to expressionsuccessfully parse it.

+3
source share
1 answer

Is this what you are looking for?

import scala.util.parsing.combinator.syntactical._

object CAQuery extends StandardTokenParsers {
    lexical.reserved += ("START", "END")
    lexical.delimiters += (" ")

    def query:Parser[Any]= "START" ~> rep1(ident) <~ "END"

    def parse(s:String) = {
       val tokens = new lexical.Scanner(s)
       phrase(query)(tokens)
   }   
}

println(CAQuery.parse("""START a END"""))       //List(a)
println(CAQuery.parse("""START a b c END"""))   //List(a, b, c)

If you want more information, you can check out this blog post.

+4
source

Source: https://habr.com/ru/post/1719458/


All Articles