0

我想這語義定向解析器組合

import scala.util.parsing.combinator._ 
def name = ident ^^ {case ident => if (ident.contains("a")) ident.toUpperCase else ident 

println(parseAll(name, "aa")) // parsed: AA 
println(parseAll(name, "bb")) 

與輸出

[1.3] parsed: AA 
[1.3] parsed: bb 
[1.1] failure: `(' expected but `a' found 

aa 
^ 
[1.3] failure: end of input expected 

f1(aa) 
^

正如你看到的,第二解析失敗。似乎第一次生產的失敗停止了嘗試第二種選擇。我實際上需要依賴於第一個標識符的值來選擇這個或那個解析器來繼續。

回答

0

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