Search code examples
scalaparser-combinators

Parser combinator for enumerated values


Is there a cleaner way to map a string to an Enumeration value in a parser combinator?

object Mode extends Enumeration {
  type Mode = Value
  val View, Add, Modify, Delete  = Value
}

import Mode._

object ModeParser extends JavaTokenParsers {
  def mode: Parser[Mode] = ("^(" + Mode.values.mkString("|") + ")$").r ^^ { 
    Mode.withName(_) 
  }
}

Solution

  • Parsers are composable, so as soon as you can build a parser reading one Mode.Value, you may compose all such variants with | :

    object ModeParser extends JavaTokenParsers {
      val mode: Parser[Mode.Value] = Mode.values.toList map{m =>
        literal(m.toString) ^^^ m
      } reduceLeft {_ | _}
    }
    

    You would use it like so:

    scala> ModeParser.parseAll(ModeParser.mode, "Viewx")