Last active
December 11, 2015 01:58
-
-
Save puffnfresh/4526736 to your computer and use it in GitHub Desktop.
Removing any2unit via a macro.
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
import language.experimental.{ macros => scalaMacros } | |
import reflect.macros.Context | |
package object macros { | |
def safe[A](expr: A) = macro safeImpl[A] | |
def safeImpl[A](c: Context)(expr: c.Expr[A]): c.Expr[A] = { | |
import c.universe._ | |
def isIgnoredStatement(tree: Tree) = tree match { | |
// Scala creates synthetic blocks with <init> calls on classes. | |
// The calls return Object so we need to ignore them. | |
case Apply(Select(_, nme.CONSTRUCTOR), _) => true | |
case _ => false | |
} | |
object NoUnit extends Traverser { | |
override def traverse(tree: Tree) = { | |
tree match { | |
case Block(statements, _) => | |
statements.foreach { stat => | |
val unitLike = stat.tpe =:= typeOf[Unit] || stat.isDef || isIgnoredStatement(stat) | |
if (!unitLike) | |
c.error(stat.pos, "Statements must return Unit") | |
} | |
case _ => | |
} | |
super.traverse(tree) | |
} | |
} | |
NoUnit.traverse(expr.tree) | |
expr | |
} | |
} |
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
// No any2unit! | |
Macros.safe { | |
def x(a: Int) = { | |
// Won't compile: | |
// a | |
println("Returning a") | |
a | |
} | |
// Won't compile: | |
// 1 | |
// x(1) | |
// x _ | |
println("HELLO") | |
println("HELLO") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
c.error(stat.pos, msg)
is better form.Traverser
, rather than aTransformer
, the easiest way is via:Universe#{nme, tpnme}