0

我正在使用log解析器实用程序来跟踪解析。

斯卡拉代码:

import scala.util.parsing.combinator.JavaTokenParsers
object Arith extends JavaTokenParsers with App {
    def expr: Parser[Any] = log(term~rep("+"~term | "-"~term))("expr")
    def term: Parser[Any] = factor~rep("*"~factor | "/"~factor)
    def factor: Parser[Any] = floatingPointNumber | "("~expr~")"
    println(parseAll(expr, "2 * (3 + 7)"))
}

输出:

trying expr at scala.util.parsing.input.CharSequenceReader@13a317a
trying expr at scala.util.parsing.input.CharSequenceReader@14c1103
expr --> [1.11] parsed: ((3~List())~List((+~(7~List()))))
expr --> [1.12] parsed: ((2~List((*~(((~((3~List())~List((+~(7~List())))))~)))))~List())
[1.12] parsed: ((2~List((*~(((~((3~List())~List((+~(7~List())))))~)))))~List())

输入打印为scala.util.parsing.input.CharSequenceReader@13a317a。有没有办法打印输入的字符串表示形式,如“2 * (3 + 7)”?

4

1 回答 1

0

覆盖log解决了我的问题。

斯卡拉片段:

import scala.util.parsing.combinator.JavaTokenParsers
object Arith extends JavaTokenParsers with App {
    override def log[T](p: => Parser[T])(name: String): Parser[T] = Parser { in =>
        def prt(x: Input) = x.source.toString.drop(x.offset)

        println("trying " + name + " at " + prt(in))
        val r = p(in)
        println(name + " --> " + r + " next: " + prt(r.next))
        r
    }
    def expr: Parser[Any] = log(term ~ rep("+" ~ term | "-" ~ term))("expr")
    def term: Parser[Any] = factor ~ rep("*" ~ factor | "/" ~ factor)
    def factor: Parser[Any] = floatingPointNumber | "(" ~ expr ~ ")"
    println(parseAll(expr, "(3+7)*2"))
}

输出:

trying expr at (3+7)*2
trying expr at 3+7)*2
expr --> [1.5] parsed: ((3~List())~List((+~(7~List())))) next: )*2
expr --> [1.8] parsed: (((((~((3~List())~List((+~(7~List())))))~))~List((*~2)))~List()) next: 
[1.8] parsed: (((((~((3~List())~List((+~(7~List())))))~))~List((*~2)))~List())
于 2013-06-19T06:08:10.253 回答