typelevel / spire

Powerful new number types and numeric abstractions for Scala.
http://typelevel.org/spire/
MIT License
1.76k stars 243 forks source link

Macro inlining fails for trivial functions #556

Open bashimao opened 8 years ago

bashimao commented 8 years ago

There is a bug with the macro inlining code. The following gives: 3

object Demo extends App {

  val res: Int = Macros.test(1, 2)
  println(res)

}

object Macros {

  def test(a: Int, b: Int): Int = macro test_impl

  def test_impl(c: Context)(a: c.Expr[Int], b: c.Expr[Int]): c.Expr[Int] = {
    import c.universe._

    val tree: Tree = q"$a + $b"
    new InlineUtil[c.type](c).inlineAndReset[Int](tree)
  }

}

which is correct. But if the macro is changed as follows, the result is 2

object Macros {

  def test(a: Int, b: Int): Int = macro test_impl

  def test_impl(c: Context)(a: c.Expr[Int], b: c.Expr[Int]): c.Expr[Int] = {
    import c.universe._

    val fn = c.universe.reify((i: Int, j: Int) => i + j)

    val tree: Tree = q"$fn($a, $b)"
    new InlineUtil[c.type](c).inlineAndReset[Int](tree)
  }

}

The worst part of it is that there is no warning. I checked the code, but my macro debugging capabilities are limited. It looks as if the error originates from values being overwritten in InlineSymbol.transform(...). Apparently, several instances of tree are supplied to transform(tree: Tree) where the tree.symbol == symbol match is ambiguous.

bashimao commented 8 years ago

I just tested it with a bunch of more complex things. The functions still work. But inlining could be much better. Would it be possible to apply an optimizer?