Parboiled2 Parser Example

1.1k views Asked by At

I'm trying to try out this example from parboiled2:

scala> class MyParser(val input: org.parboiled2.ParserInput) 
            extends org.parboiled2.Parser { 
                def f = rule { capture("foo" ~ push(42)) 
                } 
        }
defined class MyParser

Then, I create a new MyParser with input of "foo".

scala> new MyParser("foo").f
res11: org.parboiled2.Rule[shapeless.HNil,shapeless.::
            [Int,shapeless.::[String,shapeless.HNil]]] = null

Yet the return value is null.

How can I run this simple f Rule from the REPL?

1

There are 1 answers

0
Travis Brown On BEST ANSWER

Parboiled 2's rule is a macro, and methods that are defined using rule aren't intended to be referred to outside of the context of other rules or a call to run(). So if you have the following:

import org.parboiled2._

class MyParser(val input: ParserInput) extends Parser {
  def f = rule { capture("foo" ~ push(42)) } 
}

You can use it like this (with the type cleaned up for clarity):

scala>  new MyParser("foo").f.run()
res0: scala.util.Try[Int :: String :: HNil] = Success(42 :: foo :: HNil)

If you don't want a Try you can use one of the other delivery schemes.