Warm tip: This article is reproduced from stackoverflow.com, please click
parsing scala typechecking parser-combinators

Is there a way to typecheck boolean expressions using the Scala compiler?

发布于 2020-03-27 15:43:42

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.

Questioner
Chris Bartolo
Viewed
80
Chris Bartolo 2020-02-02 18:00

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)
}