Skip to content

Instantly share code, notes, and snippets.

@Sciss
Forked from retronym/macro-ret.scala
Created July 2, 2012 17:00
Show Gist options
  • Save Sciss/3034269 to your computer and use it in GitHub Desktop.
Save Sciss/3034269 to your computer and use it in GitHub Desktop.
macro with computed return type
scala> def retImpl(c: Context)(b: c.Expr[Boolean]): c.Expr[Any] = {
| import c.universe._
| val Literal(Constant(bool: Boolean)) = b.tree
| if (bool) c.reify(0) else c.reify(false)
| }
retImpl: (c: scala.reflect.makro.Context)(b: c.Expr[Boolean])c.Expr[Any]
scala> def ret(b: Boolean) = macro retImpl
ret: (b: Boolean)Any
scala> ret(true)
res3: Int = 0
scala> ret(false)
res4: Boolean = false
scala> ret(false) | true
res5: Boolean = true
scala> ret(false) * 1
<console>:16: error: value * is not a member of Boolean
ret(false) * 1
^
scala> ret(true) * 1
res7: Int = 0
@Sciss
Copy link
Author

Sciss commented Jul 2, 2012

val x = true
ret(x) // --> match error

In other words, compile time assertions will probably need to be restricted to a few tree patterns such as literals...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment