Make the method actually inline

I am creating a simple example to test the behavior of the @inline annotation:

import scala.annotation.tailrec

object InlineTest extends App {
  @inline
  private def corec(x : Int) : Int = rec(x - 1)

  @tailrec
  private def rec(x : Int) : Int =
    if (x < 3) x else {
      if (x % 3 == 0)
        corec(x-1)
      else
        rec(x-4)
    }

  @tailrec
  private def rec1(x : Int) : Int =
    if (x < 3) x else {
      if (x % 3 == 0) {
        val arg = x - 1
        rec1(arg - 1)
      } else
        rec1(x-4)
    }

  Console.println( rec(args(0).toInt) )
}

In this warning-free example, both tailrec annotations acted as I thought. But when I actually execute the code, it gives a stackoverflow exception. This means that tail recursion optimization failed because the inline method was not so inline.

I have a control function rec1that differs from the original only in manual conversion "inline". And since this function works well as expected, avoiding the stackoverflow exception with tail recursion.

What prevents the annotated method from being nested?

+4
2

. @inline , , , .

"" , - . , . , rec :

  @tailrec
  private def rec(x0: Int) : Int =
    var x: Int = x0
    while (true) {
      if (x < 3) x else {
        if (x % 3 == 0)
          return corec(x-1)
        else {
          x = x-4
          continue
        }
      }
    }

, corec , . @inline .

, , @tailrec? , . , rec ( , corec, rec).

, , corec .

@inline , inline corec, rec, corec, :

  @tailrec
  private def rec(x0: Int) : Int =
    var x: Int = x0
    while (true) {
      if (x < 3) x else {
        if (x % 3 == 0)
          return rec((x-1) - 1)
        else {
          x = x-4
          continue
        }
      }
    }

, . . . , .

TailCalls - . . API.

+7

, (scala PR 567), inline. ( 2016 )

. " SIP NN: - ( )"

:

,

inline val x = 4

,

inline def square(x: Double) = x * x

,

inline def pow(b: Double, inline n: Int): Double = {
  if (n == 0) 1
  else pow(b, n - 1)
}

, inline, ; . Inline . .

; , .
, , , .

+1

All Articles