【问题标题】:Parboiled2 Parser ExampleParboiled2 解析器示例
【发布时间】:2015-03-24 01:59:31
【问题描述】:

我正在尝试从parboiled2 尝试这个示例:

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

然后,我创建一个新的MyParser,输入为"foo"

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

然而返回值是null

如何从 REPL 运行这个简单的 fRule

【问题讨论】:

    标签: scala parsing parboiled2


    【解决方案1】:

    Parboiled 2 的rule 是一个宏,使用rule 定义的方法不打算在其他规则的上下文或对run() 的调用之外引用。因此,如果您有以下情况:

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

    你可以这样使用它(为了清楚起见,清理了类型):

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

    如果您不想要Try,您可以使用另一个delivery schemes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 2012-01-29
      • 2011-06-21
      相关资源
      最近更新 更多