Scala Parser combinator - How to call from main class

Good morning ,

Could you kindly me on how one would be possible to execute the parser using scala parser combinators.

 parser.parseAll(parser.Formula, inputSource) match {
          case parser.Success(r, n) => print("Parsing Ready")
          case _ =>  print("Parsing Error")

How is it possible that the parser still results into various exceptions, for example,

Exception in thread “main” java.lang.StackOverflowError

Thanks a lot and good day :slight_smile:

You probably have a problem with recursion in your grammar / parser. Look at the stacktrace, this might give you a hint where to look.

As usual, show your code. Preferably, make a minimal reproducible example. Otherwise we’re just guessing.

1 Like

Thanks for your reply.

Could you kindly explain to me what would be best if for example the root symbol is Formula, and a Formula can either be A | B. Is that possible first of all please ?

def Program : Parser[Program] = positioned(Formula) ^^ {result => result}

def Formula : Parser[Formula] = positioned( "A" ~ aStatement  ^^ {case "A" ~ result => new Formula(result.asInstanceOf[Either[A,B]])} |
                                  "B" ~ bStatement ^^ {case "B" ~ result => new Formula(result.asInstanceOf[Either[A,B]])})

And what should I write in the parseAll function please ?

Up till now I wrote :

def parseAll[T](p: Parser[T], in: String): ParseResult[T] = {
phrase( p )(new lexical.Scanner(in))

Thanks a lot and good day :slight_smile:

That does not really help us help you. What is aStatement or bStatement? There probably is some recursion somewhere, no?

And what is the input? Or even the problem (grammar)?

Also, using asInstanceOf smells a lot like a programming error. Types are useful, don’t try to work around them.

Sorry :slight_smile:

So an aStatement and bStatement are 2 non terminal symbols, i.e. can be further reduced.

The idea is that a Program can be formed of “aTyped” formulae or “bTyped” formulae.

I am not using recursion i.e. rep functions or repsep etc.

Thanks for the heads up of the asInstanceOf function :slight_smile:

Thanks a lot and good day :slight_smile:

You can have recursion in a parser without those functions, when non terminal symbols refer to themselves or to other non terminals that refer back to them. To help you find the cause of the stack overflow, we’d really need your whole grammar.

1 Like