我是第一次写一个词法分析器/扫描仪,并且在分割输入字符串时遇到了问题。 例如:
val result = "func add(Num x, Num y) = x+y;".split(???)
result == Array("func", "add", "(", "Num", "x", ",", "Num", "y", ")", "=", "x", "+", "y", ";")
但问题是我不能简单地拆分空白字符,这样做不会将add
与(
分开。
对此有何帮助?
答案 0 :(得分:1)
答案 1 :(得分:0)
查看http://www.scala-lang.org/api/rc/index.html#scala.util.parsing.combinator.RegexParsers
这是一个未完成的例子:
import scala.util.parsing.combinator.RegexParsers
trait Element
case class Function(name: String,
params:Map[String, String],
expression:Seq[String]) extends Element
case class Class(name: String,
params: Map[String,String],
body: Seq[String]) extends Element
object LanguageParser extends RegexParsers {
val name: Parser[String] = ".*".r
val `type`: Parser[String] = ???
val parameters: Parser[Map[String,String]] = "(" ~> (`type` ~ name).* <~")" ^^ {
case t => (t map {
case a ~ b => a -> b
}).toMap
}
val expression: Parser[Seq[String]] = ???
val function: Parser[Function] =
"func " ~> name ~ parameters ~ "="~ expression ^^ {
case name ~ params ~ _ ~ expr => Function(name, params, expr)
}
val `class`: Parser[Class] =
"class " ~> name ~ parameters ~ "{" ~ expression ~ "}" ^^ {
case name ~ params ~ _ ~ expr ~_ => Class(name, params, expr)
}
val topLevelParsers: Parser[Seq[Element]] =
function |
`class` |
value |
ifelse
def parse(s: String): Seq[Element] = parseAll(topLevelParsers, s.trim) getOrElse
(throw newIllegalArgumentException("Could not parse the given string: " + s.trim))
def parseAll(s: String):Seq[Element] =
s split ";" flatMap parse
}
干杯