這是可以做到返回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
作爲簡單標識符消耗,因爲它不是定義的包。