Skip to content

Instantly share code, notes, and snippets.

@kiritsuku
Last active December 16, 2015 22:39
Show Gist options
  • Save kiritsuku/5508769 to your computer and use it in GitHub Desktop.
Save kiritsuku/5508769 to your computer and use it in GitHub Desktop.
Scala 2.11 untyped hygienic swap macro
package macros
import language.experimental.macros
import scala.reflect.macros.Macro
object Macros {
def swap(a: _, b: _) = macro Impl.swap
}
trait Impl extends Macro {
import c.universe._
import c.universe.Flag._
def swap(a: c.Tree, b: c.Tree): c.Tree = {
val tmp = TermName(c.freshName("tmp"))
q"{ var $tmp = $a; $a = $b; $b = $tmp }"
/*
// without quasiquotes
Block(
List(
ValDef(Modifiers(MUTABLE), tmp, TypeTree(), a),
Assign(a, b),
Assign(b, Ident(tmp))
),
Literal(Constant(()))
)
*/
}
}
import macros.Macros.swap
object Test extends App {
var a = 10
var b = 5
println((a, b))
swap(a, b)
println((a, b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment