I am trying to use scala.util.parsing.combinator
to parse some MIPS code and my code works for each item (i.e. label, instruction, directive and etc) but it does not work for multiple items/lines. I think the separator regex which I pass to repsep
function does not work.
For example, I can parse label str:
but I cannot parse str: .asciiz "Hello world!"
def directive: Parser[Token] = Text.parse ||| Word.parse ||| Data.parse ||| Ascii.parse ||| Asciiz.parse
def instruction: Parser[Token] = LoadAddress.parse ||| LoadImmediate.parse ||| Move.parse ||| Label.parse
def misc: Parser[Token] = Label.parse ||| Comment.parse ||| Syscall.parse
def item: Parser[Token] = directive ||| instruction ||| misc
// this line I think is the problem ...
def program: Parser[Seq[Token]] = repsep(item, """[\s\t\n]+""".r) ^^ { _.toList }
def parseCode(code: Reader[Char]): Seq[Token] = {
parse(program, code) match {
case Success(matched, _) => matched
case Failure(msg, _) => throw new Exception(s"FAILURE: $msg")
case Error(msg, _) => throw new Exception(s"ERROR: $msg")
}
}
It seems that you're using scala.util.parsing.combinator.RegexParsers
and it skips whitespaces by default. You should override it
override def skipWhitespace = false