File: Macros_1.scala

package info (click to toggle)
scala 2.11.12-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 62,924 kB
  • sloc: javascript: 28,808; java: 13,415; xml: 3,135; sh: 1,620; python: 756; makefile: 38; awk: 36; ansic: 6
file content (22 lines) | stat: -rw-r--r-- 1,114 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context

object Macros {
  def foo[U: Numeric](x: U) = macro foo_impl[U]
  def bar[U: Numeric : Equiv, Y <% String](x: U)(implicit s: String) = macro bar_impl[U, Y]

  def foo_impl[U](c: Context)(x: c.Expr[U])(numeric: c.Expr[Numeric[U]]) = {
    import c.universe._
    val plusOne = Apply(Select(numeric.tree, newTermName("plus")), List(x.tree, Literal(Constant(1))))
    val body = Apply(Select(Ident(definitions.PredefModule), newTermName("println")), List(plusOne))
    c.Expr[Unit](body)
  }

  def bar_impl[U, Y](c: Context)(x: c.Expr[U])(numeric: c.Expr[Numeric[U]], equiv: c.Expr[Equiv[U]], viewAsString: c.Expr[Y => String], s: c.Expr[String]) = {
    import c.universe._
    val plusOne = Apply(Select(numeric.tree, newTermName("plus")), List(x.tree, Literal(Constant(1))))
    val plusLen = Apply(Select(numeric.tree, newTermName("plus")), List(plusOne, Select(s.tree, newTermName("length"))))
    val body = Apply(Select(Ident(definitions.PredefModule), newTermName("println")), List(plusLen))
    c.Expr[Unit](body)
  }
}