可以做 return Failure
,这会将球传给后续的替代品(不要与 混淆Failure
。failure
第二个将停止解析)
def name = new Parser[String] {
def apply(s: Input) = ident(s) match {
case Success(ident, rem) => if (ident.contains("a")) Success(ident.toUpperCase, rem) else Failure("identifier with 'a' expected", s)
case a => a
}
} | ident
这使得产品的真正语义调度成为可能
def pkg(prefix: String): Parser[_] = "." ~> name ^^ {case arg => s"P:$prefix.$arg"}
def function(fID: String): Parser[_] = "(" ~> name <~ ")" ^^ {case arg => s"F:$fID($arg)"}
val env = Map("p1" -> pkg _, "p2" -> pkg _, "f1" -> function _)
def name = new Parser[Any] {
def apply(s: Input) = ident(s) match {
case Success(ident, rem) => env.get(ident) match {
case Some(parser) => parser(ident)(rem)
case _ => Failure(s"object $ident not found", s)
} ; case a => a // how can we monade this identity?
}
} | ident
// test inputs
List("aaa","f1(bb)","p1.p2.c","f1(f1(c))","f1(f1(p1.f1(bbb)))","aaa(bb(.cc(bbb)))") foreach {
input => println(s"$input => " + parseAll(name, input))
}
这里名称被解析。解析器首先尝试一个标识符。它在语义上检查标识符在上下文中是否称为函数或包。如果没有,它会退回到简单的标识符解析器。这很愚蠢,但这就是我所要求的。演示解析是
aaa => [1.4] parsed: aaa
f1(bb) => [1.7] parsed: F:f1(bb)
p1.p2.c => [1.8] parsed: P:p1.P:p2.c
f1(f1(c)) => [1.10] parsed: F:f1(F:f1(c))
f1(f1(p1.f1(bbb))) => [1.19] parsed: F:f1(F:f1(P:p1.F:f1(bbb)))
aa(b) => [1.3] failure: end of input expected
aa(b)
^
f1(cc.dd) => [1.6] failure: `)' expected but `.' found
f1(cc.dd)
^
错误是预期的:f1
是唯一定义的函数,aa
不是其中之一。因此,它作为标识符被消费,不被消费(b)
。同样,cc
作为简单标识符使用,因为它不是定义的包。