Skip to content

Instantly share code, notes, and snippets.

@travisbrown
Created February 6, 2013 14:42
Show Gist options
  • Save travisbrown/4722946 to your computer and use it in GitHub Desktop.
Save travisbrown/4722946 to your computer and use it in GitHub Desktop.
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