From 8427612d59d911670806cb26e3fddfc1636441f1 Mon Sep 17 00:00:00 2001 From: Svyatoslav Scherbina Date: Fri, 3 Mar 2017 12:08:00 +0700 Subject: [PATCH] backend/tests: add trivial tests for `tailrec` --- backend.native/tests/build.gradle | 11 +++++ backend.native/tests/lower/tailrec.kt | 64 +++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 backend.native/tests/lower/tailrec.kt diff --git a/backend.native/tests/build.gradle b/backend.native/tests/build.gradle index cd9f09b0fbd..5f53c81737c 100644 --- a/backend.native/tests/build.gradle +++ b/backend.native/tests/build.gradle @@ -1207,6 +1207,7 @@ task initializers2(type: RunKonanTest) { "1\n" + "globalValue2\n" + "globalValue3\n" + source = "runtime/basic/initializers2.kt" } @@ -1301,6 +1302,16 @@ task vararg_of_literals(type: RunKonanTest) { source = "lower/vararg_of_literals.kt" } +task tailrec(type: RunKonanTest) { + goldValue = "12\n100000000\n" + + "8\n" + + "1\n" + + "3 ...\n2 ...\n1 ...\nready!\n" + + "2\n-1\n" + + "true\nfalse\n" + source = "lower/tailrec.kt" +} + task inline4(type: RunKonanTest) { goldValue = "3\n" source = "codegen/inline/inline4.kt" diff --git a/backend.native/tests/lower/tailrec.kt b/backend.native/tests/lower/tailrec.kt new file mode 100644 index 00000000000..7c357824efb --- /dev/null +++ b/backend.native/tests/lower/tailrec.kt @@ -0,0 +1,64 @@ +fun main(args: Array) { + println(add(5, 7)) + println(add(100000000, 0)) + + println(fib(6)) + + println(one(5)) + + countdown(3) + + println(listOf(1, 2, 3).indexOf(3)) + println(listOf(1, 2, 3).indexOf(4)) + + println(Integer(5).isLessOrEqualThan(7)) + println(Integer(42).isLessOrEqualThan(1)) +} + +tailrec fun add(x: Int, y: Int): Int = if (x > 0) add(x - 1, y + 1) else y + +fun fib(n: Int): Int { + tailrec fun fibAcc(n: Int, acc: Int): Int = if (n < 2) { + n + acc + } else { + fibAcc(n - 1, fibAcc(n - 2, acc)) + } + + return fibAcc(n, 0) +} + +tailrec fun one(delay: Int, result: Int = delay + 1): Int = if (delay > 0) one(delay - 1) else result + +tailrec fun countdown(iterations: Int): Unit { + if (iterations > 0) { + println("$iterations ...") + countdown(iterations - 1) + } else { + println("ready!") + } +} + +tailrec fun List.indexOf(x: T, startIndex: Int = 0): Int { + if (startIndex >= this.size) { + return -1 + } + + if (this[startIndex] != x) { + return this.indexOf(x, startIndex + 1) + } + + return startIndex + +} + +open class Integer(val value: Int) { + open tailrec fun isLessOrEqualThan(value: Int): Boolean { + if (this.value == value) { + return true + } else if (value > 0) { + return this.isLessOrEqualThan(value - 1) + } else { + return false + } + } +} \ No newline at end of file