如何使 scala 解析器失败

发布于 2024-10-16 06:16:09 字数 582 浏览 2 评论 0原文

所以我有这样的事情:

class MyParser extends JavaTokenParsers {
    var m = new HashMap[String,String]
    def store = ("var" ~> ident "=") ~ ident ^^ {
        case k ~ v => m += k -> v
    }
    def stored_val = ident ^^ {
        case k => m(k)
    }
}

我的问题是我真正想做的是让解析器stored_val失败,以便其他解析器有机会匹配输入。但现在发生的情况是,当地图找不到该值时,它会抛出异常。

我尝试像这样实现stored_val:

def stored_val = ident => {
    case k => if (m.contains(k)) m(k) else failure("identifier not found")
}

但问题是失败返回Parser[Nothing],它是与String不同的类型。

so I have something like this:

class MyParser extends JavaTokenParsers {
    var m = new HashMap[String,String]
    def store = ("var" ~> ident "=") ~ ident ^^ {
        case k ~ v => m += k -> v
    }
    def stored_val = ident ^^ {
        case k => m(k)
    }
}

And my problem is that what I really want to do is have the parser stored_val fail so that other parsers have the chance to match the input. But what happens now is that the map throws when it can't find the value.

I tried implementing stored_val like this:

def stored_val = ident => {
    case k => if (m.contains(k)) m(k) else failure("identifier not found")
}

But the problem with that is failure returns Parser[Nothing] which is a different type than String.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

享受孤独 2024-10-23 06:16:09

您可以使用接受部分函数的 ^? 组合器 (Scaladoc):

def stored_val: Parser[String] = ident ^? {
    case k if m.contains(k) => m(k)
}

我推送了 完整示例 测试到Github。

You can use the ^? combinator which accepts a partial function (Scaladoc):

def stored_val: Parser[String] = ident ^? {
    case k if m.contains(k) => m(k)
}

I pushed a full example with tests to Github.

妖妓 2024-10-23 06:16:09

如果您想检查正则表达式之外的字符内容,您可能需要查看 StandardTokenParser。尤其,

def elem (kind: String, p: (Elem) ⇒ Boolean) : Parser[Elem]

匹配满足给定谓词的输入元素的解析器
如果输入以 e' 开头且 p(e) 为 true,则 elem(kind, p) 成功。

编辑
有关标准令牌解析器的示例,请查看 Jim McBeath 关于 Scala 解析器的文章组合器。我对第一个示例进行了快速修改以演示elem。这是一个简单的解析器,只需要奇数的和:

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

trait Expression
case class EConstant(value: Int) extends Expression
case class EAdd(lhs: Expression, rhs: Expression) extends Expression

object ExpressionParser extends StandardTokenParsers {
  lexical.delimiters ++= List("+")

  def oddValue = elem("odd", { x => x.toString.toInt % 2 == 1 }) ^^ {
    x => EConstant(x.toString.toInt) }
  def value = numericLit ^^ { x => EConstant(x.toInt) }

  def sum = oddValue ~ "+" ~ oddValue ^^ { case left ~ "+" ~ right =>
          EAdd(left, right) }

  def expr = ( sum | value )

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

  def apply(s:String): Expression = parse(s) match {
    case Success(tree, _) => tree
    case e: NoSuccess =>
      throw new IllegalArgumentException("Bad syntax: "+s)
  }
}

将上面的内容保存为 ExpressionParser.scala 并将其加载到 REPL 中,如下所示:

scala> :l ExpressionParser.scala     
Loading ExpressionParser.scala...
import scala.util.parsing.combinator.syntactical._
import scala.util.parsing.combinator._
defined trait Expression
defined class EConstant
defined class EAdd
defined module ExpressionParser

scala> ExpressionParser("2 + 2")
java.lang.IllegalArgumentException: Bad syntax: 2 + 2
    at ExpressionParser$.apply(<console>:42)
    at .<init>(<console>:24)
    at .<clinit>(<console>)
    at RequestResult$.<init>(<console>:9)
    at RequestResult$.<clinit>(<console>)
    at RequestResult$scala_repl_result(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at scala.tools.nsc.Interpreter$Request$anonfun$loadAndRun$1$anonfun$apply$17.apply(Interpreter.scala:988)
    at scala.tools.nsc.Interpreter$Request$anonfun$loadAndRun$1$anonfun$apply$17.apply(Interpreter.scala:988)
    at scala.util.con...
scala> ExpressionParser("1 + 1")
res3: Expression = EAdd(EConstant(1),EConstant(1))

If you want to check the content of the characters beyond regex, you might want to check out StandardTokenParser. In particular,

def elem (kind: String, p: (Elem) ⇒ Boolean) : Parser[Elem]

A parser matching input elements that satisfy a given predicate
elem(kind, p) succeeds if the input starts with an element e' for which p(e) is true.

Edit:
For examples of Standard Token Parser, check out Jim McBeath's article on Scala Parser Combinators. I made a quick modification to the first example to demonstrate elem. It's a simple parser that only takes sum of odd numbers:

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

trait Expression
case class EConstant(value: Int) extends Expression
case class EAdd(lhs: Expression, rhs: Expression) extends Expression

object ExpressionParser extends StandardTokenParsers {
  lexical.delimiters ++= List("+")

  def oddValue = elem("odd", { x => x.toString.toInt % 2 == 1 }) ^^ {
    x => EConstant(x.toString.toInt) }
  def value = numericLit ^^ { x => EConstant(x.toInt) }

  def sum = oddValue ~ "+" ~ oddValue ^^ { case left ~ "+" ~ right =>
          EAdd(left, right) }

  def expr = ( sum | value )

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

  def apply(s:String): Expression = parse(s) match {
    case Success(tree, _) => tree
    case e: NoSuccess =>
      throw new IllegalArgumentException("Bad syntax: "+s)
  }
}

Save the above as ExpressionParser.scala and load it into REPL as follows:

scala> :l ExpressionParser.scala     
Loading ExpressionParser.scala...
import scala.util.parsing.combinator.syntactical._
import scala.util.parsing.combinator._
defined trait Expression
defined class EConstant
defined class EAdd
defined module ExpressionParser

scala> ExpressionParser("2 + 2")
java.lang.IllegalArgumentException: Bad syntax: 2 + 2
    at ExpressionParser$.apply(<console>:42)
    at .<init>(<console>:24)
    at .<clinit>(<console>)
    at RequestResult$.<init>(<console>:9)
    at RequestResult$.<clinit>(<console>)
    at RequestResult$scala_repl_result(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at scala.tools.nsc.Interpreter$Request$anonfun$loadAndRun$1$anonfun$apply$17.apply(Interpreter.scala:988)
    at scala.tools.nsc.Interpreter$Request$anonfun$loadAndRun$1$anonfun$apply$17.apply(Interpreter.scala:988)
    at scala.util.con...
scala> ExpressionParser("1 + 1")
res3: Expression = EAdd(EConstant(1),EConstant(1))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文