Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created January 24, 2018 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuwei-k/cc29e752f59aa201e6b66b1f5615e329 to your computer and use it in GitHub Desktop.
Save xuwei-k/cc29e752f59aa201e6b66b1f5615e329 to your computer and use it in GitHub Desktop.
scalaVersion := "2.12.4"
libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value
force_true > test:run
[info] Updating ...
[info] Done updating.
[info] Compiling 1 Scala source to /Users/kenji_yoshida/force_true/target/scala-2.12/classes ...
[info] Done compiling.
[info] Compiling 1 Scala source to /Users/kenji_yoshida/force_true/target/scala-2.12/test-classes ...
[info] Packaging /Users/kenji_yoshida/force_true/target/scala-2.12/force_true_2.12-0.1.0-SNAPSHOT.jar ...
[info] Done packaging.
a.==(1) を強制的に true に変換します( ^ω^)
a.==(2) を強制的に true に変換します( ^ω^)
a.==(3) を強制的に true に変換します( ^ω^)
[info] Done compiling.
[info] Packaging /Users/kenji_yoshida/force_true/target/scala-2.12/force_true_2.12-0.1.0-SNAPSHOT-tests.jar ...
[info] Done packaging.
[info] Running example.Test
true
[success] Total time: 2 s, completed 2018/01/24 14:07:14
// src/main/scala/Main.scala
package example
import scala.reflect.macros.blackbox.Context
import scala.language.experimental.macros
object Main {
def foo[A](f: A): A = macro Main.fooImpl[A]
def fooImpl[A: c.WeakTypeTag](c: reflect.macros.blackbox.Context)(f: c.Tree) = {
import c.universe._
val transformer = new Transformer{
override def transform(tree: Tree) = super.transform{
tree match {
case q"${x} == ${y}" =>
println(s" $tree を強制的に true に変換します( ^ω^)")
c.typecheck(q"true")
case _ =>
tree
}
}
}
transformer.transform(f)
}
}
// src/test/scala/Test.scala
package example
object Test {
def main(args: Array[String]): Unit = Main.foo{
val a = 0
val result = (a == 1) && (a == 2) && (a == 3)
println(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment