Add more parser combinators

154 views Asked by At

Is it possible to extend the Scala Parser Combinator library with more Parser Combinators, maybe with the help of a wrapper? I am trying to add a new Parser Combinator with a custom behavior. My current solution is to adopt the files (Parsers.scala, RegexParsers.scala, and SubSequence.scala) and to add my custom Parser Combinators directly.

EDIT

With the help of an old Gitter message, I got following solution:

import scala.util.parsing.combinator._

trait JustTesting extends RegexParsers {

  def test = "a" abc "b"

  abstract class TestParser[T] extends Parser[T] {

    def abc[U](q: ⇒ Parser[U]): Parser[U] = { // same behaviour as ~
      lazy val p = q // lazy argument
      (for (a ← this; b ← p) yield b).named("abc")
    }

  }

  override implicit def literal(s: String): TestParser[String] =
    super.literal(s).asInstanceOf[TestParser[String]] // Runtime error, because a convert is not possible

}

Is that the way to go? Is it possible to change the implementation so that I do not need to override the literal function? A problem is also that I cannot use "a" abc "b" abc "c".

1

There are 1 answers

0
nairbv On

There are a number of subclasses of Parser in the scala-parser-combinator library. You can basically just follow the examples.

e.g. these all extend Parser: https://github.com/scala/scala-parser-combinators/tree/1.0.x/shared/src/main/scala/scala/util/parsing/combinator/syntactical

And JavaTokenParsers extends RegexParsers: https://github.com/scala/scala-parser-combinators/blob/1.0.x/shared/src/main/scala/scala/util/parsing/combinator/JavaTokenParsers.scala

Here's another random example from the web, with a concrete object extending the trait: https://github.com/droby/expression-parser/blob/master/src/main/scala/com/donroby/parsing/ExpressionParsers.scala

There are many blogs you can find showing how to use the library.

In general, extending a class just requires writing class MyClass extends ClassToExtend{} and then implementing any abstract methods until the compiler stops complaining.