1

My problem is that I would like to implement a grammar that (on paper) looks like this:

functionCall = expression "(" [{expression ";"} expression ] ")"

Here are some examples:

  • foo(var)
  • foo(var1; var2)
  • foo()
  • foo(var1; var2; var3)

With this specified grammar this should also work:

foo(var1)()

  • foo(var1) => expression
  • "("
  • ")"
  • With this grammar a left recursion occurs and I do not know how to handle it.

    I am using the Scala parser library to realize this grammar.

    I have looked into some post especially this one Recursive definitions with scala-parser-combinators to figure out a solution.

    I have found many solutions for problems that look similar to this:

    expression ~ "." ~ expression

    I tried to replicate the Solution for my problem, but I was not able to achieve success.

    My simplified code looks like this:

    sealed trait Baz
    case class Start(code: Baz) extends Baz
    case class FunctionCall(call: Baz, arg: List[Baz]) extends Baz
    case class foo(text: String) extends Baz
    case class bar(nr: Int) extends Baz
    
    class ExpParser extends JavaTokenParsers {
    
      def start: Parser[Start] = expression ^^ {s => Start(s)}
    
      def expression: Parser[Baz] = foo | bar | functionCall 
    
      private val foo: Parser[Foo] = "[a-z]*".r ^^ {f => Foo(f)}
      private val bar: Parser[Bar] = "[0-9]*".r ^^ {b => Bar(b)}
    
      private val functionCall: Parser[Baz] = expression ~ "(" ~  repsep(expression, ";") <~ ")" ^^ {case l~_~r => FunctionCall(l,r)}
    }
    
    object ParseProgram extends ExpParser {
      def parse(s: String): ParseResult[Start] = {
        parseAll(code, s)
      }
    }
    
    

    I have tried to use chainl1 but reading the Implementation it seems at least to me that this won't work for my problem.

    I would like to know if there is any way to change my code so that I can avoid this left recursion and keep the data structure of functionCall with the List.

    If I was unclear about anything I apologize and would be glad to answer you.

    Any help is very appreciated!

    0

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.