diff options
author | Martin Odersky <odersky@gmail.com> | 2005-10-05 11:08:17 +0000 |
---|---|---|
committer | Martin Odersky <odersky@gmail.com> | 2005-10-05 11:08:17 +0000 |
commit | 0a6b2c44cbdcea9e9c248b6a5b9970ad4cd86001 (patch) | |
tree | c008a12ea7e928b3f34e0c345c84832d90c1c8ad /test-nsc/files/run | |
parent | 041a971eb7f89d2976bee5512a6caf7de7bff27c (diff) | |
download | scala-0a6b2c44cbdcea9e9c248b6a5b9970ad4cd86001.tar.gz scala-0a6b2c44cbdcea9e9c248b6a5b9970ad4cd86001.tar.bz2 scala-0a6b2c44cbdcea9e9c248b6a5b9970ad4cd86001.zip |
*** empty log message ***
Diffstat (limited to 'test-nsc/files/run')
33 files changed, 8674 insertions, 0 deletions
diff --git a/test-nsc/files/run/Course-2002-01.scala b/test-nsc/files/run/Course-2002-01.scala new file mode 100755 index 0000000000..b31d1016fd --- /dev/null +++ b/test-nsc/files/run/Course-2002-01.scala @@ -0,0 +1,240 @@ +//############################################################################ +// Programmation IV - 2002 - Week 01 +//############################################################################ +// $Id$ + +object M0 { + + //########################################################################## + + Console.println(87 + 145); + Console.println(1000 - 333); + Console.println(5 + 2 * 3); + + //########################################################################## + + def size = 2; + def pi = 3.14159; + def radius = 10; + def circumference = 2 * pi * radius; + + Console.println(5 * size); + Console.println(2 * pi * radius); + Console.println(circumference); + Console.println((2 * pi) * radius); + + //########################################################################## + + def square(x: Double) = x * x; + + Console.println(square(2)); + Console.println(square(5 + 4)); + Console.println(square(square(4))); + + //########################################################################## + + def sumOfSquares(x: Double, y: Double) = square(x) + square(y); + + Console.println(sumOfSquares(3, 2+2)); + + //########################################################################## + + def loop: Int = loop; + def first(x: Int, y: Int) = x; + def constOne(x: Int, y: => Int) = 1; + + Console.println(constOne(1, loop)); + + //########################################################################## + + def abs(x: Double) = if (x >= 0) x else -x; + + Console.println(abs(737)); + Console.println(abs(1)); + Console.println(abs(0)); + Console.println(abs(-1)); + Console.println(abs(-76)); + + //########################################################################## + + def sqrtIter0(guess: Double, x: Double): Double = + if (isGoodEnough0(guess, x)) guess + else sqrtIter0(improve0(guess, x), x); + + def improve0(guess: Double, x: Double) = + (guess + x / guess) / 2; + + def isGoodEnough0(guess: Double, x: Double) = + abs(square(guess) - x) < 0.001; + + def sqrt0(x: Double) = sqrtIter0(1.0, x); + + Console.println(sqrt0(2)); + Console.println(sqrt0(3)); + Console.println(sqrt0(4)); + + //########################################################################## + + def sqrt1(x: Double) = { + def sqrtIter1(guess: Double, x: Double): Double = + if (isGoodEnough1(guess, x)) guess + else sqrtIter1(improve1(guess, x), x); + + def improve1(guess: Double, x: Double) = + (guess + x / guess) / 2; + + def isGoodEnough1(guess: Double, x: Double) = + abs(square(guess) - x) < 0.001; + + sqrtIter1(1.0, x) + } + + Console.println(sqrt1(2)); + Console.println(sqrt1(3)); + Console.println(sqrt1(4)); + + //########################################################################## + + def sqrt2(x: Double) = { + def sqrtIter2(guess: Double): Double = + if (isGoodEnough2(guess)) guess + else sqrtIter2(improve2(guess)); + + def improve2(guess: Double) = + (guess + x / guess) / 2; + + def isGoodEnough2(guess: Double) = + abs(square(guess) - x) < 0.001; + + sqrtIter2(1.0) + } + + Console.println(sqrt2(2)); + Console.println(sqrt2(3)); + Console.println(sqrt2(4)); + + //########################################################################## +} + +//############################################################################ + +object M1 { + def abs(x: Double) = if (x >= 0) x else -x; + + def sqrt(x: Double): Double = { + def sqrtIter(prev: Double, guess: Double): Double = + if (isGoodEnough(prev, guess)) guess + else sqrtIter(guess, improve(guess)); + + def improve(guess: Double) = (guess + x / guess) / 2; + + def isGoodEnough(prev: Double, guess: Double) = + abs(prev - guess) / guess < 0.001; + + sqrtIter(1.0, improve(1.0)) + } + + Console.println("sqrt(2) = " + sqrt(2)); +} + +//############################################################################ + +object M2 { + def abs(x: Double) = if (x >= 0) x else -x; + + def sqrt(x:Double):Double = { + def sqrtIter(guess:Double):Double = { + val next = improve(guess); + if (isGoodEnough(guess,next)) next + else sqrtIter(next) + } + + def improve(guess:Double) = (guess+x/guess)/2; + + def isGoodEnough(prev:Double,guess:Double) = abs(prev-guess)/guess<0.001; + + sqrtIter(1.0) + } + + Console.println("sqrt(2) = " + sqrt(2)); +} + +//############################################################################ + +object M3 { + def abs(x: Double) = if (x >= 0) x else -x; + + def cbrt(x:Double):Double = { + def cbrtIter(guess:Double):Double = { + val next = improve(guess); + if (isGoodEnough(guess,next)) next + else cbrtIter(next) + } + + def improve(y:Double) = (x/(y*y)+2*y)/3; + + def isGoodEnough(prev:Double,guess:Double) = abs(prev-guess)/guess<0.001; + + cbrtIter(1.0) + } + + Console.println("cbrt(2) = " + cbrt(2)); +} + +//############################################################################ + +object M4 { + def pascal(c: Int, l: Int): Int = + if (c <= 0 || c >= l) 1 + else pascal(c - 1, l - 1) + pascal(c, l - 1); + + Console.print(pascal(0,0)); + Console.println; + + Console.print(pascal(0,1)); + Console.print(' '); + Console.print(pascal(1,1)); + Console.println; + + Console.print(pascal(0,2)); + Console.print(' '); + Console.print(pascal(1,2)); + Console.print(' '); + Console.print(pascal(2,2)); + Console.println; + + Console.print(pascal(0,3)); + Console.print(' '); + Console.print(pascal(1,3)); + Console.print(' '); + Console.print(pascal(2,3)); + Console.print(' '); + Console.print(pascal(3,3)); + Console.println; + + Console.print(pascal(0,4)); + Console.print(' '); + Console.print(pascal(1,4)); + Console.print(' '); + Console.print(pascal(2,4)); + Console.print(' '); + Console.print(pascal(3,4)); + Console.print(' '); + Console.print(pascal(4,4)); + Console.println; +} + +//############################################################################ + +object Test { + def main(args: Array[String]): Unit = { + M0; + M1; + M2; + M3; + M4; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/Course-2002-02.scala b/test-nsc/files/run/Course-2002-02.scala new file mode 100755 index 0000000000..00f43501f4 --- /dev/null +++ b/test-nsc/files/run/Course-2002-02.scala @@ -0,0 +1,554 @@ +//############################################################################ +// Programmation IV - 2002 - Week 02 +//############################################################################ +// $Id$ + +object M0 { + def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b); + def factorial(n: Int): Int = if (n == 0) 1 else n * factorial(n - 1); + + Console.println(gcd(14,21)); + Console.println(factorial(5)); + Console.println; +} + +//############################################################################ + +object M1 { + def cube(x: Int): Double = x * x * x; + + def sumInts(a: Int, b: Int): Double = + if (a > b) 0 + else a + sumInts(a + 1, b); + + def sumCubes(a: Int, b: Int): Double = + if (a > b) 0 + else cube(a) + sumCubes(a + 1, b); + + def sumReciprocals(a: Int, b: Int): Double = + if (a > b) 0 + else 1.0/a + sumReciprocals(a + 1, b); + + def sumPi(n: Int): Double = { + def element(x: Int): Double = 4.0/(4*x+1) - 4.0/(4*x-1); + def sumElements(a: Int, b: Int): Double = + if (a > b) 0 + else element(a) + sumElements(a + 1, b); + 4 + sumElements(1,n) + } + + Console.println(sumInts(1,4)); + Console.println(sumCubes(1,4)); + Console.println(sumReciprocals(1,4)); + Console.println(sumCubes(1, 10) + sumReciprocals(10, 20)); + Console.println("pi = " + sumPi(20)); + Console.println; +} + +//############################################################################ + +object M2 { + def id(x: Int): Double = x; + def cube(x: Int): Double = x * x * x; + def reciprocal(x: Int): Double = 1.0/x; + + def sum(f: Int => Double, a: Int, b: Int): Double = + if (a > b) 0 + else f(a) + sum(f, a + 1, b); + + def sumInts(a: Int, b: Int): Double = sum(id, a, b); + def sumCubes(a: Int, b: Int): Double = sum(cube, a, b); + def sumReciprocals(a: Int, b: Int): Double = sum(reciprocal, a, b); + def sumPi(n: Int): Double = { + def element(x: Int): Double = 4.0/(4*x+1) - 4.0/(4*x-1); + 4 + sum(element, 1, n) + } + + Console.println(sumInts(1,4)); + Console.println(sumCubes(1,4)); + Console.println(sumReciprocals(1,4)); + Console.println(sumCubes(1, 10) + sumReciprocals(10, 20)); + Console.println("pi = " + sumPi(20)); + Console.println; +} + +//############################################################################ + +object M3 { + def sum(f: Int => Double, a: Int, b: Int): Double = + if (a > b) 0 + else f(a) + sum(f, a + 1, b); + + def sumInts(a: Int, b: Int): Double = sum((xXXXXX => xXXXXX), a, b); + def sumCubes(a: Int, b: Int): Double = sum((x => x * x * x), a, b); + def sumReciprocals(a: Int, b: Int): Double = sum((x => 1.0/x), a, b); + def sumPi(n: Int): Double = 4 + sum((x => 4.0/(4*x+1) - 4.0/(4*x-1)), 1, n); + + Console.println(sumInts(1,4)); + Console.println(sumCubes(1,4)); + Console.println(sumReciprocals(1,4)); + Console.println(sumCubes(1, 10) + sumReciprocals(10, 20)); + Console.println("pi = " + sumPi(20)); + Console.println; +} + +//############################################################################ + +object M4 { + def sum(f: Int => Double) = { + def sumF(a: Int, b: Int): Double = + if (a > b) 0 + else f(a) + sumF(a + 1, b); + sumF + } + + def sumInts = sum(x => x); + def sumCubes = sum(x => x * x * x); + def sumReciprocals = sum(x => 1.0/x); + def sumPi = (n: Int => 4 + sum(x => 4.0/(4*x+1) - 4.0/(4*x-1))(1, n)); + + Console.println(sumInts(1,4)); + Console.println(sumCubes(1,4)); + Console.println(sumReciprocals(1,4)); + Console.println(sumCubes(1, 10) + sumReciprocals(10, 20)); + Console.println("pi = " + sumPi(20)); + Console.println; +} + +//############################################################################ + +object M5 { + def sum(f: Int => Double): (Int, Int) => Double = { (a, b) => + if (a > b) 0 + else f(a) + sum(f)(a + 1, b) + } + + def sumInts = sum(x => x); + def sumCubes = sum(x => x * x * x); + def sumReciprocals = sum(x => 1.0/x); + def sumPi = (n: Int => 4 + sum(x => 4.0/(4*x+1) - 4.0/(4*x-1))(1, n)); + + Console.println(sumInts(1,4)); + Console.println(sumCubes(1,4)); + Console.println(sumReciprocals(1,4)); + Console.println(sumCubes(1, 10) + sumReciprocals(10, 20)); + Console.println("pi = " + sumPi(20)); + Console.println; +} + +//############################################################################ + +object M6 { + def sum(f: Int => Double)(a: Int, b: Int): Double = + if (a > b) 0 + else f(a) + sum(f)(a + 1, b); + + def sumInts = sum(x => x); + def sumCubes = sum(x => x * x * x); + def sumReciprocals = sum(x => 1.0/x); + def sumPi = (n: Int => 4 + sum(x => 4.0/(4*x+1) - 4.0/(4*x-1))(1, n)); + + Console.println(sumInts(1,4)); + Console.println(sumCubes(1,4)); + Console.println(sumReciprocals(1,4)); + Console.println(sumCubes(1, 10) + sumReciprocals(10, 20)); + Console.println("pi = " + sumPi(20)); + Console.println; +} + +//############################################################################ + +object M7 { + def sum(f: Int => Double)(a: Int, b: Int): Double = { + def iter(a: Int, result: Double): Double = + if (a > b) result + else iter(a + 1, f(a) + result); + iter(a, 0) + } + + def sumInts = sum(x => x); + def sumCubes = sum(x => x * x * x); + def sumReciprocals = sum(x => 1.0/x); + def sumPi = (n: Int => 4 + sum(x => 4.0/(4*x+1) - 4.0/(4*x-1))(1, n)); + + Console.println(sumInts(1,4)); + Console.println(sumCubes(1,4)); + Console.println(sumReciprocals(1,4)); + Console.println(sumCubes(1, 10) + sumReciprocals(10, 20)); + Console.println("pi = " + sumPi(20)); + Console.println; +} + +//############################################################################ + +object M8 { + def product(f: Int => Double)(a: Int, step: Int, b: Int): Double = + if (a > b) 1 + else f(a) * product(f)(a + step, step, b); + + def productPi = (n: Int => product(x=>4.0*x*x/(2*x-1)/(2*x-1))(1,1,n)/n); + + val pi = 2 * product(x => x * x)(2, 2, 40) / product(x => x * x)(1, 2,40)/40; + + Console.println("pi = " + productPi(20)); + Console.println("pi = " + pi); + Console.println; +} + +//############################################################################ + +object M9 { + def accumulate[t](combiner: (t, t) => t, nullValue: t, f: Int => t, next: Int => Int) + (a: Int, b: Int): t = + if (a > b) nullValue + else combiner(f(a), accumulate(combiner, nullValue, f, next)(next(a), b)); + + def inc(x: Int) = x + 1; + + def sum(f: Int => Double) = + accumulate((x: Double, y: Double) => x + y, 0d, f, inc); + def product(f: Int => Double) = + accumulate((x: Double, y: Double) => x * y, 1d, f, inc); + + def sumInts = sum(x => x); + def sumCubes = sum(x => x * x * x); + def sumReciprocals = sum(x => 1.0/x); + def sumPi = (n: Int => 4 + sum(x => 4.0/(4*x+1) - 4.0/(4*x-1))(1, n)); + + def productPi = (n: Int => product(x=>4.0*x*x/(2*x-1)/(2*x-1))(1,n)/n); + + val pi = 2*product(x => 2*x*2*x)(1,20)/product(x =>(2*x-1)*(2*x-1))(1,20)/40; + + Console.println(sumInts(1,4)); + Console.println(sumCubes(1,4)); + Console.println(sumReciprocals(1,4)); + Console.println(sumCubes(1, 10) + sumReciprocals(10, 20)); + Console.println("pi = " + sumPi(20)); + Console.println("pi = " + productPi(20)); + Console.println("pi = " + pi); + Console.println; +} + +//############################################################################ + +object MA { + val tolerance = 0.0001; + def abs(x: Double) = if (x < 0) -x else x; + def isCloseEnough(x: Double, y: Double) = abs((x - y) / x) < tolerance; + def fixedPoint(f: Double => Double)(firstGuess: Double) = { + def iterate(guess: Double): Double = { + val next = f(guess); + Console.println(next); + if (isCloseEnough(guess, next)) next + else iterate(next) + } + iterate(firstGuess) + } + def sqrt(x: Double) = fixedPoint(y => (y + x / y) / 2)(1.0); + + Console.println("sqrt(2) = " + sqrt(2)); + Console.println +} + +//############################################################################ + +object MB { + val tolerance = 0.0001; + def abs(x: Double) = if (x < 0) -x else x; + def isCloseEnough(x: Double, y: Double) = abs((x - y) / x) < tolerance; + def fixedPoint(f: Double => Double)(firstGuess: Double) = { + def iterate(guess: Double): Double = { + val next = f(guess); + Console.println(next); + if (isCloseEnough(guess, next)) next + else iterate(next) + } + iterate(firstGuess) + } + def averageDamp(f: Double => Double)(x: Double) = (x + f(x)) / 2; + def sqrt(x: Double) = fixedPoint(averageDamp(y => x/y))(1.0); + + Console.println("sqrt(2) = " + sqrt(2)); + Console.println +} + +//############################################################################ + +object MC { + def sum(f: Int => Double)(a: Int, b: Int): Double = { + def iter(a: Int, result: Double): Double = { + if (a > b) result + else iter(a + 1, result + f(a)) + } + iter(a, 0) + } + + def product(f: Int => Double)(a: Int, b: Int): Double = { + def iter(a: Int, result: Double): Double = { + if (a > b) result + else iter(a + 1, result * f(a)) + } + iter(a, 1) + } + + def factorial(n: Int) = product(x => x)(1 , n); + + Console.println( + "1 + 2 + .. + 5 = " + sum(x => x)(1, 5)); + Console.println( + "1 * 2 * .. * 5 = " + product(x => x)(1, 5)); + Console.println; + + Console.println( + "1^2 + 2^2 + .. + 5^2 = " + sum(x => x*x)(1, 5)); + Console.println( + "1^2 * 2^2 * .. * 5^2 = " + product(x => x*x)(1, 5)); + Console.println; + + Console.println( + "factorial(0) = " + factorial(0)); + Console.println( + "factorial(1) = " + factorial(1)); + Console.println( + "factorial(2) = " + factorial(2)); + Console.println( + "factorial(3) = " + factorial(3)); + Console.println( + "factorial(4) = " + factorial(4)); + Console.println( + "factorial(5) = " + factorial(5)); + Console.println; +} + +//############################################################################ + +object MD { + def reduce(op: (Double,Double) => Double, zero:Double) + (f: Int => Double)(a: Int,b: Int): Double = { + def iter(a: Int, result: Double): Double = { + if (a > b) result + else iter(a + 1, op(result, f(a))) + } + iter(a, zero) + } + + def plus (x:Double,y:Double) = x+y; val sum = reduce(plus , 0); + def times(x:Double,y:Double) = x*y; val product = reduce(times, 1); + + def factorial(n: Int) = product(x => x)(1 , n); + + Console.println( + "1 + 2 + .. + 5 = " + sum(x => x)(1, 5)); + Console.println( + "1 * 2 * .. * 5 = " + product(x => x)(1, 5)); + Console.println; + + Console.println( + "1^2 + 2^2 + .. + 5^2 = " + sum(x => x*x)(1, 5)); + Console.println( + "1^2 * 2^2 * .. * 5^2 = " + product(x => x*x)(1, 5)); + Console.println; + + Console.println( + "factorial(0) = " + factorial(0)); + Console.println( + "factorial(1) = " + factorial(1)); + Console.println( + "factorial(2) = " + factorial(2)); + Console.println( + "factorial(3) = " + factorial(3)); + Console.println( + "factorial(4) = " + factorial(4)); + Console.println( + "factorial(5) = " + factorial(5)); + Console.println; +} + +//############################################################################ + +object ME { + def reduce(op: (Double,Double) => Double, zero:Double) + (f: Int => Double)(a: Int,b: Int): Double = { + def iter(a: Int, result: Double): Double = { + if (a > b) result + else iter(a + 1, op(result, f(a))) + } + iter(a, zero) + } + + def sum = reduce((x,y) => x + y, 0); + def product = reduce((x,y) => x * y, 1); + + def factorial(n: Int) = product(x => x)(1 , n); + + Console.println( + "1 + 2 + .. + 5 = " + sum(x => x)(1, 5)); + Console.println( + "1 * 2 * .. * 5 = " + product(x => x)(1, 5)); + Console.println; + + Console.println( + "1^2 + 2^2 + .. + 5^2 = " + sum(x => x*x)(1, 5)); + Console.println( + "1^2 * 2^2 * .. * 5^2 = " + product(x => x*x)(1, 5)); + Console.println; + + Console.println( + "factorial(0) = " + factorial(0)); + Console.println( + "factorial(1) = " + factorial(1)); + Console.println( + "factorial(2) = " + factorial(2)); + Console.println( + "factorial(3) = " + factorial(3)); + Console.println( + "factorial(4) = " + factorial(4)); + Console.println( + "factorial(5) = " + factorial(5)); + Console.println; +} + +//############################################################################ + +object MF { + def fib(x: Int): Int = + if (x <= 1) x + else fib(x - 2) + fib(x - 1); + + Console.println("fib(0) = " + fib(0)); + Console.println("fib(1) = " + fib(1)); + Console.println("fib(2) = " + fib(2)); + Console.println("fib(3) = " + fib(3)); + Console.println("fib(4) = " + fib(4)); + Console.println("fib(5) = " + fib(5)); + Console.println("fib(6) = " + fib(6)); + Console.println("fib(7) = " + fib(7)); + Console.println("fib(8) = " + fib(8)); + Console.println("fib(9) = " + fib(9)); +} + +//############################################################################ + +object MG { + def fib(x: Int) = { + def loop(n: Int, prev: Int, fibn: Int): Int = + if (n == x) fibn + else loop(n + 1, fibn, fibn + prev); + if (x == 0) 0 else loop(1, 0, 1) + } + + Console.println("fib(0) = " + fib(0)); + Console.println("fib(1) = " + fib(1)); + Console.println("fib(2) = " + fib(2)); + Console.println("fib(3) = " + fib(3)); + Console.println("fib(4) = " + fib(4)); + Console.println("fib(5) = " + fib(5)); + Console.println("fib(6) = " + fib(6)); + Console.println("fib(7) = " + fib(7)); + Console.println("fib(8) = " + fib(8)); + Console.println("fib(9) = " + fib(9)); +} + +//############################################################################ + +object MH { + def power(x: Double, y: Int): Double = + if (y <= 0) 1 + else if (y % 2 == 0) power(x * x, y / 2) + else x * power(x, y - 1); + + + Console.println("power(0,0) = " + power(0,0)); + Console.println("power(0,1) = " + power(0,1)); + Console.println("power(0,2) = " + power(0,2)); + Console.println("power(0,3) = " + power(0,3)); + Console.println("power(0,4) = " + power(0,4)); + Console.println("power(0,5) = " + power(0,5)); + Console.println("power(0,6) = " + power(0,6)); + Console.println("power(0,7) = " + power(0,7)); + Console.println("power(0,8) = " + power(0,8)); + Console.println; + + Console.println("power(1,0) = " + power(1,0)); + Console.println("power(1,1) = " + power(1,1)); + Console.println("power(1,2) = " + power(1,2)); + Console.println("power(1,3) = " + power(1,3)); + Console.println("power(1,4) = " + power(1,4)); + Console.println("power(1,5) = " + power(1,5)); + Console.println("power(1,6) = " + power(1,6)); + Console.println("power(1,7) = " + power(1,7)); + Console.println("power(1,8) = " + power(1,8)); + Console.println; + + Console.println("power(2,0) = " + power(2,0)); + Console.println("power(2,1) = " + power(2,1)); + Console.println("power(2,2) = " + power(2,2)); + Console.println("power(2,3) = " + power(2,3)); + Console.println("power(2,4) = " + power(2,4)); + Console.println("power(2,5) = " + power(2,5)); + Console.println("power(2,6) = " + power(2,6)); + Console.println("power(2,7) = " + power(2,7)); + Console.println("power(2,8) = " + power(2,8)); + Console.println; + + Console.println("power(3,0) = " + power(3,0)); + Console.println("power(3,1) = " + power(3,1)); + Console.println("power(3,2) = " + power(3,2)); + Console.println("power(3,3) = " + power(3,3)); + Console.println("power(3,4) = " + power(3,4)); + Console.println("power(3,5) = " + power(3,5)); + Console.println("power(3,6) = " + power(3,6)); + Console.println("power(3,7) = " + power(3,7)); + Console.println("power(3,8) = " + power(3,8)); + Console.println; + + Console.println("power(4,0) = " + power(4,0)); + Console.println("power(4,1) = " + power(4,1)); + Console.println("power(4,2) = " + power(4,2)); + Console.println("power(4,3) = " + power(4,3)); + Console.println("power(4,4) = " + power(4,4)); + Console.println("power(4,5) = " + power(4,5)); + Console.println("power(4,6) = " + power(4,6)); + Console.println("power(4,7) = " + power(4,7)); + Console.println("power(4,8) = " + power(4,8)); + Console.println; + + Console.println("power(5,0) = " + power(5,0)); + Console.println("power(5,1) = " + power(5,1)); + Console.println("power(5,2) = " + power(5,2)); + Console.println("power(5,3) = " + power(5,3)); + Console.println("power(5,4) = " + power(5,4)); + Console.println("power(5,5) = " + power(5,5)); + Console.println("power(5,6) = " + power(5,6)); + Console.println("power(5,7) = " + power(5,7)); + Console.println("power(5,8) = " + power(5,8)); + Console.println; +} + +//############################################################################ + +object Test { + def main(args: Array[String]): Unit = { + M0; + M1; + M2; + M3; + M4; + M5; + M6; + M7; + M8; + M9; + MA; + MB; + MC; + MD; + ME; + MF; + MG; + MH; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/Course-2002-03.scala b/test-nsc/files/run/Course-2002-03.scala new file mode 100644 index 0000000000..7933514f9a --- /dev/null +++ b/test-nsc/files/run/Course-2002-03.scala @@ -0,0 +1,392 @@ +//############################################################################ +// Programmation IV - 2002 - Week 03 +//############################################################################ +// $Id$ + +object M0 { + class Rational(x: Int, y: Int) { + def numer = x; + def denom = y; + } + + def addRational(r: Rational, s: Rational): Rational = + new Rational( + r.numer * s.denom + s.numer * r.denom, + r.denom * s.denom); + + def makeString(r: Rational) = + r.numer + "/" + r.denom; + + val x = new Rational(1, 2); + val y = new Rational(1, 3); + Console.println(x.numer); + Console.println(x.denom); + Console.println(makeString(x)); + Console.println(makeString(addRational(x,y))); + Console.println; +} + +//############################################################################ + +object M1 { + class Rational(x: Int, y: Int) { + def numer = x; + def denom = y; + def add(r: Rational) = + new Rational( + numer * r.denom + r.numer * denom, + denom * r.denom); + def mul(r: Rational) = + new Rational( + numer * r.numer, + denom * r.denom); + override def toString() = numer + "/" + denom; + } + + val x = new Rational(1, 3); + val y = new Rational(5, 7); + val z = new Rational(3, 2); + Console.println(x); + Console.println(y); + Console.println(z); + Console.println(x.add(y).mul(z)); + Console.println; +} + +//############################################################################ + +object M2 { + class Rational(x: Int, y: Int) { + private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b); + private val g = gcd(x, y); + def numer = x / g; + def denom = y / g; + def add(r: Rational) = + new Rational( + numer * r.denom + r.numer * denom, + denom * r.denom); + def sub(r: Rational) = + new Rational( + numer * r.denom - r.numer * denom, + denom * r.denom); + def mul(r: Rational) = + new Rational( + numer * r.numer, + denom * r.denom); + def div(r: Rational) = + new Rational( + numer * r.denom, + denom * r.numer); + override def toString() = numer + "/" + denom; + } + + val x = new Rational(1, 3); + val y = new Rational(5, 7); + val z = new Rational(3, 2); + Console.println(x); + Console.println(y); + Console.println(z); + Console.println(x.add(y).mul(z)); + Console.println; +} + +//############################################################################ + +object M3 { + class Rational(x: Int, y: Int) { + private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b); + def numer = x / gcd(x, y); + def denom = y / gcd(x, y); + def less(that: Rational) = + this.numer * that.denom < that.numer * this.denom; + def max(that: Rational) = if (this.less(that)) that else this; + override def toString() = numer + "/" + denom; + } + + val x = new Rational(66, 42); + val y = new Rational(42, 66); + Console.println(x); + Console.println(y); + Console.println(x.max(y)); + Console.println(y.max(x)); + Console.println; +} + +//############################################################################ + +object M4 { + class Rational(x: Int, y: Int) { + private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b); + private val g = gcd(x, y); + def numer = x / g; + def denom = y / g; + def + (r: Rational) = + new Rational( + numer * r.denom + r.numer * denom, + denom * r.denom); + def - (r: Rational) = + new Rational( + numer * r.denom - r.numer * denom, + denom * r.denom); + def * (r: Rational) = + new Rational( + numer * r.numer, + denom * r.denom); + def / (r: Rational) = + new Rational( + numer * r.denom, + denom * r.numer); + override def toString() = numer + "/" + denom; + } + + val x = new Rational(1, 2); + val y = new Rational(1, 3); + Console.println(x * x + y * y); + Console.println; +} + +//############################################################################ + +object M5 { + trait IntSet { + def incl(x: Int): IntSet; + def contains(x: Int): Boolean; + } + + class Empty extends IntSet { + def contains(x: Int): Boolean = false; + def incl(x: Int): IntSet = new NonEmpty(x, new Empty, new Empty); + } + + class NonEmpty(elem: Int, left: IntSet, right: IntSet) extends IntSet { + def contains(x: Int): Boolean = + if (x < elem) left contains x + else if (x > elem) right contains x + else true; + def incl(x: Int): IntSet = + if (x < elem) new NonEmpty(elem, left incl x, right) + else if (x > elem) new NonEmpty(elem, left, right incl x) + else this; + } + + val x = new Empty incl 1 incl 2; + Console.println(x contains 0); + Console.println(x contains 1); + Console.println(x contains 2); + Console.println(x contains 3); + Console.println; +} + +//############################################################################ + +object M6 { + trait Boolean { + def ifThenElse[a](t: => a)(e: => a): a; + + def ! : Boolean = ifThenElse[Boolean](new False())(new True()); + + def && (x: => Boolean): Boolean = ifThenElse[Boolean](x)(new False()); + def || (x: => Boolean): Boolean = ifThenElse[Boolean](new True())(x); + + // !!! def == (x: Boolean): Boolean = ifThenElse[Boolean](x)(x.!); + // !!! def != (x: Boolean): Boolean = ifThenElse[Boolean](x.!)(x); + def < (x: Boolean): Boolean = ifThenElse[Boolean](new False())(x); + def > (x: Boolean): Boolean = ifThenElse[Boolean](x.!)(new False()); + def <= (x: Boolean): Boolean = ifThenElse[Boolean](x)(new True()); + def >= (x: Boolean): Boolean = ifThenElse[Boolean](new True())(x.!); + } + class True() extends Boolean { // !!! class -> object + def ifThenElse[a](t: => a)(e: => a): a = t } + class False() extends Boolean { // !!! class -> object + def ifThenElse[a](t: => a)(e: => a): a = e } +} + +//############################################################################ + +object M7 { + trait Nat { + def isZero(): Boolean; + def predecessor: Nat; + def successor: Nat; + def + (that: Nat): Nat; + def - (that: Nat): Nat; + } +} + +//############################################################################ + +object M8 { + + trait IntSet { + def incl(x: Int): IntSet; + def contains(x: Int): Boolean; + def map(f: Int => Int): IntSet; + + def foreach(f: Int => Unit): Unit; + def intersect0(that: IntSet, accu: IntSet): IntSet; + def filter0(f: Int => Boolean, accu: IntSet): IntSet; + + def intersect(that: IntSet): IntSet = intersect0(that, new Empty); + def intersect2(that: IntSet): IntSet = filter(x => that.contains(x)); + def filter(f: Int => Boolean): IntSet = filter0(f, new Empty); + + def printOn(out: java.io.PrintStream) = foreach(out.println); + + override def toString(): String = { + val buffer: java.lang.StringBuffer = new java.lang.StringBuffer(); + buffer.append('['); + foreach(i => { + if (buffer.length() > 1) {buffer.append(','); ()}; // !!! ; () + buffer.append(i); + ()}); + buffer.append(']'); + buffer.toString(); + } + } + + class Empty extends IntSet { // !!! class Empty() -> object Empty + def contains(x: Int): Boolean = false; + def incl(x: Int): IntSet = new NonEmpty(x, new Empty, new Empty); + def map(f: Int => Int): IntSet = this; + + def foreach(f: Int => Unit): Unit = (); + def intersect0(that: IntSet, accu: IntSet): IntSet = accu; + def filter0(f: Int => Boolean, accu: IntSet): IntSet = accu; + } + + class NonEmpty(elem: Int, left: IntSet, right: IntSet) extends IntSet { + def contains(x: Int): Boolean = + if (x < elem) left contains x + else if (x > elem) right contains x + else true; + + def incl(x: Int): IntSet = + if (x < elem) new NonEmpty(elem, left incl x, right) + else if (x > elem) new NonEmpty(elem, left, right incl x) + else this; + + + def map(f: Int => Int): IntSet = { + val lset = left.map(f); + val rset = right.map(f); + new NonEmpty(f(elem), lset, rset) + } + + def foreach(f: Int => Unit): Unit = { + left.foreach(f); + f(elem); + right.foreach(f); + } + + def intersect0(that: IntSet, accu: IntSet): IntSet = + right.intersect0(that, left.intersect0(that, + if (that.contains(elem)) accu.incl(elem) else accu)); + + def filter0(f: Int => Boolean, accu: IntSet): IntSet = + right.filter0(f, left.filter0(f, + if (f(elem)) accu.incl(elem) else accu)); + } + + def test = { + val set0: IntSet = new Empty; + val set1: IntSet = new Empty incl 1; + val set2: IntSet = new Empty incl 1 incl 2; + val set3: IntSet = new Empty incl 1 incl 2 incl 3; + val set4: IntSet = new Empty incl 1 incl 2 incl 3 incl 4; + val setx: IntSet = set0 incl -10 incl 5 incl 21 incl -1 incl 0 incl 3; + val sety: IntSet = set0 incl 3 incl 7 incl -5 incl 0 incl-9 incl 8 incl-1; + + Console.println("set0 = " + set0); + Console.println("set1 = " + (set1.toString())); + Console.println("set2 = " + set2); + Console.println("set3 = " + (set3.toString())); + Console.println("set4 = " + set4); + Console.println; + + Console.println("set2 contains the following elements:"); + set2.foreach(Console.println); + Console.println; + + Console.println("set3 contains the following elements:"); + set3 foreach Console.println; + Console.println; + + Console.println("set4 contains the following elements:"); + set4.printOn(java.lang.System.out); + Console.println; + + Console.println("2 <- set2: " + (set2 contains 2)); + Console.println("3 <- set2: " + set2.contains(3)); + Console.println; + + Console.println("setx = " + setx); + Console.println("setx * 2 = " + (setx.map(x => 2 * x))); + Console.println; + + Console.println("setx = " + setx); + Console.println("sety = " + sety); + Console.println("setx & sety = " + (setx.intersect(sety))); + Console.println("sety & setx = " + (sety.intersect(setx))); + Console.println("setx > 0 = " + (setx.filter(x => x > 0))); + Console.println("sety > 0 = " + (sety.filter(x => x > 0))); + Console.println("setx & sety = " + (setx.intersect2(sety))); + Console.println("sety & setx = " + (sety.intersect2(setx))); + Console.println; + } +} + +//############################################################################ + +object M9 { + class Rational(x: Int, y: Int) { + private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b); + private val g = gcd(x, y); + def numer = x / g; + def denom = y / g; + def add(r: Rational) = + new Rational( + numer * r.denom + r.numer * denom, + denom * r.denom); + def sub(r: Rational) = + new Rational( + numer * r.denom - r.numer * denom, + denom * r.denom); + def mul(r: Rational) = + new Rational( + numer * r.numer, + denom * r.denom); + def equal(r: Rational) = + new Rational( + numer * r.denom, + denom * r.numer); + def asString = numer.toString().concat("/").concat(denom.toString()); + override def toString() = asString; + } + + def test = { + Console.println(new Rational(2,2).asString); + Console.println(new Rational(2,2).toString()); + Console.println(new Rational(2,2)); + Console.println; + } +} + +//############################################################################ + +object Test { + def main(args: Array[String]): Unit = { + M0; + M1; + M2; + M3; + M4; + M5; + M6; + M7; + M8.test; + M9.test; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/Course-2002-04.scala b/test-nsc/files/run/Course-2002-04.scala new file mode 100755 index 0000000000..31aaa44c23 --- /dev/null +++ b/test-nsc/files/run/Course-2002-04.scala @@ -0,0 +1,245 @@ +//############################################################################ +// Programmation IV - 2002 - Week 04 +//############################################################################ +// $Id$ + +object M0 { + + def quicksort[a] (less : (a,a) => Boolean) (xs : List[a]) : List[a] = { + if (xs.isEmpty) + xs + else { + val pivot : a = xs.head; + val smaller : List[a] = + quicksort(less)(xs.tail.filter(elem => less(elem, pivot))); + val greaterOrEqual : List[a] = + quicksort(less)(xs.tail.filter(elem => !less(elem, pivot))); + smaller ::: List(pivot) ::: greaterOrEqual + } + } + + def test = { + val isort = quicksort[Int]((x,y) => x < y); + val list0 = List(6,3,1,8,7,1,2,5,8,4,3,4,8); + val list1 = quicksort[Int]((x,y) => x < y)(list0); + val list2 = quicksort[Int]((x,y) => x < y)(list1); + val list3 = isort(list0); + val list4 = isort(list1); + val list5 = quicksort[Int]((x,y) => x >= y)(list0); + val list6 = quicksort[Int]((x,y) => x >= y)(list1); + + Console.println("list0 = " + list0); + Console.println("list1 = " + list1); + Console.println("list2 = " + list2); + Console.println("list3 = " + list3); + Console.println("list4 = " + list4); + Console.println("list5 = " + list5); + Console.println("list6 = " + list6); + Console.println; + } +} + +//############################################################################ + +object M1 { + + def mergesort[a] (less : (a,a) => Boolean) (xs: Array[a]): Unit = { + + def While(c: => Boolean)(b: => Unit): Unit = + if (c) { b ; While(c)(b) } else (); + + def swap(i: Int, j: Int): Unit = { + val t = xs(i); + val u = xs(j); + xs(i) = u; + xs(j) = t; + } + + def sort1(l: Int, r: Int): Unit = { + val pivot = xs((l + r) / 2); + var i = l; + var j = r; + While (i <= j) { + While (less(xs(i), pivot)) { i = i + 1 } + While (less(pivot, xs(j))) { j = j - 1 } + if (i <= j) { + swap(i, j); + i = i + 1; + j = j - 1; + } + } + if (l < j) sort1(l, j); + if (j < r) sort1(i, r); + } + + if (xs.length > 0) sort1(0, xs.length - 1); + } + + def list2array(list: List[Int]): Array[Int] = { + val array = new Array[Int](list.length); + list.copyToArray(array, 0); + array; + } + + def array2list(array: Array[Int]): List[Int] = { + var list = List[Int](); + List.range(0, array.length).map(i => list = array(i) :: list); + list.reverse; + } + + def isort(list: List[Int]): List[Int] = { + val array = list2array(list); + mergesort[Int]((x,y) => x < y)(array); + array2list(array); + } + + def test = { + val list0 = List(); + val list1 = List(0); + val list2 = List(0,1); + val list3 = List(1,0); + val list4 = List(0,1,2); + val list5 = List(1,0,2); + val list6 = List(0,1,2); + val list7 = List(1,0,2); + val list8 = List(2,0,1); + val list9 = List(2,1,0); + val listA = List(6,3,1,8,7,1,2,5,8,4); + + Console.println("list0: " + list0 + " -> " + isort(list0)); + Console.println("list1: " + list1 + " -> " + isort(list1)); + Console.println("list2: " + list2 + " -> " + isort(list2)); + Console.println("list3: " + list3 + " -> " + isort(list3)); + Console.println("list4: " + list4 + " -> " + isort(list4)); + Console.println("list5: " + list5 + " -> " + isort(list5)); + Console.println("list6: " + list6 + " -> " + isort(list6)); + Console.println("list7: " + list7 + " -> " + isort(list7)); + Console.println("list8: " + list8 + " -> " + isort(list8)); + Console.println("list9: " + list9 + " -> " + isort(list9)); + Console.println("listA: " + listA + " -> " + isort(listA)); + Console.println; + } + +} + +//############################################################################ + +object M2 { + + def horner (x : Double, coefs : List[Double]) : Double = { + if (coefs.isEmpty) + 0 + else + horner(x, coefs.tail) * x + coefs.head + } + + def test = { + val poly = List(9.0,5.0,7.0,5.0); + Console.println("f(x) = 5x^3+7x^2+5x+9"); + Console.println("f(0) = " + horner(0, poly)); + Console.println("f(1) = " + horner(1, poly)); + Console.println("f(2) = " + horner(2, poly)); + Console.println("f(3) = " + horner(3, poly)); + Console.println; + } +} + +//############################################################################ + +object M3 { + + def dotproduct (v : List[Double], w : List[Double]) : Double = { + if (v.isEmpty) + 0 + else + (v.head * w.head) + dotproduct(v.tail, w.tail) + } + + def matrixTimesVector (m : List[List[Double]], v : List[Double]) + : List[Double] = { + m.map(row => dotproduct(row, v)) + } + + def transpose(m : List[List[Double]]) : List[List[Double]] = { + if (m.isEmpty || m.head.isEmpty) + List() + else + m.map(row => row.head) :: transpose (m.map (row => row.tail)) + } + + def matrixTimesMatrix(m1 : List[List[Double]], m2 : List[List[Double]]) + : List[List[Double]] = { + val columns = transpose(m2); + m1.map(row => matrixTimesVector(columns, row)) + } + + def test = { + val v1 = List(2.0,3.0,4.0); + val v2 = List(6.0,7.0,8.0); + def id = List(List(1.0,0.0,0.0),List(0.0,1.0,0.0),List(0.0,0.0,1.0)); + def m1 = List(List(2.0,0.0,0.0),List(0.0,2.0,0.0),List(0.0,0.0,2.0)); + def m2 = List(List(1.0,2.0,3.0),List(4.0,5.0,6.0),List(7.0,8.0,9.0)); + + def v = List(2.0,3.0,4.0); + + Console.println("v1 = " + v1); + Console.println("v2 = " + v2); + Console.println; + + Console.println("id = " + id); + Console.println("m1 = " + m1); + Console.println("m2 = " + m2); + Console.println; + + Console.println("v1 * v1 = " + dotproduct(v1,v1)); + Console.println("v1 * v2 = " + dotproduct(v1,v2)); + Console.println("v2 * v1 = " + dotproduct(v2,v1)); + Console.println("v1 * v2 = " + dotproduct(v1,v2)); + Console.println; + + Console.println("id * v1 = " + matrixTimesVector(id,v1)); + Console.println("m1 * v1 = " + matrixTimesVector(m1,v1)); + Console.println("m2 * v1 = " + matrixTimesVector(m2,v1)); + Console.println; + + Console.println("trn(id) = " + transpose(id)); + Console.println("trn(m1) = " + transpose(m1)); + Console.println("trn(m2) = " + transpose(m2)); + Console.println; + + Console.println("List(v1) * id = " + matrixTimesMatrix(List(v1),id)); + Console.println("List(v1) * m1 = " + matrixTimesMatrix(List(v1),m1)); + Console.println("List(v1) * m2 = " + matrixTimesMatrix(List(v1),m2)); + Console.println; + + Console.println("id * List(v1) = " + matrixTimesMatrix(id,List(v1))); + Console.println("m1 * List(v1) = " + matrixTimesMatrix(m1,List(v1))); + Console.println("m2 * List(v1) = " + matrixTimesMatrix(m2,List(v1))); + Console.println; + + Console.println("id * id = " + matrixTimesMatrix(id,id)); + Console.println("id * m1 = " + matrixTimesMatrix(id,m1)); + Console.println("m1 * id = " + matrixTimesMatrix(m1,id)); + Console.println("m1 * m1 = " + matrixTimesMatrix(m1,m1)); + Console.println("id * m2 = " + matrixTimesMatrix(id,m2)); + Console.println("m2 * id = " + matrixTimesMatrix(m2,id)); + Console.println("m1 * m2 = " + matrixTimesMatrix(m1,m2)); + Console.println("m2 * m1 = " + matrixTimesMatrix(m2,m1)); + Console.println("m2 * m2 = " + matrixTimesMatrix(m2,m2)); + Console.println; + } +} + +//############################################################################ + +object Test { + def main(args: Array[String]): Unit = { + M0.test; + M1.test; + M2.test; + M3.test; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/Course-2002-05.scala b/test-nsc/files/run/Course-2002-05.scala new file mode 100755 index 0000000000..6f40f7f99e --- /dev/null +++ b/test-nsc/files/run/Course-2002-05.scala @@ -0,0 +1,215 @@ +//############################################################################ +// Programmation IV - 2002 - Week 05 +//############################################################################ +// $Id$ + +object M0 { + def partition[a](xs: List[a], pred: a => boolean): Pair[List[a], List[a]] = { + if (xs.isEmpty) + Pair(List(),List()) + else { + val tailPartition = partition(xs.tail, pred); + if (pred(xs.head)) + Pair(xs.head :: tailPartition._1, tailPartition._2) + else + Pair(tailPartition._1, xs.head :: tailPartition._2) + } + } + + def quicksort[a] (less : (a,a) => boolean) (xs : List[a]) : List[a] = { + if (xs.isEmpty) + xs + else { + val pivot = xs.head; + val sub = partition(xs.tail, (elem : a => less(elem, pivot))); + quicksort(less)(sub._1) ::: List(pivot) ::: quicksort(less)(sub._2) + } + } + + def test = { + Console.println(partition[int](List(1,2,3,4,5,6,7,8), (x => x < 0))); + Console.println(partition[int](List(1,2,3,4,5,6,7,8), (x => x < 5))); + Console.println(partition[int](List(1,2,3,4,5,6,7,8), (x => x < 9))); + Console.println; + + Console.println(partition[int](List(8,7,6,5,4,3,2,1), (x => x < 0))); + Console.println(partition[int](List(8,7,6,5,4,3,2,1), (x => x < 5))); + Console.println(partition[int](List(8,7,6,5,4,3,2,1), (x => x < 9))); + Console.println; + + Console.println(partition[int](List(7,2,1,5,4,3,8,6), (x => x < 0))); + Console.println(partition[int](List(7,2,1,5,4,3,8,6), (x => x < 5))); + Console.println(partition[int](List(7,2,1,5,4,3,8,6), (x => x < 9))); + Console.println; + + Console.println(quicksort[int]((x,y) => x < y)(List(7,2,1,5,4,3,8,6))); + Console.println; + } +} + +//############################################################################ + +object M1 { + def partition[a](xs: List[a], pred: a => boolean): Pair[List[a], List[a]] = { + xs.foldRight[Pair[List[a], List[a]]](Pair(List(), List())) { + (x, p) => if (pred (x)) Pair(x :: p._1, p._2) else Pair(p._1, x :: p._2) + } + } + + def quicksort[a] (less : (a,a) => boolean) (xs : List[a]) : List[a] = { + if (xs.isEmpty) + xs + else { + val pivot = xs.head; + val sub = partition(xs.tail, (elem : a => less(elem, pivot))); + quicksort(less)(sub._1) ::: List(pivot) ::: quicksort(less)(sub._2) + } + } + + def test = { + Console.println(partition[int](List(1,2,3,4,5,6,7,8), (x => x < 0))); + Console.println(partition[int](List(1,2,3,4,5,6,7,8), (x => x < 5))); + Console.println(partition[int](List(1,2,3,4,5,6,7,8), (x => x < 9))); + Console.println; + + Console.println(partition[int](List(8,7,6,5,4,3,2,1), (x => x < 0))); + Console.println(partition[int](List(8,7,6,5,4,3,2,1), (x => x < 5))); + Console.println(partition[int](List(8,7,6,5,4,3,2,1), (x => x < 9))); + Console.println; + + Console.println(partition[int](List(7,2,1,5,4,3,8,6), (x => x < 0))); + Console.println(partition[int](List(7,2,1,5,4,3,8,6), (x => x < 5))); + Console.println(partition[int](List(7,2,1,5,4,3,8,6), (x => x < 9))); + Console.println; + + Console.println(quicksort[int]((x,y) => x < y)(List(7,2,1,5,4,3,8,6))); + Console.println; + } +} + +//############################################################################ + +object M2 { + + def powerset[a] (s : List[a]) : List[List[a]] = { + if (s.isEmpty) + List(List()) + else { + val x = s.head; + val withoutX = powerset(s.tail); + withoutX ::: withoutX.map(s1 : List[a] => x::s1) + } + } + + def test = { + Console.println(powerset(List())); + Console.println(powerset(List(1))); + Console.println(powerset(List(1,2))); + Console.println(powerset(List(1,2,3))); + Console.println(powerset(List(1,2,3,4))); + Console.println; + } +} + +//############################################################################ + +object M3 { + + def abs(x: int) = if (x < 0) 0 - x else x; + + def range(lo: Int, hi: Int): List[Int] = + if (lo > hi) List() + else lo :: range(lo + 1, hi); + + type Placement = List[Pair[int,int]]; + + def queens(n: int): List[Placement] = { + def placeQueens(row: int): List[Placement] = { + if (row == 0) + List(List()) + else { + def isSafe(column: int, placement: Placement): boolean = + placement forall { + pos => pos._2 != column + && abs(pos._2 - column) != row - pos._1 + } + + def adjoinRow(placement: Placement): List[Placement] = + range(1, n) + filter (column => isSafe(column, placement)) + map (column => Pair(row, column) :: placement); + + placeQueens(row - 1) flatMap adjoinRow + } + } + placeQueens(n) + } + + def test = { + Console.println("queens(1) = " + queens(1)); + Console.println("queens(2) = " + queens(2)); + Console.println("queens(3) = " + queens(3)); + Console.println("queens(4) = " + queens(4)); + Console.println; + } +} + +//############################################################################ + +object M4 { + + def abs(x: int) = if (x < 0) 0 - x else x; + + def range(lo: Int, hi: Int): List[Int] = + if (lo > hi) List() + else lo :: range(lo + 1, hi); + + type Placement = List[Int]; + + def queens(n: Int): List[Placement] = { + val columns = range(1, n); + def placeQueens(row: Int): List[Placement] = { + if (row == 0) + List(List()) + else { + def isSafe(col: Int, p: Placement, delta: Int): Boolean = + p.isEmpty || + (col != p.head && + abs(col - p.head) != delta && + isSafe(col, p.tail, delta + 1)); + + for ( + val placement <- placeQueens(row - 1); + val col <- columns; + isSafe(col, placement, 1) + ) yield { + col :: placement + } + } + } + placeQueens(n); + } + + def test = { + Console.println("queens(1) = " + queens(1)); + Console.println("queens(2) = " + queens(2)); + Console.println("queens(3) = " + queens(3)); + Console.println("queens(4) = " + queens(4)); + Console.println; + } +} + +//############################################################################ + +object Test { + def main(args: Array[String]): unit = { + M0.test; + M1.test; + M2.test; + M3.test; + M4.test; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/Course-2002-06.scala b/test-nsc/files/run/Course-2002-06.scala new file mode 100644 index 0000000000..8ce003333f --- /dev/null +++ b/test-nsc/files/run/Course-2002-06.scala @@ -0,0 +1,263 @@ +//############################################################################ +// Programmation IV - 2002 - Week 06 +//############################################################################ +// $Id$ + +/** Two-dimensional vector. */ +class Vector (_x: Double, _y: Double) { + def x: Double = _x; + def y: Double = _y; + def +(that: Vector): Vector = new Vector(x + that.x, y + that.y); + def *(scalar: Double): Vector = new Vector(x * scalar, y * scalar); + def -(that: Vector): Vector = new Vector(x - that.x, y - that.y); + def /(scalar: Double): Vector = new Vector(x / scalar, y / scalar); + def norm: Double = scala.runtime.compat.Math.sqrt(x * x + y * y); +} + +//############################################################################ + +/** Frame. */ +class Frame (_origin: Vector, _edgeX: Vector, _edgeY: Vector) { + def origin: Vector = _origin; + def edgeX: Vector = _edgeX; + def edgeY: Vector = _edgeY; + /** The vector v in the absolute (drawing) coordinate system */ + def coordMap(v: Vector): Vector = origin + (edgeX * v.x) + (edgeY * v.y); +} + +//############################################################################ + +/** Space on which we can draw lines. */ +abstract class Graphics(_width: Double, _height: Double) { + /** Width of the picture.*/ + def width: Double = _width; + + /** Height of the picture.*/ + def height: Double = _height; + + /** Frame that represents the drawable area of the output device*/ + val frame: Frame; + + /** Draw a line in device coordinates*/ + def plotLine(x1: Double, y1: Double, x2: Double, y2: Double): Unit; + + /** Draw a line in logical coordinates*/ + def drawLine(v1: Vector, v2: Vector): Unit = { + val _v1 = frame.coordMap(v1); + val _v2 = frame.coordMap(v2); + plotLine(_v1.x, _v1.y, _v2.x, _v2.y); + } + + /** Draw a segment of the picture.*/ + def drawSegment(frm: Frame)(v1: Vector, v2: Vector): Unit = { + val _v1 = frm.coordMap(v1); + val _v2 = frm.coordMap(v2); + drawLine(_v1, _v2); + } + + /** Draw a list of segments on the picture.*/ + def drawSegments(frm: Frame)(segments: List[Pair[Vector, Vector]]): Unit = + if (segments.isEmpty) () + else { + drawSegment(frm)(segments.head._1, segments.head._2); + drawSegments(frm)(segments.tail) + } + + /** Draw a list of continuous segments on the picture.*/ + def drawPolySegment(frm: Frame)(points: List[Vector]) : Unit = + if (!points.tail.isEmpty) { + drawSegment(frm)(points.head, points.tail.head); + drawPolySegment(frm)(points.tail); + } + + /** updates the contents of the output device*/ + def repaint = (); + + /** Add the last touch to the picture.*/ + def close : Unit; +} + +//############################################################################ + +/** Provides PostScript output. The name of the file is the first parameter + * of the constructor. The width and height determine the aspect ratio + */ +class PostScript (filename: String, _width: Double, _height: Double) + extends Graphics(_width, _height) { + /** Convert mm into 72th of inch.*/ + def mm2ps(x: Double) : Double = round(x * 72.0 / 25.4); + + def round(x: Double): Double = + scala.runtime.compat.Math.floor(x * 100.0 + 0.5) / 100.0; + + def scaleAndCenter(frm: Frame, ratio:Double): Frame = { + val currentRatio = frm.edgeX.norm / frm.edgeY.norm; + if (currentRatio < ratio) { + val newEdgeX = frm.edgeX; + val newEdgeY = frm.edgeY * (currentRatio /ratio); + val newOrigin = frm.origin + ((frm.edgeY - newEdgeY) / 2); + new Frame(newOrigin, newEdgeX, newEdgeY) + } + else { + val newEdgeX = frm.edgeX * (ratio / currentRatio); + val newEdgeY = frm.edgeY; + val newOrigin = frm.origin + ((frm.edgeX - newEdgeX) / 2); + new Frame(newOrigin, newEdgeX, newEdgeY) + } + } + + /** Line thickness in millimeters.*/ + val line_thickness : Double = 0.05; + + /** Width, height, left and right margins in mm.*/ + val psWidth: Double = 210.0; + val psHeight: Double = 297.0; + val psWidthMargin: Double = 15.0; + val psHeightMargin: Double = 15.0; + + val frame: Frame = { + val origin = new Vector(mm2ps(psWidthMargin), mm2ps(psHeightMargin)); + val edgeX = new Vector(mm2ps(psWidth) - 2 * mm2ps(psWidthMargin), 0); + val edgeY = new Vector(0, mm2ps(psHeight) - 2 * mm2ps(psHeightMargin)); + scaleAndCenter(new Frame(origin, edgeX, edgeY), width / height) + } + + def plotLine(x1: Double, y1: Double, x2: Double, y2: Double): Unit = { + Console.println(round(x1) + " " + round(y1) + " m " + + round(x2) + " " + round(y2) + " l"); + } + + /** Print the PS header.*/ + Console.println("%!PS-Adobe-3.0 EPSF-3.0\n%%Title: ProgrammationIV"); + Console.println("%%Creator: LAMP"); + Console.println("%%BoundingBox: 0 0 " + mm2ps(psWidth) + " " + mm2ps(psHeight)); + Console.println("%%EndComments\n"); + Console.println("/m {moveto} bind def\n/l {lineto} bind def\n"); + Console.println(mm2ps(line_thickness) + " setlinewidth\nnewpath"); + + /** Terminate the PS document and close the file stream. */ + def close : Unit = { + Console.println("stroke\nshowpage\n%%EOF"); + Console.flush; + } +} + +//############################################################################ + +object M0 { + + /** Define the type of a painter as a function that takes a frame, + * draws itself onto it and returns nothing + */ + type Painter = (Frame) => Unit; + + + /** Transform the frame in which the painter is to be drawn, hence + * changing the appearance of the painter + */ + def transformPainter(origin: Vector, newX: Vector, newY: Vector) + (painter: Painter): Painter = { + frame: Frame => { + val newOrigin = frame.coordMap(origin); + val newFrame = new Frame(newOrigin, + frame.coordMap(newX) - newOrigin, + frame.coordMap(newY) - newOrigin); + painter(newFrame) + } + } + + + /** Flip the painter vertically + */ + def flipVert = + transformPainter(new Vector(0.0, 1.0), + new Vector(1.0, 1.0), + new Vector(0.0, 0.0)); + + /** Flip the painter horizontally + */ + def flipHoriz = + transformPainter(new Vector(1.0, 0.0), + new Vector(0.0, 0.0), + new Vector(1.0, 1.0)); + + /** Compose a painter that draws p1 on the left of p2 + */ + def beside(p1: Painter, p2: Painter) : Painter = { + frame: Frame => { + transformPainter(new Vector(0.0, 0.0), + new Vector(0.5, 0.0), + new Vector(0.0, 1.0))(p1)(frame); + transformPainter(new Vector(0.5, 0.0), + new Vector(1.0, 0.0), + new Vector(0.5, 1.0))(p2)(frame) + } + } + + /** Compose a painter that draws p1 below p2 + */ + def below(p1: Painter, p2: Painter): Painter = { + frame: Frame => { + transformPainter(new Vector(0.0, 0.0), + new Vector(1.0, 0.0), + new Vector(0.0, 0.5))(p1)(frame); + transformPainter(new Vector(0.0, 0.5), + new Vector(1.0, 0.5), + new Vector(0.0, 1.0))(p2)(frame) + } + } + + def rightSplit(painter: Painter, n: Int): Painter = { + if (n == 0) painter + else { + val smaller = rightSplit(painter, n-1); + beside(painter, below(smaller, smaller)) + } + } + + // A small test painter. + def house(canvas: Graphics)(frame: Frame): Unit = { + canvas.drawPolySegment(frame)(List(new Vector(0.0, 0.0), + new Vector(1.0, 0.0), + new Vector(1.0, 2.0/3.0), + new Vector(0.0, 2.0/3.0), + new Vector(0.5, 1.0), + new Vector(1.0, 2.0/3.0), + new Vector(0.0, 0.0), + new Vector(0.0, 2.0/3.0), + new Vector(1.0, 0.0))); + canvas.repaint + } + + def test = { + val psfile = "-"; + val canvas: Graphics = new PostScript(psfile, 2, 2); + + // the identity frame + val identFrame = new Frame(new Vector(0.0,0.0), + new Vector(1.0,0.0), + new Vector(0.0,1.0)); + + // Create a basic painter... + val p: Painter = house(canvas); + // ...then compose it with itself. + val threeHouses = beside(p, beside(p, flipVert(p))); + + // Use the painter to draw the final image. + threeHouses(identFrame); + + // Don't forget to close the canvas! + canvas.close + } +} + +//############################################################################ + +object Test { + def main(args: Array[String]): Unit = { + M0.test; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/Course-2002-07.scala b/test-nsc/files/run/Course-2002-07.scala new file mode 100755 index 0000000000..5ebb1ad7ab --- /dev/null +++ b/test-nsc/files/run/Course-2002-07.scala @@ -0,0 +1,726 @@ +//############################################################################ +// Programmation IV - 2002 - Week 07 +//############################################################################ +// $Id$ + +import java.lang.System; // to avoid name clash with .NET's library + +object M0 { + + trait Expr { + def isNumber: boolean; + def isSum: boolean; + def numValue: int; + def leftOp: Expr; + def rightOp: Expr; + } + + class Number(n: int) extends Expr { + def isNumber: boolean = true; + def isSum: boolean = false; + def numValue: int = n; + def leftOp: Expr = error("Number.leftOp"); + def rightOp: Expr = error("Number.rightOp"); + } + class Sum(e1: Expr, e2: Expr) extends Expr { + def isNumber: boolean = false; + def isSum: boolean = true; + def numValue: int = error("Sum.numValue"); + def leftOp: Expr = e1; + def rightOp: Expr = e2; + } + + class Prod(e1: Expr, e2: Expr) extends Expr { + def isNumber: boolean = false; + def isSum: boolean = false; + def numValue: int = error("Prod.numValue"); + def leftOp: Expr = e1; + def rightOp: Expr = e2; + } + + class Var(x: String) extends Expr { + def isNumber: boolean = false; + def isSum: boolean = false; + def numValue: int = error("Var.numValue"); + def leftOp: Expr = error("Var.leftOp"); + def rightOp: Expr = error("Var.rightOp"); + } + + def eval(e: Expr): int = { + if (e.isNumber) e.numValue + else if (e.isSum) eval(e.leftOp) + eval(e.rightOp) + else error("unknown expression") + } + + def test = { + System.out.println(" 0 = " + eval(new Number(0))); + System.out.println(" 1 = " + eval(new Number(1))); + System.out.println(" 0 + 1 = " + + eval(new Sum(new Number(0),new Number(1)))); + System.out.println(" 1 + 2 = " + + eval(new Sum(new Number(1),new Number(2)))); + System.out.println("2 + 3 + 4 = " + + eval(new Sum(new Sum(new Number(2),new Number(3)),new Number(4)))); + System.out.println(); + } + +} + +//############################################################################ + +object M1 { + + trait Expr { + def eval: int; + } + class Number(n: int) extends Expr { + def eval: int = n; + } + class Sum(e1: Expr, e2: Expr) extends Expr { + def eval: int = e1.eval + e2.eval; + } + + def test = { + System.out.println(" 0 = " + new Number(0).eval); + System.out.println(" 1 = " + new Number(1).eval); + System.out.println(" 0 + 1 = " + + new Sum(new Number(0),new Number(1)).eval); + System.out.println(" 1 + 2 = " + + new Sum(new Number(1),new Number(2)).eval); + System.out.println("2 + 3 + 4 = " + + new Sum(new Sum(new Number(2),new Number(3)),new Number(4)).eval); + System.out.println(); + } +} + +//############################################################################ + +object M2 { + + trait Expr; + case class Number(n: int) extends Expr; + case class Sum(e1: Expr, e2: Expr) extends Expr; + + def eval(e: Expr): int = e match { + case Number(n) => n + case Sum(e1, e2) => eval(e1) + eval(e2) + } + + def test = { + System.out.println(" 0 = " + eval(Number(0))); + System.out.println(" 1 = " + eval(Number(1))); + System.out.println(" 0 + 1 = " + eval(Sum(Number(0),Number(1)))); + System.out.println(" 1 + 2 = " + eval(Sum(Number(1),Number(2)))); + System.out.println("2 + 3 + 4 = " + eval(Sum(Sum(Number(2),Number(3)), + Number(4)))); + System.out.println(); + } +} + +//############################################################################ + +object M3 { + + trait Expr { + def eval: int = this match { + case Number(n) => n + case Sum(e1, e2) => e1.eval + e2.eval + } + } + case class Number(n: int) extends Expr; + case class Sum(e1: Expr, e2: Expr) extends Expr; + + def test = { + System.out.println(" 0 = " + Number(0).eval); + System.out.println(" 1 = " + Number(1).eval); + System.out.println(" 0 + 1 = " + Sum(Number(0),Number(1)).eval); + System.out.println(" 1 + 2 = " + Sum(Number(1),Number(2)).eval); + System.out.println("2 + 3 + 4 = " + Sum(Sum(Number(2),Number(3)), + Number(4)).eval); + System.out.println(); + } + +} + +//############################################################################ + +object M4 { + + def concat[a](xss: List[List[a]]): List[a] = xss match { + case List() => List() + case xs :: xss1 => xs ::: concat(xss1) + } + + def test_concat[a](xss: List[List[a]]) = { + System.out.println(concat(xss).toString() + " = concat(" + xss + ")"); // !!! .toString() + } + + def test = { + test_concat(List()); + test_concat(List(List())); + test_concat(List(List(),List())); + test_concat(List(List(),List(),List())); + + test_concat(List(List(1,2,3,4,5,6))); + test_concat(List(List(1,2,3,4,5,6),List[int]())); // !!! [int] + test_concat(List(List(1,2,3),List(4,5,6))); + test_concat(List(List[int](),List(1,2,3,4,5,6))); // !!! [int] + test_concat(List(List(1,2,3,4,5,6),List[int](),List[int]())); // !!! [int] + test_concat(List(List(1,2,3,4,5),List(6),List[int]())); // !!! [int] + test_concat(List(List(1,2,3),List(4,5,6),List[int]())); // !!! [int] + test_concat(List(List(1),List(2,3,4,5,6),List[int]())); // !!! [int] + test_concat(List(List[int](),List(1,2,3,4,5,6),List[int]())); // !!! [int] + test_concat(List(List[int](),List(1,2,3,4,5),List(6))); // !!! [int] + test_concat(List(List[int](),List(1,2,3),List(4,5,6))); // !!! [int] + test_concat(List(List[int](),List(1),List(2,3,4,5,6))); // !!! [int] + test_concat(List(List[int](),List[int](),List(1,2,3,4,5,6))); // !!! [int] + test_concat(List(List(1,2),List(3,4),List(5,6))); + System.out.println(); + } + +} + +//############################################################################ + +object M5 { + + def zipFun[a,b](xs:List[a], ys:List[b]):List[Pair[a,b]] = Pair(xs,ys) match { + case Pair(List(), _) => List() + case Pair(_, List()) => List() + case Pair(x :: xs1, y :: ys1) => Pair(x, y) :: zipFun(xs1, ys1) + } + + def test_zipFun[a,b](xs: List[a], ys: List[b]) = { + System.out.println(zipFun(xs,ys).toString() + " = zipFun(" + xs + "," + ys + ")"); // !!! .toString() + } + + def test = { + test_zipFun(List(),List()); + test_zipFun(List(),List('a','b','c')); + test_zipFun(List(1,2,3),List()); + + test_zipFun(List(1),List('a')); + test_zipFun(List(1),List('a','b','c')); + test_zipFun(List(1,2,3),List('a')); + + test_zipFun(List(1,2),List('a','b')); + test_zipFun(List(1,2),List('a','b','c')); + test_zipFun(List(1,2,3),List('a','b')); + + test_zipFun(List(1,2,3),List('a','b','c')); + + System.out.println(); + } + +} + + +//############################################################################ + +object M6 { + + def zipFun[a,b](xs:List[a], ys:List[b]):List[Pair[a,b]] = Pair(xs,ys) match { + // !!! case Pair(List(), _), Pair(_, List()) => List() + case Pair(x :: xs1, y :: ys1) => Pair(x, y) :: zipFun(xs1, ys1) + } + + def test_zipFun[a,b](xs: List[a], ys: List[b]) = { + System.out.println(zipFun(xs,ys).toString() + " = zipFun(" + xs + "," + ys + ")"); // !!! .toString() + } + + def test = { + test_zipFun(List(),List()); + test_zipFun(List(),List('a','b','c')); + test_zipFun(List(1,2,3),List()); + + test_zipFun(List(1),List('a')); + test_zipFun(List(1),List('a','b','c')); + test_zipFun(List(1,2,3),List('a')); + + test_zipFun(List(1,2),List('a','b')); + test_zipFun(List(1,2),List('a','b','c')); + test_zipFun(List(1,2,3),List('a','b')); + + test_zipFun(List(1,2,3),List('a','b','c')); + + System.out.println(); + } + +} + +//############################################################################ + +object M7 { + + def heads[a](xss: List[List[a]]): List[a] = xss flatMap { + case x :: xs => List(x) + case List() => List() + } + + def test_heads[a](xss: List[List[a]]) = { + System.out.println(heads(xss).toString() + " = heads(" + xss + ")"); // !!! .toString() + } + + + def test = { + test_heads(List()); + test_heads(List(List())); + test_heads(List(List(),List())); + test_heads(List(List(),List(),List())); + + test_heads(List(List(1,2,3,4,5,6))); + test_heads(List(List(1,2,3,4,5,6),List[int]())); // !!! [int] + test_heads(List(List[int](),List(1,2,3,4,5,6))); // !!! [int] + test_heads(List(List(1,2,3,4,5,6),List[int](),List[int]())); // !!! [int] + test_heads(List(List[int](),List(1,2,3,4,5,6),List[int]())); // !!! [int] + test_heads(List(List[int](),List[int](),List(1,2,3,4,5,6))); // !!! [int] + + test_heads(List(List(1),List(2,3,4,5,6),List[int]())); // !!! [int] + test_heads(List(List[int](),List(1),List(2,3,4,5,6))); // !!! [int] + + test_heads(List(List(1,2,3),List(4,5,6))); + test_heads(List(List(1,2,3),List(4,5,6),List[int]())); // !!! [int] + test_heads(List(List[int](),List(1,2,3),List(4,5,6))); // !!! [int] + + test_heads(List(List(1,2,3,4,5),List(6),List[int]())); // !!! [int] + test_heads(List(List[int](),List(1,2,3,4,5),List(6))); // !!! [int] + + test_heads(List(List(1,2),List(3,4),List(5,6))); + + System.out.println(); + } + +} + +//############################################################################ + +object M8 { + + def heads[a](xss: List[List[a]]): List[a] = xss.flatMap { + y => y match { + case x :: xs => List(x) + case List() => List() + } + } + + def test_heads[a](xss: List[List[a]]) = { + System.out.println(heads(xss).toString() + " = heads(" + xss + ")"); // !!! .toString() + } + + + def test = { + test_heads(List()); + test_heads(List(List())); + test_heads(List(List(),List())); + test_heads(List(List(),List(),List())); + + test_heads(List(List(1,2,3,4,5,6))); + test_heads(List(List(1,2,3,4,5,6),List[int]())); // !!! [int] + test_heads(List(List[int](),List(1,2,3,4,5,6))); // !!! [int] + test_heads(List(List(1,2,3,4,5,6),List[int](),List[int]())); // !!! [int] + test_heads(List(List[int](),List(1,2,3,4,5,6),List[int]())); // !!! [int] + test_heads(List(List[int](),List[int](),List(1,2,3,4,5,6))); // !!! [int] + + test_heads(List(List(1),List(2,3,4,5,6),List[int]())); // !!! [int] + test_heads(List(List[int](),List(1),List(2,3,4,5,6))); // !!! [int] + + test_heads(List(List(1,2,3),List(4,5,6))); + test_heads(List(List(1,2,3),List(4,5,6),List[int]())); // !!! [int] + test_heads(List(List[int](),List(1,2,3),List(4,5,6))); // !!! + + test_heads(List(List(1,2,3,4,5),List(6),List[int]())); // !!! [int] + test_heads(List(List[int](),List(1,2,3,4,5),List(6))); // !!! [int] + + test_heads(List(List(1,2),List(3,4),List(5,6))); + + System.out.println(); + } + +} + +//############################################################################ + +object M9 { + + trait Expr { + def derive(v: Var): Expr = this match { + case Number(_) => Number(0) + case Var(name) => if (name == v.name) Number(1) else Number(0) + case Sum(e1, e2) => Sum(e1 derive v, e2 derive v) + case Prod(e1, e2) => Sum(Prod(e1, e2 derive v), Prod(e2, e1 derive v)) + } + } + case class Number(x: int) extends Expr { + override def toString() = "Number(" + x + ")"; // !!! remove ! + } + case class Var(name: String) extends Expr { + override def toString() = "Var(" + name + ")"; // !!! remove ! + } + case class Sum(e1: Expr, e2: Expr) extends Expr { + override def toString() = "Sum(" + e1 + ", " + e2 + ")"; // !!! remove ! + } + case class Prod(e1: Expr, e2: Expr) extends Expr { + override def toString() = "Prod(" + e1 + ", " + e2 + ")"; // !!! remove ! + } + + def test = { + val x = Var("x"); + val f0 = Prod(x, x); + val f1 = f0 derive x; + System.out.println("f (x) = " + f0); + System.out.println("f'(x) = " + f1); + System.out.println(); + } + +} + +//############################################################################ + +object MA { + + def lookup[k,v](xs: List[Pair[k,v]], k: k): v = xs match { + case List() => error("no value for " + k) + case Pair(k1,v1) :: xs1 => if (k1 == k) v1 else lookup(xs1, k) + } + + trait Expr { + def + (that: Expr) = Sum(this, that); + def * (that: Expr) = Prod(this, that); + def derive(v: Var): Expr = this match { + case Number(_) => Number(0) + case Var(name) => if (name == v.name) Number(1) else Number(0) + case Sum(e1, e2) => (e1 derive v) + (e2 derive v) + case Prod(e1, e2) => e1 * (e2 derive v) + e2 * (e1 derive v) + } + } + case class Number(x: int) extends Expr { + override def toString() = x.toString() + } + case class Var(name: String) extends Expr { + override def toString() = name; + } + case class Sum(e1: Expr, e2: Expr) extends Expr { + override def toString() = e1.toString() + " + " + e2.toString(); + } + case class Prod(e1: Expr, e2: Expr) extends Expr { + override def toString() = { + def factorToString(e: Expr) = e match { + case Sum(_, _) => "(" + e.toString() + ")" + case _ => e.toString() + } + factorToString(e1) + " * " + factorToString(e2); + } + } + + def eval(e: Expr): int = e match { + case Number(n) => n + case Var(_) => error("cannot evaluate variable") + case Sum(e1, e2) => eval(e1) + eval(e2) + case Prod(e1, e2) => eval(e1) * eval(e2) + } + + def evalvars(xs: List[Pair[String,int]]) = { + def loop(e: Expr): int = e match { + case Number(n) => n + case Var(name) => lookup(xs,name) + case Sum(e1, e2) => loop(e1) + loop(e2) + case Prod(e1, e2) => loop(e1) * loop(e2) + } + loop + } + + def test = { + val x = Var("x"); + + val f0 = x * x; + val f1 = f0 derive x; + System.out.println("f (x) = " + f0); + System.out.println("f'(x) = " + f1); + + val g0 = Number(2) * x * x + Number(3) * x; + val g1 = g0 derive x; + System.out.println("g (x) = " + g0); + System.out.println("g'(x) = " + g1); + System.out.println("g (3) = " + evalvars(List(Pair("x",3)))(g0)); + System.out.println("g'(3) = " + evalvars(List(Pair("x",3)))(g1)); + + System.out.println(); + } + +} + +//############################################################################ + +object Utils { + + private def power0(x: int, y: int): int = + if (y == 1) x else if (y % 2 == 0) power0(x*x,y/2) else x*power0(x, y-1); + + def power(x: int, y: int): int = Pair(x,y) match { + case Pair(0,0) => error("power(0,0)") + case Pair(0,_) => 0 + case Pair(1,_) => 1 + case Pair(_,0) => 1 + case Pair(_,1) => x + case Pair(_,2) => x*x + case Pair(_,_) => if (y < 0) 1/power0(x,y) else power0(x,y) + } + + def lookup(entries: List[Pair[String,int]], key: String):int = entries match{ + case List() => error("no value for " + key) + case Pair(k,v) :: _ if (k == key) => v + case _ :: rest => lookup(rest, key) + } + + def compare(xs: List[String], ys: List[String]): int = Pair(xs,ys) match{ + case Pair(List(), List()) => 0 + case Pair(List(), _ ) => -1 + case Pair(_ , List()) => +1 + case Pair(x::xs , y::ys ) => { + val diff = x.compareTo(y); + if (diff != 0) diff else compare(xs,ys) + } + } + +} + +object MB { + + import Utils._; + + + trait Expr { + + private def count: int = this match { + case Lit(n) => n + case Mul(Lit(n),_) => n + case _ => 1 + } + + private def term: Expr = this match { + case Lit(_) => Lit(1) + case Mul(Lit(_),r) => r + case _ => this + } + + private def vars: List[String] = this match { + case Var(n) => List(n) + case Mul(l,r) => l.vars ::: r.vars + case Pow(l,n) => { val vs = l.vars; List.range(0,n).flatMap(i => vs) } + case _ => List() + } + + private def +< (that: Expr): boolean = (this +<? that) < 0; + private def +<= (that: Expr): boolean = (this +<? that) <= 0; + private def +<? (that: Expr): int = Pair(this,that) match { + case Pair(Add(_,_), _ ) => 0 + case Pair(_ , Add(_,_)) => 0 + case Pair(_ , _ ) => compare(this.vars,that.vars) + } + + def + (that: Expr): Expr = if (that +<= this) Pair(this,that) match { + case Pair(_ , Lit(0) ) => this + case Pair(Lit(l) , Lit(r) ) => Lit(l + r) + case Pair(_ , Add(rl,rr)) => (this + rl) + rr + case Pair(Add(ll,lr), _ ) if (lr +<= that) => ll + (that + lr) + case Pair(_ , _ ) => { + val l = this.term; + val r = that.term; + if (l equ r) Lit(this.count + that.count) * r else Add(this, that) + } + } else that + this; + + private def *< (that: Expr): boolean = (this *<? that) < 0; + private def *<= (that: Expr): boolean = (this *<? that) <= 0; + private def *<? (that: Expr): int = Pair(this,that) match { + case Pair(Mul(_,_), _ ) => 0 + case Pair(_ , Mul(_,_)) => 0 + case Pair(Add(_,_), Add(_,_)) => 0 + case Pair(Add(_,_), _ ) => -1 + case Pair(_ , Add(_,_)) => +1 + case Pair(Lit(_) , Lit(_) ) => 0 + case Pair(Lit(_) , _ ) => -1 + case Pair(_ , Lit(_) ) => +1 + case Pair(Var(l) , Var(r) ) => l.compareTo(r) + case Pair(Var(_) , Pow(r,_)) => if (this *<= r) -1 else +1 + case Pair(Pow(l,_), Var(_) ) => if (l *< that) -1 else +1 + case Pair(Pow(l,_), Pow(r,_)) => l *<? r + } + + def * (that: Expr): Expr = if (this *<= that) Pair(this,that) match { + case Pair(Lit(0) , _ ) => this + case Pair(Lit(1) , _ ) => that + case Pair(Mul(ll,lr), r ) => ll * (lr * r) + case Pair(Add(ll,lr), r ) => ll * r + lr * r + case Pair(Lit(l) , Lit(r) ) => Lit(l * r) + case Pair(Var(_) , Var(_) ) if (this equ that) => Pow(this,2) + case Pair(Var(_) , Pow(r,n) ) if (this equ r) => Pow(this,n + 1) + case Pair(Pow(ll,lr), Pow(rl,rr)) if (ll equ rl) => Pow(ll,lr + rr) + case Pair(l , Mul(rl,rr)) if (rl *<= l) => (rl * l) * rr + case Pair(_ , _ ) => Mul(this,that) + } else that * this; + + def ^ (that: int): Expr = Pair(this,that) match { + case Pair(_ ,1) => this + case Pair(Lit(i) ,n) => Lit(power(i,n)) + case Pair(Var(_) ,n) => Pow(this,n) + case Pair(Add(_,_),n) => this * (this ^ (n - 1)) + case Pair(Mul(l,r),n) => (l ^ n) * (r ^ n) + case Pair(Pow(e,m),n) => Pow(e,m + n) + } + + def derive(v: Var): Expr = this match { + case Lit(_) => Lit(0) + case Var(name) => if (name == v.name) Lit(1) else Lit(0) + case Add(e1, e2) => (e1 derive v) + (e2 derive v) + case Mul(e1, e2) => e1 * (e2 derive v) + e2 * (e1 derive v) + case Pow(e1, i2) => Lit(i2) * (e1 derive v) * (e1 ^ (i2 - 1)) + } + + def evaluate(vars: List[Pair[String,int]]): int = this match { + case Lit(cst) => cst + case Var (name) => lookup(vars, name) + case Add (l, r) => l.evaluate(vars) + r.evaluate(vars) + case Mul (l, r) => l.evaluate(vars) * r.evaluate(vars) + case Pow(l, r) => power(l.evaluate(vars), r) + } + + def equ(that: Expr): boolean = Pair(this,that) match { + case Pair(Lit(l) ,Lit(r)) => l == r + case Pair(Var(l) ,Var(r)) => l == r + case Pair(Add(ll,lr),Add(rl,rr)) => (ll equ rl) && (lr equ rr) + case Pair(Mul(ll,lr),Mul(rl,rr)) => (ll equ rl) && (lr equ rr) + case Pair(Pow(ll,lr),Pow(rl,rr)) => (ll equ rl) && (lr == rr) + case _ => false + } + + } + + case class Lit(x: int) extends Expr { + override def toString() = x.toString() + } + + case class Var(name: String) extends Expr { + override def toString() = name; + } + + case class Add(e1: Expr, e2: Expr) extends Expr { + override def toString() = e1.toString() + " + " + e2.toString(); // !!! .toString + } + + case class Mul(e1: Expr, e2: Expr) extends Expr { + override def toString() = { + def factorToString(e: Expr) = e match { + case Add(_, _) => "(" + e.toString() + ")" + case _ => e.toString() + } + factorToString(e1) + " * " + factorToString(e2); + } + } + + case class Pow(e1: Expr, i2: int) extends Expr { + override def toString() = { + def factorToString(e: Expr) = e match { + case Add(_, _) => "(" + e.toString() + ")" + case Mul(_, _) => "(" + e.toString() + ")" + case _ => e.toString() + } + factorToString(e1) + "^" + i2; + } + } + + def test = { + val _1 = Lit(1); + val _2 = Lit(2); + val _3 = Lit(3); + val _4 = Lit(4); + val _5 = Lit(5); + + val x = Var("x"); + + val ta = (_1 + (_2 + x)); + val tb = (_1 + (x + _2)); + val tc = ((_1 + x) + _2); + val td = ((x + _1) + _2); + val te = ((x + _1) + (x + _2)); + val tf = ((_1 + x) + (_2 + x)); + val tg = x + x + (x * _2) + x + x; + val th = x * x * (x ^ 2) * x * x; + + System.out.println("ta(x) = " + ta); + System.out.println("tb(x) = " + tb); + System.out.println("tc(x) = " + tc); + System.out.println("td(x) = " + td); + System.out.println("te(x) = " + te); + System.out.println("tf(x) = " + tf); + System.out.println("tg(x) = " + tg); + System.out.println("th(x) = " + th); + System.out.println(); + + val f4 = (x+ _3)*(_2+x)*x*(x+ _1) + (x+ _5)*(x*(x+ _2)+x+ _1) + (x^2) + x; + val f3 = f4.derive(x); + val f2 = f3.derive(x); + val f1 = f2.derive(x); + val f0 = f1.derive(x); + + System.out.println("f4(x) = " + f4); + System.out.println("f3(x) = " + f3); + System.out.println("f2(x) = " + f2); + System.out.println("f1(x) = " + f1); + System.out.println("f0(x) = " + f0); + System.out.println(); + + def check(n: String, f: Expr, x: int, e: int) = { + val a: int = f.evaluate(List(Pair("x",x))); + val s: String = if (a == e) "ok" else "KO(" + e + ")"; + System.out.println(n + "(" + x + ") = " + a + " " + s); + } + + check("f4", f4, 0, 5); + check("f4", f4, 1, 56); + check("f4", f4, 2, 203); + check("f4", f4, 3, 524); + check("f4", f4, 4, 1121); + System.out.println(); + + check("f3", f3, 0, 23); + check("f3", f3, 1, 88); + check("f3", f3, 2, 219); + check("f3", f3, 3, 440); + System.out.println(); + + check("f2", f2, 0, 40); + check("f2", f2, 1, 94); + check("f2", f2, 2, 172); + System.out.println(); + + check("f1", f1, 0, 42); + check("f1", f1, 1, 66); + System.out.println(); + + check("f0", f0, 0, 24); + System.out.println(); + } +} + +//############################################################################ + +object Test { + def main(args: Array[String]): unit = { + M0.test; + M1.test; + M2.test; + M3.test; + M4.test; + M5.test; + // !!! M6.test; + M7.test; + M8.test; + M9.test; + MA.test; + MB.test; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/Course-2002-08.scala b/test-nsc/files/run/Course-2002-08.scala new file mode 100755 index 0000000000..7e06001732 --- /dev/null +++ b/test-nsc/files/run/Course-2002-08.scala @@ -0,0 +1,602 @@ +//############################################################################ +// Programmation IV - 2002 - Week 08 +//############################################################################ +// $Id$ + +import List._; + +object M0 { + + var x: String = "abc"; + var count = 111; + + def test = { + Console.println("x = " + x); + Console.println("count = " + count); + x = "hello"; + count = count + 1; + Console.println("x = " + x); + Console.println("count = " + count); + Console.println; + } +} + +//############################################################################ + +object M1 { + + class BankAccount() { + private var balance = 0; + def deposit(amount: Int): Unit = + if (amount > 0) balance = balance + amount; + + def withdraw(amount: Int): Int = + if (0 < amount && amount <= balance) { + balance = balance - amount; + balance + } else error("insufficient funds"); + } + + def test0 = { + val account = new BankAccount(); + Console.print("account deposit 50 -> "); + Console.println((account deposit 50).toString()); // !!! .toString + Console.print("account withdraw 20 -> "); + Console.println(account withdraw 20); + Console.print("account withdraw 20 -> "); + Console.println(account withdraw 20); + Console.print("account withdraw 15 -> "); + Console.println; + } + + def test1 = { + val x = new BankAccount(); + val y = new BankAccount(); + Console.print("x deposit 30 -> "); + Console.println((x deposit 30).toString()); // !!! .toString + Console.print("y withdraw 20 -> "); + Console.println; + } + + def test2 = { + val x = new BankAccount(); + val y = new BankAccount(); + Console.print("x deposit 30 -> "); + Console.println((x deposit 30).toString()); // !!! .toString + Console.print("x withdraw 20 -> "); + Console.println(x withdraw 20); + } + + def test3 = { + val x = new BankAccount(); + val y = x; + Console.print("x deposit 30 -> "); + Console.println((x deposit 30).toString()); // !!! .toString + Console.print("y withdraw 20 -> "); + Console.println(y withdraw 20); + } + + def test = { + test0; Console.println; + test1; Console.println; + test2; Console.println; + test3; Console.println; + } +} + + +//############################################################################ + +object M2 { + + def While(condition: => Boolean)(command: => Unit): Unit = + if (condition) { + command; While(condition)(command) + } else { + } + + def power (x: Double, exp: Int): Double = { + var r = 1.0; + var i = exp; + While (i > 0) { r = r * x; i = i - 1 } + r + } + + def test = { + Console.println("2^0 = " + power(2,0)); + Console.println("2^1 = " + power(2,1)); + Console.println("2^2 = " + power(2,2)); + Console.println("2^3 = " + power(2,3)); + Console.println; + } +} + +//############################################################################ + +object M3 { + + def power (x: Double, exp: Int): Double = { + var r = 1.0; + var i = exp; + while (i > 0) { r = r * x; i = i - 1 } + r + } + + def test = { + Console.println("2^0 = " + power(2,0)); + Console.println("2^1 = " + power(2,1)); + Console.println("2^2 = " + power(2,2)); + Console.println("2^3 = " + power(2,3)); + Console.println; + } +} + +//############################################################################ + +object M4 { + + def test = { + for (val i <- range(1, 4)) { Console.print(i + " ") }; + Console.println; + Console.println(for (val i <- range(1, 4)) yield i); + Console.println; + } +} + +//############################################################################ + +object M5 { + + type Action = () => Unit; + + class Wire() { + private var sigVal = false; + private var actions: List[Action] = List(); + def getSignal = sigVal; + def setSignal(s: Boolean) = + if (s != sigVal) { + sigVal = s; + actions.foreach(action => action()); + } + def addAction(a: Action) = { + actions = a :: actions; a() + } + } + + abstract class Simulation() { + private type Agenda = List[Pair[Int, Action]]; + private var agenda: Agenda = List(); + private var curtime = 0; + def currentTime: Int = curtime; + + def afterDelay(delay: Int)(action: Action): Unit = { + def insert(ag: Agenda, time: Int): Agenda = ag match { + case List() => + List(Pair(time, action)) + case Pair(t, act) :: ag1 => + if (time < t) Pair(time, action) :: ag + else Pair(t, act) :: insert(ag1, time) + } + agenda = insert(agenda, curtime + delay) + } + + private def next: Unit = agenda match { + case List() => () + case Pair(time, action) :: ag1 => { + agenda = ag1; + curtime = time; + action(); + } + } + + def run: Unit = { + afterDelay(0){() => Console.println("*** simulation started ***"); } + while (!agenda.isEmpty) { next } + } + } + + abstract class BasicCircuitSimulation() extends Simulation() { + + val InverterDelay: Int; + val AndGateDelay: Int; + val OrGateDelay: Int; + + def inverter(input: Wire, output: Wire): Unit = { + def invertAction() = { + val inputSig = input.getSignal; + afterDelay(InverterDelay) {() => output.setSignal(!inputSig) }; + } + input addAction invertAction + } + + def andGate(a1: Wire, a2: Wire, output: Wire): Unit = { + def andAction() = { + val a1Sig = a1.getSignal; + val a2Sig = a2.getSignal; + afterDelay(AndGateDelay) {() => output.setSignal(a1Sig & a2Sig) }; + } + a1 addAction andAction; + a2 addAction andAction; + } + + def orGate(o1: Wire, o2: Wire, output: Wire): Unit = { + def orAction() = { + val o1Sig = o1.getSignal; + val o2Sig = o2.getSignal; + afterDelay(OrGateDelay) {() => output.setSignal(o1Sig | o2Sig) }; + } + o1 addAction orAction; + o2 addAction orAction; + } + + def probe(name: String, wire: Wire): Unit = { + wire addAction {() => + Console.println( + name + " " + currentTime + " new-value = " + wire.getSignal); + } + } + } + + abstract class CircuitSimulation() extends BasicCircuitSimulation() { + + def halfAdder(a: Wire, b: Wire, s: Wire, c: Wire): Unit = { + val d = new Wire(); + val e = new Wire(); + orGate(a, b, d); + andGate(a, b, c); + inverter(c, e); + andGate(d, e, s); + } + + def fullAdder(a: Wire, b: Wire, cin: Wire, sum: Wire, cout: Wire): Unit = { + val s = new Wire(); + val c1 = new Wire(); + val c2 = new Wire(); + halfAdder(a, cin, s, c1); + halfAdder(b, s, sum, c2); + orGate(c1, c2, cout); + } + } + + class Test() extends CircuitSimulation() { + + val InverterDelay = 1; + val AndGateDelay = 3; + val OrGateDelay = 5; + + def invert = { + val ain = new Wire(); + val cout = new Wire(); + inverter(ain, cout); + + def result = if (cout.getSignal) 1 else 0; + + def test(a: Int) = { + ain setSignal (if (a == 0) false else true); + run; + Console.println("!" + a + " = " + result); + Console.println; + } + + probe("out ", cout); + + test(0); + test(1); + } + + def and = { + val ain = new Wire(); + val bin = new Wire(); + val cout = new Wire(); + andGate(ain, bin, cout); + + def result = if (cout.getSignal) 1 else 0; + + def test(a: Int, b: Int) = { + ain setSignal (if (a == 0) false else true); + bin setSignal (if (b == 0) false else true); + run; + Console.println(a + " & " + b + " = " + result); + Console.println; + } + + probe("out ", cout); + Console.println; + + test(0,0); + test(0,1); + test(1,0); + test(1,1); + } + + def or = { + val ain = new Wire(); + val bin = new Wire(); + val cout = new Wire(); + orGate(ain, bin, cout); + + def result = if (cout.getSignal) 1 else 0; + + def test(a: Int, b: Int) = { + ain setSignal (if (a == 0) false else true); + bin setSignal (if (b == 0) false else true); + run; + Console.println(a + " | " + b + " = " + result); + Console.println; + } + + probe("out ", cout); + Console.println; + + test(0,0); + test(0,1); + test(1,0); + test(1,1); + } + + def half = { + val ain = new Wire(); + val bin = new Wire(); + val sout = new Wire(); + val cout = new Wire(); + halfAdder(ain, bin, sout, cout); + + def result = + (if (sout.getSignal) 1 else 0) + + (if (cout.getSignal) 2 else 0); + + def test(a: Int, b: Int) = { + ain setSignal (if (a == 0) false else true); + bin setSignal (if (b == 0) false else true); + run; + Console.println(a + " + " + b + " = " + result); + Console.println; + } + + probe("sum ", sout); + probe("carry", cout); + Console.println; + + test(0,0); + test(0,1); + test(1,0); + test(1,1); + } + + def full = { + val ain = new Wire(); + val bin = new Wire(); + val cin = new Wire(); + val sout = new Wire(); + val cout = new Wire(); + fullAdder(ain, bin, cin, sout, cout); + + def result = + (if (sout.getSignal) 1 else 0) + + (if (cout.getSignal) 2 else 0); + + def test(a: Int, b: Int, c: Int) = { + ain setSignal (if (a == 0) false else true); + bin setSignal (if (b == 0) false else true); + cin setSignal (if (c == 0) false else true); + run; + Console.println(a + " + " + b + " + " + c + " = " + result); + Console.println; + } + + probe("sum ", sout); + probe("carry", cout); + Console.println; + + test(0,0,0); + test(0,0,1); + test(0,1,0); + test(0,1,1); + test(1,0,0); + test(1,0,1); + test(1,1,0); + test(1,1,1); + } + } + + def test = { + val sim = new Test(); + sim.invert; + sim.and; + sim.or; + sim.half; + sim.full; + } +} + +//############################################################################ + +class Simulator() { + + type Action = () => Unit; + type Agenda = List[Pair[Int, Action]]; + + private var agenda: Agenda = List(); + private var curtime = 0; + + def afterDelay(delay: Int)(action: Action) = { + def insert(ag: Agenda, time: Int): Agenda = ag match { + case List() => + List(Pair(time, action)) + case Pair(t, act) :: ag1 => + if (time < t) Pair(time, action) :: ag + else Pair(t, act) :: insert(ag1, time) + } + agenda = insert(agenda, curtime + delay) + } + + def next: Unit = agenda match { + case List() => () + case Pair(time, action) :: rest => { + agenda = rest; + curtime = time; + action(); + } + } + + protected def currentTime: Int = curtime; + + def run = { + afterDelay(0){() => Console.println("*** simulation started ***"); } + while (!agenda.isEmpty) { next } + } +} + +class Wire() { + private var sigVal = false; + private var actions: List[() => Unit] = List(); + def getSignal = sigVal; + def setSignal(s: Boolean) = + if (s != sigVal) { + sigVal = s; + actions.foreach(action => action()); + } + def addAction(a: () => Unit) = { + actions = a :: actions; + a() + } +} + +abstract class BasicCircuitSimulator() extends Simulator() { + + def probe(name: String, wire: Wire): Unit = { + wire addAction {() => + Console.println( + name + " " + currentTime + " new-value = " + wire.getSignal); + } + } + + val InverterDelay: Int; + val AndGateDelay: Int; + val OrGateDelay: Int; + + def inverter(input: Wire, output: Wire) = { + def invertAction() = { + val inputSig = input.getSignal; + afterDelay(InverterDelay) {() => output.setSignal(!inputSig) }; + } + input addAction invertAction + } + + def andGate(a1: Wire, a2: Wire, output: Wire) = { + def andAction() = { + val a1Sig = a1.getSignal; + val a2Sig = a2.getSignal; + afterDelay(AndGateDelay) {() => output.setSignal(a1Sig & a2Sig) }; + } + a1 addAction andAction; + a2 addAction andAction + } + + def orGate(a1: Wire, a2: Wire, output: Wire) = { + def orAction() = { + val a1Sig = a1.getSignal; + val a2Sig = a2.getSignal; + afterDelay(OrGateDelay) {() => output.setSignal(a1Sig | a2Sig) }; + } + a1 addAction orAction; + a2 addAction orAction + } + + def orGate2(a1: Wire, a2: Wire, output: Wire) = { + val w1 = new Wire(); + val w2 = new Wire(); + val w3 = new Wire(); + inverter(a1, w1); + inverter(a2, w2); + andGate(w1, w2, w3); + inverter(w3, output); + } +} + +abstract class CircuitSimulator() extends BasicCircuitSimulator() { + def demux2(in: Wire, ctrl: List[Wire], out: List[Wire]) : Unit = { + val ctrlN = ctrl.map(w => { val iw = new Wire(); inverter(w,iw); iw}); + val w0 = new Wire(); + val w1 = new Wire(); + val w2 = new Wire(); + val w3 = new Wire(); + + andGate(in, ctrl(1), w3); + andGate(in, ctrl(1), w2); + andGate(in, ctrlN(1), w1); + andGate(in, ctrlN(1), w0); + + andGate(w3, ctrl(0), out(3)); + andGate(w2, ctrlN(0), out(2)); + andGate(w1, ctrl(0), out(1)); + andGate(w0, ctrlN(0), out(0)); + } + + def connect(in: Wire, out: Wire) = { + in addAction {() => out.setSignal(in.getSignal); } + } + + def demux(in: Wire, ctrl: List[Wire], out: List[Wire]): Unit = ctrl match { + case List() => connect(in, out.head); + case c :: rest => + val c_ = new Wire(); + val w1 = new Wire(); + val w2 = new Wire(); + inverter(c, c_); + andGate(in, c_, w1); + andGate(in, c, w2); + demux(w1, rest, out.drop(out.length / 2)); + demux(w2, rest, out.take(out.length / 2)); + } +} + +class Main() extends CircuitSimulator() { + + val InverterDelay = 1; + val AndGateDelay = 3; + val OrGateDelay = 5; + + def main = { + val n = 3; + val outNum = 1 << n; + + val in = new Wire(); + val ctrl = for (val x <- range(0,n)) yield { new Wire() }; + val out = for (val x <- range(0,outNum)) yield { new Wire() }; + + demux(in, ctrl.reverse, out.reverse); + + probe("in", in); + for (val Pair(x,c) <- range(0,n) zip ctrl) { probe("ctrl" + x, c) } + for (val Pair(x,o) <- range(0,outNum) zip out) { probe("out" + x, o) } + + in.setSignal(true); + run; + ctrl(0).setSignal(true); + run; + ctrl(1).setSignal(true); + run; + ctrl(2).setSignal(true); + run; + ctrl(0).setSignal(false); + run; + } +} + +//############################################################################ + +object Test { + def main(args: Array[String]): Unit = { + M0.test; + M1.test; + M2.test; + M3.test; + M4.test; + M5.test; + new Main().main; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/Course-2002-09.scala b/test-nsc/files/run/Course-2002-09.scala new file mode 100755 index 0000000000..65f9adad2b --- /dev/null +++ b/test-nsc/files/run/Course-2002-09.scala @@ -0,0 +1,334 @@ +//############################################################################ +// Programmation IV - 2002 - Week 09 +//############################################################################ +// $Id$ + +trait Constraint { + def newValue: Unit; + def dropValue: Unit +} + +object NoConstraint extends Constraint { + def newValue: Unit = error("NoConstraint.newValue"); + def dropValue: Unit = error("NoConstraint.dropValue"); +} + +class Adder(a1: Quantity,a2: Quantity,sum: Quantity) extends Constraint { + def newValue = Triple(a1.getValue, a2.getValue, sum.getValue) match { + case Triple(Some(x1), Some(x2), _ ) => sum.setValue(x1 + x2, this) + case Triple(Some(x1), _ , Some(r)) => a2.setValue(r - x1, this) + case Triple(_ , Some(x2), Some(r)) => a1.setValue(r - x2, this) + case _ => + } + def dropValue: Unit = { + a1.forgetValue(this); a2.forgetValue(this); sum.forgetValue(this); + } + a1 connect this; + a2 connect this; + sum connect this; +} + +class Multiplier(m1: Quantity, m2: Quantity, prod: Quantity) + extends Constraint { + def newValue = Triple(m1.getValue, m2.getValue, prod.getValue) match { + case Triple(Some(0d), _ , _ ) => prod.setValue(0, this); + case Triple(_ , Some(0d), _ ) => prod.setValue(0, this); + case Triple(Some(x1), Some(x2), _ ) => prod.setValue(x1 * x2, this) + case Triple(Some(x1), _ , Some(r)) => m2.setValue(r / x1, this) + case Triple(_, Some(x2), Some(r)) => m1.setValue(r / x2, this) + case _ => + } + def dropValue: Unit = { + m1.forgetValue(this); m2.forgetValue(this); prod.forgetValue(this); + } + m1 connect this; + m2 connect this; + prod connect this; +} + +class Squarer(square: Quantity, root: Quantity) extends Constraint { + def newValue: Unit = Pair(square.getValue, root.getValue) match { + case Pair(Some(x), _ )if (x < 0) => error("Square of negative number") + case Pair(Some(x), _ ) => + root.setValue(scala.runtime.compat.Math.sqrt(x), this) + case Pair(_ , Some(x)) => square.setValue(x*x, this) + case _ => + } + def dropValue: Unit = { + square.forgetValue(this); root.forgetValue(this); + } + square connect this; + root connect this; +} + +class Eq(a: Quantity, b: Quantity) extends Constraint { + def newValue = Pair(a.getValue, b.getValue) match { + case Pair(Some(x), _ ) => b.setValue(x, this); + case Pair(_ , Some(y)) => a.setValue(y, this); + } + def dropValue: Unit = { + a.forgetValue(this); b.forgetValue(this); + } + a connect this; + b connect this; +} + +class Constant(q: Quantity, v: double) extends Constraint { + def newValue: Unit = error("Constant.newValue"); + def dropValue: Unit = error("Constant.dropValue"); + q connect this; + q.setValue(v, this); +} + +class Probe(name: String, q: Quantity) extends Constraint { + def newValue: Unit = printProbe(q.getValue); + def dropValue: Unit = printProbe(None); + private def printProbe(v: Option[double]): Unit = { + val vstr = v match { + case Some(x) => x.toString() + case None => "?" + } + Console.println("Probe: " + name + " = " + vstr); + } + q connect this +} + +class Quantity() { + private var value: Option[double] = None; + private var constraints: List[Constraint] = List(); + private var informant: Constraint = null; + + def getValue: Option[double] = value; + + def setValue(v: double, setter: Constraint) = value match { + case Some(v1) => + if (v != v1) error("Error! contradiction: " + v + " and " + v1); + case None => + informant = setter; value = Some(v); + for (val c <- constraints; !(c == informant)) { + c.newValue; + } + } + def setValue(v: double): Unit = setValue(v, NoConstraint); + + def forgetValue(retractor: Constraint): Unit = { + if (retractor == informant) { + value = None; + for (val c <- constraints; !(c == informant)) c.dropValue; + } + } + def forgetValue: Unit = forgetValue(NoConstraint); + + def connect(c: Constraint) = { + constraints = c :: constraints; + value match { + case Some(_) => c.newValue + case None => + } + } + + def +(that: Quantity): Quantity = { + val sum = new Quantity(); + new Adder(this, that, sum); + sum; + } + + def *(that: Quantity): Quantity = { + val prod = new Quantity(); + new Multiplier(this, that, prod); + prod; + } + + def square: Quantity = { + val square = new Quantity(); + new Squarer(square, this); + square; + } + + def sqrt: Quantity = { + val root = new Quantity(); + new Squarer(this, root); + root; + } + + def ===(that: Quantity): Constraint = { + new Eq(this, that); + } + + override def toString(): String = value match { + case None => " ?" + case Some(v) => v.toString() + } + + def str: String = toString(); +} + +//############################################################################ + +object M0 { + + def CFconverter(c: Quantity, f: Quantity) = { + val u = new Quantity(); + val v = new Quantity(); + val w = new Quantity(); + val x = new Quantity(); + val y = new Quantity(); + new Multiplier(c, w, u); + new Multiplier(v, x, u); + new Adder(v, y, f); + new Constant(w, 9); + new Constant(x, 5); + new Constant(y, 32); + } + + def test = { + val c = new Quantity(); new Probe("c", c); + val f = new Quantity(); new Probe("f", f); + CFconverter(c, f); + + c.setValue(0); + c.forgetValue; + Console.println; + + c.setValue(100); + c.forgetValue; + Console.println; + + f.setValue(32); + f.forgetValue; + Console.println; + + f.setValue(212); + f.forgetValue; + Console.println; + } +} + +//############################################################################ + +object M1 { + + def constant(x: double): Quantity = { + val q = new Quantity(); + new Constant(q, x); + q + } + + def CFconverter(c: Quantity, f: Quantity) = { + val v = new Quantity(); + constant(9) * c === constant(5) * v; + v + constant(32) === f; + } + + def show_c2f(c: Quantity, f: Quantity, v: int) = { + c.setValue(v); + Console.println(c.str + " Celsius -> " + f.str + " Fahrenheits"); + c.forgetValue; + } + + def show_f2c(c: Quantity, f: Quantity, v: int) = { + f.setValue(v); + Console.println(f.str + " Fahrenheits -> " + c.str + " Celsius"); + f.forgetValue; + } + + def test = { + val c = new Quantity(); + val f = new Quantity(); + CFconverter(c, f); + + show_c2f(c, f, 0); + show_c2f(c, f, 100); + show_f2c(c, f, 32); + show_f2c(c, f, 212); + Console.println; + } +} + +//############################################################################ + +object M2 { + + val a = new Quantity(); + val b = new Quantity(); + val c = a * b; + + def set(q: Quantity, o: Option[int]): String = { + o match { + case None => "?" + case Some(v) => q.setValue(v); v.toString() + }; + } + + def show(x: Option[int], y: Option[int], z: Option[int]) = { + Console.print("a = " +set(a,x)+ ", b = " +set(b,y)+ ", c = " +set(c,z)); + Console.println(" => " + a.str + " * " + b.str + " = " + c.str); + a.forgetValue; b.forgetValue; c.forgetValue; + } + + def test = { + show(None , None , None ); + show(Some(2), None , None ); + show(None , Some(3), None ); + show(None , None , Some(6)); + show(Some(2), Some(3), None ); + show(Some(2), None , Some(6)); + show(None , Some(3), Some(6)); + show(Some(2), Some(3), Some(6)); + Console.println; + + show(Some(0), None , None ); + show(None , Some(0), None ); + show(None , None , Some(0)); + show(Some(0), Some(7), None ); + show(Some(7), Some(0), None ); + show(Some(0), Some(0), None ); + show(Some(0), None , Some(0)); + show(None , Some(0), Some(0)); + show(Some(0), Some(7), Some(0)); + show(Some(7), Some(0), Some(0)); + show(Some(0), Some(0), Some(0)); + Console.println; + } +} + + +//############################################################################ + +object M3 { + + def test = { + val a = new Quantity(); + val b = new Quantity(); + val c = new Quantity(); + c === (a.square + b.square).sqrt; + + a.setValue(3); b.setValue(4); + Console.println("a = 3, b = 4 => c = " + c.str); + a.forgetValue; b.forgetValue; + + a.setValue(3); c.setValue(5); + Console.println("a = 3, c = 5 => b = " + b.str); + a.forgetValue; c.forgetValue; + + b.setValue(4); c.setValue(5); + Console.println("b = 4, c = 5 => a = " + a.str); + b.forgetValue; c.forgetValue; + + Console.println; + } +} + +//############################################################################ + +object Test { + def main(args: Array[String]): Unit = { + M0.test; + M1.test; + M2.test; + M3.test; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/Course-2002-10.scala b/test-nsc/files/run/Course-2002-10.scala new file mode 100755 index 0000000000..e634309018 --- /dev/null +++ b/test-nsc/files/run/Course-2002-10.scala @@ -0,0 +1,136 @@ +//############################################################################ +// Programmation IV - 2002 - Week 10 +//############################################################################ +// $Id$ + +import java.lang.System; // to avoid name clash with .NET's library + +object M0 { + + def addStream (s1: Stream[int], s2: Stream[int]): Stream[int] = + Stream.cons(s1.head + s2.head, addStream(s1.tail, s2.tail)); + + val fib: Stream[int] = + Stream.cons(0, Stream.cons(1, addStream(this.fib, this.fib.tail))); + + def test = { + var i = 0; + fib.take(20).foreach(n => {System.out.println("fib("+i+") = "+n); i=i+1}); + System.out.println(); + } +} + +//############################################################################ + +object M1 { + + def scale(x: double, s: Stream[double]): Stream[double] = + s map (e: double => e*x); + + def partialSums(s: Stream[double]): Stream[double] = + Stream.cons(s.head, partialSums(s.tail) map (x => x + s.head)); + + def euler(s: Stream[double]): Stream[double] = { + val nm1 = s at 0; + val n = s at 1; + val np1 = s at 2; + Stream.cons(np1 - ((np1 - n)*(np1 - n) / (nm1 - 2*n + np1)),euler(s.tail)) + }; + + def better(s: Stream[double], transform: Stream[double] => Stream[double]) + : Stream[Stream[double]] = + Stream.cons(s, better(transform(s), transform)); + + def veryGood(s: Stream[double], transform: Stream[double] => Stream[double]) + : Stream[double] = + better(s, transform) map (x => x.head); + + def lnSummands(n: double): Stream[double] = + Stream.cons(1.0 / n, lnSummands(n + 1.0) map (x: double => -x)); + + var ln0 = partialSums(lnSummands(1.0)); + var ln1 = euler(ln0); + var ln2 = veryGood(ln0, euler); + + def piSummands(n: double): Stream[double] = + Stream.cons(1.0 / n, piSummands(n + 2.0) map (x: double => -x)); + + var pi0 = scale(4.0, partialSums(piSummands(1.0))); + var pi1 = euler(pi0); + var pi2 = veryGood(pi0, euler); + + def pad(s: String, n: int): String = + if (n <= 0) s.substring(0, s.length() + n) + else pad(s + " ", n - 1); + def str(d: double) = { val s = d.toString(); pad(s, 18 - s.length()) }; + + def test = { + var i = 0; + while (i < 10) { + System.out.print("pi("+i+") = "); + System.out.print(str(pi0.at(i)) + ", "); + System.out.print(str(pi1.at(i)) + ", "); + System.out.print(str(pi2.at(i)) + "\n"); + i = i + 1; + } + System.out.print("pi = "); + System.out.print(str(Math.PI) + ", "); + System.out.print(str(Math.PI) + ", "); + System.out.print(str(Math.PI) + "\n"); + System.out.println(); + i = 0; + while (i < 10) { + System.out.print("ln("+i+") = "); + System.out.print(str(ln0.at(i)) + ", "); + System.out.print(str(ln1.at(i)) + ", "); + System.out.print(str(ln2.at(i)) + "\n"); + i = i + 1; + } + System.out.print("ln = "); + System.out.print(str(Math.log(2)) + ", "); + System.out.print(str(Math.log(2)) + ", "); + System.out.print(str(Math.log(2)) + "\n"); + System.out.println(); + } +} + +//############################################################################ + +object M2 { + + class IntIterator(start: int) extends Iterator[int] { + var current: int = start; + def hasNext = true; + def next = { current = current + 1; current - 1 }; + } + + class PrimeIterator() extends Iterator[int] { + var current: Iterator[int] = new IntIterator(2); + def hasNext = true; + def next = { + val p = current.next; + current = current filter { x => !((x % p) == 0) }; + p + } + } + + def test = { + val i = (new PrimeIterator()).take(30); + System.out.print("prime numbers:"); + while (i.hasNext) { System.out.print(" " + i.next); } + System.out.println(); + } +} + +//############################################################################ + +object Test { + def main(args: Array[String]): Unit = { + M0.test; + M1.test; + M2.test; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/Course-2002-13.scala b/test-nsc/files/run/Course-2002-13.scala new file mode 100755 index 0000000000..e98d8944a8 --- /dev/null +++ b/test-nsc/files/run/Course-2002-13.scala @@ -0,0 +1,324 @@ +//############################################################################ +// Programmation IV - 2002 - Week 13 +//############################################################################ +// $Id$ + +class Tokenizer(s: String, delimiters: String) extends Iterator[String] { + + private var i = 0; + + def isDelimiter(ch: Char) = { + var i = 0; + while (i < delimiters.length() && delimiters.charAt(i) != ch) { i = i + 1 } + i < delimiters.length() + } + + def hasNext: boolean = { + while (i < s.length() && s.charAt(i) <= ' ') { i = i + 1 } + i < s.length() + } + + def next: String = + if (hasNext) { + val start = i; + var ch = s.charAt(i); i = i + 1; + if (isDelimiter(ch)) ch.toString() + else { + while (i < s.length() && + s.charAt(i) > ' ' && + !isDelimiter(s.charAt(i))){ i = i + 1 } + s.substring(start, i) + } + } else ""; + +} + +object Terms { + + val debug = false; + + trait Term { + def map(s: Subst): Term; + def tyvars: List[String]; + } + + case class Binding(name: String, term: Term) { + term match { case Var(n) if (name == n) => error("bad binding") case _ => () } + override def toString() = name + " = " + term; + } + + type Subst = List[Binding]; + + def lookup(s: Subst, name: String): Option[Term] = s match { + case List() => None + case b :: s1 => if (name == b.name) Some(b.term) else lookup(s1, name) + } + + case class Var(a: String) extends Term { + override def toString() = a; + def map(s: Subst): Term = lookup(s, a) match { + case Some(b) => b map s + case None => this; + } + def tyvars = List(a); + } + + case class Con(a: String, ts: List[Term]) extends Term { + override def toString() = + a + (if (ts.isEmpty) "" else ts.mkString("(", ",", ")")); + def map(s: Subst): Term = Con(a, ts map (t => t map s)); + def tyvars = (ts flatMap (t => t.tyvars)).removeDuplicates; + } + + private var count = 0; + def newVar(prefix: String) = { count = count + 1; Var(prefix + count) } + + val NoTerm = Con("<none>", List()); + + def unify1(x: Term, y: Term, s: Subst): Option[Subst] = Pair(x, y) match { + case Pair(Var(a), Var(b)) if (a == b) => + Some(s) + case Pair(Var(a), _) => lookup(s, a) match { + case Some(x1) => unify(x1, y, s) + case None => if (y.tyvars contains a) None else Some(Binding(a, y) :: s) + } + case Pair(_, Var(b)) => lookup(s, b) match { + case Some(y1) => unify(x, y1, s) + case None => if (x.tyvars contains b) None else Some(Binding(b, x) :: s) + } + case Pair(Con(a, xs), Con(b, ys)) if (a == b) => + unify(xs, ys, s) + case _ => None + } + + def unify(x: Term, y: Term, s: Subst): Option[Subst] = { + val ss = unify1(x, y, s); + if (debug) Console.println("unify " + x + " with " + y + " = " + ss); + ss + } + + def unify(xs: List[Term], ys: List[Term], s: Subst): Option[Subst] = Pair(xs, ys) match { + case Pair(List(), List()) => Some(s) + case Pair(x :: xs1, y :: ys1) => + unify(x, y, s) match { + case Some(s1) => unify(xs1, ys1, s1) + case None => None + } + case _ => None + } +} + +import Terms._; + +object Programs { + + case class Clause(lhs: Term, rhs: List[Term]) { + def tyvars = + (lhs.tyvars ::: (rhs flatMap (t => t.tyvars))).removeDuplicates; + def newInstance = { + var s: Subst = List(); + for (val a <- tyvars) { s = Binding(a, newVar(a)) :: s } + Clause(lhs map s, rhs map (t => t map s)) + } + override def toString() = + lhs.toString() + " :- " + rhs.mkString("", ",", "") + "."; + } + + def list2stream[a](xs: List[a]): Stream[a] = xs match { + case List() => Stream.empty + case x :: xs1 => Stream.cons(x, list2stream(xs1)) + } + def option2stream[a](xo: Option[a]): Stream[a] = xo match { + case None => Stream.empty + case Some(x) => Stream.cons(x, Stream.empty) + } + + def solve(query: List[Term], clauses: List[Clause]): Stream[Subst] = { + + def solve2(query: List[Term], s: Subst): Stream[Subst] = query match { + case List() => + Stream.cons(s, Stream.empty) + case Con("not", qs) :: query1 => + if (solve1(qs, s).isEmpty) Stream.cons(s, Stream.empty) + else Stream.empty + case q :: query1 => + for (val clause <- list2stream(clauses); + val s1 <- tryClause(clause.newInstance, q, s); + val s2 <- solve1(query1, s1)) yield s2 + } + + def solve1(query: List[Term], s: Subst): Stream[Subst] = { + val ss = solve2(query, s); + if (debug) Console.println("solved " + query + " = " + ss); + ss + } + + def tryClause(c: Clause, q: Term, s: Subst): Stream[Subst] = { + if (debug) Console.println("trying " + c); + for (val s1 <- option2stream(unify(q, c.lhs, s)); + val s2 <- solve1(c.rhs, s1)) yield s2; + } + + solve1(query, List()) + } +} + +import Programs._; + +class Parser(s: String) { + val it = new Tokenizer(s, "(),.?"); + + var token: String = it.next; + + def syntaxError(msg: String): Unit = error(msg + ", but " + token + " found"); + + def rep[a](p: => a): List[a] = { + val t = p; + if (token == ",") { token = it.next; t :: rep(p) } else List(t) + } + + def constructor: Term = { + val a = token; + token = it.next; + Con(a, + if (token equals "(") { + token = it.next; + val ts: List[Term] = if (token equals ")") List() else rep(term); + if (token equals ")") token = it.next else syntaxError("`)' expected"); + ts + } else List()) + } + + def term: Term = { + val ch = token.charAt(0); + if ('A' <= ch && ch <= 'Z') { val a = token; token = it.next; Var(a) } + else if (it.isDelimiter(ch)) { syntaxError("term expected"); null } + else constructor + } + + def line: Clause = { + val result = + if (token equals "?") { + token = it.next; + Clause(NoTerm, rep(constructor)); + } else { + Clause( + constructor, + if (token equals ":-") { token = it.next; rep(constructor) } else List()) + } + if (token equals ".") token = it.next else syntaxError("`.' expected"); + result + } + + def all: List[Clause] = if (token equals "") List() else line :: all; +} + +object Prolog { + + def processor: String => Unit = { + var program: List[Clause] = List(); + var solutions: Stream[Subst] = Stream.empty; + var tvs: List[String] = List(); + { input => + new Parser(input).all foreach { c => + if (c.lhs == NoTerm) { + c.rhs match { + case List(Con("more", List())) => + solutions = solutions.tail; + case _ => + solutions = solve(c.rhs, program); + tvs = c.tyvars; + } + if (solutions.isEmpty) { + Console.println("no") + } else { + val s: Subst = solutions.head + .filter(b => tvs contains b.name) + .map(b => Binding(b.name, b.term map solutions.head)) + .reverse; + if (s.isEmpty) Console.println("yes") + else Console.println(s); + } + } else { + program = program ::: List(c); + } + } + } + } + + def process(code: String) = processor(code); +} + +//############################################################################ + +object Test { + def main(args: Array[String]): Unit = { + Prolog.process( + "sujet(jean).\n" + + "sujet(marie).\n" + + "verbe(mange).\n" + + "verbe(dort).\n" + + "article(le).\n" + + "article(la).\n" + + "adjectif(grand).\n" + + "adjectif(belle).\n" + + "nom(table).\n" + + "nom(cheval).\n" + + + "complement(A,D,N) :- article(A), adjectif(D), nom(N).\n" + + "phrase(S,V,A,D,N) :- sujet(S), verbe(V), complement(A,D,N).\n" + + + "?phrase(S,V,A,D,N).\n" + "?more.\n" + ); + Console.println; + + Prolog.process( + "sujet(jean).\n" + + "sujet(marie).\n" + + "verbe(mange).\n" + + "verbe(dort).\n" + + "article(le,m).\n" + + "article(la,f).\n" + + "adjectif(grand,m).\n" + + "adjectif(belle,f).\n" + + "nom(table,f).\n" + + "nom(cheval,m).\n" + + + "complement(A,D,N) :- article(A,G), adjectif(D,G), nom(N,G).\n" + + "phrase(S,V,A,D,N) :- sujet(S), verbe(V), complement(A,D,N).\n" + + + "?phrase(S,V,A,D,N).\n" + "?more.\n" + ); + Console.println; + + Prolog.process( + "sujet(jean).\n" + + "sujet(marie).\n" + + "verbe(mange).\n" + + "verbe(dort).\n" + + "article(le,m).\n" + + "article(la,f).\n" + + "adjectif(grand,m).\n" + + "adjectif(belle,f).\n" + + "nom(table,f).\n" + + "nom(cheval,m).\n" + + + "adjectifs(nil,G).\n" + + "adjectifs(cons(A1,nil),G) :- adjectif(A1,G).\n" + + "adjectifs(cons(A1,cons(A2,nil)),G) :- adjectif(A1,G),adjectif(A2,G).\n"+ + "complement(A,D,N) :- article(A,G), adjectifs(D,G), nom(N,G).\n" + + "phrase(S,V,A,D,N) :- sujet(S), verbe(V), complement(A,D,N).\n" + + + "?phrase(S,V,A,D,N).\n" + "?more.\n" + "?more.\n" + "?more.\n" + + + "?phrase(jean,mange,le,nil,cheval).\n" + + "?phrase(jean,mange,le,cons(grand,nil),cheval).\n" + + "?phrase(jean,mange,le,cons(grand,nil),table).\n" + ); + Console.println; + + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/NestedClasses.scala b/test-nsc/files/run/NestedClasses.scala new file mode 100755 index 0000000000..5a427144fc --- /dev/null +++ b/test-nsc/files/run/NestedClasses.scala @@ -0,0 +1,98 @@ +//############################################################################ +// Test nested classes +//############################################################################ +// $Id$ + +// The following set of classes tests nasty references to "outer" +// values. + +class A(pa : Int) { + def a1 = pa; + class B(pb : Int) { + def b1 = pa+pb+a1; + class C(pc : Int) extends A(b1) { + def c1 = pc+pb+pa + } + val c1 = new C(13) + } +} + +trait M { + def m1 = 1 +} + +class A1(x : Int) extends A(x) with M { + class D extends B(14) { + val c2 = new C(15); + class E extends C(16) { + def e1 = c1+b1+a1+m1; + def e2 = new D(); + } + } +} + +// The following set of classes test qualified "this" and "super" +// references. + +class AA { + def m = 1; + class BB { + def m = 2; + class CC { + def m = 3; + def am = AA.this.m; + def bm = BB.this.m; + } + } +} + +class AAA { + def f = 42; +} + +class BBB extends AAA { + override def f = 24; +} + +class AAA1 extends AAA { + override def f = 111; + class BBB1 extends BBB { + override def f = AAA1.super.f; + } + class BBB2 extends BBB { + override def f = BBB2.super.f; + } + class BBB3 extends BBB { + override def f = super.f; + } + class BBB4 extends BBB { } +} + +object Test { + def main(args: Array[String]): Unit = { + val a = new A1(12); + val d = new a.D; + val e = new d.E; + Console.println("e.e1 = " + e.e1); + + val aa = new AA; + val bb = new aa.BB; + val cc = new bb.CC; + Console.println("cc.m = " + cc.m); + Console.println("cc.am = " + cc.am); + Console.println("cc.bm = " + cc.bm); + + val aaa = new AAA1; + val bbb1 = new aaa.BBB1; + val bbb2 = new aaa.BBB2; + val bbb3 = new aaa.BBB3; + val bbb4 = new aaa.BBB4; + Console.println("aaa.f = " + aaa.f); + Console.println("bbb1.f = " + bbb1.f); + Console.println("bbb2.f = " + bbb2.f); + Console.println("bbb3.f = " + bbb3.f); + Console.println("bbb4.f = " + bbb4.f); + } +} + +//############################################################################ diff --git a/test-nsc/files/run/all.lst b/test-nsc/files/run/all.lst new file mode 100644 index 0000000000..5742905aa8 --- /dev/null +++ b/test-nsc/files/run/all.lst @@ -0,0 +1,32 @@ +arrays.scala +boolexprs.scala +bridges.scala +bugs.scala +constructors.scala +Course-2002-01.scala +Course-2002-02.scala +Course-2002-03.scala +Course-2002-04.scala +Course-2002-05.scala +Course-2002-06.scala +Course-2002-07.scala +Course-2002-08.scala +Course-2002-09.scala +Course-2002-10.scala +Course-2002-13.scala +enums.scala +exceptions.scala +imports.scala +iq.scala +iterators.scala +lisp.scala +lists.scala +literals.scala +map_test.scala +misc.scala +mixins.scala +NestedClasses.scala +overloads.scala +regularpatmat.scala +runtime.scala +tailcalls.scala diff --git a/test-nsc/files/run/arrays.scala b/test-nsc/files/run/arrays.scala new file mode 100644 index 0000000000..9e9c3c065b --- /dev/null +++ b/test-nsc/files/run/arrays.scala @@ -0,0 +1,912 @@ +//############################################################################ +// Arrays +//############################################################################ +// $Id$ + +//############################################################################ + +object Test { + + //########################################################################## + // Types + + type Strings = List[String]; + type Map = scala.collection.Map[Int, Any]; + type HashMap = scala.collection.mutable.HashMap[Int, Any]; + type TreeMap = scala.collection.immutable.TreeMap[Int, Any]; + + //########################################################################## + // Identity Functions + + def id_Ta_T[T <: Any ](x: T): T = x; + def id_Tr_T[T <: AnyRef ](x: T): T = x; + def id_To_T[T <: Object ](x: T): T = x; + + def id_Ta_a[T <: Any ](x: T): Any = x; + def id_Tr_a[T <: AnyRef ](x: T): Any = x; + def id_To_a[T <: Object ](x: T): Any = x; + + def id_Tr_r[T <: AnyRef ](x: T): AnyRef = x; + def id_To_r[T <: Object ](x: T): AnyRef = x; + + def id_To_o[T <: Object ](x: T): Object = x; + + def id_TSa_T [S <: Any , T <: Array[S]](x: T): T = x; + def id_TSv_T [S <: AnyVal , T <: Array[S]](x: T): T = x; + def id_TSr_T [S <: AnyRef , T <: Array[S]](x: T): T = x; + def id_TSo_T [S <: Object , T <: Array[S]](x: T): T = x; + def id_TSm_T [S <: Map , T <: Array[S]](x: T): T = x; + def id_TSn_T [S <: Strings, T <: Array[S]](x: T): T = x; + + def id_TSa_Ss[S <: Any , T <: Array[S]](x: T): Array[S] = x; + def id_TSv_Ss[S <: AnyVal , T <: Array[S]](x: T): Array[S] = x; + def id_TSr_Ss[S <: AnyRef , T <: Array[S]](x: T): Array[S] = x; + def id_TSo_Ss[S <: Object , T <: Array[S]](x: T): Array[S] = x; + def id_TSm_Ss[S <: Map , T <: Array[S]](x: T): Array[S] = x; + def id_TSn_Ss[S <: Strings, T <: Array[S]](x: T): Array[S] = x; + + def id_TSa_a [S <: Any , T <: Array[S]](x: T): Any = x; + def id_TSv_a [S <: AnyVal , T <: Array[S]](x: T): Any = x; + def id_TSr_a [S <: AnyRef , T <: Array[S]](x: T): Any = x; + def id_TSo_a [S <: Object , T <: Array[S]](x: T): Any = x; + def id_TSm_a [S <: Map , T <: Array[S]](x: T): Any = x; + def id_TSn_a [S <: Strings, T <: Array[S]](x: T): Any = x; + + def id_TSa_r [S <: Any , T <: Array[S]](x: T): AnyRef = x; + def id_TSv_r [S <: AnyVal , T <: Array[S]](x: T): AnyRef = x; + def id_TSr_r [S <: AnyRef , T <: Array[S]](x: T): AnyRef = x; + def id_TSo_r [S <: Object , T <: Array[S]](x: T): AnyRef = x; + def id_TSm_r [S <: Map , T <: Array[S]](x: T): AnyRef = x; + def id_TSn_r [S <: Strings, T <: Array[S]](x: T): AnyRef = x; + + def id_TSa_o [S <: Any , T <: Array[S]](x: T): Object = x; + def id_TSv_o [S <: AnyVal , T <: Array[S]](x: T): Object = x; + def id_TSr_o [S <: AnyRef , T <: Array[S]](x: T): Object = x; + def id_TSo_o [S <: Object , T <: Array[S]](x: T): Object = x; + def id_TSm_o [S <: Map , T <: Array[S]](x: T): Object = x; + def id_TSn_o [S <: Strings, T <: Array[S]](x: T): Object = x; + + def id_Sas_Ss[S <: Any ](xs: Array[S]): Array[S] = xs; + def id_Svs_Ss[S <: AnyVal ](xs: Array[S]): Array[S] = xs; + def id_Srs_Ss[S <: AnyRef ](xs: Array[S]): Array[S] = xs; + def id_Sos_Ss[S <: Object ](xs: Array[S]): Array[S] = xs; + def id_Sms_Ss[S <: Map ](xs: Array[S]): Array[S] = xs; + def id_Sns_Ss[S <: Strings](xs: Array[S]): Array[S] = xs; + + def id_Sas_a [S <: Any ](xs: Array[S]): Any = xs; + def id_Svs_a [S <: AnyVal ](xs: Array[S]): Any = xs; + def id_Srs_a [S <: AnyRef ](xs: Array[S]): Any = xs; + def id_Sos_a [S <: Object ](xs: Array[S]): Any = xs; + def id_Sms_a [S <: Map ](xs: Array[S]): Any = xs; + def id_Sns_a [S <: Strings](xs: Array[S]): Any = xs; + + def id_Sas_r [S <: Any ](xs: Array[S]): AnyRef = xs; + def id_Svs_r [S <: AnyVal ](xs: Array[S]): AnyRef = xs; + def id_Srs_r [S <: AnyRef ](xs: Array[S]): AnyRef = xs; + def id_Sos_r [S <: Object ](xs: Array[S]): AnyRef = xs; + def id_Sms_r [S <: Map ](xs: Array[S]): AnyRef = xs; + def id_Sns_r [S <: Strings](xs: Array[S]): AnyRef = xs; + + def id_Sas_o [S <: Any ](xs: Array[S]): Object = xs; + def id_Svs_o [S <: AnyVal ](xs: Array[S]): Object = xs; + def id_Srs_o [S <: AnyRef ](xs: Array[S]): Object = xs; + def id_Sos_o [S <: Object ](xs: Array[S]): Object = xs; + def id_Sms_o [S <: Map ](xs: Array[S]): Object = xs; + def id_Sns_o [S <: Strings](xs: Array[S]): Object = xs; + + //########################################################################## + // Generic Checks + + type Check[T] = Array[T] => Unit; + + var checks: Int = 0; + + def check(test0: Boolean, actual: Any, expected: Any): Unit = { + val test1: Boolean = actual == expected; + if (!test0 || !test1) { + val s0 = if (test0) "ok" else "KO"; + val s1 = if (test1) "ok" else "KO"; + val s2 = actual.toString(); + val s3 = expected.toString(); + error(s0 + " - " + s1 + ": " + s2 + " != " + s3); + } + checks = checks + 1; + } + + def check_Ta[T <: Any ](xs: Array[T], l: Int, x0: T, c: Check[T]): Unit ={ + check(xs.length == l, xs.length, l); + check(xs(0) == x0, xs(0), x0); + c(xs); + } + + def check_Tv[T <: AnyVal ](xs: Array[T], l: Int, x0: T, c: Check[T]): Unit ={ + check(xs.length == l, xs.length, l); + check(xs(0) == x0, xs(0), x0); + check_Ta(xs, l, x0, c); + c(xs); + } + + def check_Tr[T <: AnyRef ](xs: Array[T], l: Int, x0: T, c: Check[T]): Unit ={ + check(xs.length == l, xs.length, l); + check(xs(0) == x0, xs(0), x0); + check_Ta(xs, l, x0, c); + c(xs); + } + + def check_To[T <: Object ](xs: Array[T], l: Int, x0: T, c: Check[T]): Unit ={ + check(xs.length == l, xs.length, l); + check(xs(0) == x0, xs(0), x0); + check_Ta(xs, l, x0, c); + check_Tr(xs, l, x0, c); + c(xs); + } + + def check_Tm[T <: Map ](xs: Array[T], l: Int, x0: T, c: Check[T]): Unit ={ + check(xs.length == l, xs.length, l); + check(xs(0) == x0, xs(0), x0); + check_Ta(xs, l, x0, c); + check_Tr(xs, l, x0, c); + check_To(xs, l, x0, c); + c(xs); + } + + def check_Tn[T <: Strings](xs: Array[T], l: Int, x0: T, c: Check[T]): Unit ={ + check(xs.length == l, xs.length, l); + check(xs(0) == x0, xs(0), x0); + check_Ta(xs, l, x0, c); + check_Tr(xs, l, x0, c); + check_To(xs, l, x0, c); + c(xs); + } + + //########################################################################## + // Values + + import scala.runtime.compat.Math._; + + val u0: Unit = (); + val u1: Unit = (); + + val z0: Boolean = false; + val z1: Boolean = true; + + val b0: Byte = MIN_BYTE; + val b1: Byte = 1; + val b2: Byte = MAX_BYTE; + + val s0: Short = MIN_SHORT; + val s1: Short = 2; + val s2: Short = MAX_SHORT; + + val c0: Char = MIN_CHAR; + val c1: Char = '3'; + val c2: Char = MAX_CHAR; + + val i0: Int = MIN_INT; + val i1: Int = 4; + val i2: Int = MAX_INT; + + val l0: Long = MIN_LONG; + val l1: Int = 5; + val l2: Long = MAX_LONG; + + val f0: Float = MIN_FLOAT; + val f1: Int = 6; + val f2: Float = MAX_FLOAT; + + val d0: Double = MIN_DOUBLE; + val d1: Int = 7; + val d2: Double = MAX_DOUBLE; + + val a0: Unit = (); + val a1: Boolean = false; + val a2: Int = 0; + val a3: AllRef = null; + val a4: String = "a-z"; + val a5: Symbol = 'token; + val a6: HashMap = new HashMap(); + val a7: TreeMap = scala.collection.immutable.TreeMap.Empty; + val a8: Strings = List("a", "z"); + + val v0: Unit = (); + val v1: Boolean = false; + val v2: Int = 0; + val v3: Long = l2; + val v4: Float = f2; + val v5: Double = d2; + + val r0: AllRef = a3; + val r1: String = a4; + val r2: Symbol = a5; + val r3: HashMap = a6; + val r4: TreeMap = a7; + val r5: Strings = a8; + + val o0: AllRef = r0; + val o1: String = r1; + val o2: Symbol = r2; + val o3: HashMap = r3; + val o4: TreeMap = r4; + val o5: Strings = r5; + + val m0: AllRef = r0; + val m1: HashMap = r3; + val m2: TreeMap = r4; + + val n0: AllRef = r0; + val n1: Strings = r5; + val n2: Nil.type= Nil; + + //########################################################################## + // Specific Checks + + def ucheck(xs: Array[Unit ]): Unit = { + check(xs.length == 2, xs.length, 2); + check(xs(0) == u0, xs(0), u0); + check(xs(1) == u1, xs(1), u1); + } + + def zcheck(xs: Array[Boolean]): Unit = { + check(xs.length == 2, xs.length, 2); + check(xs(0) == z0, xs(0), z0); + check(xs(1) == z1, xs(1), z1); + } + + def bcheck(xs: Array[Byte ]): Unit = { + check(xs.length == 3, xs.length, 3); + check(xs(0) == b0, xs(0), b0); + check(xs(1) == b1, xs(1), b1); + check(xs(2) == b2, xs(2), b2); + } + + def scheck(xs: Array[Short ]): Unit = { + check(xs.length == 3, xs.length, 3); + check(xs(0) == s0, xs(0), s0); + check(xs(1) == s1, xs(1), s1); + check(xs(2) == s2, xs(2), s2); + } + + def ccheck(xs: Array[Char ]): Unit = { + check(xs.length == 3, xs.length, 3); + check(xs(0) == c0, xs(0), c0); + check(xs(1) == c1, xs(1), c1); + check(xs(2) == c2, xs(2), c2); + } + + def icheck(xs: Array[Int ]): Unit = { + check(xs.length == 3, xs.length, 3); + check(xs(0) == i0, xs(0), i0); + check(xs(1) == i1, xs(1), i1); + check(xs(2) == i2, xs(2), i2); + } + + def lcheck(xs: Array[Long ]): Unit = { + check(xs.length == 3, xs.length, 3); + check(xs(0) == l0, xs(0), l0); + check(xs(1) == l1, xs(1), l1: Long); // !!! : Long + check(xs(2) == l2, xs(2), l2); + } + + def fcheck(xs: Array[Float ]): Unit = { + check(xs.length == 3, xs.length, 3); + check(xs(0) == f0, xs(0), f0); + check(xs(1) == f1, xs(1), f1: Float); // !!! : Float + check(xs(2) == f2, xs(2), f2); + } + + def dcheck(xs: Array[Double ]): Unit = { + check(xs.length == 3, xs.length, 3); + check(xs(0) == d0, xs(0), d0); + check(xs(1) == d1, xs(1), d1: Double); // !!! : Double + check(xs(2) == d2, xs(2), d2); + } + + def rcheck(xs: Array[AnyRef ]): Unit = { + check(xs.length == 6, xs.length, 6); + check(xs(0) == r0, xs(0), r0); + check(xs(1) == r1, xs(1), r1); + check(xs(2) == r2, xs(2), r2); + check(xs(3) == r3, xs(3), r3); + check(xs(4) == r4, xs(4), r4); + check(xs(5) == r5, xs(5), r5); + } + + def ocheck(xs: Array[Object ]): Unit = { + check(xs.length == 6, xs.length, 6); + check(xs(0) == o0, xs(0), o0); + check(xs(1) == o1, xs(1), o1); + check(xs(2) == o2, xs(2), o2); + check(xs(3) == o3, xs(3), o3); + check(xs(4) == o4, xs(4), o4); + check(xs(5) == o5, xs(5), o5); + } + + def mcheck(xs: Array[Map ]): Unit = { + check(xs.length == 3, xs.length, 3); + check(xs(0) == m0, xs(0), m0); + check(xs(1) == m1, xs(1), m1); + check(xs(2) == m2, xs(2), m2); + } + + def ncheck(xs: Array[Strings]): Unit = { + check(xs.length == 3, xs.length, 3); + check(xs(0) == n0, xs(0), n0); + check(xs(1) == n1, xs(1), n1); + check(xs(2) == n2, xs(2), n2); + } + + //########################################################################## + // Arrays + + val uarray: Array[Unit ] = Array(u0, u1); + val zarray: Array[Boolean] = Array(z0, z1); + val barray: Array[Byte ] = Array(b0, b1, b2); + val sarray: Array[Short ] = Array(s0, s1, s2); + val carray: Array[Char ] = Array(c0, c1, c2); + val iarray: Array[Int ] = Array(i0, i1, i2); + val larray: Array[Long ] = Array(l0, l1, l2); + val farray: Array[Float ] = Array(f0, f1, f2); + val darray: Array[Double ] = Array(d0, d1, d2); + val rarray: Array[AnyRef ] = Array(r0, r1, r2, r4, r4, r5); + val oarray: Array[Object ] = Array(o0, o1, o2, o4, o4, o5); + val marray: Array[Map ] = Array(m0, m1, m2); + val narray: Array[Strings] = Array(n0, n1, n2); + + //########################################################################## + // Main + + def main(args: Array[String]): Unit = { + + //###################################################################### + + ucheck(uarray); + zcheck(zarray); + bcheck(barray); + scheck(sarray); + ccheck(carray); + icheck(iarray); + lcheck(larray); + fcheck(farray); + dcheck(darray); + rcheck(rarray); + ocheck(oarray); + mcheck(marray); + ncheck(narray); + + //###################################################################### + + ucheck(id_Ta_T(uarray)); + zcheck(id_Ta_T(zarray)); + bcheck(id_Ta_T(barray)); + scheck(id_Ta_T(sarray)); + ccheck(id_Ta_T(carray)); + icheck(id_Ta_T(iarray)); + lcheck(id_Ta_T(larray)); + fcheck(id_Ta_T(farray)); + dcheck(id_Ta_T(darray)); + rcheck(id_Ta_T(rarray)); + ocheck(id_Ta_T(oarray)); + mcheck(id_Ta_T(marray)); + ncheck(id_Ta_T(narray)); + + ucheck(id_Tr_T(uarray)); + zcheck(id_Tr_T(zarray)); + bcheck(id_Tr_T(barray)); + scheck(id_Tr_T(sarray)); + ccheck(id_Tr_T(carray)); + icheck(id_Tr_T(iarray)); + lcheck(id_Tr_T(larray)); + fcheck(id_Tr_T(farray)); + dcheck(id_Tr_T(darray)); + rcheck(id_Tr_T(rarray)); + ocheck(id_Tr_T(oarray)); + mcheck(id_Tr_T(marray)); + ncheck(id_Tr_T(narray)); + + ucheck(id_To_T(uarray)); + zcheck(id_To_T(zarray)); + bcheck(id_To_T(barray)); + scheck(id_To_T(sarray)); + ccheck(id_To_T(carray)); + icheck(id_To_T(iarray)); + lcheck(id_To_T(larray)); + fcheck(id_To_T(farray)); + dcheck(id_To_T(darray)); + rcheck(id_To_T(rarray)); + ocheck(id_To_T(oarray)); + mcheck(id_To_T(marray)); + ncheck(id_To_T(narray)); + + ucheck(id_Ta_a(uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_Ta_a(zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_Ta_a(barray).asInstanceOf[Array[Byte ]]); + scheck(id_Ta_a(sarray).asInstanceOf[Array[Short ]]); + ccheck(id_Ta_a(carray).asInstanceOf[Array[Char ]]); + icheck(id_Ta_a(iarray).asInstanceOf[Array[Int ]]); + lcheck(id_Ta_a(larray).asInstanceOf[Array[Long ]]); + fcheck(id_Ta_a(farray).asInstanceOf[Array[Float ]]); + dcheck(id_Ta_a(darray).asInstanceOf[Array[Double ]]); + rcheck(id_Ta_a(rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_Ta_a(oarray).asInstanceOf[Array[Object ]]); + mcheck(id_Ta_a(marray).asInstanceOf[Array[Map ]]); + ncheck(id_Ta_a(narray).asInstanceOf[Array[Strings]]); + + ucheck(id_Tr_a(uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_Tr_a(zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_Tr_a(barray).asInstanceOf[Array[Byte ]]); + scheck(id_Tr_a(sarray).asInstanceOf[Array[Short ]]); + ccheck(id_Tr_a(carray).asInstanceOf[Array[Char ]]); + icheck(id_Tr_a(iarray).asInstanceOf[Array[Int ]]); + lcheck(id_Tr_a(larray).asInstanceOf[Array[Long ]]); + fcheck(id_Tr_a(farray).asInstanceOf[Array[Float ]]); + dcheck(id_Tr_a(darray).asInstanceOf[Array[Double ]]); + rcheck(id_Tr_a(rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_Tr_a(oarray).asInstanceOf[Array[Object ]]); + mcheck(id_Tr_a(marray).asInstanceOf[Array[Map ]]); + ncheck(id_Tr_a(narray).asInstanceOf[Array[Strings]]); + + ucheck(id_To_a(uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_To_a(zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_To_a(barray).asInstanceOf[Array[Byte ]]); + scheck(id_To_a(sarray).asInstanceOf[Array[Short ]]); + ccheck(id_To_a(carray).asInstanceOf[Array[Char ]]); + icheck(id_To_a(iarray).asInstanceOf[Array[Int ]]); + lcheck(id_To_a(larray).asInstanceOf[Array[Long ]]); + fcheck(id_To_a(farray).asInstanceOf[Array[Float ]]); + dcheck(id_To_a(darray).asInstanceOf[Array[Double ]]); + rcheck(id_To_a(rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_To_a(oarray).asInstanceOf[Array[Object ]]); + mcheck(id_To_a(marray).asInstanceOf[Array[Map ]]); + ncheck(id_To_a(narray).asInstanceOf[Array[Strings]]); + + ucheck(id_Tr_r(uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_Tr_r(zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_Tr_r(barray).asInstanceOf[Array[Byte ]]); + scheck(id_Tr_r(sarray).asInstanceOf[Array[Short ]]); + ccheck(id_Tr_r(carray).asInstanceOf[Array[Char ]]); + icheck(id_Tr_r(iarray).asInstanceOf[Array[Int ]]); + lcheck(id_Tr_r(larray).asInstanceOf[Array[Long ]]); + fcheck(id_Tr_r(farray).asInstanceOf[Array[Float ]]); + dcheck(id_Tr_r(darray).asInstanceOf[Array[Double ]]); + rcheck(id_Tr_r(rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_Tr_r(oarray).asInstanceOf[Array[Object ]]); + mcheck(id_Tr_r(marray).asInstanceOf[Array[Map ]]); + ncheck(id_Tr_r(narray).asInstanceOf[Array[Strings]]); + + ucheck(id_To_r(uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_To_r(zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_To_r(barray).asInstanceOf[Array[Byte ]]); + scheck(id_To_r(sarray).asInstanceOf[Array[Short ]]); + ccheck(id_To_r(carray).asInstanceOf[Array[Char ]]); + icheck(id_To_r(iarray).asInstanceOf[Array[Int ]]); + lcheck(id_To_r(larray).asInstanceOf[Array[Long ]]); + fcheck(id_To_r(farray).asInstanceOf[Array[Float ]]); + dcheck(id_To_r(darray).asInstanceOf[Array[Double ]]); + rcheck(id_To_r(rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_To_r(oarray).asInstanceOf[Array[Object ]]); + mcheck(id_To_r(marray).asInstanceOf[Array[Map ]]); + ncheck(id_To_r(narray).asInstanceOf[Array[Strings]]); + + ucheck(id_To_o(uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_To_o(zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_To_o(barray).asInstanceOf[Array[Byte ]]); + scheck(id_To_o(sarray).asInstanceOf[Array[Short ]]); + ccheck(id_To_o(carray).asInstanceOf[Array[Char ]]); + icheck(id_To_o(iarray).asInstanceOf[Array[Int ]]); + lcheck(id_To_o(larray).asInstanceOf[Array[Long ]]); + fcheck(id_To_o(farray).asInstanceOf[Array[Float ]]); + dcheck(id_To_o(darray).asInstanceOf[Array[Double ]]); + rcheck(id_To_o(rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_To_o(oarray).asInstanceOf[Array[Object ]]); + mcheck(id_To_o(marray).asInstanceOf[Array[Map ]]); + ncheck(id_To_o(narray).asInstanceOf[Array[Strings]]); + + //###################################################################### + + ucheck(id_TSa_T [Unit , Array[Unit ]](uarray)); + zcheck(id_TSa_T [Boolean, Array[Boolean]](zarray)); + bcheck(id_TSa_T [Byte , Array[Byte ]](barray)); + scheck(id_TSa_T [Short , Array[Short ]](sarray)); + ccheck(id_TSa_T [Char , Array[Char ]](carray)); + icheck(id_TSa_T [Int , Array[Int ]](iarray)); + lcheck(id_TSa_T [Long , Array[Long ]](larray)); + fcheck(id_TSa_T [Float , Array[Float ]](farray)); + dcheck(id_TSa_T [Double , Array[Double ]](darray)); + rcheck(id_TSa_T [AnyRef , Array[AnyRef ]](rarray)); + ocheck(id_TSa_T [Object , Array[Object ]](oarray)); + mcheck(id_TSa_T [Map , Array[Map ]](marray)); + ncheck(id_TSa_T [Strings, Array[Strings]](narray)); + + ucheck(id_TSv_T [Unit , Array[Unit ]](uarray)); + zcheck(id_TSv_T [Boolean, Array[Boolean]](zarray)); + bcheck(id_TSv_T [Byte , Array[Byte ]](barray)); + scheck(id_TSv_T [Short , Array[Short ]](sarray)); + ccheck(id_TSv_T [Char , Array[Char ]](carray)); + icheck(id_TSv_T [Int , Array[Int ]](iarray)); + lcheck(id_TSv_T [Long , Array[Long ]](larray)); + fcheck(id_TSv_T [Float , Array[Float ]](farray)); + dcheck(id_TSv_T [Double , Array[Double ]](darray)); + + rcheck(id_TSr_T [AnyRef , Array[AnyRef ]](rarray)); + ocheck(id_TSr_T [Object , Array[Object ]](oarray)); + mcheck(id_TSr_T [Map , Array[Map ]](marray)); + ncheck(id_TSr_T [Strings, Array[Strings]](narray)); + + rcheck(id_TSo_T [AnyRef , Array[AnyRef ]](rarray)); + ocheck(id_TSo_T [Object , Array[Object ]](oarray)); + mcheck(id_TSo_T [Map , Array[Map ]](marray)); + ncheck(id_TSo_T [Strings, Array[Strings]](narray)); + + mcheck(id_TSm_T [Map , Array[Map ]](marray)); + + ncheck(id_TSn_T [Strings, Array[Strings]](narray)); + + //###################################################################### + + ucheck(id_TSa_Ss[Unit , Array[Unit ]](uarray)); + zcheck(id_TSa_Ss[Boolean, Array[Boolean]](zarray)); + bcheck(id_TSa_Ss[Byte , Array[Byte ]](barray)); + scheck(id_TSa_Ss[Short , Array[Short ]](sarray)); + ccheck(id_TSa_Ss[Char , Array[Char ]](carray)); + icheck(id_TSa_Ss[Int , Array[Int ]](iarray)); + lcheck(id_TSa_Ss[Long , Array[Long ]](larray)); + fcheck(id_TSa_Ss[Float , Array[Float ]](farray)); + dcheck(id_TSa_Ss[Double , Array[Double ]](darray)); + rcheck(id_TSa_Ss[AnyRef , Array[AnyRef ]](rarray)); + ocheck(id_TSa_Ss[Object , Array[Object ]](oarray)); + mcheck(id_TSa_Ss[Map , Array[Map ]](marray)); + ncheck(id_TSa_Ss[Strings, Array[Strings]](narray)); + + ucheck(id_TSv_Ss[Unit , Array[Unit ]](uarray)); + zcheck(id_TSv_Ss[Boolean, Array[Boolean]](zarray)); + bcheck(id_TSv_Ss[Byte , Array[Byte ]](barray)); + scheck(id_TSv_Ss[Short , Array[Short ]](sarray)); + ccheck(id_TSv_Ss[Char , Array[Char ]](carray)); + icheck(id_TSv_Ss[Int , Array[Int ]](iarray)); + lcheck(id_TSv_Ss[Long , Array[Long ]](larray)); + fcheck(id_TSv_Ss[Float , Array[Float ]](farray)); + dcheck(id_TSv_Ss[Double , Array[Double ]](darray)); + + rcheck(id_TSr_Ss[AnyRef , Array[AnyRef ]](rarray)); + ocheck(id_TSr_Ss[Object , Array[Object ]](oarray)); + mcheck(id_TSr_Ss[Map , Array[Map ]](marray)); + ncheck(id_TSr_Ss[Strings, Array[Strings]](narray)); + + rcheck(id_TSo_Ss[AnyRef , Array[AnyRef ]](rarray)); + ocheck(id_TSo_Ss[Object , Array[Object ]](oarray)); + mcheck(id_TSo_Ss[Map , Array[Map ]](marray)); + ncheck(id_TSo_Ss[Strings, Array[Strings]](narray)); + + mcheck(id_TSm_Ss[Map , Array[Map ]](marray)); + + ncheck(id_TSn_Ss[Strings, Array[Strings]](narray)); + + //###################################################################### + + ucheck(id_TSa_a [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSa_a [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSa_a [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSa_a [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSa_a [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSa_a [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSa_a [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSa_a [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSa_a [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + rcheck(id_TSa_a [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSa_a [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSa_a [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSa_a [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + ucheck(id_TSv_a [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSv_a [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSv_a [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSv_a [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSv_a [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSv_a [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSv_a [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSv_a [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSv_a [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + + rcheck(id_TSr_a [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSr_a [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSr_a [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSr_a [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + rcheck(id_TSo_a [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSo_a [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSo_a [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSo_a [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + mcheck(id_TSm_a [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + + ncheck(id_TSn_a [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + //###################################################################### + + ucheck(id_TSa_r [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSa_r [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSa_r [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSa_r [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSa_r [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSa_r [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSa_r [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSa_r [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSa_r [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + rcheck(id_TSa_r [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSa_r [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSa_r [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSa_r [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + ucheck(id_TSv_r [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSv_r [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSv_r [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSv_r [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSv_r [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSv_r [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSv_r [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSv_r [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSv_r [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + + rcheck(id_TSr_r [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSr_r [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSr_r [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSr_r [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + rcheck(id_TSo_r [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSo_r [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSo_r [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSo_r [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + mcheck(id_TSm_r [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + + ncheck(id_TSn_r [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + //###################################################################### + + ucheck(id_TSa_o [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSa_o [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSa_o [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSa_o [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSa_o [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSa_o [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSa_o [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSa_o [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSa_o [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + rcheck(id_TSa_o [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSa_o [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSa_o [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSa_o [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + ucheck(id_TSv_o [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSv_o [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSv_o [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSv_o [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSv_o [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSv_o [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSv_o [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSv_o [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSv_o [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + + rcheck(id_TSr_o [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSr_o [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSr_o [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSr_o [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + rcheck(id_TSo_o [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSo_o [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSo_o [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSo_o [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + mcheck(id_TSm_o [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + + ncheck(id_TSn_o [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + //###################################################################### + + ucheck(id_Sas_Ss[Unit ](uarray)); + zcheck(id_Sas_Ss[Boolean](zarray)); + bcheck(id_Sas_Ss[Byte ](barray)); + scheck(id_Sas_Ss[Short ](sarray)); + ccheck(id_Sas_Ss[Char ](carray)); + icheck(id_Sas_Ss[Int ](iarray)); + lcheck(id_Sas_Ss[Long ](larray)); + fcheck(id_Sas_Ss[Float ](farray)); + dcheck(id_Sas_Ss[Double ](darray)); + rcheck(id_Sas_Ss[AnyRef ](rarray)); + ocheck(id_Sas_Ss[Object ](oarray)); + mcheck(id_Sas_Ss[Map ](marray)); + ncheck(id_Sas_Ss[Strings](narray)); + + ucheck(id_Svs_Ss[Unit ](uarray)); + zcheck(id_Svs_Ss[Boolean](zarray)); + bcheck(id_Svs_Ss[Byte ](barray)); + scheck(id_Svs_Ss[Short ](sarray)); + ccheck(id_Svs_Ss[Char ](carray)); + icheck(id_Svs_Ss[Int ](iarray)); + lcheck(id_Svs_Ss[Long ](larray)); + fcheck(id_Svs_Ss[Float ](farray)); + dcheck(id_Svs_Ss[Double ](darray)); + + rcheck(id_Srs_Ss[AnyRef ](rarray)); + ocheck(id_Srs_Ss[Object ](oarray)); + mcheck(id_Srs_Ss[Map ](marray)); + ncheck(id_Srs_Ss[Strings](narray)); + + rcheck(id_Sos_Ss[AnyRef ](rarray)); + ocheck(id_Sos_Ss[Object ](oarray)); + mcheck(id_Sos_Ss[Map ](marray)); + ncheck(id_Sos_Ss[Strings](narray)); + + mcheck(id_Sms_Ss[Map ](marray)); + + ncheck(id_Sns_Ss[Strings](narray)); + + //###################################################################### + + ucheck(id_TSa_a [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSa_a [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSa_a [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSa_a [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSa_a [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSa_a [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSa_a [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSa_a [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSa_a [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + rcheck(id_TSa_a [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSa_a [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSa_a [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSa_a [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + ucheck(id_TSv_a [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSv_a [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSv_a [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSv_a [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSv_a [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSv_a [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSv_a [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSv_a [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSv_a [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + + rcheck(id_TSr_a [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSr_a [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSr_a [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSr_a [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + rcheck(id_TSo_a [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSo_a [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSo_a [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSo_a [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + mcheck(id_TSm_a [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + + ncheck(id_TSn_a [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + //###################################################################### + + ucheck(id_TSa_r [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSa_r [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSa_r [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSa_r [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSa_r [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSa_r [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSa_r [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSa_r [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSa_r [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + rcheck(id_TSa_r [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSa_r [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSa_r [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSa_r [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + ucheck(id_TSv_r [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSv_r [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSv_r [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSv_r [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSv_r [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSv_r [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSv_r [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSv_r [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSv_r [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + + rcheck(id_TSr_r [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSr_r [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSr_r [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSr_r [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + rcheck(id_TSo_r [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSo_r [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSo_r [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSo_r [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + mcheck(id_TSm_r [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + + ncheck(id_TSn_r [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + //###################################################################### + + ucheck(id_TSa_o [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSa_o [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSa_o [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSa_o [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSa_o [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSa_o [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSa_o [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSa_o [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSa_o [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + rcheck(id_TSa_o [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSa_o [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSa_o [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSa_o [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + ucheck(id_TSv_o [Unit , Array[Unit ]](uarray).asInstanceOf[Array[Unit ]]); + zcheck(id_TSv_o [Boolean, Array[Boolean]](zarray).asInstanceOf[Array[Boolean]]); + bcheck(id_TSv_o [Byte , Array[Byte ]](barray).asInstanceOf[Array[Byte ]]); + scheck(id_TSv_o [Short , Array[Short ]](sarray).asInstanceOf[Array[Short ]]); + ccheck(id_TSv_o [Char , Array[Char ]](carray).asInstanceOf[Array[Char ]]); + icheck(id_TSv_o [Int , Array[Int ]](iarray).asInstanceOf[Array[Int ]]); + lcheck(id_TSv_o [Long , Array[Long ]](larray).asInstanceOf[Array[Long ]]); + fcheck(id_TSv_o [Float , Array[Float ]](farray).asInstanceOf[Array[Float ]]); + dcheck(id_TSv_o [Double , Array[Double ]](darray).asInstanceOf[Array[Double ]]); + + rcheck(id_TSr_o [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSr_o [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSr_o [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSr_o [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + rcheck(id_TSo_o [AnyRef , Array[AnyRef ]](rarray).asInstanceOf[Array[AnyRef ]]); + ocheck(id_TSo_o [Object , Array[Object ]](oarray).asInstanceOf[Array[Object ]]); + mcheck(id_TSo_o [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + ncheck(id_TSo_o [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + mcheck(id_TSm_o [Map , Array[Map ]](marray).asInstanceOf[Array[Map ]]); + + ncheck(id_TSn_o [Strings, Array[Strings]](narray).asInstanceOf[Array[Strings]]); + + //###################################################################### + + check_Ta(uarray, 2, u0, ucheck); + check_Ta(zarray, 2, z0, zcheck); + check_Ta(barray, 3, b0, bcheck); + check_Ta(sarray, 3, s0, scheck); + check_Ta(carray, 3, c0, ccheck); + check_Ta(iarray, 3, i0, icheck); + check_Ta(larray, 3, l0, lcheck); + check_Ta(farray, 3, f0, fcheck); + check_Ta(darray, 3, d0, dcheck); + check_Ta(rarray, 6, r0, rcheck); + check_Ta(oarray, 6, o0, ocheck); + check_Ta(marray, 3, m0, mcheck); + check_Ta(narray, 3, n0, ncheck); + + check_Tv(uarray, 2, u0, ucheck); + check_Tv(zarray, 2, z0, zcheck); + check_Tv(barray, 3, b0, bcheck); + check_Tv(sarray, 3, s0, scheck); + check_Tv(carray, 3, c0, ccheck); + check_Tv(iarray, 3, i0, icheck); + check_Tv(larray, 3, l0, lcheck); + check_Tv(farray, 3, f0, fcheck); + check_Tv(darray, 3, d0, dcheck); + + check_Tr(rarray, 6, r0, rcheck); + check_Tr(oarray, 6, o0, ocheck); + check_Tr(marray, 3, m0, mcheck); + check_Tr(narray, 3, n0, ncheck); + + check_To(rarray, 6, r0, rcheck); + check_To(oarray, 6, o0, ocheck); + check_To(marray, 3, m0, mcheck); + check_To(narray, 3, n0, ncheck); + + check_Tm(marray, 3, m0, mcheck); + + check_Tn(narray, 3, n0, ncheck); + + //###################################################################### + + Console.println("checks: " + checks); + + //###################################################################### + } + + //########################################################################## +} diff --git a/test-nsc/files/run/boolexprs.scala b/test-nsc/files/run/boolexprs.scala new file mode 100755 index 0000000000..7080f84b56 --- /dev/null +++ b/test-nsc/files/run/boolexprs.scala @@ -0,0 +1,61 @@ +//############################################################################ +// Boolean Expressions +//############################################################################ +// $Id$ + +class Counter { + private var n: Int = 0; + def incrThen(b: Boolean) = if (b) n = n + 1; + def value = n; +} + +object Test1 { + var flag = false; + def flip: boolean = { val tmp = flag; flag = !flag; tmp } + def run: Int = { + val c = new Counter; + c.incrThen(flip || flip); + c.value + } +} + +object Test2 { + val a = Array(false); + + def run: Int = { + val c = new Counter; + c.incrThen(true && a(0)); + c.incrThen(false || Nil.length > 0); + c.value + } +} + +//############################################################################ +// Test code + +object Test { + def check_success(name: String, closure: => Int, expected: Int): Unit = { + Console.print("test " + name); + try { + val actual: Int = closure; + if (actual == expected) { + Console.print(" was successful"); + } else { + Console.print(" failed: expected "+ expected +", found "+ actual); + } + } catch { + case exception: Throwable => { + Console.print(" raised exception " + exception); + } + } + Console.println; + } + + def main(args: Array[String]): Unit = { + check_success("Test1", Test1.run, 1); + check_success("Test2", Test2.run, 0); + Console.println; + } +} + +//############################################################################ diff --git a/test-nsc/files/run/bugs.scala b/test-nsc/files/run/bugs.scala new file mode 100755 index 0000000000..18c17c1501 --- /dev/null +++ b/test-nsc/files/run/bugs.scala @@ -0,0 +1,512 @@ +//############################################################################ +// Bugs +//############################################################################ +// $Id$ + +//############################################################################ +// serves as an entry point with the MSIL backend + +object TestMain { + def main(args: Array[String]): Unit = { + Test.main(args); + } +} + +//############################################################################ +// Bug 98 + +object Bug98Test { + object MyCase { def name = "mycase" }; + def main(args: Array[String]) = { + Console.println(MyCase.name); + } +} + +//############################################################################ +// Bug 120 + +class Bug120A(x: Int) { + Console.println("A"); +} +<<<<<<< bugs.scala +trait Bug120B { + System.out.println("B"); +======= +class Bug120B(x: Int) { + Console.println("B"); +>>>>>>> 1.25 +} +class Bug120C(x: Int) +<<<<<<< bugs.scala + extends Bug120A(Bug120Test.print("one", 1)) + with Bug120B { + System.out.println("C"); +======= + with Bug120A(Bug120Test.print("one", 1)) + with Bug120B(Bug120Test.print("two", 2)) { + Console.println("C"); +>>>>>>> 1.25 +} +object Bug120Test { + def print[A](str: String, res: A): A = { + Console.println(str); res + } + def main(args: Array[String]) = { + val c = new Bug120C(1); + } +} + +//############################################################################ +// Bug 135 + +object Bug135Test { + + import scala.collection.immutable.TreeMap; + + def main(args: Array[String]): Unit = { + val myMap:TreeMap[int,String] = new TreeMap; + val map1 = myMap + 42 -> "The answer"; + Console.println(map1.get(42)); + } + +} + +//############################################################################ +// Bug 142 + +abstract class Bug142Foo1 { class Inner; def foo: Inner; foo; } +abstract class Bug142Foo2 { class Inner; def foo: Inner = {Console.println("ok"); null};} +abstract class Bug142Foo3 { type Inner; def foo: Inner; foo; } +abstract class Bug142Foo4 { type Inner; def foo: Inner = {Console.println("ok"); null.asInstanceOf[Inner]}; } + +<<<<<<< bugs.scala +trait Bug142Bar1 { type Inner; def foo: Inner = {System.out.println("ok"); null.asInstanceOf[Inner]}; } +trait Bug142Bar2 { type Inner; def foo: Inner; foo; } +trait Bug142Bar3 { class Inner; def foo: Inner = {System.out.println("ok"); null}; } +trait Bug142Bar4 { class Inner; def foo: Inner; foo; } +======= +abstract class Bug142Bar1 { type Inner; def foo: Inner = {Console.println("ok"); null.asInstanceOf[Inner]}; } +abstract class Bug142Bar2 { type Inner; def foo: Inner; foo; } +abstract class Bug142Bar3 { class Inner; def foo: Inner = {Console.println("ok"); null}; } +abstract class Bug142Bar4 { class Inner; def foo: Inner; foo; } +>>>>>>> 1.25 + +object Bug142Test1 extends Bug142Foo1 with Bug142Bar1 {def main(args:Array[String]):Unit=();} +object Bug142Test2 extends Bug142Foo2 with Bug142Bar2 {def main(args:Array[String]):Unit=();} +object Bug142Test3 extends Bug142Foo3 with Bug142Bar3 {def main(args:Array[String]):Unit=();} +object Bug142Test4 extends Bug142Foo4 with Bug142Bar4 {def main(args:Array[String]):Unit=();} +object Bug142Test5 extends Bug142Foo1 with Bug142Bar1 {def main(args:Array[String]):Unit=();} +object Bug142Test6 extends Bug142Foo2 with Bug142Bar2 {def main(args:Array[String]):Unit=();} +object Bug142Test7 extends Bug142Foo3 with Bug142Bar3 {def main(args:Array[String]):Unit=();} +object Bug142Test8 extends Bug142Foo4 with Bug142Bar4 {def main(args:Array[String]):Unit=();} + +object Bug142Test { + def main(args:Array[String]): Unit = { + Bug142Test1; + Bug142Test2; + Bug142Test3; + Bug142Test4; + Bug142Test5; + Bug142Test6; + Bug142Test7; + Bug142Test8; + () + } +} + +//############################################################################ +// Bug 166 + +object Bug166Test { + import scala.collection.mutable.HashMap ; + def main(args:Array[String]) = { + val m:HashMap[String,String] = new HashMap[String,String]; + m.update("foo","bar"); + } +} + +//############################################################################ +// Bug 167 + +class Bug167Node(bar:Int) { + val foo = { + val bar = 1; + bar + } +} + +object Bug167Test { + def main(args: Array[String]): Unit = { + if (new Bug167Node(0).foo != 1) Console.println("bug 167"); + } +} + +//############################################################################ +// Bug 168 + +class Bug168Foo { + class Bar; + def foo = new Bar; +} + +object Bug168Test { + def main(args: Array[String]): Unit = { + (new Bug168Foo).foo; + () + } +} + +//############################################################################ +// Bug 174 + +class Bug174Foo[X] { + + class Tree; + class Node extends Tree; + + + val inner:Inner = new SubInner; + + trait Inner { + def test: Bug174Foo[X]#Tree ; + } + + class SubInner extends Inner { + def test = new Node; + } + +} + +object Bug174Test { + def main(args: Array[String]): Unit = { + (new Bug174Foo[Int]).inner.test; + () + } +} + + +//############################################################################ +// Bug 176 + +trait Bug176A { + type T; + def foo(x: T): Int; + def bar: T; + def test = foo(bar); +} +trait Bug176B { + type S <: Object; + type T = S; + def foo(x: S): Int; + def bar: S; +} +class Bug176C extends Bug176A with Bug176B { + class S; + def foo(x: S) = 1; + def bar = new S; +} +object Bug176Test { + def main(args: Array[String]): Unit = { + val x: Bug176A = new Bug176C; + Console.println(x.test); + } +} + +//############################################################################ +// Bug 199 + +class Bug199C { object o; } +object Bug199Test { + def main(args: Array[String]) = { + (new Bug199C).o; () + } +} + +//############################################################################ +// Bug 213 + +trait Bug213Foo { + def testAll: Unit; + def testAllRef: String; +} + +class Bug213Bar extends Bug213Foo { + def testAll = (().asInstanceOf[All] : All); + def testAllRef = ("".asInstanceOf[AllRef] : AllRef); +} + +object Bug213Test { + def main(args: Array[String]): Unit = { + val foo: Bug213Foo = new Bug213Bar; + foo.testAll; + foo.testAllRef; + () + } +} + +//############################################################################ +// Bug 217 + +object Bug217Test { + def foo[t](fun: Function0[t]): t = fun(); + def bar(x: Int): Unit = { + foo(() => 0); + () + } + def main(args: Array[String]): Unit = bar(32); +} + +//############################################################################ +// Bug 222 + +object Bug222Test { + def main(args:Array[String]): Unit = { + val array: Array[String] = new Array(16); + () + } +} + +//############################################################################ +// Bug 225 + +case class Bug225C(); + +object Bug225Test { + + def main(args: Array[String]): Unit = { + val a = new Array[Array[Bug225C]](2); + a(0) = new Array[Bug225C](2); + a(0)(0) = new Bug225C(); + } +} + +//############################################################################ +// Bug 226 + +object Bug226Test { + + def id[a](xs: Array[a]): Array[a] = xs; + + def main(args: Array[String]): Unit = { + var xs = new Array[Int](1); + class X { xs }; + xs = id(xs); + id(xs); + () + } + +} + +//############################################################################ +// Bug 233 + +object Bug233Test { + val b: Array[String] = null; + def main(args: Array[String]): Unit = + Console.println(b == null); +} + +//############################################################################ +// Bug 250 + +object Bug250Test { + def main(args: Array[String]): Unit = { + if (true) null; + () + } +} + +//############################################################################ +// Bug 257 + +object Bug257Test { + def sayhello(): Unit = { Console.println("hello"); }; + + def f1(x: Unit): Unit = (); + def f2(x: Unit)(y: Unit): Unit = (); + + def f(x: => Unit) = { + f1(x); + f2(x); + } + + def main(args: Array[String]): Unit = { + f(sayhello()) + } +} + +//############################################################################ +// Bug 266 + +// version - A + +abstract class Bug266AFoo { + type T <: AnyRef; + abstract class I0 { def f(x: T): Unit; f(null); } +} + +object Bug266ATest extends Bug266AFoo { + type T = String; + class I1 extends I0 { def f(x: String): Unit = { Console.println("hello"); ();} } + def main(args: Array[String]): Unit = { new I1; () } +} + +// version - B + +abstract class Bug266BA { + type t; + abstract class P { + def f(x: t): unit; + } +} + +abstract class Bug266BA1 extends Bug266BA { + def mkP: Bug266BA1.this.P; + val in: t; +} + +trait Bug266BB extends Bug266BA { + type t = int; + class P1 extends Bug266BB.this.P { + def f(x: int): unit = Console.println(x + 1); + } + def mkP = new P1; + val in = 3; +} + +object Bug266BTest extends Application { + val a: Bug266BA1 = new Bug266BA1 with Bug266BB; + a.mkP.f(a.in); +} + +// main + +object Bug266Test { + def main(args: Array[String]): Unit = { + Bug266ATest.main(args); + Bug266BTest.main(args); + } +} + +//############################################################################ +// Bug 316 + +class Bug316MyIterator extends Iterator[Int] { + def hasNext = false; + def next = 42; +} + +object Bug316Test { + def main(args: Array[String]): Unit = + (new Bug316MyIterator) filter { x: Int => x == 1 }; +} + +//############################################################################ +// Bug 328 + +object Bug328Test { + def test(f: Function1[Int,String]): Unit = (); + def main(args: Array[String]): Unit = test(args); +} + +//############################################################################ +// Bug 396 + +trait Bug396A { + class I { + def run = Console.println("A"); + } +} +trait Bug396B extends Bug396A { + class I extends super.I { + override def run = { super.run; Console.println("B"); } + } +} +<<<<<<< bugs.scala +trait Bug396C extends Bug396A { + trait I extends super.I { + override def run = { super.run; System.out.println("C"); } +======= +class Bug396C extends Bug396A { + class I extends super.I { + override def run = { super.run; Console.println("C"); } +>>>>>>> 1.25 + } +} +object Bug396Test extends Application with Bug396B with Bug396C { + class I2 extends super[Bug396B].I with super[Bug396C].I; + (new I2).run +} + +//############################################################################ +// Bug 399 + +object Bug399Test { + def f(x: String): String = { + trait C { def f: String = x; } + class D extends C; + trait F extends C; + class G extends D with F; + (new G).f + } + + def main(args: Array[String]): Unit = { + Console.println(f("a")); + } +} + +//############################################################################ +// Main + +object Test { + var errors: Int = 0; + def test(bug: Int, test: => Unit): Unit = { + Console.println("<<< bug " + bug); + try { + test; + } catch { + case exception => { + val curr: String = scala.runtime.compat.Platform.currentThread.toString(); + Console.print("Exception in thread \"" + curr + "\" " + exception); + Console.println; + errors = errors + 1; + } + } + Console.println(">>> bug " + bug); + Console.println; + } + + def main(args: Array[String]): Unit = { + + test( 98, Bug98Test.main(args)); + test(120, Bug120Test.main(args)); + test(135, Bug135Test.main(args)); + test(142, Bug142Test.main(args)); + test(166, Bug166Test.main(args)); + test(167, Bug167Test.main(args)); + test(168, Bug168Test.main(args)); + test(174, Bug174Test.main(args)); + test(176, Bug176Test.main(args)); + test(199, Bug199Test.main(args)); + test(213, Bug213Test.main(args)); + test(217, Bug217Test.main(args)); + test(222, Bug222Test.main(args)); + test(225, Bug225Test.main(args)); + test(226, Bug226Test.main(args)); + test(233, Bug233Test.main(args)); + test(250, Bug250Test.main(args)); + test(257, Bug257Test.main(args)); + test(266, Bug266Test.main(args)); + test(316, Bug316Test.main(args)); + test(328, Bug328Test.main(args)); + test(396, Bug396Test.main(args)); + test(399, Bug399Test.main(args)); + + if (errors > 0) { + Console.println; + Console.println(errors + " error" + (if (errors > 1) "s" else "")); + } + } +} + +//############################################################################ diff --git a/test-nsc/files/run/constructors.scala b/test-nsc/files/run/constructors.scala new file mode 100755 index 0000000000..e85f3b8667 --- /dev/null +++ b/test-nsc/files/run/constructors.scala @@ -0,0 +1,29 @@ +// $Id$ + +// Test constructors, including multiple ones. + +class A(x: Int, y: Int) { + def this(x: Int) = this(x, x); + def this() = this(1); + override def toString() = "x=" + x + " y=" + y; + class B(a: Int, b: Int, c: String) { + def this(str: String) = this(x, y, str); + override def toString() = + "x=" + x + " y=" + y + " a=" + a + " b=" + b + " c=" + c; + } +} + +object Test { + def main(args: Array[String]): Unit = { + val a1 = new A(1,2); + val a2 = new A(3); + val a3 = new A(); + val b1 = new a1.B(1,2,"a"); + val b2 = new a2.B("b"); + Console.println(a1); + Console.println(a2); + Console.println(a3); + Console.println(b1); + Console.println(b2); + } +} diff --git a/test-nsc/files/run/enums.scala b/test-nsc/files/run/enums.scala new file mode 100755 index 0000000000..2332fb87d4 --- /dev/null +++ b/test-nsc/files/run/enums.scala @@ -0,0 +1,80 @@ +//############################################################################ +// Enumerations +//############################################################################ +// $Id$ + +object Test1 { + + object WeekDays extends Enumeration { + val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value + } + + def isWorkingDay(d: WeekDays.Value) = + ! (d == WeekDays.Sat || d == WeekDays.Sun); + + def run: Int = { + val it = WeekDays filter (isWorkingDay); + it.toList.length + } +} + +object Test2 { + + object ThreadState extends Enumeration { + val New = Value("NEW"); + val Runnable = Value("RUNNABLE"); + val Blocked = Value("BLOCKED"); + val Waiting = Value("WAITING"); + val TimedWaiting = Value("TIMED_WAITING"); + val Terminated = Value("TERMINATED"); + } + + def run: Int = { + val it = for (val s <- ThreadState; s.id != 0) yield s; + it.toList.length + } +} + +object Test3 { + + object Direction extends Enumeration("North", "South", "East", "West") { + val North, South, East, West = Value; + } + + def run: Int = { + val it = for (val d <- Direction; d.toString() startsWith "N") yield d; + it.toList.length + } +} + +//############################################################################ +// Test code + +object Test { + + def check_success(name: String, closure: => Int, expected: Int): Unit = { + Console.print("test " + name); + try { + val actual: Int = closure; + if (actual == expected) { + Console.print(" was successful"); + } else { + Console.print(" failed: expected "+ expected +", found "+ actual); + } + } catch { + case exception: Throwable => { + Console.print(" raised exception " + exception); + } + } + Console.println; + } + + def main(args: Array[String]): Unit = { + check_success("Test1", Test1.run, 5); + check_success("Test2", Test2.run, 5); + check_success("Test3", Test3.run, 1); + Console.println; + } +} + +//############################################################################ diff --git a/test-nsc/files/run/exceptions.scala b/test-nsc/files/run/exceptions.scala new file mode 100755 index 0000000000..04fc4a1a85 --- /dev/null +++ b/test-nsc/files/run/exceptions.scala @@ -0,0 +1,53 @@ +//############################################################################ +// Exceptions +//############################################################################ +// $Id$ + +//############################################################################ + +abstract class IntMap[A] { + def lookup(key: Int): A = this match { + case Empty() => error("KO") + case _ => error("ok") + } +} + +case class Empty[A]() extends IntMap[A]; + +object exceptions { + + def check(what: String, actual: Any, expected: Any): Unit = { + val success: Boolean = actual == expected; + Console.print(if (success) "ok" else "KO"); + var value: String = if (actual == null) "null" else actual.toString(); + if (value == "\u0000") value = "\\u0000"; + Console.print(": " + what + " = " + value); + if (!success) Console.print(" != " + expected); + Console.println; + Console.flush; + } + + def test: Unit = { + val key = 2000; + val map: IntMap[String] = new Empty[String]; + val value = try { + map.lookup(key) + } catch { + case e => scala.runtime.compat.Platform.getMessage(e) + } + check("lookup(" + key + ")", value, "KO"); + } + +} + +//############################################################################ + +object Test { + + def main(args: Array[String]): Unit = { + exceptions.test; + } + +} + +//############################################################################ diff --git a/test-nsc/files/run/imports.scala b/test-nsc/files/run/imports.scala new file mode 100755 index 0000000000..d976478d8b --- /dev/null +++ b/test-nsc/files/run/imports.scala @@ -0,0 +1,97 @@ +//############################################################################ +// Import statements +//############################################################################ +// $Id$ + +//############################################################################ + +object checker { + def check(where: String, what: String, value: Any): Unit = { + Console.print("In " + where + ", " + what + ".toString() returns "); + Console.flush; + val string: String = if (value == null) "null" else value.toString(); + val test = if (string == where) "ok" else "KO"; + Console.println(string + " -> " + test); + Console.flush; + } +} + +import checker.check; + +//############################################################################ + +//import o_ico.v_ico; + +class C_ico() { + o_ico.v_ico = this; + import o_ico.v_ico; + override def toString(): String = "C_ico"; + def method: C_ico = v_ico; + val field: C_ico = v_ico; + + check("C_ico", "v_ico ", v_ico); + check("C_ico", "field ", field); + check("C_ico", "method", method); + Console.println; +} + +object o_ico { + var v_ico: C_ico = null; + new C_ico(); +} + +//############################################################################ + +object o_ioc { + var v_ioc: C_ioc = null; + new C_ioc(); +} + +import o_ioc.v_ioc; + + +class C_ioc() { + o_ioc.v_ioc = this; + override def toString(): String = "C_ioc"; + def method: C_ioc = v_ioc; + val field: C_ioc = v_ioc; + + check("C_ioc", "v_ioc ", v_ioc); + check("C_ioc", "field ", field); + check("C_ioc", "method", method); + Console.println; +} + +//############################################################################ + +object o_oic { + var v_oic: C_oic = null; + new C_oic(); +} + +import o_oic.v_oic; + +class C_oic() { + o_oic.v_oic = this; + override def toString(): String = "C_oic"; + def method: C_oic = v_oic; + val field: C_oic = v_oic; + + check("C_oic", "v_oic ", v_oic); + check("C_oic", "field ", field); + check("C_oic", "method", method); + Console.println; +} + +//############################################################################ + +object Test { + def main(args: Array[String]): Unit = { + o_ico; + o_ioc; + o_oic; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/iq.scala b/test-nsc/files/run/iq.scala new file mode 100755 index 0000000000..87bbe45cd7 --- /dev/null +++ b/test-nsc/files/run/iq.scala @@ -0,0 +1,100 @@ +/* $Id$ + * Test file for immutable queues. + */ + +import scala.collection.immutable.Queue; + +object iq { + def main = { + /* Create an empty queue. */ + val q:Queue[Int] = Queue.Empty; + + /* Test isEmpty. + * Expected: Empty + */ + if(q.isEmpty) { + Console.println("Empty"); + } + + /* Test infix enqueing. */ + val q2 = q + 42 + 0; + + /* Test is empty and dequeue. + * Expected: Head: 42 + */ + val q4 = + if(q2.isEmpty) { + Console.println("Empty"); + q2; + } else { + val Pair(head,q3) = q2.dequeue; + Console.println("Head: " + head); + q3; + }; + + /* Test sequence enqueing. */ + val q5:Queue[Any] = q4.enqueue(1,2,3,4,5,6,7,8,9); + /* Test toString. + * Expected: Head: q5: Queue(0,1,2,3,4,5,6,7,8,9) + */ + Console.println("q5: " + q5); + /* Test apply + * Expected: q5[5]: 5 + */ + Console.println("q5[5]: " + q5(5)); + + + + val q5c:Queue[int] = Queue.Empty.enqueue(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + + /* Testing == + * Expected: q5 == q9: true + * q9 == q5: true + */ + Console.println("q5 == q5c: " + (q5 == q5c)); + Console.println("q5c == q5: " + (q5c == q5)); + + val Pair(_,q6) = q5.dequeue; + val Pair(_,q7) = q6.dequeue; + val q8 = q7 + 10 + 11; + /* Test dequeu + * Expected: q8: Queue(2,3,4,5,6,7,8,9,10,11) + */ + Console.println("q8: " + q8); + val q9 = new Queue(2,3,4,5,6,7,8,9,10,11); + + /* Testing == + * Expected: q8 == q9: true + */ + Console.println("q8 == q9: " + (q8 == q9)); + + /* Testing elements + * Expected: Elements: 1 2 3 4 5 6 7 8 9 + */ + Console.print("Elements: "); + q6.elements.foreach(e => Console.print(" "+ e + " ")); + Console.println; + + /* Testing mkString + * Expected: String: <1-2-3-4-5-6-7-8-9> + */ + Console.println("String: " + q6.mkString("<","-",">")); + + /* Testing length + * Expected: Length: 9 + */ + Console.println("Length: " + q6.length); + + /* Testing front + * Expected: Front: 1 + */ + Console.println("Front: " + q6.front); + } +} + +object Test { + def main(args: Array[String]): Unit = { + iq.main; + (); + } +} diff --git a/test-nsc/files/run/iterators.scala b/test-nsc/files/run/iterators.scala new file mode 100644 index 0000000000..7d1e44a0df --- /dev/null +++ b/test-nsc/files/run/iterators.scala @@ -0,0 +1,79 @@ +//############################################################################ +// Iterators +//############################################################################ +// $Id$ + +//############################################################################ + +object Test { + + def check_from: Int = { + val it1 = Iterator.from(-1); + val it2 = Iterator.from(0, -1); + it1.next + it2.next + } + + def check_range: Int = { + val xs1 = Iterator.range(0, 10, 2) toList; + val xs2 = Iterator.range(0, 10, -2) toList; + val xs3 = Iterator.range(10, 0, -2) toList; + val xs4 = Iterator.range(10, 0, 2) toList; + xs1.length + xs2.length + xs3.length + xs4.length + } + + def check_take: Int = { + val it1 = Iterator.from(0); + val xs1 = it1 take 10 toList; + xs1.length + } + + def check_drop: Int = { + val it1 = Iterator.from(0); + val it2 = it1 map { x => 2 * x }; + val n1 = it1 drop 2 next; + val n2 = it2 drop 2 next; + n1 + n2 + } + + def check_foreach: Int = { + val it1 = Iterator.from(0) take 20; + var n = 0; + it1 foreach { x => n = n + x } + n + } + + def check_forall: Int = { + val it1 = Iterator.from(0); + val it2 = Iterator.from(1); + 0 + } + + def check_success[A](name: String, closure: => A, expected: A): Unit = { + Console.print("test " + name); + try { + val actual: A = closure; + if (actual == expected) + Console.print(" was successful"); + else + Console.print(" failed: expected "+ expected +", found "+ actual); + } + catch { + case exception: Throwable => { + Console.print(" raised exception " + exception); + } + } + Console.println; + } + + def main(args: Array[String]): Unit = { + check_success("check_from", check_from, -1); + check_success("check_range", check_range, 10); + check_success("check_take", check_take, 10); + check_success("check_drop", check_drop, 12); + check_success("check_foreach", check_foreach, 190); + check_success("check_forall", check_forall, 0); + Console.println; + } +} + +//############################################################################ diff --git a/test-nsc/files/run/lisp.scala b/test-nsc/files/run/lisp.scala new file mode 100755 index 0000000000..34c4e7c7cc --- /dev/null +++ b/test-nsc/files/run/lisp.scala @@ -0,0 +1,522 @@ +//############################################################################ +// Lisp interpreter +//############################################################################ +// $Id$ + +//############################################################################ +// Lisp Scanner + +class LispTokenizer(s: String) extends Iterator[String] { + private var i = 0; + private def isDelimiter(ch: Char) = ch <= ' ' || ch == '(' || ch == ')'; + def hasNext: Boolean = { + while (i < s.length() && s.charAt(i) <= ' ') { i = i + 1 } + i < s.length() + } + def next: String = + if (hasNext) { + val start = i; + var ch = s.charAt(i); i = i + 1; + if (ch == '(') "(" + else if (ch == ')') ")" + else { + while (i < s.length() && !isDelimiter(s.charAt(i))){ i = i + 1 } + s.substring(start, i) + } + } else error("premature end of string") +} + +//############################################################################ +// Lisp Interface + +trait Lisp { + type Data; + + def string2lisp(s: String): Data; + def lisp2string(s: Data): String; + + def evaluate(d: Data): Data; + // !!! def evaluate(s: String): Data = evaluate(string2lisp(s)); + def evaluate(s: String): Data; +} + +//############################################################################ +// Lisp Implementation Using Case Classes + +object LispCaseClasses extends Lisp { + + import List.range; + + trait Data { + def elemsToString(): String = toString(); + } + case class CONS(car: Data, cdr: Data) extends Data { + override def toString() = "(" + elemsToString() + ")"; + override def elemsToString() = car.toString() + (cdr match { + case NIL() => "" + case _ => " " + cdr.elemsToString(); + }) + } + case class NIL() extends Data { // !!! use case object + override def toString() = "()"; + } + case class SYM(name: String) extends Data { + override def toString() = name; + } + case class NUM(x: Int) extends Data { + override def toString() = x.toString(); + } + case class STR(x: String) extends Data { + override def toString() = "\"" + x + "\""; + } + case class FUN(f: List[Data] => Data) extends Data { + override def toString() = "<fn>"; + } + + def list(): Data = + NIL(); + def list(x0: Data): Data = + CONS(x0, NIL()); + def list(x0: Data, x1: Data): Data = + CONS(x0, list(x1)); + def list(x0: Data, x1: Data, x2: Data): Data = + CONS(x0, list(x1, x2)); + def list(x0: Data, x1: Data, x2: Data, x3: Data): Data = + CONS(x0, list(x1, x2, x3)); + def list(x0: Data, x1: Data, x2: Data, x3: Data, x4: Data): Data = + CONS(x0, list(x1, x2, x3, x4)); + def list(x0: Data, x1: Data, x2: Data, x3: Data, x4: Data, x5: Data): Data = + CONS(x0, list(x1, x2, x3, x4, x5)); + def list(x0: Data, x1: Data, x2: Data, x3: Data, x4: Data, x5: Data, + x6: Data): Data = + CONS(x0, list(x1, x2, x3, x4, x5, x6)); + def list(x0: Data, x1: Data, x2: Data, x3: Data, x4: Data, x5: Data, + x6: Data, x7: Data): Data = + CONS(x0, list(x1, x2, x3, x4, x5, x6, x7)); + def list(x0: Data, x1: Data, x2: Data, x3: Data, x4: Data, x5: Data, + x6: Data, x7: Data, x8: Data): Data = + CONS(x0, list(x1, x2, x3, x4, x5, x6, x7, x8)); + def list(x0: Data, x1: Data, x2: Data, x3: Data, x4: Data, x5: Data, + x6: Data, x7: Data, x8: Data, x9: Data): Data = + CONS(x0, list(x1, x2, x3, x4, x5, x6, x7, x8, x9)); + + var curexp: Data = null; + var trace: Boolean = false; + var indent: Int = 0; + + def lispError[a](msg: String): a = + error("error: " + msg + "\n" + curexp); + + trait Environment { + def lookup(n: String): Data; + def extendRec(name: String, expr: Environment => Data) = + new Environment { + def lookup(n: String): Data = + if (n == name) expr(this) else Environment.this.lookup(n); + } + def extend(name: String, v: Data) = extendRec(name, (env1 => v)); + } + val EmptyEnvironment = new Environment { + def lookup(n: String): Data = lispError("undefined: " + n); + } + + def toList(x: Data): List[Data] = x match { + case NIL() => List() + case CONS(y, ys) => y :: toList(ys) + case _ => lispError("malformed list: " + x); + } + + def toBoolean(x: Data) = x match { + case NUM(0) => false + case _ => true + } + + def normalize(x: Data): Data = x match { + case CONS(SYM("def"), + CONS(CONS(SYM(name), args), CONS(body, CONS(expr, NIL())))) => + normalize(list(SYM("def"), + SYM(name), list(SYM("lambda"), args, body), expr)) + case CONS(SYM("cond"), CONS(CONS(SYM("else"), CONS(expr, NIL())),NIL())) => + normalize(expr) + case CONS(SYM("cond"), CONS(CONS(test, CONS(expr, NIL())), rest)) => + normalize(list(SYM("if"), test, expr, CONS(SYM("cond"), rest))) + case CONS(h, t) => CONS(normalize(h), normalize(t)) + case _ => x + } + + def eval(x: Data, env: Environment): Data = { + val prevexp = curexp; + curexp = x; + if (trace) { + for (val x <- range(1, indent)) Console.print(" "); + Console.println("===> " + x); + indent = indent + 1; + } + val result = eval1(x, env); + if (trace) { + indent = indent - 1; + for (val x <- range(1, indent)) Console.print(" "); + Console.println("<=== " + result); + } + curexp = prevexp; + result + } + + def eval1(x: Data, env: Environment): Data = x match { + case SYM(name) => + env lookup name + case CONS(SYM("def"), CONS(SYM(name), CONS(y, CONS(z, NIL())))) => + eval(z, env.extendRec(name, (env1 => eval(y, env1)))) + case CONS(SYM("val"), CONS(SYM(name), CONS(y, CONS(z, NIL())))) => + eval(z, env.extend(name, eval(y, env))) + case CONS(SYM("lambda"), CONS(params, CONS(y, NIL()))) => + mkLambda(params, y, env) + case CONS(SYM("if"), CONS(c, CONS(t, CONS(e, NIL())))) => + if (toBoolean(eval(c, env))) eval(t, env) else eval(e, env) + case CONS(SYM("quote"), CONS(x, NIL())) => + x + case CONS(y, xs) => + apply(eval(y, env), toList(xs) map (x => eval(x, env))) + case NUM(_) => x + case STR(_) => x + case FUN(_) => x + case _ => + lispError("illegal term") + } + + def apply(fn: Data, args: List[Data]): Data = fn match { + case FUN(f) => f(args); + case _ => lispError("application of non-function: " + fn); + } + + def mkLambda(params: Data, expr: Data, env: Environment): Data = { + + def extendEnv(env: Environment, + ps: List[String], args: List[Data]): Environment = + Pair(ps, args) match { + case Pair(List(), List()) => + env + case Pair(p :: ps1, arg :: args1) => + extendEnv(env.extend(p, arg), ps1, args1) + case _ => + lispError("wrong number of arguments") + } + + val ps: List[String] = toList(params) map { + case SYM(name) => name + case _ => error("illegal parameter list"); + } + + FUN(args => eval(expr, extendEnv(env, ps, args))) + } + + val globalEnv = EmptyEnvironment + .extend("=", FUN({ + case List(NUM(arg1),NUM(arg2)) => NUM(if (arg1 == arg2) 1 else 0) + case List(STR(arg1),STR(arg2)) => NUM(if (arg1 == arg2) 1 else 0)})) + .extend("+", FUN({ + case List(NUM(arg1),NUM(arg2)) => NUM(arg1 + arg2) + case List(STR(arg1),STR(arg2)) => STR(arg1 + arg2)})) + .extend("-", FUN({ + case List(NUM(arg1),NUM(arg2)) => NUM(arg1 - arg2)})) + .extend("*", FUN({ + case List(NUM(arg1),NUM(arg2)) => NUM(arg1 * arg2)})) + .extend("/", FUN({ + case List(NUM(arg1),NUM(arg2)) => NUM(arg1 / arg2)})) + .extend("car", FUN({ + case List(CONS(x, xs)) => x})) + .extend("cdr", FUN({ + case List(CONS(x, xs)) => xs})) + .extend("null?", FUN({ + case List(NIL()) => NUM(1) + case _ => NUM(0)})) + .extend("cons", FUN({ + case List(x, y) => CONS(x, y)})); + + def evaluate(x: Data): Data = eval(normalize(x), globalEnv); + def evaluate(s: String): Data = evaluate(string2lisp(s)); + + def string2lisp(s: String): Data = { + val it = new LispTokenizer(s); + def parseExpr(token: String): Data = { + if (token == "(") parseList + else if (token == ")") error("unbalanced parentheses") + else if ('0' <= token.charAt(0) && token.charAt(0) <= '9') + NUM(scala.runtime.compat.Platform.parseInt(token)) + else if (token.charAt(0) == '\"' && token.charAt(token.length()-1)=='\"') + STR(token.substring(1,token.length() - 1)) + else SYM(token) + } + def parseList: Data = { + val token = it.next; + if (token == ")") NIL() else CONS(parseExpr(token), parseList) + } + parseExpr(it.next) + } + + def lisp2string(d: Data): String = d.toString(); +} + +//############################################################################ +// Lisp Implementation Using Any + +object LispAny extends Lisp { + + import List._; + + type Data = Any; + + case class Lambda(f: List[Data] => Data); + + var curexp: Data = null; + var trace: boolean = false; + var indent: int = 0; + + def lispError[a](msg: String): a = + error("error: " + msg + "\n" + curexp); + + trait Environment { + def lookup(n: String): Data; + def extendRec(name: String, expr: Environment => Data) = + new Environment { + def lookup(n: String): Data = + if (n == name) expr(this) else Environment.this.lookup(n); + } + def extend(name: String, v: Data) = extendRec(name, (env1 => v)); + } + val EmptyEnvironment = new Environment { + def lookup(n: String): Data = lispError("undefined: " + n); + } + + def asList(x: Data): List[Data] = x match { + case y: List[Data] => y + case _ => lispError("malformed list: " + x) + } + + def asInt(x: Data): int = x match { + case y: int => y + case _ => lispError("not an integer: " + x) + } + + def asString(x: Data): String = x match { + case y: String => y + case _ => lispError("not a string: " + x) + } + + def asBoolean(x: Data): boolean = + if (x == 0) false else true; + + def normalize(x: Data): Data = x match { + case 'and :: x :: y :: Nil => + normalize('if :: x :: y :: 0 :: Nil) + case 'or :: x :: y :: Nil => + normalize('if :: x :: 1 :: y :: Nil) + case 'def :: (name :: args) :: body :: expr :: Nil => + normalize('def :: name :: ('lambda :: args :: body :: Nil) :: expr :: Nil) + case 'cond :: ('else :: expr :: Nil) :: rest => + normalize(expr); + case 'cond :: (test :: expr :: Nil) :: rest => + normalize('if :: test :: expr :: ('cond :: rest) :: Nil) + case 'cond :: 'else :: expr :: Nil => + normalize(expr) + case h :: t => + normalize(h) :: asList(normalize(t)) + case _ => + x + } + + def eval(x: Data, env: Environment): Data = { + val prevexp = curexp; + curexp = x; + if (trace) { + for (val x <- range(1, indent)) Console.print(" "); + Console.println("===> " + x); + indent = indent + 1; + } + val result = eval1(x, env); + if (trace) { + indent = indent - 1; + for (val x <- range(1, indent)) Console.print(" "); + Console.println("<=== " + result); + } + curexp = prevexp; + result + } + + def eval1(x: Data, env: Environment): Data = x match { + case Symbol(name) => + env lookup name + case 'def :: Symbol(name) :: y :: z :: Nil => + eval(z, env.extendRec(name, (env1 => eval(y, env1)))) + case 'val :: Symbol(name) :: y :: z :: Nil => + eval(z, env.extend(name, eval(y, env))) + case 'lambda :: params :: y :: Nil => + mkLambda(params, y, env) + case 'if :: c :: y :: z :: Nil => + if (asBoolean(eval(c, env))) eval(y, env) else eval(z, env) + case 'quote :: y :: Nil => + y + case y :: z => + apply(eval(y, env), z map (x => eval(x, env))) + case Lambda(_) => x + case y: String => x + case y: int => x + case y => lispError("illegal term") + } + + def lisp2string(x: Data): String = x match { + case Symbol(name) => name + case Nil => "()" + case y :: ys => + def list2string(xs: List[Data]): String = xs match { + case List() => "" + case y :: ys => " " + lisp2string(y) + list2string(ys) + } + "(" + lisp2string(y) + list2string(ys) + ")" + case _ => if (x.isInstanceOf[String]) "\"" + x + "\""; else x.toString() + } + + def apply(fn: Data, args: List[Data]): Data = fn match { + case Lambda(f) => f(args); + case _ => lispError("application of non-function: " + fn + " to " + args); + } + + def mkLambda(params: Data, expr: Data, env: Environment): Data = { + + def extendEnv(env: Environment, + ps: List[String], args: List[Data]): Environment = + Pair(ps, args) match { + case Pair(List(), List()) => + env + case Pair(p :: ps1, arg :: args1) => + extendEnv(env.extend(p, arg), ps1, args1) + case _ => + lispError("wrong number of arguments") + } + + val ps: List[String] = asList(params) map { + case Symbol(name) => name + case _ => error("illegal parameter list"); + } + + Lambda(args => eval(expr, extendEnv(env, ps, args))) + } + + val globalEnv = EmptyEnvironment + .extend("=", Lambda{ + case List(arg1, arg2) => if(arg1 == arg2) 1 else 0}) + .extend("+", Lambda{ + case List(arg1: int, arg2: int) => arg1 + arg2 + case List(arg1: String, arg2: String) => arg1 + arg2}) + .extend("-", Lambda{ + case List(arg1: int, arg2: int) => arg1 - arg2}) + .extend("*", Lambda{ + case List(arg1: int, arg2: int) => arg1 * arg2}) + .extend("/", Lambda{ + case List(arg1: int, arg2: int) => arg1 / arg2}) + .extend("nil", Nil) + .extend("cons", Lambda{ + case List(arg1, arg2) => arg1 :: asList(arg2)}) + .extend("car", Lambda{ + case List(x :: xs) => x}) + .extend("cdr", Lambda{ + case List(x :: xs) => xs}) + .extend("null?", Lambda{ + case List(Nil) => 1 + case _ => 0}); + + def evaluate(x: Data): Data = eval(normalize(x), globalEnv); + def evaluate(s: String): Data = evaluate(string2lisp(s)); + + def string2lisp(s: String): Data = { + val it = new LispTokenizer(s); + def parseExpr(token: String): Data = { + if (token == "(") parseList + else if (token == ")") error("unbalanced parentheses") + //else if (Character.isDigit(token.charAt(0))) + else if (scala.runtime.compat.Platform.isDigit(token.charAt(0))) + scala.runtime.compat.Platform.parseInt(token) + else if (token.charAt(0) == '\"' && token.charAt(token.length()-1)=='\"') + token.substring(1,token.length() - 1) + else Symbol(token) + } + def parseList: List[Data] = { + val token = it.next; + if (token == ")") Nil else parseExpr(token) :: parseList + } + parseExpr(it.next) + } +} + +//############################################################################ +// List User + +class LispUser(lisp: Lisp) { + + import lisp._; + + def evaluate(s: String) = lisp2string(lisp.evaluate(s)); + + def run = { + + Console.println(string2lisp("(lambda (x) (+ (* x x) 1))").asInstanceOf[Object]); + Console.println(lisp2string(string2lisp("(lambda (x) (+ (* x x) 1))"))); + Console.println; + + Console.println("( '(1 2 3)) = " + evaluate(" (quote(1 2 3))")); + Console.println("(car '(1 2 3)) = " + evaluate("(car (quote(1 2 3)))")); + Console.println("(cdr '(1 2 3)) = " + evaluate("(cdr (quote(1 2 3)))")); + Console.println("(null? '(2 3)) = " + evaluate("(null? (quote(2 3)))")); + Console.println("(null? '()) = " + evaluate("(null? (quote()))")); + Console.println; + + Console.println("faculty(10) = " + evaluate( + "(def (faculty n) " + + "(if (= n 0) " + + "1 " + + "(* n (faculty (- n 1)))) " + + "(faculty 10))")); + Console.println("faculty(10) = " + evaluate( + "(def (faculty n) " + + "(cond " + + "((= n 0) 1) " + + "(else (* n (faculty (- n 1))))) " + + "(faculty 10))")); + Console.println("foobar = " + evaluate( + "(def (foo n) " + + "(cond " + + "((= n 0) \"a\")" + + "((= n 1) \"b\")" + + "((= (/ n 2) 1) " + + "(cond " + + "((= n 2) \"c\")" + + "(else \"d\")))" + + "(else " + + "(def (bar m) " + + "(cond " + + "((= m 0) \"e\")" + + "((= m 1) \"f\")" + + "(else \"z\"))" + + "(bar (- n 4)))))" + + "(val nil (quote ())" + + "(val v1 (foo 0) " + + "(val v2 (+ (foo 1) (foo 2)) " + + "(val v3 (+ (+ (foo 3) (foo 4)) (foo 5)) " + + "(val v4 (foo 6) " + + "(cons v1 (cons v2 (cons v3 (cons v4 nil))))))))))")); + Console.println; + } +} + +//############################################################################ +// Main + +object Test { + def main(args: Array[String]): Unit = { + new LispUser(LispCaseClasses).run; + new LispUser(LispAny).run; + () + } +} + +//############################################################################ diff --git a/test-nsc/files/run/lists.scala b/test-nsc/files/run/lists.scala new file mode 100755 index 0000000000..3791828a1c --- /dev/null +++ b/test-nsc/files/run/lists.scala @@ -0,0 +1,115 @@ +//############################################################################ +// Lists +//############################################################################ +// $Id$ + +//############################################################################ + +object Test { + + val xs1 = List(1, 2, 3); + val xs2 = List('a', 'b'); + val xs3 = List(List(1, 2), List(4, 5)); + val xs4 = List(2, 4, 6, 8); + val xs5 = List(List(3, 4), List(3), List(4, 5)); + + def check_count: int = { + val n1 = xs1 count { e => e % 2 != 0 }; + val n2 = xs4 count { e => e < 5 }; + n1 + n2 + } + + def check_diff: int = { + val ys1 = xs1 diff xs4; + val ys2 = xs3 diff xs5; + ys1.length + ys2.length + } + + def check_exists: boolean = { + val b1 = xs1 exists { e => e % 2 == 0 }; + val b2 = xs4 exists { e => e == 5 }; + b1 & b2 + } + + def check_filter: int = { + val ys1 = xs1 filter { e => e % 2 == 0 }; + val ys2 = xs4 filter { e => e < 5 }; + ys1.length + ys2.length + } + + def check_foldLeft: int = { + val n1 = xs1.foldLeft(0)((e1, e2) => e1 + e2); + val ys1 = xs4.foldLeft(List[Int]())((e1, e2) => e2 :: e1); + n1 + ys1.length + } + + def check_forall: boolean = { + val b1 = xs1 forall { e => e < 10}; + val b2 = xs4 forall { e => e % 2 == 0 }; + b1 & b2 + } + + def check_intersect: int = { + val ys1 = xs1 intersect xs4; + val ys2 = xs3 intersect xs5; + ys1.length + ys2.length + } + + def check_remove: int = { + val ys1 = xs1 remove { e => e % 2 != 0 }; + val ys2 = xs4 remove { e => e < 5 }; + ys1.length + ys2.length + } + + def check_union: int = { + val ys1 = xs1 union xs4; + val ys2 = xs3 union xs5; + ys1.length + ys2.length + } + + def check_zip: int = { + val ys1 = xs1 zip xs2; + val ys2 = xs1 zip xs3; + ys1.length + ys2.length + } + + def check_zipAll: int = { + val ys1 = xs1.zipAll(xs2, 0, '_'); + val ys2 = xs1.zipAll(xs3, 0, List(-1)); + ys1.length + ys2.length + } + + def check_success[A](name: String, closure: => A, expected: A): Unit = { + Console.print("test " + name); + try { + val actual: A = closure; + if (actual == expected) + Console.print(" was successful"); + else + Console.print(" failed: expected "+ expected +", found "+ actual); + } + catch { + case exception: Throwable => { + Console.print(" raised exception " + exception); + } + } + Console.println; + } + + def main(args: Array[String]): Unit = { + check_success("check_count", check_count, 4); + check_success("check_diff", check_diff, 3); + check_success("check_exists", check_exists, false); + check_success("check_filter", check_filter, 3); + check_success("check_foldLeft", check_foldLeft, 10); + check_success("check_forall", check_forall, true); + check_success("check_intersect", check_intersect, 2); + check_success("check_remove", check_remove, 3); + check_success("check_union", check_union, 10); + check_success("check_zip", check_zip, 4); + check_success("check_zipAll", check_zipAll, 6); + Console.println; + } +} + +//############################################################################ diff --git a/test-nsc/files/run/literals.scala b/test-nsc/files/run/literals.scala new file mode 100755 index 0000000000..7bf6238920 --- /dev/null +++ b/test-nsc/files/run/literals.scala @@ -0,0 +1,134 @@ +//############################################################################ +// Literals +//############################################################################ +// $Id$ + +//############################################################################ + +object Test { + + /* I add a couple of Unicode identifier tests here temporarily */ + + def \u03b1\u03c1\u03b5\u03c4\u03b7 = "alpha rho epsilon tau eta"; + + case class GGG(i:int) { + def \u21a1\u21a1( that:GGG ) = that; + } + def check_success[a](name: String, closure: => a, expected: a): Unit = { + Console.print("test " + name); + try { + val actual: a = closure; + if (actual == expected) { + Console.print(" was successful"); + } else { + Console.print(" failed: expected "+ expected +", found "+ actual); + } + } catch { + case exception: Throwable => { + Console.print(" raised exception " + exception); + } + } + Console.println; + } + + def main(args: Array[String]) = { + // char + check_success("'\\u0024' == '$'", '\u0024', '$'); + check_success("'\\u005f' == '_'", '\u005f', '_'); + check_success("65.asInstanceOf[char] == 'A'", 65.asInstanceOf[char], 'A'); + + Console.println; + + // int + check_success("01 == 1", 01, 1); + check_success("010 == 8", 010, 8); + check_success("0X01 == 1", 0X01, 1); + check_success("0x01 == 1", 0x01, 1); + check_success("0x10 == 16", 0x10, 16); + check_success("0xa == 10", 0xa, 10); + check_success("0x0a == 10", 0x0a, 10); + + check_success("+01 == 1", +01, 1); + check_success("+010 == 8", +010, 8); + check_success("+0x01 == 1", +0x01, 1); + check_success("+0x10 == 16", +0x10, 16); + check_success("+0xa == 10", +0xa, 10); + check_success("+0x0a == 10", +0x0a, 10); + + check_success("-01 == -1", -01, -1); + check_success("-010 == -8", -010, -8); + check_success("-0x01 == -1", -0x01, -1); + check_success("-0x10 == -16", -0x10, -16); + check_success("-0xa == -10", -0xa, -10); + check_success("-0x0a == -10", -0x0a, -10); + + check_success("017777777777 == 2147483647", 017777777777, 2147483647); + check_success("020000000000 == -2147483648", 020000000000, -2147483648); + check_success("037777777777 == -1", 037777777777, -1); + + check_success("0x7fffffff == 2147483647", 0x7fffffff, 2147483647); + check_success("0x80000000 == -2147483648", 0x80000000, -2147483648); + check_success("0xffffffff == -1", 0xffffffff, -1); + + Console.println; + + // long + check_success("1l == 1L", 1l, 1L); + check_success("1L == 1l", 1L, 1l); + check_success("1.asInstanceOf[long] == 1l", 1.asInstanceOf[long], 1l); + + check_success("0777777777777777777777L == 9223372036854775807L", + 0777777777777777777777L, 9223372036854775807L); + check_success("01000000000000000000000L == -9223372036854775808L", + 01000000000000000000000L, -9223372036854775808L); + check_success("01777777777777777777777L == -1L", + 01777777777777777777777L, -1L); + + check_success("0x7fffffffffffffffL == 9223372036854775807L", + 0x7fffffffffffffffL, 9223372036854775807L); + check_success("0x8000000000000000L == -9223372036854775808L", + 0x8000000000000000L, -9223372036854775808L); + check_success("0xffffffffffffffffL == -1L", + 0xffffffffffffffffL, -1L); + + Console.println; + + // see JLS at address: + // http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#230798 + + // float + check_success("1e1f == 10.0f", 1e1f, 10.0f); + check_success("2.f == 2.0f", 2.f, 2.0f); + check_success(".3f == 0.3f", .3f, 0.3f); + check_success("0f == 0.0f", 0f, 0.0f); + check_success("3.14f == 3.14f", 3.14f, 3.14f); + check_success("6.022e23f == 6.022e23f", 6.022e23f, 6.022e23f); + check_success("09f == 9.0f", 09f, 9.0f); + check_success("1.asInstanceOf[float] == 1.0", 1.asInstanceOf[float], 1.0f); + check_success("1l.asInstanceOf[float] == 1.0", 1l.asInstanceOf[float], 1.0f); + + Console.println; + + // double + check_success("1e1 == 10.0", 1e1, 10.0); + check_success("2. == 2.0", 2., 2.0); + check_success("2.d == 2.0", 2.d, 2.0); + check_success(".3 == 0.3", .3, 0.3); + check_success("0.0 == 0.0", 0.0, 0.0); + check_success("0d == 0.0", 0d, 0.0); + check_success("3.14 == 3.14", 3.14, 3.14); + check_success("1e-9d == 1.0e-9", 1e-9d, 1.0e-9); + check_success("1e137 == 1.0e137", 1e137, 1.0e137); + check_success("1.asInstanceOf[double] == 1.0", 1.asInstanceOf[double], 1.0); + check_success("1l.asInstanceOf[double] == 1.0", 1l.asInstanceOf[double], 1.0); + + Console.println; + check_success("\"\".length()", "\u001a".length(), 1); +/* + val ggg = GGG( 1 ) \u21a1\u21a1 GGG( 2 ); + check_success("ggg == GGG( 2 )", ggg, GGG( 2 )); +*/ + } +} + +//############################################################################ diff --git a/test-nsc/files/run/map_test.scala b/test-nsc/files/run/map_test.scala new file mode 100755 index 0000000000..53ee416367 --- /dev/null +++ b/test-nsc/files/run/map_test.scala @@ -0,0 +1,42 @@ +import scala.collection.immutable.Map; +import scala.collection.immutable.TreeMap; +import scala.collection.immutable.ListMap; + +object Test extends Application { + test1(); + test2(); + Console.println("OK"); + + + + def test1() = { + val myMap:TreeMap[int,String] = new TreeMap; + test_map(myMap); + } + + def test2() = { + val myMap:ListMap[int,String] = new ListMap; + test_map(myMap); + } + + def test_map(myMap:Map[int,String]) = { + val map1 = myMap.update(42,"The answer"); + val map2 = map1.update(17,"A small random number"); + val map3 = map2.update(666,"A bigger random number"); + val map4 = map3.update(4711,"A big random number"); + map1 == myMap + 42 -> "The answer"; + var i = 0; + var map = map4; + while(i < 43) { + map = map.update(i,i.toString()); + i = i + 1; + } + i = 0; + while(i < 4712) { + if(map.isDefinedAt(i)) + Console.print(i + "->" + map(i) + " "); + i = i + 1; + } + Console.println(""); + } +} diff --git a/test-nsc/files/run/misc.scala b/test-nsc/files/run/misc.scala new file mode 100644 index 0000000000..900139e1cd --- /dev/null +++ b/test-nsc/files/run/misc.scala @@ -0,0 +1,239 @@ +// $Id$ + +object Test { + +def fac(n: Int): Int = if (n < 2) 1 else fac(n - 1) * n; + +// Fibonacci + + +def fib(n: Int): Int = if (n < 2) 1 else fib(n - 1) + fib(n - 2); + +def show_fib(n: Int): Int = { + Console.print("### fib("); + Console.print(n); + Console.print(") = "); + Console.flush; + val v = fib(n); + Console.print(v); + Console.println; + Console.flush; + v +} + +def id[X](x: X): X = x; + +def apply[X](f: X => X, x: X): X = f(x); + +def id_obj(x: Object): Object = x; + +def apply_obj(f: Object => Object, x: Object): Object = f(x); + +def id_any(x: scala.Any): scala.Any = x; + +def apply_any(f: scala.Any => scala.Any, x: scala.Any): scala.Any = f(x); + +def id_int(x: Int): Int = x; + +def apply_int(f: Int => Int, x: Int): Int = f(x); + +class MyClass() { + override def toString() = "=== MyClass::toString ==="; + def test() = Console.println("=== MyClass::test ==="); +} + +class MySubclass() extends MyClass() { + override def toString() = "=== MySubclass::toString ==="; +} + +def foobar = { + 42; + 42l; + 23.5f; + 23.5; + "Hello"; + 32 + 45; + // !!! System + // java; // !!! why is this legal ? what does it return ? + // java.lang; + //System.out; + Console.println("### Hello"); + Console.print("### "); + Console.println(17); + Console.println("### Bye"); + Console.println; + val x = 13; + x; + // !!! why are DefDef replaced by Block(Tree[0])? we should use Empty! + def f = 19; + f; + def f0() = 11; + f0(); + def f1(x: Int) = x; + f1(7); + def f2(x: Int, y: Int) = x + y; + f2(3,5); + def f11(x: Int)(y: Int) = x + y; + f11(23)(2); + 1 < 2; + if (1 < 2) 3 else 4; + + + show_fib(0); + show_fib(1); + show_fib(2); + show_fib(3); + show_fib(4); + + // !!! show_fib(id[Int](4)); + +/* + show_fib(5); + show_fib(6); + show_fib(7); + show_fib(8); + show_fib(9); + show_fib(10); + show_fib(11); + show_fib(12); +*/ + + val myObj = new MyClass(); + Console.println(myObj); + val mySub = new MySubclass(); + Console.println(mySub); + myObj.test(); + Console.println; + + Console.println(apply_any(id_any, "identity").toString()); + Console.println; +}; + +foobar; + +//############################################################################ + +class A(a: Int) { + def getA = a; +} + +class B(b: Int, c: Int) extends A(b + c) { + def getB = b; +} + +class X(x: Int) { + def getX = x; +} +case class Y(y: Int, z: Int) extends X(y + z) { + def getY = y; + def getAA = this.y; +} + +{ + val a: A = new A(1); + val b: B = new B(2,3); + + val x: X = new X(4); + val y: Y = new Y(5,6); + + Console.println("A.a = " + a.getA); + Console.println("B.a = " + b.getA); + Console.println("B.b = " + b.getB); + Console.println; + + Console.println("X.a = " + x.getX); + Console.println("Y.a = " + y.getX); + Console.println("Y.b = " + y.getY); + Console.println("Y.b = " + y.y); + Console.println; +} + +//############################################################################ + +{ +class X() { + + def foo = { + Console.println("X::foo"); + } + +} + +class Y() extends X() { + + override def foo = { + Console.println("Y::foo"); + super.foo; + } + +} + +val x: X = new X(); +val y: X = new Y(); + +x.foo; +Console.println; + +y.foo; +Console.println; +} + +//############################################################################ + +{ +class X() {} + +class O(a: Int) { + + + case class Y(b: Int) extends X() { + override def toString() = ""; + def bar = a + b; + } + + def foo = Y(2).bar +} + +Console.println(new O(1).foo) +} + +{ + +class O(a: Int) { + + class X() {} + + case class Y(b: Int) extends X() { + override def toString() = ""; + def bar = a + b; + } + + def foo = Y(2).bar +} + +Console.println(new O(1).foo) +} + +Console.println; + + case class Bar(); + + case class Foo(i:int, j:char, c:Bar) ; + + Console.println( + Foo(3,'a',Bar()).caseElement( -1 ) == null + && Foo(3,'a',Bar()).caseElement( 0 ) == 3 + && Foo(3,'a',Bar()).caseElement( 1 ) == 'a' + && Foo(3,'a',Bar()).caseElement( 2 ) == Bar() + && Foo(3,'a',Bar()).caseElement( 3 ) == null + && Bar().caseArity == 0 + && Foo(3,'a',Bar()).caseArity == 3); + +//############################################################################ + + def main(args: Array[String]): Unit = { + () + } + +//############################################################################ +} diff --git a/test-nsc/files/run/mixins.scala b/test-nsc/files/run/mixins.scala new file mode 100755 index 0000000000..f896551108 --- /dev/null +++ b/test-nsc/files/run/mixins.scala @@ -0,0 +1,94 @@ +// $Id$ + +// Test 1: "super" coming from mixins + +object Test1 { + class A { + def f = "A::f"; + } + + class B extends A { + override def f = "B::f"; + } + + trait M1 extends A { + override def f = "M1::" + super.f; + } + + class C extends B with M1 { + override def f = super[M1].f; + } + + def test(): Unit = { + val c = new C; + Console.println(c.f); + } +} + +// Test 2: qualified "super" inside of the host class + +object Test2 { + class M1 { + def f = "M1::f"; + } + + trait M2 { + def f = "M2::f"; + } + + trait M3 { + def f = "M3::f"; + } + + class Host extends M1 with M2 with M3 { + override def f = super[M1].f + " " + super[M2].f + " " + super[M3].f + } + + def test(): Unit = { + val h = new Host; + Console.println(h.f) + } +} + +// Test 3: mixin evaluation order (bug 120) + +object Test3 { + + class A(x: Unit, y: Unit) { + Console.println("A"); + } + +<<<<<<< mixins.scala + trait B { + println("B"); +======= + class B(x: Unit) { + Console.println("B"); +>>>>>>> 1.5 + } + +<<<<<<< mixins.scala + class C extends A({ println("one"); }, { println("two"); }) + with B { + println("C"); +======= + class C with A({ Console.println("one"); }, { Console.println("two"); }) + with B({ Console.println("three"); }) { + Console.println("C"); +>>>>>>> 1.5 + } + + def test() = { + val c = new C(); + } +} + +// Main testing function + +object Test { + def main(args: Array[String]): Unit = { + Test1.test(); + Test2.test(); + Test3.test(); + } +} diff --git a/test-nsc/files/run/ok.lst b/test-nsc/files/run/ok.lst new file mode 100755 index 0000000000..b8d709a476 --- /dev/null +++ b/test-nsc/files/run/ok.lst @@ -0,0 +1,30 @@ +arrays.scala +boolexprs.scala +bugs.scala +constructors.scala +Course-2002-01.scala +Course-2002-02.scala +Course-2002-03.scala +Course-2002-04.scala +Course-2002-05.scala +Course-2002-06.scala +Course-2002-07.scala +Course-2002-08.scala +Course-2002-09.scala +Course-2002-10.scala +Course-2002-13.scala +enums.scala +exceptions.scala +imports.scala +iq.scala +iterators.scala +lisp.scala +lists.scala +map_test.scala +misc.scala +mixins.scala +NestedClasses.scala +overloads.scala +runtime.scala +literals.scala +bridges.scala diff --git a/test-nsc/files/run/overloads.scala b/test-nsc/files/run/overloads.scala new file mode 100755 index 0000000000..31664b2ea6 --- /dev/null +++ b/test-nsc/files/run/overloads.scala @@ -0,0 +1,96 @@ +//############################################################################ +// Overloads +//############################################################################ +// $Id$ + +//############################################################################ + +object Ops { + def - = 0; + def -(c: Char) = c; + def -(i: Int) = i; + + def -- = 0; + def --(c: Char) = c; + def --(i: Int) = i; +} + +object Funcs { + def foo = 0; +// def foo() = 1; + def foo(c: Char) = 2; + def foo(i: Int) = 3; +} + +object M1 { + def f[A](x: A) = 11; + def f[A <: Ordered[A]](x: A) = 12; +} + +object M2 { + def f[A <: Ordered[A]](x: A) = 21; + def f[A](x: A) = 22; +} + +object overloads { + + def check(what: String, actual: Any, expected: Any): Unit = { + val success: Boolean = actual == expected; + Console.print(if (success) "ok" else "KO"); + var value: String = if (actual == null) "null" else actual.toString(); + if (value == "\u0000") value = "\\u0000"; + Console.print(": " + what + " = " + value); + if (!success) Console.print(" != " + expected); + Console.println; + Console.flush; + } + + def - = 0; + def -(c: Char) = c; + def -(i: Int) = i; + + def -- = 0; + def --(c: Char) = c; + def --(i: Int) = i; + + def test: Unit = { + check("-('a')", -('a'), -97); + check("-(97)", -(97), -97); + + check("Ops.-('a')", Ops.-('a'), 'a'); + check("Ops.-(97)", Ops.-(97), 97); + + check("--", --, 0); + check("--('a')", --('a'), 'a'); + check("--(97)", --(97), 97); + + check("Ops.--", Ops.--, 0); + check("Ops.--('a')", Ops.--('a'), 'a'); + check("Ops.--(97)", Ops.--(97), 97); + + check("Funcs.foo", Funcs.foo, 0); +// check("Funcs.foo()", Funcs.foo(), 1); + check("Funcs.foo('a')", Funcs.foo('a'), 2); + check("Funcs.foo(97)", Funcs.foo(97), 3); + + val x = 3; + check("M1.f(" + x +")", M1.f(x), 11); + check("M2.f(" + x +")", M2.f(x), 22); +// val y = new scala.collection.mutable.Stack[Int]; +// check("M1.f(" + y +")", M1.f(y), 12); +// check("M2.f(" + y +")", M2.f(y), 21); + } + +} + +//############################################################################ + +object Test { + + def main(args: Array[String]): Unit = { + overloads.test; + } + +} + +//############################################################################ diff --git a/test-nsc/files/run/regularpatmat.scala b/test-nsc/files/run/regularpatmat.scala new file mode 100755 index 0000000000..4d1ac796e0 --- /dev/null +++ b/test-nsc/files/run/regularpatmat.scala @@ -0,0 +1,809 @@ +// Burak's test suite for regular pattern matching + +//import java.lang.System; // to avoid name clash with .NET's library + +object Test { + def main(args: Array[String]): Unit = { + Console.println("pretest"); + val L = List(1,2,3); + scala.testing.UnitTest.assertEquals( L, L match { case List(xs@_*) => xs; } ) ; + + testWR.main( args ); + testWS.main( args ); + testWT.main( args ); + testWV.main( args ); + //testWW.main( args ); + testBK.main( args ); + testBL.main( args ); + testBM.main( args ); + testBN.main( args ); + testBO.main( args ); + testMZ.main; + //testNN.main; + //testBugSequenceApply.main; + } +} + +// contains 17 visitors plus X + +// analyzer related (no execution) +object bug179 { + case class One(); + object Foo { + def test(xs: List[Any]) = xs match { + case List(((((One(), One())*) | (One(), One())), One())) => + Console.println("case") + case _ => + Console.println("default"); + } + } +} +// testW? are for recognition only ( no variables ) +// testB? are for variables binding + +object values { // test values reused in nearly all test cases + + val s0:List[Char] = Nil ; + val s1:List[Char] = 'a'::'b'::'c'::Nil ; + val s2:List[Char] = 'a'::'b'::'c'::s1 ; + val s3:List[Char] = 'a'::'a'::'a'::Nil ; + val s4:List[Char] = 'b'::'c'::Nil ; + val s5:List[Char] = 'b'::Nil ; + val s6:List[Char] = 'b'::'a'::'a'::'a'::Nil ; + + val s7:List[Int] = 1::2::7::Nil ; + val s8:List[Int] = 1::0::1::0::Nil; + val s9:List[Int] = Nil ; + + val s10:List[Char] = '7'::'0'::'1'::'.'::'2'::'4'::Nil ; + +} + +// matching without binding + +// 2do case [ 'a'; x; y ] => 100 +// case [ z @ ('a'; x; y) ] => 100 +// 2do case [ 'a'*; x @ ( _;('a'; 'b')* ); y @ 'b'* ] => 100 +// case _ => 321 // 20022 // this never happens + +object testBK { + + import values._ ; + + import scala.testing.UnitTest._ ; + + def doit1(e: List[Char]):Int = e match { + + case List( 'a'*, x @ ( 'a',('a', 'b')* ), y @ ('b'*) ) => { 100 } + + case List( _ * ) => 321 + }; + + def test1:Unit = { + Console.println("testBK"); + //test[List[Char],Int]( doit1, s0, 321); + assertEquals( doit1( s0 ), 321); + assertEquals( doit1( s1 ),321); + assertEquals( doit1( s2 ),321); + assertEquals( doit1( s3 ),100); + assertEquals( doit1( s4 ),321); + assertEquals( doit1( s5 ),321); + assertEquals( doit1( s6 ),321) + }; + + def main( args:Array[ String ] ) = { + test1; + } + +} + +// tests with binding + +object testBL { + + import scala.testing.UnitTest._ ; + + def preTest(a:String,b:String):boolean = (a==b); + + def doit( x:List[String] ):String = x match { + + case List( z @ "John" ) => z + + } + + // BEWARE: main type should be specified... + // often, last thing is not () then you have a problem + + def main(args:Array[String]):Unit = { + + val a = "John"; + val b = "John"; + + assertEquals( a == b, true ); + assertEquals( doit( List( b ) ), "John" ) + + } +} +object testBM { + + import scala.testing.UnitTest._ ; + import values._ ; + + def doit1(e: List[Char]):List[Char] = e match { + + case List( 'a'*, x @ ( 'a',('a', 'b')* ), y @ ('b'*) ) + + => { x.toList } + + case List( 'a'*, x @ (('a', 'b')*) , y @ (('a','b','c') *) ) + + => { y.toList } + + case List( _ * ) + + => Nil + }; + + def test1:Unit = { + Console.println("testBM"); + assertEquals( doit1( s0 ), Nil); + assertEquals( doit1( s1 ), s1); + assertEquals( doit1( s2 ), s2); + + assertEquals( doit1( s3 ), List('a')); + assertEquals( doit1( s4 ), Nil); + assertEquals( doit1( s5 ), Nil); + assertEquals( doit1( s6 ), Nil); + + val t7:List[Char] = 'a'::'a'::'a'::'b'::'b'::'b'::Nil; + //val t7ex:List[Char] = 'a'::'a'::'b'::Nil; // with longest match policy + + assertEquals( doit1( t7 ), List('a') ); + }; + + def main( args:Array[ String ] ) = { + test1; + } + +} +object testBN { + + import scala.testing.UnitTest._ ; + import values._ ; + + class testClass; + + case class testA( arg:List[Char] ) extends testClass; + + def doit1(e: testClass):List[Char] = e match { + case testA(List( 'a', x, y )) => x::y::Nil + case _ => Nil + }; + + def test1:Unit = { + Console.print("BN preTest: "); + Console.println( Nil == Nil ); + Console.println("testBN"); + + assertEquals + ( doit1( testA(s0)), Nil); + + assertEquals + ( doit1( testA(s1)), 'b'::'c'::Nil); + + assertEquals + ( doit1( testA(s2)), Nil); + + assertEquals + ( doit1( testA(s3)), 'a'::'a'::Nil); + + assertEquals + ( doit1( testA(s4)), Nil); + + assertEquals + ( doit1( testA(s5)), Nil); + + assertEquals + ( doit1( testA(s6)), Nil); + + }; + + + def main( args:Array[String] ) = { + + test1 + + } + +} + +object testBO { + + // example suggested by Matthias + import scala.testing.UnitTest._ ; + + + case class Person( firstname:String, lastname:String ); + + def onlyJohn( db:List[ Person ] ):List[ String ] = { + + db match { + + case List( Person( "John", lastname ) ) + + => lastname::Nil + + case _ + => Nil + + } + + } + + /** first longest match policy -> the star is greedy/hungry/... + */ + + def searchFirstJohn( db:List[ Person ] ):String = { + + db match { + + case List( _ *, Person( "John", lastname ), _ * ) + => lastname + + case _ + => "<not found>" + + } + + } + + /** first longest match policy -> star is a greedy/hungry + */ + + def searchJohns( db:List[Person]):List[String] = { + + db match { + + case List( _ *, Person( "John", lastname ), rest@(_ *) ) + => { //Console.print("before is : "+before ); + lastname::searchJohns( rest.toList ) + } + + case _ + => Nil + + } + + } + + def main( args:Array[String] ) = { + + val p1 = Person("Albert", "Camus"); + val p2 = Person("Henry", "Miller"); + val p3 = Person("John", "Le Carre"); + val p4 = Person("Herbert", "Franke"); + val p5 = Person("John", "Smith"); + val p6 = Person("William", "Gibson"); + + val db:List[Person] = p1::p2::p3::p4::p5::p6::Nil; + + val db2:List[Person] = p3::Nil; + + Console.println("testBO"); + + assertEquals + ( onlyJohn( db ), Nil ); + + assertEquals + ( onlyJohn( db2 ), "Le Carre"::Nil ); + + assertEquals + ( searchFirstJohn( db ), "Le Carre" ); + + assertEquals + ( searchFirstJohn( db2 ), "Le Carre" ); + + assertEquals + ( searchJohns( db ), "Le Carre"::"Smith"::Nil ); + + assertEquals + ( searchJohns( db2 ), "Le Carre"::Nil ); + + } + +} +object testWR { + + import values._ ; + + import scala.testing.UnitTest._ ; + + def doit1(e: List[Char]):Int = e match { + case List( 'a', 'b', 'c' ) => 100 + case _ => 321 + }; + + def test1:Unit = { + Console.println("testWR_1"); + assertEquals( doit1( s0 ),321); + assertEquals( doit1( s1 ),100); + assertEquals( doit1( s2 ),321); + assertEquals( doit1( s3 ),321); + assertEquals( doit1( s4 ),321); + assertEquals( doit1( s5 ),321); + assertEquals( doit1( s6 ),321) + }; + + def doit2(e: List[Char]):Int = e match { + case List( ('a', 'b','c')? ) => 1000 + case _ => 321 + } + + def test2:Unit = { + Console.println("testWR_2"); + assertEquals( doit2( s0 ),1000); + assertEquals( doit2( s1 ),1000); + assertEquals( doit2( s2 ),321); + assertEquals( doit2( s3 ),321); + assertEquals( doit2( s4 ),321); + assertEquals( doit2( s5 ),321); + assertEquals( doit2( s6 ),321); + } + + + def doit3(e: List[Char]):String = e match { + case List( ('a', 'a','a')? ) => "ok" + case _ => "fail" + } + + def test3:Unit = { + Console.println("testWR_3"); + assertEquals( doit3( s0 ), "ok"); + assertEquals( doit3( s1 ),"fail"); + assertEquals( doit3( s2 ), "fail"); + assertEquals( doit3( s3 ),"ok"); + assertEquals( doit3( s4 ),"fail"); + assertEquals( doit3( s5 ),"fail"); + assertEquals( doit3( s6 ),"fail"); + } + + def doit4(e: List[Char]):String = e match { + case List( ('a'|'b')*,('a'|'b'|'c')+ ) => "ga!!!!" + case _ => "gu" + } + + def test4:Unit = { + Console.println("testWR_4"); + assertEquals( doit4( s0 ), "gu"); + assertEquals( doit4( s1 ), "ga!!!!"); + assertEquals( doit4( s2 ), "ga!!!!"); + assertEquals( doit4( s3 ), "ga!!!!"); + assertEquals( doit4( s4 ), "ga!!!!"); + assertEquals( doit4( s5 ), "ga!!!!"); + assertEquals( doit4( s6 ), "ga!!!!"); + } + + def doit5(e: List[Int]):String = e match { + case List( (0|1)+ ) => "binary" + case _ => "not binary" + } + + def test5:Unit = { + Console.println("testWR_5"); + assertEquals( doit5( s7 ), "not binary"); + assertEquals( doit5( s8 ), "binary"); + assertEquals( doit5( s9 ), "not binary"); + } + + // { ('0'..'9')*;'.';('0'..'9');('0'..'9')* ] + def doit6(e: List[Char]):String = e match { + case List( ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')*, + '.', + ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'), + ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')* ) + + => "decimal number" + case _ => "not decimal" + } + + def test6:Unit = { + Console.println("testWR_6"); + assertEquals( doit6( s3 ), "not decimal"); + assertEquals( doit6( s10 ), "decimal number"); + } + + def test8: Unit = { + Console.println("testWR_8"); + + assertTrue( List('d','c') match { + case List('a'*, 'd'|'e', 'c'*) => true + case _ => false + }); + } + + def test7:Unit = { + Console.println("testWR_7"); + assertEquals( List(1,2) match { + case List(1,(3*,2))=> true; // test normalization (pattern normalizer) + case _ => false; + }, true); + } + def main( args:Array[String] ) = { + test1; + test2; + test3; + test4; + test5; + test6; + test7; + test8; + } + + + +} +object testWS { + + import values._ ; + + import scala.testing.UnitTest._ ; + + /* strings: + + "blabla" == [ "bla";"bla" ] == [ 'b';'l';'a';'b';'l';'a' ] + + [ "blabla";'x';'y'? ] == [ ('b';'l';'a';'b';'l';'a'); 'x'; 'y'? ] + + */ + + /* + def isIdentifierStart(c:char) ; + + case [ ... ; _isIdentifierStart_ ; ... ] + + calls method is..., needs to have type (elementType)Boolean + + translated to pattern + + [ ... ; Apply(is..., Tree.Empty) ; ... ] + + */ + + /* for tree automata: + + [ t0; t1; ...; tn ] with ti = labeli ( argsi ) + + gets translated to + + [ _isTree$0_ ; _isTree$1_ ; ... ; _isTree$n_ ] + + where isTree$i( t ) = t.is[ labeli ] ... (algebraic matcher) + + special case: sequences + + [ ...; seq ; ... ] where seq = [ ... ] + + gets translated to + + [ ...; _seq$0_ ; ...] with seq$0( s ) = t.is[ Sequence ] and + seq$0match( s.newIterator ) + + subroutines return + 1) d'abord true or false, + 2) later ( true|false, environment ) + assume order on variables, enviroment is a tuple/sequence + */ + + def doit1(e: List[Char]):Int = e match { + case List( 'a', 'b', 'c' ) => 100 + case List( ('a', 'b','c')? ) => 1004 + case List( ('a', 'a','a')? ) => 50 + case List( ('a'|'b')*,('a'|'b') ) => 700 + case _ => 321 + }; + + def test1:Unit = { + Console.println("testWS"); + assertEquals( doit1( s0 ),1004); + assertEquals( doit1( s1 ),100); + assertEquals( doit1( s2 ),321); + assertEquals( doit1( s3 ),50); + assertEquals( doit1( s4 ),321); + assertEquals( doit1( s5 ),700); + assertEquals( doit1( s6 ),700); + }; + + def main( args:Array[String] ) = { + test1; + } + + + +} +object testWT { + + import values._ ; + + import scala.testing.UnitTest._ ; + + def doit1(e: List[Char]):Int = e match { + case List( 'a', _, _ ) => 100 + case List( _ * ) => 321 + case _ => 20022 // this never happens + }; + + def test1:Unit = { + Console.println("testWT"); + assertEquals( doit1( s0 ),321); + assertEquals( doit1( s1 ),100); + assertEquals( doit1( s2 ),321); + assertEquals( doit1( s3 ),100); + assertEquals( doit1( s4 ),321); + assertEquals( doit1( s5 ),321); + assertEquals( doit1( s6 ),321) + }; + + def main( args:Array[ String ] ) = { + test1; + } + +} +object testWV { + + import values._ ; + + import scala.testing.UnitTest._ ; + + class testClass; + + case class testA( arg:List[Char] ) extends testClass; + + def doit1( e: testClass ):Int = e match { + + case testA( List( 'a', 'b', 'c' )) => 100 + case testA( List( ('a', 'b','c')? )) => 1004 + case testA( List( ('a', 'a','a')? )) => 50 + case testA( List( ('a'|'b')*,('a'|'b') )) => 700 + case testA( _ ) => 321 + + }; + + def test1:Unit = { + Console.println("testWV"); + assertEquals( doit1( testA(s0) ),1004); + assertEquals( doit1( testA(s1) ),100); + assertEquals( doit1( testA(s2) ),321); + assertEquals( doit1( testA(s3) ),50); + assertEquals( doit1( testA(s4) ),321); + assertEquals( doit1( testA(s5) ),700); + assertEquals( doit1( testA(s6) ),700); + }; + + + def main( args:Array[String] ) = { + + test1 + + } + +} +/* +object testWW { + + import values._ ; + + import scala.testing.UnitTest._ ; + + class testClass; + case class testA( arg:List[Char] ) extends testClass; + + def doit1(e: List[testClass]):Int = e match { + + case List( testA(List()), testA( List( 'a', 'b' )) ) => 100 + case _ => 321 + + }; + + def test1:Unit = { + val x1 = List( testA(s0) ); + + Console.println("testWW"); + + assertEquals( doit1( x1 ), 321 ); + + val x2 = List( testA(Nil), testA('a'::'b'::Nil) ); + + assertEquals( doit1( x2 ), 100 ); + + } + + def main( args:Array[String] ) = { + test1; + } + +} +*/ +object testMZ { + import scala.testing.UnitTest.assertEquals ; + class Expr; + case class One(xs: List[Expr]) extends Expr; + case class Two() extends Expr; + def testFoo(xs: List[Expr]) = xs match { //bug#132 + case List(Two()?,a,Two()?) => "a = " + a; + case List(Two()*,b,Two()*) => "b = " + b; + case List(_*) => "no match"; + } + case class OneN(); + def bind(xs: List[Any]):String = xs match { // bug#133b + case List(x@(OneN()*), y@(OneN())) => "case"; + case _ => "default"; + } + case class On(); + case class Tw(); + def testBar(xs: List[Any]) = xs match { // bug#180 + case List(((On(), Tw())* | (On(), On())), On()) => "caseBar" + case _ => "default"; + } + + + def mat195(x:Expr) = x match { // bug#195 + case One(x@List(_*)) => + "x = " + x; + + case _ =>"default"; + + } + + def mat196(xs: List[Any]) = xs match { // bug#196 + case List(b@(()|())) => + "case, b = " + b; + + case _ =>"default"; + + } + + def mat398(xs:List[Any]) = xs match { // bug#398 + case List(1) => "one" + case x::xs => "two" + } + + def mat406() = { + class Type; + case class A() extends Type; + case class B() extends Type; + case class C() extends Type; + + def foo(x: Type, y: Type): String = Pair(x, y) match { + case Pair(A(), A()) + | Pair(A(), B()) + | Pair(B(), A()) + | Pair(B(), B()) => "3" + case Pair(C(), C()) => "4" + case Pair(A(), _) + | Pair(B(), _) => "7" + case _ => "8" + } + + foo(A(), C()) + } + + def mat441() = { + val tata = 1; + val titi = 0.8 + Math.random(); + try { + tata match { + case 1 if (titi < 0.5) => "a" + case 0 | 1 => "b" + } + } catch { + case _ => "c" + } + } + + /* this will crash + def matSymbolCloning = { + 2 match { + case 3 | 4 => + class Foo extends scala.xml.Atom[Int](3) { + def bar = 7; + } + null + } + } + */ + + def main:Unit = { + Console.println("testMZ - bugs #132 #133b #180 #195 #196 #398 #406 #441"); + assertEquals(testFoo( List(Two(),Two(),Two(),Two()) ),"b = Two"); + assertEquals(testFoo( List(Two(),Two(),Two()) ),"a = Two"); + assertEquals(testFoo( List(Two(),Two()) ),"a = Two"); + assertEquals(testFoo( List(Two()) ),"a = Two"); + assertEquals(testFoo( List() ),"no match"); + assertEquals(bind( List(OneN(),OneN()) ),"case"); + assertEquals(testBar( List() ),"default"); + assertEquals(testBar( List(On()) ),"caseBar"); + assertEquals(testBar( List(On(), On())), "default"); + assertEquals(testBar( List(On(), On(), On()) ),"caseBar"); + assertEquals(testBar( List(On(), On(), On(), On()) ),"default"); + assertEquals(testBar( List(On(), On(), On(), On(), On()) ),"default"); + assertEquals(mat195( One(List(Two(),Two())) ),"x = List(Two,Two)"); + assertEquals(mat195( One(List()) ),"x = List()"); + assertEquals(mat195( Two() ),"default"); + assertEquals(mat196( List(1) ),"default"); + assertEquals(mat196( List() ),"case, b = List()"); + assertEquals(mat398( List(2) ),"two"); + assertEquals(mat398( List(2) ),"two"); + assertEquals(mat406(), "7"); + assertEquals(mat441(), "b"); + () + } + +} +/* +object testNN { + import scala.testing.UnitTest._ ; + abstract class K; + case class F(x:K*) extends K; + case class G() extends K; + + def mtch(k:K):boolean = k match { + case F(F(G()*),G(),F(G()*)) => true; + case _ => false; + } + + def main:Unit = { + Console.println("testNN"); + assertEquals(mtch( F(F(G()),G(),F(G()))), true); + assertEquals(mtch( F(F(),G(),F(G(),G(),G(),G())) ), true); + assertEquals(mtch( G() ), false); + assertEquals(mtch( F(G()) ), false); + } +} +*/ +object testNO { // this does not need to be run, only compiled + + trait Operator; + case class Increment() extends Operator; + case class Decrement() extends Operator; + + trait Expression { + def eval = this match { + case Operation (v: Value, o: Increment) => v + case Operation (v: Value, d: Decrement) => v + } + } + + case class Value() extends Expression; + case class Operation (e: Expression, o: Operator) extends Expression; + + +} + +/** see comments in scala.tools.scalac.transformer.matching.PatternMatcher::isSeqApply 2005-02-17 + */ + +/* +object testBugSequenceApply { + + val x = List(1,2,3); + + case class ThreeBars extends Seq[Int] { + override def length = 3; + def elements = x.elements; + def apply(i:Int) = x.apply(i); + } + + // this works + def main:Unit = { + Console.print("testBugSequenceApply "); + val z: Seq[Int] = new ThreeBars(); + Console.print(z match { + case Seq(1,2,3) => "hello" // but ThreeBars is a case class... + }); + + Console.print(ThreeBars() match { + case Seq(1,2,3) => " hello" // but ThreeBars is a case class... + }); + } +} +*/ diff --git a/test-nsc/files/run/runtime.scala b/test-nsc/files/run/runtime.scala new file mode 100755 index 0000000000..8dca7229d2 --- /dev/null +++ b/test-nsc/files/run/runtime.scala @@ -0,0 +1,219 @@ +//############################################################################ +// Run Time Bugs & Test Cases +//############################################################################ +// $Id$ + +//############################################################################ +// serves as an entry point with the MSIL backend + +object TestMain { + def main(args: Array[String]): Unit = { + Test.main(args); + } +} + +//############################################################################ +// Test 0 - Array creation + +object Test0Test { + def println[A](xs: Array[A]): Unit = { + var i = 0; + Console.print("["); + while (i < xs.length) { + if (i > 0) Console.print(","); + Console.print(xs(i)); + i = i + 1; + } + Console.print("]"); + Console.println; + } + + def main(args: Array[String]): Unit = { + val zs: Array[Boolean] = Array(false, true); + val bs: Array[Byte ] = Array(0, 1, 2); + val ss: Array[Short ] = Array(3, 4, 5); + val cs: Array[Char ] = Array('a', 'b', 'c'); + val is: Array[Int ] = Array(6, 7, 8); + val ls: Array[Long ] = Array(9l, 10l, 11l); + val fs: Array[Float ] = Array(12.0f, 13.0f); + val ds: Array[Double ] = Array(14.0d, 15.0d); + val os: Array[AnyRef ] = Array("string"); + println(zs); + println(bs); + println(ss); + println(cs); + println(is); + println(ls); + println(fs); + println(ds); + println(os); + } +} + +//############################################################################ +// Test 1 - Block Qualifiers + +package test1.bar { + + object System { + val out: PrintStream = new PrintStream(); + } + + class PrintStream() { + def println(): Unit = { + Console.println; + } + } + +} + +object Test1Test { + + def main(args: Array[String]): Unit = { + {Console.print(10)}; Console.println; + // {System.out.print(11); java}.lang.System.out.println(); + // {System.out.print(12); java.lang}.System.out.println(); + // {System.out.print(13); java.lang.System}.out.println(); + {Console.print(14); Console}.println; + {Console.print(15); (() => Console.println):(() => Unit)}(); + {Console.print(16); Console.println}; + + {Console.print(20)}; test1.bar.System.out.println(); + // {System.out.print(21); test1}.bar.System.out.println(); + // {System.out.print(22); test1.bar}.System.out.println(); + {Console.print(23); test1.bar.System}.out.println(); + {Console.print(24); test1.bar.System.out}.println(); + {Console.print(25); test1.bar.System.out.println:(() => Unit)}(); + {Console.print(26); test1.bar.System.out.println()}; + } + +} + +//############################################################################ +// Test 2 - Super Calls with Mixins + +package test2 { + + class A { + def run = Console.println("A"); + } + +<<<<<<< runtime.scala + trait M0 extends A { + override def run = { super.run; System.out.println("M0"); } +======= + class M0 extends A { + override def run = { super.run; Console.println("M0"); } +>>>>>>> 1.9 + } + + class M1 extends M0 { + override def run = { super.run; Console.println("M1"); } + } + +<<<<<<< runtime.scala + trait N0 extends A { + override def run = { super.run; System.out.println("N0"); } +======= + class N0 extends A { + override def run = { super.run; Console.println("N0"); } +>>>>>>> 1.9 + } + + class N1 extends N0 { + override def run = { super.run; Console.println("N1"); } + } + + object M0N0 extends M0 with N0; + object N0M0 extends N0 with M0; + object M1N0 extends M1 with N0; + object N1M0 extends N1 with M0; + +} + +object Test2Test { + def main(args: Array[String]): Unit = { + test2.M0N0.run; Console.println; + test2.N0M0.run; Console.println; + test2.M1N0.run; Console.println; + test2.N1M0.run; Console.println; + } +} + +//############################################################################ +// Test 3 - Methods eq and ne + +object Test3Test { + + class Foo { override def equals(that: Any) = error("abort"); } + + def check(expected: Boolean, actual1: Boolean, actual2: Boolean): Unit = + Console.println( + if ((actual1 == expected) && (actual2 == !expected)) "Ok" else "KO: " + + "expected: " + expected + " - " + (!expected) + ", " + + "found: " + actual1 + " - " + actual1); + + def main(args: Array[String]): Unit = { + val foo1: AnyRef = null; + val foo2: AnyRef = new Foo(); + val foo3: AnyRef = new Foo(); + + check(true , null eq null, null ne null); + check(true , null eq foo1, null ne foo1); + check(false, null eq foo2, null ne foo2); + check(false, null eq foo3, null ne foo3); + + check(true , foo1 eq null, foo1 ne null); + check(true , foo1 eq foo1, foo1 ne foo1); + check(false, foo1 eq foo2, foo1 ne foo2); + check(false, foo1 eq foo3, foo1 ne foo3); + + check(false, foo2 eq null, foo2 ne null); + check(false, foo2 eq foo1, foo2 ne foo1); + check(true , foo2 eq foo2, foo2 ne foo2); + check(false, foo2 eq foo3, foo2 ne foo3); + + check(false, foo3 eq null, foo3 ne null); + check(false, foo3 eq foo1, foo3 ne foo1); + check(false, foo3 eq foo2, foo3 ne foo2); + check(true , foo3 eq foo3, foo3 ne foo3); + } + +} + +//############################################################################ +// Main + +object Test { + var errors: Int = 0; + def test(name: String, test: => Unit): Unit = { + Console.println("<<< " + name); + try { + test; + } catch { + case exception => { + //val name: String = Thread.currentThread().getName(); + Console.print("Exception in thread \"" + name + "\" " + exception); + Console.println; + errors = errors + 1; + } + } + Console.println(">>> " + name); + Console.println; + } + + def main(args: Array[String]): Unit = { + + test("Test0" , Test0Test.main(args)); + test("Test1" , Test1Test.main(args)); + test("Test2" , Test2Test.main(args)); + test("Test3" , Test3Test.main(args)); + + if (errors > 0) { + Console.println; + Console.println(errors + " error" + (if (errors > 1) "s" else "")); + } + } +} + +//############################################################################ diff --git a/test-nsc/files/run/tailcalls.scala b/test-nsc/files/run/tailcalls.scala new file mode 100644 index 0000000000..3279e6bf64 --- /dev/null +++ b/test-nsc/files/run/tailcalls.scala @@ -0,0 +1,290 @@ +//############################################################################ +// Tail Calls +//############################################################################ +// $Id$ + +//############################################################################ +// Calibration + +class Calibrator { + def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); +} + +//############################################################################ +// Tail calls in different contexts + +class Class { + def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); +} + +class SubClass extends Class { + override def f(n: Int, v: Int): Int = v; +} + +sealed class Sealed { + def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); +} + +class SubSealed extends Sealed { + override def f(n: Int, v: Int): Int = v; +} + +final class Final { + def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); +} + +object Object { + def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); +} + +//############################################################################ +// Tail calls in nested objects/classes + +object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + val c: C = new C; + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + val c: C = new C; + } + val c: C = new C; + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + val c: C = new C; + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + val c: C = new C; + } + val c: C = new C; + } + val c: C = new C; +} + +class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + val c: C = new C; + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + val c: C = new C; + } + val c: C = new C; + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + val c: C = new C; + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + object O { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + class C { + final def f(n: Int, v: Int): Int = if (n == 0) v else f(n - 1, v - 1); + } + val c: C = new C; + } + val c: C = new C; + } + val c: C = new C; +} + +//############################################################################ +// Tail calls with different signatures + +class TailCall[S](s: S) { + def getS: S = s; + + final def f1(n: Int, v: Int): Int = + if (n == 0) v else f1(n - 1, v - 1); + final def f2[T](n: Int, v: Int): Int = + if (n == 0) v else f2[T](n - 1, v - 1); + final def f3[T](n: Int, v: Int, ls: List[T]): Int = + if (n == 0) v else f3(n - 1, v - 1, ls); + + final def g1(x: Int, y: Int): Int = { + def aux(n: Int, v: Int): Int = + if (n == 0) v else aux(n - 1, v - 1); + aux(x, y); + } + final def g2[T](x: Int, y: Int): Int = { + def aux[U](n: Int, v: Int): Int = + if (n == 0) v else aux[U](n - 1, v - 1); + aux[T](x, y); + } + final def g3[T](x: Int, y: Int, zs: List[T]): Int = { + def aux[U](n: Int, v: Int, ls: List[Pair[T,U]]): Int = + if (n == 0) v else aux(n - 1, v - 1, ls); + aux(x, y, Nil); + } + + def h1(n: Int, v: Int): Int = hP(n, v); + private def hP(n: Int, v: Int): Int = if (n == 0) v else hP(n - 1, v - 1); + + // !!! test return in non-tail-call position + // !!! test non-same-instance calls + // !!! test non-same-type calls + +} + +//############################################################################ +// Test code + +object Test { + def check_success(name: String, closure: => Int, expected: Int): Unit = { + Console.print("test " + name); + try { + val actual: Int = closure; + if (actual == expected) { + Console.print(" was successful"); + } else { + Console.print(" failed: expected "+ expected +", found "+ actual); + } + } catch { + case exception: Throwable => { + Console.print(" raised exception " + exception); + } + } + Console.println; + } + + def calibrate: Int = { + val calibrator = new Calibrator(); + var stop = false; + var n = 1; + while (!stop) { + try { + calibrator.f(n, n); + if (n >= scala.runtime.compat.Math.MAX_INT / 2) error("calibration failure"); + n = 2 * n; + } catch { + case exception: StackOverflowError => stop = true + } + } + 4 * n; + } + + def main(args: Array[String]): Unit = { + // compute min and max iteration number + val min = 16; + val max = calibrate; + + // test tail calls in different contexts + val Final = new Final(); + val Class = new Class(); + val SubClass = new SubClass(); + val Sealed = new Sealed(); + val SubSealed = new SubSealed(); + check_success("Object .f", Object .f(max, max), 0); + check_success("Final .f", Final .f(max, max), 0); + check_success("Class .f", Class .f(max, max), 0); + check_success("SubClass .f", SubClass .f(max, max), max); + check_success("Sealed .f", Sealed .f(max, max), 0); + check_success("SubSealed.f", SubSealed.f(max, max), max); + Console.println; + + // test tail calls in nested classes/objects + val c: C = new C; + check_success("O .f", O .f(max, max), 0); + check_success("c .f", c .f(max, max), 0); + check_success("O.O .f", O.O .f(max, max), 0); + check_success("O.c .f", O.c .f(max, max), 0); + check_success("c.O .f", c.O .f(max, max), 0); + check_success("c.c .f", c.c .f(max, max), 0); + check_success("O.O.O .f", O.O.O .f(max, max), 0); + check_success("O.O.c .f", O.O.c .f(max, max), 0); + check_success("O.c.O .f", O.c.O .f(max, max), 0); + check_success("O.c.c .f", O.c.c .f(max, max), 0); + check_success("c.O.O .f", c.O.O .f(max, max), 0); + check_success("c.O.c .f", c.O.c .f(max, max), 0); + check_success("c.c.O .f", c.c.O .f(max, max), 0); + check_success("c.c.c .f", c.c.c .f(max, max), 0); + check_success("O.O.O.O.f", O.O.O.O.f(max, max), 0); + check_success("O.O.O.c.f", O.O.O.c.f(max, max), 0); + check_success("O.O.c.O.f", O.O.c.O.f(max, max), 0); + check_success("O.O.c.c.f", O.O.c.c.f(max, max), 0); + check_success("O.c.O.O.f", O.c.O.O.f(max, max), 0); + check_success("O.c.O.c.f", O.c.O.c.f(max, max), 0); + check_success("O.c.c.O.f", O.c.c.O.f(max, max), 0); + check_success("O.c.c.c.f", O.c.c.c.f(max, max), 0); + check_success("c.O.O.O.f", c.O.O.O.f(max, max), 0); + check_success("c.O.O.c.f", c.O.O.c.f(max, max), 0); + check_success("c.O.c.O.f", c.O.c.O.f(max, max), 0); + check_success("c.O.c.c.f", c.O.c.c.f(max, max), 0); + check_success("c.c.O.O.f", c.c.O.O.f(max, max), 0); + check_success("c.c.O.c.f", c.c.O.c.f(max, max), 0); + check_success("c.c.c.O.f", c.c.c.O.f(max, max), 0); + check_success("c.c.c.c.f", c.c.c.c.f(max, max), 0); + Console.println; + + // test tail calls with different signatures + val TailCall = new TailCall("S"); + check_success("TailCall.f1", TailCall.f1(max, max ), 0); + check_success("TailCall.f2", TailCall.f2(max, max ), 0); + check_success("TailCall.f3", TailCall.f3(max, max, Nil), 0); + check_success("TailCall.g1", TailCall.g1(max, max ), 0); + check_success("TailCall.g2", TailCall.g2(max, max ), 0); + check_success("TailCall.g3", TailCall.g3(max, max, Nil), 0); + check_success("TailCall.h1", TailCall.h1(max, max ), 0); + Console.println; + } +} + +//############################################################################ |