Scala: How to combine parser combinators from different objects

Posted by eed3si9n on Stack Overflow See other posts from Stack Overflow or by eed3si9n
Published on 2010-04-16T02:42:43Z Indexed on 2010/04/16 2:53 UTC
Read the original article Hit count: 457

Filed under:
|
|

Given a family of objects that implement parser combinators, how do I combine the parsers? Since Parsers.Parser is an inner class, and in Scala inner classes are bound to the outer object, the story becomes slightly complicated.

Here's an example that attempts to combine two parsers from different objects.

import scala.util.parsing.combinator._

class BinaryParser extends JavaTokenParsers {
  def anyrep: Parser[Any] = rep(any)
  def any: Parser[Any] = zero | one
  def zero: Parser[Any] = "0"
  def one: Parser[Any] = "1"
}

object LongChainParser extends BinaryParser {
  def parser1: Parser[Any] = zero~zero~one~one
}

object ShortChainParser extends BinaryParser {
  def parser2: Parser[Any] = zero~zero
}

object ExampleParser extends BinaryParser {
  def parser: Parser[Any] = (LongChainParser.parser1
    ||| ShortChainParser.parser2) ~ anyrep

  def main(args: Array[String]) {
    println(parseAll(parser, args(0) ))
  }
}

This results to the following error:

<console>:11: error: type mismatch;
 found   : ShortChainParser.Parser[Any]
 required: LongChainParser.Parser[?]
         def parser: Parser[Any] = (LongChainParser.parser1 
           ||| ShortChainParser.parser2) ~ anyrep

I've found the solution to this problem already, but since it was brought up recently on scala-user ML (Problem injecting one parser into another), it's probably worth putting it here too.

© Stack Overflow or respective owner

Related posts about scala

Related posts about parser-combinators