I am currently building a parser using Scala parser combinators. The parser must accept boolean expressions which at the moment I am type checking and evaluating manually. However, I want to extend this particular feature and be able to accept more complex boolean expressions which would require more manual work. I was wondering whether the typechecking could be achieved using directly the Scala compiler, to which I would pass the particular expression that I want to be typechecked and the types of each particular variable. Below is an example of what I mean:
Assume that I have a boolean expression: age > 18
. Together with a mapping knowing that the variable age
is of type Int
. I want to be able to pass (in any format) age > 18
and the type mappings to the Scala compiler, and it will return whether it typechecks to a boolean expression or not.
Courtesy of u/aepurniet from this Reddit post.
The statement must be prefixed to the statement with some value definitions, then parse and then type checked. The resultant type of the expression can be checked from checked.tpe
.
def main(args: Array[String]): Unit = {
import scala.reflect.runtime._
import scala.tools.reflect.ToolBox
val toolbox = currentMirror.mkToolBox()
val expr = "age > 18"
val eval = s"""
|val age: Int = ???
|$expr
|""".stripMargin
val tree = toolbox.parse(eval)
val checked = toolbox.typecheck(tree)
println(checked.tpe)
}