Created
February 6, 2013 14:42
-
-
Save travisbrown/4722946 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
package example | |
import scala.language.experimental.macros | |
import scala.reflect.macros.{ Context, Macro } | |
trait SInt[I <: Int] | |
object SInt { | |
implicit def materializeSInt[I <: Int](i: Int): SInt[I] = | |
macro MaterializeSInt.expand[I] | |
} | |
trait MaterializeSInt extends Macro { | |
def expand[I <: Int: c.WeakTypeTag](i: c.Expr[Int]): c.Expr[SInt[I]] = | |
c.universe.reify(new SInt[I] {}) | |
override def onInfer(tic: c.TypeInferenceContext): Unit = { | |
import c.universe._ | |
val Apply(_, List(Literal(const: Constant))) = tic.tree | |
tic.infer(tic.unknowns(0), ConstantType(const)) | |
} | |
} | |
trait SSum[A <: Int, B <: Int, C <: Int] | |
object SSum { | |
implicit def materializeSSum[A <: Int, B <: Int, C <: Int]: SSum[A, B, C] = | |
macro MaterializeSSum.expand[A, B, C] | |
} | |
trait MaterializeSSum extends Macro { | |
def expand[ | |
A <: Int: c.WeakTypeTag, | |
B <: Int: c.WeakTypeTag, | |
C <: Int: c.WeakTypeTag | |
]: c.Expr[SSum[A, B, C]] = c.universe.reify(new SSum[A, B, C] {}) | |
override def onInfer(tic: c.TypeInferenceContext): Unit = { | |
import c.universe._ | |
val TypeRef( | |
_, _, | |
List(ConstantType(Constant(a: Int)), ConstantType(Constant(b: Int)), _) | |
) = tic.expectedType | |
tic.infer(tic.unknowns(0), ConstantType(Constant(a))) | |
tic.infer(tic.unknowns(1), ConstantType(Constant(b))) | |
tic.infer(tic.unknowns(2), ConstantType(Constant(a + b))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment