reemq8 reemq8 - 3 months ago 12
Scala Question

Type missmatch with packrat scala/kiama error

I'm creating a mini-java compiler in Scala (kiama). One of my code blocks called "tipe" gives me an error that my introductory knowledge in Scala just cant crack.

This is my code (somewhat incomplete, but that I don't believe is giving me the error)

lazy val tipe : PackratParser[Type] =
"bool"|
"int" |
"obj" |
tipe ~("->" ~> tipe) |
("(" ~> tipe <~")")


I get the following error when i try to compile my program:


Type mismatch found:

Found : SyntaxAnalysis.this.Parser[Object]

Required: SyntaxAnalysis.this.PackratParser[funjs.FunJSTree.type]

tipe ~ ( "->" ~> tipe ) |


With an arrow pointing at the |

Any help would be appreciated, I'm new to Scala and this is rather complicated for me.

Answer

The compiler supposes tipe has the type you provide: PackratParser[Type]. This means tipe ~("->" ~> tipe) is a Parser[Type ~ Type], while "bool" etc. are converted to Parser[String]. Combining Parser[String] and Parser[Type ~ Type] using | gives you a Parser[Object] (as the common supertype of String and Type ~ Type). To solve this, you need to make sure every alternative (argument of |) is a Parser[Type]. Typically it should look like

lazy val tipe : PackratParser[Type] =
 "bool" ^^^ BoolType |
 ...
 tipe ~("->" ~> tipe) ^^ { case (t1, t2) => someFunctionOf(t1, t2) } |
 ("(" ~> tipe <~")")

using ^^ and ^^^ combinators.

(Note: if you are unfamiliar with { case (t1, t2) => ... } syntax, I recommend starting with something more basic.)

Comments