Created
March 2, 2016 10:09
-
-
Save lancelet/0d0713af7eb1401c9b1a to your computer and use it in GitHub Desktop.
WillBeTrue (Improved)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Intended to be run in shapeless sbt console; use :paste | |
| //--- paste this first to define the macro | |
| import scala.language.experimental.macros | |
| import scala.reflect.macros.whitebox | |
| import scala.util.control.NonFatal | |
| object WillBeTrue { | |
| def apply(code: String): Boolean = macro WillBeTrueMacros.applyImpl | |
| } | |
| @macrocompat.bundle | |
| class WillBeTrueMacros(val c: whitebox.Context) { | |
| import c.universe._ | |
| def applyImpl(code: Tree): Tree = { | |
| // unpack the string | |
| val Literal(Constant(codeStr: String)) = code | |
| // try to compile it and evaluate it as a Boolean | |
| try { | |
| val dummy0 = TermName(c.freshName) | |
| val dummy1 = TermName(c.freshName) | |
| val tree = c.parse(s"{ object $dummy0 { val $dummy1: Boolean = { $codeStr } }; $dummy0.$dummy1 }") | |
| c.typecheck(tree) | |
| tree | |
| } catch { | |
| case NonFatal(e) => | |
| println(s"Exception: $e") | |
| q"false" | |
| } | |
| } | |
| } | |
| //--- paste this second | |
| val wontCompile: Boolean = WillBeTrue(""" ("LambdaJam!": Int) == 42 """) | |
| val willCompile: Boolean = WillBeTrue(""" (42: Int) == 42 """) | |
| val compilesButWrong: Boolean = WillBeTrue(""" (42: Int) == 43 """) | |
| // also captures the environment | |
| val x = true; WillBeTrue(""" x """) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works for me! I think this'd make a great addition to shapeless, prolly in the getOrElse form ..