Created
April 19, 2018 17:04
-
-
Save dos65/6a94cbf3be19ad458f50ef4d4a9e3595 to your computer and use it in GitHub Desktop.
This file contains 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 scala.collection.mutable | |
import scala.collection.mutable.ListBuffer | |
import scala.reflect.macros.whitebox.Context | |
import scala.language.experimental.macros | |
trait Dealised[A] { | |
def value: A | |
} | |
object Dealised { | |
implicit def materialize[A]: Dealised[A] = macro DealisedMacro.macroIml[A] | |
} | |
object DealisedMacro { | |
def macroIml[T: c.WeakTypeTag](c: Context): c.Expr[Dealised[T]] = { | |
import c.universe._ | |
val searchType = c.weakTypeOf[T] | |
def dealiased(t: c.Type): String = { | |
val x = t.dealias | |
val args = x.typeArgs | |
if (args.nonEmpty) { | |
val fixed = args.map(dealiased) | |
x.typeSymbol.name + fixed.mkString("[", ",", "]") | |
} else { | |
x.typeSymbol.name.decodedName.toString | |
} | |
} | |
val value = c.inferImplicitValue(searchType) | |
if (value.isEmpty) { | |
val t = dealiased(searchType) | |
val msg = s"could not find implicit value parameter for $t" | |
c.info(c.enclosingPosition, msg, true) | |
c.abort(c.enclosingPosition, msg) | |
} else { | |
c.Expr[Dealised[T]]( | |
q""" | |
new Dealised[$searchType] { | |
override def value: $searchType = $value | |
} | |
""" | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment