Skip to content

Instantly share code, notes, and snippets.

@mandubian
Forked from scalamacroxamplez-admin/CODE
Last active December 20, 2015 01:19
Show Gist options
  • Save mandubian/6048471 to your computer and use it in GitHub Desktop.
Save mandubian/6048471 to your computer and use it in GitHub Desktop.
Infer #implicit #typeclass of input type inside macro #scala2.10
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
import scala.reflect.macros.Context
import language.experimental.macros
trait MyTypeClass[A] {
def doit(a: A): A
}
object Macros {
def inferImplicitsImpl[A: c.WeakTypeTag](c: Context): c.Expr[MyTypeClass[A]] = {
import c.universe._
// gets type of input type
val theType = weakTypeOf[A]
// builds expected implicit MyTypeClass[A]
val neededImplicitType = appliedType(weakTypeOf[MyTypeClass[_]].typeConstructor, theType :: Nil)
// searches an implicit in scope
val neededImplicit = c.inferImplicitValue(neededImplicitType)
neededImplicit match {
case EmptyTree => c.abort(c.enclosingPosition, s"No implicit MyTypeClass[${theType}] available.")
case impl => c.Expr[MyTypeClass[A]](impl)
}
}
def inferImplicits[A] = macro inferImplicitsImpl[A]
}
object Test {
implicit val myImpl = new MyTypeClass[Long]{
def doit(a: Long) = a
}
val toto = Macros.inferImplicits[Long]
val tata = Macros.inferImplicits[String]
}
// Launch it in scala macro & get error
<console>:22: error: No implicit MyTypeClass[String] available.
val tata = Macros.inferImplicits[String]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment