scala解析器。日志解析器实用程序的输出

时间:2013-06-19 05:26:54

标签: parsing scala

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

Scala代码:

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)”?

1 个答案:

答案 0 :(得分:0)

覆盖log解决了我的问题。

Scala Snippet:

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())