我發現日誌功能是非常尷尬的類型。喜歡爲什麼我必須做log(parser)("string")
?爲什麼不能像parser.log("string")
那樣簡單?不管怎麼說,要克服的是,我做了這個:
trait Logging { self: Parsers =>
// Used to turn logging on or off
val debug: Boolean
// Much easier than having to wrap a parser with a log function and type a message
// i.e. log(someParser)("Message") vs someParser.log("Message")
implicit class Logged[+A](parser: Parser[A]) {
def log(msg: String): Parser[A] =
if (debug) self.log(parser)(msg) else parser
}
}
在解析器
現在,你可以混合在這個特質,像這樣:
import scala.util.parsing.combinator.Parsers
import scala.util.parsing.input.CharSequenceReader
object CombinatorParserTest extends App with Parsers with Logging {
type Elem = Char
override val debug: Boolean = true
def notComma: Parser[Char] = elem("not comma", _ != ',')
def notEndLine: Parser[Char] = elem("not end line", x => x != '\r' && x != '\n')
def text: Parser[List[Char]] = rep(notComma.log("notComma") | notEndLine.log("notEndLine"))
val r = text(new CharSequenceReader(","))
println(r)
}
您也可以覆蓋debug
場關閉日誌如果需要的話。
運行,這也顯示了第二語法分析器分析正確的逗號:
trying notComma at [email protected]
notComma --> [1.1] failure: not comma expected
,
^
trying notEndLine at [email protected]
notEndLine --> [1.2] parsed: ,
trying notComma at [email protected]
notComma --> [1.2] failure: end of input
,
^
trying notEndLine at [email protected]
notEndLine --> [1.2] failure: end of input
,
^
The result is List(,)
Process finished with exit code 0
我認爲EOF是人爲引進,但你說得對,這是在似乎重複設置請求時反覆解析當輸入已經在序列的末尾時還有一個額外的字符。 – huynhjl 2010-03-06 18:08:55