From 48fdb8620aeb3253f0048667044b39301c1d77c8 Mon Sep 17 00:00:00 2001 From: Geoffrey Washburn Date: Mon, 7 Apr 2008 12:15:54 +0000 Subject: New reorg plan --- src/android-library/scala/ScalaObject.scala | 23 + src/cldc-library/scala/Array.scala | 430 +++++++ src/cldc-library/scala/Console.scala | 96 ++ src/cldc-library/scala/List.scala | 1244 ++++++++++++++++++ src/cldc-library/scala/Math.scala | 56 + src/cldc-library/scala/Predef.scala | 285 +++++ src/cldc-library/scala/Random.scala | 41 + src/cldc-library/scala/StringBuilder.scala | 862 +++++++++++++ src/cldc-library/scala/Symbol.scala | 48 + .../collection/mutable/CloneableCollection.scala | 19 + src/cldc-library/scala/compat/Platform.scala | 56 + src/cldc-library/scala/runtime/BooleanRef.java | 19 + src/cldc-library/scala/runtime/BoxedAnyArray.scala | 234 ++++ .../scala/runtime/BoxedObjectArray.scala | 73 ++ src/cldc-library/scala/runtime/BoxedUnit.java | 33 + src/cldc-library/scala/runtime/BoxesRunTime.java | 361 ++++++ src/cldc-library/scala/runtime/BoxesUtility.java | 147 +++ src/cldc-library/scala/runtime/ByteRef.java | 19 + src/cldc-library/scala/runtime/CharRef.java | 19 + src/cldc-library/scala/runtime/Comparator.java | 53 + src/cldc-library/scala/runtime/IntRef.java | 19 + src/cldc-library/scala/runtime/LongRef.java | 19 + src/cldc-library/scala/runtime/ObjectRef.java | 19 + src/cldc-library/scala/runtime/RichChar.scala | 71 ++ src/cldc-library/scala/runtime/RichException.scala | 29 + src/cldc-library/scala/runtime/RichLong.scala | 30 + src/cldc-library/scala/runtime/RichString.scala | 219 ++++ src/cldc-library/scala/runtime/ScalaRunTime.scala | 142 +++ src/cldc-library/scala/runtime/ShortRef.java | 19 + src/cldc-library/scala/runtime/SquareRoot.scala | 151 +++ src/cldc-library/scala/runtime/StringAdd.scala | 22 + src/dotnet-library/scala/Application.scala | 61 + src/dotnet-library/scala/Console.scala | 298 +++++ src/dotnet-library/scala/List.scala | 1305 +++++++++++++++++++ src/dotnet-library/scala/Math.scala | 135 ++ src/dotnet-library/scala/Predef.scala | 310 +++++ src/dotnet-library/scala/Random.scala | 74 ++ src/dotnet-library/scala/StringBuilder.scala | 709 +++++++++++ src/dotnet-library/scala/Symbol.scala | 49 + src/dotnet-library/scala/compat/Platform.scala | 64 + src/dotnet-library/scala/runtime/BooleanRef.cs | 22 + src/dotnet-library/scala/runtime/BoxedUnit.cs | 36 + src/dotnet-library/scala/runtime/ByteRef.cs | 22 + src/dotnet-library/scala/runtime/CharRef.cs | 22 + src/dotnet-library/scala/runtime/Comparator.cs | 40 + src/dotnet-library/scala/runtime/DoubleRef.cs | 22 + .../scala/runtime/ExceptionHandling.cs | 27 + src/dotnet-library/scala/runtime/FloatRef.cs | 22 + src/dotnet-library/scala/runtime/IntRef.cs | 22 + src/dotnet-library/scala/runtime/LongRef.cs | 22 + src/dotnet-library/scala/runtime/ObjectRef.cs | 22 + src/dotnet-library/scala/runtime/RichChar.scala | 70 + src/dotnet-library/scala/runtime/RichClass.scala | 25 + src/dotnet-library/scala/runtime/RichDouble.scala | 52 + .../scala/runtime/RichException.scala | 21 + src/dotnet-library/scala/runtime/RichFloat.scala | 54 + src/dotnet-library/scala/runtime/RichInt.scala | 39 + src/dotnet-library/scala/runtime/RichLong.scala | 30 + src/dotnet-library/scala/runtime/RichString.scala | 196 +++ src/dotnet-library/scala/runtime/Runnable.cs | 17 + src/dotnet-library/scala/runtime/ShortRef.cs | 22 + src/dotnet-library/scala/runtime/StringAdd.scala | 28 + .../scala/runtime/SymtabAttribute.cs | 22 + .../scala/util/DynamicVariable.scala | 83 ++ src/library/dotnet/scala/Application.scala | 61 - src/library/dotnet/scala/Console.scala | 298 ----- src/library/dotnet/scala/List.scala | 1305 ------------------- src/library/dotnet/scala/Math.scala | 135 -- src/library/dotnet/scala/Predef.scala | 310 ----- src/library/dotnet/scala/Random.scala | 74 -- src/library/dotnet/scala/StringBuilder.scala | 709 ----------- src/library/dotnet/scala/Symbol.scala | 49 - src/library/dotnet/scala/compat/Platform.scala | 64 - src/library/dotnet/scala/runtime/BooleanRef.cs | 22 - src/library/dotnet/scala/runtime/BoxedUnit.cs | 36 - src/library/dotnet/scala/runtime/ByteRef.cs | 22 - src/library/dotnet/scala/runtime/CharRef.cs | 22 - src/library/dotnet/scala/runtime/Comparator.cs | 40 - src/library/dotnet/scala/runtime/DoubleRef.cs | 22 - .../dotnet/scala/runtime/ExceptionHandling.cs | 27 - src/library/dotnet/scala/runtime/FloatRef.cs | 22 - src/library/dotnet/scala/runtime/IntRef.cs | 22 - src/library/dotnet/scala/runtime/LongRef.cs | 22 - src/library/dotnet/scala/runtime/ObjectRef.cs | 22 - src/library/dotnet/scala/runtime/RichChar.scala | 70 - src/library/dotnet/scala/runtime/RichClass.scala | 25 - src/library/dotnet/scala/runtime/RichDouble.scala | 52 - .../dotnet/scala/runtime/RichException.scala | 21 - src/library/dotnet/scala/runtime/RichFloat.scala | 54 - src/library/dotnet/scala/runtime/RichInt.scala | 39 - src/library/dotnet/scala/runtime/RichLong.scala | 30 - src/library/dotnet/scala/runtime/RichString.scala | 196 --- src/library/dotnet/scala/runtime/Runnable.cs | 17 - src/library/dotnet/scala/runtime/ShortRef.cs | 22 - src/library/dotnet/scala/runtime/StringAdd.scala | 28 - .../dotnet/scala/runtime/SymtabAttribute.cs | 22 - .../dotnet/scala/util/DynamicVariable.scala | 83 -- src/library/jvm/android/scala/ScalaObject.scala | 23 - src/library/jvm/cldc/scala/Array.scala | 430 ------- src/library/jvm/cldc/scala/Console.scala | 96 -- src/library/jvm/cldc/scala/List.scala | 1244 ------------------ src/library/jvm/cldc/scala/Math.scala | 56 - src/library/jvm/cldc/scala/Predef.scala | 285 ----- src/library/jvm/cldc/scala/Random.scala | 41 - src/library/jvm/cldc/scala/StringBuilder.scala | 862 ------------- src/library/jvm/cldc/scala/Symbol.scala | 48 - .../collection/mutable/CloneableCollection.scala | 19 - src/library/jvm/cldc/scala/compat/Platform.scala | 56 - src/library/jvm/cldc/scala/runtime/BooleanRef.java | 19 - .../jvm/cldc/scala/runtime/BoxedAnyArray.scala | 234 ---- .../jvm/cldc/scala/runtime/BoxedObjectArray.scala | 73 -- src/library/jvm/cldc/scala/runtime/BoxedUnit.java | 33 - .../jvm/cldc/scala/runtime/BoxesRunTime.java | 361 ------ .../jvm/cldc/scala/runtime/BoxesUtility.java | 147 --- src/library/jvm/cldc/scala/runtime/ByteRef.java | 19 - src/library/jvm/cldc/scala/runtime/CharRef.java | 19 - src/library/jvm/cldc/scala/runtime/Comparator.java | 53 - src/library/jvm/cldc/scala/runtime/IntRef.java | 19 - src/library/jvm/cldc/scala/runtime/LongRef.java | 19 - src/library/jvm/cldc/scala/runtime/ObjectRef.java | 19 - src/library/jvm/cldc/scala/runtime/RichChar.scala | 71 -- .../jvm/cldc/scala/runtime/RichException.scala | 29 - src/library/jvm/cldc/scala/runtime/RichLong.scala | 30 - .../jvm/cldc/scala/runtime/RichString.scala | 219 ---- .../jvm/cldc/scala/runtime/ScalaRunTime.scala | 142 --- src/library/jvm/cldc/scala/runtime/ShortRef.java | 19 - .../jvm/cldc/scala/runtime/SquareRoot.scala | 151 --- src/library/jvm/cldc/scala/runtime/StringAdd.scala | 22 - src/library/jvm/scala/Application.scala | 60 - src/library/jvm/scala/Array.scala | 452 ------- src/library/jvm/scala/BigDecimal.scala | 266 ---- src/library/jvm/scala/BigInt.scala | 365 ------ src/library/jvm/scala/CharSequence.scala | 172 --- src/library/jvm/scala/ClassfileAnnotation.scala | 23 - src/library/jvm/scala/ClassfileAttribute.scala | 26 - src/library/jvm/scala/Console.scala | 345 ----- src/library/jvm/scala/LazyCharSequence.scala | 265 ---- src/library/jvm/scala/List.scala | 1339 -------------------- src/library/jvm/scala/Math.scala | 204 --- src/library/jvm/scala/Predef.scala | 349 ----- src/library/jvm/scala/Random.scala | 72 -- src/library/jvm/scala/StringBuilder.scala | 946 -------------- src/library/jvm/scala/Symbol.scala | 69 - src/library/jvm/scala/compat/Platform.scala | 60 - src/library/jvm/scala/mobile/Code.scala | 247 ---- src/library/jvm/scala/mobile/Location.scala | 100 -- src/library/jvm/scala/ref/PhantomReference.scala | 20 - src/library/jvm/scala/ref/Reference.scala | 27 - src/library/jvm/scala/ref/ReferenceQueue.scala | 27 - src/library/jvm/scala/ref/ReferenceWrapper.scala | 33 - src/library/jvm/scala/ref/SoftReference.scala | 21 - src/library/jvm/scala/ref/WeakReference.scala | 21 - src/library/jvm/scala/testing/Benchmark.scala | 97 -- src/library/jvm/scala/testing/SUnit.scala | 253 ---- src/library/jvm/scala/text/Document.scala | 122 -- src/library/jvm/scala/throws.scala | 30 - src/library/scala/Application.scala | 60 + src/library/scala/Array.scala | 452 +++++++ src/library/scala/BigDecimal.scala | 266 ++++ src/library/scala/BigInt.scala | 365 ++++++ src/library/scala/CharSequence.scala | 172 +++ src/library/scala/ClassfileAnnotation.scala | 23 + src/library/scala/ClassfileAttribute.scala | 26 + src/library/scala/Console.scala | 345 +++++ src/library/scala/LazyCharSequence.scala | 265 ++++ src/library/scala/List.scala | 1339 ++++++++++++++++++++ src/library/scala/Math.scala | 204 +++ src/library/scala/Predef.scala | 349 +++++ src/library/scala/Random.scala | 72 ++ src/library/scala/StringBuilder.scala | 946 ++++++++++++++ src/library/scala/Symbol.scala | 69 + src/library/scala/compat/Platform.scala | 60 + src/library/scala/mobile/Code.scala | 247 ++++ src/library/scala/mobile/Location.scala | 100 ++ src/library/scala/ref/PhantomReference.scala | 20 + src/library/scala/ref/Reference.scala | 27 + src/library/scala/ref/ReferenceQueue.scala | 27 + src/library/scala/ref/ReferenceWrapper.scala | 33 + src/library/scala/ref/SoftReference.scala | 21 + src/library/scala/ref/WeakReference.scala | 21 + src/library/scala/testing/Benchmark.scala | 97 ++ src/library/scala/testing/SUnit.scala | 253 ++++ src/library/scala/text/Document.scala | 122 ++ src/library/scala/throws.scala | 30 + 184 files changed, 14812 insertions(+), 14812 deletions(-) create mode 100644 src/android-library/scala/ScalaObject.scala create mode 100644 src/cldc-library/scala/Array.scala create mode 100644 src/cldc-library/scala/Console.scala create mode 100644 src/cldc-library/scala/List.scala create mode 100644 src/cldc-library/scala/Math.scala create mode 100644 src/cldc-library/scala/Predef.scala create mode 100644 src/cldc-library/scala/Random.scala create mode 100644 src/cldc-library/scala/StringBuilder.scala create mode 100644 src/cldc-library/scala/Symbol.scala create mode 100644 src/cldc-library/scala/collection/mutable/CloneableCollection.scala create mode 100644 src/cldc-library/scala/compat/Platform.scala create mode 100644 src/cldc-library/scala/runtime/BooleanRef.java create mode 100644 src/cldc-library/scala/runtime/BoxedAnyArray.scala create mode 100644 src/cldc-library/scala/runtime/BoxedObjectArray.scala create mode 100644 src/cldc-library/scala/runtime/BoxedUnit.java create mode 100644 src/cldc-library/scala/runtime/BoxesRunTime.java create mode 100644 src/cldc-library/scala/runtime/BoxesUtility.java create mode 100644 src/cldc-library/scala/runtime/ByteRef.java create mode 100644 src/cldc-library/scala/runtime/CharRef.java create mode 100644 src/cldc-library/scala/runtime/Comparator.java create mode 100644 src/cldc-library/scala/runtime/IntRef.java create mode 100644 src/cldc-library/scala/runtime/LongRef.java create mode 100644 src/cldc-library/scala/runtime/ObjectRef.java create mode 100644 src/cldc-library/scala/runtime/RichChar.scala create mode 100644 src/cldc-library/scala/runtime/RichException.scala create mode 100644 src/cldc-library/scala/runtime/RichLong.scala create mode 100644 src/cldc-library/scala/runtime/RichString.scala create mode 100644 src/cldc-library/scala/runtime/ScalaRunTime.scala create mode 100644 src/cldc-library/scala/runtime/ShortRef.java create mode 100644 src/cldc-library/scala/runtime/SquareRoot.scala create mode 100644 src/cldc-library/scala/runtime/StringAdd.scala create mode 100644 src/dotnet-library/scala/Application.scala create mode 100644 src/dotnet-library/scala/Console.scala create mode 100644 src/dotnet-library/scala/List.scala create mode 100644 src/dotnet-library/scala/Math.scala create mode 100644 src/dotnet-library/scala/Predef.scala create mode 100644 src/dotnet-library/scala/Random.scala create mode 100644 src/dotnet-library/scala/StringBuilder.scala create mode 100644 src/dotnet-library/scala/Symbol.scala create mode 100644 src/dotnet-library/scala/compat/Platform.scala create mode 100644 src/dotnet-library/scala/runtime/BooleanRef.cs create mode 100644 src/dotnet-library/scala/runtime/BoxedUnit.cs create mode 100644 src/dotnet-library/scala/runtime/ByteRef.cs create mode 100644 src/dotnet-library/scala/runtime/CharRef.cs create mode 100644 src/dotnet-library/scala/runtime/Comparator.cs create mode 100644 src/dotnet-library/scala/runtime/DoubleRef.cs create mode 100644 src/dotnet-library/scala/runtime/ExceptionHandling.cs create mode 100644 src/dotnet-library/scala/runtime/FloatRef.cs create mode 100644 src/dotnet-library/scala/runtime/IntRef.cs create mode 100644 src/dotnet-library/scala/runtime/LongRef.cs create mode 100644 src/dotnet-library/scala/runtime/ObjectRef.cs create mode 100644 src/dotnet-library/scala/runtime/RichChar.scala create mode 100644 src/dotnet-library/scala/runtime/RichClass.scala create mode 100644 src/dotnet-library/scala/runtime/RichDouble.scala create mode 100644 src/dotnet-library/scala/runtime/RichException.scala create mode 100644 src/dotnet-library/scala/runtime/RichFloat.scala create mode 100644 src/dotnet-library/scala/runtime/RichInt.scala create mode 100644 src/dotnet-library/scala/runtime/RichLong.scala create mode 100644 src/dotnet-library/scala/runtime/RichString.scala create mode 100644 src/dotnet-library/scala/runtime/Runnable.cs create mode 100644 src/dotnet-library/scala/runtime/ShortRef.cs create mode 100644 src/dotnet-library/scala/runtime/StringAdd.scala create mode 100644 src/dotnet-library/scala/runtime/SymtabAttribute.cs create mode 100644 src/dotnet-library/scala/util/DynamicVariable.scala delete mode 100644 src/library/dotnet/scala/Application.scala delete mode 100644 src/library/dotnet/scala/Console.scala delete mode 100644 src/library/dotnet/scala/List.scala delete mode 100644 src/library/dotnet/scala/Math.scala delete mode 100644 src/library/dotnet/scala/Predef.scala delete mode 100644 src/library/dotnet/scala/Random.scala delete mode 100644 src/library/dotnet/scala/StringBuilder.scala delete mode 100644 src/library/dotnet/scala/Symbol.scala delete mode 100644 src/library/dotnet/scala/compat/Platform.scala delete mode 100644 src/library/dotnet/scala/runtime/BooleanRef.cs delete mode 100644 src/library/dotnet/scala/runtime/BoxedUnit.cs delete mode 100644 src/library/dotnet/scala/runtime/ByteRef.cs delete mode 100644 src/library/dotnet/scala/runtime/CharRef.cs delete mode 100644 src/library/dotnet/scala/runtime/Comparator.cs delete mode 100644 src/library/dotnet/scala/runtime/DoubleRef.cs delete mode 100644 src/library/dotnet/scala/runtime/ExceptionHandling.cs delete mode 100644 src/library/dotnet/scala/runtime/FloatRef.cs delete mode 100644 src/library/dotnet/scala/runtime/IntRef.cs delete mode 100644 src/library/dotnet/scala/runtime/LongRef.cs delete mode 100644 src/library/dotnet/scala/runtime/ObjectRef.cs delete mode 100644 src/library/dotnet/scala/runtime/RichChar.scala delete mode 100644 src/library/dotnet/scala/runtime/RichClass.scala delete mode 100644 src/library/dotnet/scala/runtime/RichDouble.scala delete mode 100644 src/library/dotnet/scala/runtime/RichException.scala delete mode 100644 src/library/dotnet/scala/runtime/RichFloat.scala delete mode 100644 src/library/dotnet/scala/runtime/RichInt.scala delete mode 100644 src/library/dotnet/scala/runtime/RichLong.scala delete mode 100644 src/library/dotnet/scala/runtime/RichString.scala delete mode 100644 src/library/dotnet/scala/runtime/Runnable.cs delete mode 100644 src/library/dotnet/scala/runtime/ShortRef.cs delete mode 100644 src/library/dotnet/scala/runtime/StringAdd.scala delete mode 100644 src/library/dotnet/scala/runtime/SymtabAttribute.cs delete mode 100644 src/library/dotnet/scala/util/DynamicVariable.scala delete mode 100644 src/library/jvm/android/scala/ScalaObject.scala delete mode 100644 src/library/jvm/cldc/scala/Array.scala delete mode 100644 src/library/jvm/cldc/scala/Console.scala delete mode 100644 src/library/jvm/cldc/scala/List.scala delete mode 100644 src/library/jvm/cldc/scala/Math.scala delete mode 100644 src/library/jvm/cldc/scala/Predef.scala delete mode 100644 src/library/jvm/cldc/scala/Random.scala delete mode 100644 src/library/jvm/cldc/scala/StringBuilder.scala delete mode 100644 src/library/jvm/cldc/scala/Symbol.scala delete mode 100644 src/library/jvm/cldc/scala/collection/mutable/CloneableCollection.scala delete mode 100644 src/library/jvm/cldc/scala/compat/Platform.scala delete mode 100644 src/library/jvm/cldc/scala/runtime/BooleanRef.java delete mode 100644 src/library/jvm/cldc/scala/runtime/BoxedAnyArray.scala delete mode 100644 src/library/jvm/cldc/scala/runtime/BoxedObjectArray.scala delete mode 100644 src/library/jvm/cldc/scala/runtime/BoxedUnit.java delete mode 100644 src/library/jvm/cldc/scala/runtime/BoxesRunTime.java delete mode 100644 src/library/jvm/cldc/scala/runtime/BoxesUtility.java delete mode 100644 src/library/jvm/cldc/scala/runtime/ByteRef.java delete mode 100644 src/library/jvm/cldc/scala/runtime/CharRef.java delete mode 100644 src/library/jvm/cldc/scala/runtime/Comparator.java delete mode 100644 src/library/jvm/cldc/scala/runtime/IntRef.java delete mode 100644 src/library/jvm/cldc/scala/runtime/LongRef.java delete mode 100644 src/library/jvm/cldc/scala/runtime/ObjectRef.java delete mode 100644 src/library/jvm/cldc/scala/runtime/RichChar.scala delete mode 100644 src/library/jvm/cldc/scala/runtime/RichException.scala delete mode 100644 src/library/jvm/cldc/scala/runtime/RichLong.scala delete mode 100644 src/library/jvm/cldc/scala/runtime/RichString.scala delete mode 100644 src/library/jvm/cldc/scala/runtime/ScalaRunTime.scala delete mode 100644 src/library/jvm/cldc/scala/runtime/ShortRef.java delete mode 100644 src/library/jvm/cldc/scala/runtime/SquareRoot.scala delete mode 100644 src/library/jvm/cldc/scala/runtime/StringAdd.scala delete mode 100644 src/library/jvm/scala/Application.scala delete mode 100644 src/library/jvm/scala/Array.scala delete mode 100644 src/library/jvm/scala/BigDecimal.scala delete mode 100644 src/library/jvm/scala/BigInt.scala delete mode 100644 src/library/jvm/scala/CharSequence.scala delete mode 100644 src/library/jvm/scala/ClassfileAnnotation.scala delete mode 100644 src/library/jvm/scala/ClassfileAttribute.scala delete mode 100644 src/library/jvm/scala/Console.scala delete mode 100644 src/library/jvm/scala/LazyCharSequence.scala delete mode 100644 src/library/jvm/scala/List.scala delete mode 100644 src/library/jvm/scala/Math.scala delete mode 100644 src/library/jvm/scala/Predef.scala delete mode 100644 src/library/jvm/scala/Random.scala delete mode 100644 src/library/jvm/scala/StringBuilder.scala delete mode 100644 src/library/jvm/scala/Symbol.scala delete mode 100644 src/library/jvm/scala/compat/Platform.scala delete mode 100644 src/library/jvm/scala/mobile/Code.scala delete mode 100644 src/library/jvm/scala/mobile/Location.scala delete mode 100644 src/library/jvm/scala/ref/PhantomReference.scala delete mode 100644 src/library/jvm/scala/ref/Reference.scala delete mode 100644 src/library/jvm/scala/ref/ReferenceQueue.scala delete mode 100644 src/library/jvm/scala/ref/ReferenceWrapper.scala delete mode 100644 src/library/jvm/scala/ref/SoftReference.scala delete mode 100644 src/library/jvm/scala/ref/WeakReference.scala delete mode 100644 src/library/jvm/scala/testing/Benchmark.scala delete mode 100644 src/library/jvm/scala/testing/SUnit.scala delete mode 100644 src/library/jvm/scala/text/Document.scala delete mode 100644 src/library/jvm/scala/throws.scala create mode 100644 src/library/scala/Application.scala create mode 100644 src/library/scala/Array.scala create mode 100644 src/library/scala/BigDecimal.scala create mode 100644 src/library/scala/BigInt.scala create mode 100644 src/library/scala/CharSequence.scala create mode 100644 src/library/scala/ClassfileAnnotation.scala create mode 100644 src/library/scala/ClassfileAttribute.scala create mode 100644 src/library/scala/Console.scala create mode 100644 src/library/scala/LazyCharSequence.scala create mode 100644 src/library/scala/List.scala create mode 100644 src/library/scala/Math.scala create mode 100644 src/library/scala/Predef.scala create mode 100644 src/library/scala/Random.scala create mode 100644 src/library/scala/StringBuilder.scala create mode 100644 src/library/scala/Symbol.scala create mode 100644 src/library/scala/compat/Platform.scala create mode 100644 src/library/scala/mobile/Code.scala create mode 100644 src/library/scala/mobile/Location.scala create mode 100644 src/library/scala/ref/PhantomReference.scala create mode 100644 src/library/scala/ref/Reference.scala create mode 100644 src/library/scala/ref/ReferenceQueue.scala create mode 100644 src/library/scala/ref/ReferenceWrapper.scala create mode 100644 src/library/scala/ref/SoftReference.scala create mode 100644 src/library/scala/ref/WeakReference.scala create mode 100644 src/library/scala/testing/Benchmark.scala create mode 100644 src/library/scala/testing/SUnit.scala create mode 100644 src/library/scala/text/Document.scala create mode 100644 src/library/scala/throws.scala diff --git a/src/android-library/scala/ScalaObject.scala b/src/android-library/scala/ScalaObject.scala new file mode 100644 index 0000000000..67b49cbe4e --- /dev/null +++ b/src/android-library/scala/ScalaObject.scala @@ -0,0 +1,23 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import Predef._ + +trait ScalaObject extends AnyRef { + + /** This method is needed for optimizing pattern matching expressions + * which match on constructors of case classes. + */ + def $tag(): Int = 0 + +} diff --git a/src/cldc-library/scala/Array.scala b/src/cldc-library/scala/Array.scala new file mode 100644 index 0000000000..d0e0d68d7b --- /dev/null +++ b/src/cldc-library/scala/Array.scala @@ -0,0 +1,430 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + + +import Predef._ +import compat.Platform.arraycopy + +/** This object contains utility methods operating on arrays. + * + * @author Martin Odersky + * @version 1.0 + */ +object Array { + + /** Copy one array to another. + * Equivalent to + * System.arraycopy(src, srcPos, dest, destPos, length), + * except that this works also for polymorphic and boxed arrays. + * + * @param src ... + * @param srcPos ... + * @param dest ... + * @param destPos ... + * @param length ... + */ + def copy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int): Unit = src match { + case xs: runtime.BoxedArray => + xs.copyTo(srcPos, dest, destPos, length) + case _ => + dest match { + case xs: runtime.BoxedArray => + xs.copyFrom(src, srcPos, destPos, length) + case _ => + arraycopy(src, srcPos, dest, destPos, length) + } + } + + /** Concatenate all argument arrays into a single array. + * + * @param xs ... + */ + def concat[T](xs: Array[T]*) = { + var len = 0 + for (x <- xs) len += x.length + val result = new Array[T](len) + var start = 0 + for (x <- xs) { + copy(x, 0, result, start, x.length) + start += x.length + } + result + } + + /** Create a an array containing of successive integers. + * + * @param from the value of the first element of the array + * @param end the value of the last element fo the array plus 1 + * @return the sorted array of all integers in range [from;end). + */ + def range(start: Int, end: Int): Array[Int] = { + val result = new Array[Int](end - start) + for (i <- start until end) result(i - start) = i + result + } + + /** Create an array with given elements. + * + * @param xs the elements to put in the array + * @return the array containing elements xs. + */ + def apply[A <: AnyRef](xs: A*): Array[A] = { + val array = new Array[A](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + +/* The following metod clashes with the previous one, and has therefore been + * removed. Note that this is a choice between efficiency and generality. + * The previous factory method is more efficient than the one that has been + * commented out. Since it is anyway possible to create a polymorphic array + * using + * new Array[T] + * it was preferred to restrict the definition of the factory method. + + def Array[A](xs: A*): Array[A] = { + val array = new Array[A](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } +*/ + + def apply(xs: Boolean*): Array[Boolean] = { + val array = new Array[Boolean](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + def apply(xs: Byte*): Array[Byte] = { + val array = new Array[Byte](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + def apply(xs: Short*): Array[Short] = { + val array = new Array[Short](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + def apply(xs: Char*): Array[Char] = { + val array = new Array[Char](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + def apply(xs: Int*): Array[Int] = { + val array = new Array[Int](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + def apply(xs: Long*): Array[Long] = { + val array = new Array[Long](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + def apply(xs: Unit*): Array[Unit] = { + val array = new Array[Unit](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + /** Create an array containing several copies of an element. + * + * @param n the length of the resulting array + * @param elem the element composing the resulting array + * @return an array composed of n elements all equal to elem + */ + def make[A](n: Int, elem: A): Array[A] = { + val a = new Array[A](n) + var i = 0 + while (i < n) { + a(i) = elem + i += 1 + } + a + } + + /** This method is called as a result of a pattern match { case Array(...) => } or val Array(...) = .... + * + * @param x the selector value + * @return array wrapped in an option + */ + def unapplySeq[A](x: Array[A]): Option[Seq[A]] = Some(x) + + trait Projection[A] extends RandomAccessSeq.MutableProjection[A] { + protected def newArray[B >: A](length : Int, elements : Iterator[A]) : Array[B] + override def toArray[B >: A] = (newArray(length, elements))//:Any).asInstanceOf[Array[B]] + override def force : Array[A] = toArray + override def drop( from: Int) = slice(from, length) + override def take(until: Int) = slice(0, until) + override def slice(from0 : Int, until0 : Int) : Projection[A] = new RandomAccessSeq.MutableSlice[A] with Projection[A] { + override def from = from0 + override def until = until0 + override def underlying = Projection.this + override protected def newArray[B >: A](length : Int, elements : Iterator[A]) = + underlying.newArray(length, elements) + override def slice(from0 : Int, until0 : Int) = + Projection.this.slice(from + from0, from + until0) + } + override def reverse : Projection[A] = new Projection[A] { + override protected def newArray[B >: A](length : Int, elements : Iterator[A]) = + Projection.this.newArray(length, elements) + def update(idx : Int, what : A) : Unit = Projection.this.update(length - idx - 1, what) + def length = Projection.this.length + def apply(idx : Int) = Projection.this.apply(length - idx - 1) + override def stringPrefix = Projection.this.stringPrefix + "R" + } + } + trait Array0[A] extends RandomAccessSeq.Mutable[A] { + override def projection : Projection[A] = throw new Error + override def slice(from : Int, until : Int) : Projection[A] = projection.slice(from, until) + override def take(until : Int) : Projection[A] = projection.take(until) + override def drop(from : Int) : Projection[A] = projection.drop(from) + override def reverse = projection.reverse + } +} + +/** This class represents polymorphic arrays. Array[T] is Scala's representation + * for Java's T[]. + * + * @author Martin Odersky + * @version 1.0 + */ +final class Array[A](_length: Int) extends Array.Array0[A] { + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int) = { + this(dim1); + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int) = { + this(dim1); + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int) = { + this(dim1); + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int) = { + this(dim1); + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int) = { + this(dim1); + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int) = { + this(dim1); + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int) = { + this(dim1); + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int, dim9: Int) = { + this(dim1); + throw new Error() + } + + /** The length of the array */ + def length: Int = throw new Error() + + /** The element at given index. + *

+ * Indices start a 0; xs.apply(0) is the first + * element of array xs. + *

+ *

+ * Note the indexing syntax xs(i) is a shorthand for + * xs.apply(i). + *

+ * + * @param i the index + * @throws ArrayIndexOutOfBoundsException if i < 0 or + * length <= i + */ + def apply(i: Int): A = throw new Error() + + /**

+ * Update the element at given index. + *

+ *

+ * Indices start a 0; xs.apply(0) is the first + * element of array xs. + *

+ *

+ * Note the indexing syntax xs(i) = x is a shorthand + * for xs.update(i, x). + *

+ * + * @param i the index + * @param x the value to be written at index i + * @throws ArrayIndexOutOfBoundsException if i < 0 or + * length <= i + */ + override def update(i: Int, x: A): Unit = throw new Error() + + /** An iterator returning the elements of this array, starting from 0. + */ + override def elements: Iterator[A] = throw new Error() + + /** @deprecated use slice(from,end).force instead */ + def subArray(from: Int, end: Int): Array[A] = throw new Error() + + /** Returns an array consisting of all elements of this array that satisfy the + * predicate p. The order of the elements is preserved. + * + * @param p the predicate used to filter the array. + * @return the elements of this array satisfying p. + */ + override def filter(p: A => Boolean): Array[A] = throw new Error() + + /** Returns the longest prefix of this array whose elements satisfy + * the predicate p. + * + * @param p the test predicate. + * @return the longest prefix of this array whose elements satisfy + * the predicate p. + */ + override def takeWhile(p: A => Boolean): Array[A] = throw new Error() + + /** Returns the longest suffix of this array whose first element + * does not satisfy the predicate p. + * + * @param p the test predicate. + * @return the longest suffix of the array whose first element + * does not satisfy the predicate p. + */ + override def dropWhile(p: A => Boolean): Array[A] = throw new Error() + + /** Returns an array consisting of all elements of this array followed + * by all elements of the argument iterable. + */ + override def ++[B >: A](that: Iterable[B]): Array[B] = throw new Error() + + /** Returns the array resulting from applying the given function f to each + * element of this array. + * + * @param f function to apply to each element. + * @return [f(a0), ..., f(an)] if this array is [a0, ..., an]. + */ + override def map[B](f: A => B): Array[B] = throw new Error() + + /** Applies the given function f to each element of + * this array, then concatenates the results. + * + * @param f the function to apply on each element. + * @return f(a0) ::: ... ::: f(an) if + * this array is [a0, ..., an]. + */ + override def flatMap[B](f: A => Iterable[B]): Array[B] = throw new Error() + + /** Returns an array formed from this array and the specified array + * that by associating each element of the former with + * the element at the same position in the latter. + * If one of the two arrays is longer than the other, its remaining elements are ignored. + * + * @return Array({a0,b0}, ..., + * {amin(m,n),bmin(m,n)}) when + * Array(a0, ..., am) + * zip Array(b0, ..., bn) is invoked. + */ + def zip[B](that: Array[B]): Array[Tuple2[A,B]] = throw new Error() + + /** Returns an array that pairs each element of this array + * with its index, counting from 0. + * + * @return the array Array({a0,0}, {a1,1},...) + * where ai are the elements of this stream. + */ + def zipWithIndex: Array[Tuple2[A,Int]] = throw new Error() + + /** Returns an array that contains all indices of this array */ + def indices: Array[Int] = throw new Error() + + /** + * @return a deep string representation of this array. + */ + def deepToString(): String = throw new Error() + + /**

+ * Returns a string representation of this array object. The resulting string + * begins with the string start and is finished by the string + * end. Inside, the string representations of elements (w.r.t. + * the method deepToString()) are separated by the string + * sep. For example: + *

+ *

+ * Array(Array(1, 2), Array(3)).deepMkString("[", "; ", "]") = "[[1; 2]; [3]]" + *

+ * + * @param start starting string. + * @param sep separator string. + * @param end ending string. + * @return a string representation of this array object. + */ + def deepMkString(start: String, sep: String, end: String): String = + throw new Error() + + /** Returns a string representation of this array object. The string + * representations of elements (w.r.t. the method deepToString()) + * are separated by the string sep. + * + * @param sep separator string. + * @return a string representation of this array object. + */ + def deepMkString(sep: String): String = throw new Error() + + /**

+ * Returns true if the two specified arrays are + * deeply equal to one another. + *

+ *

+ * Two array references are considered deeply equal if both are null, + * or if they refer to arrays that contain the same number of elements + * and all corresponding pairs of elements in the two arrays are deeply + * equal. + *

+ *

+ * See also method deepEquals in the Java class + * java.utils.Arrays + *

+ * + * @param that the second + * @return true iff both arrays are deeply equal. + */ + def deepEquals(that: Any): Boolean = throw new Error() + +} diff --git a/src/cldc-library/scala/Console.scala b/src/cldc-library/scala/Console.scala new file mode 100644 index 0000000000..43fe2ae894 --- /dev/null +++ b/src/cldc-library/scala/Console.scala @@ -0,0 +1,96 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import java.io.{OutputStream, PrintStream} + +import Predef._ + + +/** The Console object implements functionality for + * printing Scala values on the terminal. There are also functions + * for reading specific values. Console also defines + * constants for marking up text on ANSI terminals. + * + * @author Matthias Zenger + * @version 1.0, 03/09/2003 + */ +object Console { + + // ANSI colors foreground + final val BLACK = "\033[30m" + final val RED = "\033[31m" + final val GREEN = "\033[32m" + final val YELLOW = "\033[33m" + final val BLUE = "\033[34m" + final val MAGENTA = "\033[35m" + final val CYAN = "\033[36m" + final val WHITE = "\033[37m" + + // ANSI colors background + final val BLACK_B = "\033[40m" + final val RED_B = "\033[41m" + final val GREEN_B = "\033[42m" + final val YELLOW_B = "\033[43m" + final val BLUE_B = "\033[44m" + final val MAGENTA_B = "\033[45m" + final val CYAN_B = "\033[46m" + final val WHITE_B = "\033[47m" + + // ANSI styles + final val RESET = "\033[0m" + final val BOLD = "\033[1m" + final val UNDERLINED = "\033[4m" + final val BLINK = "\033[5m" + final val REVERSED = "\033[7m" + final val INVISIBLE = "\033[8m" + + var out: PrintStream = java.lang.System.out + val err = java.lang.System.err + + /** Set the default output stream. + * + * @param out the new output stream. + */ + def setOut(out: PrintStream): Unit = this.out = out + + /** Set the default output stream. + * + * @param@ out the new output stream. + */ + def setOut(out: OutputStream): Unit = + setOut(new PrintStream(out)) + + /** Print an object on the terminal. + * + * @param obj the object to print. + */ + def print(obj: Any): Unit = + out.print(if (null == obj) "null" else obj.toString()) + + /** Flush the output stream. This function is required when partial + * output (i.e. output not terminated by a new line character) has + * to be made visible on the terminal. + */ + def flush(): Unit = out.flush() + + /** Print a new line character on the terminal. + */ + def println(): Unit = out.println() + + /** Print out an object followed by a new line character. + * + * @param x the object to print. + */ + def println(x: Any): Unit = out.println(x) + +} diff --git a/src/cldc-library/scala/List.scala b/src/cldc-library/scala/List.scala new file mode 100644 index 0000000000..4f5693dc4f --- /dev/null +++ b/src/cldc-library/scala/List.scala @@ -0,0 +1,1244 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import scala.collection.mutable.ListBuffer +import Predef._ + +/** This object provides methods for creating specialized lists, and for + * transforming special kinds of lists (e.g. lists of lists). + * + * @author Martin Odersky and others + * @version 1.0, 15/07/2003 + */ +object List { + + /** Create a list with given elements. + * + * @param xs the elements to put in the list + * @return the list containing elements xs. + */ + def apply[A](xs: A*): List[A] = xs.toList + + /** for unapply matching + */ + def unapplySeq[A](x: List[A]): Some[List[A]] = Some(x) + + /** Create a sorted list of all integers in a range. + * + * @param from the start value of the list + * @param end the end value of the list + * @return the sorted list of all integers in range [from;end). + */ + def range(from: Int, end: Int): List[Int] = + range(from, end, 1) + + /** Create a sorted list of all integers in a range. + * + * @param from the start value of the list + * @param end the end value of the list + * @param step the increment value of the list + * @return the sorted list of all integers in range [from;end). + */ + def range(from: Int, end: Int, step: Int): List[Int] = { + val b = new ListBuffer[Int] + var i = from + while (i < end) { + b += i + i += step + } + b.toList + } + + /** Create a sorted list of all integers in a range. + * + * @param from the start value of the list + * @param end the end value of the list + * @param step the increment function of the list + * @return the sorted list of all integers in range [from;end). + */ + def range(from: Int, end: Int, step: Int => Int): List[Int] = { + val b = new ListBuffer[Int] + var i = from + while (i < end) { + b += i + i += step(i) + } + b.toList + } + + /** Create a list containing several copies of an element. + * + * @param n the length of the resulting list + * @param elem the element composing the resulting list + * @return a list composed of n elements all equal to elem + */ + def make[A](n: Int, elem: A): List[A] = { + val b = new ListBuffer[A] + var i = 0 + while (i < n) { + b += elem + i += 1 + } + b.toList + } + + /** Create a list by applying a function to successive integers. + * + * @param n the length of the resulting list + * @param maker the procedure which, given an integer n, + * returns the nth element of the resulting list, where + * n is in interval [0;n). + * @return the list obtained by applying the maker function to + * successive integers from 0 to n (exclusive). + */ + def tabulate[A](n: Int, maker: Int => A): List[A] = { + val b = new ListBuffer[A] + var i = 0 + while (i < n) { + b += maker(i) + i += 1 + } + b.toList + } + + /** Concatenate all the elements of a given list of lists. + * + * @param xss the list of lists that are to be concatenated + * @return the concatenation of all the lists + */ + def flatten[A](xss: List[List[A]]): List[A] = concat(xss: _*) + + /** Concatenate all the argument lists into a single list. + * + * @param xss the lists that are to be concatenated + * @return the concatenation of all the lists + */ + def concat[A](xss: List[A]*): List[A] = { + val b = new ListBuffer[A] + for (xs <- xss) { + var xc = xs + while (!xc.isEmpty) { + b += xc.head + xc = xc.tail + } + } + b.toList + } + + /** Transforms a list of pair into a pair of lists. + * + * @param xs the list of pairs to unzip + * @return a pair of lists: the first list in the pair contains the list + */ + def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = { + val b1 = new ListBuffer[A] + val b2 = new ListBuffer[B] + var xc = xs + while (!xc.isEmpty) { + b1 += xc.head._1 + b2 += xc.head._2 + xc = xc.tail + } + (b1.toList, b2.toList) + } + + /** Converts an iterator to a list. + * + * @param it the iterator to convert + * @return a list that contains the elements returned by successive + * calls to it.next + */ + def fromIterator[A](it: Iterator[A]): List[A] = it.toList + + /** Converts an array into a list. + * + * @param arr the array to convert + * @return a list that contains the same elements than arr + * in the same order + */ + def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length) + + /** Converts a range of an array into a list. + * + * @param arr the array to convert + * @param start the first index to consider + * @param len the lenght of the range to convert + * @return a list that contains the same elements than arr + * in the same order + */ + def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = { + var res: List[A] = Nil + var i = start + len + while (i > start) { + i -= 1 + res = arr(i) :: res + } + res + } + + /** Parses a string which contains substrings separated by a + * separator character and returns a list of all substrings. + * + * @param str the string to parse + * @param separator the separator character + * @return the list of substrings + */ + def fromString(str: String, separator: Char): List[String] = { + var words: List[String] = Nil + var pos = str.length() + while (pos > 0) { + val pos1 = str.lastIndexOf(separator, pos - 1) + if (pos1 + 1 < pos) + words = str.substring(pos1 + 1, pos) :: words + pos = pos1 + } + words + } + + /** Returns the given string as a list of characters. + * + * @param str the string to convert. + * @return the string as a list of characters. + * @deprecated use str.toList instead + */ + @deprecated def fromString(str: String): List[Char] = + str.toList + + /** Returns the given list of characters as a string. + * + * @param xs the list to convert. + * @return the list in form of a string. + */ + def toString(xs: List[Char]): String = { + val sb = new StringBuilder() + var xc = xs + while (!xc.isEmpty) { + sb.append(xc.head) + xc = xc.tail + } + sb.toString() + } + + /** Like xs map f, but returns xs unchanged if function + * f maps all elements to themselves. + * + * @param xs ... + * @param f ... + * @return ... + */ + def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = { + def loop(ys: List[A]): List[A] = + if (ys.isEmpty) xs + else { + val head0 = ys.head + val head1 = f(head0) + if (head1 eq head0) { + loop(ys.tail) + } else { + val ys1 = head1 :: mapConserve(ys.tail)(f) + if (xs eq ys) ys1 + else { + val b = new ListBuffer[A] + var xc = xs + while (xc ne ys) { + b += xc.head + xc = xc.tail + } + b.prependToList(ys1) + } + } + } + loop(xs) + } + + /** Returns the list resulting from applying the given function f + * to corresponding elements of the argument lists. + * + * @param f function to apply to each pair of elements. + * @return [f(a0,b0), ..., f(an,bn)] if the lists are + * [a0, ..., ak], [b0, ..., bl] and + * n = min(k,l) + */ + def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = { + val b = new ListBuffer[C] + var xc = xs + var yc = ys + while (!xc.isEmpty && !yc.isEmpty) { + b += f(xc.head, yc.head) + xc = xc.tail + yc = yc.tail + } + b.toList + } + + /** Returns the list resulting from applying the given function + * f to corresponding elements of the argument lists. + * + * @param f function to apply to each pair of elements. + * @return [f(a0,b0,c0), + * ..., f(an,bn,cn)] + * if the lists are [a0, ..., ak], + * [b0, ..., bl], + * [c0, ..., cm] and + * n = min(k,l,m) + */ + def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = { + val b = new ListBuffer[D] + var xc = xs + var yc = ys + var zc = zs + while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) { + b += f(xc.head, yc.head, zc.head) + xc = xc.tail + yc = yc.tail + zc = zc.tail + } + b.toList + } + + /** Tests whether the given predicate p holds + * for all corresponding elements of the argument lists. + * + * @param p function to apply to each pair of elements. + * @return (p(a0,b0) && + * ... && p(an,bn))] + * if the lists are [a0, ..., ak]; + * [b0, ..., bl] + * and n = min(k,l) + */ + def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { + var xc = xs + var yc = ys + while (!xc.isEmpty && !yc.isEmpty) { + if (!f(xc.head, yc.head)) return false + xc = xc.tail + yc = yc.tail + } + true + } + + /** Tests whether the given predicate p holds + * for some corresponding elements of the argument lists. + * + * @param p function to apply to each pair of elements. + * @return n != 0 && (p(a0,b0) || + * ... || p(an,bn))] if the lists are + * [a0, ..., ak], + * [b0, ..., bl] and + * n = min(k,l) + */ + def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { + var xc = xs + var yc = ys + while (!xc.isEmpty && !yc.isEmpty) { + if (f(xc.head, yc.head)) return true + xc = xc.tail + yc = yc.tail + } + false + } + + /** Transposes a list of lists. + * pre: All element lists have the same length. + * + * @param xss the list of lists + * @return the transposed list of lists + */ + def transpose[A](xss: List[List[A]]): List[List[A]] = + if (xss.head.isEmpty) List() + else (xss map (xs => xs.head)) :: transpose(xss map (xs => xs.tail)) + + /** Lists with ordered elements are ordered + implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] { + def compare [b >: List[a] <% Ordered[b]](y: b): Int = y match { + case y1: List[a] => compareLists(x, y1); + case _ => -(y compare x) + } + private def compareLists(xs: List[a], ys: List[a]): Int = { + if (xs.isEmpty && ys.isEmpty) 0 + else if (xs.isEmpty) -1 + else if (ys.isEmpty) 1 + else { + val s = xs.head compare ys.head; + if (s != 0) s + else compareLists(xs.tail, ys.tail) + } + } + } + */ +} + +/** A class representing an ordered collection of elements of type + * a. This class comes with two implementing case + * classes scala.Nil and scala.:: that + * implement the abstract members isEmpty, + * head and tail. + * + * @author Martin Odersky and others + * @version 1.0, 16/07/2003 + */ +sealed abstract class List[+A] extends Seq[A] { + + /** Returns true if the list does not contain any elements. + * @return true, iff the list is empty. + */ + override def isEmpty: Boolean + + /** Returns this first element of the list. + * + * @return the first element of this list. + * @throws Predef.NoSuchElementException if the list is empty. + */ + def head: A + + /** returns length - l, without calling length + */ + override def lengthCompare(l: Int) = { + if (isEmpty) 0 - l + else if (l <= 0) 1 + else tail.lengthCompare(l - 1) + } + + /** Returns this list without its first element. + * + * @return this list without its first element. + * @throws Predef.NoSuchElementException if the list is empty. + */ + def tail: List[A] + + /**

+ * Add an element x at the beginning of this list. + *

+ * + * @param x the element to append. + * @return the list with x appended at the beginning. + * @ex 1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3) + */ + def ::[B >: A] (x: B): List[B] = + new scala.::(x, this) + + /**

+ * Returns a list resulting from the concatenation of the given + * list prefix and this list. + *

+ * + * @param prefix the list to concatenate at the beginning of this list. + * @return the concatenation of the two lists. + * @ex List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4) + */ + def :::[B >: A](prefix: List[B]): List[B] = + if (isEmpty) prefix + else { + val b = new ListBuffer[B] + var those = prefix + while (!those.isEmpty) { + b += those.head + those = those.tail + } + b.prependToList(this) + } + + /** Reverse the given prefix and append the current list to that. + * This function is equivalent to an application of reverse + * on the prefix followed by a call to :::, but more + * efficient (and tail recursive). + * + * @param prefix the prefix to reverse and then prepend + * @return the concatenation of the reversed prefix and the current list. + */ + def reverse_:::[B >: A](prefix: List[B]): List[B] = { + var these: List[B] = this + var pres = prefix + while (!pres.isEmpty) { + these = pres.head :: these + pres = pres.tail + } + these + } + + /** Returns the number of elements in the list. + * + * @return the number of elements in the list. + */ + def length: Int = { + var these = this + var len = 0 + while (!these.isEmpty) { + len += 1 + these = these.tail + } + len + } + + /** Creates a list with all indices in the list. This is + * equivalent to a call to List.range(0, xs.length). + * + * @return a list of all indices in the list. + */ + def indices: List[Int] = { + val b = new ListBuffer[Int] + var i = 0 + var these = this + while (!these.isEmpty) { + b += i + i += 1 + these = these.tail + } + b.toList + } + + /** Returns the elements in the list as an iterator + * + * @return an iterator on the list elements. + */ + override def elements: Iterator[A] = new Iterator[A] { + var these = List.this + def hasNext: Boolean = !these.isEmpty + def next: A = + if (!hasNext) + throw new NoSuchElementException("next on empty Iterator") + else { + val result = these.head; these = these.tail; result + } + override def toList: List[A] = these + } + + /** Overrides the method in Iterable for efficiency. + * + * @return the list itself + */ + override def toList: List[A] = this + + /** Returns the list without its last element. + * + * @return the list without its last element. + * @throws Predef.UnsupportedOperationException if the list is empty. + */ + def init: List[A] = + if (isEmpty) throw new UnsupportedOperationException("Nil.init") + else { + val b = new ListBuffer[A] + var elem = head + var next = tail + while (!next.isEmpty) { + b += elem + elem = next.head + next = next.tail + } + b.toList + } + + /** Returns the last element of this list. + * + * @return the last element of the list. + * @throws Predef.UnsupportedOperationException if the list is empty. + */ + override def last: A = + if (isEmpty) throw new Predef.NoSuchElementException("Nil.last") + else { + var cur = this + var next = this.tail + while (!next.isEmpty) { + cur = next + next = next.tail + } + cur.head + } + + /** Returns the n first elements of this list, or else the whole + * list, if it has less than n elements. + * + * @param n the number of elements to take. + * @return the n first elements of this list. + */ + override def take(n: Int): List[A] = { + val b = new ListBuffer[A] + var i = 0 + var these = this + while (!these.isEmpty && i < n) { + i += 1 + b += these.head + these = these.tail + } + if (these.isEmpty) this + else b.toList + } + + /** Returns the list with elements belonging to the given index range. + * + * @param start the start position of the list slice. + * @param end the end position (exclusive) of the list slice. + * @return the list with elements belonging to the given index range. + */ + override def slice(start: Int, end: Int): List[A] = { + val s = start max 0 + val e = end min this.length + drop(s) take (e - s) + } + + /** Returns the list without its n first elements. + * If this list has less than n elements, the empty list is returned. + * + * @param n the number of elements to drop. + * @return the list without its n first elements. + */ + override def drop(n: Int): List[A] = { + var these = this + var count = n + while (!these.isEmpty && count > 0) { + these = these.tail + count -= 1 + } + these + } + + /** Returns the rightmost n elements from this list. + * + * @param n the number of elements to take + * @return the suffix of length n of the list + */ + def takeRight(n: Int): List[A] = { + def loop(lead: List[A], lag: List[A]): List[A] = lead match { + case Nil => lag + case _ :: tail => loop(tail, lag.tail) + } + loop(drop(n), this) + } + + /** Returns the list wihout its rightmost n elements. + * + * @param n the number of elements to take + * @return the suffix of length n of the list + */ + def dropRight(n: Int): List[A] = { + def loop(lead: List[A], lag: List[A]): List[A] = lead match { + case Nil => Nil + case _ :: tail => lag.head :: loop(tail, lag.tail) + } + loop(drop(n), this) + } + + /** Split the list at a given point and return the two parts thus + * created. + * + * @param n the position at which to split + * @return a pair of lists composed of the first n + * elements, and the other elements. + */ + def splitAt(n: Int): (List[A], List[A]) = { + val b = new ListBuffer[A] + var i = 0 + var these = this + while (!these.isEmpty && i < n) { + i += 1 + b += these.head + these = these.tail + } + (b.toList, these) + } + + /** Returns the longest prefix of this list whose elements satisfy + * the predicate p. + * + * @param p the test predicate. + * @return the longest prefix of this list whose elements satisfy + * the predicate p. + */ + override def takeWhile(p: A => Boolean): List[A] = { + val b = new ListBuffer[A] + var these = this + while (!these.isEmpty && p(these.head)) { + b += these.head + these = these.tail + } + b.toList + } + + /** Returns the longest suffix of this list whose first element + * does not satisfy the predicate p. + * + * @param p the test predicate. + * @return the longest suffix of the list whose first element + * does not satisfy the predicate p. + */ + override def dropWhile(p: A => Boolean): List[A] = + if (isEmpty || !p(head)) this + else tail dropWhile p + + /** Returns the longest prefix of the list whose elements all satisfy + * the given predicate, and the rest of the list. + * + * @param p the test predicate + * @return a pair consisting of the longest prefix of the list whose + * elements all satisfy p, and the rest of the list. + */ + def span(p: A => Boolean): (List[A], List[A]) = { + val b = new ListBuffer[A] + var these = this + while (!these.isEmpty && p(these.head)) { + b += these.head + these = these.tail + } + (b.toList, these) + } + + /** Like span but with the predicate inverted. + */ + def break(p: A => Boolean): (List[A], List[A]) = span { x => !p(x) } + + /** Returns the n-th element of this list. The first element + * (head of the list) is at position 0. + * + * @param n index of the element to return + * @return the element at position n in this list. + * @throws Predef.NoSuchElementException if the list is too short. + */ + def apply(n: Int): A = drop(n).head + + /** Returns the list resulting from applying the given function f to each + * element of this list. + * + * @param f function to apply to each element. + * @return [f(a0), ..., f(an)] if this list is [a0, ..., an]. + */ + final override def map[B](f: A => B): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + b += f(these.head) + these = these.tail + } + b.toList + } + + /** Apply a function to all the elements of the list, and return the + * reversed list of results. This is equivalent to a call to map + * followed by a call to reverse, but more efficient. + * + * @param f the function to apply to each elements. + * @return the reversed list of results. + */ + def reverseMap[B](f: A => B): List[B] = { + def loop(l: List[A], res: List[B]): List[B] = l match { + case Nil => res + case head :: tail => loop(tail, f(head) :: res) + } + loop(this, Nil) + } + + /** Apply the given function f to each element of this list + * (while respecting the order of the elements). + * + * @param f the treatment to apply to each element. + */ + final override def foreach(f: A => Unit) { + var these = this + while (!these.isEmpty) { + f(these.head) + these = these.tail + } + } + + /** Returns all the elements of this list that satisfy the + * predicate p. The order of the elements is preserved. + * It is guarenteed that the receiver list itself is returned iff all its + * elements satisfy the predicate `p'. Hence the following equality is valid: + * + * (xs filter p) eq xs == xs forall p + * + * @param p the predicate used to filter the list. + * @return the elements of this list satisfying p. + */ + final override def filter(p: A => Boolean): List[A] = { + // return same list if all elements satisfy p + var these = this + while (!these.isEmpty && p(these.head)) { + these = these.tail + } + if (these.isEmpty) this + else { + val b = new ListBuffer[A] + var these1 = this + while (these1 ne these) { + b += these1.head + these1 = these1.tail + } + + these = these.tail // prevent the second evaluation of the predicate + // on the element on which it first failed + while (!these.isEmpty) { + if (p(these.head)) b += these.head + these = these.tail + } + b.toList + } + } + +// final def filterMap[B](f: PartialFunction[A, B]): List[B] = +// this filter f.isDefinedAt map f + + /** Removes all elements of the list which satisfy the predicate + * p. This is like filter with the + * predicate inversed. + * + * @param p the predicate to use to test elements + * @return the list without all elements which satisfy p + */ + def remove(p: A => Boolean): List[A] = filter (x => !p(x)) + + /** Partition the list in two sub-lists according to a predicate. + * + * @param p the predicate on which to partition + * @return a pair of lists: the list of all elements which satisfy + * p and the list of all elements which do not. + * The relative order of the elements in the sub-lists is the + * same as in the original list. + */ + override def partition(p: A => Boolean): (List[A], List[A]) = { + val btrue = new ListBuffer[A] + val bfalse = new ListBuffer[A] + var these = this + while (!these.isEmpty) { + (if (p(these.head)) btrue else bfalse) += these.head + these = these.tail + } + (btrue.toList, bfalse.toList) + } + + /**

+ * Sort the list according to the comparison function + * <(e1: a, e2: a) => Boolean, + * which should be true iff e1 is smaller than + * e2. + *

+ * + * @param lt the comparison function + * @return a list sorted according to the comparison function + * <(e1: a, e2: a) => Boolean. + * @ex
+   *    List("Steve", "Tom", "John", "Bob")
+   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
+   *    List("Bob", "John", "Steve", "Tom")
+ */ + def sort(lt : (A,A) => Boolean): List[A] = { + /** Merge two already-sorted lists */ + def merge(l1: List[A], l2: List[A]): List[A] = { + val res = new ListBuffer[A] + var left1 = l1 + var left2 = l2 + + while (!left1.isEmpty && !left2.isEmpty) { + if(lt(left1.head, left2.head)) { + res += left1.head + left1 = left1.tail + } else { + res += left2.head + left2 = left2.tail + } + } + + res ++= left1 + res ++= left2 + + res.toList + } + + /** Split a list into two lists of about the same size */ + def split(lst: List[A]) = { + val res1 = new ListBuffer[A] + val res2 = new ListBuffer[A] + var left = lst + + while (!left.isEmpty) { + res1 += left.head + left = left.tail + if (!left.isEmpty) { + res2 += left.head + left = left.tail + } + } + + (res1.toList, res2.toList) + } + + + /** Merge-sort the specified list */ + def ms(lst: List[A]): List[A] = + lst match { + case Nil => lst + case x :: Nil => lst + case x :: y :: Nil => + if (lt(x,y)) + lst + else + y :: x :: Nil + + case lst => + val (l1, l2) = split(lst) + val l1s = ms(l1) + val l2s = ms(l2) + merge(l1s, l2s) + } + + ms(this) + } + + + /** Count the number of elements in the list which satisfy a predicate. + * + * @param p the predicate for which to count + * @return the number of elements satisfying the predicate p. + */ + def count(p: A => Boolean): Int = { + var cnt = 0 + var these = this + while (!these.isEmpty) { + if (p(these.head)) cnt += 1 + these = these.tail + } + cnt + } + + /** Tests if the predicate p is satisfied by all elements + * in this list. + * + * @param p the test predicate. + * @return true iff all elements of this list satisfy the + * predicate p. + */ + override def forall(p: A => Boolean): Boolean = { + var these = this + while (!these.isEmpty) { + if (!p(these.head)) return false + these = these.tail + } + true + } + + /** Tests the existence in this list of an element that satisfies the + * predicate p. + * + * @param p the test predicate. + * @return true iff there exists an element in this list that + * satisfies the predicate p. + */ + override def exists(p: A => Boolean): Boolean = { + var these = this + while (!these.isEmpty) { + if (p(these.head)) return true + these = these.tail + } + false + } + + /** Find and return the first element of the list satisfying a + * predicate, if any. + * + * @param p the predicate + * @return the first element in the list satisfying p, + * or None if none exists. + */ + override def find(p: A => Boolean): Option[A] = { + var these = this + while (!these.isEmpty) { + if (p(these.head)) return Some(these.head) + these = these.tail + } + None + } + + /** Combines the elements of this list together using the binary + * function f, from left to right, and starting with + * the value z. + * + * @return f(... (f(f(z, a0), a1) ...), + * an) if the list is + * [a0, a1, ..., an]. + */ + override def foldLeft[B](z: B)(f: (B, A) => B): B = { + var acc = z + var these = this + while (!these.isEmpty) { + acc = f(acc, these.head) + these = these.tail + } + acc + } + + /** Combines the elements of this list together using the binary + * function f, from right to left, and starting with + * the value z. + * + * @return f(a0, f(a1, f(..., f(an, z)...))) + * if the list is [a0, a1, ..., an]. + */ + override def foldRight[B](z: B)(f: (A, B) => B): B = this match { + case Nil => z + case x :: xs => f(x, xs.foldRight(z)(f)) + } + + /** Combines the elements of this list together using the binary + * operator op, from left to right + * @param op The operator to apply + * @return op(... op(a0,a1), ..., an) + if the list has elements + * a0, a1, ..., an. + * @throws Predef.UnsupportedOperationException if the list is empty. + */ + override def reduceLeft[B >: A](f: (B, B) => B): B = this match { + case Nil => throw new UnsupportedOperationException("Nil.reduceLeft") + case x :: xs => ((xs: List[B]) foldLeft (x: B))(f) + } + + /** Combines the elements of this list together using the binary + * operator op, from right to left + * @param op The operator to apply + * + * @return a0 op (... op (an-1 op an)...) + * if the list has elements a0, a1, ..., + * an. + * + * @throws Predef.UnsupportedOperationException if the list is empty. + */ + override def reduceRight[B >: A](f: (B, B) => B): B = this match { + case Nil => throw new UnsupportedOperationException("Nil.reduceRight") + case x :: Nil => x: B + case x :: xs => f(x, xs reduceRight f) + } + + /** Applies the given function f to each element of + * this list, then concatenates the results. + * + * @param f the function to apply on each element. + * @return f(a0) ::: ... ::: f(an) if + * this list is [a0, ..., an]. + */ + final override def flatMap[B](f: A => Iterable[B]): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + var those = f(these.head).elements + while (those.hasNext) { + b += those.next + } + these = these.tail + } + b.toList + } + + /** A list consisting of all elements of this list in reverse order. + */ + override def reverse: List[A] = { + var result: List[A] = Nil + var these = this + while (!these.isEmpty) { + result = these.head :: result + these = these.tail + } + result + } + + /** Returns a list formed from this list and the specified list + * that by associating each element of the former with + * the element at the same position in the latter. + * If one of the two lists is longer than the other, its remaining elements are ignored. + * + * @return List((a0,b0), ..., + * (amin(m,n),bmin(m,n))) when + * List(a0, ..., am) + * zip List(b0, ..., bn) is invoked. + */ + def zip[B](that: List[B]): List[(A, B)] = { + val b = new ListBuffer[(A, B)] + var these = this + var those = that + while (!these.isEmpty && !those.isEmpty) { + b += (these.head, those.head) + these = these.tail + those = those.tail + } + b.toList + } + + /** Returns a list that pairs each element of this list + * with its index, counting from 0. + * + * @return the list List((a0,0), (a1,1), ...) + * where ai are the elements of this list. + */ + def zipWithIndex: List[(A, Int)] = { + val b = new ListBuffer[(A, Int)] + var these = this + var idx = 0 + + while(!these.isEmpty) { + b += (these.head, idx) + these = these.tail + idx += 1 + } + + b.toList + } + + /** Returns a list formed from this list and the specified list + * that by associating each element of the former with + * the element at the same position in the latter. + * + * @param that list that may have a different length + * as the self list. + * @param thisElem element thisElem is used to fill up the + * resulting list if the self list is shorter than + * that + * @param thatElem element thatElem is used to fill up the + * resulting list if that is shorter than + * the self list + * @return List((a0,b0), ..., + * (an,bn), (elem,bn+1), + * ..., {elem,bm}) + * when [a0, ..., an] zip + * [b0, ..., bm] is + * invoked where m > n. + */ + def zipAll[B, C >: A, D >: B](that: List[B], thisElem: C, thatElem: D): List[(C, D)] = { + val b = new ListBuffer[(C, D)] + var these = this + var those = that + while (!these.isEmpty && !those.isEmpty) { + b += (these.head, those.head) + these = these.tail + those = those.tail + } + while (!these.isEmpty) { + b += (these.head, thatElem) + these = these.tail + } + while (!those.isEmpty) { + b += (thisElem, those.head) + those = those.tail + } + b.toList + } + + /** Computes the union of this list and the given list + * that. + * + * @param that the list of elements to add to the list. + * @return a list without doubles containing the elements of this + * list and those of the given list that. + */ + def union[B >: A](that: List[B]): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + if (!that.contains(these.head)) b += these.head + these = these.tail + } + b.prependToList(that) + } + + /** Computes the difference between this list and the given list + * that. + * + * @param that the list of elements to remove from this list. + * @return this list without the elements of the given list + * that. + */ + def diff[B >: A](that: List[B]): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + if (!that.contains(these.head)) b += these.head + these = these.tail + } + b.toList + } + + def flatten[B](implicit f : A => Iterable[B]) : List[B] = { + val buf = new ListBuffer[B] + foreach(f(_).foreach(buf += _)) + buf.toList + } + + + /** Computes the intersection between this list and the given list + * that. + * + * @param that the list to intersect. + * @return the list of elements contained both in this list and + * in the given list that. + */ + def intersect[B >: A](that: List[B]): List[B] = filter(x => that contains x) + + /** Removes redundant elements from the list. Uses the method == + * to decide if two elements are identical. + * + * @return the list without doubles. + */ + def removeDuplicates: List[A] = { + val b = new ListBuffer[A] + var these = this + while (!these.isEmpty) { + if (!these.tail.contains(these.head)) b += these.head + these = these.tail + } + b.toList + } + + override protected def stringPrefix = "List" + override def projection = toStream + override def toStream : Stream[A] = new Stream.Definite[A] { + override def force : List[A] = List.this + override def isEmpty = List.this.isEmpty + override def head = List.this.head + override def tail = List.this.tail.toStream + protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = if (!isEmpty) { + var prefix0 = prefix + var buf1 = buf.append(prefix0).append(head) + prefix0 = ", " + var tail0 = tail + while (!tail0.isEmpty) { + buf1 = buf.append(prefix0).append(tail0.head) + tail0 = tail0.tail + } + buf1 + } else buf + } + +} + +/** The empty list. + * + * @author Martin Odersky + * @version 1.0, 15/07/2003 + */ +@SerialVersionUID(0 - 8256821097970055419L) +case object Nil extends List[Nothing] { + override def isEmpty = true + def head: Nothing = + throw new NoSuchElementException("head of empty list") + def tail: List[Nothing] = + throw new NoSuchElementException("tail of empty list") +} + +/** A non empty list characterized by a head and a tail. + * + * @author Martin Odersky + * @version 1.0, 15/07/2003 + */ +@SerialVersionUID(0L - 8476791151983527571L) +final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] { + def head : B = hd + def tail : List[B] = tl + override def isEmpty: Boolean = false +} + diff --git a/src/cldc-library/scala/Math.scala b/src/cldc-library/scala/Math.scala new file mode 100644 index 0000000000..d33613efd6 --- /dev/null +++ b/src/cldc-library/scala/Math.scala @@ -0,0 +1,56 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +/** The object Math contains methods for performing basic numeric + * operations such as the elementary exponential, logarithm, square root, and + * trigonometric functions. + */ +object Math { + + /** The smalles possible value for scala.Byte. */ + val MIN_BYTE = java.lang.Byte.MIN_VALUE + /** The greatest possible value for scala.Byte. */ + val MAX_BYTE = java.lang.Byte.MAX_VALUE + + /** The smalles possible value for scala.Short. */ + val MIN_SHORT = java.lang.Short.MIN_VALUE + /** The greatest possible value for scala.Short. */ + val MAX_SHORT = java.lang.Short.MAX_VALUE + + /** The smalles possible value for scala.Char. */ + val MIN_CHAR = java.lang.Character.MIN_VALUE + /** The greatest possible value for scala.Char. */ + val MAX_CHAR = java.lang.Character.MAX_VALUE + + /** The smalles possible value for scala.Int. */ + val MIN_INT = java.lang.Integer.MIN_VALUE + /** The greatest possible value for scala.Int. */ + val MAX_INT = java.lang.Integer.MAX_VALUE + + /** The smalles possible value for scala.Long. */ + val MIN_LONG = java.lang.Long.MIN_VALUE + /** The greatest possible value for scala.Long. */ + val MAX_LONG = java.lang.Long.MAX_VALUE + + + def abs(x: Int): Int = java.lang.Math.abs(x) + def abs(x: Long): Long = java.lang.Math.abs(x) + + def max(x: Int, y: Int): Int = java.lang.Math.max(x, y) + def max(x: Long, y: Long): Long = java.lang.Math.max(x, y) + + def min(x: Int, y: Int): Int = java.lang.Math.min(x, y) + def min(x: Long, y: Long): Long = java.lang.Math.min(x, y) + + def sqrt(x: Int): Int = runtime.SquareRoot.accurateSqrt(x) +} diff --git a/src/cldc-library/scala/Predef.scala b/src/cldc-library/scala/Predef.scala new file mode 100644 index 0000000000..385541a71a --- /dev/null +++ b/src/cldc-library/scala/Predef.scala @@ -0,0 +1,285 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + + +/** The Predef object provides definitions that are + * accessible in all Scala compilation units without explicit + * qualification. + */ +object Predef { + + // classOf dummy ------------------------------------------------------ + + /** Return the runtime representation of a class type. */ + def classOf[T]: Class[T] = null + + // aliases ------------------------------------------------------------ + + type byte = scala.Byte + type short = scala.Short + type char = scala.Char + type int = scala.Int + type long = scala.Long + type boolean = scala.Boolean + type unit = scala.Unit + + /** @deprecated use Int instead */ + @deprecated type Integer = java.lang.Integer + /** @deprecated use Char instead */ + @deprecated type Character = java.lang.Character + + type String = java.lang.String + type Class[T] = java.lang.Class[T] + type Runnable = java.lang.Runnable + + type Throwable = java.lang.Throwable + type Exception = java.lang.Exception + type Error = java.lang.Error + + type AssertionError = java.lang.Error + type RuntimeException = java.lang.RuntimeException + type NullPointerException = java.lang.NullPointerException + type ClassCastException = java.lang.ClassCastException + type IndexOutOfBoundsException = java.lang.IndexOutOfBoundsException + type ArrayIndexOutOfBoundsException = java.lang.ArrayIndexOutOfBoundsException + type StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException + type UnsupportedOperationException = RuntimeException //java.lang.UnsupportedOperationException + type IllegalArgumentException = java.lang.IllegalArgumentException + type NoSuchElementException = java.util.NoSuchElementException + type NumberFormatException = java.lang.NumberFormatException + + // miscelleaneous ----------------------------------------------------- + + //val $scope = scala.xml.TopScope + + type Function[-A, +B] = Function1[A, B] + + type Map[A, B] = collection.immutable.Map[A, B] + type Set[A] = collection.immutable.Set[A] + + val Map = collection.immutable.Map + val Set = collection.immutable.Set + + // errors and asserts ------------------------------------------------- + + def error(message: String): Nothing = throw new Error(message) + + def exit: Nothing = exit(0) + + def exit(status: Int): Nothing = { + java.lang.System.exit(status) + throw new Throwable() + } + + def assert(assertion: Boolean) { + if (!assertion) + throw new AssertionError("assertion failed") + } + + def assert(assertion: Boolean, message: Any) { + if (!assertion) + throw new AssertionError("assertion failed: " + message) + } + + def assume(assumption: Boolean) { + if (!assumption) + throw new IllegalArgumentException("assumption failed") + } + + def assume(assumption: Boolean, message: Any) { + if (!assumption) + throw new IllegalArgumentException("assumption failed: " + message) + } + + // tupling ------------------------------------------------------------ + + type Pair[+A, +B] = Tuple2[A, B] + object Pair { + def apply[A, B](x: A, y: B) = Tuple2(x, y) + def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x) + } + + type Triple[+A, +B, +C] = Tuple3[A, B, C] + object Triple { + def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z) + def unapply[A, B, C](x: Tuple3[A, B, C]): Option[Tuple3[A, B, C]] = Some(x) + } + + class ArrowAssoc[A](x: A) { + def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y) + } + implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x) + + def Tuple[A1](x1: A1) = Tuple1(x1) + def Tuple[A1, A2](x1: A1, x2: A2) = Tuple2(x1, x2) + def Tuple[A1, A2, A3](x1: A1, x2: A2, x3: A3) = Tuple3(x1, x2, x3) + def Tuple[A1, A2, A3, A4](x1: A1, x2: A2, x3: A3, x4: A4) = Tuple4(x1, x2, x3, x4) + def Tuple[A1, A2, A3, A4, A5](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5) = Tuple5(x1, x2, x3, x4, x5) + def Tuple[A1, A2, A3, A4, A5, A6](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6) = Tuple6(x1, x2, x3, x4, x5, x6) + def Tuple[A1, A2, A3, A4, A5, A6, A7](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7) = Tuple7(x1, x2, x3, x4, x5, x6, x7) + def Tuple[A1, A2, A3, A4, A5, A6, A7, A8](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8) = Tuple8(x1, x2, x3, x4, x5, x6, x7, x8) + def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9) = Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9) + + // printing and reading ----------------------------------------------- + + def print(x: Any) = Console.print(x) + def println() = Console.println() + def println(x: Any) = Console.println(x) + + // views -------------------------------------------------------------- + + implicit def identity[A](x: A): A = x + + implicit def byteWrapper(x: Byte) = new runtime.RichByte(x) + implicit def shortWrapper(x: Short) = new runtime.RichShort(x) + implicit def intWrapper(x: Int) = new runtime.RichInt(x) + implicit def charWrapper(c: Char) = new runtime.RichChar(c) + implicit def longWrapper(x: Long) = new runtime.RichLong(x) + + implicit def booleanWrapper(x: Boolean) = new runtime.RichBoolean(x) + + implicit def stringWrapper(x: String) = new runtime.RichString(x) + implicit def stringBuilderWrapper(x : StringBuilder) = new runtime.RichStringBuilder(x) + + implicit def any2stringadd(x: Any) = new runtime.StringAdd(x) + + implicit def exceptionWrapper(exc: Throwable) = new runtime.RichException(exc) + + implicit def unit2ordered(x: Unit): Ordered[Unit] = new Ordered[Unit] with Proxy { + def self: Any = x + def compare(y: Unit): Int = 0 + } + + implicit def iterable2ordered[A <% Ordered[A]](xs: Iterable[A]): Ordered[Iterable[A]] = + new Ordered[Iterable[A]] with Proxy { + val self = xs + def compare(that: Iterable[A]): Int = { + var res = 0 + val these = xs.elements + val those = that.elements + while (res == 0 && these.hasNext) + res = if (those.hasNext) these.next compare those.next else 1 + if (res == 0) { + if (those.hasNext) -1 else 0 + } else + res + } + } + + implicit def tuple22ordered[A1 <% Ordered[A1], A2 <% Ordered[A2]](x: Tuple2[A1, A2]): Ordered[Tuple2[A1, A2]] = + new Ordered[Tuple2[A1, A2]] with Proxy { + val self = x + def compare(y: Tuple2[A1, A2]): Int = { + val res = x._1 compare y._1 + if (res == 0) x._2 compare y._2 + else res + } + } + + implicit def tuple32ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3]](x: Tuple3[A1, A2, A3]): Ordered[Tuple3[A1, A2, A3]] = + new Ordered[Tuple3[A1, A2, A3]] with Proxy { + val self = x + def compare(y: Tuple3[A1, A2, A3]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple2(x._2, x._3) compare Tuple2(y._2, y._3) + else res + } + } + + implicit def tuple42ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4]](x: Tuple4[A1, A2, A3, A4]): Ordered[Tuple4[A1, A2, A3, A4]] = + new Ordered[Tuple4[A1, A2, A3, A4]] with Proxy { + val self = x + def compare(y: Tuple4[A1, A2, A3, A4]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple3(x._2, x._3, x._4) compare Tuple3(y._2, y._3, y._4) + else res + } + } + + implicit def tuple52ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5]](x: Tuple5[A1, A2, A3, A4, A5]): Ordered[Tuple5[A1, A2, A3, A4, A5]] = + new Ordered[Tuple5[A1, A2, A3, A4, A5]] with Proxy { + val self = x + def compare(y: Tuple5[A1, A2, A3, A4, A5]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple4(x._2, x._3, x._4, x._5) compare Tuple4(y._2, y._3, y._4, y._5) + else res + } + } + + implicit def tuple62ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6]](x: Tuple6[A1, A2, A3, A4, A5, A6]): Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] = + new Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] with Proxy { + val self = x + def compare(y: Tuple6[A1, A2, A3, A4, A5, A6]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple5(x._2, x._3, x._4, x._5, x._6) compare Tuple5(y._2, y._3, y._4, y._5, y._6) + else res + } + } + + implicit def tuple72ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7]](x: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] = + new Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] with Proxy { + val self = x + def compare(y: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple6(x._2, x._3, x._4, x._5, x._6, x._7) compare Tuple6(y._2, y._3, y._4, y._5, y._6, y._7) + else res + } + } + + implicit def tuple82ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8]](x: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] = + new Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] with Proxy { + val self = x + def compare(y: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple7(x._2, x._3, x._4, x._5, x._6, x._7, x._8) compare Tuple7(y._2, y._3, y._4, y._5, y._6, y._7, y._8) + else res + } + } + + implicit def tuple92ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8], A9 <% Ordered[A9]](x: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] = + new Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] with Proxy { + val self = x + def compare(y: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple8(x._2, x._3, x._4, x._5, x._6, x._7, x._8, x._9) compare Tuple8(y._2, y._3, y._4, y._5, y._6, y._7, y._8, y._9) + else res + } + } + + implicit def byte2short(x: Byte): Short = x.toShort + implicit def byte2int(x: Byte): Int = x.toInt + implicit def byte2long(x: Byte): Long = x.toLong + + implicit def short2int(x: Short): Int = x.toInt + implicit def short2long(x: Short): Long = x.toLong + + implicit def char2int(x: Char): Int = x.toInt + implicit def char2long(x: Char): Long = x.toLong + + implicit def int2long(x: Int): Long = x.toLong + + implicit def byte2Byte(x: Byte) = new java.lang.Byte(x) + implicit def short2Short(x: Short) = new java.lang.Short(x) + implicit def char2Character(x: Char) = new java.lang.Character(x) + implicit def int2Integer(x: Int) = new java.lang.Integer(x) + implicit def long2Long(x: Long) = new java.lang.Long(x) + implicit def boolean2Boolean(x: Boolean) = new java.lang.Boolean(x) + + /** any array projection can be automatically converted into an array */ + implicit def forceArrayProjection[A](x: Array.Projection[A]): Array[A] = x.force + /** any random access character seq (including rich string can be converted into a string */ + implicit def forceRandomAccessCharSeq(x: runtime.RichString): String = x.mkString + + def currentThread = java.lang.Thread.currentThread() + +} diff --git a/src/cldc-library/scala/Random.scala b/src/cldc-library/scala/Random.scala new file mode 100644 index 0000000000..9168166752 --- /dev/null +++ b/src/cldc-library/scala/Random.scala @@ -0,0 +1,41 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +/** (see http://java.sun.com/javame/reference/apis/jsr030/) + * + * @author Stephane Micheloud + */ +class Random(val self: java.util.Random) { + + /** Creates a new random number generator using a single long seed. */ + def this(seed: Long) = this(new java.util.Random(seed)) + + /** Creates a new random number generator using a single integer seed. */ + def this(seed: Int) = this(seed.toLong) + + /** Creates a new random number generator. */ + def this() = this(compat.Platform.currentTime) + + /** Returns the next pseudorandom, uniformly distributed int value + * from this random number generator's sequence. + */ + def nextInt(): Int = self.nextInt() + + /** Returns the next pseudorandom, uniformly distributed long value + * from this random number generator's sequence. + */ + def nextLong(): Long = self.nextLong() + + def setSeed(seed: Long) { self.setSeed(seed) } + +} diff --git a/src/cldc-library/scala/StringBuilder.scala b/src/cldc-library/scala/StringBuilder.scala new file mode 100644 index 0000000000..eab003d33c --- /dev/null +++ b/src/cldc-library/scala/StringBuilder.scala @@ -0,0 +1,862 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import Predef._ + +/**

+ * A mutable sequence of characters. This class provides an API compatible + * with java.lang.StringBuilder, but with no guarantee of + * synchronization. + *

+ * + * @author Stephane Micheloud + * @version 1.0 + */ +final class StringBuilder(initCapacity: Int, private val initValue: String) +extends (Int => Char) with Proxy { + if (initCapacity < 0) throw new IllegalArgumentException + if (initValue eq null) throw new NullPointerException + + /** The value is used for character storage. */ + private var value = new Array[Char](initCapacity + initValue.length) + + /** The count is the number of characters used. */ + private var count: Int = 0 + + /** Constructs a string builder with no characters in it and an + * initial capacity of 16 characters. + */ + def this() = this(16, "") + + /** Constructs a string builder with no characters in it and an + * initial capacity specified by the capacity argument. + * + * @param capacity the initial capacity. + * @throws NegativeArraySizeException if the capacity + * argument is less than 0. + */ + def this(capacity: Int) = this(capacity, "") + + def this(str: String) = this(16, str) + + append(initValue) + + def self = this + + def toArray: Array[Char] = value + + def length: Int = count + + def length_=(n: Int) { setLength(n) } + + /** Sets the length of the character sequence. + * + * @param newLength the new length + * @throws IndexOutOfBoundsException if the n argument is negative. + */ + def setLength(n: Int) { + if (n < 0) + throw new StringIndexOutOfBoundsException(n) + if (n > value.length) expandCapacity(n) + if (count < n) + while (count < n) { + value(count) = '\0'; count += 1 + } + else + count = n + } + + /** Returns the current capacity. The capacity is the amount of storage + * available for newly inserted characters, beyond which an allocation + * will occur. + * + * @return the current capacity + */ + def capacity: Int = value.length + + /** Same as ensureCapacity. */ + def capacity_=(n: Int) { ensureCapacity(n) } + + /**

+ * Ensures that the capacity is at least equal to the specified minimum. + * If the current capacity is less than the argument, then a new internal + * array is allocated with greater capacity. The new capacity is the larger of: + *

+ * + *

+ * If the n argument is non-positive, this + * method takes no action and simply returns. + *

+ * + * @param n the minimum desired capacity. + */ + def ensureCapacity(n: Int) { + if (n > value.length) expandCapacity(n) + } + + private def expandCapacity(n: Int) { + val newCapacity = (value.length + 1) * 2 + value = StringBuilder.copyOf( + value, + if (newCapacity < 0) Math.MAX_INT else if (n > newCapacity) n else newCapacity + ) + } + + /**

+ * Returns the Char value in this sequence at the specified index. + * The first Char value is at index 0, the next at index + * 1, and so on, as in array indexing. + *

+ *

+ * The index argument must be greater than or equal to + * 0, and less than the length of this sequence. + *

+ * + * @param index the index of the desired Char value. + * @return the Char value at the specified index. + * @throws IndexOutOfBoundsException if index is + * negative or greater than or equal to length(). + */ + def charAt(index: Int): Char = { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException(index) + value(index) + } + + /** Same as charAt. */ + def apply(i: Int): Char = charAt(i) + + /**

+ * Removes the Char at the specified position in this + * sequence. This sequence is shortened by one Char. + *

+ * + * @param index Index of Char to remove + * @return This object. + * @throws StringIndexOutOfBoundsException if the index + * is negative or greater than or equal to length(). + */ + def deleteCharAt(index: Int): StringBuilder = { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException(index) + compat.Platform.arraycopy(value, index + 1, value, index, count - index - 1) + count -= 1 + this + } + + /**

+ * The character at the specified index is set to ch. This + * sequence is altered to represent a new character sequence that is + * identical to the old character sequence, except that it contains the + * character ch at position index. + *

+ *

+ * The index argument must be greater than or equal to + * 0, and less than the length of this sequence. + *

+ * + * @param index the index of the character to modify. + * @param ch the new character. + * @throws IndexOutOfBoundsException if index is + * negative or greater than or equal to length(). + */ + def setCharAt(index: Int, c: Char) { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException(index) + value(index) = c + } + + /** Same as setCharAt. */ + def update(i: Int, c: Char) { setCharAt(i, c) } + + /** Returns a new String that contains a subsequence of + * characters currently contained in this character sequence. The + * substring begins at the specified index and extends to the end of + * this sequence. + * + * @param start The beginning index, inclusive. + * @return The new string. + * @throws StringIndexOutOfBoundsException if start is + * less than zero, or greater than the length of this object. + */ + def substring(start: Int): String = substring(start, count) + + /** Returns a new String that contains a subsequence of + * characters currently contained in this sequence. The + * substring begins at the specified start and + * extends to the character at index end - 1. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @return The new string. + * @throws StringIndexOutOfBoundsException if start + * or end are negative or greater than + * length(), or start is + * greater than end. + */ + def substring(start: Int, end: Int): String = { + if (start < 0) + throw new StringIndexOutOfBoundsException(start) + if (end > count) + throw new StringIndexOutOfBoundsException(end) + if (start > end) + throw new StringIndexOutOfBoundsException(end - start) + new String(value, start, end - start) + } + + /**

+ * Appends the string representation of the Any + * argument. + *

+ *

+ * The argument is converted to a string as if by the method + * String.valueOf, and the characters of that + * string are then appended to this sequence. + *

+ * + * @param x an Any object. + * @return a reference to this object. + */ + def append(x: Any): StringBuilder = + append(String.valueOf(x)) + + /** Appends the specified string to this character sequence. + * + * @param s a string. + * @return a reference to this object. + */ + def append(s: String): StringBuilder = { + val str = if (s == null) "null" else s + val len = str.length + if (len > 0) { + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(str.toCharArray, 0, value, count, len) + count = newCount + } + this + } + + /** Appends the specified string builder to this sequence. + * + * @param sb + * @return + */ + def append(sb: StringBuilder): StringBuilder = + if (sb == null) + append("null") + else { + val len = sb.length + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(sb.toArray, 0, value, count, len) + count = newCount + this + } + + /**

+ * Appends the string representation of the Char sequence + * argument to this sequence. + *

+ *

+ * The characters of the sequence argument are appended, in order, + * to the contents of this sequence. The length of this sequence + * increases by the length of the argument. + *

+ * + * @param x the characters to be appended. + * @return a reference to this object. + */ + def append(x: Seq[Char]): StringBuilder = + append(x.toArray, 0, x.length) + + /**

+ * Appends the string representation of the Char array + * argument to this sequence. + *

+ *

+ * The characters of the array argument are appended, in order, to + * the contents of this sequence. The length of this sequence + * increases by the length of the argument. + *

+ * + * @param x the characters to be appended. + * @return a reference to this object. + */ + def append(x: Array[Char]): StringBuilder = + append(x, 0, x.length) + + /**

+ * Appends the string representation of a subarray of the + * char array argument to this sequence. + *

+ *

+ * Characters of the Char array x, starting at + * index offset, are appended, in order, to the contents + * of this sequence. The length of this sequence increases + * by the value of len. + *

+ * + * @param x the characters to be appended. + * @param offset the index of the first Char to append. + * @param len the number of Chars to append. + * @return a reference to this object. + */ + def append(x: Array[Char], offset: Int, len: Int): StringBuilder = { + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(x, offset, value, count, len) + count = newCount + this + } + + /**

+ * Appends the string representation of the Boolean + * argument to the sequence. + *

+ *

+ * The argument is converted to a string as if by the method + * String.valueOf, and the characters of that + * string are then appended to this sequence. + *

+ * + * @param x a Boolean. + * @return a reference to this object. + */ + def append(x: Boolean): StringBuilder = { + if (x) { + val newCount = count + 4 + if (newCount > value.length) expandCapacity(newCount) + value(count) = 't'; count += 1 + value(count) = 'r'; count += 1 + value(count) = 'u'; count += 1 + value(count) = 'e'; count += 1 + } else { + val newCount = count + 5 + if (newCount > value.length) expandCapacity(newCount) + value(count) = 'f'; count += 1 + value(count) = 'a'; count += 1 + value(count) = 'l'; count += 1 + value(count) = 's'; count += 1 + value(count) = 'e'; count += 1 + } + this + } + + def append(x: Byte): StringBuilder = + append(String.valueOf(x)) + + def append(x: Char): StringBuilder = { + val newCount = count + 1 + if (newCount > value.length) expandCapacity(newCount) + value(count) = x; count += 1 + this + } + + def append(x: Short): StringBuilder = + append(String.valueOf(x)) + + def append(x: Int): StringBuilder = + append(String.valueOf(x)) + + def append(x: Long): StringBuilder = + append(String.valueOf(x)) + + /** Removes the characters in a substring of this sequence. + * The substring begins at the specified start and extends to + * the character at index end - 1 or to the end of the + * sequence if no such character exists. If + * start is equal to end, no changes are made. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @return This object. + * @throws StringIndexOutOfBoundsException if start + * is negative, greater than length(), or + * greater than end. + */ + def delete(start: Int, end: Int): StringBuilder = { + if (start < 0 || start > end) + throw new StringIndexOutOfBoundsException(start) + val end0 = if (end > count) count else end + val len = end0 - start + if (len > 0) { + compat.Platform.arraycopy(value, start + len, value, start, count - end0) + count -= len + } + this + } + + /** Replaces the characters in a substring of this sequence + * with characters in the specified String. The substring + * begins at the specified start and extends to the character + * at index end - 1 or to the end of the sequence if no such + * character exists. First the characters in the substring are removed and + * then the specified String is inserted at start. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @param str String that will replace previous contents. + * @return This object. + * @throws StringIndexOutOfBoundsException if start + * is negative, greater than length(), or + * greater than end. + */ + def replace(start: Int, end: Int, str: String) { + if (start < 0 || start > count || start > end) + throw new StringIndexOutOfBoundsException(start) + + val end0 = if (end > count) count else end + val len = str.length() + val newCount = count + len - (end0 - start) + if (newCount > value.length) expandCapacity(newCount) + + compat.Platform.arraycopy(value, end, value, start + len, count - end) + compat.Platform.arraycopy(str.toArray, 0, value, start, len) + count = newCount + this + } + + /** Inserts the string representation of a subarray of the str + * array argument into this sequence. The subarray begins at the specified + * offset and extends len chars. + * The characters of the subarray are inserted into this sequence at + * the position indicated by index. The length of this + * sequence increases by len Chars. + * + * @param index position at which to insert subarray. + * @param str a Char array. + * @param offset the index of the first char in subarray to + * be inserted. + * @param len the number of Chars in the subarray to + * be inserted. + * @return This object + * @throws StringIndexOutOfBoundsException if index + * is negative or greater than length(), or + * offset or len are negative, or + * (offset+len) is greater than + * str.length. + */ + def insert(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = { + if (index < 0 || index > count) + throw new StringIndexOutOfBoundsException(index) + if (offset < 0 || len < 0 || offset > str.length - len) + throw new StringIndexOutOfBoundsException( + "offset " + offset + ", len " + len + + ", str.length " + str.length) + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, index, value, index + len, count - index) + compat.Platform.arraycopy(str, offset, value, index, len) + count = newCount + this + } + + /**

+ * Inserts the string representation of the Any + * argument into this character sequence. + *

+ *

+ * The second argument is converted to a string as if by the method + * String.valueOf, and the characters of that + * string are then inserted into this sequence at the indicated + * offset. + *

+ *

+ * The offset argument must be greater than or equal to + * 0, and less than or equal to the length of this + * sequence. + *

+ * + * @param offset the offset. + * @param x an Any value. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: Any): StringBuilder = + insert(at, String.valueOf(x)) + + /** Inserts the string into this character sequence. + * + * @param at the offset position. + * @param x a string. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: String): StringBuilder = { + if (at < 0 || at > count) + throw new StringIndexOutOfBoundsException(at) + val str = if (x == null) "null" else x + val len = str.length + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, at, value, at + len, count - at) + compat.Platform.arraycopy(str.toArray: Array[Char], 0, value, at, len) + count = newCount + this + } + + /** Inserts the string representation of the Char sequence + * argument into this sequence. + * + * @param at the offset position. + * @param x a character sequence. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: Seq[Char]): StringBuilder = + insert(at, x.toArray) + + /** Inserts the string representation of the Char array + * argument into this sequence. + * + * @param at the offset position. + * @param x a character array. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: Array[Char]): StringBuilder = { + if (at < 0 || at > count) + throw new StringIndexOutOfBoundsException(at) + val len = x.length + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, at, value, at + len, count - at) + compat.Platform.arraycopy(x, 0, value, at, len) + count = newCount + this + } + + /**

+ * Inserts the string representation of the Boolean argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Boolean value. + * @return a reference to this object. + */ + def insert(at: Int, x: Boolean): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Inserts the string representation of the Byte argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Byte value. + * @return a reference to this object. + */ + def insert(at: Int, x: Byte): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Inserts the string representation of the Char argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Char value. + * @return a reference to this object. + */ + def insert(at: Int, x: Char): StringBuilder = { + if (at < 0 || at > count) + throw new StringIndexOutOfBoundsException(at) + val newCount = count + 1 + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, at, value, at + 1, count - at) + value(at) = x + count = newCount + this + } + + /**

+ * Inserts the string representation of the Short argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Short value. + * @return a reference to this object. + */ + def insert(at: Int, x: Short): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Inserts the string representation of the Int argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Int value. + * @return a reference to this object. + */ + def insert(at: Int, x: Int): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Inserts the string representation of the Long argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Long value. + * @return a reference to this object. + */ + def insert(at: Int, x: Long): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Returns the index within this string of the first occurrence of the + * specified substring. The integer returned is the smallest value + * k such that: + *

+ *
+   *  this.toString().startsWith(str, k)
+ *
+ *

+ * is true. + *

+ * + * @param str any string. + * @return if the string argument occurs as a substring within this + * object, then the index of the first character of the first + * such substring is returned; if it does not occur as a + * substring, -1 is returned. + * @throws NullPointerException if str is null. + */ + def indexOf(str: String): Int = indexOf(str, 0) + + /**

+ * Returns the index within this string of the first occurrence of the + * specified substring, starting at the specified index. The integer + * returned is the smallest value k for which: + *

+   *    k >= Math.min(fromIndex, str.length()) &&
+   *                   this.toString().startsWith(str, k)
+ *

+ * If no such value of k exists, then -1 + * is returned. + *

+ * + * @param str the substring for which to search. + * @param fromIndex the index from which to start the search. + * @return the index within this string of the first occurrence + * of the specified substring, starting at the specified index. + */ + def indexOf(str: String, fromIndex: Int): Int = + StringBuilder.indexOf(value, 0, count, str.toArray, 0, str.length(), fromIndex) + + /**

+ * Returns the index within this string of the rightmost occurrence + * of the specified substring. The rightmost empty string "" is + * considered to occur at the index value this.length(). + * The returned index is the largest value k such that + *

+ *
+   *  this.toString().startsWith(str, k)
+ *
+ *

+ * is true. + *

+ * + * @param str the substring to search for. + * @return if the string argument occurs one or more times as a substring + * within this object, then the index of the first character of + * the last such substring is returned. If it does not occur as + * a substring, -1 is returned. + * @throws NullPointerException if str is null. + */ + def lastIndexOf(str: String): Int = lastIndexOf(str, count) + + /**

+ * Returns the index within this string of the last occurrence of the + * specified substring. The integer returned is the largest value + * k such that: + *

+   *    k <= Math.min(fromIndex, str.length()) &&
+   *                   this.toString().startsWith(str, k)
+ *

+ * If no such value of k exists, then -1 + * is returned. + *

+ * + * @param str the substring to search for. + * @param fromIndex the index to start the search from. + * @return the index within this sequence of the last occurrence + * of the specified substring. + */ + def lastIndexOf(str: String, fromIndex: Int): Int = + StringBuilder.lastIndexOf(value, 0, count, str.toArray, 0, str.length(), fromIndex) + + /**

+ * Causes this character sequence to be replaced by the reverse of the + * sequence. If there are any surrogate pairs included in the sequence, + * these are treated as single characters for the reverse operation. + * Thus, the order of the high-low surrogates is never reversed. + *

+ *

+ * Let n be the character length of this character sequence + * (not the length in Char values) just prior to + * execution of the reverse method. Then the + * character at index k in the new character sequence is + * equal to the character at index n-k-1 in the old + * character sequence. + *

+ * + * @return a reference to this object. + */ + def reverse(): StringBuilder = { + val n = count - 1 + var j = (n-1) >> 1 + while (j >= 0) { + val temp = value(j) + val temp2 = value(n - j) + value(j) = temp2 + value(n - j) = temp + j -= 1 + } + this + } + + /** Returns a string representing the data in this sequence. + * A new String object is allocated and initialized to + * contain the character sequence currently represented by this + * object. This String is then returned. Subsequent + * changes to this sequence do not affect the contents of the + * String. + * + * @return a string representation of this sequence of characters. + */ + override def toString(): String = new String(value, 0, count) + +} + + +object StringBuilder { + + // method java.util.Arrays.copyOf exists since 1.6 + private def copyOf(src: Array[Char], newLength: Int): Array[Char] = { + val dest = new Array[Char](newLength) + val (start, end) = + if (src.length < newLength) (src.length, newLength) + else (newLength, src.length) + compat.Platform.arraycopy(src, 0, dest, 0, start) + // For any indices that are valid in the copy but not the original, + // the copy will contain '\\u000'. + for (i <- start until end) dest(i) = '\0' + dest + } + + private def indexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, + target: Array[Char], targetOffset: Int, targetCount: Int, + fromIndex: Int): Int = + if (fromIndex >= sourceCount) + if (targetCount == 0) sourceCount else -1 + else { + val inx = if (fromIndex < 0) 0 else fromIndex + if (targetCount == 0) + inx + else { + val first = target(targetOffset) + val max = sourceOffset + (sourceCount - targetCount) + + var i = sourceOffset + inx + while (i <= max) { + /* Look for first character. */ + if (source(i) != first) { + i += 1 + while (i <= max && source(i) != first) i += 1 + } + /* Found first character, now look at the rest of v2 */ + if (i <= max) { + var j = i + 1 + val end = j + targetCount - 1 + var k = targetOffset + 1 + while (j < end && source(j) == target(k)) { + j += 1 + k += 1 + } + if (j == end) { + /* Found whole string. */ + return i - sourceOffset + } + } // if + i += 1 + } // while + -1 + } + } + + private def lastIndexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, + target: Array[Char], targetOffset: Int, targetCount: Int, + fromIndex: Int): Int = { + val rightIndex = sourceCount - targetCount + if (fromIndex < 0) return -1 + val inx = if (fromIndex > rightIndex) rightIndex else fromIndex + // Empty string always matches + if (targetCount == 0) return inx + + val strLastIndex = targetOffset + targetCount - 1 + val strLastChar = target(strLastIndex) + val min = sourceOffset + targetCount - 1 + var i = min + fromIndex + + while (true) { + while (i >= min && source(i) != strLastChar) i -= 1 + if (i < min) return -1 + var j = i - 1 + val start = j - (targetCount - 1) + var k = strLastIndex - 1 + var outerWhile = false + while (j > start && !outerWhile) { + if (source(j) != target(k)) { + j -= 1 + k -= 1 + i -= 1 + outerWhile = true + } + } + if (!outerWhile) return start - sourceOffset + 1 + } + -1 + } +} diff --git a/src/cldc-library/scala/Symbol.scala b/src/cldc-library/scala/Symbol.scala new file mode 100644 index 0000000000..3af5172406 --- /dev/null +++ b/src/cldc-library/scala/Symbol.scala @@ -0,0 +1,48 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +/**

+ * Instances of Symbol can be created easily with + * Scala's built-in quote mechanism. + *

+ *

+ * For instance, the Scala + * term 'mysym will invoke the constructor of the + * Symbol class in the following way: + * new Symbol("mysym"). + *

+ * + * @author Martin Odersky + * @version 1.7, 08/12/2003 + */ +final case class Symbol(name: String) { + + /** Converts this symbol to a string. + */ + override def toString(): String = { + "'" + name + } + + /**

+ * Makes this symbol into a unique reference. + *

+ *

+ * If two interened symbols are equal (i.e. they have the same name) + * then they must be identical (wrt reference equality). + *

+ * + * @return the unique reference to this symbol. + */ + def intern: Symbol = this + +} diff --git a/src/cldc-library/scala/collection/mutable/CloneableCollection.scala b/src/cldc-library/scala/collection/mutable/CloneableCollection.scala new file mode 100644 index 0000000000..fed584e5ba --- /dev/null +++ b/src/cldc-library/scala/collection/mutable/CloneableCollection.scala @@ -0,0 +1,19 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.collection.mutable + +/** The J2ME version of the library defined this trait with a clone method + * to substitute for the lack of Object.clone there + */ +trait CloneableCollection { + def clone(): AnyRef = Predef.error("Cloning not supported") +} diff --git a/src/cldc-library/scala/compat/Platform.scala b/src/cldc-library/scala/compat/Platform.scala new file mode 100644 index 0000000000..6d2ccbcfbb --- /dev/null +++ b/src/cldc-library/scala/compat/Platform.scala @@ -0,0 +1,56 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.compat + + +import java.lang.System +import Predef._ + +object Platform { + + //type StackOverflowError = java.lang.StackOverflowError + type ConcurrentModificationException = java.lang.RuntimeException + + /** + * @param src .. + * @param srcPos .. + * @param dest .. + * @param destPos .. + * @param length .. + */ + def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int): Unit = + System.arraycopy(src, srcPos, dest, destPos, length) + + /** Create array of the same type as arrayInstance with the given + * length. + * + * @param elemClass .. + * @param length .. + * @return .. + */ + def createArray(elemClass: Class[_], length: Int): AnyRef = + throw new RuntimeException("" + elemClass + "[" + length+ "]") + //java.lang.reflect.Array.newInstance(elemClass, length) + + //def arrayclear(arr: Array[Int]): Unit = java.util.Arrays.fill(arr, 0) + def arrayclear(arr: Array[Int]): Unit = for (i <- 0 to arr.length) arr(i) = 0 + + def getClassForName(name: String): Class[_] = java.lang.Class.forName(name) + + val EOL = "\n" + + def currentTime: Long = System.currentTimeMillis() + + def collectGarbage: Unit = System.gc() + +} + diff --git a/src/cldc-library/scala/runtime/BooleanRef.java b/src/cldc-library/scala/runtime/BooleanRef.java new file mode 100644 index 0000000000..a0b2878506 --- /dev/null +++ b/src/cldc-library/scala/runtime/BooleanRef.java @@ -0,0 +1,19 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + + +public class BooleanRef { + public boolean elem; + public BooleanRef(boolean elem) { this.elem = elem; } + public String toString() { return String.valueOf(elem); } +} diff --git a/src/cldc-library/scala/runtime/BoxedAnyArray.scala b/src/cldc-library/scala/runtime/BoxedAnyArray.scala new file mode 100644 index 0000000000..23768c87bd --- /dev/null +++ b/src/cldc-library/scala/runtime/BoxedAnyArray.scala @@ -0,0 +1,234 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +import Predef._ +import compat.Platform + +/** + * Arrays created by new Array[T](length) where T + * is a type variable. + */ +@serializable +final class BoxedAnyArray(val length: Int) extends BoxedArray { + + private var boxed = new Array[AnyRef](length) + private val hash = boxed.hashCode() + private var unboxed: AnyRef = null + private var elemClass: Class[_] = null + + def apply(index: Int): Any = synchronized { + if (unboxed eq null) + boxed(index); + else if (elemClass eq classOf[Int]) + Int.box(unboxed.asInstanceOf[Array[Int]](index)) + else if (elemClass eq classOf[Long]) + Long.box(unboxed.asInstanceOf[Array[Long]](index)) + else if (elemClass eq classOf[Char]) + Char.box(unboxed.asInstanceOf[Array[Char]](index)) + else if (elemClass eq classOf[Byte]) + Byte.box(unboxed.asInstanceOf[Array[Byte]](index)) + else if (elemClass eq classOf[Short]) + Short.box(unboxed.asInstanceOf[Array[Short]](index)) + else if (elemClass eq classOf[Boolean]) + Boolean.box(unboxed.asInstanceOf[Array[Boolean]](index)) + else + unboxed.asInstanceOf[Array[AnyRef]](index) + } + + def update(index: Int, _elem: Any): Unit = synchronized { + val elem = _elem.asInstanceOf[AnyRef] + if (unboxed eq null) + boxed(index) = elem + else if (elemClass eq classOf[Int]) + unboxed.asInstanceOf[Array[Int]](index) = Int.unbox(elem) + else if (elemClass eq classOf[Long]) + unboxed.asInstanceOf[Array[Long]](index) = Long.unbox(elem) + else if (elemClass eq classOf[Char]) + unboxed.asInstanceOf[Array[Char]](index) = Char.unbox(elem) + else if (elemClass eq classOf[Byte]) + unboxed.asInstanceOf[Array[Byte]](index) = Byte.unbox(elem) + else if (elemClass eq classOf[Short]) + unboxed.asInstanceOf[Array[Short]](index) = Short.unbox(elem) + else if (elemClass eq classOf[Boolean]) + unboxed.asInstanceOf[Array[Boolean]](index) = Boolean.unbox(elem) + else + unboxed.asInstanceOf[Array[AnyRef]](index) = elem + } + + def unbox(elemTag: String): AnyRef = + if (elemTag eq ScalaRunTime.IntTag) unbox(classOf[Int]) + else if (elemTag eq ScalaRunTime.LongTag) unbox(classOf[Long]) + else if (elemTag eq ScalaRunTime.CharTag) unbox(classOf[Char]) + else if (elemTag eq ScalaRunTime.ByteTag) unbox(classOf[Byte]) + else if (elemTag eq ScalaRunTime.ShortTag) unbox(classOf[Short]) + else if (elemTag eq ScalaRunTime.BooleanTag) unbox(classOf[Boolean]) + else unbox(Platform.getClassForName(elemTag)) + + def unbox(elemClass: Class[_]): AnyRef = synchronized { + if (unboxed eq null) { + this.elemClass = elemClass + if (elemClass eq classOf[Int]) { + val newvalue = new Array[Int](length) + var i = 0 + while (i < length) { + newvalue(i) = Int.unbox(boxed(i)) + i += 1 + } + unboxed = newvalue + } else if (elemClass eq classOf[Long]) { + val newvalue = new Array[Long](length) + var i = 0 + while (i < length) { + newvalue(i) = Long.unbox(boxed(i)) + i += 1 + } + unboxed = newvalue; + } else if (elemClass eq classOf[Char]) { + val newvalue = new Array[Char](length) + var i = 0 + while (i < length) { + newvalue(i) = Char.unbox(boxed(i)) + i += 1 + } + unboxed = newvalue + } else if (elemClass eq classOf[Byte]) { + val newvalue = new Array[Byte](length) + var i = 0 + while (i < length) { + newvalue(i) = Byte.unbox(boxed(i)) + i += 1 + } + unboxed = newvalue + } else if (elemClass eq classOf[Short]) { + val newvalue = new Array[Short](length) + var i = 0 + while (i < length) { + newvalue(i) = Short.unbox(boxed(i)) + i += 1 + } + unboxed = newvalue + } else if (elemClass eq classOf[Boolean]) { + val newvalue = new Array[Boolean](length) + var i = 0 + while (i < length) { + newvalue(i) = Boolean.unbox(boxed(i)) + i += 1 + } + unboxed = newvalue; +// } else if (elemClass == boxed.getClass().getComponentType()) { +// // todo: replace with ScalaRunTime.AnyRef.class +// unboxed = boxed + } else { + unboxed = Platform.createArray(elemClass, length) + Platform.arraycopy(boxed, 0, unboxed, 0, length) + } + boxed = null + } + unboxed + } + + override def equals(other: Any): Boolean = ( + other.isInstanceOf[BoxedAnyArray] && (this eq (other.asInstanceOf[BoxedAnyArray])) || + (if (unboxed eq null) boxed == other else unboxed == other) + ) + + override def hashCode(): Int = hash + + def value: AnyRef = { + if (unboxed eq null) throw new NotDefinedError("BoxedAnyArray.value") + unboxed + } + + private def adapt(other: AnyRef): AnyRef = + if (this.unboxed eq null) + other match { + case that: BoxedAnyArray => + if (that.unboxed eq null) { + that.boxed + } else { + if (ScalaRunTime.isValueClass(that.elemClass)) unbox(that.elemClass); + that.unboxed + } + case that: BoxedArray => + adapt(that.value) + case that: Array[Int] => + unbox(ScalaRunTime.IntTag); that + case that: Array[Long] => + unbox(ScalaRunTime.LongTag); that + case that: Array[Char] => + unbox(ScalaRunTime.CharTag); that + case that: Array[Short] => + unbox(ScalaRunTime.ShortTag); that + case that: Array[Byte] => + unbox(ScalaRunTime.ByteTag); that + case that: Array[Boolean] => + unbox(ScalaRunTime.BooleanTag); that + case _ => + other + } + else + other match { + case that: BoxedAnyArray => + if (that.unboxed ne null) that.unboxed + else if (ScalaRunTime.isValueClass(this.elemClass)) that.unbox(this.elemClass) + else that.boxed + case that: BoxedArray => + adapt(that.value) + case _ => + other + } + + override def copyFrom(src: AnyRef, from: Int, to: Int, len: Int) { + val src1 = adapt(src) + Array.copy(src1, from, if (unboxed ne null) unboxed else boxed, to, len) + } + + override def copyTo(from: Int, dest: AnyRef, to: Int, len: Int) { + var dest1 = adapt(dest) + Array.copy(if (unboxed ne null) unboxed else boxed, from, dest1, to, len) + } + + override def subArray(start: Int, end: Int): AnyRef = { + val result = new BoxedAnyArray(end - start); + Array.copy(this, start, result, 0, end - start) + result + } + + final override def filter(p: Any => Boolean): BoxedArray = { + val include = new Array[Boolean](length) + var len = 0 + var i = 0 + while (i < length) { + if (p(this(i))) { include(i) = true; len += 1 } + i += 1 + } + val result = new BoxedAnyArray(len) + len = 0 + i = 0 + while (len < result.length) { + if (include(i)) { result(len) = this(i); len += 1 } + i += 1 + } + result + } + override protected def newArray(length : Int, elements : Iterator[Any]) = { + val result = new BoxedAnyArray(length) + var i = 0 + while (elements.hasNext) { + result(i) = elements.next + i += 1 + } + result + } +} diff --git a/src/cldc-library/scala/runtime/BoxedObjectArray.scala b/src/cldc-library/scala/runtime/BoxedObjectArray.scala new file mode 100644 index 0000000000..878b7ac042 --- /dev/null +++ b/src/cldc-library/scala/runtime/BoxedObjectArray.scala @@ -0,0 +1,73 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +import Predef._ +import compat.Platform.createArray + +@serializable +final class BoxedObjectArray(val value: Array[AnyRef]) extends BoxedArray { + + def length: Int = value.length + + def apply(index: Int): Any = value(index) + + def update(index: Int, elem: Any) { + value(index) = elem.asInstanceOf[AnyRef] + } + + def unbox(elemTag: String): AnyRef = value + def unbox(elemClass: Class[_]): AnyRef = value + + override def equals(other: Any): Boolean = + value == other || + other.isInstanceOf[BoxedObjectArray] && value == other.asInstanceOf[BoxedObjectArray].value + + override def hashCode(): Int = value.hashCode() + + private def create(length: Int): Array[AnyRef] = { + //createArray(value.getClass().getComponentType(), length).asInstanceOf[Array[AnyRef]] + new Array[AnyRef](length) + } + + override def subArray(start: Int, end: Int): Array[AnyRef] = { + val result = create(end - start) + Array.copy(value, start, result, 0, end - start) + result + } + + final override def filter(p: Any => Boolean): BoxedArray = { + val include = new Array[Boolean](value.length) + var len = 0 + var i = 0 + while (i < value.length) { + if (p(value(i))) { include(i) = true; len += 1 } + i += 1 + } + val result = create(len) + len = 0 + i = 0 + while (len < result.length) { + if (include(i)) { result(len) = value(i); len += 1 } + i += 1 + } + new BoxedObjectArray(result) + } + + override protected def newArray(length: Int, elements: Iterator[Any]) = { + val result = create(length) + elements.map(_.asInstanceOf[AnyRef]).copyToArray(result, 0) + new BoxedObjectArray(result) + } +} + diff --git a/src/cldc-library/scala/runtime/BoxedUnit.java b/src/cldc-library/scala/runtime/BoxedUnit.java new file mode 100644 index 0000000000..bafd0ec010 --- /dev/null +++ b/src/cldc-library/scala/runtime/BoxedUnit.java @@ -0,0 +1,33 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + + +public final class BoxedUnit +{ + + public final static BoxedUnit UNIT = new BoxedUnit(); + + private BoxedUnit() { } + + public boolean equals(java.lang.Object other) { + return this == other; + } + + public int hashCode() { + return 0; + } + + public String toString() { + return "()"; + } +} diff --git a/src/cldc-library/scala/runtime/BoxesRunTime.java b/src/cldc-library/scala/runtime/BoxesRunTime.java new file mode 100644 index 0000000000..bab4c63524 --- /dev/null +++ b/src/cldc-library/scala/runtime/BoxesRunTime.java @@ -0,0 +1,361 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + +/** An object (static class) that defines methods used for creating, + * reverting, and calculating with, boxed values. There are four classes + * of methods in this object: + * - High-performance value boxing methods that feed from a pre- + * computed map of instances for the most common instanciations. + * - Convenience unboxing methods returning default value on null. + * - The generalised comparison method to be used when an object may + * be a boxed value. + * - Standard value operators for boxed number and quasi-number values. + * + * @author Gilles Dubochet + * @author Martin Odersky + * @contributor Stepan Koltsov + * @version 2.0 */ +public class BoxesRunTime { + + private static final int CHAR = 0, BYTE = 1, SHORT = 2, INT = 3, LONG = 4, OTHER = 7; + + private static int typeCode(Object a) { + if (a instanceof Integer) return INT; + if (a instanceof Character) return CHAR; + if (a instanceof Long) return LONG; + if (a instanceof Byte) return BYTE; + if (a instanceof Short) return SHORT; + return OTHER; + } + +/* BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING */ + + private static int charLowBound = 0; + private static int charUpBound = 255; + private static Character[] charCache = new Character[charUpBound - charLowBound + 1]; + + private static int byteLowBound = -128; + private static int byteUpBound = 127; + private static Byte[] byteCache = new Byte[byteUpBound - byteLowBound + 1]; + + private static int shortLowBound = -128; + private static int shortUpBound = 127; + private static Short[] shortCache = new Short[shortUpBound - shortLowBound + 1]; + + private static int intLowBound = -128; + private static int intUpBound = 1024; + private static Integer[] intCache = new Integer[intUpBound - intLowBound + 1]; + + private static int longLowBound = -128; + private static int longUpBound = 1024; + private static Long[] longCache = new Long[longUpBound - longLowBound + 1]; + + static { + int idx = 0; + while (idx <= charUpBound - charLowBound) { + charCache[idx] = new Character((char)(idx + charLowBound)); + idx = idx + 1; + } + idx = 0; + while (idx <= byteUpBound - byteLowBound) { + byteCache[idx] = new Byte((byte)(idx + byteLowBound)); + idx = idx + 1; + } + idx = 0; + while (idx <= shortUpBound - shortLowBound) { + shortCache[idx] = new Short((short)(idx + shortLowBound)); + idx = idx + 1; + } + idx = 0; + while (idx <= intUpBound - intLowBound) { + intCache[idx] = new Integer((int)(idx + intLowBound)); + idx = idx + 1; + } + idx = 0; + while (idx <= longUpBound - longLowBound) { + longCache[idx] = new Long((long)(idx + longLowBound)); + idx = idx + 1; + } + } + + private static final Boolean TRUE = new Boolean(true); + private static final Boolean FALSE = new Boolean(false); + public static Boolean boxToBoolean(boolean b) { + return b ? TRUE : FALSE; + } + + public static Character boxToCharacter(char c) { + if (c >= charLowBound && c <= charUpBound) + return charCache[(int)c - charLowBound]; + return new Character(c); + } + + public static Byte boxToByte(byte b) { + if (b >= byteLowBound && b <= byteUpBound) + return byteCache[(int)b - byteLowBound]; + return new Byte(b); + } + + public static Short boxToShort(short s) { + if (s >= shortLowBound && s <= shortUpBound) + return shortCache[(int)s - shortLowBound]; + return new Short(s); + } + + public static Integer boxToInteger(int i) { + if (i >= intLowBound && i <= intUpBound) + return intCache[(int)i - intLowBound]; + return new Integer(i); + } + + public static Long boxToLong(long l) { + if (l >= longLowBound && l <= longUpBound) + return longCache[(int)l - longLowBound]; + return new Long(l); + } + +/* UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING */ + + public static boolean unboxToBoolean(Object b) { + return b == null ? false : ((Boolean)b).booleanValue(); + } + + public static char unboxToChar(Object c) { + return c == null ? 0 : ((Character)c).charValue(); + } + + public static byte unboxToByte(Object b) { + return b == null ? 0 : ((Byte)b).byteValue(); + } + + public static short unboxToShort(Object s) { + return s == null ? 0 : ((Short)s).shortValue(); + } + + public static int unboxToInt(Object i) { + return i == null ? 0 : ((Integer)i).intValue(); + } + + public static long unboxToLong(Object l) { + return l == null ? 0 : ((Long)l).longValue(); + } + + /* + public static boolean unboxToBoolean(Object b) { + if (b == null) + throw new ClassCastException("null is no Boolean value"); + return ((Boolean)b).booleanValue(); + } + + public static char unboxToChar(Object c) { + if (c == null) + throw new ClassCastException("null is no Char value"); + return ((Character)c).charValue(); + } + + public static byte unboxToByte(Object b) { + if (b == null) + throw new ClassCastException("null is no Byte value"); + return ((Byte)b).byteValue(); + } + + public static short unboxToShort(Object s) { + if (s == null) + throw new ClassCastException("null is no Short value"); + return ((Short)s).shortValue(); + } + + public static int unboxToInt(Object i) { + if (i == null) + throw new ClassCastException("null is no Int value"); + return ((Integer)i).intValue(); + } + + public static long unboxToLong(Object l) { + if (l == null) + throw new ClassCastException("null is no Long value"); + return ((Long)l).longValue(); + } + */ + +/* COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON */ + + /** A rich implementation of the equals method that overrides the + * default equals because Java's boxed primitives are utterly broken. This equals + * is inserted instead of a normal equals by the Scala compiler (in the + * ICode phase, method genEqEqPrimitive) only when either + * side of the comparison is a subclass of AnyVal, of + * java.lang.Number, of java.lang.Character or + * is exactly Any or AnyRef. */ + public static boolean equals(Object a, Object b) { + if (a == null) + return b == null; + if (b == null) + return false; + if (a.equals(b)) + return true; + + final long left = + (a instanceof Integer) ? ((Integer)a).intValue() : + (a instanceof Character) ? ((Character)a).charValue() : + (a instanceof Long) ? ((Long)a).longValue() : + (a instanceof Byte) ? ((Byte)a).byteValue() : + ((Short)a).shortValue(); + + final long right = + (b instanceof Integer) ? ((Integer)b).intValue() : + (b instanceof Character) ? ((Character)b).charValue() : + (b instanceof Long) ? ((Long)b).longValue() : + (b instanceof Byte) ? ((Byte)b).byteValue() : + ((Short)b).shortValue(); + + return left == right; + } + +/* OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS */ + + /** arg1 + arg2 */ + public static Object add(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 - arg2 */ + public static Object subtract(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 * arg2 */ + public static Object multiply(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 / arg2 */ + public static Object divide(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 % arg2 */ + public static Object takeModulo(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 >> arg2 */ + public static Object shiftSignedRight(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 << arg2 */ + public static Object shiftSignedLeft(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 >>> arg2 */ + public static Object shiftLogicalRight(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** -arg */ + public static Object negate(Object arg) throws Error { + throw new Error(); + } + + /** +arg */ + public static Object positive(Object arg) throws Error { + throw new Error(); + } + + /** arg1 & arg2 */ + public static Object takeAnd(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 | arg2 */ + public static Object takeOr(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 ^ arg2 */ + public static Object takeXor(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 && arg2 */ + public static Object takeConditionalAnd(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg1 || arg2 */ + public static Object takeConditionalOr(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** ~arg */ + public static Object complement(Object arg) throws Error { + throw new Error(); + } + + /** !arg */ + public static Object takeNot(Object arg) throws Error { + throw new Error(); + } + + public static Object testEqual(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + public static Object testNotEqual(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + public static Object testLessThan(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + public static Object testLessOrEqualThan(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + public static Object testGreaterOrEqualThan(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + public static Object testGreaterThan(Object arg1, Object arg2) throws Error { + throw new Error(); + } + + /** arg.toChar */ + public static Character toCharacter(Object arg) throws Error { + throw new Error(); + } + + /** arg.toByte */ + public static Byte toByte(Object arg) throws Error { + throw new Error(); + } + + /** arg.toShort */ + public static Short toShort(Object arg) throws Error { + throw new Error(); + } + + /** arg.toInt */ + public static Integer toInteger(Object arg) throws Error { + throw new Error(); + } + + /** arg.toLong */ + public static Long toLong(Object arg) throws Error { + throw new Error(); + } + +} diff --git a/src/cldc-library/scala/runtime/BoxesUtility.java b/src/cldc-library/scala/runtime/BoxesUtility.java new file mode 100644 index 0000000000..de33635e0f --- /dev/null +++ b/src/cldc-library/scala/runtime/BoxesUtility.java @@ -0,0 +1,147 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + +/** + * @author Gilles Dubochet + * @version 1.0 + */ +public class BoxesUtility { + + private static int charLowBound = 0; + private static int charUpBound = 255; + private static Character[] charCache = new Character[charUpBound - charLowBound + 1]; + + private static int byteLowBound = -128; + private static int byteUpBound = 127; + private static Byte[] byteCache = new Byte[byteUpBound - byteLowBound + 1]; + + private static int shortLowBound = -128; + private static int shortUpBound = 127; + private static Short[] shortCache = new Short[shortUpBound - shortLowBound + 1]; + + private static int intLowBound = -128; + private static int intUpBound = 1024; + private static Integer[] intCache = new Integer[intUpBound - intLowBound + 1]; + + private static int longLowBound = -128; + private static int longUpBound = 1024; + private static Long[] longCache = new Long[longUpBound - longLowBound + 1]; + + static { + int idx = 0; + while (idx <= charUpBound - charLowBound) { + charCache[idx] = new Character((char)(idx + charLowBound)); + idx = idx + 1; + } + idx = 0; + while (idx <= byteUpBound - byteLowBound) { + byteCache[idx] = new Byte((byte)(idx + byteLowBound)); + idx = idx + 1; + } + idx = 0; + while (idx <= shortUpBound - shortLowBound) { + shortCache[idx] = new Short((short)(idx + shortLowBound)); + idx = idx + 1; + } + idx = 0; + while (idx <= intUpBound - intLowBound) { + intCache[idx] = new Integer((int)(idx + intLowBound)); + idx = idx + 1; + } + idx = 0; + while (idx <= longUpBound - longLowBound) { + longCache[idx] = new Long((long)(idx + longLowBound)); + idx = idx + 1; + } + } + private static final Boolean TRUE = new Boolean(true); + private static final Boolean FALSE = new Boolean(false); + public static Boolean boxToBoolean(boolean b) { + return b ? TRUE : FALSE; + } + + public static Character boxToCharacter(char c) { + if (c >= charLowBound && c <= charUpBound) + return charCache[(int)c - charLowBound]; + else + return new Character(c); + } + + public static Byte boxToByte(byte b) { + if (b >= byteLowBound && b <= byteUpBound) + return byteCache[(int)b - byteLowBound]; + else + return new Byte(b); + } + + public static Short boxToShort(short s) { + if (s >= shortLowBound && s <= shortUpBound) + return shortCache[(int)s - shortLowBound]; + else + return new Short(s); + } + + public static Integer boxToInteger(int i) { + if (i >= intLowBound && i <= intUpBound) + return intCache[(int)i - intLowBound]; + else + return new Integer(i); + } + + public static Long boxToLong(long l) { + if (l >= longLowBound && l <= longUpBound) + return longCache[(int)l - longLowBound]; + else + return new Long(l); + } + + public static boolean unboxToBoolean(Object b) { + return b == null ? false : ((Boolean)b).booleanValue(); + } + + public static char unboxToChar(Object c) { + if (c == null) + return 0; + else + return ((Character)c).charValue(); + } + + public static byte unboxToByte(Object b) { + if (b == null) + return 0; + else + return ((Byte)b).byteValue(); + } + + public static short unboxToShort(Object s) { + if (s == null) + return 0; + else + return ((Short)s).shortValue(); + } + + public static int unboxToInt(Object i) { + if (i == null) + return 0; + else + return ((Integer)i).intValue(); + } + + public static long unboxToLong(Object l) { + if (l == null) + return 0; + else + return ((Long)l).longValue(); + } + +} diff --git a/src/cldc-library/scala/runtime/ByteRef.java b/src/cldc-library/scala/runtime/ByteRef.java new file mode 100644 index 0000000000..f420362d03 --- /dev/null +++ b/src/cldc-library/scala/runtime/ByteRef.java @@ -0,0 +1,19 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + + +public class ByteRef { + public byte elem; + public ByteRef(byte elem) { this.elem = elem; } + public String toString() { return String.valueOf(elem); } +} diff --git a/src/cldc-library/scala/runtime/CharRef.java b/src/cldc-library/scala/runtime/CharRef.java new file mode 100644 index 0000000000..ea92945134 --- /dev/null +++ b/src/cldc-library/scala/runtime/CharRef.java @@ -0,0 +1,19 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + + +public class CharRef { + public char elem; + public CharRef(char elem) { this.elem = elem; } + public String toString() { return String.valueOf(elem); } +} diff --git a/src/cldc-library/scala/runtime/Comparator.java b/src/cldc-library/scala/runtime/Comparator.java new file mode 100644 index 0000000000..75469e69b1 --- /dev/null +++ b/src/cldc-library/scala/runtime/Comparator.java @@ -0,0 +1,53 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + +/** + * @author Gilles Dubochet + * @author Martin Odersky + * @version 1.2 */ +public class Comparator { + + /** A rich implementation of the equals method that overrides the default + * equals because Java's boxed primitives are utterly broken. This equals + * is inserted instead of a normal equals by the Scala compiler (in the + * ICode phase, method genEqEqPrimitive) only when either + * side of the comparison is a subclass of AnyVal, of + * java.lang.Number, of java.lang.Character or + * is exactly Any or AnyRef, but when both sides + * have different types. */ + public static boolean equals(Object a, Object b) { + if (a == null) + return b == null; + if (b == null) + return false; + if (a.equals(b)) + return true; + + final long left = + (a instanceof Integer) ? ((Integer)a).intValue() : + (a instanceof Character) ? ((Character)a).charValue() : + (a instanceof Long) ? ((Long)a).longValue() : + (a instanceof Byte) ? ((Byte)a).byteValue() : + ((Short)a).shortValue(); + + final long right = + (b instanceof Integer) ? ((Integer)b).intValue() : + (b instanceof Character) ? ((Character)b).charValue() : + (b instanceof Long) ? ((Long)b).longValue() : + (b instanceof Byte) ? ((Byte)b).byteValue() : + ((Short)b).shortValue(); + + return left == right; + } + +} diff --git a/src/cldc-library/scala/runtime/IntRef.java b/src/cldc-library/scala/runtime/IntRef.java new file mode 100644 index 0000000000..dde9b18d17 --- /dev/null +++ b/src/cldc-library/scala/runtime/IntRef.java @@ -0,0 +1,19 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + + +public class IntRef { + public int elem; + public IntRef(int elem) { this.elem = elem; } + public String toString() { return String.valueOf(elem); } +} diff --git a/src/cldc-library/scala/runtime/LongRef.java b/src/cldc-library/scala/runtime/LongRef.java new file mode 100644 index 0000000000..50a5133d87 --- /dev/null +++ b/src/cldc-library/scala/runtime/LongRef.java @@ -0,0 +1,19 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + + +public class LongRef { + public long elem; + public LongRef(long elem) { this.elem = elem; } + public String toString() { return String.valueOf(elem); } +} diff --git a/src/cldc-library/scala/runtime/ObjectRef.java b/src/cldc-library/scala/runtime/ObjectRef.java new file mode 100644 index 0000000000..895fb472ef --- /dev/null +++ b/src/cldc-library/scala/runtime/ObjectRef.java @@ -0,0 +1,19 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + + +public class ObjectRef { + public Object elem; + public ObjectRef(Object elem) { this.elem = elem; } + public String toString() { return "" + elem; } +} diff --git a/src/cldc-library/scala/runtime/RichChar.scala b/src/cldc-library/scala/runtime/RichChar.scala new file mode 100644 index 0000000000..9c7bd95d4e --- /dev/null +++ b/src/cldc-library/scala/runtime/RichChar.scala @@ -0,0 +1,71 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +import java.lang.Character +import Predef.NoSuchElementException + +/**

+ * For example, in the following code + *

+ *
+ *    object test extends Application {
+ *      Console.println('\40'.isWhitespace)
+ *      Console.println('\011'.isWhitespace)
+ *      Console.println('1'.asDigit == 1)
+ *      Console.println('A'.asDigit == 10)
+ *    }
+ *

+ * the implicit conversions are performed using the predefined view + * Predef.charWrapper. + *

+ */ +final class RichChar(x: Char) extends Proxy with Ordered[Char] { + + // Proxy.self + def self: Any = x + + // Ordered[Char].compare + def compare (y: Char): Int = if (x < y) -1 else if (x > y) 1 else 0 + + def asDigit: Int = Character.digit(x, Character.MAX_RADIX) + + //def isControl: Boolean = Character.isISOControl(x) + def isDigit: Boolean = Character.isDigit(x) + //def isLetter: Boolean = Character.isLetter(x) + //def isLetterOrDigit: Boolean = Character.isLetterOrDigit(x) + def isLowerCase: Boolean = Character.isLowerCase(x) + def isUpperCase: Boolean = Character.isUpperCase(x) + //def isWhitespace: Boolean = Character.isWhitespace(x) + + def toLowerCase: Char = Character.toLowerCase(x) + def toUpperCase: Char = Character.toUpperCase(x) + + /** Create an Iterator[Char] over the characters from 'x' to 'y' - 1 + */ + def until(limit: Char): Iterator[Char] = new Iterator[Char] { + private var ch = x + def hasNext: Boolean = ch < limit + def next: Char = + if (hasNext) { val j = ch; ch = (ch + 1).toChar; j } + else throw new NoSuchElementException("next on empty iterator") + } + + //def until(y: Char): Iterator[Char] = to(y) + + /** Create an Iterator[Char] over the characters from 'x' to 'y' + */ + def to(y: Char): Iterator[Char] = until((y + 1).toChar) + +} diff --git a/src/cldc-library/scala/runtime/RichException.scala b/src/cldc-library/scala/runtime/RichException.scala new file mode 100644 index 0000000000..9acab2e052 --- /dev/null +++ b/src/cldc-library/scala/runtime/RichException.scala @@ -0,0 +1,29 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id + + +package scala.runtime + +import Predef._ +import compat.Platform.EOL + +final class RichException(exc: Throwable) { + + def getStackTraceString: String = { + throw new UnsupportedOperationException(exc.toString) +// val s = new StringBuilder() +// for (trElem <- exc.getStackTrace()) { +// s.append(trElem.toString()) +// s.append(EOL) +// } +// s.toString() + } + +} diff --git a/src/cldc-library/scala/runtime/RichLong.scala b/src/cldc-library/scala/runtime/RichLong.scala new file mode 100644 index 0000000000..2df4fdc23d --- /dev/null +++ b/src/cldc-library/scala/runtime/RichLong.scala @@ -0,0 +1,30 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +final class RichLong(x: Long) extends Proxy with Ordered[Long] { + + // Proxy.self + def self: Any = x + + // Ordered[Long].compare + def compare(y: Long): Int = if (x < y) -1 else if (x > y) 1 else 0 + + def min(y: Long): Long = if (x < y) x else y + def max(y: Long): Long = if (x > y) x else y + def abs: Long = if (x < 0) -x else x + + def toBinaryString: String = java.lang.Long.toString(x, 2) + def toHexString: String = java.lang.Long.toString(x, 16) + def toOctalString: String = java.lang.Long.toString(x, 8) +} diff --git a/src/cldc-library/scala/runtime/RichString.scala b/src/cldc-library/scala/runtime/RichString.scala new file mode 100644 index 0000000000..40e208246d --- /dev/null +++ b/src/cldc-library/scala/runtime/RichString.scala @@ -0,0 +1,219 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +import Predef._ + +final class RichString(val self: String) extends Proxy with RandomAccessSeq[Char] with Ordered[String] { + import RichString._ + override def apply(n: Int) = self charAt n + override def length = self.length + override def toString = self + override def mkString = self + + override def slice(from: Int, until: Int): RichString = { + val len = self.length + new RichString( + if (from >= until || from >= len) + "" + else { + val from0 = if (from < 0) 0 else from + val until0 = if (until > len) len else until + self.substring(from0, until0) + } + ) + } + + //override def ++ [B >: A](that: Iterable[B]): Seq[B] = { + override def ++[B >: Char](that: Iterable[B]): RandomAccessSeq[B] = that match { + case that: RichString => new RichString(self + that.self) + case that => super.++(that) + } + + override def take(until: Int): RichString = slice(0, until) + + override def drop(from: Int): RichString = slice(from, self.length) + + override def startsWith[B](that: Seq[B]) = that match { + case that: RichString => self startsWith that.self + case that => super.startsWith(that) + } + + override def endsWith[B](that: Seq[B]) = that match { + case that: RichString => self endsWith that.self + case that => super.endsWith(that) + } + + override def indexOf[B](that: Seq[B]) = that match { + case that: RichString => self indexOf that.self + case that => super.indexOf(that) + } + + override def containsSlice[B](that: Seq[B]) = that match { + case that: RichString => self contains that.self + case that => super.containsSlice(that) + } + + override def reverse: RichString = { + val buf = new StringBuilder + var i = self.length - 1 + while (i >= 0) { + buf append (self charAt i) + i -= 1 + } + new RichString(buf.toString) + } + + override def compare(other: String) = self compareTo other + + private def isLineBreak(c: Char) = c == LF || c == FF + + /**

+ * Strip trailing line end character from this string if it has one. + * A line end character is one of + *

+ * + *

+ * If a line feed character LF is preceded by a carriage return CR + * (0x0D hex), the CR character is also stripped (Windows convention). + *

+ */ + def stripLineEnd: String = { + val len = self.length + if (len == 0) self + else { + val last = apply(len - 1) + if (isLineBreak(last)) + self.substring(0, if (last == LF && len >= 2 && apply(len - 2) == CR) len - 2 else len - 1) + else + self + } + } + + /**

+ * Return all lines in this string in an iterator, including trailing + * line end characters. + *

+ *

+ * The number of strings returned is one greater than the number of line + * end characters in this string. For an empty string, a single empty + * line is returned. A line end character is one of + *

+ * + */ + def linesWithSeparators = new Iterator[String] { + val len = self.length + var index = 0 + def hasNext: Boolean = index < len + def next(): String = { + if (index >= len) throw new NoSuchElementException("next on empty iterator") + val start = index + while (index < len && !isLineBreak(apply(index))) index += 1 + index += 1 + self.substring(start, index min len) + } + } + + /** Return all lines in this string in an iterator, excluding trailing line + * end characters, i.e. apply .stripLineEnd to all lines + * returned by linesWithSeparators. + */ + def lines: Iterator[String] = + linesWithSeparators map (line => new RichString(line).stripLineEnd) + + /** Returns this string with first character converted to upper case */ + def capitalize: String = + if (self == null) null + else if (self.length == 0) "" + else { + val chars = self.toCharArray + chars(0) = chars(0).toUpperCase + new String(chars) + } + + /**

+ * For every line in this string: + *

+ *
+ * Strip a leading prefix consisting of blanks or control characters + * followed by marginChar from the line. + *
+ */ + def stripMargin(marginChar: Char): String = { + val buf = new StringBuilder() + for (line <- linesWithSeparators) { + val len = line.length + var index = 0 + while (index < len && line.charAt(index) <= ' ') index += 1 + buf append + (if (index < len && line.charAt(index) == marginChar) line.substring(index + 1) else line) + } + buf.toString + } + + /**

+ * For every line in this string: + *

+ *
+ * Strip a leading prefix consisting of blanks or control characters + * followed by | from the line. + *
+ */ + def stripMargin: String = stripMargin('|') +/* + private def escape(ch: Char): String = ch match { + case '.' | '$' | '^' | '\\' => "\\" + ch + case _ => "" + ch + } + + @throws(classOf[java.util.regex.PatternSyntaxException]) + def split(separator: Char): Array[String] = self.split(escape(separator)) + + @throws(classOf[java.util.regex.PatternSyntaxException]) + def split(separators: Array[Char]): Array[String] = { + val re = separators.foldLeft("[")(_+_) + "]" + self.split(re) + } +*/ + def toBoolean: Boolean = parseBoolean(self) + def toByte: Byte = java.lang.Byte.parseByte(self) + def toShort: Short = java.lang.Short.parseShort(self) + def toInt: Int = java.lang.Integer.parseInt(self) + def toLong: Long = java.lang.Long.parseLong(self) + //def toFloat: Float = java.lang.Float.parseFloat(self) + //def toDouble: Double = java.lang.Double.parseDouble(self) +} + +object RichString { + // just statics for rich string. + private final val LF: Char = 0x0A + private final val FF: Char = 0x0C + private final val CR: Char = 0x0D + private final val SU: Char = 0x1A + + private def parseBoolean(s: String): Boolean = + if (s != null) s.toLowerCase match { + case "true" => true + case "false" => false + case _ => throw new NumberFormatException("For input string: \""+s+"\"") + } + else + throw new NumberFormatException("For input string: \"null\"") +} + diff --git a/src/cldc-library/scala/runtime/ScalaRunTime.scala b/src/cldc-library/scala/runtime/ScalaRunTime.scala new file mode 100644 index 0000000000..004234af8f --- /dev/null +++ b/src/cldc-library/scala/runtime/ScalaRunTime.scala @@ -0,0 +1,142 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +import Predef._ + +/* The object ScalaRunTime provides ... + */ +object ScalaRunTime { + + /** Names for primitive types, used by array unboxing */ + val ByteTag = ".Byte" + val ShortTag = ".Short" + val CharTag = ".Char" + val IntTag = ".Int" + val LongTag = ".Long" + val BooleanTag = ".Boolean" + + def isArray(x: AnyRef): Boolean = + (x != null && x.getClass.isArray) || (x != null && x.isInstanceOf[BoxedArray]) + + def isValueTag(tag: String) = tag.charAt(0) == '.' + + def isValueClass(clazz: Class[_]) = + clazz == classOf[Boolean] || clazz == classOf[Byte] || + clazz == classOf[Short ] || clazz == classOf[Char] || + clazz == classOf[Int ] || clazz == classOf[Long] + + def checkInitialized[T <: AnyRef](x: T): T = + if (x == null) throw new UninitializedError else x + + abstract class Try[A] { + def Catch[B >: A](handler: PartialFunction[Throwable, B]): B + def Finally(handler: Unit): A + } + + def Try[A](block: => A): Try[A] = new Try[A] with Runnable { + var result: A = _ + var exception: Throwable = ExceptionHandling.tryCatch(this) + + def run() { result = block } + + def Catch[B >: A](handler: PartialFunction[Throwable, B]): B = + if (exception eq null) + result.asInstanceOf[B] + // !!! else if (exception is LocalReturn) + // !!! // ... + else if (handler isDefinedAt exception) + handler(exception) + else + throw exception + + def Finally(handler: Unit): A = + if (exception eq null) + result.asInstanceOf[A] + else + throw exception + } + + def caseFields(x: Product): List[Any] = { + val arity = x.productArity + def fields(from: Int): List[Any] = + if (from == arity) List() + else x.productElement(from) :: fields(from + 1) + fields(0) + } + + def _toString(x: Product): String = + caseFields(x).mkString(x.productPrefix + "(", ",", ")") + + def _hashCode(x: Product): Int = { + var code = x.getClass().hashCode() + val arr = x.productArity + var i = 0 + while (i < arr) { + code = code * 41 + x.productElement(i).hashCode() + i += 1 + } + code + } + + def _equals(x: Product, y: Any): Boolean = y match { + case y1: Product if x.productArity == y1.productArity => + val arity = x.productArity + var i = 0 + while (i < arity && x.productElement(i) == y1.productElement(i)) + i += 1 + i == arity + case _ => + false + } + + def _equalsWithVarArgs(x: Product, y: Any): Boolean = y match { + case y1: Product if x.productArity == y1.productArity => + val arity = x.productArity + var i = 0 + while (i < arity - 1 && x.productElement(i) == y1.productElement(i)) + i += 1 + i == arity - 1 && { + x.productElement(i) match { + case xs: Seq[_] => + y1.productElement(i) match { + case ys: Seq[_] => xs sameElements ys + } + } + } + case _ => + false + } + + //def checkDefined[T >: Null](x: T): T = + // if (x == null) throw new UndefinedException else x + + def Seq[A](xs: A*): Seq[A] = null // interpreted specially by new backend. + + def arrayValue(x: BoxedArray, elemTag: String): AnyRef = + if (x eq null) null else x.unbox(elemTag) + + def arrayValue(x: BoxedArray, elemClass: Class[_]): AnyRef = + if (x eq null) null else x.unbox(elemClass) + + def boxArray(value: AnyRef): BoxedArray = value match { + case x: Array[Byte] => new BoxedByteArray(x) + case x: Array[Short] => new BoxedShortArray(x) + case x: Array[Char] => new BoxedCharArray(x) + case x: Array[Int] => new BoxedIntArray(x) + case x: Array[Long] => new BoxedLongArray(x) + case x: Array[Boolean] => new BoxedBooleanArray(x) + case x: Array[AnyRef] => new BoxedObjectArray(x) + case x: BoxedArray => x + } +} diff --git a/src/cldc-library/scala/runtime/ShortRef.java b/src/cldc-library/scala/runtime/ShortRef.java new file mode 100644 index 0000000000..fc844c07a8 --- /dev/null +++ b/src/cldc-library/scala/runtime/ShortRef.java @@ -0,0 +1,19 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime; + + +public class ShortRef { + public short elem; + public ShortRef(short elem) { this.elem = elem; } + public String toString() { return String.valueOf(elem); } +} diff --git a/src/cldc-library/scala/runtime/SquareRoot.scala b/src/cldc-library/scala/runtime/SquareRoot.scala new file mode 100644 index 0000000000..edfa7f7f1d --- /dev/null +++ b/src/cldc-library/scala/runtime/SquareRoot.scala @@ -0,0 +1,151 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2007-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + +import Predef._ + +/** + *

+ * Integer Square Root function (see http://atoms.alife.co.uk/sqrt/index.html). + *

+ *

+ * Contributors include Arne Steinarson for the basic approximation idea, Dann + * Corbit and Mathew Hendry for the first cut at the algorithm, Lawrence Kirby + * for the rearrangement, improvments and range optimization, Paul Hsieh + * for the round-then-adjust idea, Tim Tyler, for the Java port + * and Jeff Lawson for a bug-fix and some code to improve accuracy. + *

+ * + * @version v0.02 - 2003/09/07 + */ + +/** + * Faster replacements for (int)(java.lang.Math.sqrt(integer)) + */ +object SquareRoot { + private val table = Array( + 0, 16, 22, 27, 32, 35, 39, 42, 45, 48, 50, 53, 55, 57, + 59, 61, 64, 65, 67, 69, 71, 73, 75, 76, 78, 80, 81, 83, + 84, 86, 87, 89, 90, 91, 93, 94, 96, 97, 98, 99, 101, 102, + 103, 104, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, + 119, 120, 121, 122, 123, 124, 125, 126, 128, 128, 129, 130, 131, 132, + 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 144, 145, + 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155, 156, 157, + 158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166, 167, 167, 168, + 169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178, + 179, 180, 181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, + 189, 189, 190, 191, 192, 192, 193, 193, 194, 195, 195, 196, 197, 197, + 198, 199, 199, 200, 201, 201, 202, 203, 203, 204, 204, 205, 206, 206, + 207, 208, 208, 209, 209, 210, 211, 211, 212, 212, 213, 214, 214, 215, + 215, 216, 217, 217, 218, 218, 219, 219, 220, 221, 221, 222, 222, 223, + 224, 224, 225, 225, 226, 226, 227, 227, 228, 229, 229, 230, 230, 231, + 231, 232, 232, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, + 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, + 246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, + 253, 254, 254, 255 + ) + + /** + *

+ * A faster replacement for (int)(java.lang.Math.sqrt(x)). + * Completely accurate for x < 2147483648 (i.e. 2^31)... + *

+ *

+ * Adjusted to more closely approximate "(int)(java.lang.Math.sqrt(x) + 0.5)" + * by Jeff Lawson. + *

+ */ + @throws(classOf[IllegalArgumentException]) + def accurateSqrt(x: Int): Int = { + if (x >= 0x10000) { + val xn = if (x >= 0x1000000) { + var xn0 = + if (x >= 0x10000000) + if (x >= 0x40000000) table(x >> 24) << 8 + else table(x >> 22) << 7 + else + if (x >= 0x4000000) table(x >> 20) << 6 + else table(x >> 18) << 5 + + xn0 = (xn0 + 1 + (x / xn0)) >> 1 + (xn0 + 1 + (x / xn0)) >> 1 + } else { + var xn0 = + if (x >= 0x100000) + if (x >= 0x400000) table(x >> 16) << 4 + else table(x >> 14) << 3 + else + if (x >= 0x40000) table(x >> 12) << 2 + else table(x >> 10) << 1 + + (xn0 + 1 + (x / xn0)) >> 1 + } + adjustment(x, xn) + } + else if (x >= 0x100) { + val xn = + if (x >= 0x1000) + if (x >= 0x4000) (table(x >> 8)) + 1 + else (table(x >> 6) >> 1) + 1 + else + if (x >= 0x400) (table(x >> 4) >> 2) + 1 + else (table(x >> 2) >> 3) + 1 + + adjustment(x, xn) + } + else if (x >= 0) { + adjustment(x, table(x) >> 4) + } + else { + throw new IllegalArgumentException("Attempt to take the square root of negative number") + -1 + } + } + + private def adjustment(x: Int, xn: Int): Int = { + // Added by Jeff Lawson: + // need to test: + // if |xn * xn - x| > |x - (xn-1) * (xn-1)| then xn-1 is more accurate + // if |xn * xn - x| > |(xn+1) * (xn+1) - x| then xn+1 is more accurate + // or, for all cases except x == 0: + // if |xn * xn - x| > x - xn * xn + 2 * xn - 1 then xn-1 is more accurate + // if |xn * xn - x| > xn * xn + 2 * xn + 1 - x then xn+1 is more accurate + val xn2 = xn * xn + + // |xn * xn - x| + var comparitor0 = xn2 - x + if (comparitor0 < 0) comparitor0 = -comparitor0 + + val twice_xn = xn << 1 + + // |x - (xn-1) * (xn-1)| + var comparitor1 = x - xn2 + twice_xn - 1 + if (comparitor1 < 0) comparitor1 = -comparitor1 // only gets here when x == 0 + + // |(xn+1) * (xn+1) - x| + val comparitor2 = xn2 + twice_xn + 1 - x + + if (comparitor0 > comparitor1) + if (comparitor1 > comparitor2) xn+1 else xn-1 + else + if (comparitor0 > comparitor2) xn+1 else xn + } + + def main(args: Array[String]) { + def toInt(s: String): Option[Int] = + try { Some(s.toInt) } catch { case e: NumberFormatException => None } + for (arg <- args; val x = toInt(arg); if !x.isEmpty) { + val n = x.get + println("sqrt("+n+") = "+accurateSqrt(n)) + } + } +} diff --git a/src/cldc-library/scala/runtime/StringAdd.scala b/src/cldc-library/scala/runtime/StringAdd.scala new file mode 100644 index 0000000000..ab74c6464b --- /dev/null +++ b/src/cldc-library/scala/runtime/StringAdd.scala @@ -0,0 +1,22 @@ +/* *\ +** ________ ___ __ ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ |_| ** +** ** +\* */ + +// $Id$ + + +package scala.runtime + + +import Predef._ + +final class StringAdd(self: Any) { + + def +(other: String) = self.toString + other + +} + diff --git a/src/dotnet-library/scala/Application.scala b/src/dotnet-library/scala/Application.scala new file mode 100644 index 0000000000..4a47186a15 --- /dev/null +++ b/src/dotnet-library/scala/Application.scala @@ -0,0 +1,61 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +//import java.lang.System.getProperty +//import scala.compat.Platform.currentTime + +/**

+ * The Application class can be used to quickly turn objects + * into executable programs. Here is an example: + *

+ *  object Main with Application {
+ *    Console.println("Hello World!");
+ *  }
+ *  
+ *

+ * Here, object Main inherits the main method + * of Application. The body of the Main object + * defines the main program. This technique does not work if the main + * program depends on command-line arguments (which are not accessible + * with the technique presented here). + *

+ *

+ * It is possible to time the execution of objects that inherit from class + * Application by setting the global scala.time + * property. Here is an example for benchmarking object Main: + *

+ *  java -Dscala.time Main
+ *  
+ * + * @author Matthias Zenger + * @version 1.0, 10/09/2003 + */ + +trait Application { + + /** The time when execution of this program started. + */ +// val executionStart: Long = currentTime + + /** The default main method. + * + * @param args the arguments passed to the main method + */ + def main(args: Array[String]) = { +// if (getProperty("scala.time") ne null) { +// val total = currentTime - executionStart +// Console.println("[total " + total + "ms]") +// } + } + +} diff --git a/src/dotnet-library/scala/Console.scala b/src/dotnet-library/scala/Console.scala new file mode 100644 index 0000000000..7a9c20c034 --- /dev/null +++ b/src/dotnet-library/scala/Console.scala @@ -0,0 +1,298 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + + +import System.IO.{TextReader,TextWriter} + +import scala.util.DynamicVariable +import Predef._ + + +/** The Console object implements functionality for + * printing Scala values on the terminal. There are also functions + * for reading specific values. Console also defines + * constants for marking up text on ANSI terminals. + * + * @author Matthias Zenger + * @version 1.0, 03/09/2003 + */ +object Console { + + // ANSI colors foreground + final val BLACK = "\033[30m" + final val RED = "\033[31m" + final val GREEN = "\033[32m" + final val YELLOW = "\033[33m" + final val BLUE = "\033[34m" + final val MAGENTA = "\033[35m" + final val CYAN = "\033[36m" + final val WHITE = "\033[37m" + + // ANSI colors background + final val BLACK_B = "\033[40m" + final val RED_B = "\033[41m" + final val GREEN_B = "\033[42m" + final val YELLOW_B = "\033[43m" + final val BLUE_B = "\033[44m" + final val MAGENTA_B = "\033[45m" + final val CYAN_B = "\033[46m" + final val WHITE_B = "\033[47m" + + // ANSI styles + final val RESET = "\033[0m" + final val BOLD = "\033[1m" + final val UNDERLINED = "\033[4m" + final val BLINK = "\033[5m" + final val REVERSED = "\033[7m" + final val INVISIBLE = "\033[8m" + + private val outVar = new DynamicVariable[TextWriter](System.Console.Out) + private val inVar = new DynamicVariable[TextReader](System.Console.In) + + def out = outVar.value + def in = inVar.value + + /** Set the default output stream. + * + * @param out the new output stream. + */ + def setOut(out: TextWriter) { outVar.value = out } + + /** Set the default output stream for the duration + * of execution of one thunk. + * + * @param out the new output stream. + * @param thunk the code to execute with + * the new output stream active + */ + def withOut[T](out: TextWriter)(thunk: =>T): T = + outVar.withValue(out)(thunk) + + + /** Set the default input stream. + * + * @param reader specifies the new input stream. + */ + def setIn(reader: TextReader): Unit = { + inVar.value = reader + } + + /** Set the default input stream for the duration + * of execution of one thunk. + * + * @param in the new input stream. + * @param thunk the code to execute with + * the new input stream active + */ + def withIn[T](reader: TextReader)(thunk: =>T): T = + inVar.withValue(reader)(thunk) + + /** Print an object on the terminal. + * + * @param obj the object to print. + */ + def print(obj: Any): Unit = { + out.Write(if (null == obj) "null" else obj.toString()); + } + + /** Flush the output stream. This function is required when partial + * output (i.e. output not terminated by a new line character) has + * to be made visible on the terminal. + */ + def flush() { out.Flush() } + + /** Print a new line character on the terminal. + */ + def println(): Unit = out.WriteLine() + + /** Print out an object followed by a new line character. + * + * @param x the object to print. + */ + def println(x: Any): Unit = out.WriteLine(x) + + /**

+ * Format and print out some text (in a fashion similar to printf in C or + * printf in Java 6). + *

+ *

+ * The format of the text to print is specified by the parameter + * text. The arguments that are inserted into specific + * locations in text are provided with parameter + * args. See class java.text.MessageFormat + * for a full specification of the format syntax. + *

+ * + * @param text the format of the text to print out. + * @param args the parameters used to instantiate the format. + * @throws java.lang.IllegalArgumentException + */ + def printf(text: String, args: Any*) { format(text, args: _*) } + + /** + * @see Console.printf. + */ + def format(text: String, args: Any*): Unit = + if (text eq null) out.Write("null") + else out.Write(text, args.toArray) + + /** Read a full line from the terminal. + * + * @return the string read from the terminal. + */ + def readLine(): String = in.ReadLine(); + + /** Print a formatted text and read a full line from the terminal + * + * @param text the format of the text to print out. + * @param args the parameters used to instantiate the format. + * @return the string read from the terminal. + */ + def readLine(text: String, args: Any*): String = { + format(text, args: _*) + readLine() + } + + + /** Read a boolean value from the terminal. + * + * @return the boolean value read from the terminal. + */ + def readBoolean(): Boolean = readLine().toLowerCase() match { + case "true" => true + case "t" => true + case "yes" => true + case "y" => true + case _ => false + } + + /** Read a byte value from the terminal. + */ + def readByte(): Byte = readLine().toByte + + /** Read a short value from the terminal. + */ + def readShort(): Short = readLine.toShort + + /** Read a char value from the terminal. + */ + def readChar(): Char = readLine() charAt 0 + + /** Read an int value from the terminal. + */ + def readInt(): Int = readLine().toInt + + /** Read an int value from the terminal. + */ + def readLong(): Long = readLine().toLong + + /** Read a float value from the terminal. + */ + def readFloat(): Float = readLine().toFloat + + /** Read a double value from the terminal. + */ + def readDouble(): Double = readLine().toDouble + +// /** Read in some structured input, specified by a format specifier. +// * See class java.text.MessageFormat for details of +// * the format specification. +// * +// * @param format the format of the input. +// * @return a list of all extracted values. +// */ +// def readf(format: String): List[Any] = +// textComponents(new MessageFormat(format).parse(readLine())) + +// /** Read in some structured input, specified by a format specifier. +// * Opposed to readf, this function only returns the +// * first value extracted from the input according to the format +// * specification. +// * +// * @param format ... +// * @return ... +// */ +// def readf1(format: String): Any = readf(format).head + +// /** Read in some structured input, specified by a format specifier. +// * Opposed to readf, this function only returns the +// * first two values extracted from the input according to the format +// * specification. +// * +// * @param format ... +// * @return ... +// */ +// def readf2(format: String): (Any, Any) = { +// val res = readf(format) +// (res.head, res.tail.head) +// } + +// /** Read in some structured input, specified by a format specifier. +// * Opposed to readf, this function only returns the +// * first three values extracted from the input according to the format +// * specification. +// * +// * @param format ... +// * @return ... +// */ +// def readf3(format: String): (Any, Any, Any) = { +// val res = readf(format) +// (res.head, res.tail.head, res.tail.tail.head) +// } + +// private def textComponents(a: Array[AnyRef]): List[Any] = { +// var i: Int = a.length - 1 +// var res: List[Any] = Nil +// while (i >= 0) { +// res = (a(i) match { +// case x: java.lang.Boolean => x.booleanValue() +// case x: java.lang.Byte => x.byteValue() +// case x: java.lang.Short => x.shortValue() +// case x: java.lang.Character => x.charValue() +// case x: java.lang.Integer => x.intValue() +// case x: java.lang.Long => x.longValue() +// case x: java.lang.Float => x.floatValue() +// case x: java.lang.Double => x.doubleValue() +// case x => x +// }) :: res; +// i = i - 1 +// } +// res +// } + +// private def textParams(s: Seq[Any]): Array[AnyRef] = { +// val res = new Array[AnyRef](s.length); +// var i: Int = 0; +// val iter = s.elements; +// while (iter.hasNext) { +// res(i) = iter.next match { +// case x: Boolean => new java.lang.Boolean(x) +// case x: Byte => new java.lang.Byte(x) +// case x: Short => new java.lang.Short(x) +// case x: Char => new java.lang.Character(x) +// case x: Int => new java.lang.Integer(x) +// case x: Long => new java.lang.Long(x) +// case x: Float => new java.lang.Float(x) +// case x: Double => new java.lang.Double(x) +// case x: Unit => "()" +// case x: AnyRef => x +// } +// i = i + 1 +// } +// res +// } + +} diff --git a/src/dotnet-library/scala/List.scala b/src/dotnet-library/scala/List.scala new file mode 100644 index 0000000000..a592060f9a --- /dev/null +++ b/src/dotnet-library/scala/List.scala @@ -0,0 +1,1305 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import scala.collection.mutable.ListBuffer +import Predef._ + +/** This object provides methods for creating specialized lists, and for + * transforming special kinds of lists (e.g. lists of lists). + * + * @author Martin Odersky and others + * @version 1.0, 15/07/2003 + */ +object List { + + /** Create a list with given elements. + * + * @param xs the elements to put in the list + * @return the list containing elements xs. + */ + def apply[A](xs: A*): List[A] = xs.toList + + /** for unapply matching + */ + def unapplySeq[A](x: List[A]): Some[List[A]] = Some(x) + + /** Create a sorted list of all integers in a range. + * + * @param from the start value of the list + * @param end the end value of the list + * @return the sorted list of all integers in range [from;end). + */ + def range(start: Int, end: Int): List[Int] = + range(start, end, 1) + + /** Create a list with element values + * vn+1 = vn + step + * where v0 = start + * and elements are in the range between start (inclusive) + * and end (exclusive) + * + * @param start the start value of the list + * @param end the end value of the list + * @param step the increment value of the list + * @return the sorted list of all integers in range [start;end). + */ + def range(start: Int, end: Int, step: Int): List[Int] = { + val b = new ListBuffer[Int] + var i = start + while ((step <= 0 || i < end) && (step >= 0 || i > end)) { + b += i + i += step + } + b.toList + } + + /** Create a sorted list with element values + * vn+1 = step(vn) + * where v0 = start + * and elements are in the range between start (inclusive) + * and end (exclusive) + * + * @param start the start value of the list + * @param end the end value of the list + * @param step the increment function of the list, must be monotonically increasing or decreasing + * @return the sorted list of all integers in range [start;end). + */ + def range(start: Int, end: Int, step: Int => Int): List[Int] = { + val up = step(start) > start + val down = step(start) < start + val b = new ListBuffer[Int] + var i = start + while ((!up || i < end) && (!down || i > end)) { + b += i + i += step(i) + } + b.toList + } + + /** Create a list containing several copies of an element. + * + * @param n the length of the resulting list + * @param elem the element composing the resulting list + * @return a list composed of n elements all equal to elem + */ + def make[A](n: Int, elem: A): List[A] = { + val b = new ListBuffer[A] + var i = 0 + while (i < n) { + b += elem + i += 1 + } + b.toList + } + + /** Create a list by applying a function to successive integers. + * + * @param n the length of the resulting list + * @param maker the procedure which, given an integer n, + * returns the nth element of the resulting list, where + * n is in interval [0;n). + * @return the list obtained by applying the maker function to + * successive integers from 0 to n (exclusive). + */ + def tabulate[A](n: Int, maker: Int => A): List[A] = { + val b = new ListBuffer[A] + var i = 0 + while (i < n) { + b += maker(i) + i += 1 + } + b.toList + } + + /** Concatenate all the elements of a given list of lists. + * + * @param xss the list of lists that are to be concatenated + * @return the concatenation of all the lists + */ + def flatten[A](xss: List[List[A]]): List[A] = concat(xss: _*) + + /** Concatenate all the argument lists into a single list. + * + * @param xss the lists that are to be concatenated + * @return the concatenation of all the lists + */ + def concat[A](xss: List[A]*): List[A] = { + val b = new ListBuffer[A] + for (xs <- xss) { + var xc = xs + while (!xc.isEmpty) { + b += xc.head + xc = xc.tail + } + } + b.toList + } + + /** Transforms a list of pair into a pair of lists. + * + * @param xs the list of pairs to unzip + * @return a pair of lists: the first list in the pair contains the list + */ + def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = { + val b1 = new ListBuffer[A] + val b2 = new ListBuffer[B] + var xc = xs + while (!xc.isEmpty) { + b1 += xc.head._1 + b2 += xc.head._2 + xc = xc.tail + } + (b1.toList, b2.toList) + } + + /** Converts an iterator to a list. + * + * @param it the iterator to convert + * @return a list that contains the elements returned by successive + * calls to it.next + */ + def fromIterator[A](it: Iterator[A]): List[A] = it.toList + + /** Converts an array into a list. + * + * @param arr the array to convert + * @return a list that contains the same elements than arr + * in the same order + */ + def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length) + + /** Converts a range of an array into a list. + * + * @param arr the array to convert + * @param start the first index to consider + * @param len the lenght of the range to convert + * @return a list that contains the same elements than arr + * in the same order + */ + def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = { + var res: List[A] = Nil + var i = start + len + while (i > start) { + i -= 1 + res = arr(i) :: res + } + res + } + + /** Parses a string which contains substrings separated by a + * separator character and returns a list of all substrings. + * + * @param str the string to parse + * @param separator the separator character + * @return the list of substrings + */ + def fromString(str: String, separator: Char): List[String] = { + var words: List[String] = Nil + var pos = str.length() + while (pos > 0) { + val pos1 = str.lastIndexOf(separator, pos - 1) + if (pos1 + 1 < pos) + words = str.substring(pos1 + 1, pos) :: words + pos = pos1 + } + words + } + + /** Returns the given string as a list of characters. + * + * @param str the string to convert. + * @return the string as a list of characters. + * @deprecated use str.toList instead + */ + @deprecated def fromString(str: String): List[Char] = + str.toList + + /** Returns the given list of characters as a string. + * + * @param xs the list to convert. + * @return the list in form of a string. + */ + def toString(xs: List[Char]): String = { + val sb = new StringBuilder() + var xc = xs + while (!xc.isEmpty) { + sb.append(xc.head) + xc = xc.tail + } + sb.toString() + } + + /** Like xs map f, but returns xs unchanged if function + * f maps all elements to themselves. + * + * @param xs ... + * @param f ... + * @return ... + */ + def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = { + def loop(ys: List[A]): List[A] = + if (ys.isEmpty) xs + else { + val head0 = ys.head + val head1 = f(head0) + if (head1 eq head0) { + loop(ys.tail) + } else { + val ys1 = head1 :: mapConserve(ys.tail)(f) + if (xs eq ys) ys1 + else { + val b = new ListBuffer[A] + var xc = xs + while (xc ne ys) { + b += xc.head + xc = xc.tail + } + b.prependToList(ys1) + } + } + } + loop(xs) + } + + /** Returns the list resulting from applying the given function f + * to corresponding elements of the argument lists. + * + * @param f function to apply to each pair of elements. + * @return [f(a0,b0), ..., f(an,bn)] if the lists are + * [a0, ..., ak], [b0, ..., bl] and + * n = min(k,l) + */ + def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = { + val b = new ListBuffer[C] + var xc = xs + var yc = ys + while (!xc.isEmpty && !yc.isEmpty) { + b += f(xc.head, yc.head) + xc = xc.tail + yc = yc.tail + } + b.toList + } + + /** Returns the list resulting from applying the given function + * f to corresponding elements of the argument lists. + * + * @param f function to apply to each pair of elements. + * @return [f(a0,b0,c0), + * ..., f(an,bn,cn)] + * if the lists are [a0, ..., ak], + * [b0, ..., bl], + * [c0, ..., cm] and + * n = min(k,l,m) + */ + def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = { + val b = new ListBuffer[D] + var xc = xs + var yc = ys + var zc = zs + while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) { + b += f(xc.head, yc.head, zc.head) + xc = xc.tail + yc = yc.tail + zc = zc.tail + } + b.toList + } + + /** Tests whether the given predicate p holds + * for all corresponding elements of the argument lists. + * + * @param p function to apply to each pair of elements. + * @return (p(a0,b0) && + * ... && p(an,bn))] + * if the lists are [a0, ..., ak]; + * [b0, ..., bl] + * and n = min(k,l) + */ + def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { + var xc = xs + var yc = ys + while (!xc.isEmpty && !yc.isEmpty) { + if (!f(xc.head, yc.head)) return false + xc = xc.tail + yc = yc.tail + } + true + } + + /** Tests whether the given predicate p holds + * for some corresponding elements of the argument lists. + * + * @param p function to apply to each pair of elements. + * @return n != 0 && (p(a0,b0) || + * ... || p(an,bn))] if the lists are + * [a0, ..., ak], + * [b0, ..., bl] and + * n = min(k,l) + */ + def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { + var xc = xs + var yc = ys + while (!xc.isEmpty && !yc.isEmpty) { + if (f(xc.head, yc.head)) return true + xc = xc.tail + yc = yc.tail + } + false + } + + /** Transposes a list of lists. + * pre: All element lists have the same length. + * + * @param xss the list of lists + * @return the transposed list of lists + */ + def transpose[A](xss: List[List[A]]): List[List[A]] = { + val buf = new ListBuffer[List[A]] + var yss = xss + while (!yss.head.isEmpty) { + buf += (yss map (_.head)) + yss = (yss map (_.tail)) + } + buf.toList + } + + /** Lists with ordered elements are ordered + implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] { + def compare [b >: List[a] <% Ordered[b]](y: b): Int = y match { + case y1: List[a] => compareLists(x, y1); + case _ => -(y compare x) + } + private def compareLists(xs: List[a], ys: List[a]): Int = { + if (xs.isEmpty && ys.isEmpty) 0 + else if (xs.isEmpty) -1 + else if (ys.isEmpty) 1 + else { + val s = xs.head compare ys.head; + if (s != 0) s + else compareLists(xs.tail, ys.tail) + } + } + } + */ +} + +/** A class representing an ordered collection of elements of type + * a. This class comes with two implementing case + * classes scala.Nil and scala.:: that + * implement the abstract members isEmpty, + * head and tail. + * + * @author Martin Odersky and others + * @version 1.0, 16/07/2003 + */ +sealed abstract class List[+A] extends Seq[A] { + + /** Returns true if the list does not contain any elements. + * @return true, iff the list is empty. + */ + override def isEmpty: Boolean + + /** Returns this first element of the list. + * + * @return the first element of this list. + * @throws Predef.NoSuchElementException if the list is empty. + */ + def head: A + + /** returns length - l, without calling length + */ + override def lengthCompare(l: Int) = { + if (isEmpty) 0 - l + else if (l <= 0) 1 + else tail.lengthCompare(l - 1) + } + + /** Returns this list without its first element. + * + * @return this list without its first element. + * @throws Predef.NoSuchElementException if the list is empty. + */ + def tail: List[A] + + /**

+ * Add an element x at the beginning of this list. + *

+ * + * @param x the element to prepend. + * @return the list with x added at the beginning. + * @ex 1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3) + */ + def ::[B >: A] (x: B): List[B] = + new scala.::(x, this) + + /**

+ * Add an element x at the end of this list. + *

+ * + * @param x the element to append. + * @return the list with x added at the end. + */ + def +[B >: A](x: B): List[B] = + if (isEmpty) List(x) + else { + val buf = new ListBuffer[B] + this copyToBuffer buf + buf += x + buf.toList + } + + /**

+ * Returns a list resulting from the concatenation of the given + * list prefix and this list. + *

+ * + * @param prefix the list to concatenate at the beginning of this list. + * @return the concatenation of the two lists. + * @ex List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4) + */ + def :::[B >: A](prefix: List[B]): List[B] = + if (isEmpty) prefix + else { + val b = new ListBuffer[B] + var those = prefix + while (!those.isEmpty) { + b += those.head + those = those.tail + } + b.prependToList(this) + } + + /** Appends two list objects. + */ + override def ++[B >: A](that: Iterable[B]): List[B] = { + val buf = new ListBuffer[B] + this copyToBuffer buf + that copyToBuffer buf + buf.toList + } + + /** Reverse the given prefix and append the current list to that. + * This function is equivalent to an application of reverse + * on the prefix followed by a call to :::, but more + * efficient (and tail recursive). + * + * @param prefix the prefix to reverse and then prepend + * @return the concatenation of the reversed prefix and the current list. + */ + def reverse_:::[B >: A](prefix: List[B]): List[B] = { + var these: List[B] = this + var pres = prefix + while (!pres.isEmpty) { + these = pres.head :: these + pres = pres.tail + } + these + } + + /** Returns the number of elements in the list. + * + * @return the number of elements in the list. + */ + def length: Int = { + var these = this + var len = 0 + while (!these.isEmpty) { + len += 1 + these = these.tail + } + len + } + + /** Creates a list with all indices in the list. This is + * equivalent to a call to List.range(0, xs.length). + * + * @return a list of all indices in the list. + */ + def indices: List[Int] = { + val b = new ListBuffer[Int] + var i = 0 + var these = this + while (!these.isEmpty) { + b += i + i += 1 + these = these.tail + } + b.toList + } + + /** Returns the elements in the list as an iterator + * + * @return an iterator on the list elements. + */ + override def elements: Iterator[A] = new Iterator[A] { + var these = List.this + def hasNext: Boolean = !these.isEmpty + def next: A = + if (!hasNext) + throw new NoSuchElementException("next on empty Iterator") + else { + val result = these.head; these = these.tail; result + } + override def toList: List[A] = these + } + + /** Overrides the method in Iterable for efficiency. + * + * @return the list itself + */ + override def toList: List[A] = this + + /** Returns the list without its last element. + * + * @return the list without its last element. + * @throws Predef.UnsupportedOperationException if the list is empty. + */ + def init: List[A] = + if (isEmpty) throw new UnsupportedOperationException("Nil.init") + else { + val b = new ListBuffer[A] + var elem = head + var next = tail + while (!next.isEmpty) { + b += elem + elem = next.head + next = next.tail + } + b.toList + } + + /** Returns the last element of this list. + * + * @return the last element of the list. + * @throws Predef.NoSuchElementException if the list is empty. + */ + override def last: A = + if (isEmpty) throw new Predef.NoSuchElementException("Nil.last") + else { + var cur = this + var next = this.tail + while (!next.isEmpty) { + cur = next + next = next.tail + } + cur.head + } + + /** Returns the n first elements of this list, or else the whole + * list, if it has less than n elements. + * + * @param n the number of elements to take. + * @return the n first elements of this list. + */ + override def take(n: Int): List[A] = { + val b = new ListBuffer[A] + var i = 0 + var these = this + while (!these.isEmpty && i < n) { + i += 1 + b += these.head + these = these.tail + } + if (these.isEmpty) this + else b.toList + } + + /** Returns the list with elements belonging to the given index range. + * + * @param start the start position of the list slice. + * @param end the end position (exclusive) of the list slice. + * @return the list with elements belonging to the given index range. + */ + override def slice(start: Int, end: Int): List[A] = { + val s = start max 0 + val e = end min this.length + drop(s) take (e - s) + } + + /** Returns the list without its n first elements. + * If this list has less than n elements, the empty list is returned. + * + * @param n the number of elements to drop. + * @return the list without its n first elements. + */ + override def drop(n: Int): List[A] = { + var these = this + var count = n + while (!these.isEmpty && count > 0) { + these = these.tail + count -= 1 + } + these + } + + /** Returns the rightmost n elements from this list. + * + * @param n the number of elements to take + * @return the suffix of length n of the list + */ + def takeRight(n: Int): List[A] = { + def loop(lead: List[A], lag: List[A]): List[A] = lead match { + case Nil => lag + case _ :: tail => loop(tail, lag.tail) + } + loop(drop(n), this) + } + + /** Returns the list wihout its rightmost n elements. + * + * @param n the number of elements to take + * @return the suffix of length n of the list + */ + def dropRight(n: Int): List[A] = { + def loop(lead: List[A], lag: List[A]): List[A] = lead match { + case Nil => Nil + case _ :: tail => lag.head :: loop(tail, lag.tail) + } + loop(drop(n), this) + } + + /** Split the list at a given point and return the two parts thus + * created. + * + * @param n the position at which to split + * @return a pair of lists composed of the first n + * elements, and the other elements. + */ + def splitAt(n: Int): (List[A], List[A]) = { + val b = new ListBuffer[A] + var i = 0 + var these = this + while (!these.isEmpty && i < n) { + i += 1 + b += these.head + these = these.tail + } + (b.toList, these) + } + + /** Returns the longest prefix of this list whose elements satisfy + * the predicate p. + * + * @param p the test predicate. + * @return the longest prefix of this list whose elements satisfy + * the predicate p. + */ + override def takeWhile(p: A => Boolean): List[A] = { + val b = new ListBuffer[A] + var these = this + while (!these.isEmpty && p(these.head)) { + b += these.head + these = these.tail + } + b.toList + } + + /** Returns the longest suffix of this list whose first element + * does not satisfy the predicate p. + * + * @param p the test predicate. + * @return the longest suffix of the list whose first element + * does not satisfy the predicate p. + */ + override def dropWhile(p: A => Boolean): List[A] = + if (isEmpty || !p(head)) this + else tail dropWhile p + + /** Returns the longest prefix of the list whose elements all satisfy + * the given predicate, and the rest of the list. + * + * @param p the test predicate + * @return a pair consisting of the longest prefix of the list whose + * elements all satisfy p, and the rest of the list. + */ + def span(p: A => Boolean): (List[A], List[A]) = { + val b = new ListBuffer[A] + var these = this + while (!these.isEmpty && p(these.head)) { + b += these.head + these = these.tail + } + (b.toList, these) + } + + /** Like span but with the predicate inverted. + */ + def break(p: A => Boolean): (List[A], List[A]) = span { x => !p(x) } + + /** Returns the n-th element of this list. The first element + * (head of the list) is at position 0. + * + * @param n index of the element to return + * @return the element at position n in this list. + * @throws Predef.NoSuchElementException if the list is too short. + */ + def apply(n: Int): A = drop(n).head + + /** Returns the list resulting from applying the given function f to each + * element of this list. + * + * @param f function to apply to each element. + * @return [f(a0), ..., f(an)] if this list is [a0, ..., an]. + */ + final override def map[B](f: A => B): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + b += f(these.head) + these = these.tail + } + b.toList + } + + /** Apply a function to all the elements of the list, and return the + * reversed list of results. This is equivalent to a call to map + * followed by a call to reverse, but more efficient. + * + * @param f the function to apply to each elements. + * @return the reversed list of results. + */ + def reverseMap[B](f: A => B): List[B] = { + def loop(l: List[A], res: List[B]): List[B] = l match { + case Nil => res + case head :: tail => loop(tail, f(head) :: res) + } + loop(this, Nil) + } + + /** Apply the given function f to each element of this list + * (while respecting the order of the elements). + * + * @param f the treatment to apply to each element. + */ + final override def foreach(f: A => Unit) { + var these = this + while (!these.isEmpty) { + f(these.head) + these = these.tail + } + } + + /** Returns all the elements of this list that satisfy the + * predicate p. The order of the elements is preserved. + * It is guarenteed that the receiver list itself is returned iff all its + * elements satisfy the predicate `p'. Hence the following equality is valid: + * + * (xs filter p) eq xs == xs forall p + * + * @param p the predicate used to filter the list. + * @return the elements of this list satisfying p. + */ + final override def filter(p: A => Boolean): List[A] = { + // return same list if all elements satisfy p + var these = this + while (!these.isEmpty && p(these.head)) { + these = these.tail + } + if (these.isEmpty) this + else { + val b = new ListBuffer[A] + var these1 = this + while (these1 ne these) { + b += these1.head + these1 = these1.tail + } + + these = these.tail // prevent the second evaluation of the predicate + // on the element on which it first failed + while (!these.isEmpty) { + if (p(these.head)) b += these.head + these = these.tail + } + b.toList + } + } + +// final def filterMap[B](f: PartialFunction[A, B]): List[B] = +// this filter f.isDefinedAt map f + + /** Removes all elements of the list which satisfy the predicate + * p. This is like filter with the + * predicate inversed. + * + * @param p the predicate to use to test elements + * @return the list without all elements which satisfy p + */ + def remove(p: A => Boolean): List[A] = filter (x => !p(x)) + + /** Partition the list in two sub-lists according to a predicate. + * + * @param p the predicate on which to partition + * @return a pair of lists: the list of all elements which satisfy + * p and the list of all elements which do not. + * The relative order of the elements in the sub-lists is the + * same as in the original list. + */ + override def partition(p: A => Boolean): (List[A], List[A]) = { + val btrue = new ListBuffer[A] + val bfalse = new ListBuffer[A] + var these = this + while (!these.isEmpty) { + (if (p(these.head)) btrue else bfalse) += these.head + these = these.tail + } + (btrue.toList, bfalse.toList) + } + + /**

+ * Sort the list according to the comparison function + * <(e1: a, e2: a) => Boolean, + * which should be true iff e1 is smaller than + * e2. + *

+ * + * @param lt the comparison function + * @return a list sorted according to the comparison function + * <(e1: a, e2: a) => Boolean. + * @ex
+   *    List("Steve", "Tom", "John", "Bob")
+   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
+   *    List("Bob", "John", "Steve", "Tom")
+ */ + def sort(lt : (A,A) => Boolean): List[A] = { + /** Merge two already-sorted lists */ + def merge(l1: List[A], l2: List[A]): List[A] = { + val res = new ListBuffer[A] + var left1 = l1 + var left2 = l2 + + while (!left1.isEmpty && !left2.isEmpty) { + if(lt(left1.head, left2.head)) { + res += left1.head + left1 = left1.tail + } else { + res += left2.head + left2 = left2.tail + } + } + + res ++= left1 + res ++= left2 + + res.toList + } + + /** Split a list into two lists of about the same size */ + def split(lst: List[A]) = { + val res1 = new ListBuffer[A] + val res2 = new ListBuffer[A] + var left = lst + + while (!left.isEmpty) { + res1 += left.head + left = left.tail + if (!left.isEmpty) { + res2 += left.head + left = left.tail + } + } + + (res1.toList, res2.toList) + } + + + /** Merge-sort the specified list */ + def ms(lst: List[A]): List[A] = + lst match { + case Nil => lst + case x :: Nil => lst + case x :: y :: Nil => + if (lt(x,y)) + lst + else + y :: x :: Nil + + case lst => + val (l1, l2) = split(lst) + val l1s = ms(l1) + val l2s = ms(l2) + merge(l1s, l2s) + } + + ms(this) + } + + + /** Count the number of elements in the list which satisfy a predicate. + * + * @param p the predicate for which to count + * @return the number of elements satisfying the predicate p. + */ + def count(p: A => Boolean): Int = { + var cnt = 0 + var these = this + while (!these.isEmpty) { + if (p(these.head)) cnt += 1 + these = these.tail + } + cnt + } + + /** Tests if the predicate p is satisfied by all elements + * in this list. + * + * @param p the test predicate. + * @return true iff all elements of this list satisfy the + * predicate p. + */ + override def forall(p: A => Boolean): Boolean = { + var these = this + while (!these.isEmpty) { + if (!p(these.head)) return false + these = these.tail + } + true + } + + /** Tests the existence in this list of an element that satisfies the + * predicate p. + * + * @param p the test predicate. + * @return true iff there exists an element in this list that + * satisfies the predicate p. + */ + override def exists(p: A => Boolean): Boolean = { + var these = this + while (!these.isEmpty) { + if (p(these.head)) return true + these = these.tail + } + false + } + + /** Find and return the first element of the list satisfying a + * predicate, if any. + * + * @param p the predicate + * @return the first element in the list satisfying p, + * or None if none exists. + */ + override def find(p: A => Boolean): Option[A] = { + var these = this + while (!these.isEmpty) { + if (p(these.head)) return Some(these.head) + these = these.tail + } + None + } + + /** Combines the elements of this list together using the binary + * function f, from left to right, and starting with + * the value z. + * + * @return f(... (f(f(z, a0), a1) ...), + * an) if the list is + * [a0, a1, ..., an]. + */ + override def foldLeft[B](z: B)(f: (B, A) => B): B = { + var acc = z + var these = this + while (!these.isEmpty) { + acc = f(acc, these.head) + these = these.tail + } + acc + } + + /** Combines the elements of this list together using the binary + * function f, from right to left, and starting with + * the value z. + * + * @return f(a0, f(a1, f(..., f(an, z)...))) + * if the list is [a0, a1, ..., an]. + */ + override def foldRight[B](z: B)(f: (A, B) => B): B = this match { + case Nil => z + case x :: xs => f(x, xs.foldRight(z)(f)) + } + + /** Combines the elements of this list together using the binary + * operator op, from left to right + * @param op The operator to apply + * @return op(... op(a0,a1), ..., an) + if the list has elements + * a0, a1, ..., an. + * @throws Predef.UnsupportedOperationException if the list is empty. + */ + override def reduceLeft[B >: A](f: (B, B) => B): B = this match { + case Nil => throw new UnsupportedOperationException("Nil.reduceLeft") + case x :: xs => ((xs: List[B]) foldLeft (x: B))(f) + } + + /** Combines the elements of this list together using the binary + * operator op, from right to left + * @param op The operator to apply + * + * @return a0 op (... op (an-1 op an)...) + * if the list has elements a0, a1, ..., + * an. + * + * @throws Predef.UnsupportedOperationException if the list is empty. + */ + override def reduceRight[B >: A](f: (B, B) => B): B = this match { + case Nil => throw new UnsupportedOperationException("Nil.reduceRight") + case x :: Nil => x: B + case x :: xs => f(x, xs reduceRight f) + } + + /** Applies the given function f to each element of + * this list, then concatenates the results. + * + * @param f the function to apply on each element. + * @return f(a0) ::: ... ::: f(an) if + * this list is [a0, ..., an]. + */ + final override def flatMap[B](f: A => Iterable[B]): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + var those = f(these.head).elements + while (those.hasNext) { + b += those.next + } + these = these.tail + } + b.toList + } + + /** A list consisting of all elements of this list in reverse order. + */ + override def reverse: List[A] = { + var result: List[A] = Nil + var these = this + while (!these.isEmpty) { + result = these.head :: result + these = these.tail + } + result + } + + /** Returns a list formed from this list and the specified list + * that by associating each element of the former with + * the element at the same position in the latter. + * If one of the two lists is longer than the other, its remaining elements are ignored. + * + * @return List((a0,b0), ..., + * (amin(m,n),bmin(m,n))) when + * List(a0, ..., am) + * zip List(b0, ..., bn) is invoked. + */ + def zip[B](that: List[B]): List[(A, B)] = { + val b = new ListBuffer[(A, B)] + var these = this + var those = that + while (!these.isEmpty && !those.isEmpty) { + b += (these.head, those.head) + these = these.tail + those = those.tail + } + b.toList + } + + /** Returns a list that pairs each element of this list + * with its index, counting from 0. + * + * @return the list List((a0,0), (a1,1), ...) + * where ai are the elements of this list. + */ + def zipWithIndex: List[(A, Int)] = { + val b = new ListBuffer[(A, Int)] + var these = this + var idx = 0 + + while(!these.isEmpty) { + b += (these.head, idx) + these = these.tail + idx += 1 + } + + b.toList + } + + /** Returns a list formed from this list and the specified list + * that by associating each element of the former with + * the element at the same position in the latter. + * + * @param that list that may have a different length + * as the self list. + * @param thisElem element thisElem is used to fill up the + * resulting list if the self list is shorter than + * that + * @param thatElem element thatElem is used to fill up the + * resulting list if that is shorter than + * the self list + * @return List((a0,b0), ..., + * (an,bn), (elem,bn+1), + * ..., {elem,bm}) + * when [a0, ..., an] zip + * [b0, ..., bm] is + * invoked where m > n. + */ + def zipAll[B, C >: A, D >: B](that: List[B], thisElem: C, thatElem: D): List[(C, D)] = { + val b = new ListBuffer[(C, D)] + var these = this + var those = that + while (!these.isEmpty && !those.isEmpty) { + b += (these.head, those.head) + these = these.tail + those = those.tail + } + while (!these.isEmpty) { + b += (these.head, thatElem) + these = these.tail + } + while (!those.isEmpty) { + b += (thisElem, those.head) + those = those.tail + } + b.toList + } + + /** Computes the union of this list and the given list + * that. + * + * @param that the list of elements to add to the list. + * @return a list without doubles containing the elements of this + * list and those of the given list that. + */ + def union[B >: A](that: List[B]): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + if (!that.contains(these.head)) b += these.head + these = these.tail + } + b.prependToList(that) + } + + /** Computes the difference between this list and the given list + * that. + * + * @param that the list of elements to remove from this list. + * @return this list without the elements of the given list + * that. + * @deprecated use -- instead + */ + @deprecated + def diff[B >: A](that: List[B]): List[B] = this -- that + + /** Computes the difference between this list and the given list + * that. + * + * @param that the list of elements to remove from this list. + * @return this list without the elements of the given list + * that. + */ + def -- [B >: A](that: List[B]): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + if (!that.contains(these.head)) b += these.head + these = these.tail + } + b.toList + } + + /** Computes the difference between this list and the given object + * x. + * + * @param x the object to remove from this list. + * @return this list without the elements of the given object + * x. + */ + def - [B >: A](x: B): List[B] = + this -- List(x) + + def flatten[B](implicit f : A => Iterable[B]) : List[B] = { + val buf = new ListBuffer[B] + foreach(f(_).foreach(buf += _)) + buf.toList + } + + /** Computes the intersection between this list and the given list + * that. + * + * @param that the list to intersect. + * @return the list of elements contained both in this list and + * in the given list that. + */ + def intersect[B >: A](that: List[B]): List[B] = filter(x => that contains x) + + /** Removes redundant elements from the list. Uses the method == + * to decide if two elements are identical. + * + * @return the list without doubles. + */ + def removeDuplicates: List[A] = { + val b = new ListBuffer[A] + var these = this + while (!these.isEmpty) { + if (!these.tail.contains(these.head)) b += these.head + these = these.tail + } + b.toList + } + + override protected def stringPrefix = "List" + override def projection = toStream + override def toStream : Stream[A] = new Stream.Definite[A] { + override def force : List[A] = List.this + override def isEmpty = List.this.isEmpty + override def head = List.this.head + override def tail = List.this.tail.toStream + protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = if (!isEmpty) { + var prefix0 = prefix + var buf1 = buf.append(prefix0).append(head) + prefix0 = ", " + var tail0 = tail + while (!tail0.isEmpty) { + buf1 = buf.append(prefix0).append(tail0.head) + tail0 = tail0.tail + } + buf1 + } else buf + } + +} + +/** The empty list. + * + * @author Martin Odersky + * @version 1.0, 15/07/2003 + */ +@SerialVersionUID(0 - 8256821097970055419L) +case object Nil extends List[Nothing] { + override def isEmpty = true + def head: Nothing = + throw new NoSuchElementException("head of empty list") + def tail: List[Nothing] = + throw new NoSuchElementException("tail of empty list") +} + +/** A non empty list characterized by a head and a tail. + * + * @author Martin Odersky + * @version 1.0, 15/07/2003 + */ +@SerialVersionUID(0L - 8476791151983527571L) +final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] { + def head : B = hd + def tail : List[B] = tl + override def isEmpty: Boolean = false +} + diff --git a/src/dotnet-library/scala/Math.scala b/src/dotnet-library/scala/Math.scala new file mode 100644 index 0000000000..4d03de9b77 --- /dev/null +++ b/src/dotnet-library/scala/Math.scala @@ -0,0 +1,135 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + + +import Predef._ + +object Math { + + /** The smallest possible value for scala.Byte. */ + val MIN_BYTE = System.Byte.MinValue + /** The greatest possible value for scala.Byte. */ + val MAX_BYTE = System.Byte.MaxValue + + /** The smallest possible value for scala.Short. */ + val MIN_SHORT = System.Int16.MinValue + /** The greatest possible value for scala.Short. */ + val MAX_SHORT = System.Int16.MaxValue + + /** The smallest possible value for scala.Char. */ + val MIN_CHAR = System.Char.MinValue + /** The greatest possible value for scala.Char. */ + val MAX_CHAR = System.Char.MaxValue + + /** The smallest possible value for scala.Int. */ + val MIN_INT = System.Int32.MinValue + /** The greatest possible value for scala.Int. */ + val MAX_INT = System.Int32.MaxValue + + /** The smallest possible value for scala.Long. */ + val MIN_LONG = System.Int64.MinValue + /** The greatest possible value for scala.Long. */ + val MAX_LONG = System.Int64.MaxValue + + /** The smallest possible value for scala.Float. */ + val MIN_FLOAT = System.Single.MinValue + /** The smallest difference between two values of scala.Float. */ + val EPS_FLOAT = System.Single.Epsilon + /** The greatest possible value for scala.Float. */ + val MAX_FLOAT = System.Single.MinValue + /** A value of type scala.Float that represents no number. */ + //val NaN_FLOAT = System.Single.NaN + /** Negative infinity of type scala.Float. */ + //val NEG_INF_FLOAT = System.Double.NegativeInfinity + /** Positive infinity of type scala.Float. */ + //val POS_INF_FLOAT = System.Double.PositiveInfinity + + /** The smallest possible value for scala.Double. */ + val MIN_DOUBLE = System.Double.MinValue + /** The smallest difference between two values of scala.Double. */ + val EPS_DOUBLE = System.Double.Epsilon + /** The greatest possible value for scala.Double. */ + val MAX_DOUBLE = System.Double.MaxValue + /** A value of type scala.Double that represents no number. */ + //val NaN_DOUBLE = System.Double.NaN + /** Negative infinity of type scala.Double. */ + //val NEG_INF_DOUBLE = System.Double.NegativeInfinity + /** Positive infinity of type scala.Double. */ + //val POS_INF_DOUBLE = System.Double.PositiveInfinity + + /** The double value that is closer than any other to + * e, the base of the natural logarithms. + */ + + val E = System.Math.E + val Pi = System.Math.PI + + //def random: Double = System.Math.random() + + def sin(x: Double): Double = System.Math.Sin(x) + def cos(x: Double): Double = System.Math.Cos(x) + def tan(x: Double): Double = System.Math.Tan(x) + def asin(x: Double): Double = System.Math.Asin(x) + def acos(x: Double): Double = System.Math.Acos(x) + def atan(x: Double): Double = System.Math.Atan(x) + + def toRadians(x: Double): Double = x * Pi / 180.0 + + def toDegrees(x: Double): Double = x * 180.0 / Pi + + def exp(x: Double): Double = System.Math.Exp(x) + def log(x: Double): Double = System.Math.Log(x) + def sqrt(x: Double): Double = System.Math.Sqrt(x) + def sqrt(x: Int): Int = System.Math.Sqrt(x.toDouble).toInt + def IEEEremainder(x: Double, y: Double): Double = System.Math.IEEERemainder(x, y) + + def ceil(x: Double): Double = System.Math.Ceiling(x) + def floor(x: Double): Double = System.Math.Floor(x) + + //def rint(x: Double): Double = System.Math.rint(x) + def atan2(y: Double, x: Double): Double = System.Math.Atan2(y, x) + def pow(x: Double, y: Double): Double = System.Math.Pow(x, y) + def round(x: Float): Int = System.Math.Round(x).toInt + def round(x: Double): Long = System.Math.Round(x).toLong + + def abs(x: Int): Int = System.Math.Abs(x) + def abs(x: Long): Long = System.Math.Abs(x) + def abs(x: Float): Float = System.Math.Abs(x) + def abs(x: Double): Double = System.Math.Abs(x) + + def max(x: Int, y: Int): Int = System.Math.Max(x, y) + def max(x: Long, y: Long): Long = System.Math.Max(x, y) + def max(x: Float, y: Float): Float = System.Math.Max(x, y) + def max(x: Double, y: Double): Double = System.Math.Max(x, y) + + def min(x: Int, y: Int): Int = System.Math.Min(x, y) + def min(x: Long, y: Long): Long = System.Math.Min(x, y) + def min(x: Float, y: Float): Float = System.Math.Min(x, y) + def min(x: Double, y: Double): Double = System.Math.Min(x, y) + + // from Java 1.5 +// def log10(x: Double): Double = java.lang.Math.log10(x) +// def cbrt(x: Double): Double = java.lang.Math.cbrt(x) + +// def ulp(x: Double): Double = java.lang.Math.ulp(x) +// def ulp(x: Float): Float = java.lang.Math.ulp(x) +// def signum(x: Double): Double = java.lang.Math.signum(x) +// def signum(x: Float): Float = java.lang.Math.signum(x) +// def sinh(x: Double): Double = java.lang.Math.sinh(x) +// def cosh(x: Double): Double = java.lang.Math.cosh(x) +// def tanh(x: Double):Double = java.lang.Math.tanh(x) +// def hypot(x: Double, y: Double): Double = java.lang.Math.hypot(x, y) +// def expm1(x: Double): Double = java.lang.Math.expm1(x) +// def log1p(x: Double): Double = java.lang.Math.log1p(x) + +} diff --git a/src/dotnet-library/scala/Predef.scala b/src/dotnet-library/scala/Predef.scala new file mode 100644 index 0000000000..dc45fe2bec --- /dev/null +++ b/src/dotnet-library/scala/Predef.scala @@ -0,0 +1,310 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + + +/** The Predef object provides definitions that are + * accessible in all Scala compilation units without explicit + * qualification. + */ +object Predef { + + // classOf dummy ------------------------------------------------------ + + /** Return the runtime representation of a class type. */ + def classOf[T]: Class[T] = null + + // aliases ------------------------------------------------------------ + + type byte = scala.Byte + type short = scala.Short + type char = scala.Char + type int = scala.Int + type long = scala.Long + type float = scala.Float + type double = scala.Double + type boolean = scala.Boolean + type unit = scala.Unit + + type String = System.String + type Class[T] = System.Type + type Runnable = scala.runtime.Runnable + + type Throwable = System.Exception + type Exception = System.Exception + type Error = System.Exception + + type RuntimeException = System.Exception + type NullPointerException = System.NullReferenceException + type ClassCastException = System.InvalidCastException + type IndexOutOfBoundsException = System.IndexOutOfRangeException + type ArrayIndexOutOfBoundsException = System.IndexOutOfRangeException + type StringIndexOutOfBoundsException = System.IndexOutOfRangeException + type UnsupportedOperationException = System.InvalidOperationException + type IllegalArgumentException = System.ArgumentException + type NoSuchElementException = System.InvalidOperationException + //type NumberFormatException = java.lang.NumberFormatException + + // miscelleaneous ----------------------------------------------------- + + //val $scope = scala.xml.TopScope + + type Function[-A, +B] = Function1[A, B] + + type Map[A, B] = collection.immutable.Map[A, B] + type Set[A] = collection.immutable.Set[A] + + val Map = collection.immutable.Map + val Set = collection.immutable.Set + + // errors and asserts ------------------------------------------------- + + def error(message: String): Nothing = throw new Error(message) + + def exit: Nothing = exit(0) + + def exit(status: Int): Nothing = { + System.Environment.Exit(status) + throw new Throwable() + } + + def assert(assertion: Boolean) { + if (!assertion) + throw new Error("assertion failed") + } + + def assert(assertion: Boolean, message: Any) { + if (!assertion) + throw new Error("assertion failed: " + message) + } + + def assume(assumption: Boolean) { + if (!assumption) + throw new IllegalArgumentException("assumption failed") + } + + def assume(assumption: Boolean, message: Any) { + if (!assumption) + throw new IllegalArgumentException("assumption failed: " + message) + } + + // tupling ------------------------------------------------------------ + + type Pair[+A, +B] = Tuple2[A, B] + object Pair { + def apply[A, B](x: A, y: B) = Tuple2(x, y) + def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x) + } + + type Triple[+A, +B, +C] = Tuple3[A, B, C] + object Triple { + def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z) + def unapply[A, B, C](x: Tuple3[A, B, C]): Option[Tuple3[A, B, C]] = Some(x) + } + + class ArrowAssoc[A](x: A) { + def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y) + } + implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x) + + def Tuple[A1](x1: A1) = Tuple1(x1) + def Tuple[A1, A2](x1: A1, x2: A2) = Tuple2(x1, x2) + def Tuple[A1, A2, A3](x1: A1, x2: A2, x3: A3) = Tuple3(x1, x2, x3) + def Tuple[A1, A2, A3, A4](x1: A1, x2: A2, x3: A3, x4: A4) = Tuple4(x1, x2, x3, x4) + def Tuple[A1, A2, A3, A4, A5](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5) = Tuple5(x1, x2, x3, x4, x5) + def Tuple[A1, A2, A3, A4, A5, A6](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6) = Tuple6(x1, x2, x3, x4, x5, x6) + def Tuple[A1, A2, A3, A4, A5, A6, A7](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7) = Tuple7(x1, x2, x3, x4, x5, x6, x7) + def Tuple[A1, A2, A3, A4, A5, A6, A7, A8](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8) = Tuple8(x1, x2, x3, x4, x5, x6, x7, x8) + def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9) = Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9) + + // printing and reading ----------------------------------------------- + + def print(x: Any) = Console.print(x) + def println() = Console.println() + def println(x: Any) = Console.println(x) + //def printf(text: String, xs: Any*) = Console.printf(text, xs: _*) + //def format(text: String, xs: Any*) = Console.format(text, xs) + + def readLine(): String = Console.readLine() + def readLine(text: String, args: Any*) = Console.readLine(text, args) + def readBoolean() = Console.readBoolean() + def readByte() = Console.readByte() + def readShort() = Console.readShort() + def readChar() = Console.readChar() + def readInt() = Console.readInt() + def readLong() = Console.readLong() + def readFloat() = Console.readFloat() + def readDouble() = Console.readDouble() + //def readf(format: String) = Console.readf(format) + //def readf1(format: String) = Console.readf1(format) + //def readf2(format: String) = Console.readf2(format) + //def readf3(format: String) = Console.readf3(format) + + // views -------------------------------------------------------------- + + implicit def identity[A](x: A): A = x + + implicit def byteWrapper(x: Byte) = new runtime.RichByte(x) + implicit def shortWrapper(x: Short) = new runtime.RichShort(x) + implicit def intWrapper(x: Int) = new runtime.RichInt(x) + implicit def charWrapper(c: Char) = new runtime.RichChar(c) + implicit def longWrapper(x: Long) = new runtime.RichLong(x) + implicit def floatWrapper(x: Float) = new runtime.RichFloat(x) + implicit def doubleWrapper(x: Double) = new runtime.RichDouble(x) + + implicit def booleanWrapper(x: Boolean) = new runtime.RichBoolean(x) + + implicit def stringWrapper(x: String) = new runtime.RichString(x) + //implicit def stringBuilderWrapper(x : StringBuilder) = new runtime.RichStringBuilder(x) + + implicit def any2stringadd(x: Any) = new runtime.StringAdd(x) + + implicit def exceptionWrapper(exc: Throwable) = new runtime.RichException(exc) + + final class GetClassWrapper(obj: AnyRef) { + def getClass(): runtime.RichClass = classWrapper(obj.GetType()) + } + implicit def getClassWrapper(obj: AnyRef) = new GetClassWrapper(obj) + implicit def classWrapper(clazz: Class[_]): runtime.RichClass = + new runtime.RichClass(clazz) + + implicit def unit2ordered(x: Unit): Ordered[Unit] = new Ordered[Unit] with Proxy { + def self: Any = x + def compare(y: Unit): Int = 0 + } + + implicit def iterable2ordered[A <% Ordered[A]](xs: Iterable[A]): Ordered[Iterable[A]] = + new Ordered[Iterable[A]] with Proxy { + val self = xs + def compare(that: Iterable[A]): Int = { + var res = 0 + val these = xs.elements + val those = that.elements + while (res == 0 && these.hasNext) + res = if (those.hasNext) these.next compare those.next else 1 + if (res == 0) { + if (those.hasNext) -1 else 0 + } else + res + } + } + + implicit def tuple22ordered[A1 <% Ordered[A1], A2 <% Ordered[A2]](x: Tuple2[A1, A2]): Ordered[Tuple2[A1, A2]] = + new Ordered[Tuple2[A1, A2]] with Proxy { + val self = x + def compare(y: Tuple2[A1, A2]): Int = { + val res = x._1 compare y._1 + if (res == 0) x._2 compare y._2 + else res + } + } + + implicit def tuple32ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3]](x: Tuple3[A1, A2, A3]): Ordered[Tuple3[A1, A2, A3]] = + new Ordered[Tuple3[A1, A2, A3]] with Proxy { + val self = x + def compare(y: Tuple3[A1, A2, A3]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple2(x._2, x._3) compare Tuple2(y._2, y._3) + else res + } + } + + implicit def tuple42ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4]](x: Tuple4[A1, A2, A3, A4]): Ordered[Tuple4[A1, A2, A3, A4]] = + new Ordered[Tuple4[A1, A2, A3, A4]] with Proxy { + val self = x + def compare(y: Tuple4[A1, A2, A3, A4]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple3(x._2, x._3, x._4) compare Tuple3(y._2, y._3, y._4) + else res + } + } + + implicit def tuple52ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5]](x: Tuple5[A1, A2, A3, A4, A5]): Ordered[Tuple5[A1, A2, A3, A4, A5]] = + new Ordered[Tuple5[A1, A2, A3, A4, A5]] with Proxy { + val self = x + def compare(y: Tuple5[A1, A2, A3, A4, A5]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple4(x._2, x._3, x._4, x._5) compare Tuple4(y._2, y._3, y._4, y._5) + else res + } + } + + implicit def tuple62ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6]](x: Tuple6[A1, A2, A3, A4, A5, A6]): Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] = + new Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] with Proxy { + val self = x + def compare(y: Tuple6[A1, A2, A3, A4, A5, A6]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple5(x._2, x._3, x._4, x._5, x._6) compare Tuple5(y._2, y._3, y._4, y._5, y._6) + else res + } + } + + implicit def tuple72ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7]](x: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] = + new Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] with Proxy { + val self = x + def compare(y: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple6(x._2, x._3, x._4, x._5, x._6, x._7) compare Tuple6(y._2, y._3, y._4, y._5, y._6, y._7) + else res + } + } + + implicit def tuple82ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8]](x: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] = + new Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] with Proxy { + val self = x + def compare(y: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple7(x._2, x._3, x._4, x._5, x._6, x._7, x._8) compare Tuple7(y._2, y._3, y._4, y._5, y._6, y._7, y._8) + else res + } + } + + implicit def tuple92ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8], A9 <% Ordered[A9]](x: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] = + new Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] with Proxy { + val self = x + def compare(y: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple8(x._2, x._3, x._4, x._5, x._6, x._7, x._8, x._9) compare Tuple8(y._2, y._3, y._4, y._5, y._6, y._7, y._8, y._9) + else res + } + } + + implicit def byte2short(x: Byte): Short = x.toShort + implicit def byte2int(x: Byte): Int = x.toInt + implicit def byte2long(x: Byte): Long = x.toLong + implicit def byte2float(x: Byte): Float = x.toFloat + implicit def byte2double(x: Byte): Double = x.toDouble + + implicit def short2int(x: Short): Int = x.toInt + implicit def short2long(x: Short): Long = x.toLong + implicit def short2float(x: Short): Float = x.toFloat + implicit def short2double(x: Short): Double = x.toDouble + + implicit def char2int(x: Char): Int = x.toInt + implicit def char2long(x: Char): Long = x.toLong + implicit def char2float(x: Char): Float = x.toFloat + implicit def char2double(x: Char): Double = x.toDouble + + implicit def int2long(x: Int): Long = x.toLong + implicit def int2float(x: Int): Float = x.toFloat + implicit def int2double(x: Int): Double = x.toDouble + + implicit def long2float(x: Long): Float = x.toFloat + implicit def long2double(x: Long): Double = x.toDouble + + implicit def float2double(x: Float): Double = x.toDouble + + implicit def forceArrayProjection[A](x : Array.Projection[A]) : Array[A] = x.force + + def currentThread = System.Threading.Thread.CurrentThread + +} diff --git a/src/dotnet-library/scala/Random.scala b/src/dotnet-library/scala/Random.scala new file mode 100644 index 0000000000..7d0b1be853 --- /dev/null +++ b/src/dotnet-library/scala/Random.scala @@ -0,0 +1,74 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +/** + * @author Stephane Micheloud + */ +class Random(self0: System.Random) { + private var rnd = self0 // see setSeed(seed) + def self = rnd + + /** Creates a new random number generator using a single long seed. */ + def this(seed: Long) = this(new System.Random(seed.toInt)) + + /** Creates a new random number generator using a single integer seed. */ + def this(seed: Int) = this(new System.Random(seed)) + + /** Creates a new random number generator. */ + def this() = this(new System.Random(System.Environment.TickCount)) + + /** Returns the next pseudorandom, uniformly distributed boolean value + * from this random number generator's sequence. + */ + def nextBoolean(): Boolean = (nextInt() & 0x1) == 1 + + /** Generates random bytes and places them into a user-supplied byte + * array. + */ + def nextBytes(bytes: Array[Byte]) { rnd.NextBytes(bytes) } + + /** Returns the next pseudorandom, uniformly distributed double value + * between 0.0 and 1.0 from this random number generator's sequence. + */ + def nextDouble(): Double = rnd.NextDouble() + + /** Returns the next pseudorandom, uniformly distributed float value + * between 0.0 and 1.0 from this random number generator's sequence. + */ + def nextFloat(): Float = nextDouble().toFloat + + /** Returns the next pseudorandom, Gaussian ("normally") distributed + * double value with mean 0.0 and standard deviation 1.0 from this + * random number generator's sequence. + */ + //def nextGaussian(): Double + + /** Returns the next pseudorandom, uniformly distributed int value + * from this random number generator's sequence. + */ + def nextInt(): Int = rnd.Next() + + /** Returns a pseudorandom, uniformly distributed int value between 0 + * (inclusive) and the specified value (exclusive), drawn from this + * random number generator's sequence. + */ + def nextInt(n: Int): Int = rnd.Next(0, n) + + /** Returns the next pseudorandom, uniformly distributed long value + * from this random number generator's sequence. + */ + def nextLong(): Long = nextInt().toLong // 2x nextInt() ?! + + def setSeed(seed: Long) { rnd = new System.Random(seed.toInt) } + +} diff --git a/src/dotnet-library/scala/StringBuilder.scala b/src/dotnet-library/scala/StringBuilder.scala new file mode 100644 index 0000000000..b6912060e2 --- /dev/null +++ b/src/dotnet-library/scala/StringBuilder.scala @@ -0,0 +1,709 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import Predef._ + +/**

+ * A mutable sequence of characters. This class provides an API compatible + * with java.lang.StringBuilder, but with no guarantee of + * synchronization. + *

+ * + * @author Stephane Micheloud + * @version 1.0 + */ +final class StringBuilder(initCapacity: Int, private val initValue: String) +extends (Int => Char) with Proxy { + if (initCapacity < 0) throw new IllegalArgumentException + if (initValue eq null) throw new NullPointerException + + /** The value is used for character storage. */ + private var value = new Array[Char](initCapacity + initValue.length) + + /** The count is the number of characters used. */ + private var count: Int = 0 + + /** Constructs a string builder with no characters in it and an + * initial capacity of 16 characters. + */ + def this() = this(16, "") + + /** Constructs a string builder with no characters in it and an + * initial capacity specified by the capacity argument. + * + * @param capacity the initial capacity. + * @throws NegativeArraySizeException if the capacity + * argument is less than 0. + */ + def this(capacity: Int) = this(capacity, "") + + def this(str: String) = this(16, str) + + append(initValue) + + def self = this + + def toArray: Array[Char] = value + + def length: Int = count + + def length_=(n: Int) { setLength(n) } + + /** Sets the length of the character sequence. + * + * @param newLength the new length + * @throws IndexOutOfBoundsException if the n argument is negative. + */ + def setLength(n: Int) { + if (n < 0) + throw new StringIndexOutOfBoundsException//(n) + if (n > value.length) expandCapacity(n) + if (count < n) + while (count < n) { + value(count) = '\0'; count += 1 + } + else + count = n + } + + /** Returns the current capacity. The capacity is the amount of storage + * available for newly inserted characters, beyond which an allocation + * will occur. + * + * @return the current capacity + */ + def capacity: Int = value.length + + /** Same as ensureCapacity. */ + def capacity_=(n: Int) { ensureCapacity(n) } + + /**

+ * Ensures that the capacity is at least equal to the specified minimum. + * If the current capacity is less than the argument, then a new internal + * array is allocated with greater capacity. The new capacity is the larger of: + *

+ * + *

+ * If the n argument is non-positive, this + * method takes no action and simply returns. + *

+ * + * @param n the minimum desired capacity. + */ + def ensureCapacity(n: Int) { + if (n > value.length) expandCapacity(n) + } + + private def expandCapacity(n: Int) { + val newCapacity = (value.length + 1) * 2 + value = StringBuilder.copyOf( + value, + if (newCapacity < 0) Math.MAX_INT else if (n > newCapacity) n else newCapacity + ) + } + + /**

+ * Returns the Char value in this sequence at the specified index. + * The first Char value is at index 0, the next at index + * 1, and so on, as in array indexing. + *

+ *

+ * The index argument must be greater than or equal to + * 0, and less than the length of this sequence. + *

+ * + * @param index the index of the desired Char value. + * @return the Char value at the specified index. + * @throws IndexOutOfBoundsException if index is + * negative or greater than or equal to length(). + */ + def charAt(index: Int): Char = { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException//(index) + value(index) + } + + /** Same as charAt. */ + def apply(i: Int): Char = charAt(i) + + /**

+ * Removes the Char at the specified position in this + * sequence. This sequence is shortened by one Char. + *

+ * + * @param index Index of Char to remove + * @return This object. + * @throws StringIndexOutOfBoundsException if the index + * is negative or greater than or equal to length(). + */ + def deleteCharAt(index: Int): StringBuilder = { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException//(index) + compat.Platform.arraycopy(value, index + 1, value, index, count - index - 1) + count -= 1 + this + } + + /**

+ * The character at the specified index is set to ch. This + * sequence is altered to represent a new character sequence that is + * identical to the old character sequence, except that it contains the + * character ch at position index. + *

+ *

+ * The index argument must be greater than or equal to + * 0, and less than the length of this sequence. + *

+ * + * @param index the index of the character to modify. + * @param ch the new character. + * @throws IndexOutOfBoundsException if index is + * negative or greater than or equal to length(). + */ + def setCharAt(index: Int, ch: Char) { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException//(index) + value(index) = ch + } + + /** Same as setCharAt. */ + def update(i: Int, c: Char) { setCharAt(i, c) } + + /** Returns a new String that contains a subsequence of + * characters currently contained in this character sequence. The + * substring begins at the specified index and extends to the end of + * this sequence. + * + * @param start The beginning index, inclusive. + * @return The new string. + * @throws StringIndexOutOfBoundsException if start is + * less than zero, or greater than the length of this object. + */ + def substring(start: Int): String = substring(start, count) + + /** Returns a new String that contains a subsequence of + * characters currently contained in this sequence. The + * substring begins at the specified start and + * extends to the character at index end - 1. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @return The new string. + * @throws StringIndexOutOfBoundsException if start + * or end are negative or greater than + * length(), or start is + * greater than end. + */ + def substring(start: Int, end: Int): String = { + if (start < 0) + throw new StringIndexOutOfBoundsException//(start) + if (end > count) + throw new StringIndexOutOfBoundsException//(end) + if (start > end) + throw new StringIndexOutOfBoundsException//(end - start) + new String(value, start, end - start) + } + + /**

+ * Appends the string representation of the Any + * argument. + *

+ *

+ * The argument is converted to a string as if by the method + * System.Convert.ToString, and the characters of + * that string are then appended to this sequence. + *

+ * + * @param x an Any object. + * @return a reference to this object. + */ + def append(x: Any): StringBuilder = + append(System.Convert.ToString(x)) + + /** Appends the specified string to this character sequence. + * + * @param s a string. + * @return a reference to this object. + */ + def append(s: String): StringBuilder = { + val str = if (s == null) "null" else s + val len = str.length + if (len > 0) { + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(str.ToCharArray, 0, value, count, len) + count = newCount + } + this + } + + /** Appends the specified string builder to this sequence. + * + * @param sb + * @return + */ + def append(sb: StringBuilder): StringBuilder = + if (sb == null) + append("null") + else { + val len = sb.length + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(sb.toArray, 0, value, count, len) + count = newCount + this + } + + /**

+ * Appends the string representation of the Char array + * argument to this sequence. + *

+ *

+ * The characters of the array argument are appended, in order, to + * the contents of this sequence. The length of this sequence + * increases by the length of the argument. + *

+ * + * @param x the characters to be appended. + * @return a reference to this object. + */ + def append(x: Array[Char]): StringBuilder = + append(x, 0, x.length) + + /**

+ * Appends the string representation of a subarray of the + * char array argument to this sequence. + *

+ *

+ * Characters of the Char array x, starting at + * index offset, are appended, in order, to the contents + * of this sequence. The length of this sequence increases + * by the value of len. + *

+ * + * @param x the characters to be appended. + * @param offset the index of the first Char to append. + * @param len the number of Chars to append. + * @return a reference to this object. + */ + def append(x: Array[Char], offset: Int, len: Int): StringBuilder = { + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(x, offset, value, count, len) + count = newCount + this + } + + /**

+ * Appends the string representation of the Boolean + * argument to the sequence. + *

+ *

+ * The argument is converted to a string as if by the method + * System.Convert.ToString, and the characters of + * that string are then appended to this sequence. + *

+ * + * @param x a Boolean. + * @return a reference to this object. + */ + def append(x: Boolean): StringBuilder = { + if (x) { + val newCount = count + 4 + if (newCount > value.length) expandCapacity(newCount) + value(count) = 't'; count += 1 + value(count) = 'r'; count += 1 + value(count) = 'u'; count += 1 + value(count) = 'e'; count += 1 + } else { + val newCount = count + 5 + if (newCount > value.length) expandCapacity(newCount) + value(count) = 'f'; count += 1 + value(count) = 'a'; count += 1 + value(count) = 'l'; count += 1 + value(count) = 's'; count += 1 + value(count) = 'e'; count += 1 + } + this + } + + def append(x: Char): StringBuilder = { + val newCount = count + 1 + if (newCount > value.length) expandCapacity(newCount) + value(count) = x; count += 1 + this + } + + def append(x: Int): StringBuilder = + append(System.Convert.ToString(x)) + + def append(x: Long): StringBuilder = + append(System.Convert.ToString(x)) + + def append(x: Float): StringBuilder = + append(System.Convert.ToString(x)) + + def append(x: Double): StringBuilder = + append(System.Convert.ToString(x)) + + /** Removes the characters in a substring of this sequence. + * The substring begins at the specified start and extends to + * the character at index end - 1 or to the end of the + * sequence if no such character exists. If + * start is equal to end, no changes are made. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @return This object. + * @throws StringIndexOutOfBoundsException if start + * is negative, greater than length(), or + * greater than end. + */ + def delete(start: Int, end: Int): StringBuilder = { + if (start < 0 || start > end) + throw new StringIndexOutOfBoundsException//(start) + val end0 = if (end > count) count else end + val len = end0 - start + if (len > 0) { + compat.Platform.arraycopy(value, start + len, value, start, count - end0) + count -= len + } + this + } + + /** Replaces the characters in a substring of this sequence + * with characters in the specified String. The substring + * begins at the specified start and extends to the character + * at index end - 1 or to the end of the sequence if no such + * character exists. First the characters in the substring are removed and + * then the specified String is inserted at start. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @param str String that will replace previous contents. + * @return This object. + * @throws StringIndexOutOfBoundsException if start + * is negative, greater than length(), or + * greater than end. + */ + def replace(start: Int, end: Int, str: String) { + if (start < 0 || start > count || start > end) + throw new StringIndexOutOfBoundsException//(start) + + val end0 = if (end > count) count else end + val len = str.length() + val newCount = count + len - (end0 - start) + if (newCount > value.length) expandCapacity(newCount) + + compat.Platform.arraycopy(value, end, value, start + len, count - end) + compat.Platform.arraycopy(str.ToCharArray, 0, value, start, len) + count = newCount + this + } + + /** Inserts the string representation of a subarray of the str + * array argument into this sequence. The subarray begins at the specified + * offset and extends len chars. + * The characters of the subarray are inserted into this sequence at + * the position indicated by index. The length of this + * sequence increases by len Chars. + * + * @param index position at which to insert subarray. + * @param str a Char array. + * @param offset the index of the first char in subarray to + * be inserted. + * @param len the number of Chars in the subarray to + * be inserted. + * @return This object + * @throws StringIndexOutOfBoundsException if index + * is negative or greater than length(), or + * offset or len are negative, or + * (offset+len) is greater than + * str.length. + */ + def insert(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = { + if (index < 0 || index > count) + throw new StringIndexOutOfBoundsException//(index) + if (offset < 0 || len < 0 || offset > str.length - len) + throw new StringIndexOutOfBoundsException/*( + "offset " + offset + ", len " + len + + ", str.length " + str.length)*/ + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, index, value, index + len, count - index) + compat.Platform.arraycopy(str, offset, value, index, len) + count = newCount + this + } + + /**

+ * Inserts the string representation of the Any + * argument into this character sequence. + *

+ *

+ * The second argument is converted to a string as if by the method + * System.Convert.ToString, and the characters of that + * string are then inserted into this sequence at the indicated + * offset. + *

+ *

+ * The offset argument must be greater than or equal to + * 0, and less than or equal to the length of this + * sequence. + *

+ * + * @param offset the offset. + * @param x an Any value. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: Any): StringBuilder = + insert(at, System.Convert.ToString(x)) + + /** Inserts the string into this character sequence. + * + * @param at the offset position. + * @param x a string. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: String): StringBuilder = { + if (at < 0 || at > count) + throw new StringIndexOutOfBoundsException//(at) + val str = if (x == null) "null" else x + val len = str.length + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, at, value, at + len, count - at) + compat.Platform.arraycopy(str.ToCharArray, 0, value, at, len) + count = newCount + this + } + + /** Inserts the string representation of the Char array + * argument into this sequence. + * + * @param at the offset position. + * @param x a character array. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: Array[Char]): StringBuilder = { + if (at < 0 || at > count) + throw new StringIndexOutOfBoundsException//(at) + val len = x.length + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, at, value, at + len, count - at) + compat.Platform.arraycopy(x, 0, value, at, len) + count = newCount + this + } + + def insert(at: Int, x: Boolean): StringBuilder = + insert(at, System.Convert.ToString(x)) + + def insert(at: Int, x: Char): StringBuilder = { + if (at < 0 || at > count) + throw new StringIndexOutOfBoundsException//(at) + val newCount = count + 1 + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, at, value, at + 1, count - at) + value(at) = x + count = newCount + this + } + + def insert(at: Int, x: Int): StringBuilder = + insert(at, System.Convert.ToString(x)) + + def insert(at: Int, x: Long): StringBuilder = + insert(at, System.Convert.ToString(x)) + + def insert(at: Int, x: Float): StringBuilder = + insert(at, System.Convert.ToString(x)) + + def insert(at: Int, x: Double): StringBuilder = + insert(at, System.Convert.ToString(x)) + + /** Returns the index within this string of the first occurrence of the + * specified substring. The integer returned is the smallest value + * k such that: + *
+   *  this.toString().startsWith(str, k)
+   *  
+ * is true. + * + * @param str any string. + * @return if the string argument occurs as a substring within this + * object, then the index of the first character of the first + * such substring is returned; if it does not occur as a + * substring, -1 is returned. + * @throws NullPointerException if str is null. + */ + def indexOf(str: String): Int = indexOf(str, 0) + + def indexOf(str: String, fromIndex: Int): Int = + StringBuilder.indexOf(value, 0, count, str.ToCharArray, 0, str.length(), fromIndex) + + /** Returns the index within this string of the rightmost occurrence + * of the specified substring. The rightmost empty string "" is + * considered to occur at the index value this.length(). + * The returned index is the largest value k such that + *
+   *  this.toString().startsWith(str, k)
+   *  
+ * is true. + * + * @param str the substring to search for. + * @return if the string argument occurs one or more times as a substring + * within this object, then the index of the first character of + * the last such substring is returned. If it does not occur as + * a substring, -1 is returned. + * @throws NullPointerException if str is null. + */ + def lastIndexOf(str: String): Int = lastIndexOf(str, count) + + def lastIndexOf(str: String, fromIndex: Int): Int = + StringBuilder.lastIndexOf(value, 0, count, str.ToCharArray, 0, str.length(), fromIndex) + + /**

+ * Causes this character sequence to be replaced by the reverse of the + * sequence. If there are any surrogate pairs included in the sequence, + * these are treated as single characters for the reverse operation. + * Thus, the order of the high-low surrogates is never reversed. + *

+ *

+ * Let n be the character length of this character sequence + * (not the length in Char values) just prior to + * execution of the reverse method. Then the + * character at index k in the new character sequence is + * equal to the character at index n-k-1 in the old + * character sequence. + *

+ * + * @return a reference to this object. + */ + def reverse(): StringBuilder = { + val n = count - 1 + var j = (n-1) >> 1 + while (j >= 0) { + val temp = value(j) + val temp2 = value(n - j) + value(j) = temp2 + value(n - j) = temp + j -= 1 + } + this + } + + /** Returns a string representing the data in this sequence. + * A new String object is allocated and initialized to + * contain the character sequence currently represented by this + * object. This String is then returned. Subsequent + * changes to this sequence do not affect the contents of the + * String. + * + * @return a string representation of this sequence of characters. + */ + override def toString(): String = new String(value, 0, count) + +} + + +object StringBuilder { + + // method java.util.Arrays.copyOf exists since 1.6 + private def copyOf(src: Array[Char], newLength: Int): Array[Char] = { + val dest = new Array[Char](newLength) + compat.Platform.arraycopy(src, 0, dest, 0, Math.min(src.length, newLength)) + dest + } + + private def indexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, + target: Array[Char], targetOffset: Int, targetCount: Int, + fromIndex: Int): Int = + if (fromIndex >= sourceCount) + if (targetCount == 0) sourceCount else -1 + else { + val inx = if (fromIndex < 0) 0 else fromIndex + if (targetCount == 0) + inx + else { + val first = target(targetOffset) + val max = sourceOffset + (sourceCount - targetCount) + + var i = sourceOffset + inx + while (i <= max) { + /* Look for first character. */ + if (source(i) != first) { + i += 1 + while (i <= max && source(i) != first) i += 1 + } + /* Found first character, now look at the rest of v2 */ + if (i <= max) { + var j = i + 1 + val end = j + targetCount - 1 + var k = targetOffset + 1 + while (j < end && source(j) == target(k)) { + j += 1 + k += 1 + } + if (j == end) { + /* Found whole string. */ + return i - sourceOffset + } + } // if + i += 1 + } // while + -1 + } + } + + private def lastIndexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, + target: Array[Char], targetOffset: Int, targetCount: Int, + fromIndex: Int): Int = { + val rightIndex = sourceCount - targetCount + if (fromIndex < 0) return -1 + val inx = if (fromIndex > rightIndex) rightIndex else fromIndex + // Empty string always matches + if (targetCount == 0) return inx + + val strLastIndex = targetOffset + targetCount - 1 + val strLastChar = target(strLastIndex) + val min = sourceOffset + targetCount - 1 + var i = min + fromIndex + + while (true) { + while (i >= min && source(i) != strLastChar) i -= 1 + if (i < min) return -1 + var j = i - 1 + val start = j - (targetCount - 1) + var k = strLastIndex - 1 + var outerWhile = false + while (j > start && !outerWhile) { + if (source(j) != target(k)) { + j -= 1 + k -= 1 + i -= 1 + outerWhile = true + } + } + if (!outerWhile) return start - sourceOffset + 1 + } + -1 + } +} diff --git a/src/dotnet-library/scala/Symbol.scala b/src/dotnet-library/scala/Symbol.scala new file mode 100644 index 0000000000..27bc2de7e1 --- /dev/null +++ b/src/dotnet-library/scala/Symbol.scala @@ -0,0 +1,49 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + + +/**

+ * Instances of Symbol can be created easily with + * Scala's built-in quote mechanism. + *

+ *

+ * For instance, the Scala + * term 'mysym will invoke the constructor of the + * Symbol class in the following way: + * new Symbol("mysym"). + *

+ * + * @author Martin Odersky + * @version 1.7, 08/12/2003 + */ +final case class Symbol(name: String) { + + /** Converts this symbol to a string. + */ + override def toString(): String = { + "'" + name + } + + /**

+ * Makes this symbol into a unique reference. + *

+ *

+ * If two interened symbols are equal (i.e. they have the same name) + * then they must be identical (wrt reference equality). + *

+ * + * @return the unique reference to this symbol. + */ + def intern: Symbol = this + +} diff --git a/src/dotnet-library/scala/compat/Platform.scala b/src/dotnet-library/scala/compat/Platform.scala new file mode 100644 index 0000000000..e589860bdc --- /dev/null +++ b/src/dotnet-library/scala/compat/Platform.scala @@ -0,0 +1,64 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.compat + + +import Predef._ + +object Platform { + + type StackOverflowError = System.StackOverflowException + type ConcurrentModificationException = System.Exception + + /** + * @param src .. + * @param srcPos .. + * @param dest .. + * @param destPos .. + * @param length .. + */ + def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) { + if (!src.isInstanceOf[System.Array]) throw new Exception("src for arraycopy is not an Array; use scala.Array.copy for boxed arrays"); + if (!dest.isInstanceOf[System.Array]) throw new Exception("dest for arraycopy is not an Array; use scala.Array.copy for boxed arrays"); + System.Array.Copy(src.asInstanceOf[System.Array], srcPos, dest.asInstanceOf[System.Array], destPos, length) + } + + /** Create array of the same type as arrayInstance with the given + * length. + * + * @param elemClass .. + * @param length .. + * @return .. + */ + def createArray(elemClass: Class[_], length: Int): AnyRef = + System.Array.CreateInstance(elemClass, length) + + def arrayclear(arr: Array[Int]) { + System.Array.Clear(arr.asInstanceOf[System.Array], 0, arr.length) + } + + def getClassForName(name: String): Class[_] = System.Type.GetType(name) + + val EOL = System.Environment.NewLine + + def currentTime: Long = 0L +/* // compiler crash :-( + private lazy val baseTicks = (new System.DateTime(1970, 1, 1, 0, 0, 0)).Ticks + def currentTime: Long = { + val nowTicks = System.DateTime.UtcNow.Ticks + (nowTicks - baseTicks) / 10000 + } +*/ + def collectGarbage { System.GC.Collect() } + +} + diff --git a/src/dotnet-library/scala/runtime/BooleanRef.cs b/src/dotnet-library/scala/runtime/BooleanRef.cs new file mode 100644 index 0000000000..2680b30149 --- /dev/null +++ b/src/dotnet-library/scala/runtime/BooleanRef.cs @@ -0,0 +1,22 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + [Serializable] + public class BooleanRef { + public bool elem; + public BooleanRef(bool elem) { this.elem = elem; } + override public string ToString() { return elem.ToString(); } + } + +} diff --git a/src/dotnet-library/scala/runtime/BoxedUnit.cs b/src/dotnet-library/scala/runtime/BoxedUnit.cs new file mode 100644 index 0000000000..d3ef5a3e11 --- /dev/null +++ b/src/dotnet-library/scala/runtime/BoxedUnit.cs @@ -0,0 +1,36 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +namespace scala.runtime { + + using System; + + [Serializable] + public sealed class BoxedUnit { + + public static readonly BoxedUnit UNIT = new BoxedUnit(); + + private BoxedUnit() { } + + override public bool Equals(object other) { + return this == other; + } + + override public int GetHashCode() { + return 0; + } + + override public string ToString() { + return "()"; + } + } + +} diff --git a/src/dotnet-library/scala/runtime/ByteRef.cs b/src/dotnet-library/scala/runtime/ByteRef.cs new file mode 100644 index 0000000000..6a539a3afd --- /dev/null +++ b/src/dotnet-library/scala/runtime/ByteRef.cs @@ -0,0 +1,22 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + [Serializable] + public class ByteRef { + public byte elem; + public ByteRef(byte elem) { this.elem = elem; } + override public string ToString() { return elem.ToString(); } + } + +} diff --git a/src/dotnet-library/scala/runtime/CharRef.cs b/src/dotnet-library/scala/runtime/CharRef.cs new file mode 100644 index 0000000000..75b2817b83 --- /dev/null +++ b/src/dotnet-library/scala/runtime/CharRef.cs @@ -0,0 +1,22 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + [Serializable] + public class CharRef { + public char elem; + public CharRef(char elem) { this.elem = elem; } + override public string ToString() { return elem.ToString(); } + } + +} diff --git a/src/dotnet-library/scala/runtime/Comparator.cs b/src/dotnet-library/scala/runtime/Comparator.cs new file mode 100644 index 0000000000..4a1322d49c --- /dev/null +++ b/src/dotnet-library/scala/runtime/Comparator.cs @@ -0,0 +1,40 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + public class Comparator { + public static bool equals(object a, object b) { + if (a == null) + return b == null; + if (a.Equals(b)) + return true; + if (a == b) + return true; + IConvertible aa = a as IConvertible; + IConvertible bb = b as IConvertible; + if (aa != null && bb != null) { + if (a is Decimal || b is Decimal) + return aa.ToDecimal(null) == bb.ToDecimal(null); + if (a is Double || b is Double) + return aa.ToDouble(null) == bb.ToDouble(null); + if (a is Single || b is Single) + return aa.ToSingle(null) == bb.ToSingle(null); + if (a is Int64 || b is Int64) + return aa.ToInt64(null) == bb.ToInt64(null); + return aa.ToInt32(null) == bb.ToInt32(null); + } + return false; + } + } + +} diff --git a/src/dotnet-library/scala/runtime/DoubleRef.cs b/src/dotnet-library/scala/runtime/DoubleRef.cs new file mode 100644 index 0000000000..60a155f00b --- /dev/null +++ b/src/dotnet-library/scala/runtime/DoubleRef.cs @@ -0,0 +1,22 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + [Serializable] + public class DoubleRef { + public double elem; + public DoubleRef(double elem) { this.elem = elem; } + override public string ToString() { return elem.ToString(); } + } + +} diff --git a/src/dotnet-library/scala/runtime/ExceptionHandling.cs b/src/dotnet-library/scala/runtime/ExceptionHandling.cs new file mode 100644 index 0000000000..4448777f2e --- /dev/null +++ b/src/dotnet-library/scala/runtime/ExceptionHandling.cs @@ -0,0 +1,27 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + public abstract class ExceptionHandling { + + public static Exception tryCatch(Runnable runnable) { + try { + runnable.run(); + return null; + } catch (Exception exception) { + return exception; + } + } + } + +} diff --git a/src/dotnet-library/scala/runtime/FloatRef.cs b/src/dotnet-library/scala/runtime/FloatRef.cs new file mode 100644 index 0000000000..ee81ea3c9c --- /dev/null +++ b/src/dotnet-library/scala/runtime/FloatRef.cs @@ -0,0 +1,22 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + [Serializable] + public class FloatRef { + public float elem; + public FloatRef(float elem) { this.elem = elem; } + override public string ToString() { return elem.ToString(); } + } + +} diff --git a/src/dotnet-library/scala/runtime/IntRef.cs b/src/dotnet-library/scala/runtime/IntRef.cs new file mode 100644 index 0000000000..e305df145f --- /dev/null +++ b/src/dotnet-library/scala/runtime/IntRef.cs @@ -0,0 +1,22 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + [Serializable] + public class IntRef { + public int elem; + public IntRef(int elem) { this.elem = elem; } + override public string ToString() { return elem.ToString(); } + } + +} diff --git a/src/dotnet-library/scala/runtime/LongRef.cs b/src/dotnet-library/scala/runtime/LongRef.cs new file mode 100644 index 0000000000..e6387ed96f --- /dev/null +++ b/src/dotnet-library/scala/runtime/LongRef.cs @@ -0,0 +1,22 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + [Serializable] + public class LongRef { + public long elem; + public LongRef(long elem) { this.elem = elem; } + override public string ToString() { return elem.ToString(); } + } + +} diff --git a/src/dotnet-library/scala/runtime/ObjectRef.cs b/src/dotnet-library/scala/runtime/ObjectRef.cs new file mode 100644 index 0000000000..a25d61639e --- /dev/null +++ b/src/dotnet-library/scala/runtime/ObjectRef.cs @@ -0,0 +1,22 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + [Serializable] + public class ObjectRef { + public Object elem; + public ObjectRef(Object elem) { this.elem = elem; } + override public string ToString() { return "" + elem; } + } + +} diff --git a/src/dotnet-library/scala/runtime/RichChar.scala b/src/dotnet-library/scala/runtime/RichChar.scala new file mode 100644 index 0000000000..285530e5be --- /dev/null +++ b/src/dotnet-library/scala/runtime/RichChar.scala @@ -0,0 +1,70 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +import Predef.NoSuchElementException + +/**

+ * For example, in the following code + *

+ *
+ *    object test extends Application {
+ *      Console.println('\40'.isWhitespace)
+ *      Console.println('\011'.isWhitespace)
+ *      Console.println('1'.asDigit == 1)
+ *      Console.println('A'.asDigit == 10)
+ *    }
+ *

+ * the implicit conversions are performed using the predefined view + * Predef.charWrapper. + *

+ */ +final class RichChar(x: Char) extends Proxy with Ordered[Char] { + + // Proxy.self + def self: Any = x + + // Ordered[Char].compare + def compare (y: Char): Int = if (x < y) -1 else if (x > y) 1 else 0 + + def asDigit: Int = System.Char.GetNumericValue(x).toInt + + def isControl: Boolean = System.Char.IsControl(x) + def isDigit: Boolean = System.Char.IsDigit(x) + def isLetter: Boolean = System.Char.IsLetter(x) + def isLetterOrDigit: Boolean = System.Char.IsLetterOrDigit(x) + def isLowerCase: Boolean = System.Char.IsLower(x) + def isUpperCase: Boolean = System.Char.IsUpper(x) + def isWhitespace: Boolean = System.Char.IsWhiteSpace(x) + + def toLowerCase: Char = System.Char.ToLower(x) + def toUpperCase: Char = System.Char.ToUpper(x) + + /** Create an Iterator[Char] over the characters from 'x' to 'y' - 1 + */ + def until(limit: Char): Iterator[Char] = new Iterator[Char] { + private var ch = x + def hasNext: Boolean = ch < limit + def next: Char = + if (hasNext) { val j = ch; ch = (ch + 1).toChar; j } + else throw new NoSuchElementException("next on empty iterator") + } + + //def until(y: Char): Iterator[Char] = to(y) + + /** Create an Iterator[Char] over the characters from 'x' to 'y' + */ + def to(y: Char): Iterator[Char] = until((y + 1).toChar) + +} diff --git a/src/dotnet-library/scala/runtime/RichClass.scala b/src/dotnet-library/scala/runtime/RichClass.scala new file mode 100644 index 0000000000..e964a66ab1 --- /dev/null +++ b/src/dotnet-library/scala/runtime/RichClass.scala @@ -0,0 +1,25 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + +import Predef.Class + +final class RichClass(val self: Class[_]) extends Proxy { + + def isPrimitive(): Boolean = self.IsPrimitive + def isArray(): Boolean = self.IsArray + + def getClass(): RichClass = this + def getName(): String = self.Name + def getComponentType(): Class[_] = self.GetElementType + +} diff --git a/src/dotnet-library/scala/runtime/RichDouble.scala b/src/dotnet-library/scala/runtime/RichDouble.scala new file mode 100644 index 0000000000..6f22e8c836 --- /dev/null +++ b/src/dotnet-library/scala/runtime/RichDouble.scala @@ -0,0 +1,52 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +final class RichDouble(x: Double) extends Proxy with Ordered[Double] { + + // Proxy.self + def self: Any = x + + // Ordered[Double].compare + def compare(y: Double): Int = if (x < y) -1 else if (x > y) 1 else 0 + + def min(y: Double): Double = Math.min(x, y) + def max(y: Double): Double = Math.max(x, y) + def abs: Double = Math.abs(x) + + def round: Long = Math.round(x) + def ceil: Double = Math.ceil(x) + def floor: Double = Math.floor(x) + + /** Converts an angle measured in degrees to an approximately equivalent + * angle measured in radians. + * + * @param x an angle, in degrees + * @return the measurement of the angle x in radians. + */ + def toRadians: Double = Math.toRadians(x) + + /** Converts an angle measured in radians to an approximately equivalent + * angle measured in degrees. + * + * @param x angle, in radians + * @return the measurement of the angle x in degrees. + */ + def toDegrees: Double = Math.toDegrees(x) + + def isNaN: Boolean = System.Double.IsNaN(x) + def isInfinity: Boolean = System.Double.IsInfinity(x) + def isPosInfinity: Boolean = System.Double.IsPositiveInfinity(x) + def isNegInfinity: Boolean = System.Double.IsNegativeInfinity(x) + +} diff --git a/src/dotnet-library/scala/runtime/RichException.scala b/src/dotnet-library/scala/runtime/RichException.scala new file mode 100644 index 0000000000..d08e2e0edf --- /dev/null +++ b/src/dotnet-library/scala/runtime/RichException.scala @@ -0,0 +1,21 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +final class RichException(exc: System.Exception) { + + def printStackTrace() = System.Console.WriteLine(exc.StackTrace) + def getMessage() = exc.Message + def getStackTraceString: String = exc.StackTrace + +} diff --git a/src/dotnet-library/scala/runtime/RichFloat.scala b/src/dotnet-library/scala/runtime/RichFloat.scala new file mode 100644 index 0000000000..5f8849c1a3 --- /dev/null +++ b/src/dotnet-library/scala/runtime/RichFloat.scala @@ -0,0 +1,54 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +import Predef._ + +final class RichFloat(x: Float) extends Proxy with Ordered[Float] { + + // Proxy.self + def self: Any = x + + // Ordered[Float].compare + def compare (y: Float): Int = if (x < y) -1 else if (x > y) 1 else 0 + + def min(y: Float) = Math.min(x, y) + def max(y: Float) = Math.max(x, y) + def abs: Float = Math.abs(x) + + def round: Int = Math.round(x) + def ceil: Float = Math.ceil(x).toFloat + def floor: Float = Math.floor(x).toFloat + + /** Converts an angle measured in degrees to an approximately equivalent + * angle measured in radians. + * + * @param x an angle, in degrees + * @return the measurement of the angle x in radians. + */ + def toRadians: Float = Math.toRadians(x).toFloat + + /** Converts an angle measured in radians to an approximately equivalent + * angle measured in degrees. + * + * @param x angle, in radians + * @return the measurement of the angle x in degrees. + */ + def toDegrees: Float = Math.toDegrees(x).toFloat + + def isNaN: Boolean = System.Single.IsNaN(x) + def isInfinity: Boolean = System.Single.IsInfinity(x) + def isPosInfinity: Boolean = System.Single.IsPositiveInfinity(x) + def isNegInfinity: Boolean = System.Single.IsNegativeInfinity(x) + +} diff --git a/src/dotnet-library/scala/runtime/RichInt.scala b/src/dotnet-library/scala/runtime/RichInt.scala new file mode 100644 index 0000000000..fc5080f9b3 --- /dev/null +++ b/src/dotnet-library/scala/runtime/RichInt.scala @@ -0,0 +1,39 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +final class RichInt(start: Int) extends Proxy with Ordered[Int] { + + // Proxy + def self: Any = start + + // Ordered[Int] + def compare(that: Int): Int = if (start < that) -1 else if (start > that) 1 else 0 + + /** See Iterator.range. */ + def until(end: Int): Range = new Range(start, end, 1) + + /** See Iterator.range. */ + def until(end: Int, step: Int): Range = new Range(start, end, step) + + /** like until, but includes the last index */ + def to(end: Int) = new Range.Inclusive(start, end, 1) + + def min(that: Int): Int = if (start < that) start else that + def max(that: Int): Int = if (start > that) start else that + def abs: Int = if (start < 0) -start else start + + def toBinaryString: String = System.Convert.ToString(start, 2) + def toHexString: String = System.Convert.ToString(start, 16) + def toOctalString: String = System.Convert.ToString(start, 8) +} diff --git a/src/dotnet-library/scala/runtime/RichLong.scala b/src/dotnet-library/scala/runtime/RichLong.scala new file mode 100644 index 0000000000..743b24a79f --- /dev/null +++ b/src/dotnet-library/scala/runtime/RichLong.scala @@ -0,0 +1,30 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +final class RichLong(x: Long) extends Proxy with Ordered[Long] { + + // Proxy.self + def self: Any = x + + // Ordered[Long].compare + def compare(y: Long): Int = if (x < y) -1 else if (x > y) 1 else 0 + + def min(y: Long): Long = if (x < y) x else y + def max(y: Long): Long = if (x > y) x else y + def abs: Long = if (x < 0) -x else x + + def toBinaryString: String = System.Convert.ToString(x, 2) + def toHexString: String = System.Convert.ToString(x, 16) + def toOctalString: String = System.Convert.ToString(x, 8) +} diff --git a/src/dotnet-library/scala/runtime/RichString.scala b/src/dotnet-library/scala/runtime/RichString.scala new file mode 100644 index 0000000000..d94f7430c0 --- /dev/null +++ b/src/dotnet-library/scala/runtime/RichString.scala @@ -0,0 +1,196 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.runtime + + +import Predef._ + +final class RichString(val self: String) extends Proxy with RandomAccessSeq[Char] with Ordered[String] { + override def apply(n: Int) = self charAt n + override def length = self.length + override def toString = self + override def mkString = self + + override def slice(from: Int, until: Int): RichString = { + val len = self.length + new RichString( + if (from >= until || from >= len) + "" + else { + val from0 = if (from < 0) 0 else from + val until0 = if (until > len) len else until + self.substring(from0, until0) + } + ) + } + + //override def ++ [B >: A](that: Iterable[B]): Seq[B] = { + override def ++[B >: Char](that: Iterable[B]): RandomAccessSeq[B] = that match { + case that: RichString => new RichString(self + that.self) + case that => super.++(that) + } + + override def take(until: Int): RichString = slice(0, until) + + override def drop(from: Int): RichString = slice(from, self.length) + + override def startsWith[B](that: Seq[B]) = that match { + case that: RichString => self startsWith that.self + case that => super.startsWith(that) + } + + override def endsWith[B](that: Seq[B]) = that match { + case that: RichString => self endsWith that.self + case that => super.endsWith(that) + } + + override def indexOf[B](that: Seq[B]) = that match { + case that: RichString => self indexOf that.self + case that => super.indexOf(that) + } + + override def containsSlice[B](that: Seq[B]) = that match { + case that: RichString => self contains that.self + case that => super.containsSlice(that) + } + + override def reverse: RichString = { + val buf = new StringBuilder + var i = self.length - 1 + while (i >= 0) { + buf append (self charAt i) + i -= 1 + } + new RichString(buf.toString) + } + + override def compare(other: String) = self compareTo other + + private final val LF: Char = 0x0A + private final val FF: Char = 0x0C + private final val CR: Char = 0x0D + private final val SU: Char = 0x1A + + private def isLineBreak(c: Char) = c == LF || c == FF + + /**

+ * Strip trailing line end character from this string if it has one. + * A line end character is one of + *

+ * + *

+ * If a line feed character LF is preceded by a carriage return CR + * (0x0D hex), the CR character is also stripped (Windows convention). + *

+ */ + def stripLineEnd: String = { + val len = self.length + if (len == 0) self + else { + val last = apply(len - 1) + if (isLineBreak(last)) + self.substring(0, if (last == LF && len >= 2 && apply(len - 2) == CR) len - 2 else len - 1) + else + self + } + } + + /**

+ * Return all lines in this string in an iterator, including trailing + * line end characters. + *

+ *

+ * The number of strings returned is one greater than the number of line + * end characters in this string. For an empty string, a single empty + * line is returned. A line end character is one of + *

+ * + */ + def linesWithSeparators = new Iterator[String] { + val len = self.length + var index = 0 + def hasNext: Boolean = index < len + def next(): String = { + if (index >= len) throw new NoSuchElementException("next on empty iterator") + val start = index + while (index < len && !isLineBreak(apply(index))) index += 1 + index += 1 + self.substring(start, index min len) + } + } + + /** Return all lines in this string in an iterator, excluding trailing line + * end characters, i.e. apply .stripLineEnd to all lines + * returned by linesWithSeparators. + */ + def lines: Iterator[String] = + linesWithSeparators map (line => new RichString(line).stripLineEnd) + + /** Returns this string with first character converted to upper case */ + def capitalize: String = + if (self == null) null + else if (self.length == 0) "" + else { + val chars = self.toCharArray + chars(0) = chars(0).toUpperCase + new String(chars) + } + + /**

+ * For every line in this string: + *

+ *
+ * Strip a leading prefix consisting of blanks or control characters + * followed by marginChar from the line. + *
+ */ + def stripMargin(marginChar: Char): String = { + val buf = new StringBuilder + for (line <- linesWithSeparators) { + val len = line.length + var index = 0 + while (index < len && line.charAt(index) <= ' ') index += 1 + buf append + (if (index < len && line.charAt(index) == marginChar) line.substring(index + 1) else line) + } + buf.toString + } + + /**

+ * For every line in this string: + *

+ *
+ * Strip a leading prefix consisting of blanks or control characters + * followed by | from the line. + *
+ */ + def stripMargin: String = stripMargin('|') + + def split(separator: Char): Array[String] = self.Split(Array(separator)) + + def split(separators: Array[Char]): Array[String] = self.Split(separators) + + def toBoolean: Boolean = System.Boolean.Parse(self) + def toByte: Byte = System.Byte.Parse(self) + def toShort: Short = System.Int16.Parse(self) + def toInt: Int = System.Int32.Parse(self) + def toLong: Long = System.Int64.Parse(self) + def toFloat: Float = System.Single.Parse(self) + def toDouble: Double = System.Double.Parse(self) + +} diff --git a/src/dotnet-library/scala/runtime/Runnable.cs b/src/dotnet-library/scala/runtime/Runnable.cs new file mode 100644 index 0000000000..74ab3ea16a --- /dev/null +++ b/src/dotnet-library/scala/runtime/Runnable.cs @@ -0,0 +1,17 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + public interface Runnable { + void run(); + } + +} diff --git a/src/dotnet-library/scala/runtime/ShortRef.cs b/src/dotnet-library/scala/runtime/ShortRef.cs new file mode 100644 index 0000000000..22f8f784e5 --- /dev/null +++ b/src/dotnet-library/scala/runtime/ShortRef.cs @@ -0,0 +1,22 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + [Serializable] + public class ShortRef { + public short elem; + public ShortRef(short elem) { this.elem = elem; } + override public string ToString() { return elem.ToString(); } + } + +} diff --git a/src/dotnet-library/scala/runtime/StringAdd.scala b/src/dotnet-library/scala/runtime/StringAdd.scala new file mode 100644 index 0000000000..439b2f7f65 --- /dev/null +++ b/src/dotnet-library/scala/runtime/StringAdd.scala @@ -0,0 +1,28 @@ +/* *\ +** ________ ___ __ ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ |_| ** +** ** +\* */ + +// $Id$ + + +package scala.runtime + + +import Predef._ + +final class StringAdd(self: Any) { + + def +(other: String) = self.toString + other + + /** Formats string according to given format string. + * Format strings are as for String.format (@see + * http://msdn2.microsoft.com/en-us/library/system.string.format(VS.71).aspx + * and http://www.codeproject.com/books/0735616485.asp). + */ + def formatted(format: String): String = + String.Format(format, Array(self.asInstanceOf[Object])) +} diff --git a/src/dotnet-library/scala/runtime/SymtabAttribute.cs b/src/dotnet-library/scala/runtime/SymtabAttribute.cs new file mode 100644 index 0000000000..b5608fe208 --- /dev/null +++ b/src/dotnet-library/scala/runtime/SymtabAttribute.cs @@ -0,0 +1,22 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +namespace scala.runtime { + + using System; + + public class SymtabAttribute : Attribute { + public byte[] symtab; + + public SymtabAttribute(byte[] symtab) { this.symtab = symtab; } + public SymtabAttribute() {} + } + +} diff --git a/src/dotnet-library/scala/util/DynamicVariable.scala b/src/dotnet-library/scala/util/DynamicVariable.scala new file mode 100644 index 0000000000..101ebe9573 --- /dev/null +++ b/src/dotnet-library/scala/util/DynamicVariable.scala @@ -0,0 +1,83 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.util + + +import Predef._ +import System.Threading.Thread +import System.LocalDataStoreSlot + +/**

+ * DynamicVariables provide a binding mechanism where the current + * value is found through dynamic scope, but where + * access to the variable itself is resolved through static + * scope. + *

+ *

+ * The current value can be retrieved with the + * value method. New values should be + * pushed using the withValue method. + * Values pushed via withValue only + * stay valid while the withValue's + * second argument, a parameterless closure, + * executes. When the second argument finishes, + * the variable reverts to the previous value. + *

+ *

+ * Usage of withValue looks like this: + *

+ *
+ *  someDynamicVariable.withValue(newValue) {
+ *    // ... code called in here that calls value ...
+ *    // ... will be given back the newValue ...
+ *  }
+ *  
+ *

+ * Each thread gets its own stack of bindings. When a + * new thread is created, the fluid gets a copy of + * the stack of bindings from the parent thread, and + * from then on the bindings for the new thread + * are independent of those for the original thread. + *

+ * + * @author Lex Spoon + * @version 1.1, 2007-5-21 + */ +class DynamicVariable[T](init: T) { + private val slot: LocalDataStoreSlot = Thread.AllocateDataSlot() + value = init + + /** Retrieve the current value */ + def value: T = Thread.GetData(slot).asInstanceOf[T] + + /** Set the value of the fluid while executing the specified + * thunk. + * + * @param newval The value to which to set the fluid + * @param thunk The code to evaluate under the new setting + */ + def withValue[S](newval: T)(thunk: =>S): S = { + val oldval = value + value = newval + + try { thunk } finally { + value = oldval + } + } + + /** Change the currently bound value, discarding the old value. + * Usually withValue() gives better semantics. + */ + def value_=(newval: T) = { Thread.SetData(slot, newval.asInstanceOf[AnyRef]) } + + override def toString: String = "DynamicVariable(" + value +")" +} diff --git a/src/library/dotnet/scala/Application.scala b/src/library/dotnet/scala/Application.scala deleted file mode 100644 index 4a47186a15..0000000000 --- a/src/library/dotnet/scala/Application.scala +++ /dev/null @@ -1,61 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -//import java.lang.System.getProperty -//import scala.compat.Platform.currentTime - -/**

- * The Application class can be used to quickly turn objects - * into executable programs. Here is an example: - *

- *  object Main with Application {
- *    Console.println("Hello World!");
- *  }
- *  
- *

- * Here, object Main inherits the main method - * of Application. The body of the Main object - * defines the main program. This technique does not work if the main - * program depends on command-line arguments (which are not accessible - * with the technique presented here). - *

- *

- * It is possible to time the execution of objects that inherit from class - * Application by setting the global scala.time - * property. Here is an example for benchmarking object Main: - *

- *  java -Dscala.time Main
- *  
- * - * @author Matthias Zenger - * @version 1.0, 10/09/2003 - */ - -trait Application { - - /** The time when execution of this program started. - */ -// val executionStart: Long = currentTime - - /** The default main method. - * - * @param args the arguments passed to the main method - */ - def main(args: Array[String]) = { -// if (getProperty("scala.time") ne null) { -// val total = currentTime - executionStart -// Console.println("[total " + total + "ms]") -// } - } - -} diff --git a/src/library/dotnet/scala/Console.scala b/src/library/dotnet/scala/Console.scala deleted file mode 100644 index 7a9c20c034..0000000000 --- a/src/library/dotnet/scala/Console.scala +++ /dev/null @@ -1,298 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - - -import System.IO.{TextReader,TextWriter} - -import scala.util.DynamicVariable -import Predef._ - - -/** The Console object implements functionality for - * printing Scala values on the terminal. There are also functions - * for reading specific values. Console also defines - * constants for marking up text on ANSI terminals. - * - * @author Matthias Zenger - * @version 1.0, 03/09/2003 - */ -object Console { - - // ANSI colors foreground - final val BLACK = "\033[30m" - final val RED = "\033[31m" - final val GREEN = "\033[32m" - final val YELLOW = "\033[33m" - final val BLUE = "\033[34m" - final val MAGENTA = "\033[35m" - final val CYAN = "\033[36m" - final val WHITE = "\033[37m" - - // ANSI colors background - final val BLACK_B = "\033[40m" - final val RED_B = "\033[41m" - final val GREEN_B = "\033[42m" - final val YELLOW_B = "\033[43m" - final val BLUE_B = "\033[44m" - final val MAGENTA_B = "\033[45m" - final val CYAN_B = "\033[46m" - final val WHITE_B = "\033[47m" - - // ANSI styles - final val RESET = "\033[0m" - final val BOLD = "\033[1m" - final val UNDERLINED = "\033[4m" - final val BLINK = "\033[5m" - final val REVERSED = "\033[7m" - final val INVISIBLE = "\033[8m" - - private val outVar = new DynamicVariable[TextWriter](System.Console.Out) - private val inVar = new DynamicVariable[TextReader](System.Console.In) - - def out = outVar.value - def in = inVar.value - - /** Set the default output stream. - * - * @param out the new output stream. - */ - def setOut(out: TextWriter) { outVar.value = out } - - /** Set the default output stream for the duration - * of execution of one thunk. - * - * @param out the new output stream. - * @param thunk the code to execute with - * the new output stream active - */ - def withOut[T](out: TextWriter)(thunk: =>T): T = - outVar.withValue(out)(thunk) - - - /** Set the default input stream. - * - * @param reader specifies the new input stream. - */ - def setIn(reader: TextReader): Unit = { - inVar.value = reader - } - - /** Set the default input stream for the duration - * of execution of one thunk. - * - * @param in the new input stream. - * @param thunk the code to execute with - * the new input stream active - */ - def withIn[T](reader: TextReader)(thunk: =>T): T = - inVar.withValue(reader)(thunk) - - /** Print an object on the terminal. - * - * @param obj the object to print. - */ - def print(obj: Any): Unit = { - out.Write(if (null == obj) "null" else obj.toString()); - } - - /** Flush the output stream. This function is required when partial - * output (i.e. output not terminated by a new line character) has - * to be made visible on the terminal. - */ - def flush() { out.Flush() } - - /** Print a new line character on the terminal. - */ - def println(): Unit = out.WriteLine() - - /** Print out an object followed by a new line character. - * - * @param x the object to print. - */ - def println(x: Any): Unit = out.WriteLine(x) - - /**

- * Format and print out some text (in a fashion similar to printf in C or - * printf in Java 6). - *

- *

- * The format of the text to print is specified by the parameter - * text. The arguments that are inserted into specific - * locations in text are provided with parameter - * args. See class java.text.MessageFormat - * for a full specification of the format syntax. - *

- * - * @param text the format of the text to print out. - * @param args the parameters used to instantiate the format. - * @throws java.lang.IllegalArgumentException - */ - def printf(text: String, args: Any*) { format(text, args: _*) } - - /** - * @see Console.printf. - */ - def format(text: String, args: Any*): Unit = - if (text eq null) out.Write("null") - else out.Write(text, args.toArray) - - /** Read a full line from the terminal. - * - * @return the string read from the terminal. - */ - def readLine(): String = in.ReadLine(); - - /** Print a formatted text and read a full line from the terminal - * - * @param text the format of the text to print out. - * @param args the parameters used to instantiate the format. - * @return the string read from the terminal. - */ - def readLine(text: String, args: Any*): String = { - format(text, args: _*) - readLine() - } - - - /** Read a boolean value from the terminal. - * - * @return the boolean value read from the terminal. - */ - def readBoolean(): Boolean = readLine().toLowerCase() match { - case "true" => true - case "t" => true - case "yes" => true - case "y" => true - case _ => false - } - - /** Read a byte value from the terminal. - */ - def readByte(): Byte = readLine().toByte - - /** Read a short value from the terminal. - */ - def readShort(): Short = readLine.toShort - - /** Read a char value from the terminal. - */ - def readChar(): Char = readLine() charAt 0 - - /** Read an int value from the terminal. - */ - def readInt(): Int = readLine().toInt - - /** Read an int value from the terminal. - */ - def readLong(): Long = readLine().toLong - - /** Read a float value from the terminal. - */ - def readFloat(): Float = readLine().toFloat - - /** Read a double value from the terminal. - */ - def readDouble(): Double = readLine().toDouble - -// /** Read in some structured input, specified by a format specifier. -// * See class java.text.MessageFormat for details of -// * the format specification. -// * -// * @param format the format of the input. -// * @return a list of all extracted values. -// */ -// def readf(format: String): List[Any] = -// textComponents(new MessageFormat(format).parse(readLine())) - -// /** Read in some structured input, specified by a format specifier. -// * Opposed to readf, this function only returns the -// * first value extracted from the input according to the format -// * specification. -// * -// * @param format ... -// * @return ... -// */ -// def readf1(format: String): Any = readf(format).head - -// /** Read in some structured input, specified by a format specifier. -// * Opposed to readf, this function only returns the -// * first two values extracted from the input according to the format -// * specification. -// * -// * @param format ... -// * @return ... -// */ -// def readf2(format: String): (Any, Any) = { -// val res = readf(format) -// (res.head, res.tail.head) -// } - -// /** Read in some structured input, specified by a format specifier. -// * Opposed to readf, this function only returns the -// * first three values extracted from the input according to the format -// * specification. -// * -// * @param format ... -// * @return ... -// */ -// def readf3(format: String): (Any, Any, Any) = { -// val res = readf(format) -// (res.head, res.tail.head, res.tail.tail.head) -// } - -// private def textComponents(a: Array[AnyRef]): List[Any] = { -// var i: Int = a.length - 1 -// var res: List[Any] = Nil -// while (i >= 0) { -// res = (a(i) match { -// case x: java.lang.Boolean => x.booleanValue() -// case x: java.lang.Byte => x.byteValue() -// case x: java.lang.Short => x.shortValue() -// case x: java.lang.Character => x.charValue() -// case x: java.lang.Integer => x.intValue() -// case x: java.lang.Long => x.longValue() -// case x: java.lang.Float => x.floatValue() -// case x: java.lang.Double => x.doubleValue() -// case x => x -// }) :: res; -// i = i - 1 -// } -// res -// } - -// private def textParams(s: Seq[Any]): Array[AnyRef] = { -// val res = new Array[AnyRef](s.length); -// var i: Int = 0; -// val iter = s.elements; -// while (iter.hasNext) { -// res(i) = iter.next match { -// case x: Boolean => new java.lang.Boolean(x) -// case x: Byte => new java.lang.Byte(x) -// case x: Short => new java.lang.Short(x) -// case x: Char => new java.lang.Character(x) -// case x: Int => new java.lang.Integer(x) -// case x: Long => new java.lang.Long(x) -// case x: Float => new java.lang.Float(x) -// case x: Double => new java.lang.Double(x) -// case x: Unit => "()" -// case x: AnyRef => x -// } -// i = i + 1 -// } -// res -// } - -} diff --git a/src/library/dotnet/scala/List.scala b/src/library/dotnet/scala/List.scala deleted file mode 100644 index a592060f9a..0000000000 --- a/src/library/dotnet/scala/List.scala +++ /dev/null @@ -1,1305 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import scala.collection.mutable.ListBuffer -import Predef._ - -/** This object provides methods for creating specialized lists, and for - * transforming special kinds of lists (e.g. lists of lists). - * - * @author Martin Odersky and others - * @version 1.0, 15/07/2003 - */ -object List { - - /** Create a list with given elements. - * - * @param xs the elements to put in the list - * @return the list containing elements xs. - */ - def apply[A](xs: A*): List[A] = xs.toList - - /** for unapply matching - */ - def unapplySeq[A](x: List[A]): Some[List[A]] = Some(x) - - /** Create a sorted list of all integers in a range. - * - * @param from the start value of the list - * @param end the end value of the list - * @return the sorted list of all integers in range [from;end). - */ - def range(start: Int, end: Int): List[Int] = - range(start, end, 1) - - /** Create a list with element values - * vn+1 = vn + step - * where v0 = start - * and elements are in the range between start (inclusive) - * and end (exclusive) - * - * @param start the start value of the list - * @param end the end value of the list - * @param step the increment value of the list - * @return the sorted list of all integers in range [start;end). - */ - def range(start: Int, end: Int, step: Int): List[Int] = { - val b = new ListBuffer[Int] - var i = start - while ((step <= 0 || i < end) && (step >= 0 || i > end)) { - b += i - i += step - } - b.toList - } - - /** Create a sorted list with element values - * vn+1 = step(vn) - * where v0 = start - * and elements are in the range between start (inclusive) - * and end (exclusive) - * - * @param start the start value of the list - * @param end the end value of the list - * @param step the increment function of the list, must be monotonically increasing or decreasing - * @return the sorted list of all integers in range [start;end). - */ - def range(start: Int, end: Int, step: Int => Int): List[Int] = { - val up = step(start) > start - val down = step(start) < start - val b = new ListBuffer[Int] - var i = start - while ((!up || i < end) && (!down || i > end)) { - b += i - i += step(i) - } - b.toList - } - - /** Create a list containing several copies of an element. - * - * @param n the length of the resulting list - * @param elem the element composing the resulting list - * @return a list composed of n elements all equal to elem - */ - def make[A](n: Int, elem: A): List[A] = { - val b = new ListBuffer[A] - var i = 0 - while (i < n) { - b += elem - i += 1 - } - b.toList - } - - /** Create a list by applying a function to successive integers. - * - * @param n the length of the resulting list - * @param maker the procedure which, given an integer n, - * returns the nth element of the resulting list, where - * n is in interval [0;n). - * @return the list obtained by applying the maker function to - * successive integers from 0 to n (exclusive). - */ - def tabulate[A](n: Int, maker: Int => A): List[A] = { - val b = new ListBuffer[A] - var i = 0 - while (i < n) { - b += maker(i) - i += 1 - } - b.toList - } - - /** Concatenate all the elements of a given list of lists. - * - * @param xss the list of lists that are to be concatenated - * @return the concatenation of all the lists - */ - def flatten[A](xss: List[List[A]]): List[A] = concat(xss: _*) - - /** Concatenate all the argument lists into a single list. - * - * @param xss the lists that are to be concatenated - * @return the concatenation of all the lists - */ - def concat[A](xss: List[A]*): List[A] = { - val b = new ListBuffer[A] - for (xs <- xss) { - var xc = xs - while (!xc.isEmpty) { - b += xc.head - xc = xc.tail - } - } - b.toList - } - - /** Transforms a list of pair into a pair of lists. - * - * @param xs the list of pairs to unzip - * @return a pair of lists: the first list in the pair contains the list - */ - def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = { - val b1 = new ListBuffer[A] - val b2 = new ListBuffer[B] - var xc = xs - while (!xc.isEmpty) { - b1 += xc.head._1 - b2 += xc.head._2 - xc = xc.tail - } - (b1.toList, b2.toList) - } - - /** Converts an iterator to a list. - * - * @param it the iterator to convert - * @return a list that contains the elements returned by successive - * calls to it.next - */ - def fromIterator[A](it: Iterator[A]): List[A] = it.toList - - /** Converts an array into a list. - * - * @param arr the array to convert - * @return a list that contains the same elements than arr - * in the same order - */ - def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length) - - /** Converts a range of an array into a list. - * - * @param arr the array to convert - * @param start the first index to consider - * @param len the lenght of the range to convert - * @return a list that contains the same elements than arr - * in the same order - */ - def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = { - var res: List[A] = Nil - var i = start + len - while (i > start) { - i -= 1 - res = arr(i) :: res - } - res - } - - /** Parses a string which contains substrings separated by a - * separator character and returns a list of all substrings. - * - * @param str the string to parse - * @param separator the separator character - * @return the list of substrings - */ - def fromString(str: String, separator: Char): List[String] = { - var words: List[String] = Nil - var pos = str.length() - while (pos > 0) { - val pos1 = str.lastIndexOf(separator, pos - 1) - if (pos1 + 1 < pos) - words = str.substring(pos1 + 1, pos) :: words - pos = pos1 - } - words - } - - /** Returns the given string as a list of characters. - * - * @param str the string to convert. - * @return the string as a list of characters. - * @deprecated use str.toList instead - */ - @deprecated def fromString(str: String): List[Char] = - str.toList - - /** Returns the given list of characters as a string. - * - * @param xs the list to convert. - * @return the list in form of a string. - */ - def toString(xs: List[Char]): String = { - val sb = new StringBuilder() - var xc = xs - while (!xc.isEmpty) { - sb.append(xc.head) - xc = xc.tail - } - sb.toString() - } - - /** Like xs map f, but returns xs unchanged if function - * f maps all elements to themselves. - * - * @param xs ... - * @param f ... - * @return ... - */ - def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = { - def loop(ys: List[A]): List[A] = - if (ys.isEmpty) xs - else { - val head0 = ys.head - val head1 = f(head0) - if (head1 eq head0) { - loop(ys.tail) - } else { - val ys1 = head1 :: mapConserve(ys.tail)(f) - if (xs eq ys) ys1 - else { - val b = new ListBuffer[A] - var xc = xs - while (xc ne ys) { - b += xc.head - xc = xc.tail - } - b.prependToList(ys1) - } - } - } - loop(xs) - } - - /** Returns the list resulting from applying the given function f - * to corresponding elements of the argument lists. - * - * @param f function to apply to each pair of elements. - * @return [f(a0,b0), ..., f(an,bn)] if the lists are - * [a0, ..., ak], [b0, ..., bl] and - * n = min(k,l) - */ - def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = { - val b = new ListBuffer[C] - var xc = xs - var yc = ys - while (!xc.isEmpty && !yc.isEmpty) { - b += f(xc.head, yc.head) - xc = xc.tail - yc = yc.tail - } - b.toList - } - - /** Returns the list resulting from applying the given function - * f to corresponding elements of the argument lists. - * - * @param f function to apply to each pair of elements. - * @return [f(a0,b0,c0), - * ..., f(an,bn,cn)] - * if the lists are [a0, ..., ak], - * [b0, ..., bl], - * [c0, ..., cm] and - * n = min(k,l,m) - */ - def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = { - val b = new ListBuffer[D] - var xc = xs - var yc = ys - var zc = zs - while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) { - b += f(xc.head, yc.head, zc.head) - xc = xc.tail - yc = yc.tail - zc = zc.tail - } - b.toList - } - - /** Tests whether the given predicate p holds - * for all corresponding elements of the argument lists. - * - * @param p function to apply to each pair of elements. - * @return (p(a0,b0) && - * ... && p(an,bn))] - * if the lists are [a0, ..., ak]; - * [b0, ..., bl] - * and n = min(k,l) - */ - def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { - var xc = xs - var yc = ys - while (!xc.isEmpty && !yc.isEmpty) { - if (!f(xc.head, yc.head)) return false - xc = xc.tail - yc = yc.tail - } - true - } - - /** Tests whether the given predicate p holds - * for some corresponding elements of the argument lists. - * - * @param p function to apply to each pair of elements. - * @return n != 0 && (p(a0,b0) || - * ... || p(an,bn))] if the lists are - * [a0, ..., ak], - * [b0, ..., bl] and - * n = min(k,l) - */ - def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { - var xc = xs - var yc = ys - while (!xc.isEmpty && !yc.isEmpty) { - if (f(xc.head, yc.head)) return true - xc = xc.tail - yc = yc.tail - } - false - } - - /** Transposes a list of lists. - * pre: All element lists have the same length. - * - * @param xss the list of lists - * @return the transposed list of lists - */ - def transpose[A](xss: List[List[A]]): List[List[A]] = { - val buf = new ListBuffer[List[A]] - var yss = xss - while (!yss.head.isEmpty) { - buf += (yss map (_.head)) - yss = (yss map (_.tail)) - } - buf.toList - } - - /** Lists with ordered elements are ordered - implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] { - def compare [b >: List[a] <% Ordered[b]](y: b): Int = y match { - case y1: List[a] => compareLists(x, y1); - case _ => -(y compare x) - } - private def compareLists(xs: List[a], ys: List[a]): Int = { - if (xs.isEmpty && ys.isEmpty) 0 - else if (xs.isEmpty) -1 - else if (ys.isEmpty) 1 - else { - val s = xs.head compare ys.head; - if (s != 0) s - else compareLists(xs.tail, ys.tail) - } - } - } - */ -} - -/** A class representing an ordered collection of elements of type - * a. This class comes with two implementing case - * classes scala.Nil and scala.:: that - * implement the abstract members isEmpty, - * head and tail. - * - * @author Martin Odersky and others - * @version 1.0, 16/07/2003 - */ -sealed abstract class List[+A] extends Seq[A] { - - /** Returns true if the list does not contain any elements. - * @return true, iff the list is empty. - */ - override def isEmpty: Boolean - - /** Returns this first element of the list. - * - * @return the first element of this list. - * @throws Predef.NoSuchElementException if the list is empty. - */ - def head: A - - /** returns length - l, without calling length - */ - override def lengthCompare(l: Int) = { - if (isEmpty) 0 - l - else if (l <= 0) 1 - else tail.lengthCompare(l - 1) - } - - /** Returns this list without its first element. - * - * @return this list without its first element. - * @throws Predef.NoSuchElementException if the list is empty. - */ - def tail: List[A] - - /**

- * Add an element x at the beginning of this list. - *

- * - * @param x the element to prepend. - * @return the list with x added at the beginning. - * @ex 1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3) - */ - def ::[B >: A] (x: B): List[B] = - new scala.::(x, this) - - /**

- * Add an element x at the end of this list. - *

- * - * @param x the element to append. - * @return the list with x added at the end. - */ - def +[B >: A](x: B): List[B] = - if (isEmpty) List(x) - else { - val buf = new ListBuffer[B] - this copyToBuffer buf - buf += x - buf.toList - } - - /**

- * Returns a list resulting from the concatenation of the given - * list prefix and this list. - *

- * - * @param prefix the list to concatenate at the beginning of this list. - * @return the concatenation of the two lists. - * @ex List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4) - */ - def :::[B >: A](prefix: List[B]): List[B] = - if (isEmpty) prefix - else { - val b = new ListBuffer[B] - var those = prefix - while (!those.isEmpty) { - b += those.head - those = those.tail - } - b.prependToList(this) - } - - /** Appends two list objects. - */ - override def ++[B >: A](that: Iterable[B]): List[B] = { - val buf = new ListBuffer[B] - this copyToBuffer buf - that copyToBuffer buf - buf.toList - } - - /** Reverse the given prefix and append the current list to that. - * This function is equivalent to an application of reverse - * on the prefix followed by a call to :::, but more - * efficient (and tail recursive). - * - * @param prefix the prefix to reverse and then prepend - * @return the concatenation of the reversed prefix and the current list. - */ - def reverse_:::[B >: A](prefix: List[B]): List[B] = { - var these: List[B] = this - var pres = prefix - while (!pres.isEmpty) { - these = pres.head :: these - pres = pres.tail - } - these - } - - /** Returns the number of elements in the list. - * - * @return the number of elements in the list. - */ - def length: Int = { - var these = this - var len = 0 - while (!these.isEmpty) { - len += 1 - these = these.tail - } - len - } - - /** Creates a list with all indices in the list. This is - * equivalent to a call to List.range(0, xs.length). - * - * @return a list of all indices in the list. - */ - def indices: List[Int] = { - val b = new ListBuffer[Int] - var i = 0 - var these = this - while (!these.isEmpty) { - b += i - i += 1 - these = these.tail - } - b.toList - } - - /** Returns the elements in the list as an iterator - * - * @return an iterator on the list elements. - */ - override def elements: Iterator[A] = new Iterator[A] { - var these = List.this - def hasNext: Boolean = !these.isEmpty - def next: A = - if (!hasNext) - throw new NoSuchElementException("next on empty Iterator") - else { - val result = these.head; these = these.tail; result - } - override def toList: List[A] = these - } - - /** Overrides the method in Iterable for efficiency. - * - * @return the list itself - */ - override def toList: List[A] = this - - /** Returns the list without its last element. - * - * @return the list without its last element. - * @throws Predef.UnsupportedOperationException if the list is empty. - */ - def init: List[A] = - if (isEmpty) throw new UnsupportedOperationException("Nil.init") - else { - val b = new ListBuffer[A] - var elem = head - var next = tail - while (!next.isEmpty) { - b += elem - elem = next.head - next = next.tail - } - b.toList - } - - /** Returns the last element of this list. - * - * @return the last element of the list. - * @throws Predef.NoSuchElementException if the list is empty. - */ - override def last: A = - if (isEmpty) throw new Predef.NoSuchElementException("Nil.last") - else { - var cur = this - var next = this.tail - while (!next.isEmpty) { - cur = next - next = next.tail - } - cur.head - } - - /** Returns the n first elements of this list, or else the whole - * list, if it has less than n elements. - * - * @param n the number of elements to take. - * @return the n first elements of this list. - */ - override def take(n: Int): List[A] = { - val b = new ListBuffer[A] - var i = 0 - var these = this - while (!these.isEmpty && i < n) { - i += 1 - b += these.head - these = these.tail - } - if (these.isEmpty) this - else b.toList - } - - /** Returns the list with elements belonging to the given index range. - * - * @param start the start position of the list slice. - * @param end the end position (exclusive) of the list slice. - * @return the list with elements belonging to the given index range. - */ - override def slice(start: Int, end: Int): List[A] = { - val s = start max 0 - val e = end min this.length - drop(s) take (e - s) - } - - /** Returns the list without its n first elements. - * If this list has less than n elements, the empty list is returned. - * - * @param n the number of elements to drop. - * @return the list without its n first elements. - */ - override def drop(n: Int): List[A] = { - var these = this - var count = n - while (!these.isEmpty && count > 0) { - these = these.tail - count -= 1 - } - these - } - - /** Returns the rightmost n elements from this list. - * - * @param n the number of elements to take - * @return the suffix of length n of the list - */ - def takeRight(n: Int): List[A] = { - def loop(lead: List[A], lag: List[A]): List[A] = lead match { - case Nil => lag - case _ :: tail => loop(tail, lag.tail) - } - loop(drop(n), this) - } - - /** Returns the list wihout its rightmost n elements. - * - * @param n the number of elements to take - * @return the suffix of length n of the list - */ - def dropRight(n: Int): List[A] = { - def loop(lead: List[A], lag: List[A]): List[A] = lead match { - case Nil => Nil - case _ :: tail => lag.head :: loop(tail, lag.tail) - } - loop(drop(n), this) - } - - /** Split the list at a given point and return the two parts thus - * created. - * - * @param n the position at which to split - * @return a pair of lists composed of the first n - * elements, and the other elements. - */ - def splitAt(n: Int): (List[A], List[A]) = { - val b = new ListBuffer[A] - var i = 0 - var these = this - while (!these.isEmpty && i < n) { - i += 1 - b += these.head - these = these.tail - } - (b.toList, these) - } - - /** Returns the longest prefix of this list whose elements satisfy - * the predicate p. - * - * @param p the test predicate. - * @return the longest prefix of this list whose elements satisfy - * the predicate p. - */ - override def takeWhile(p: A => Boolean): List[A] = { - val b = new ListBuffer[A] - var these = this - while (!these.isEmpty && p(these.head)) { - b += these.head - these = these.tail - } - b.toList - } - - /** Returns the longest suffix of this list whose first element - * does not satisfy the predicate p. - * - * @param p the test predicate. - * @return the longest suffix of the list whose first element - * does not satisfy the predicate p. - */ - override def dropWhile(p: A => Boolean): List[A] = - if (isEmpty || !p(head)) this - else tail dropWhile p - - /** Returns the longest prefix of the list whose elements all satisfy - * the given predicate, and the rest of the list. - * - * @param p the test predicate - * @return a pair consisting of the longest prefix of the list whose - * elements all satisfy p, and the rest of the list. - */ - def span(p: A => Boolean): (List[A], List[A]) = { - val b = new ListBuffer[A] - var these = this - while (!these.isEmpty && p(these.head)) { - b += these.head - these = these.tail - } - (b.toList, these) - } - - /** Like span but with the predicate inverted. - */ - def break(p: A => Boolean): (List[A], List[A]) = span { x => !p(x) } - - /** Returns the n-th element of this list. The first element - * (head of the list) is at position 0. - * - * @param n index of the element to return - * @return the element at position n in this list. - * @throws Predef.NoSuchElementException if the list is too short. - */ - def apply(n: Int): A = drop(n).head - - /** Returns the list resulting from applying the given function f to each - * element of this list. - * - * @param f function to apply to each element. - * @return [f(a0), ..., f(an)] if this list is [a0, ..., an]. - */ - final override def map[B](f: A => B): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - b += f(these.head) - these = these.tail - } - b.toList - } - - /** Apply a function to all the elements of the list, and return the - * reversed list of results. This is equivalent to a call to map - * followed by a call to reverse, but more efficient. - * - * @param f the function to apply to each elements. - * @return the reversed list of results. - */ - def reverseMap[B](f: A => B): List[B] = { - def loop(l: List[A], res: List[B]): List[B] = l match { - case Nil => res - case head :: tail => loop(tail, f(head) :: res) - } - loop(this, Nil) - } - - /** Apply the given function f to each element of this list - * (while respecting the order of the elements). - * - * @param f the treatment to apply to each element. - */ - final override def foreach(f: A => Unit) { - var these = this - while (!these.isEmpty) { - f(these.head) - these = these.tail - } - } - - /** Returns all the elements of this list that satisfy the - * predicate p. The order of the elements is preserved. - * It is guarenteed that the receiver list itself is returned iff all its - * elements satisfy the predicate `p'. Hence the following equality is valid: - * - * (xs filter p) eq xs == xs forall p - * - * @param p the predicate used to filter the list. - * @return the elements of this list satisfying p. - */ - final override def filter(p: A => Boolean): List[A] = { - // return same list if all elements satisfy p - var these = this - while (!these.isEmpty && p(these.head)) { - these = these.tail - } - if (these.isEmpty) this - else { - val b = new ListBuffer[A] - var these1 = this - while (these1 ne these) { - b += these1.head - these1 = these1.tail - } - - these = these.tail // prevent the second evaluation of the predicate - // on the element on which it first failed - while (!these.isEmpty) { - if (p(these.head)) b += these.head - these = these.tail - } - b.toList - } - } - -// final def filterMap[B](f: PartialFunction[A, B]): List[B] = -// this filter f.isDefinedAt map f - - /** Removes all elements of the list which satisfy the predicate - * p. This is like filter with the - * predicate inversed. - * - * @param p the predicate to use to test elements - * @return the list without all elements which satisfy p - */ - def remove(p: A => Boolean): List[A] = filter (x => !p(x)) - - /** Partition the list in two sub-lists according to a predicate. - * - * @param p the predicate on which to partition - * @return a pair of lists: the list of all elements which satisfy - * p and the list of all elements which do not. - * The relative order of the elements in the sub-lists is the - * same as in the original list. - */ - override def partition(p: A => Boolean): (List[A], List[A]) = { - val btrue = new ListBuffer[A] - val bfalse = new ListBuffer[A] - var these = this - while (!these.isEmpty) { - (if (p(these.head)) btrue else bfalse) += these.head - these = these.tail - } - (btrue.toList, bfalse.toList) - } - - /**

- * Sort the list according to the comparison function - * <(e1: a, e2: a) => Boolean, - * which should be true iff e1 is smaller than - * e2. - *

- * - * @param lt the comparison function - * @return a list sorted according to the comparison function - * <(e1: a, e2: a) => Boolean. - * @ex
-   *    List("Steve", "Tom", "John", "Bob")
-   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
-   *    List("Bob", "John", "Steve", "Tom")
- */ - def sort(lt : (A,A) => Boolean): List[A] = { - /** Merge two already-sorted lists */ - def merge(l1: List[A], l2: List[A]): List[A] = { - val res = new ListBuffer[A] - var left1 = l1 - var left2 = l2 - - while (!left1.isEmpty && !left2.isEmpty) { - if(lt(left1.head, left2.head)) { - res += left1.head - left1 = left1.tail - } else { - res += left2.head - left2 = left2.tail - } - } - - res ++= left1 - res ++= left2 - - res.toList - } - - /** Split a list into two lists of about the same size */ - def split(lst: List[A]) = { - val res1 = new ListBuffer[A] - val res2 = new ListBuffer[A] - var left = lst - - while (!left.isEmpty) { - res1 += left.head - left = left.tail - if (!left.isEmpty) { - res2 += left.head - left = left.tail - } - } - - (res1.toList, res2.toList) - } - - - /** Merge-sort the specified list */ - def ms(lst: List[A]): List[A] = - lst match { - case Nil => lst - case x :: Nil => lst - case x :: y :: Nil => - if (lt(x,y)) - lst - else - y :: x :: Nil - - case lst => - val (l1, l2) = split(lst) - val l1s = ms(l1) - val l2s = ms(l2) - merge(l1s, l2s) - } - - ms(this) - } - - - /** Count the number of elements in the list which satisfy a predicate. - * - * @param p the predicate for which to count - * @return the number of elements satisfying the predicate p. - */ - def count(p: A => Boolean): Int = { - var cnt = 0 - var these = this - while (!these.isEmpty) { - if (p(these.head)) cnt += 1 - these = these.tail - } - cnt - } - - /** Tests if the predicate p is satisfied by all elements - * in this list. - * - * @param p the test predicate. - * @return true iff all elements of this list satisfy the - * predicate p. - */ - override def forall(p: A => Boolean): Boolean = { - var these = this - while (!these.isEmpty) { - if (!p(these.head)) return false - these = these.tail - } - true - } - - /** Tests the existence in this list of an element that satisfies the - * predicate p. - * - * @param p the test predicate. - * @return true iff there exists an element in this list that - * satisfies the predicate p. - */ - override def exists(p: A => Boolean): Boolean = { - var these = this - while (!these.isEmpty) { - if (p(these.head)) return true - these = these.tail - } - false - } - - /** Find and return the first element of the list satisfying a - * predicate, if any. - * - * @param p the predicate - * @return the first element in the list satisfying p, - * or None if none exists. - */ - override def find(p: A => Boolean): Option[A] = { - var these = this - while (!these.isEmpty) { - if (p(these.head)) return Some(these.head) - these = these.tail - } - None - } - - /** Combines the elements of this list together using the binary - * function f, from left to right, and starting with - * the value z. - * - * @return f(... (f(f(z, a0), a1) ...), - * an) if the list is - * [a0, a1, ..., an]. - */ - override def foldLeft[B](z: B)(f: (B, A) => B): B = { - var acc = z - var these = this - while (!these.isEmpty) { - acc = f(acc, these.head) - these = these.tail - } - acc - } - - /** Combines the elements of this list together using the binary - * function f, from right to left, and starting with - * the value z. - * - * @return f(a0, f(a1, f(..., f(an, z)...))) - * if the list is [a0, a1, ..., an]. - */ - override def foldRight[B](z: B)(f: (A, B) => B): B = this match { - case Nil => z - case x :: xs => f(x, xs.foldRight(z)(f)) - } - - /** Combines the elements of this list together using the binary - * operator op, from left to right - * @param op The operator to apply - * @return op(... op(a0,a1), ..., an) - if the list has elements - * a0, a1, ..., an. - * @throws Predef.UnsupportedOperationException if the list is empty. - */ - override def reduceLeft[B >: A](f: (B, B) => B): B = this match { - case Nil => throw new UnsupportedOperationException("Nil.reduceLeft") - case x :: xs => ((xs: List[B]) foldLeft (x: B))(f) - } - - /** Combines the elements of this list together using the binary - * operator op, from right to left - * @param op The operator to apply - * - * @return a0 op (... op (an-1 op an)...) - * if the list has elements a0, a1, ..., - * an. - * - * @throws Predef.UnsupportedOperationException if the list is empty. - */ - override def reduceRight[B >: A](f: (B, B) => B): B = this match { - case Nil => throw new UnsupportedOperationException("Nil.reduceRight") - case x :: Nil => x: B - case x :: xs => f(x, xs reduceRight f) - } - - /** Applies the given function f to each element of - * this list, then concatenates the results. - * - * @param f the function to apply on each element. - * @return f(a0) ::: ... ::: f(an) if - * this list is [a0, ..., an]. - */ - final override def flatMap[B](f: A => Iterable[B]): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - var those = f(these.head).elements - while (those.hasNext) { - b += those.next - } - these = these.tail - } - b.toList - } - - /** A list consisting of all elements of this list in reverse order. - */ - override def reverse: List[A] = { - var result: List[A] = Nil - var these = this - while (!these.isEmpty) { - result = these.head :: result - these = these.tail - } - result - } - - /** Returns a list formed from this list and the specified list - * that by associating each element of the former with - * the element at the same position in the latter. - * If one of the two lists is longer than the other, its remaining elements are ignored. - * - * @return List((a0,b0), ..., - * (amin(m,n),bmin(m,n))) when - * List(a0, ..., am) - * zip List(b0, ..., bn) is invoked. - */ - def zip[B](that: List[B]): List[(A, B)] = { - val b = new ListBuffer[(A, B)] - var these = this - var those = that - while (!these.isEmpty && !those.isEmpty) { - b += (these.head, those.head) - these = these.tail - those = those.tail - } - b.toList - } - - /** Returns a list that pairs each element of this list - * with its index, counting from 0. - * - * @return the list List((a0,0), (a1,1), ...) - * where ai are the elements of this list. - */ - def zipWithIndex: List[(A, Int)] = { - val b = new ListBuffer[(A, Int)] - var these = this - var idx = 0 - - while(!these.isEmpty) { - b += (these.head, idx) - these = these.tail - idx += 1 - } - - b.toList - } - - /** Returns a list formed from this list and the specified list - * that by associating each element of the former with - * the element at the same position in the latter. - * - * @param that list that may have a different length - * as the self list. - * @param thisElem element thisElem is used to fill up the - * resulting list if the self list is shorter than - * that - * @param thatElem element thatElem is used to fill up the - * resulting list if that is shorter than - * the self list - * @return List((a0,b0), ..., - * (an,bn), (elem,bn+1), - * ..., {elem,bm}) - * when [a0, ..., an] zip - * [b0, ..., bm] is - * invoked where m > n. - */ - def zipAll[B, C >: A, D >: B](that: List[B], thisElem: C, thatElem: D): List[(C, D)] = { - val b = new ListBuffer[(C, D)] - var these = this - var those = that - while (!these.isEmpty && !those.isEmpty) { - b += (these.head, those.head) - these = these.tail - those = those.tail - } - while (!these.isEmpty) { - b += (these.head, thatElem) - these = these.tail - } - while (!those.isEmpty) { - b += (thisElem, those.head) - those = those.tail - } - b.toList - } - - /** Computes the union of this list and the given list - * that. - * - * @param that the list of elements to add to the list. - * @return a list without doubles containing the elements of this - * list and those of the given list that. - */ - def union[B >: A](that: List[B]): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - if (!that.contains(these.head)) b += these.head - these = these.tail - } - b.prependToList(that) - } - - /** Computes the difference between this list and the given list - * that. - * - * @param that the list of elements to remove from this list. - * @return this list without the elements of the given list - * that. - * @deprecated use -- instead - */ - @deprecated - def diff[B >: A](that: List[B]): List[B] = this -- that - - /** Computes the difference between this list and the given list - * that. - * - * @param that the list of elements to remove from this list. - * @return this list without the elements of the given list - * that. - */ - def -- [B >: A](that: List[B]): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - if (!that.contains(these.head)) b += these.head - these = these.tail - } - b.toList - } - - /** Computes the difference between this list and the given object - * x. - * - * @param x the object to remove from this list. - * @return this list without the elements of the given object - * x. - */ - def - [B >: A](x: B): List[B] = - this -- List(x) - - def flatten[B](implicit f : A => Iterable[B]) : List[B] = { - val buf = new ListBuffer[B] - foreach(f(_).foreach(buf += _)) - buf.toList - } - - /** Computes the intersection between this list and the given list - * that. - * - * @param that the list to intersect. - * @return the list of elements contained both in this list and - * in the given list that. - */ - def intersect[B >: A](that: List[B]): List[B] = filter(x => that contains x) - - /** Removes redundant elements from the list. Uses the method == - * to decide if two elements are identical. - * - * @return the list without doubles. - */ - def removeDuplicates: List[A] = { - val b = new ListBuffer[A] - var these = this - while (!these.isEmpty) { - if (!these.tail.contains(these.head)) b += these.head - these = these.tail - } - b.toList - } - - override protected def stringPrefix = "List" - override def projection = toStream - override def toStream : Stream[A] = new Stream.Definite[A] { - override def force : List[A] = List.this - override def isEmpty = List.this.isEmpty - override def head = List.this.head - override def tail = List.this.tail.toStream - protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = if (!isEmpty) { - var prefix0 = prefix - var buf1 = buf.append(prefix0).append(head) - prefix0 = ", " - var tail0 = tail - while (!tail0.isEmpty) { - buf1 = buf.append(prefix0).append(tail0.head) - tail0 = tail0.tail - } - buf1 - } else buf - } - -} - -/** The empty list. - * - * @author Martin Odersky - * @version 1.0, 15/07/2003 - */ -@SerialVersionUID(0 - 8256821097970055419L) -case object Nil extends List[Nothing] { - override def isEmpty = true - def head: Nothing = - throw new NoSuchElementException("head of empty list") - def tail: List[Nothing] = - throw new NoSuchElementException("tail of empty list") -} - -/** A non empty list characterized by a head and a tail. - * - * @author Martin Odersky - * @version 1.0, 15/07/2003 - */ -@SerialVersionUID(0L - 8476791151983527571L) -final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] { - def head : B = hd - def tail : List[B] = tl - override def isEmpty: Boolean = false -} - diff --git a/src/library/dotnet/scala/Math.scala b/src/library/dotnet/scala/Math.scala deleted file mode 100644 index 4d03de9b77..0000000000 --- a/src/library/dotnet/scala/Math.scala +++ /dev/null @@ -1,135 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - - -import Predef._ - -object Math { - - /** The smallest possible value for scala.Byte. */ - val MIN_BYTE = System.Byte.MinValue - /** The greatest possible value for scala.Byte. */ - val MAX_BYTE = System.Byte.MaxValue - - /** The smallest possible value for scala.Short. */ - val MIN_SHORT = System.Int16.MinValue - /** The greatest possible value for scala.Short. */ - val MAX_SHORT = System.Int16.MaxValue - - /** The smallest possible value for scala.Char. */ - val MIN_CHAR = System.Char.MinValue - /** The greatest possible value for scala.Char. */ - val MAX_CHAR = System.Char.MaxValue - - /** The smallest possible value for scala.Int. */ - val MIN_INT = System.Int32.MinValue - /** The greatest possible value for scala.Int. */ - val MAX_INT = System.Int32.MaxValue - - /** The smallest possible value for scala.Long. */ - val MIN_LONG = System.Int64.MinValue - /** The greatest possible value for scala.Long. */ - val MAX_LONG = System.Int64.MaxValue - - /** The smallest possible value for scala.Float. */ - val MIN_FLOAT = System.Single.MinValue - /** The smallest difference between two values of scala.Float. */ - val EPS_FLOAT = System.Single.Epsilon - /** The greatest possible value for scala.Float. */ - val MAX_FLOAT = System.Single.MinValue - /** A value of type scala.Float that represents no number. */ - //val NaN_FLOAT = System.Single.NaN - /** Negative infinity of type scala.Float. */ - //val NEG_INF_FLOAT = System.Double.NegativeInfinity - /** Positive infinity of type scala.Float. */ - //val POS_INF_FLOAT = System.Double.PositiveInfinity - - /** The smallest possible value for scala.Double. */ - val MIN_DOUBLE = System.Double.MinValue - /** The smallest difference between two values of scala.Double. */ - val EPS_DOUBLE = System.Double.Epsilon - /** The greatest possible value for scala.Double. */ - val MAX_DOUBLE = System.Double.MaxValue - /** A value of type scala.Double that represents no number. */ - //val NaN_DOUBLE = System.Double.NaN - /** Negative infinity of type scala.Double. */ - //val NEG_INF_DOUBLE = System.Double.NegativeInfinity - /** Positive infinity of type scala.Double. */ - //val POS_INF_DOUBLE = System.Double.PositiveInfinity - - /** The double value that is closer than any other to - * e, the base of the natural logarithms. - */ - - val E = System.Math.E - val Pi = System.Math.PI - - //def random: Double = System.Math.random() - - def sin(x: Double): Double = System.Math.Sin(x) - def cos(x: Double): Double = System.Math.Cos(x) - def tan(x: Double): Double = System.Math.Tan(x) - def asin(x: Double): Double = System.Math.Asin(x) - def acos(x: Double): Double = System.Math.Acos(x) - def atan(x: Double): Double = System.Math.Atan(x) - - def toRadians(x: Double): Double = x * Pi / 180.0 - - def toDegrees(x: Double): Double = x * 180.0 / Pi - - def exp(x: Double): Double = System.Math.Exp(x) - def log(x: Double): Double = System.Math.Log(x) - def sqrt(x: Double): Double = System.Math.Sqrt(x) - def sqrt(x: Int): Int = System.Math.Sqrt(x.toDouble).toInt - def IEEEremainder(x: Double, y: Double): Double = System.Math.IEEERemainder(x, y) - - def ceil(x: Double): Double = System.Math.Ceiling(x) - def floor(x: Double): Double = System.Math.Floor(x) - - //def rint(x: Double): Double = System.Math.rint(x) - def atan2(y: Double, x: Double): Double = System.Math.Atan2(y, x) - def pow(x: Double, y: Double): Double = System.Math.Pow(x, y) - def round(x: Float): Int = System.Math.Round(x).toInt - def round(x: Double): Long = System.Math.Round(x).toLong - - def abs(x: Int): Int = System.Math.Abs(x) - def abs(x: Long): Long = System.Math.Abs(x) - def abs(x: Float): Float = System.Math.Abs(x) - def abs(x: Double): Double = System.Math.Abs(x) - - def max(x: Int, y: Int): Int = System.Math.Max(x, y) - def max(x: Long, y: Long): Long = System.Math.Max(x, y) - def max(x: Float, y: Float): Float = System.Math.Max(x, y) - def max(x: Double, y: Double): Double = System.Math.Max(x, y) - - def min(x: Int, y: Int): Int = System.Math.Min(x, y) - def min(x: Long, y: Long): Long = System.Math.Min(x, y) - def min(x: Float, y: Float): Float = System.Math.Min(x, y) - def min(x: Double, y: Double): Double = System.Math.Min(x, y) - - // from Java 1.5 -// def log10(x: Double): Double = java.lang.Math.log10(x) -// def cbrt(x: Double): Double = java.lang.Math.cbrt(x) - -// def ulp(x: Double): Double = java.lang.Math.ulp(x) -// def ulp(x: Float): Float = java.lang.Math.ulp(x) -// def signum(x: Double): Double = java.lang.Math.signum(x) -// def signum(x: Float): Float = java.lang.Math.signum(x) -// def sinh(x: Double): Double = java.lang.Math.sinh(x) -// def cosh(x: Double): Double = java.lang.Math.cosh(x) -// def tanh(x: Double):Double = java.lang.Math.tanh(x) -// def hypot(x: Double, y: Double): Double = java.lang.Math.hypot(x, y) -// def expm1(x: Double): Double = java.lang.Math.expm1(x) -// def log1p(x: Double): Double = java.lang.Math.log1p(x) - -} diff --git a/src/library/dotnet/scala/Predef.scala b/src/library/dotnet/scala/Predef.scala deleted file mode 100644 index dc45fe2bec..0000000000 --- a/src/library/dotnet/scala/Predef.scala +++ /dev/null @@ -1,310 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - - -/** The Predef object provides definitions that are - * accessible in all Scala compilation units without explicit - * qualification. - */ -object Predef { - - // classOf dummy ------------------------------------------------------ - - /** Return the runtime representation of a class type. */ - def classOf[T]: Class[T] = null - - // aliases ------------------------------------------------------------ - - type byte = scala.Byte - type short = scala.Short - type char = scala.Char - type int = scala.Int - type long = scala.Long - type float = scala.Float - type double = scala.Double - type boolean = scala.Boolean - type unit = scala.Unit - - type String = System.String - type Class[T] = System.Type - type Runnable = scala.runtime.Runnable - - type Throwable = System.Exception - type Exception = System.Exception - type Error = System.Exception - - type RuntimeException = System.Exception - type NullPointerException = System.NullReferenceException - type ClassCastException = System.InvalidCastException - type IndexOutOfBoundsException = System.IndexOutOfRangeException - type ArrayIndexOutOfBoundsException = System.IndexOutOfRangeException - type StringIndexOutOfBoundsException = System.IndexOutOfRangeException - type UnsupportedOperationException = System.InvalidOperationException - type IllegalArgumentException = System.ArgumentException - type NoSuchElementException = System.InvalidOperationException - //type NumberFormatException = java.lang.NumberFormatException - - // miscelleaneous ----------------------------------------------------- - - //val $scope = scala.xml.TopScope - - type Function[-A, +B] = Function1[A, B] - - type Map[A, B] = collection.immutable.Map[A, B] - type Set[A] = collection.immutable.Set[A] - - val Map = collection.immutable.Map - val Set = collection.immutable.Set - - // errors and asserts ------------------------------------------------- - - def error(message: String): Nothing = throw new Error(message) - - def exit: Nothing = exit(0) - - def exit(status: Int): Nothing = { - System.Environment.Exit(status) - throw new Throwable() - } - - def assert(assertion: Boolean) { - if (!assertion) - throw new Error("assertion failed") - } - - def assert(assertion: Boolean, message: Any) { - if (!assertion) - throw new Error("assertion failed: " + message) - } - - def assume(assumption: Boolean) { - if (!assumption) - throw new IllegalArgumentException("assumption failed") - } - - def assume(assumption: Boolean, message: Any) { - if (!assumption) - throw new IllegalArgumentException("assumption failed: " + message) - } - - // tupling ------------------------------------------------------------ - - type Pair[+A, +B] = Tuple2[A, B] - object Pair { - def apply[A, B](x: A, y: B) = Tuple2(x, y) - def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x) - } - - type Triple[+A, +B, +C] = Tuple3[A, B, C] - object Triple { - def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z) - def unapply[A, B, C](x: Tuple3[A, B, C]): Option[Tuple3[A, B, C]] = Some(x) - } - - class ArrowAssoc[A](x: A) { - def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y) - } - implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x) - - def Tuple[A1](x1: A1) = Tuple1(x1) - def Tuple[A1, A2](x1: A1, x2: A2) = Tuple2(x1, x2) - def Tuple[A1, A2, A3](x1: A1, x2: A2, x3: A3) = Tuple3(x1, x2, x3) - def Tuple[A1, A2, A3, A4](x1: A1, x2: A2, x3: A3, x4: A4) = Tuple4(x1, x2, x3, x4) - def Tuple[A1, A2, A3, A4, A5](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5) = Tuple5(x1, x2, x3, x4, x5) - def Tuple[A1, A2, A3, A4, A5, A6](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6) = Tuple6(x1, x2, x3, x4, x5, x6) - def Tuple[A1, A2, A3, A4, A5, A6, A7](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7) = Tuple7(x1, x2, x3, x4, x5, x6, x7) - def Tuple[A1, A2, A3, A4, A5, A6, A7, A8](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8) = Tuple8(x1, x2, x3, x4, x5, x6, x7, x8) - def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9) = Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9) - - // printing and reading ----------------------------------------------- - - def print(x: Any) = Console.print(x) - def println() = Console.println() - def println(x: Any) = Console.println(x) - //def printf(text: String, xs: Any*) = Console.printf(text, xs: _*) - //def format(text: String, xs: Any*) = Console.format(text, xs) - - def readLine(): String = Console.readLine() - def readLine(text: String, args: Any*) = Console.readLine(text, args) - def readBoolean() = Console.readBoolean() - def readByte() = Console.readByte() - def readShort() = Console.readShort() - def readChar() = Console.readChar() - def readInt() = Console.readInt() - def readLong() = Console.readLong() - def readFloat() = Console.readFloat() - def readDouble() = Console.readDouble() - //def readf(format: String) = Console.readf(format) - //def readf1(format: String) = Console.readf1(format) - //def readf2(format: String) = Console.readf2(format) - //def readf3(format: String) = Console.readf3(format) - - // views -------------------------------------------------------------- - - implicit def identity[A](x: A): A = x - - implicit def byteWrapper(x: Byte) = new runtime.RichByte(x) - implicit def shortWrapper(x: Short) = new runtime.RichShort(x) - implicit def intWrapper(x: Int) = new runtime.RichInt(x) - implicit def charWrapper(c: Char) = new runtime.RichChar(c) - implicit def longWrapper(x: Long) = new runtime.RichLong(x) - implicit def floatWrapper(x: Float) = new runtime.RichFloat(x) - implicit def doubleWrapper(x: Double) = new runtime.RichDouble(x) - - implicit def booleanWrapper(x: Boolean) = new runtime.RichBoolean(x) - - implicit def stringWrapper(x: String) = new runtime.RichString(x) - //implicit def stringBuilderWrapper(x : StringBuilder) = new runtime.RichStringBuilder(x) - - implicit def any2stringadd(x: Any) = new runtime.StringAdd(x) - - implicit def exceptionWrapper(exc: Throwable) = new runtime.RichException(exc) - - final class GetClassWrapper(obj: AnyRef) { - def getClass(): runtime.RichClass = classWrapper(obj.GetType()) - } - implicit def getClassWrapper(obj: AnyRef) = new GetClassWrapper(obj) - implicit def classWrapper(clazz: Class[_]): runtime.RichClass = - new runtime.RichClass(clazz) - - implicit def unit2ordered(x: Unit): Ordered[Unit] = new Ordered[Unit] with Proxy { - def self: Any = x - def compare(y: Unit): Int = 0 - } - - implicit def iterable2ordered[A <% Ordered[A]](xs: Iterable[A]): Ordered[Iterable[A]] = - new Ordered[Iterable[A]] with Proxy { - val self = xs - def compare(that: Iterable[A]): Int = { - var res = 0 - val these = xs.elements - val those = that.elements - while (res == 0 && these.hasNext) - res = if (those.hasNext) these.next compare those.next else 1 - if (res == 0) { - if (those.hasNext) -1 else 0 - } else - res - } - } - - implicit def tuple22ordered[A1 <% Ordered[A1], A2 <% Ordered[A2]](x: Tuple2[A1, A2]): Ordered[Tuple2[A1, A2]] = - new Ordered[Tuple2[A1, A2]] with Proxy { - val self = x - def compare(y: Tuple2[A1, A2]): Int = { - val res = x._1 compare y._1 - if (res == 0) x._2 compare y._2 - else res - } - } - - implicit def tuple32ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3]](x: Tuple3[A1, A2, A3]): Ordered[Tuple3[A1, A2, A3]] = - new Ordered[Tuple3[A1, A2, A3]] with Proxy { - val self = x - def compare(y: Tuple3[A1, A2, A3]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple2(x._2, x._3) compare Tuple2(y._2, y._3) - else res - } - } - - implicit def tuple42ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4]](x: Tuple4[A1, A2, A3, A4]): Ordered[Tuple4[A1, A2, A3, A4]] = - new Ordered[Tuple4[A1, A2, A3, A4]] with Proxy { - val self = x - def compare(y: Tuple4[A1, A2, A3, A4]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple3(x._2, x._3, x._4) compare Tuple3(y._2, y._3, y._4) - else res - } - } - - implicit def tuple52ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5]](x: Tuple5[A1, A2, A3, A4, A5]): Ordered[Tuple5[A1, A2, A3, A4, A5]] = - new Ordered[Tuple5[A1, A2, A3, A4, A5]] with Proxy { - val self = x - def compare(y: Tuple5[A1, A2, A3, A4, A5]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple4(x._2, x._3, x._4, x._5) compare Tuple4(y._2, y._3, y._4, y._5) - else res - } - } - - implicit def tuple62ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6]](x: Tuple6[A1, A2, A3, A4, A5, A6]): Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] = - new Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] with Proxy { - val self = x - def compare(y: Tuple6[A1, A2, A3, A4, A5, A6]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple5(x._2, x._3, x._4, x._5, x._6) compare Tuple5(y._2, y._3, y._4, y._5, y._6) - else res - } - } - - implicit def tuple72ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7]](x: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] = - new Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] with Proxy { - val self = x - def compare(y: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple6(x._2, x._3, x._4, x._5, x._6, x._7) compare Tuple6(y._2, y._3, y._4, y._5, y._6, y._7) - else res - } - } - - implicit def tuple82ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8]](x: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] = - new Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] with Proxy { - val self = x - def compare(y: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple7(x._2, x._3, x._4, x._5, x._6, x._7, x._8) compare Tuple7(y._2, y._3, y._4, y._5, y._6, y._7, y._8) - else res - } - } - - implicit def tuple92ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8], A9 <% Ordered[A9]](x: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] = - new Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] with Proxy { - val self = x - def compare(y: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple8(x._2, x._3, x._4, x._5, x._6, x._7, x._8, x._9) compare Tuple8(y._2, y._3, y._4, y._5, y._6, y._7, y._8, y._9) - else res - } - } - - implicit def byte2short(x: Byte): Short = x.toShort - implicit def byte2int(x: Byte): Int = x.toInt - implicit def byte2long(x: Byte): Long = x.toLong - implicit def byte2float(x: Byte): Float = x.toFloat - implicit def byte2double(x: Byte): Double = x.toDouble - - implicit def short2int(x: Short): Int = x.toInt - implicit def short2long(x: Short): Long = x.toLong - implicit def short2float(x: Short): Float = x.toFloat - implicit def short2double(x: Short): Double = x.toDouble - - implicit def char2int(x: Char): Int = x.toInt - implicit def char2long(x: Char): Long = x.toLong - implicit def char2float(x: Char): Float = x.toFloat - implicit def char2double(x: Char): Double = x.toDouble - - implicit def int2long(x: Int): Long = x.toLong - implicit def int2float(x: Int): Float = x.toFloat - implicit def int2double(x: Int): Double = x.toDouble - - implicit def long2float(x: Long): Float = x.toFloat - implicit def long2double(x: Long): Double = x.toDouble - - implicit def float2double(x: Float): Double = x.toDouble - - implicit def forceArrayProjection[A](x : Array.Projection[A]) : Array[A] = x.force - - def currentThread = System.Threading.Thread.CurrentThread - -} diff --git a/src/library/dotnet/scala/Random.scala b/src/library/dotnet/scala/Random.scala deleted file mode 100644 index 7d0b1be853..0000000000 --- a/src/library/dotnet/scala/Random.scala +++ /dev/null @@ -1,74 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -/** - * @author Stephane Micheloud - */ -class Random(self0: System.Random) { - private var rnd = self0 // see setSeed(seed) - def self = rnd - - /** Creates a new random number generator using a single long seed. */ - def this(seed: Long) = this(new System.Random(seed.toInt)) - - /** Creates a new random number generator using a single integer seed. */ - def this(seed: Int) = this(new System.Random(seed)) - - /** Creates a new random number generator. */ - def this() = this(new System.Random(System.Environment.TickCount)) - - /** Returns the next pseudorandom, uniformly distributed boolean value - * from this random number generator's sequence. - */ - def nextBoolean(): Boolean = (nextInt() & 0x1) == 1 - - /** Generates random bytes and places them into a user-supplied byte - * array. - */ - def nextBytes(bytes: Array[Byte]) { rnd.NextBytes(bytes) } - - /** Returns the next pseudorandom, uniformly distributed double value - * between 0.0 and 1.0 from this random number generator's sequence. - */ - def nextDouble(): Double = rnd.NextDouble() - - /** Returns the next pseudorandom, uniformly distributed float value - * between 0.0 and 1.0 from this random number generator's sequence. - */ - def nextFloat(): Float = nextDouble().toFloat - - /** Returns the next pseudorandom, Gaussian ("normally") distributed - * double value with mean 0.0 and standard deviation 1.0 from this - * random number generator's sequence. - */ - //def nextGaussian(): Double - - /** Returns the next pseudorandom, uniformly distributed int value - * from this random number generator's sequence. - */ - def nextInt(): Int = rnd.Next() - - /** Returns a pseudorandom, uniformly distributed int value between 0 - * (inclusive) and the specified value (exclusive), drawn from this - * random number generator's sequence. - */ - def nextInt(n: Int): Int = rnd.Next(0, n) - - /** Returns the next pseudorandom, uniformly distributed long value - * from this random number generator's sequence. - */ - def nextLong(): Long = nextInt().toLong // 2x nextInt() ?! - - def setSeed(seed: Long) { rnd = new System.Random(seed.toInt) } - -} diff --git a/src/library/dotnet/scala/StringBuilder.scala b/src/library/dotnet/scala/StringBuilder.scala deleted file mode 100644 index b6912060e2..0000000000 --- a/src/library/dotnet/scala/StringBuilder.scala +++ /dev/null @@ -1,709 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import Predef._ - -/**

- * A mutable sequence of characters. This class provides an API compatible - * with java.lang.StringBuilder, but with no guarantee of - * synchronization. - *

- * - * @author Stephane Micheloud - * @version 1.0 - */ -final class StringBuilder(initCapacity: Int, private val initValue: String) -extends (Int => Char) with Proxy { - if (initCapacity < 0) throw new IllegalArgumentException - if (initValue eq null) throw new NullPointerException - - /** The value is used for character storage. */ - private var value = new Array[Char](initCapacity + initValue.length) - - /** The count is the number of characters used. */ - private var count: Int = 0 - - /** Constructs a string builder with no characters in it and an - * initial capacity of 16 characters. - */ - def this() = this(16, "") - - /** Constructs a string builder with no characters in it and an - * initial capacity specified by the capacity argument. - * - * @param capacity the initial capacity. - * @throws NegativeArraySizeException if the capacity - * argument is less than 0. - */ - def this(capacity: Int) = this(capacity, "") - - def this(str: String) = this(16, str) - - append(initValue) - - def self = this - - def toArray: Array[Char] = value - - def length: Int = count - - def length_=(n: Int) { setLength(n) } - - /** Sets the length of the character sequence. - * - * @param newLength the new length - * @throws IndexOutOfBoundsException if the n argument is negative. - */ - def setLength(n: Int) { - if (n < 0) - throw new StringIndexOutOfBoundsException//(n) - if (n > value.length) expandCapacity(n) - if (count < n) - while (count < n) { - value(count) = '\0'; count += 1 - } - else - count = n - } - - /** Returns the current capacity. The capacity is the amount of storage - * available for newly inserted characters, beyond which an allocation - * will occur. - * - * @return the current capacity - */ - def capacity: Int = value.length - - /** Same as ensureCapacity. */ - def capacity_=(n: Int) { ensureCapacity(n) } - - /**

- * Ensures that the capacity is at least equal to the specified minimum. - * If the current capacity is less than the argument, then a new internal - * array is allocated with greater capacity. The new capacity is the larger of: - *

- * - *

- * If the n argument is non-positive, this - * method takes no action and simply returns. - *

- * - * @param n the minimum desired capacity. - */ - def ensureCapacity(n: Int) { - if (n > value.length) expandCapacity(n) - } - - private def expandCapacity(n: Int) { - val newCapacity = (value.length + 1) * 2 - value = StringBuilder.copyOf( - value, - if (newCapacity < 0) Math.MAX_INT else if (n > newCapacity) n else newCapacity - ) - } - - /**

- * Returns the Char value in this sequence at the specified index. - * The first Char value is at index 0, the next at index - * 1, and so on, as in array indexing. - *

- *

- * The index argument must be greater than or equal to - * 0, and less than the length of this sequence. - *

- * - * @param index the index of the desired Char value. - * @return the Char value at the specified index. - * @throws IndexOutOfBoundsException if index is - * negative or greater than or equal to length(). - */ - def charAt(index: Int): Char = { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException//(index) - value(index) - } - - /** Same as charAt. */ - def apply(i: Int): Char = charAt(i) - - /**

- * Removes the Char at the specified position in this - * sequence. This sequence is shortened by one Char. - *

- * - * @param index Index of Char to remove - * @return This object. - * @throws StringIndexOutOfBoundsException if the index - * is negative or greater than or equal to length(). - */ - def deleteCharAt(index: Int): StringBuilder = { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException//(index) - compat.Platform.arraycopy(value, index + 1, value, index, count - index - 1) - count -= 1 - this - } - - /**

- * The character at the specified index is set to ch. This - * sequence is altered to represent a new character sequence that is - * identical to the old character sequence, except that it contains the - * character ch at position index. - *

- *

- * The index argument must be greater than or equal to - * 0, and less than the length of this sequence. - *

- * - * @param index the index of the character to modify. - * @param ch the new character. - * @throws IndexOutOfBoundsException if index is - * negative or greater than or equal to length(). - */ - def setCharAt(index: Int, ch: Char) { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException//(index) - value(index) = ch - } - - /** Same as setCharAt. */ - def update(i: Int, c: Char) { setCharAt(i, c) } - - /** Returns a new String that contains a subsequence of - * characters currently contained in this character sequence. The - * substring begins at the specified index and extends to the end of - * this sequence. - * - * @param start The beginning index, inclusive. - * @return The new string. - * @throws StringIndexOutOfBoundsException if start is - * less than zero, or greater than the length of this object. - */ - def substring(start: Int): String = substring(start, count) - - /** Returns a new String that contains a subsequence of - * characters currently contained in this sequence. The - * substring begins at the specified start and - * extends to the character at index end - 1. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @return The new string. - * @throws StringIndexOutOfBoundsException if start - * or end are negative or greater than - * length(), or start is - * greater than end. - */ - def substring(start: Int, end: Int): String = { - if (start < 0) - throw new StringIndexOutOfBoundsException//(start) - if (end > count) - throw new StringIndexOutOfBoundsException//(end) - if (start > end) - throw new StringIndexOutOfBoundsException//(end - start) - new String(value, start, end - start) - } - - /**

- * Appends the string representation of the Any - * argument. - *

- *

- * The argument is converted to a string as if by the method - * System.Convert.ToString, and the characters of - * that string are then appended to this sequence. - *

- * - * @param x an Any object. - * @return a reference to this object. - */ - def append(x: Any): StringBuilder = - append(System.Convert.ToString(x)) - - /** Appends the specified string to this character sequence. - * - * @param s a string. - * @return a reference to this object. - */ - def append(s: String): StringBuilder = { - val str = if (s == null) "null" else s - val len = str.length - if (len > 0) { - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(str.ToCharArray, 0, value, count, len) - count = newCount - } - this - } - - /** Appends the specified string builder to this sequence. - * - * @param sb - * @return - */ - def append(sb: StringBuilder): StringBuilder = - if (sb == null) - append("null") - else { - val len = sb.length - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(sb.toArray, 0, value, count, len) - count = newCount - this - } - - /**

- * Appends the string representation of the Char array - * argument to this sequence. - *

- *

- * The characters of the array argument are appended, in order, to - * the contents of this sequence. The length of this sequence - * increases by the length of the argument. - *

- * - * @param x the characters to be appended. - * @return a reference to this object. - */ - def append(x: Array[Char]): StringBuilder = - append(x, 0, x.length) - - /**

- * Appends the string representation of a subarray of the - * char array argument to this sequence. - *

- *

- * Characters of the Char array x, starting at - * index offset, are appended, in order, to the contents - * of this sequence. The length of this sequence increases - * by the value of len. - *

- * - * @param x the characters to be appended. - * @param offset the index of the first Char to append. - * @param len the number of Chars to append. - * @return a reference to this object. - */ - def append(x: Array[Char], offset: Int, len: Int): StringBuilder = { - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(x, offset, value, count, len) - count = newCount - this - } - - /**

- * Appends the string representation of the Boolean - * argument to the sequence. - *

- *

- * The argument is converted to a string as if by the method - * System.Convert.ToString, and the characters of - * that string are then appended to this sequence. - *

- * - * @param x a Boolean. - * @return a reference to this object. - */ - def append(x: Boolean): StringBuilder = { - if (x) { - val newCount = count + 4 - if (newCount > value.length) expandCapacity(newCount) - value(count) = 't'; count += 1 - value(count) = 'r'; count += 1 - value(count) = 'u'; count += 1 - value(count) = 'e'; count += 1 - } else { - val newCount = count + 5 - if (newCount > value.length) expandCapacity(newCount) - value(count) = 'f'; count += 1 - value(count) = 'a'; count += 1 - value(count) = 'l'; count += 1 - value(count) = 's'; count += 1 - value(count) = 'e'; count += 1 - } - this - } - - def append(x: Char): StringBuilder = { - val newCount = count + 1 - if (newCount > value.length) expandCapacity(newCount) - value(count) = x; count += 1 - this - } - - def append(x: Int): StringBuilder = - append(System.Convert.ToString(x)) - - def append(x: Long): StringBuilder = - append(System.Convert.ToString(x)) - - def append(x: Float): StringBuilder = - append(System.Convert.ToString(x)) - - def append(x: Double): StringBuilder = - append(System.Convert.ToString(x)) - - /** Removes the characters in a substring of this sequence. - * The substring begins at the specified start and extends to - * the character at index end - 1 or to the end of the - * sequence if no such character exists. If - * start is equal to end, no changes are made. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @return This object. - * @throws StringIndexOutOfBoundsException if start - * is negative, greater than length(), or - * greater than end. - */ - def delete(start: Int, end: Int): StringBuilder = { - if (start < 0 || start > end) - throw new StringIndexOutOfBoundsException//(start) - val end0 = if (end > count) count else end - val len = end0 - start - if (len > 0) { - compat.Platform.arraycopy(value, start + len, value, start, count - end0) - count -= len - } - this - } - - /** Replaces the characters in a substring of this sequence - * with characters in the specified String. The substring - * begins at the specified start and extends to the character - * at index end - 1 or to the end of the sequence if no such - * character exists. First the characters in the substring are removed and - * then the specified String is inserted at start. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @param str String that will replace previous contents. - * @return This object. - * @throws StringIndexOutOfBoundsException if start - * is negative, greater than length(), or - * greater than end. - */ - def replace(start: Int, end: Int, str: String) { - if (start < 0 || start > count || start > end) - throw new StringIndexOutOfBoundsException//(start) - - val end0 = if (end > count) count else end - val len = str.length() - val newCount = count + len - (end0 - start) - if (newCount > value.length) expandCapacity(newCount) - - compat.Platform.arraycopy(value, end, value, start + len, count - end) - compat.Platform.arraycopy(str.ToCharArray, 0, value, start, len) - count = newCount - this - } - - /** Inserts the string representation of a subarray of the str - * array argument into this sequence. The subarray begins at the specified - * offset and extends len chars. - * The characters of the subarray are inserted into this sequence at - * the position indicated by index. The length of this - * sequence increases by len Chars. - * - * @param index position at which to insert subarray. - * @param str a Char array. - * @param offset the index of the first char in subarray to - * be inserted. - * @param len the number of Chars in the subarray to - * be inserted. - * @return This object - * @throws StringIndexOutOfBoundsException if index - * is negative or greater than length(), or - * offset or len are negative, or - * (offset+len) is greater than - * str.length. - */ - def insert(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = { - if (index < 0 || index > count) - throw new StringIndexOutOfBoundsException//(index) - if (offset < 0 || len < 0 || offset > str.length - len) - throw new StringIndexOutOfBoundsException/*( - "offset " + offset + ", len " + len + - ", str.length " + str.length)*/ - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, index, value, index + len, count - index) - compat.Platform.arraycopy(str, offset, value, index, len) - count = newCount - this - } - - /**

- * Inserts the string representation of the Any - * argument into this character sequence. - *

- *

- * The second argument is converted to a string as if by the method - * System.Convert.ToString, and the characters of that - * string are then inserted into this sequence at the indicated - * offset. - *

- *

- * The offset argument must be greater than or equal to - * 0, and less than or equal to the length of this - * sequence. - *

- * - * @param offset the offset. - * @param x an Any value. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: Any): StringBuilder = - insert(at, System.Convert.ToString(x)) - - /** Inserts the string into this character sequence. - * - * @param at the offset position. - * @param x a string. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: String): StringBuilder = { - if (at < 0 || at > count) - throw new StringIndexOutOfBoundsException//(at) - val str = if (x == null) "null" else x - val len = str.length - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, at, value, at + len, count - at) - compat.Platform.arraycopy(str.ToCharArray, 0, value, at, len) - count = newCount - this - } - - /** Inserts the string representation of the Char array - * argument into this sequence. - * - * @param at the offset position. - * @param x a character array. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: Array[Char]): StringBuilder = { - if (at < 0 || at > count) - throw new StringIndexOutOfBoundsException//(at) - val len = x.length - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, at, value, at + len, count - at) - compat.Platform.arraycopy(x, 0, value, at, len) - count = newCount - this - } - - def insert(at: Int, x: Boolean): StringBuilder = - insert(at, System.Convert.ToString(x)) - - def insert(at: Int, x: Char): StringBuilder = { - if (at < 0 || at > count) - throw new StringIndexOutOfBoundsException//(at) - val newCount = count + 1 - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, at, value, at + 1, count - at) - value(at) = x - count = newCount - this - } - - def insert(at: Int, x: Int): StringBuilder = - insert(at, System.Convert.ToString(x)) - - def insert(at: Int, x: Long): StringBuilder = - insert(at, System.Convert.ToString(x)) - - def insert(at: Int, x: Float): StringBuilder = - insert(at, System.Convert.ToString(x)) - - def insert(at: Int, x: Double): StringBuilder = - insert(at, System.Convert.ToString(x)) - - /** Returns the index within this string of the first occurrence of the - * specified substring. The integer returned is the smallest value - * k such that: - *
-   *  this.toString().startsWith(str, k)
-   *  
- * is true. - * - * @param str any string. - * @return if the string argument occurs as a substring within this - * object, then the index of the first character of the first - * such substring is returned; if it does not occur as a - * substring, -1 is returned. - * @throws NullPointerException if str is null. - */ - def indexOf(str: String): Int = indexOf(str, 0) - - def indexOf(str: String, fromIndex: Int): Int = - StringBuilder.indexOf(value, 0, count, str.ToCharArray, 0, str.length(), fromIndex) - - /** Returns the index within this string of the rightmost occurrence - * of the specified substring. The rightmost empty string "" is - * considered to occur at the index value this.length(). - * The returned index is the largest value k such that - *
-   *  this.toString().startsWith(str, k)
-   *  
- * is true. - * - * @param str the substring to search for. - * @return if the string argument occurs one or more times as a substring - * within this object, then the index of the first character of - * the last such substring is returned. If it does not occur as - * a substring, -1 is returned. - * @throws NullPointerException if str is null. - */ - def lastIndexOf(str: String): Int = lastIndexOf(str, count) - - def lastIndexOf(str: String, fromIndex: Int): Int = - StringBuilder.lastIndexOf(value, 0, count, str.ToCharArray, 0, str.length(), fromIndex) - - /**

- * Causes this character sequence to be replaced by the reverse of the - * sequence. If there are any surrogate pairs included in the sequence, - * these are treated as single characters for the reverse operation. - * Thus, the order of the high-low surrogates is never reversed. - *

- *

- * Let n be the character length of this character sequence - * (not the length in Char values) just prior to - * execution of the reverse method. Then the - * character at index k in the new character sequence is - * equal to the character at index n-k-1 in the old - * character sequence. - *

- * - * @return a reference to this object. - */ - def reverse(): StringBuilder = { - val n = count - 1 - var j = (n-1) >> 1 - while (j >= 0) { - val temp = value(j) - val temp2 = value(n - j) - value(j) = temp2 - value(n - j) = temp - j -= 1 - } - this - } - - /** Returns a string representing the data in this sequence. - * A new String object is allocated and initialized to - * contain the character sequence currently represented by this - * object. This String is then returned. Subsequent - * changes to this sequence do not affect the contents of the - * String. - * - * @return a string representation of this sequence of characters. - */ - override def toString(): String = new String(value, 0, count) - -} - - -object StringBuilder { - - // method java.util.Arrays.copyOf exists since 1.6 - private def copyOf(src: Array[Char], newLength: Int): Array[Char] = { - val dest = new Array[Char](newLength) - compat.Platform.arraycopy(src, 0, dest, 0, Math.min(src.length, newLength)) - dest - } - - private def indexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, - target: Array[Char], targetOffset: Int, targetCount: Int, - fromIndex: Int): Int = - if (fromIndex >= sourceCount) - if (targetCount == 0) sourceCount else -1 - else { - val inx = if (fromIndex < 0) 0 else fromIndex - if (targetCount == 0) - inx - else { - val first = target(targetOffset) - val max = sourceOffset + (sourceCount - targetCount) - - var i = sourceOffset + inx - while (i <= max) { - /* Look for first character. */ - if (source(i) != first) { - i += 1 - while (i <= max && source(i) != first) i += 1 - } - /* Found first character, now look at the rest of v2 */ - if (i <= max) { - var j = i + 1 - val end = j + targetCount - 1 - var k = targetOffset + 1 - while (j < end && source(j) == target(k)) { - j += 1 - k += 1 - } - if (j == end) { - /* Found whole string. */ - return i - sourceOffset - } - } // if - i += 1 - } // while - -1 - } - } - - private def lastIndexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, - target: Array[Char], targetOffset: Int, targetCount: Int, - fromIndex: Int): Int = { - val rightIndex = sourceCount - targetCount - if (fromIndex < 0) return -1 - val inx = if (fromIndex > rightIndex) rightIndex else fromIndex - // Empty string always matches - if (targetCount == 0) return inx - - val strLastIndex = targetOffset + targetCount - 1 - val strLastChar = target(strLastIndex) - val min = sourceOffset + targetCount - 1 - var i = min + fromIndex - - while (true) { - while (i >= min && source(i) != strLastChar) i -= 1 - if (i < min) return -1 - var j = i - 1 - val start = j - (targetCount - 1) - var k = strLastIndex - 1 - var outerWhile = false - while (j > start && !outerWhile) { - if (source(j) != target(k)) { - j -= 1 - k -= 1 - i -= 1 - outerWhile = true - } - } - if (!outerWhile) return start - sourceOffset + 1 - } - -1 - } -} diff --git a/src/library/dotnet/scala/Symbol.scala b/src/library/dotnet/scala/Symbol.scala deleted file mode 100644 index 27bc2de7e1..0000000000 --- a/src/library/dotnet/scala/Symbol.scala +++ /dev/null @@ -1,49 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - - -/**

- * Instances of Symbol can be created easily with - * Scala's built-in quote mechanism. - *

- *

- * For instance, the Scala - * term 'mysym will invoke the constructor of the - * Symbol class in the following way: - * new Symbol("mysym"). - *

- * - * @author Martin Odersky - * @version 1.7, 08/12/2003 - */ -final case class Symbol(name: String) { - - /** Converts this symbol to a string. - */ - override def toString(): String = { - "'" + name - } - - /**

- * Makes this symbol into a unique reference. - *

- *

- * If two interened symbols are equal (i.e. they have the same name) - * then they must be identical (wrt reference equality). - *

- * - * @return the unique reference to this symbol. - */ - def intern: Symbol = this - -} diff --git a/src/library/dotnet/scala/compat/Platform.scala b/src/library/dotnet/scala/compat/Platform.scala deleted file mode 100644 index e589860bdc..0000000000 --- a/src/library/dotnet/scala/compat/Platform.scala +++ /dev/null @@ -1,64 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.compat - - -import Predef._ - -object Platform { - - type StackOverflowError = System.StackOverflowException - type ConcurrentModificationException = System.Exception - - /** - * @param src .. - * @param srcPos .. - * @param dest .. - * @param destPos .. - * @param length .. - */ - def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) { - if (!src.isInstanceOf[System.Array]) throw new Exception("src for arraycopy is not an Array; use scala.Array.copy for boxed arrays"); - if (!dest.isInstanceOf[System.Array]) throw new Exception("dest for arraycopy is not an Array; use scala.Array.copy for boxed arrays"); - System.Array.Copy(src.asInstanceOf[System.Array], srcPos, dest.asInstanceOf[System.Array], destPos, length) - } - - /** Create array of the same type as arrayInstance with the given - * length. - * - * @param elemClass .. - * @param length .. - * @return .. - */ - def createArray(elemClass: Class[_], length: Int): AnyRef = - System.Array.CreateInstance(elemClass, length) - - def arrayclear(arr: Array[Int]) { - System.Array.Clear(arr.asInstanceOf[System.Array], 0, arr.length) - } - - def getClassForName(name: String): Class[_] = System.Type.GetType(name) - - val EOL = System.Environment.NewLine - - def currentTime: Long = 0L -/* // compiler crash :-( - private lazy val baseTicks = (new System.DateTime(1970, 1, 1, 0, 0, 0)).Ticks - def currentTime: Long = { - val nowTicks = System.DateTime.UtcNow.Ticks - (nowTicks - baseTicks) / 10000 - } -*/ - def collectGarbage { System.GC.Collect() } - -} - diff --git a/src/library/dotnet/scala/runtime/BooleanRef.cs b/src/library/dotnet/scala/runtime/BooleanRef.cs deleted file mode 100644 index 2680b30149..0000000000 --- a/src/library/dotnet/scala/runtime/BooleanRef.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - [Serializable] - public class BooleanRef { - public bool elem; - public BooleanRef(bool elem) { this.elem = elem; } - override public string ToString() { return elem.ToString(); } - } - -} diff --git a/src/library/dotnet/scala/runtime/BoxedUnit.cs b/src/library/dotnet/scala/runtime/BoxedUnit.cs deleted file mode 100644 index d3ef5a3e11..0000000000 --- a/src/library/dotnet/scala/runtime/BoxedUnit.cs +++ /dev/null @@ -1,36 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -namespace scala.runtime { - - using System; - - [Serializable] - public sealed class BoxedUnit { - - public static readonly BoxedUnit UNIT = new BoxedUnit(); - - private BoxedUnit() { } - - override public bool Equals(object other) { - return this == other; - } - - override public int GetHashCode() { - return 0; - } - - override public string ToString() { - return "()"; - } - } - -} diff --git a/src/library/dotnet/scala/runtime/ByteRef.cs b/src/library/dotnet/scala/runtime/ByteRef.cs deleted file mode 100644 index 6a539a3afd..0000000000 --- a/src/library/dotnet/scala/runtime/ByteRef.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - [Serializable] - public class ByteRef { - public byte elem; - public ByteRef(byte elem) { this.elem = elem; } - override public string ToString() { return elem.ToString(); } - } - -} diff --git a/src/library/dotnet/scala/runtime/CharRef.cs b/src/library/dotnet/scala/runtime/CharRef.cs deleted file mode 100644 index 75b2817b83..0000000000 --- a/src/library/dotnet/scala/runtime/CharRef.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - [Serializable] - public class CharRef { - public char elem; - public CharRef(char elem) { this.elem = elem; } - override public string ToString() { return elem.ToString(); } - } - -} diff --git a/src/library/dotnet/scala/runtime/Comparator.cs b/src/library/dotnet/scala/runtime/Comparator.cs deleted file mode 100644 index 4a1322d49c..0000000000 --- a/src/library/dotnet/scala/runtime/Comparator.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - public class Comparator { - public static bool equals(object a, object b) { - if (a == null) - return b == null; - if (a.Equals(b)) - return true; - if (a == b) - return true; - IConvertible aa = a as IConvertible; - IConvertible bb = b as IConvertible; - if (aa != null && bb != null) { - if (a is Decimal || b is Decimal) - return aa.ToDecimal(null) == bb.ToDecimal(null); - if (a is Double || b is Double) - return aa.ToDouble(null) == bb.ToDouble(null); - if (a is Single || b is Single) - return aa.ToSingle(null) == bb.ToSingle(null); - if (a is Int64 || b is Int64) - return aa.ToInt64(null) == bb.ToInt64(null); - return aa.ToInt32(null) == bb.ToInt32(null); - } - return false; - } - } - -} diff --git a/src/library/dotnet/scala/runtime/DoubleRef.cs b/src/library/dotnet/scala/runtime/DoubleRef.cs deleted file mode 100644 index 60a155f00b..0000000000 --- a/src/library/dotnet/scala/runtime/DoubleRef.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - [Serializable] - public class DoubleRef { - public double elem; - public DoubleRef(double elem) { this.elem = elem; } - override public string ToString() { return elem.ToString(); } - } - -} diff --git a/src/library/dotnet/scala/runtime/ExceptionHandling.cs b/src/library/dotnet/scala/runtime/ExceptionHandling.cs deleted file mode 100644 index 4448777f2e..0000000000 --- a/src/library/dotnet/scala/runtime/ExceptionHandling.cs +++ /dev/null @@ -1,27 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - public abstract class ExceptionHandling { - - public static Exception tryCatch(Runnable runnable) { - try { - runnable.run(); - return null; - } catch (Exception exception) { - return exception; - } - } - } - -} diff --git a/src/library/dotnet/scala/runtime/FloatRef.cs b/src/library/dotnet/scala/runtime/FloatRef.cs deleted file mode 100644 index ee81ea3c9c..0000000000 --- a/src/library/dotnet/scala/runtime/FloatRef.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - [Serializable] - public class FloatRef { - public float elem; - public FloatRef(float elem) { this.elem = elem; } - override public string ToString() { return elem.ToString(); } - } - -} diff --git a/src/library/dotnet/scala/runtime/IntRef.cs b/src/library/dotnet/scala/runtime/IntRef.cs deleted file mode 100644 index e305df145f..0000000000 --- a/src/library/dotnet/scala/runtime/IntRef.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - [Serializable] - public class IntRef { - public int elem; - public IntRef(int elem) { this.elem = elem; } - override public string ToString() { return elem.ToString(); } - } - -} diff --git a/src/library/dotnet/scala/runtime/LongRef.cs b/src/library/dotnet/scala/runtime/LongRef.cs deleted file mode 100644 index e6387ed96f..0000000000 --- a/src/library/dotnet/scala/runtime/LongRef.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - [Serializable] - public class LongRef { - public long elem; - public LongRef(long elem) { this.elem = elem; } - override public string ToString() { return elem.ToString(); } - } - -} diff --git a/src/library/dotnet/scala/runtime/ObjectRef.cs b/src/library/dotnet/scala/runtime/ObjectRef.cs deleted file mode 100644 index a25d61639e..0000000000 --- a/src/library/dotnet/scala/runtime/ObjectRef.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - [Serializable] - public class ObjectRef { - public Object elem; - public ObjectRef(Object elem) { this.elem = elem; } - override public string ToString() { return "" + elem; } - } - -} diff --git a/src/library/dotnet/scala/runtime/RichChar.scala b/src/library/dotnet/scala/runtime/RichChar.scala deleted file mode 100644 index 285530e5be..0000000000 --- a/src/library/dotnet/scala/runtime/RichChar.scala +++ /dev/null @@ -1,70 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -import Predef.NoSuchElementException - -/**

- * For example, in the following code - *

- *
- *    object test extends Application {
- *      Console.println('\40'.isWhitespace)
- *      Console.println('\011'.isWhitespace)
- *      Console.println('1'.asDigit == 1)
- *      Console.println('A'.asDigit == 10)
- *    }
- *

- * the implicit conversions are performed using the predefined view - * Predef.charWrapper. - *

- */ -final class RichChar(x: Char) extends Proxy with Ordered[Char] { - - // Proxy.self - def self: Any = x - - // Ordered[Char].compare - def compare (y: Char): Int = if (x < y) -1 else if (x > y) 1 else 0 - - def asDigit: Int = System.Char.GetNumericValue(x).toInt - - def isControl: Boolean = System.Char.IsControl(x) - def isDigit: Boolean = System.Char.IsDigit(x) - def isLetter: Boolean = System.Char.IsLetter(x) - def isLetterOrDigit: Boolean = System.Char.IsLetterOrDigit(x) - def isLowerCase: Boolean = System.Char.IsLower(x) - def isUpperCase: Boolean = System.Char.IsUpper(x) - def isWhitespace: Boolean = System.Char.IsWhiteSpace(x) - - def toLowerCase: Char = System.Char.ToLower(x) - def toUpperCase: Char = System.Char.ToUpper(x) - - /** Create an Iterator[Char] over the characters from 'x' to 'y' - 1 - */ - def until(limit: Char): Iterator[Char] = new Iterator[Char] { - private var ch = x - def hasNext: Boolean = ch < limit - def next: Char = - if (hasNext) { val j = ch; ch = (ch + 1).toChar; j } - else throw new NoSuchElementException("next on empty iterator") - } - - //def until(y: Char): Iterator[Char] = to(y) - - /** Create an Iterator[Char] over the characters from 'x' to 'y' - */ - def to(y: Char): Iterator[Char] = until((y + 1).toChar) - -} diff --git a/src/library/dotnet/scala/runtime/RichClass.scala b/src/library/dotnet/scala/runtime/RichClass.scala deleted file mode 100644 index e964a66ab1..0000000000 --- a/src/library/dotnet/scala/runtime/RichClass.scala +++ /dev/null @@ -1,25 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - -import Predef.Class - -final class RichClass(val self: Class[_]) extends Proxy { - - def isPrimitive(): Boolean = self.IsPrimitive - def isArray(): Boolean = self.IsArray - - def getClass(): RichClass = this - def getName(): String = self.Name - def getComponentType(): Class[_] = self.GetElementType - -} diff --git a/src/library/dotnet/scala/runtime/RichDouble.scala b/src/library/dotnet/scala/runtime/RichDouble.scala deleted file mode 100644 index 6f22e8c836..0000000000 --- a/src/library/dotnet/scala/runtime/RichDouble.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -final class RichDouble(x: Double) extends Proxy with Ordered[Double] { - - // Proxy.self - def self: Any = x - - // Ordered[Double].compare - def compare(y: Double): Int = if (x < y) -1 else if (x > y) 1 else 0 - - def min(y: Double): Double = Math.min(x, y) - def max(y: Double): Double = Math.max(x, y) - def abs: Double = Math.abs(x) - - def round: Long = Math.round(x) - def ceil: Double = Math.ceil(x) - def floor: Double = Math.floor(x) - - /** Converts an angle measured in degrees to an approximately equivalent - * angle measured in radians. - * - * @param x an angle, in degrees - * @return the measurement of the angle x in radians. - */ - def toRadians: Double = Math.toRadians(x) - - /** Converts an angle measured in radians to an approximately equivalent - * angle measured in degrees. - * - * @param x angle, in radians - * @return the measurement of the angle x in degrees. - */ - def toDegrees: Double = Math.toDegrees(x) - - def isNaN: Boolean = System.Double.IsNaN(x) - def isInfinity: Boolean = System.Double.IsInfinity(x) - def isPosInfinity: Boolean = System.Double.IsPositiveInfinity(x) - def isNegInfinity: Boolean = System.Double.IsNegativeInfinity(x) - -} diff --git a/src/library/dotnet/scala/runtime/RichException.scala b/src/library/dotnet/scala/runtime/RichException.scala deleted file mode 100644 index d08e2e0edf..0000000000 --- a/src/library/dotnet/scala/runtime/RichException.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -final class RichException(exc: System.Exception) { - - def printStackTrace() = System.Console.WriteLine(exc.StackTrace) - def getMessage() = exc.Message - def getStackTraceString: String = exc.StackTrace - -} diff --git a/src/library/dotnet/scala/runtime/RichFloat.scala b/src/library/dotnet/scala/runtime/RichFloat.scala deleted file mode 100644 index 5f8849c1a3..0000000000 --- a/src/library/dotnet/scala/runtime/RichFloat.scala +++ /dev/null @@ -1,54 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -import Predef._ - -final class RichFloat(x: Float) extends Proxy with Ordered[Float] { - - // Proxy.self - def self: Any = x - - // Ordered[Float].compare - def compare (y: Float): Int = if (x < y) -1 else if (x > y) 1 else 0 - - def min(y: Float) = Math.min(x, y) - def max(y: Float) = Math.max(x, y) - def abs: Float = Math.abs(x) - - def round: Int = Math.round(x) - def ceil: Float = Math.ceil(x).toFloat - def floor: Float = Math.floor(x).toFloat - - /** Converts an angle measured in degrees to an approximately equivalent - * angle measured in radians. - * - * @param x an angle, in degrees - * @return the measurement of the angle x in radians. - */ - def toRadians: Float = Math.toRadians(x).toFloat - - /** Converts an angle measured in radians to an approximately equivalent - * angle measured in degrees. - * - * @param x angle, in radians - * @return the measurement of the angle x in degrees. - */ - def toDegrees: Float = Math.toDegrees(x).toFloat - - def isNaN: Boolean = System.Single.IsNaN(x) - def isInfinity: Boolean = System.Single.IsInfinity(x) - def isPosInfinity: Boolean = System.Single.IsPositiveInfinity(x) - def isNegInfinity: Boolean = System.Single.IsNegativeInfinity(x) - -} diff --git a/src/library/dotnet/scala/runtime/RichInt.scala b/src/library/dotnet/scala/runtime/RichInt.scala deleted file mode 100644 index fc5080f9b3..0000000000 --- a/src/library/dotnet/scala/runtime/RichInt.scala +++ /dev/null @@ -1,39 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -final class RichInt(start: Int) extends Proxy with Ordered[Int] { - - // Proxy - def self: Any = start - - // Ordered[Int] - def compare(that: Int): Int = if (start < that) -1 else if (start > that) 1 else 0 - - /** See Iterator.range. */ - def until(end: Int): Range = new Range(start, end, 1) - - /** See Iterator.range. */ - def until(end: Int, step: Int): Range = new Range(start, end, step) - - /** like until, but includes the last index */ - def to(end: Int) = new Range.Inclusive(start, end, 1) - - def min(that: Int): Int = if (start < that) start else that - def max(that: Int): Int = if (start > that) start else that - def abs: Int = if (start < 0) -start else start - - def toBinaryString: String = System.Convert.ToString(start, 2) - def toHexString: String = System.Convert.ToString(start, 16) - def toOctalString: String = System.Convert.ToString(start, 8) -} diff --git a/src/library/dotnet/scala/runtime/RichLong.scala b/src/library/dotnet/scala/runtime/RichLong.scala deleted file mode 100644 index 743b24a79f..0000000000 --- a/src/library/dotnet/scala/runtime/RichLong.scala +++ /dev/null @@ -1,30 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -final class RichLong(x: Long) extends Proxy with Ordered[Long] { - - // Proxy.self - def self: Any = x - - // Ordered[Long].compare - def compare(y: Long): Int = if (x < y) -1 else if (x > y) 1 else 0 - - def min(y: Long): Long = if (x < y) x else y - def max(y: Long): Long = if (x > y) x else y - def abs: Long = if (x < 0) -x else x - - def toBinaryString: String = System.Convert.ToString(x, 2) - def toHexString: String = System.Convert.ToString(x, 16) - def toOctalString: String = System.Convert.ToString(x, 8) -} diff --git a/src/library/dotnet/scala/runtime/RichString.scala b/src/library/dotnet/scala/runtime/RichString.scala deleted file mode 100644 index d94f7430c0..0000000000 --- a/src/library/dotnet/scala/runtime/RichString.scala +++ /dev/null @@ -1,196 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -import Predef._ - -final class RichString(val self: String) extends Proxy with RandomAccessSeq[Char] with Ordered[String] { - override def apply(n: Int) = self charAt n - override def length = self.length - override def toString = self - override def mkString = self - - override def slice(from: Int, until: Int): RichString = { - val len = self.length - new RichString( - if (from >= until || from >= len) - "" - else { - val from0 = if (from < 0) 0 else from - val until0 = if (until > len) len else until - self.substring(from0, until0) - } - ) - } - - //override def ++ [B >: A](that: Iterable[B]): Seq[B] = { - override def ++[B >: Char](that: Iterable[B]): RandomAccessSeq[B] = that match { - case that: RichString => new RichString(self + that.self) - case that => super.++(that) - } - - override def take(until: Int): RichString = slice(0, until) - - override def drop(from: Int): RichString = slice(from, self.length) - - override def startsWith[B](that: Seq[B]) = that match { - case that: RichString => self startsWith that.self - case that => super.startsWith(that) - } - - override def endsWith[B](that: Seq[B]) = that match { - case that: RichString => self endsWith that.self - case that => super.endsWith(that) - } - - override def indexOf[B](that: Seq[B]) = that match { - case that: RichString => self indexOf that.self - case that => super.indexOf(that) - } - - override def containsSlice[B](that: Seq[B]) = that match { - case that: RichString => self contains that.self - case that => super.containsSlice(that) - } - - override def reverse: RichString = { - val buf = new StringBuilder - var i = self.length - 1 - while (i >= 0) { - buf append (self charAt i) - i -= 1 - } - new RichString(buf.toString) - } - - override def compare(other: String) = self compareTo other - - private final val LF: Char = 0x0A - private final val FF: Char = 0x0C - private final val CR: Char = 0x0D - private final val SU: Char = 0x1A - - private def isLineBreak(c: Char) = c == LF || c == FF - - /**

- * Strip trailing line end character from this string if it has one. - * A line end character is one of - *

- * - *

- * If a line feed character LF is preceded by a carriage return CR - * (0x0D hex), the CR character is also stripped (Windows convention). - *

- */ - def stripLineEnd: String = { - val len = self.length - if (len == 0) self - else { - val last = apply(len - 1) - if (isLineBreak(last)) - self.substring(0, if (last == LF && len >= 2 && apply(len - 2) == CR) len - 2 else len - 1) - else - self - } - } - - /**

- * Return all lines in this string in an iterator, including trailing - * line end characters. - *

- *

- * The number of strings returned is one greater than the number of line - * end characters in this string. For an empty string, a single empty - * line is returned. A line end character is one of - *

- * - */ - def linesWithSeparators = new Iterator[String] { - val len = self.length - var index = 0 - def hasNext: Boolean = index < len - def next(): String = { - if (index >= len) throw new NoSuchElementException("next on empty iterator") - val start = index - while (index < len && !isLineBreak(apply(index))) index += 1 - index += 1 - self.substring(start, index min len) - } - } - - /** Return all lines in this string in an iterator, excluding trailing line - * end characters, i.e. apply .stripLineEnd to all lines - * returned by linesWithSeparators. - */ - def lines: Iterator[String] = - linesWithSeparators map (line => new RichString(line).stripLineEnd) - - /** Returns this string with first character converted to upper case */ - def capitalize: String = - if (self == null) null - else if (self.length == 0) "" - else { - val chars = self.toCharArray - chars(0) = chars(0).toUpperCase - new String(chars) - } - - /**

- * For every line in this string: - *

- *
- * Strip a leading prefix consisting of blanks or control characters - * followed by marginChar from the line. - *
- */ - def stripMargin(marginChar: Char): String = { - val buf = new StringBuilder - for (line <- linesWithSeparators) { - val len = line.length - var index = 0 - while (index < len && line.charAt(index) <= ' ') index += 1 - buf append - (if (index < len && line.charAt(index) == marginChar) line.substring(index + 1) else line) - } - buf.toString - } - - /**

- * For every line in this string: - *

- *
- * Strip a leading prefix consisting of blanks or control characters - * followed by | from the line. - *
- */ - def stripMargin: String = stripMargin('|') - - def split(separator: Char): Array[String] = self.Split(Array(separator)) - - def split(separators: Array[Char]): Array[String] = self.Split(separators) - - def toBoolean: Boolean = System.Boolean.Parse(self) - def toByte: Byte = System.Byte.Parse(self) - def toShort: Short = System.Int16.Parse(self) - def toInt: Int = System.Int32.Parse(self) - def toLong: Long = System.Int64.Parse(self) - def toFloat: Float = System.Single.Parse(self) - def toDouble: Double = System.Double.Parse(self) - -} diff --git a/src/library/dotnet/scala/runtime/Runnable.cs b/src/library/dotnet/scala/runtime/Runnable.cs deleted file mode 100644 index 74ab3ea16a..0000000000 --- a/src/library/dotnet/scala/runtime/Runnable.cs +++ /dev/null @@ -1,17 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - public interface Runnable { - void run(); - } - -} diff --git a/src/library/dotnet/scala/runtime/ShortRef.cs b/src/library/dotnet/scala/runtime/ShortRef.cs deleted file mode 100644 index 22f8f784e5..0000000000 --- a/src/library/dotnet/scala/runtime/ShortRef.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - [Serializable] - public class ShortRef { - public short elem; - public ShortRef(short elem) { this.elem = elem; } - override public string ToString() { return elem.ToString(); } - } - -} diff --git a/src/library/dotnet/scala/runtime/StringAdd.scala b/src/library/dotnet/scala/runtime/StringAdd.scala deleted file mode 100644 index 439b2f7f65..0000000000 --- a/src/library/dotnet/scala/runtime/StringAdd.scala +++ /dev/null @@ -1,28 +0,0 @@ -/* *\ -** ________ ___ __ ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ |_| ** -** ** -\* */ - -// $Id$ - - -package scala.runtime - - -import Predef._ - -final class StringAdd(self: Any) { - - def +(other: String) = self.toString + other - - /** Formats string according to given format string. - * Format strings are as for String.format (@see - * http://msdn2.microsoft.com/en-us/library/system.string.format(VS.71).aspx - * and http://www.codeproject.com/books/0735616485.asp). - */ - def formatted(format: String): String = - String.Format(format, Array(self.asInstanceOf[Object])) -} diff --git a/src/library/dotnet/scala/runtime/SymtabAttribute.cs b/src/library/dotnet/scala/runtime/SymtabAttribute.cs deleted file mode 100644 index b5608fe208..0000000000 --- a/src/library/dotnet/scala/runtime/SymtabAttribute.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -namespace scala.runtime { - - using System; - - public class SymtabAttribute : Attribute { - public byte[] symtab; - - public SymtabAttribute(byte[] symtab) { this.symtab = symtab; } - public SymtabAttribute() {} - } - -} diff --git a/src/library/dotnet/scala/util/DynamicVariable.scala b/src/library/dotnet/scala/util/DynamicVariable.scala deleted file mode 100644 index 101ebe9573..0000000000 --- a/src/library/dotnet/scala/util/DynamicVariable.scala +++ /dev/null @@ -1,83 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.util - - -import Predef._ -import System.Threading.Thread -import System.LocalDataStoreSlot - -/**

- * DynamicVariables provide a binding mechanism where the current - * value is found through dynamic scope, but where - * access to the variable itself is resolved through static - * scope. - *

- *

- * The current value can be retrieved with the - * value method. New values should be - * pushed using the withValue method. - * Values pushed via withValue only - * stay valid while the withValue's - * second argument, a parameterless closure, - * executes. When the second argument finishes, - * the variable reverts to the previous value. - *

- *

- * Usage of withValue looks like this: - *

- *
- *  someDynamicVariable.withValue(newValue) {
- *    // ... code called in here that calls value ...
- *    // ... will be given back the newValue ...
- *  }
- *  
- *

- * Each thread gets its own stack of bindings. When a - * new thread is created, the fluid gets a copy of - * the stack of bindings from the parent thread, and - * from then on the bindings for the new thread - * are independent of those for the original thread. - *

- * - * @author Lex Spoon - * @version 1.1, 2007-5-21 - */ -class DynamicVariable[T](init: T) { - private val slot: LocalDataStoreSlot = Thread.AllocateDataSlot() - value = init - - /** Retrieve the current value */ - def value: T = Thread.GetData(slot).asInstanceOf[T] - - /** Set the value of the fluid while executing the specified - * thunk. - * - * @param newval The value to which to set the fluid - * @param thunk The code to evaluate under the new setting - */ - def withValue[S](newval: T)(thunk: =>S): S = { - val oldval = value - value = newval - - try { thunk } finally { - value = oldval - } - } - - /** Change the currently bound value, discarding the old value. - * Usually withValue() gives better semantics. - */ - def value_=(newval: T) = { Thread.SetData(slot, newval.asInstanceOf[AnyRef]) } - - override def toString: String = "DynamicVariable(" + value +")" -} diff --git a/src/library/jvm/android/scala/ScalaObject.scala b/src/library/jvm/android/scala/ScalaObject.scala deleted file mode 100644 index 67b49cbe4e..0000000000 --- a/src/library/jvm/android/scala/ScalaObject.scala +++ /dev/null @@ -1,23 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import Predef._ - -trait ScalaObject extends AnyRef { - - /** This method is needed for optimizing pattern matching expressions - * which match on constructors of case classes. - */ - def $tag(): Int = 0 - -} diff --git a/src/library/jvm/cldc/scala/Array.scala b/src/library/jvm/cldc/scala/Array.scala deleted file mode 100644 index d0e0d68d7b..0000000000 --- a/src/library/jvm/cldc/scala/Array.scala +++ /dev/null @@ -1,430 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - - -import Predef._ -import compat.Platform.arraycopy - -/** This object contains utility methods operating on arrays. - * - * @author Martin Odersky - * @version 1.0 - */ -object Array { - - /** Copy one array to another. - * Equivalent to - * System.arraycopy(src, srcPos, dest, destPos, length), - * except that this works also for polymorphic and boxed arrays. - * - * @param src ... - * @param srcPos ... - * @param dest ... - * @param destPos ... - * @param length ... - */ - def copy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int): Unit = src match { - case xs: runtime.BoxedArray => - xs.copyTo(srcPos, dest, destPos, length) - case _ => - dest match { - case xs: runtime.BoxedArray => - xs.copyFrom(src, srcPos, destPos, length) - case _ => - arraycopy(src, srcPos, dest, destPos, length) - } - } - - /** Concatenate all argument arrays into a single array. - * - * @param xs ... - */ - def concat[T](xs: Array[T]*) = { - var len = 0 - for (x <- xs) len += x.length - val result = new Array[T](len) - var start = 0 - for (x <- xs) { - copy(x, 0, result, start, x.length) - start += x.length - } - result - } - - /** Create a an array containing of successive integers. - * - * @param from the value of the first element of the array - * @param end the value of the last element fo the array plus 1 - * @return the sorted array of all integers in range [from;end). - */ - def range(start: Int, end: Int): Array[Int] = { - val result = new Array[Int](end - start) - for (i <- start until end) result(i - start) = i - result - } - - /** Create an array with given elements. - * - * @param xs the elements to put in the array - * @return the array containing elements xs. - */ - def apply[A <: AnyRef](xs: A*): Array[A] = { - val array = new Array[A](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - -/* The following metod clashes with the previous one, and has therefore been - * removed. Note that this is a choice between efficiency and generality. - * The previous factory method is more efficient than the one that has been - * commented out. Since it is anyway possible to create a polymorphic array - * using - * new Array[T] - * it was preferred to restrict the definition of the factory method. - - def Array[A](xs: A*): Array[A] = { - val array = new Array[A](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } -*/ - - def apply(xs: Boolean*): Array[Boolean] = { - val array = new Array[Boolean](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - def apply(xs: Byte*): Array[Byte] = { - val array = new Array[Byte](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - def apply(xs: Short*): Array[Short] = { - val array = new Array[Short](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - def apply(xs: Char*): Array[Char] = { - val array = new Array[Char](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - def apply(xs: Int*): Array[Int] = { - val array = new Array[Int](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - def apply(xs: Long*): Array[Long] = { - val array = new Array[Long](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - def apply(xs: Unit*): Array[Unit] = { - val array = new Array[Unit](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - /** Create an array containing several copies of an element. - * - * @param n the length of the resulting array - * @param elem the element composing the resulting array - * @return an array composed of n elements all equal to elem - */ - def make[A](n: Int, elem: A): Array[A] = { - val a = new Array[A](n) - var i = 0 - while (i < n) { - a(i) = elem - i += 1 - } - a - } - - /** This method is called as a result of a pattern match { case Array(...) => } or val Array(...) = .... - * - * @param x the selector value - * @return array wrapped in an option - */ - def unapplySeq[A](x: Array[A]): Option[Seq[A]] = Some(x) - - trait Projection[A] extends RandomAccessSeq.MutableProjection[A] { - protected def newArray[B >: A](length : Int, elements : Iterator[A]) : Array[B] - override def toArray[B >: A] = (newArray(length, elements))//:Any).asInstanceOf[Array[B]] - override def force : Array[A] = toArray - override def drop( from: Int) = slice(from, length) - override def take(until: Int) = slice(0, until) - override def slice(from0 : Int, until0 : Int) : Projection[A] = new RandomAccessSeq.MutableSlice[A] with Projection[A] { - override def from = from0 - override def until = until0 - override def underlying = Projection.this - override protected def newArray[B >: A](length : Int, elements : Iterator[A]) = - underlying.newArray(length, elements) - override def slice(from0 : Int, until0 : Int) = - Projection.this.slice(from + from0, from + until0) - } - override def reverse : Projection[A] = new Projection[A] { - override protected def newArray[B >: A](length : Int, elements : Iterator[A]) = - Projection.this.newArray(length, elements) - def update(idx : Int, what : A) : Unit = Projection.this.update(length - idx - 1, what) - def length = Projection.this.length - def apply(idx : Int) = Projection.this.apply(length - idx - 1) - override def stringPrefix = Projection.this.stringPrefix + "R" - } - } - trait Array0[A] extends RandomAccessSeq.Mutable[A] { - override def projection : Projection[A] = throw new Error - override def slice(from : Int, until : Int) : Projection[A] = projection.slice(from, until) - override def take(until : Int) : Projection[A] = projection.take(until) - override def drop(from : Int) : Projection[A] = projection.drop(from) - override def reverse = projection.reverse - } -} - -/** This class represents polymorphic arrays. Array[T] is Scala's representation - * for Java's T[]. - * - * @author Martin Odersky - * @version 1.0 - */ -final class Array[A](_length: Int) extends Array.Array0[A] { - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int) = { - this(dim1); - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int) = { - this(dim1); - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int) = { - this(dim1); - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int) = { - this(dim1); - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int) = { - this(dim1); - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int) = { - this(dim1); - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int) = { - this(dim1); - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int, dim9: Int) = { - this(dim1); - throw new Error() - } - - /** The length of the array */ - def length: Int = throw new Error() - - /** The element at given index. - *

- * Indices start a 0; xs.apply(0) is the first - * element of array xs. - *

- *

- * Note the indexing syntax xs(i) is a shorthand for - * xs.apply(i). - *

- * - * @param i the index - * @throws ArrayIndexOutOfBoundsException if i < 0 or - * length <= i - */ - def apply(i: Int): A = throw new Error() - - /**

- * Update the element at given index. - *

- *

- * Indices start a 0; xs.apply(0) is the first - * element of array xs. - *

- *

- * Note the indexing syntax xs(i) = x is a shorthand - * for xs.update(i, x). - *

- * - * @param i the index - * @param x the value to be written at index i - * @throws ArrayIndexOutOfBoundsException if i < 0 or - * length <= i - */ - override def update(i: Int, x: A): Unit = throw new Error() - - /** An iterator returning the elements of this array, starting from 0. - */ - override def elements: Iterator[A] = throw new Error() - - /** @deprecated use slice(from,end).force instead */ - def subArray(from: Int, end: Int): Array[A] = throw new Error() - - /** Returns an array consisting of all elements of this array that satisfy the - * predicate p. The order of the elements is preserved. - * - * @param p the predicate used to filter the array. - * @return the elements of this array satisfying p. - */ - override def filter(p: A => Boolean): Array[A] = throw new Error() - - /** Returns the longest prefix of this array whose elements satisfy - * the predicate p. - * - * @param p the test predicate. - * @return the longest prefix of this array whose elements satisfy - * the predicate p. - */ - override def takeWhile(p: A => Boolean): Array[A] = throw new Error() - - /** Returns the longest suffix of this array whose first element - * does not satisfy the predicate p. - * - * @param p the test predicate. - * @return the longest suffix of the array whose first element - * does not satisfy the predicate p. - */ - override def dropWhile(p: A => Boolean): Array[A] = throw new Error() - - /** Returns an array consisting of all elements of this array followed - * by all elements of the argument iterable. - */ - override def ++[B >: A](that: Iterable[B]): Array[B] = throw new Error() - - /** Returns the array resulting from applying the given function f to each - * element of this array. - * - * @param f function to apply to each element. - * @return [f(a0), ..., f(an)] if this array is [a0, ..., an]. - */ - override def map[B](f: A => B): Array[B] = throw new Error() - - /** Applies the given function f to each element of - * this array, then concatenates the results. - * - * @param f the function to apply on each element. - * @return f(a0) ::: ... ::: f(an) if - * this array is [a0, ..., an]. - */ - override def flatMap[B](f: A => Iterable[B]): Array[B] = throw new Error() - - /** Returns an array formed from this array and the specified array - * that by associating each element of the former with - * the element at the same position in the latter. - * If one of the two arrays is longer than the other, its remaining elements are ignored. - * - * @return Array({a0,b0}, ..., - * {amin(m,n),bmin(m,n)}) when - * Array(a0, ..., am) - * zip Array(b0, ..., bn) is invoked. - */ - def zip[B](that: Array[B]): Array[Tuple2[A,B]] = throw new Error() - - /** Returns an array that pairs each element of this array - * with its index, counting from 0. - * - * @return the array Array({a0,0}, {a1,1},...) - * where ai are the elements of this stream. - */ - def zipWithIndex: Array[Tuple2[A,Int]] = throw new Error() - - /** Returns an array that contains all indices of this array */ - def indices: Array[Int] = throw new Error() - - /** - * @return a deep string representation of this array. - */ - def deepToString(): String = throw new Error() - - /**

- * Returns a string representation of this array object. The resulting string - * begins with the string start and is finished by the string - * end. Inside, the string representations of elements (w.r.t. - * the method deepToString()) are separated by the string - * sep. For example: - *

- *

- * Array(Array(1, 2), Array(3)).deepMkString("[", "; ", "]") = "[[1; 2]; [3]]" - *

- * - * @param start starting string. - * @param sep separator string. - * @param end ending string. - * @return a string representation of this array object. - */ - def deepMkString(start: String, sep: String, end: String): String = - throw new Error() - - /** Returns a string representation of this array object. The string - * representations of elements (w.r.t. the method deepToString()) - * are separated by the string sep. - * - * @param sep separator string. - * @return a string representation of this array object. - */ - def deepMkString(sep: String): String = throw new Error() - - /**

- * Returns true if the two specified arrays are - * deeply equal to one another. - *

- *

- * Two array references are considered deeply equal if both are null, - * or if they refer to arrays that contain the same number of elements - * and all corresponding pairs of elements in the two arrays are deeply - * equal. - *

- *

- * See also method deepEquals in the Java class - * java.utils.Arrays - *

- * - * @param that the second - * @return true iff both arrays are deeply equal. - */ - def deepEquals(that: Any): Boolean = throw new Error() - -} diff --git a/src/library/jvm/cldc/scala/Console.scala b/src/library/jvm/cldc/scala/Console.scala deleted file mode 100644 index 43fe2ae894..0000000000 --- a/src/library/jvm/cldc/scala/Console.scala +++ /dev/null @@ -1,96 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import java.io.{OutputStream, PrintStream} - -import Predef._ - - -/** The Console object implements functionality for - * printing Scala values on the terminal. There are also functions - * for reading specific values. Console also defines - * constants for marking up text on ANSI terminals. - * - * @author Matthias Zenger - * @version 1.0, 03/09/2003 - */ -object Console { - - // ANSI colors foreground - final val BLACK = "\033[30m" - final val RED = "\033[31m" - final val GREEN = "\033[32m" - final val YELLOW = "\033[33m" - final val BLUE = "\033[34m" - final val MAGENTA = "\033[35m" - final val CYAN = "\033[36m" - final val WHITE = "\033[37m" - - // ANSI colors background - final val BLACK_B = "\033[40m" - final val RED_B = "\033[41m" - final val GREEN_B = "\033[42m" - final val YELLOW_B = "\033[43m" - final val BLUE_B = "\033[44m" - final val MAGENTA_B = "\033[45m" - final val CYAN_B = "\033[46m" - final val WHITE_B = "\033[47m" - - // ANSI styles - final val RESET = "\033[0m" - final val BOLD = "\033[1m" - final val UNDERLINED = "\033[4m" - final val BLINK = "\033[5m" - final val REVERSED = "\033[7m" - final val INVISIBLE = "\033[8m" - - var out: PrintStream = java.lang.System.out - val err = java.lang.System.err - - /** Set the default output stream. - * - * @param out the new output stream. - */ - def setOut(out: PrintStream): Unit = this.out = out - - /** Set the default output stream. - * - * @param@ out the new output stream. - */ - def setOut(out: OutputStream): Unit = - setOut(new PrintStream(out)) - - /** Print an object on the terminal. - * - * @param obj the object to print. - */ - def print(obj: Any): Unit = - out.print(if (null == obj) "null" else obj.toString()) - - /** Flush the output stream. This function is required when partial - * output (i.e. output not terminated by a new line character) has - * to be made visible on the terminal. - */ - def flush(): Unit = out.flush() - - /** Print a new line character on the terminal. - */ - def println(): Unit = out.println() - - /** Print out an object followed by a new line character. - * - * @param x the object to print. - */ - def println(x: Any): Unit = out.println(x) - -} diff --git a/src/library/jvm/cldc/scala/List.scala b/src/library/jvm/cldc/scala/List.scala deleted file mode 100644 index 4f5693dc4f..0000000000 --- a/src/library/jvm/cldc/scala/List.scala +++ /dev/null @@ -1,1244 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import scala.collection.mutable.ListBuffer -import Predef._ - -/** This object provides methods for creating specialized lists, and for - * transforming special kinds of lists (e.g. lists of lists). - * - * @author Martin Odersky and others - * @version 1.0, 15/07/2003 - */ -object List { - - /** Create a list with given elements. - * - * @param xs the elements to put in the list - * @return the list containing elements xs. - */ - def apply[A](xs: A*): List[A] = xs.toList - - /** for unapply matching - */ - def unapplySeq[A](x: List[A]): Some[List[A]] = Some(x) - - /** Create a sorted list of all integers in a range. - * - * @param from the start value of the list - * @param end the end value of the list - * @return the sorted list of all integers in range [from;end). - */ - def range(from: Int, end: Int): List[Int] = - range(from, end, 1) - - /** Create a sorted list of all integers in a range. - * - * @param from the start value of the list - * @param end the end value of the list - * @param step the increment value of the list - * @return the sorted list of all integers in range [from;end). - */ - def range(from: Int, end: Int, step: Int): List[Int] = { - val b = new ListBuffer[Int] - var i = from - while (i < end) { - b += i - i += step - } - b.toList - } - - /** Create a sorted list of all integers in a range. - * - * @param from the start value of the list - * @param end the end value of the list - * @param step the increment function of the list - * @return the sorted list of all integers in range [from;end). - */ - def range(from: Int, end: Int, step: Int => Int): List[Int] = { - val b = new ListBuffer[Int] - var i = from - while (i < end) { - b += i - i += step(i) - } - b.toList - } - - /** Create a list containing several copies of an element. - * - * @param n the length of the resulting list - * @param elem the element composing the resulting list - * @return a list composed of n elements all equal to elem - */ - def make[A](n: Int, elem: A): List[A] = { - val b = new ListBuffer[A] - var i = 0 - while (i < n) { - b += elem - i += 1 - } - b.toList - } - - /** Create a list by applying a function to successive integers. - * - * @param n the length of the resulting list - * @param maker the procedure which, given an integer n, - * returns the nth element of the resulting list, where - * n is in interval [0;n). - * @return the list obtained by applying the maker function to - * successive integers from 0 to n (exclusive). - */ - def tabulate[A](n: Int, maker: Int => A): List[A] = { - val b = new ListBuffer[A] - var i = 0 - while (i < n) { - b += maker(i) - i += 1 - } - b.toList - } - - /** Concatenate all the elements of a given list of lists. - * - * @param xss the list of lists that are to be concatenated - * @return the concatenation of all the lists - */ - def flatten[A](xss: List[List[A]]): List[A] = concat(xss: _*) - - /** Concatenate all the argument lists into a single list. - * - * @param xss the lists that are to be concatenated - * @return the concatenation of all the lists - */ - def concat[A](xss: List[A]*): List[A] = { - val b = new ListBuffer[A] - for (xs <- xss) { - var xc = xs - while (!xc.isEmpty) { - b += xc.head - xc = xc.tail - } - } - b.toList - } - - /** Transforms a list of pair into a pair of lists. - * - * @param xs the list of pairs to unzip - * @return a pair of lists: the first list in the pair contains the list - */ - def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = { - val b1 = new ListBuffer[A] - val b2 = new ListBuffer[B] - var xc = xs - while (!xc.isEmpty) { - b1 += xc.head._1 - b2 += xc.head._2 - xc = xc.tail - } - (b1.toList, b2.toList) - } - - /** Converts an iterator to a list. - * - * @param it the iterator to convert - * @return a list that contains the elements returned by successive - * calls to it.next - */ - def fromIterator[A](it: Iterator[A]): List[A] = it.toList - - /** Converts an array into a list. - * - * @param arr the array to convert - * @return a list that contains the same elements than arr - * in the same order - */ - def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length) - - /** Converts a range of an array into a list. - * - * @param arr the array to convert - * @param start the first index to consider - * @param len the lenght of the range to convert - * @return a list that contains the same elements than arr - * in the same order - */ - def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = { - var res: List[A] = Nil - var i = start + len - while (i > start) { - i -= 1 - res = arr(i) :: res - } - res - } - - /** Parses a string which contains substrings separated by a - * separator character and returns a list of all substrings. - * - * @param str the string to parse - * @param separator the separator character - * @return the list of substrings - */ - def fromString(str: String, separator: Char): List[String] = { - var words: List[String] = Nil - var pos = str.length() - while (pos > 0) { - val pos1 = str.lastIndexOf(separator, pos - 1) - if (pos1 + 1 < pos) - words = str.substring(pos1 + 1, pos) :: words - pos = pos1 - } - words - } - - /** Returns the given string as a list of characters. - * - * @param str the string to convert. - * @return the string as a list of characters. - * @deprecated use str.toList instead - */ - @deprecated def fromString(str: String): List[Char] = - str.toList - - /** Returns the given list of characters as a string. - * - * @param xs the list to convert. - * @return the list in form of a string. - */ - def toString(xs: List[Char]): String = { - val sb = new StringBuilder() - var xc = xs - while (!xc.isEmpty) { - sb.append(xc.head) - xc = xc.tail - } - sb.toString() - } - - /** Like xs map f, but returns xs unchanged if function - * f maps all elements to themselves. - * - * @param xs ... - * @param f ... - * @return ... - */ - def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = { - def loop(ys: List[A]): List[A] = - if (ys.isEmpty) xs - else { - val head0 = ys.head - val head1 = f(head0) - if (head1 eq head0) { - loop(ys.tail) - } else { - val ys1 = head1 :: mapConserve(ys.tail)(f) - if (xs eq ys) ys1 - else { - val b = new ListBuffer[A] - var xc = xs - while (xc ne ys) { - b += xc.head - xc = xc.tail - } - b.prependToList(ys1) - } - } - } - loop(xs) - } - - /** Returns the list resulting from applying the given function f - * to corresponding elements of the argument lists. - * - * @param f function to apply to each pair of elements. - * @return [f(a0,b0), ..., f(an,bn)] if the lists are - * [a0, ..., ak], [b0, ..., bl] and - * n = min(k,l) - */ - def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = { - val b = new ListBuffer[C] - var xc = xs - var yc = ys - while (!xc.isEmpty && !yc.isEmpty) { - b += f(xc.head, yc.head) - xc = xc.tail - yc = yc.tail - } - b.toList - } - - /** Returns the list resulting from applying the given function - * f to corresponding elements of the argument lists. - * - * @param f function to apply to each pair of elements. - * @return [f(a0,b0,c0), - * ..., f(an,bn,cn)] - * if the lists are [a0, ..., ak], - * [b0, ..., bl], - * [c0, ..., cm] and - * n = min(k,l,m) - */ - def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = { - val b = new ListBuffer[D] - var xc = xs - var yc = ys - var zc = zs - while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) { - b += f(xc.head, yc.head, zc.head) - xc = xc.tail - yc = yc.tail - zc = zc.tail - } - b.toList - } - - /** Tests whether the given predicate p holds - * for all corresponding elements of the argument lists. - * - * @param p function to apply to each pair of elements. - * @return (p(a0,b0) && - * ... && p(an,bn))] - * if the lists are [a0, ..., ak]; - * [b0, ..., bl] - * and n = min(k,l) - */ - def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { - var xc = xs - var yc = ys - while (!xc.isEmpty && !yc.isEmpty) { - if (!f(xc.head, yc.head)) return false - xc = xc.tail - yc = yc.tail - } - true - } - - /** Tests whether the given predicate p holds - * for some corresponding elements of the argument lists. - * - * @param p function to apply to each pair of elements. - * @return n != 0 && (p(a0,b0) || - * ... || p(an,bn))] if the lists are - * [a0, ..., ak], - * [b0, ..., bl] and - * n = min(k,l) - */ - def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { - var xc = xs - var yc = ys - while (!xc.isEmpty && !yc.isEmpty) { - if (f(xc.head, yc.head)) return true - xc = xc.tail - yc = yc.tail - } - false - } - - /** Transposes a list of lists. - * pre: All element lists have the same length. - * - * @param xss the list of lists - * @return the transposed list of lists - */ - def transpose[A](xss: List[List[A]]): List[List[A]] = - if (xss.head.isEmpty) List() - else (xss map (xs => xs.head)) :: transpose(xss map (xs => xs.tail)) - - /** Lists with ordered elements are ordered - implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] { - def compare [b >: List[a] <% Ordered[b]](y: b): Int = y match { - case y1: List[a] => compareLists(x, y1); - case _ => -(y compare x) - } - private def compareLists(xs: List[a], ys: List[a]): Int = { - if (xs.isEmpty && ys.isEmpty) 0 - else if (xs.isEmpty) -1 - else if (ys.isEmpty) 1 - else { - val s = xs.head compare ys.head; - if (s != 0) s - else compareLists(xs.tail, ys.tail) - } - } - } - */ -} - -/** A class representing an ordered collection of elements of type - * a. This class comes with two implementing case - * classes scala.Nil and scala.:: that - * implement the abstract members isEmpty, - * head and tail. - * - * @author Martin Odersky and others - * @version 1.0, 16/07/2003 - */ -sealed abstract class List[+A] extends Seq[A] { - - /** Returns true if the list does not contain any elements. - * @return true, iff the list is empty. - */ - override def isEmpty: Boolean - - /** Returns this first element of the list. - * - * @return the first element of this list. - * @throws Predef.NoSuchElementException if the list is empty. - */ - def head: A - - /** returns length - l, without calling length - */ - override def lengthCompare(l: Int) = { - if (isEmpty) 0 - l - else if (l <= 0) 1 - else tail.lengthCompare(l - 1) - } - - /** Returns this list without its first element. - * - * @return this list without its first element. - * @throws Predef.NoSuchElementException if the list is empty. - */ - def tail: List[A] - - /**

- * Add an element x at the beginning of this list. - *

- * - * @param x the element to append. - * @return the list with x appended at the beginning. - * @ex 1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3) - */ - def ::[B >: A] (x: B): List[B] = - new scala.::(x, this) - - /**

- * Returns a list resulting from the concatenation of the given - * list prefix and this list. - *

- * - * @param prefix the list to concatenate at the beginning of this list. - * @return the concatenation of the two lists. - * @ex List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4) - */ - def :::[B >: A](prefix: List[B]): List[B] = - if (isEmpty) prefix - else { - val b = new ListBuffer[B] - var those = prefix - while (!those.isEmpty) { - b += those.head - those = those.tail - } - b.prependToList(this) - } - - /** Reverse the given prefix and append the current list to that. - * This function is equivalent to an application of reverse - * on the prefix followed by a call to :::, but more - * efficient (and tail recursive). - * - * @param prefix the prefix to reverse and then prepend - * @return the concatenation of the reversed prefix and the current list. - */ - def reverse_:::[B >: A](prefix: List[B]): List[B] = { - var these: List[B] = this - var pres = prefix - while (!pres.isEmpty) { - these = pres.head :: these - pres = pres.tail - } - these - } - - /** Returns the number of elements in the list. - * - * @return the number of elements in the list. - */ - def length: Int = { - var these = this - var len = 0 - while (!these.isEmpty) { - len += 1 - these = these.tail - } - len - } - - /** Creates a list with all indices in the list. This is - * equivalent to a call to List.range(0, xs.length). - * - * @return a list of all indices in the list. - */ - def indices: List[Int] = { - val b = new ListBuffer[Int] - var i = 0 - var these = this - while (!these.isEmpty) { - b += i - i += 1 - these = these.tail - } - b.toList - } - - /** Returns the elements in the list as an iterator - * - * @return an iterator on the list elements. - */ - override def elements: Iterator[A] = new Iterator[A] { - var these = List.this - def hasNext: Boolean = !these.isEmpty - def next: A = - if (!hasNext) - throw new NoSuchElementException("next on empty Iterator") - else { - val result = these.head; these = these.tail; result - } - override def toList: List[A] = these - } - - /** Overrides the method in Iterable for efficiency. - * - * @return the list itself - */ - override def toList: List[A] = this - - /** Returns the list without its last element. - * - * @return the list without its last element. - * @throws Predef.UnsupportedOperationException if the list is empty. - */ - def init: List[A] = - if (isEmpty) throw new UnsupportedOperationException("Nil.init") - else { - val b = new ListBuffer[A] - var elem = head - var next = tail - while (!next.isEmpty) { - b += elem - elem = next.head - next = next.tail - } - b.toList - } - - /** Returns the last element of this list. - * - * @return the last element of the list. - * @throws Predef.UnsupportedOperationException if the list is empty. - */ - override def last: A = - if (isEmpty) throw new Predef.NoSuchElementException("Nil.last") - else { - var cur = this - var next = this.tail - while (!next.isEmpty) { - cur = next - next = next.tail - } - cur.head - } - - /** Returns the n first elements of this list, or else the whole - * list, if it has less than n elements. - * - * @param n the number of elements to take. - * @return the n first elements of this list. - */ - override def take(n: Int): List[A] = { - val b = new ListBuffer[A] - var i = 0 - var these = this - while (!these.isEmpty && i < n) { - i += 1 - b += these.head - these = these.tail - } - if (these.isEmpty) this - else b.toList - } - - /** Returns the list with elements belonging to the given index range. - * - * @param start the start position of the list slice. - * @param end the end position (exclusive) of the list slice. - * @return the list with elements belonging to the given index range. - */ - override def slice(start: Int, end: Int): List[A] = { - val s = start max 0 - val e = end min this.length - drop(s) take (e - s) - } - - /** Returns the list without its n first elements. - * If this list has less than n elements, the empty list is returned. - * - * @param n the number of elements to drop. - * @return the list without its n first elements. - */ - override def drop(n: Int): List[A] = { - var these = this - var count = n - while (!these.isEmpty && count > 0) { - these = these.tail - count -= 1 - } - these - } - - /** Returns the rightmost n elements from this list. - * - * @param n the number of elements to take - * @return the suffix of length n of the list - */ - def takeRight(n: Int): List[A] = { - def loop(lead: List[A], lag: List[A]): List[A] = lead match { - case Nil => lag - case _ :: tail => loop(tail, lag.tail) - } - loop(drop(n), this) - } - - /** Returns the list wihout its rightmost n elements. - * - * @param n the number of elements to take - * @return the suffix of length n of the list - */ - def dropRight(n: Int): List[A] = { - def loop(lead: List[A], lag: List[A]): List[A] = lead match { - case Nil => Nil - case _ :: tail => lag.head :: loop(tail, lag.tail) - } - loop(drop(n), this) - } - - /** Split the list at a given point and return the two parts thus - * created. - * - * @param n the position at which to split - * @return a pair of lists composed of the first n - * elements, and the other elements. - */ - def splitAt(n: Int): (List[A], List[A]) = { - val b = new ListBuffer[A] - var i = 0 - var these = this - while (!these.isEmpty && i < n) { - i += 1 - b += these.head - these = these.tail - } - (b.toList, these) - } - - /** Returns the longest prefix of this list whose elements satisfy - * the predicate p. - * - * @param p the test predicate. - * @return the longest prefix of this list whose elements satisfy - * the predicate p. - */ - override def takeWhile(p: A => Boolean): List[A] = { - val b = new ListBuffer[A] - var these = this - while (!these.isEmpty && p(these.head)) { - b += these.head - these = these.tail - } - b.toList - } - - /** Returns the longest suffix of this list whose first element - * does not satisfy the predicate p. - * - * @param p the test predicate. - * @return the longest suffix of the list whose first element - * does not satisfy the predicate p. - */ - override def dropWhile(p: A => Boolean): List[A] = - if (isEmpty || !p(head)) this - else tail dropWhile p - - /** Returns the longest prefix of the list whose elements all satisfy - * the given predicate, and the rest of the list. - * - * @param p the test predicate - * @return a pair consisting of the longest prefix of the list whose - * elements all satisfy p, and the rest of the list. - */ - def span(p: A => Boolean): (List[A], List[A]) = { - val b = new ListBuffer[A] - var these = this - while (!these.isEmpty && p(these.head)) { - b += these.head - these = these.tail - } - (b.toList, these) - } - - /** Like span but with the predicate inverted. - */ - def break(p: A => Boolean): (List[A], List[A]) = span { x => !p(x) } - - /** Returns the n-th element of this list. The first element - * (head of the list) is at position 0. - * - * @param n index of the element to return - * @return the element at position n in this list. - * @throws Predef.NoSuchElementException if the list is too short. - */ - def apply(n: Int): A = drop(n).head - - /** Returns the list resulting from applying the given function f to each - * element of this list. - * - * @param f function to apply to each element. - * @return [f(a0), ..., f(an)] if this list is [a0, ..., an]. - */ - final override def map[B](f: A => B): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - b += f(these.head) - these = these.tail - } - b.toList - } - - /** Apply a function to all the elements of the list, and return the - * reversed list of results. This is equivalent to a call to map - * followed by a call to reverse, but more efficient. - * - * @param f the function to apply to each elements. - * @return the reversed list of results. - */ - def reverseMap[B](f: A => B): List[B] = { - def loop(l: List[A], res: List[B]): List[B] = l match { - case Nil => res - case head :: tail => loop(tail, f(head) :: res) - } - loop(this, Nil) - } - - /** Apply the given function f to each element of this list - * (while respecting the order of the elements). - * - * @param f the treatment to apply to each element. - */ - final override def foreach(f: A => Unit) { - var these = this - while (!these.isEmpty) { - f(these.head) - these = these.tail - } - } - - /** Returns all the elements of this list that satisfy the - * predicate p. The order of the elements is preserved. - * It is guarenteed that the receiver list itself is returned iff all its - * elements satisfy the predicate `p'. Hence the following equality is valid: - * - * (xs filter p) eq xs == xs forall p - * - * @param p the predicate used to filter the list. - * @return the elements of this list satisfying p. - */ - final override def filter(p: A => Boolean): List[A] = { - // return same list if all elements satisfy p - var these = this - while (!these.isEmpty && p(these.head)) { - these = these.tail - } - if (these.isEmpty) this - else { - val b = new ListBuffer[A] - var these1 = this - while (these1 ne these) { - b += these1.head - these1 = these1.tail - } - - these = these.tail // prevent the second evaluation of the predicate - // on the element on which it first failed - while (!these.isEmpty) { - if (p(these.head)) b += these.head - these = these.tail - } - b.toList - } - } - -// final def filterMap[B](f: PartialFunction[A, B]): List[B] = -// this filter f.isDefinedAt map f - - /** Removes all elements of the list which satisfy the predicate - * p. This is like filter with the - * predicate inversed. - * - * @param p the predicate to use to test elements - * @return the list without all elements which satisfy p - */ - def remove(p: A => Boolean): List[A] = filter (x => !p(x)) - - /** Partition the list in two sub-lists according to a predicate. - * - * @param p the predicate on which to partition - * @return a pair of lists: the list of all elements which satisfy - * p and the list of all elements which do not. - * The relative order of the elements in the sub-lists is the - * same as in the original list. - */ - override def partition(p: A => Boolean): (List[A], List[A]) = { - val btrue = new ListBuffer[A] - val bfalse = new ListBuffer[A] - var these = this - while (!these.isEmpty) { - (if (p(these.head)) btrue else bfalse) += these.head - these = these.tail - } - (btrue.toList, bfalse.toList) - } - - /**

- * Sort the list according to the comparison function - * <(e1: a, e2: a) => Boolean, - * which should be true iff e1 is smaller than - * e2. - *

- * - * @param lt the comparison function - * @return a list sorted according to the comparison function - * <(e1: a, e2: a) => Boolean. - * @ex
-   *    List("Steve", "Tom", "John", "Bob")
-   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
-   *    List("Bob", "John", "Steve", "Tom")
- */ - def sort(lt : (A,A) => Boolean): List[A] = { - /** Merge two already-sorted lists */ - def merge(l1: List[A], l2: List[A]): List[A] = { - val res = new ListBuffer[A] - var left1 = l1 - var left2 = l2 - - while (!left1.isEmpty && !left2.isEmpty) { - if(lt(left1.head, left2.head)) { - res += left1.head - left1 = left1.tail - } else { - res += left2.head - left2 = left2.tail - } - } - - res ++= left1 - res ++= left2 - - res.toList - } - - /** Split a list into two lists of about the same size */ - def split(lst: List[A]) = { - val res1 = new ListBuffer[A] - val res2 = new ListBuffer[A] - var left = lst - - while (!left.isEmpty) { - res1 += left.head - left = left.tail - if (!left.isEmpty) { - res2 += left.head - left = left.tail - } - } - - (res1.toList, res2.toList) - } - - - /** Merge-sort the specified list */ - def ms(lst: List[A]): List[A] = - lst match { - case Nil => lst - case x :: Nil => lst - case x :: y :: Nil => - if (lt(x,y)) - lst - else - y :: x :: Nil - - case lst => - val (l1, l2) = split(lst) - val l1s = ms(l1) - val l2s = ms(l2) - merge(l1s, l2s) - } - - ms(this) - } - - - /** Count the number of elements in the list which satisfy a predicate. - * - * @param p the predicate for which to count - * @return the number of elements satisfying the predicate p. - */ - def count(p: A => Boolean): Int = { - var cnt = 0 - var these = this - while (!these.isEmpty) { - if (p(these.head)) cnt += 1 - these = these.tail - } - cnt - } - - /** Tests if the predicate p is satisfied by all elements - * in this list. - * - * @param p the test predicate. - * @return true iff all elements of this list satisfy the - * predicate p. - */ - override def forall(p: A => Boolean): Boolean = { - var these = this - while (!these.isEmpty) { - if (!p(these.head)) return false - these = these.tail - } - true - } - - /** Tests the existence in this list of an element that satisfies the - * predicate p. - * - * @param p the test predicate. - * @return true iff there exists an element in this list that - * satisfies the predicate p. - */ - override def exists(p: A => Boolean): Boolean = { - var these = this - while (!these.isEmpty) { - if (p(these.head)) return true - these = these.tail - } - false - } - - /** Find and return the first element of the list satisfying a - * predicate, if any. - * - * @param p the predicate - * @return the first element in the list satisfying p, - * or None if none exists. - */ - override def find(p: A => Boolean): Option[A] = { - var these = this - while (!these.isEmpty) { - if (p(these.head)) return Some(these.head) - these = these.tail - } - None - } - - /** Combines the elements of this list together using the binary - * function f, from left to right, and starting with - * the value z. - * - * @return f(... (f(f(z, a0), a1) ...), - * an) if the list is - * [a0, a1, ..., an]. - */ - override def foldLeft[B](z: B)(f: (B, A) => B): B = { - var acc = z - var these = this - while (!these.isEmpty) { - acc = f(acc, these.head) - these = these.tail - } - acc - } - - /** Combines the elements of this list together using the binary - * function f, from right to left, and starting with - * the value z. - * - * @return f(a0, f(a1, f(..., f(an, z)...))) - * if the list is [a0, a1, ..., an]. - */ - override def foldRight[B](z: B)(f: (A, B) => B): B = this match { - case Nil => z - case x :: xs => f(x, xs.foldRight(z)(f)) - } - - /** Combines the elements of this list together using the binary - * operator op, from left to right - * @param op The operator to apply - * @return op(... op(a0,a1), ..., an) - if the list has elements - * a0, a1, ..., an. - * @throws Predef.UnsupportedOperationException if the list is empty. - */ - override def reduceLeft[B >: A](f: (B, B) => B): B = this match { - case Nil => throw new UnsupportedOperationException("Nil.reduceLeft") - case x :: xs => ((xs: List[B]) foldLeft (x: B))(f) - } - - /** Combines the elements of this list together using the binary - * operator op, from right to left - * @param op The operator to apply - * - * @return a0 op (... op (an-1 op an)...) - * if the list has elements a0, a1, ..., - * an. - * - * @throws Predef.UnsupportedOperationException if the list is empty. - */ - override def reduceRight[B >: A](f: (B, B) => B): B = this match { - case Nil => throw new UnsupportedOperationException("Nil.reduceRight") - case x :: Nil => x: B - case x :: xs => f(x, xs reduceRight f) - } - - /** Applies the given function f to each element of - * this list, then concatenates the results. - * - * @param f the function to apply on each element. - * @return f(a0) ::: ... ::: f(an) if - * this list is [a0, ..., an]. - */ - final override def flatMap[B](f: A => Iterable[B]): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - var those = f(these.head).elements - while (those.hasNext) { - b += those.next - } - these = these.tail - } - b.toList - } - - /** A list consisting of all elements of this list in reverse order. - */ - override def reverse: List[A] = { - var result: List[A] = Nil - var these = this - while (!these.isEmpty) { - result = these.head :: result - these = these.tail - } - result - } - - /** Returns a list formed from this list and the specified list - * that by associating each element of the former with - * the element at the same position in the latter. - * If one of the two lists is longer than the other, its remaining elements are ignored. - * - * @return List((a0,b0), ..., - * (amin(m,n),bmin(m,n))) when - * List(a0, ..., am) - * zip List(b0, ..., bn) is invoked. - */ - def zip[B](that: List[B]): List[(A, B)] = { - val b = new ListBuffer[(A, B)] - var these = this - var those = that - while (!these.isEmpty && !those.isEmpty) { - b += (these.head, those.head) - these = these.tail - those = those.tail - } - b.toList - } - - /** Returns a list that pairs each element of this list - * with its index, counting from 0. - * - * @return the list List((a0,0), (a1,1), ...) - * where ai are the elements of this list. - */ - def zipWithIndex: List[(A, Int)] = { - val b = new ListBuffer[(A, Int)] - var these = this - var idx = 0 - - while(!these.isEmpty) { - b += (these.head, idx) - these = these.tail - idx += 1 - } - - b.toList - } - - /** Returns a list formed from this list and the specified list - * that by associating each element of the former with - * the element at the same position in the latter. - * - * @param that list that may have a different length - * as the self list. - * @param thisElem element thisElem is used to fill up the - * resulting list if the self list is shorter than - * that - * @param thatElem element thatElem is used to fill up the - * resulting list if that is shorter than - * the self list - * @return List((a0,b0), ..., - * (an,bn), (elem,bn+1), - * ..., {elem,bm}) - * when [a0, ..., an] zip - * [b0, ..., bm] is - * invoked where m > n. - */ - def zipAll[B, C >: A, D >: B](that: List[B], thisElem: C, thatElem: D): List[(C, D)] = { - val b = new ListBuffer[(C, D)] - var these = this - var those = that - while (!these.isEmpty && !those.isEmpty) { - b += (these.head, those.head) - these = these.tail - those = those.tail - } - while (!these.isEmpty) { - b += (these.head, thatElem) - these = these.tail - } - while (!those.isEmpty) { - b += (thisElem, those.head) - those = those.tail - } - b.toList - } - - /** Computes the union of this list and the given list - * that. - * - * @param that the list of elements to add to the list. - * @return a list without doubles containing the elements of this - * list and those of the given list that. - */ - def union[B >: A](that: List[B]): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - if (!that.contains(these.head)) b += these.head - these = these.tail - } - b.prependToList(that) - } - - /** Computes the difference between this list and the given list - * that. - * - * @param that the list of elements to remove from this list. - * @return this list without the elements of the given list - * that. - */ - def diff[B >: A](that: List[B]): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - if (!that.contains(these.head)) b += these.head - these = these.tail - } - b.toList - } - - def flatten[B](implicit f : A => Iterable[B]) : List[B] = { - val buf = new ListBuffer[B] - foreach(f(_).foreach(buf += _)) - buf.toList - } - - - /** Computes the intersection between this list and the given list - * that. - * - * @param that the list to intersect. - * @return the list of elements contained both in this list and - * in the given list that. - */ - def intersect[B >: A](that: List[B]): List[B] = filter(x => that contains x) - - /** Removes redundant elements from the list. Uses the method == - * to decide if two elements are identical. - * - * @return the list without doubles. - */ - def removeDuplicates: List[A] = { - val b = new ListBuffer[A] - var these = this - while (!these.isEmpty) { - if (!these.tail.contains(these.head)) b += these.head - these = these.tail - } - b.toList - } - - override protected def stringPrefix = "List" - override def projection = toStream - override def toStream : Stream[A] = new Stream.Definite[A] { - override def force : List[A] = List.this - override def isEmpty = List.this.isEmpty - override def head = List.this.head - override def tail = List.this.tail.toStream - protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = if (!isEmpty) { - var prefix0 = prefix - var buf1 = buf.append(prefix0).append(head) - prefix0 = ", " - var tail0 = tail - while (!tail0.isEmpty) { - buf1 = buf.append(prefix0).append(tail0.head) - tail0 = tail0.tail - } - buf1 - } else buf - } - -} - -/** The empty list. - * - * @author Martin Odersky - * @version 1.0, 15/07/2003 - */ -@SerialVersionUID(0 - 8256821097970055419L) -case object Nil extends List[Nothing] { - override def isEmpty = true - def head: Nothing = - throw new NoSuchElementException("head of empty list") - def tail: List[Nothing] = - throw new NoSuchElementException("tail of empty list") -} - -/** A non empty list characterized by a head and a tail. - * - * @author Martin Odersky - * @version 1.0, 15/07/2003 - */ -@SerialVersionUID(0L - 8476791151983527571L) -final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] { - def head : B = hd - def tail : List[B] = tl - override def isEmpty: Boolean = false -} - diff --git a/src/library/jvm/cldc/scala/Math.scala b/src/library/jvm/cldc/scala/Math.scala deleted file mode 100644 index d33613efd6..0000000000 --- a/src/library/jvm/cldc/scala/Math.scala +++ /dev/null @@ -1,56 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -/** The object Math contains methods for performing basic numeric - * operations such as the elementary exponential, logarithm, square root, and - * trigonometric functions. - */ -object Math { - - /** The smalles possible value for scala.Byte. */ - val MIN_BYTE = java.lang.Byte.MIN_VALUE - /** The greatest possible value for scala.Byte. */ - val MAX_BYTE = java.lang.Byte.MAX_VALUE - - /** The smalles possible value for scala.Short. */ - val MIN_SHORT = java.lang.Short.MIN_VALUE - /** The greatest possible value for scala.Short. */ - val MAX_SHORT = java.lang.Short.MAX_VALUE - - /** The smalles possible value for scala.Char. */ - val MIN_CHAR = java.lang.Character.MIN_VALUE - /** The greatest possible value for scala.Char. */ - val MAX_CHAR = java.lang.Character.MAX_VALUE - - /** The smalles possible value for scala.Int. */ - val MIN_INT = java.lang.Integer.MIN_VALUE - /** The greatest possible value for scala.Int. */ - val MAX_INT = java.lang.Integer.MAX_VALUE - - /** The smalles possible value for scala.Long. */ - val MIN_LONG = java.lang.Long.MIN_VALUE - /** The greatest possible value for scala.Long. */ - val MAX_LONG = java.lang.Long.MAX_VALUE - - - def abs(x: Int): Int = java.lang.Math.abs(x) - def abs(x: Long): Long = java.lang.Math.abs(x) - - def max(x: Int, y: Int): Int = java.lang.Math.max(x, y) - def max(x: Long, y: Long): Long = java.lang.Math.max(x, y) - - def min(x: Int, y: Int): Int = java.lang.Math.min(x, y) - def min(x: Long, y: Long): Long = java.lang.Math.min(x, y) - - def sqrt(x: Int): Int = runtime.SquareRoot.accurateSqrt(x) -} diff --git a/src/library/jvm/cldc/scala/Predef.scala b/src/library/jvm/cldc/scala/Predef.scala deleted file mode 100644 index 385541a71a..0000000000 --- a/src/library/jvm/cldc/scala/Predef.scala +++ /dev/null @@ -1,285 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - - -/** The Predef object provides definitions that are - * accessible in all Scala compilation units without explicit - * qualification. - */ -object Predef { - - // classOf dummy ------------------------------------------------------ - - /** Return the runtime representation of a class type. */ - def classOf[T]: Class[T] = null - - // aliases ------------------------------------------------------------ - - type byte = scala.Byte - type short = scala.Short - type char = scala.Char - type int = scala.Int - type long = scala.Long - type boolean = scala.Boolean - type unit = scala.Unit - - /** @deprecated use Int instead */ - @deprecated type Integer = java.lang.Integer - /** @deprecated use Char instead */ - @deprecated type Character = java.lang.Character - - type String = java.lang.String - type Class[T] = java.lang.Class[T] - type Runnable = java.lang.Runnable - - type Throwable = java.lang.Throwable - type Exception = java.lang.Exception - type Error = java.lang.Error - - type AssertionError = java.lang.Error - type RuntimeException = java.lang.RuntimeException - type NullPointerException = java.lang.NullPointerException - type ClassCastException = java.lang.ClassCastException - type IndexOutOfBoundsException = java.lang.IndexOutOfBoundsException - type ArrayIndexOutOfBoundsException = java.lang.ArrayIndexOutOfBoundsException - type StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException - type UnsupportedOperationException = RuntimeException //java.lang.UnsupportedOperationException - type IllegalArgumentException = java.lang.IllegalArgumentException - type NoSuchElementException = java.util.NoSuchElementException - type NumberFormatException = java.lang.NumberFormatException - - // miscelleaneous ----------------------------------------------------- - - //val $scope = scala.xml.TopScope - - type Function[-A, +B] = Function1[A, B] - - type Map[A, B] = collection.immutable.Map[A, B] - type Set[A] = collection.immutable.Set[A] - - val Map = collection.immutable.Map - val Set = collection.immutable.Set - - // errors and asserts ------------------------------------------------- - - def error(message: String): Nothing = throw new Error(message) - - def exit: Nothing = exit(0) - - def exit(status: Int): Nothing = { - java.lang.System.exit(status) - throw new Throwable() - } - - def assert(assertion: Boolean) { - if (!assertion) - throw new AssertionError("assertion failed") - } - - def assert(assertion: Boolean, message: Any) { - if (!assertion) - throw new AssertionError("assertion failed: " + message) - } - - def assume(assumption: Boolean) { - if (!assumption) - throw new IllegalArgumentException("assumption failed") - } - - def assume(assumption: Boolean, message: Any) { - if (!assumption) - throw new IllegalArgumentException("assumption failed: " + message) - } - - // tupling ------------------------------------------------------------ - - type Pair[+A, +B] = Tuple2[A, B] - object Pair { - def apply[A, B](x: A, y: B) = Tuple2(x, y) - def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x) - } - - type Triple[+A, +B, +C] = Tuple3[A, B, C] - object Triple { - def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z) - def unapply[A, B, C](x: Tuple3[A, B, C]): Option[Tuple3[A, B, C]] = Some(x) - } - - class ArrowAssoc[A](x: A) { - def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y) - } - implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x) - - def Tuple[A1](x1: A1) = Tuple1(x1) - def Tuple[A1, A2](x1: A1, x2: A2) = Tuple2(x1, x2) - def Tuple[A1, A2, A3](x1: A1, x2: A2, x3: A3) = Tuple3(x1, x2, x3) - def Tuple[A1, A2, A3, A4](x1: A1, x2: A2, x3: A3, x4: A4) = Tuple4(x1, x2, x3, x4) - def Tuple[A1, A2, A3, A4, A5](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5) = Tuple5(x1, x2, x3, x4, x5) - def Tuple[A1, A2, A3, A4, A5, A6](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6) = Tuple6(x1, x2, x3, x4, x5, x6) - def Tuple[A1, A2, A3, A4, A5, A6, A7](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7) = Tuple7(x1, x2, x3, x4, x5, x6, x7) - def Tuple[A1, A2, A3, A4, A5, A6, A7, A8](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8) = Tuple8(x1, x2, x3, x4, x5, x6, x7, x8) - def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9) = Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9) - - // printing and reading ----------------------------------------------- - - def print(x: Any) = Console.print(x) - def println() = Console.println() - def println(x: Any) = Console.println(x) - - // views -------------------------------------------------------------- - - implicit def identity[A](x: A): A = x - - implicit def byteWrapper(x: Byte) = new runtime.RichByte(x) - implicit def shortWrapper(x: Short) = new runtime.RichShort(x) - implicit def intWrapper(x: Int) = new runtime.RichInt(x) - implicit def charWrapper(c: Char) = new runtime.RichChar(c) - implicit def longWrapper(x: Long) = new runtime.RichLong(x) - - implicit def booleanWrapper(x: Boolean) = new runtime.RichBoolean(x) - - implicit def stringWrapper(x: String) = new runtime.RichString(x) - implicit def stringBuilderWrapper(x : StringBuilder) = new runtime.RichStringBuilder(x) - - implicit def any2stringadd(x: Any) = new runtime.StringAdd(x) - - implicit def exceptionWrapper(exc: Throwable) = new runtime.RichException(exc) - - implicit def unit2ordered(x: Unit): Ordered[Unit] = new Ordered[Unit] with Proxy { - def self: Any = x - def compare(y: Unit): Int = 0 - } - - implicit def iterable2ordered[A <% Ordered[A]](xs: Iterable[A]): Ordered[Iterable[A]] = - new Ordered[Iterable[A]] with Proxy { - val self = xs - def compare(that: Iterable[A]): Int = { - var res = 0 - val these = xs.elements - val those = that.elements - while (res == 0 && these.hasNext) - res = if (those.hasNext) these.next compare those.next else 1 - if (res == 0) { - if (those.hasNext) -1 else 0 - } else - res - } - } - - implicit def tuple22ordered[A1 <% Ordered[A1], A2 <% Ordered[A2]](x: Tuple2[A1, A2]): Ordered[Tuple2[A1, A2]] = - new Ordered[Tuple2[A1, A2]] with Proxy { - val self = x - def compare(y: Tuple2[A1, A2]): Int = { - val res = x._1 compare y._1 - if (res == 0) x._2 compare y._2 - else res - } - } - - implicit def tuple32ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3]](x: Tuple3[A1, A2, A3]): Ordered[Tuple3[A1, A2, A3]] = - new Ordered[Tuple3[A1, A2, A3]] with Proxy { - val self = x - def compare(y: Tuple3[A1, A2, A3]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple2(x._2, x._3) compare Tuple2(y._2, y._3) - else res - } - } - - implicit def tuple42ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4]](x: Tuple4[A1, A2, A3, A4]): Ordered[Tuple4[A1, A2, A3, A4]] = - new Ordered[Tuple4[A1, A2, A3, A4]] with Proxy { - val self = x - def compare(y: Tuple4[A1, A2, A3, A4]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple3(x._2, x._3, x._4) compare Tuple3(y._2, y._3, y._4) - else res - } - } - - implicit def tuple52ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5]](x: Tuple5[A1, A2, A3, A4, A5]): Ordered[Tuple5[A1, A2, A3, A4, A5]] = - new Ordered[Tuple5[A1, A2, A3, A4, A5]] with Proxy { - val self = x - def compare(y: Tuple5[A1, A2, A3, A4, A5]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple4(x._2, x._3, x._4, x._5) compare Tuple4(y._2, y._3, y._4, y._5) - else res - } - } - - implicit def tuple62ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6]](x: Tuple6[A1, A2, A3, A4, A5, A6]): Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] = - new Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] with Proxy { - val self = x - def compare(y: Tuple6[A1, A2, A3, A4, A5, A6]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple5(x._2, x._3, x._4, x._5, x._6) compare Tuple5(y._2, y._3, y._4, y._5, y._6) - else res - } - } - - implicit def tuple72ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7]](x: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] = - new Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] with Proxy { - val self = x - def compare(y: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple6(x._2, x._3, x._4, x._5, x._6, x._7) compare Tuple6(y._2, y._3, y._4, y._5, y._6, y._7) - else res - } - } - - implicit def tuple82ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8]](x: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] = - new Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] with Proxy { - val self = x - def compare(y: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple7(x._2, x._3, x._4, x._5, x._6, x._7, x._8) compare Tuple7(y._2, y._3, y._4, y._5, y._6, y._7, y._8) - else res - } - } - - implicit def tuple92ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8], A9 <% Ordered[A9]](x: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] = - new Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] with Proxy { - val self = x - def compare(y: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple8(x._2, x._3, x._4, x._5, x._6, x._7, x._8, x._9) compare Tuple8(y._2, y._3, y._4, y._5, y._6, y._7, y._8, y._9) - else res - } - } - - implicit def byte2short(x: Byte): Short = x.toShort - implicit def byte2int(x: Byte): Int = x.toInt - implicit def byte2long(x: Byte): Long = x.toLong - - implicit def short2int(x: Short): Int = x.toInt - implicit def short2long(x: Short): Long = x.toLong - - implicit def char2int(x: Char): Int = x.toInt - implicit def char2long(x: Char): Long = x.toLong - - implicit def int2long(x: Int): Long = x.toLong - - implicit def byte2Byte(x: Byte) = new java.lang.Byte(x) - implicit def short2Short(x: Short) = new java.lang.Short(x) - implicit def char2Character(x: Char) = new java.lang.Character(x) - implicit def int2Integer(x: Int) = new java.lang.Integer(x) - implicit def long2Long(x: Long) = new java.lang.Long(x) - implicit def boolean2Boolean(x: Boolean) = new java.lang.Boolean(x) - - /** any array projection can be automatically converted into an array */ - implicit def forceArrayProjection[A](x: Array.Projection[A]): Array[A] = x.force - /** any random access character seq (including rich string can be converted into a string */ - implicit def forceRandomAccessCharSeq(x: runtime.RichString): String = x.mkString - - def currentThread = java.lang.Thread.currentThread() - -} diff --git a/src/library/jvm/cldc/scala/Random.scala b/src/library/jvm/cldc/scala/Random.scala deleted file mode 100644 index 9168166752..0000000000 --- a/src/library/jvm/cldc/scala/Random.scala +++ /dev/null @@ -1,41 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -/** (see http://java.sun.com/javame/reference/apis/jsr030/) - * - * @author Stephane Micheloud - */ -class Random(val self: java.util.Random) { - - /** Creates a new random number generator using a single long seed. */ - def this(seed: Long) = this(new java.util.Random(seed)) - - /** Creates a new random number generator using a single integer seed. */ - def this(seed: Int) = this(seed.toLong) - - /** Creates a new random number generator. */ - def this() = this(compat.Platform.currentTime) - - /** Returns the next pseudorandom, uniformly distributed int value - * from this random number generator's sequence. - */ - def nextInt(): Int = self.nextInt() - - /** Returns the next pseudorandom, uniformly distributed long value - * from this random number generator's sequence. - */ - def nextLong(): Long = self.nextLong() - - def setSeed(seed: Long) { self.setSeed(seed) } - -} diff --git a/src/library/jvm/cldc/scala/StringBuilder.scala b/src/library/jvm/cldc/scala/StringBuilder.scala deleted file mode 100644 index eab003d33c..0000000000 --- a/src/library/jvm/cldc/scala/StringBuilder.scala +++ /dev/null @@ -1,862 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import Predef._ - -/**

- * A mutable sequence of characters. This class provides an API compatible - * with java.lang.StringBuilder, but with no guarantee of - * synchronization. - *

- * - * @author Stephane Micheloud - * @version 1.0 - */ -final class StringBuilder(initCapacity: Int, private val initValue: String) -extends (Int => Char) with Proxy { - if (initCapacity < 0) throw new IllegalArgumentException - if (initValue eq null) throw new NullPointerException - - /** The value is used for character storage. */ - private var value = new Array[Char](initCapacity + initValue.length) - - /** The count is the number of characters used. */ - private var count: Int = 0 - - /** Constructs a string builder with no characters in it and an - * initial capacity of 16 characters. - */ - def this() = this(16, "") - - /** Constructs a string builder with no characters in it and an - * initial capacity specified by the capacity argument. - * - * @param capacity the initial capacity. - * @throws NegativeArraySizeException if the capacity - * argument is less than 0. - */ - def this(capacity: Int) = this(capacity, "") - - def this(str: String) = this(16, str) - - append(initValue) - - def self = this - - def toArray: Array[Char] = value - - def length: Int = count - - def length_=(n: Int) { setLength(n) } - - /** Sets the length of the character sequence. - * - * @param newLength the new length - * @throws IndexOutOfBoundsException if the n argument is negative. - */ - def setLength(n: Int) { - if (n < 0) - throw new StringIndexOutOfBoundsException(n) - if (n > value.length) expandCapacity(n) - if (count < n) - while (count < n) { - value(count) = '\0'; count += 1 - } - else - count = n - } - - /** Returns the current capacity. The capacity is the amount of storage - * available for newly inserted characters, beyond which an allocation - * will occur. - * - * @return the current capacity - */ - def capacity: Int = value.length - - /** Same as ensureCapacity. */ - def capacity_=(n: Int) { ensureCapacity(n) } - - /**

- * Ensures that the capacity is at least equal to the specified minimum. - * If the current capacity is less than the argument, then a new internal - * array is allocated with greater capacity. The new capacity is the larger of: - *

- * - *

- * If the n argument is non-positive, this - * method takes no action and simply returns. - *

- * - * @param n the minimum desired capacity. - */ - def ensureCapacity(n: Int) { - if (n > value.length) expandCapacity(n) - } - - private def expandCapacity(n: Int) { - val newCapacity = (value.length + 1) * 2 - value = StringBuilder.copyOf( - value, - if (newCapacity < 0) Math.MAX_INT else if (n > newCapacity) n else newCapacity - ) - } - - /**

- * Returns the Char value in this sequence at the specified index. - * The first Char value is at index 0, the next at index - * 1, and so on, as in array indexing. - *

- *

- * The index argument must be greater than or equal to - * 0, and less than the length of this sequence. - *

- * - * @param index the index of the desired Char value. - * @return the Char value at the specified index. - * @throws IndexOutOfBoundsException if index is - * negative or greater than or equal to length(). - */ - def charAt(index: Int): Char = { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException(index) - value(index) - } - - /** Same as charAt. */ - def apply(i: Int): Char = charAt(i) - - /**

- * Removes the Char at the specified position in this - * sequence. This sequence is shortened by one Char. - *

- * - * @param index Index of Char to remove - * @return This object. - * @throws StringIndexOutOfBoundsException if the index - * is negative or greater than or equal to length(). - */ - def deleteCharAt(index: Int): StringBuilder = { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException(index) - compat.Platform.arraycopy(value, index + 1, value, index, count - index - 1) - count -= 1 - this - } - - /**

- * The character at the specified index is set to ch. This - * sequence is altered to represent a new character sequence that is - * identical to the old character sequence, except that it contains the - * character ch at position index. - *

- *

- * The index argument must be greater than or equal to - * 0, and less than the length of this sequence. - *

- * - * @param index the index of the character to modify. - * @param ch the new character. - * @throws IndexOutOfBoundsException if index is - * negative or greater than or equal to length(). - */ - def setCharAt(index: Int, c: Char) { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException(index) - value(index) = c - } - - /** Same as setCharAt. */ - def update(i: Int, c: Char) { setCharAt(i, c) } - - /** Returns a new String that contains a subsequence of - * characters currently contained in this character sequence. The - * substring begins at the specified index and extends to the end of - * this sequence. - * - * @param start The beginning index, inclusive. - * @return The new string. - * @throws StringIndexOutOfBoundsException if start is - * less than zero, or greater than the length of this object. - */ - def substring(start: Int): String = substring(start, count) - - /** Returns a new String that contains a subsequence of - * characters currently contained in this sequence. The - * substring begins at the specified start and - * extends to the character at index end - 1. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @return The new string. - * @throws StringIndexOutOfBoundsException if start - * or end are negative or greater than - * length(), or start is - * greater than end. - */ - def substring(start: Int, end: Int): String = { - if (start < 0) - throw new StringIndexOutOfBoundsException(start) - if (end > count) - throw new StringIndexOutOfBoundsException(end) - if (start > end) - throw new StringIndexOutOfBoundsException(end - start) - new String(value, start, end - start) - } - - /**

- * Appends the string representation of the Any - * argument. - *

- *

- * The argument is converted to a string as if by the method - * String.valueOf, and the characters of that - * string are then appended to this sequence. - *

- * - * @param x an Any object. - * @return a reference to this object. - */ - def append(x: Any): StringBuilder = - append(String.valueOf(x)) - - /** Appends the specified string to this character sequence. - * - * @param s a string. - * @return a reference to this object. - */ - def append(s: String): StringBuilder = { - val str = if (s == null) "null" else s - val len = str.length - if (len > 0) { - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(str.toCharArray, 0, value, count, len) - count = newCount - } - this - } - - /** Appends the specified string builder to this sequence. - * - * @param sb - * @return - */ - def append(sb: StringBuilder): StringBuilder = - if (sb == null) - append("null") - else { - val len = sb.length - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(sb.toArray, 0, value, count, len) - count = newCount - this - } - - /**

- * Appends the string representation of the Char sequence - * argument to this sequence. - *

- *

- * The characters of the sequence argument are appended, in order, - * to the contents of this sequence. The length of this sequence - * increases by the length of the argument. - *

- * - * @param x the characters to be appended. - * @return a reference to this object. - */ - def append(x: Seq[Char]): StringBuilder = - append(x.toArray, 0, x.length) - - /**

- * Appends the string representation of the Char array - * argument to this sequence. - *

- *

- * The characters of the array argument are appended, in order, to - * the contents of this sequence. The length of this sequence - * increases by the length of the argument. - *

- * - * @param x the characters to be appended. - * @return a reference to this object. - */ - def append(x: Array[Char]): StringBuilder = - append(x, 0, x.length) - - /**

- * Appends the string representation of a subarray of the - * char array argument to this sequence. - *

- *

- * Characters of the Char array x, starting at - * index offset, are appended, in order, to the contents - * of this sequence. The length of this sequence increases - * by the value of len. - *

- * - * @param x the characters to be appended. - * @param offset the index of the first Char to append. - * @param len the number of Chars to append. - * @return a reference to this object. - */ - def append(x: Array[Char], offset: Int, len: Int): StringBuilder = { - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(x, offset, value, count, len) - count = newCount - this - } - - /**

- * Appends the string representation of the Boolean - * argument to the sequence. - *

- *

- * The argument is converted to a string as if by the method - * String.valueOf, and the characters of that - * string are then appended to this sequence. - *

- * - * @param x a Boolean. - * @return a reference to this object. - */ - def append(x: Boolean): StringBuilder = { - if (x) { - val newCount = count + 4 - if (newCount > value.length) expandCapacity(newCount) - value(count) = 't'; count += 1 - value(count) = 'r'; count += 1 - value(count) = 'u'; count += 1 - value(count) = 'e'; count += 1 - } else { - val newCount = count + 5 - if (newCount > value.length) expandCapacity(newCount) - value(count) = 'f'; count += 1 - value(count) = 'a'; count += 1 - value(count) = 'l'; count += 1 - value(count) = 's'; count += 1 - value(count) = 'e'; count += 1 - } - this - } - - def append(x: Byte): StringBuilder = - append(String.valueOf(x)) - - def append(x: Char): StringBuilder = { - val newCount = count + 1 - if (newCount > value.length) expandCapacity(newCount) - value(count) = x; count += 1 - this - } - - def append(x: Short): StringBuilder = - append(String.valueOf(x)) - - def append(x: Int): StringBuilder = - append(String.valueOf(x)) - - def append(x: Long): StringBuilder = - append(String.valueOf(x)) - - /** Removes the characters in a substring of this sequence. - * The substring begins at the specified start and extends to - * the character at index end - 1 or to the end of the - * sequence if no such character exists. If - * start is equal to end, no changes are made. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @return This object. - * @throws StringIndexOutOfBoundsException if start - * is negative, greater than length(), or - * greater than end. - */ - def delete(start: Int, end: Int): StringBuilder = { - if (start < 0 || start > end) - throw new StringIndexOutOfBoundsException(start) - val end0 = if (end > count) count else end - val len = end0 - start - if (len > 0) { - compat.Platform.arraycopy(value, start + len, value, start, count - end0) - count -= len - } - this - } - - /** Replaces the characters in a substring of this sequence - * with characters in the specified String. The substring - * begins at the specified start and extends to the character - * at index end - 1 or to the end of the sequence if no such - * character exists. First the characters in the substring are removed and - * then the specified String is inserted at start. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @param str String that will replace previous contents. - * @return This object. - * @throws StringIndexOutOfBoundsException if start - * is negative, greater than length(), or - * greater than end. - */ - def replace(start: Int, end: Int, str: String) { - if (start < 0 || start > count || start > end) - throw new StringIndexOutOfBoundsException(start) - - val end0 = if (end > count) count else end - val len = str.length() - val newCount = count + len - (end0 - start) - if (newCount > value.length) expandCapacity(newCount) - - compat.Platform.arraycopy(value, end, value, start + len, count - end) - compat.Platform.arraycopy(str.toArray, 0, value, start, len) - count = newCount - this - } - - /** Inserts the string representation of a subarray of the str - * array argument into this sequence. The subarray begins at the specified - * offset and extends len chars. - * The characters of the subarray are inserted into this sequence at - * the position indicated by index. The length of this - * sequence increases by len Chars. - * - * @param index position at which to insert subarray. - * @param str a Char array. - * @param offset the index of the first char in subarray to - * be inserted. - * @param len the number of Chars in the subarray to - * be inserted. - * @return This object - * @throws StringIndexOutOfBoundsException if index - * is negative or greater than length(), or - * offset or len are negative, or - * (offset+len) is greater than - * str.length. - */ - def insert(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = { - if (index < 0 || index > count) - throw new StringIndexOutOfBoundsException(index) - if (offset < 0 || len < 0 || offset > str.length - len) - throw new StringIndexOutOfBoundsException( - "offset " + offset + ", len " + len + - ", str.length " + str.length) - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, index, value, index + len, count - index) - compat.Platform.arraycopy(str, offset, value, index, len) - count = newCount - this - } - - /**

- * Inserts the string representation of the Any - * argument into this character sequence. - *

- *

- * The second argument is converted to a string as if by the method - * String.valueOf, and the characters of that - * string are then inserted into this sequence at the indicated - * offset. - *

- *

- * The offset argument must be greater than or equal to - * 0, and less than or equal to the length of this - * sequence. - *

- * - * @param offset the offset. - * @param x an Any value. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: Any): StringBuilder = - insert(at, String.valueOf(x)) - - /** Inserts the string into this character sequence. - * - * @param at the offset position. - * @param x a string. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: String): StringBuilder = { - if (at < 0 || at > count) - throw new StringIndexOutOfBoundsException(at) - val str = if (x == null) "null" else x - val len = str.length - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, at, value, at + len, count - at) - compat.Platform.arraycopy(str.toArray: Array[Char], 0, value, at, len) - count = newCount - this - } - - /** Inserts the string representation of the Char sequence - * argument into this sequence. - * - * @param at the offset position. - * @param x a character sequence. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: Seq[Char]): StringBuilder = - insert(at, x.toArray) - - /** Inserts the string representation of the Char array - * argument into this sequence. - * - * @param at the offset position. - * @param x a character array. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: Array[Char]): StringBuilder = { - if (at < 0 || at > count) - throw new StringIndexOutOfBoundsException(at) - val len = x.length - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, at, value, at + len, count - at) - compat.Platform.arraycopy(x, 0, value, at, len) - count = newCount - this - } - - /**

- * Inserts the string representation of the Boolean argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Boolean value. - * @return a reference to this object. - */ - def insert(at: Int, x: Boolean): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Inserts the string representation of the Byte argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Byte value. - * @return a reference to this object. - */ - def insert(at: Int, x: Byte): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Inserts the string representation of the Char argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Char value. - * @return a reference to this object. - */ - def insert(at: Int, x: Char): StringBuilder = { - if (at < 0 || at > count) - throw new StringIndexOutOfBoundsException(at) - val newCount = count + 1 - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, at, value, at + 1, count - at) - value(at) = x - count = newCount - this - } - - /**

- * Inserts the string representation of the Short argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Short value. - * @return a reference to this object. - */ - def insert(at: Int, x: Short): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Inserts the string representation of the Int argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Int value. - * @return a reference to this object. - */ - def insert(at: Int, x: Int): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Inserts the string representation of the Long argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Long value. - * @return a reference to this object. - */ - def insert(at: Int, x: Long): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Returns the index within this string of the first occurrence of the - * specified substring. The integer returned is the smallest value - * k such that: - *

- *
-   *  this.toString().startsWith(str, k)
- *
- *

- * is true. - *

- * - * @param str any string. - * @return if the string argument occurs as a substring within this - * object, then the index of the first character of the first - * such substring is returned; if it does not occur as a - * substring, -1 is returned. - * @throws NullPointerException if str is null. - */ - def indexOf(str: String): Int = indexOf(str, 0) - - /**

- * Returns the index within this string of the first occurrence of the - * specified substring, starting at the specified index. The integer - * returned is the smallest value k for which: - *

-   *    k >= Math.min(fromIndex, str.length()) &&
-   *                   this.toString().startsWith(str, k)
- *

- * If no such value of k exists, then -1 - * is returned. - *

- * - * @param str the substring for which to search. - * @param fromIndex the index from which to start the search. - * @return the index within this string of the first occurrence - * of the specified substring, starting at the specified index. - */ - def indexOf(str: String, fromIndex: Int): Int = - StringBuilder.indexOf(value, 0, count, str.toArray, 0, str.length(), fromIndex) - - /**

- * Returns the index within this string of the rightmost occurrence - * of the specified substring. The rightmost empty string "" is - * considered to occur at the index value this.length(). - * The returned index is the largest value k such that - *

- *
-   *  this.toString().startsWith(str, k)
- *
- *

- * is true. - *

- * - * @param str the substring to search for. - * @return if the string argument occurs one or more times as a substring - * within this object, then the index of the first character of - * the last such substring is returned. If it does not occur as - * a substring, -1 is returned. - * @throws NullPointerException if str is null. - */ - def lastIndexOf(str: String): Int = lastIndexOf(str, count) - - /**

- * Returns the index within this string of the last occurrence of the - * specified substring. The integer returned is the largest value - * k such that: - *

-   *    k <= Math.min(fromIndex, str.length()) &&
-   *                   this.toString().startsWith(str, k)
- *

- * If no such value of k exists, then -1 - * is returned. - *

- * - * @param str the substring to search for. - * @param fromIndex the index to start the search from. - * @return the index within this sequence of the last occurrence - * of the specified substring. - */ - def lastIndexOf(str: String, fromIndex: Int): Int = - StringBuilder.lastIndexOf(value, 0, count, str.toArray, 0, str.length(), fromIndex) - - /**

- * Causes this character sequence to be replaced by the reverse of the - * sequence. If there are any surrogate pairs included in the sequence, - * these are treated as single characters for the reverse operation. - * Thus, the order of the high-low surrogates is never reversed. - *

- *

- * Let n be the character length of this character sequence - * (not the length in Char values) just prior to - * execution of the reverse method. Then the - * character at index k in the new character sequence is - * equal to the character at index n-k-1 in the old - * character sequence. - *

- * - * @return a reference to this object. - */ - def reverse(): StringBuilder = { - val n = count - 1 - var j = (n-1) >> 1 - while (j >= 0) { - val temp = value(j) - val temp2 = value(n - j) - value(j) = temp2 - value(n - j) = temp - j -= 1 - } - this - } - - /** Returns a string representing the data in this sequence. - * A new String object is allocated and initialized to - * contain the character sequence currently represented by this - * object. This String is then returned. Subsequent - * changes to this sequence do not affect the contents of the - * String. - * - * @return a string representation of this sequence of characters. - */ - override def toString(): String = new String(value, 0, count) - -} - - -object StringBuilder { - - // method java.util.Arrays.copyOf exists since 1.6 - private def copyOf(src: Array[Char], newLength: Int): Array[Char] = { - val dest = new Array[Char](newLength) - val (start, end) = - if (src.length < newLength) (src.length, newLength) - else (newLength, src.length) - compat.Platform.arraycopy(src, 0, dest, 0, start) - // For any indices that are valid in the copy but not the original, - // the copy will contain '\\u000'. - for (i <- start until end) dest(i) = '\0' - dest - } - - private def indexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, - target: Array[Char], targetOffset: Int, targetCount: Int, - fromIndex: Int): Int = - if (fromIndex >= sourceCount) - if (targetCount == 0) sourceCount else -1 - else { - val inx = if (fromIndex < 0) 0 else fromIndex - if (targetCount == 0) - inx - else { - val first = target(targetOffset) - val max = sourceOffset + (sourceCount - targetCount) - - var i = sourceOffset + inx - while (i <= max) { - /* Look for first character. */ - if (source(i) != first) { - i += 1 - while (i <= max && source(i) != first) i += 1 - } - /* Found first character, now look at the rest of v2 */ - if (i <= max) { - var j = i + 1 - val end = j + targetCount - 1 - var k = targetOffset + 1 - while (j < end && source(j) == target(k)) { - j += 1 - k += 1 - } - if (j == end) { - /* Found whole string. */ - return i - sourceOffset - } - } // if - i += 1 - } // while - -1 - } - } - - private def lastIndexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, - target: Array[Char], targetOffset: Int, targetCount: Int, - fromIndex: Int): Int = { - val rightIndex = sourceCount - targetCount - if (fromIndex < 0) return -1 - val inx = if (fromIndex > rightIndex) rightIndex else fromIndex - // Empty string always matches - if (targetCount == 0) return inx - - val strLastIndex = targetOffset + targetCount - 1 - val strLastChar = target(strLastIndex) - val min = sourceOffset + targetCount - 1 - var i = min + fromIndex - - while (true) { - while (i >= min && source(i) != strLastChar) i -= 1 - if (i < min) return -1 - var j = i - 1 - val start = j - (targetCount - 1) - var k = strLastIndex - 1 - var outerWhile = false - while (j > start && !outerWhile) { - if (source(j) != target(k)) { - j -= 1 - k -= 1 - i -= 1 - outerWhile = true - } - } - if (!outerWhile) return start - sourceOffset + 1 - } - -1 - } -} diff --git a/src/library/jvm/cldc/scala/Symbol.scala b/src/library/jvm/cldc/scala/Symbol.scala deleted file mode 100644 index 3af5172406..0000000000 --- a/src/library/jvm/cldc/scala/Symbol.scala +++ /dev/null @@ -1,48 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -/**

- * Instances of Symbol can be created easily with - * Scala's built-in quote mechanism. - *

- *

- * For instance, the Scala - * term 'mysym will invoke the constructor of the - * Symbol class in the following way: - * new Symbol("mysym"). - *

- * - * @author Martin Odersky - * @version 1.7, 08/12/2003 - */ -final case class Symbol(name: String) { - - /** Converts this symbol to a string. - */ - override def toString(): String = { - "'" + name - } - - /**

- * Makes this symbol into a unique reference. - *

- *

- * If two interened symbols are equal (i.e. they have the same name) - * then they must be identical (wrt reference equality). - *

- * - * @return the unique reference to this symbol. - */ - def intern: Symbol = this - -} diff --git a/src/library/jvm/cldc/scala/collection/mutable/CloneableCollection.scala b/src/library/jvm/cldc/scala/collection/mutable/CloneableCollection.scala deleted file mode 100644 index fed584e5ba..0000000000 --- a/src/library/jvm/cldc/scala/collection/mutable/CloneableCollection.scala +++ /dev/null @@ -1,19 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.collection.mutable - -/** The J2ME version of the library defined this trait with a clone method - * to substitute for the lack of Object.clone there - */ -trait CloneableCollection { - def clone(): AnyRef = Predef.error("Cloning not supported") -} diff --git a/src/library/jvm/cldc/scala/compat/Platform.scala b/src/library/jvm/cldc/scala/compat/Platform.scala deleted file mode 100644 index 6d2ccbcfbb..0000000000 --- a/src/library/jvm/cldc/scala/compat/Platform.scala +++ /dev/null @@ -1,56 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.compat - - -import java.lang.System -import Predef._ - -object Platform { - - //type StackOverflowError = java.lang.StackOverflowError - type ConcurrentModificationException = java.lang.RuntimeException - - /** - * @param src .. - * @param srcPos .. - * @param dest .. - * @param destPos .. - * @param length .. - */ - def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int): Unit = - System.arraycopy(src, srcPos, dest, destPos, length) - - /** Create array of the same type as arrayInstance with the given - * length. - * - * @param elemClass .. - * @param length .. - * @return .. - */ - def createArray(elemClass: Class[_], length: Int): AnyRef = - throw new RuntimeException("" + elemClass + "[" + length+ "]") - //java.lang.reflect.Array.newInstance(elemClass, length) - - //def arrayclear(arr: Array[Int]): Unit = java.util.Arrays.fill(arr, 0) - def arrayclear(arr: Array[Int]): Unit = for (i <- 0 to arr.length) arr(i) = 0 - - def getClassForName(name: String): Class[_] = java.lang.Class.forName(name) - - val EOL = "\n" - - def currentTime: Long = System.currentTimeMillis() - - def collectGarbage: Unit = System.gc() - -} - diff --git a/src/library/jvm/cldc/scala/runtime/BooleanRef.java b/src/library/jvm/cldc/scala/runtime/BooleanRef.java deleted file mode 100644 index a0b2878506..0000000000 --- a/src/library/jvm/cldc/scala/runtime/BooleanRef.java +++ /dev/null @@ -1,19 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - - -public class BooleanRef { - public boolean elem; - public BooleanRef(boolean elem) { this.elem = elem; } - public String toString() { return String.valueOf(elem); } -} diff --git a/src/library/jvm/cldc/scala/runtime/BoxedAnyArray.scala b/src/library/jvm/cldc/scala/runtime/BoxedAnyArray.scala deleted file mode 100644 index 23768c87bd..0000000000 --- a/src/library/jvm/cldc/scala/runtime/BoxedAnyArray.scala +++ /dev/null @@ -1,234 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -import Predef._ -import compat.Platform - -/** - * Arrays created by new Array[T](length) where T - * is a type variable. - */ -@serializable -final class BoxedAnyArray(val length: Int) extends BoxedArray { - - private var boxed = new Array[AnyRef](length) - private val hash = boxed.hashCode() - private var unboxed: AnyRef = null - private var elemClass: Class[_] = null - - def apply(index: Int): Any = synchronized { - if (unboxed eq null) - boxed(index); - else if (elemClass eq classOf[Int]) - Int.box(unboxed.asInstanceOf[Array[Int]](index)) - else if (elemClass eq classOf[Long]) - Long.box(unboxed.asInstanceOf[Array[Long]](index)) - else if (elemClass eq classOf[Char]) - Char.box(unboxed.asInstanceOf[Array[Char]](index)) - else if (elemClass eq classOf[Byte]) - Byte.box(unboxed.asInstanceOf[Array[Byte]](index)) - else if (elemClass eq classOf[Short]) - Short.box(unboxed.asInstanceOf[Array[Short]](index)) - else if (elemClass eq classOf[Boolean]) - Boolean.box(unboxed.asInstanceOf[Array[Boolean]](index)) - else - unboxed.asInstanceOf[Array[AnyRef]](index) - } - - def update(index: Int, _elem: Any): Unit = synchronized { - val elem = _elem.asInstanceOf[AnyRef] - if (unboxed eq null) - boxed(index) = elem - else if (elemClass eq classOf[Int]) - unboxed.asInstanceOf[Array[Int]](index) = Int.unbox(elem) - else if (elemClass eq classOf[Long]) - unboxed.asInstanceOf[Array[Long]](index) = Long.unbox(elem) - else if (elemClass eq classOf[Char]) - unboxed.asInstanceOf[Array[Char]](index) = Char.unbox(elem) - else if (elemClass eq classOf[Byte]) - unboxed.asInstanceOf[Array[Byte]](index) = Byte.unbox(elem) - else if (elemClass eq classOf[Short]) - unboxed.asInstanceOf[Array[Short]](index) = Short.unbox(elem) - else if (elemClass eq classOf[Boolean]) - unboxed.asInstanceOf[Array[Boolean]](index) = Boolean.unbox(elem) - else - unboxed.asInstanceOf[Array[AnyRef]](index) = elem - } - - def unbox(elemTag: String): AnyRef = - if (elemTag eq ScalaRunTime.IntTag) unbox(classOf[Int]) - else if (elemTag eq ScalaRunTime.LongTag) unbox(classOf[Long]) - else if (elemTag eq ScalaRunTime.CharTag) unbox(classOf[Char]) - else if (elemTag eq ScalaRunTime.ByteTag) unbox(classOf[Byte]) - else if (elemTag eq ScalaRunTime.ShortTag) unbox(classOf[Short]) - else if (elemTag eq ScalaRunTime.BooleanTag) unbox(classOf[Boolean]) - else unbox(Platform.getClassForName(elemTag)) - - def unbox(elemClass: Class[_]): AnyRef = synchronized { - if (unboxed eq null) { - this.elemClass = elemClass - if (elemClass eq classOf[Int]) { - val newvalue = new Array[Int](length) - var i = 0 - while (i < length) { - newvalue(i) = Int.unbox(boxed(i)) - i += 1 - } - unboxed = newvalue - } else if (elemClass eq classOf[Long]) { - val newvalue = new Array[Long](length) - var i = 0 - while (i < length) { - newvalue(i) = Long.unbox(boxed(i)) - i += 1 - } - unboxed = newvalue; - } else if (elemClass eq classOf[Char]) { - val newvalue = new Array[Char](length) - var i = 0 - while (i < length) { - newvalue(i) = Char.unbox(boxed(i)) - i += 1 - } - unboxed = newvalue - } else if (elemClass eq classOf[Byte]) { - val newvalue = new Array[Byte](length) - var i = 0 - while (i < length) { - newvalue(i) = Byte.unbox(boxed(i)) - i += 1 - } - unboxed = newvalue - } else if (elemClass eq classOf[Short]) { - val newvalue = new Array[Short](length) - var i = 0 - while (i < length) { - newvalue(i) = Short.unbox(boxed(i)) - i += 1 - } - unboxed = newvalue - } else if (elemClass eq classOf[Boolean]) { - val newvalue = new Array[Boolean](length) - var i = 0 - while (i < length) { - newvalue(i) = Boolean.unbox(boxed(i)) - i += 1 - } - unboxed = newvalue; -// } else if (elemClass == boxed.getClass().getComponentType()) { -// // todo: replace with ScalaRunTime.AnyRef.class -// unboxed = boxed - } else { - unboxed = Platform.createArray(elemClass, length) - Platform.arraycopy(boxed, 0, unboxed, 0, length) - } - boxed = null - } - unboxed - } - - override def equals(other: Any): Boolean = ( - other.isInstanceOf[BoxedAnyArray] && (this eq (other.asInstanceOf[BoxedAnyArray])) || - (if (unboxed eq null) boxed == other else unboxed == other) - ) - - override def hashCode(): Int = hash - - def value: AnyRef = { - if (unboxed eq null) throw new NotDefinedError("BoxedAnyArray.value") - unboxed - } - - private def adapt(other: AnyRef): AnyRef = - if (this.unboxed eq null) - other match { - case that: BoxedAnyArray => - if (that.unboxed eq null) { - that.boxed - } else { - if (ScalaRunTime.isValueClass(that.elemClass)) unbox(that.elemClass); - that.unboxed - } - case that: BoxedArray => - adapt(that.value) - case that: Array[Int] => - unbox(ScalaRunTime.IntTag); that - case that: Array[Long] => - unbox(ScalaRunTime.LongTag); that - case that: Array[Char] => - unbox(ScalaRunTime.CharTag); that - case that: Array[Short] => - unbox(ScalaRunTime.ShortTag); that - case that: Array[Byte] => - unbox(ScalaRunTime.ByteTag); that - case that: Array[Boolean] => - unbox(ScalaRunTime.BooleanTag); that - case _ => - other - } - else - other match { - case that: BoxedAnyArray => - if (that.unboxed ne null) that.unboxed - else if (ScalaRunTime.isValueClass(this.elemClass)) that.unbox(this.elemClass) - else that.boxed - case that: BoxedArray => - adapt(that.value) - case _ => - other - } - - override def copyFrom(src: AnyRef, from: Int, to: Int, len: Int) { - val src1 = adapt(src) - Array.copy(src1, from, if (unboxed ne null) unboxed else boxed, to, len) - } - - override def copyTo(from: Int, dest: AnyRef, to: Int, len: Int) { - var dest1 = adapt(dest) - Array.copy(if (unboxed ne null) unboxed else boxed, from, dest1, to, len) - } - - override def subArray(start: Int, end: Int): AnyRef = { - val result = new BoxedAnyArray(end - start); - Array.copy(this, start, result, 0, end - start) - result - } - - final override def filter(p: Any => Boolean): BoxedArray = { - val include = new Array[Boolean](length) - var len = 0 - var i = 0 - while (i < length) { - if (p(this(i))) { include(i) = true; len += 1 } - i += 1 - } - val result = new BoxedAnyArray(len) - len = 0 - i = 0 - while (len < result.length) { - if (include(i)) { result(len) = this(i); len += 1 } - i += 1 - } - result - } - override protected def newArray(length : Int, elements : Iterator[Any]) = { - val result = new BoxedAnyArray(length) - var i = 0 - while (elements.hasNext) { - result(i) = elements.next - i += 1 - } - result - } -} diff --git a/src/library/jvm/cldc/scala/runtime/BoxedObjectArray.scala b/src/library/jvm/cldc/scala/runtime/BoxedObjectArray.scala deleted file mode 100644 index 878b7ac042..0000000000 --- a/src/library/jvm/cldc/scala/runtime/BoxedObjectArray.scala +++ /dev/null @@ -1,73 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -import Predef._ -import compat.Platform.createArray - -@serializable -final class BoxedObjectArray(val value: Array[AnyRef]) extends BoxedArray { - - def length: Int = value.length - - def apply(index: Int): Any = value(index) - - def update(index: Int, elem: Any) { - value(index) = elem.asInstanceOf[AnyRef] - } - - def unbox(elemTag: String): AnyRef = value - def unbox(elemClass: Class[_]): AnyRef = value - - override def equals(other: Any): Boolean = - value == other || - other.isInstanceOf[BoxedObjectArray] && value == other.asInstanceOf[BoxedObjectArray].value - - override def hashCode(): Int = value.hashCode() - - private def create(length: Int): Array[AnyRef] = { - //createArray(value.getClass().getComponentType(), length).asInstanceOf[Array[AnyRef]] - new Array[AnyRef](length) - } - - override def subArray(start: Int, end: Int): Array[AnyRef] = { - val result = create(end - start) - Array.copy(value, start, result, 0, end - start) - result - } - - final override def filter(p: Any => Boolean): BoxedArray = { - val include = new Array[Boolean](value.length) - var len = 0 - var i = 0 - while (i < value.length) { - if (p(value(i))) { include(i) = true; len += 1 } - i += 1 - } - val result = create(len) - len = 0 - i = 0 - while (len < result.length) { - if (include(i)) { result(len) = value(i); len += 1 } - i += 1 - } - new BoxedObjectArray(result) - } - - override protected def newArray(length: Int, elements: Iterator[Any]) = { - val result = create(length) - elements.map(_.asInstanceOf[AnyRef]).copyToArray(result, 0) - new BoxedObjectArray(result) - } -} - diff --git a/src/library/jvm/cldc/scala/runtime/BoxedUnit.java b/src/library/jvm/cldc/scala/runtime/BoxedUnit.java deleted file mode 100644 index bafd0ec010..0000000000 --- a/src/library/jvm/cldc/scala/runtime/BoxedUnit.java +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - - -public final class BoxedUnit -{ - - public final static BoxedUnit UNIT = new BoxedUnit(); - - private BoxedUnit() { } - - public boolean equals(java.lang.Object other) { - return this == other; - } - - public int hashCode() { - return 0; - } - - public String toString() { - return "()"; - } -} diff --git a/src/library/jvm/cldc/scala/runtime/BoxesRunTime.java b/src/library/jvm/cldc/scala/runtime/BoxesRunTime.java deleted file mode 100644 index bab4c63524..0000000000 --- a/src/library/jvm/cldc/scala/runtime/BoxesRunTime.java +++ /dev/null @@ -1,361 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - -/** An object (static class) that defines methods used for creating, - * reverting, and calculating with, boxed values. There are four classes - * of methods in this object: - * - High-performance value boxing methods that feed from a pre- - * computed map of instances for the most common instanciations. - * - Convenience unboxing methods returning default value on null. - * - The generalised comparison method to be used when an object may - * be a boxed value. - * - Standard value operators for boxed number and quasi-number values. - * - * @author Gilles Dubochet - * @author Martin Odersky - * @contributor Stepan Koltsov - * @version 2.0 */ -public class BoxesRunTime { - - private static final int CHAR = 0, BYTE = 1, SHORT = 2, INT = 3, LONG = 4, OTHER = 7; - - private static int typeCode(Object a) { - if (a instanceof Integer) return INT; - if (a instanceof Character) return CHAR; - if (a instanceof Long) return LONG; - if (a instanceof Byte) return BYTE; - if (a instanceof Short) return SHORT; - return OTHER; - } - -/* BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING */ - - private static int charLowBound = 0; - private static int charUpBound = 255; - private static Character[] charCache = new Character[charUpBound - charLowBound + 1]; - - private static int byteLowBound = -128; - private static int byteUpBound = 127; - private static Byte[] byteCache = new Byte[byteUpBound - byteLowBound + 1]; - - private static int shortLowBound = -128; - private static int shortUpBound = 127; - private static Short[] shortCache = new Short[shortUpBound - shortLowBound + 1]; - - private static int intLowBound = -128; - private static int intUpBound = 1024; - private static Integer[] intCache = new Integer[intUpBound - intLowBound + 1]; - - private static int longLowBound = -128; - private static int longUpBound = 1024; - private static Long[] longCache = new Long[longUpBound - longLowBound + 1]; - - static { - int idx = 0; - while (idx <= charUpBound - charLowBound) { - charCache[idx] = new Character((char)(idx + charLowBound)); - idx = idx + 1; - } - idx = 0; - while (idx <= byteUpBound - byteLowBound) { - byteCache[idx] = new Byte((byte)(idx + byteLowBound)); - idx = idx + 1; - } - idx = 0; - while (idx <= shortUpBound - shortLowBound) { - shortCache[idx] = new Short((short)(idx + shortLowBound)); - idx = idx + 1; - } - idx = 0; - while (idx <= intUpBound - intLowBound) { - intCache[idx] = new Integer((int)(idx + intLowBound)); - idx = idx + 1; - } - idx = 0; - while (idx <= longUpBound - longLowBound) { - longCache[idx] = new Long((long)(idx + longLowBound)); - idx = idx + 1; - } - } - - private static final Boolean TRUE = new Boolean(true); - private static final Boolean FALSE = new Boolean(false); - public static Boolean boxToBoolean(boolean b) { - return b ? TRUE : FALSE; - } - - public static Character boxToCharacter(char c) { - if (c >= charLowBound && c <= charUpBound) - return charCache[(int)c - charLowBound]; - return new Character(c); - } - - public static Byte boxToByte(byte b) { - if (b >= byteLowBound && b <= byteUpBound) - return byteCache[(int)b - byteLowBound]; - return new Byte(b); - } - - public static Short boxToShort(short s) { - if (s >= shortLowBound && s <= shortUpBound) - return shortCache[(int)s - shortLowBound]; - return new Short(s); - } - - public static Integer boxToInteger(int i) { - if (i >= intLowBound && i <= intUpBound) - return intCache[(int)i - intLowBound]; - return new Integer(i); - } - - public static Long boxToLong(long l) { - if (l >= longLowBound && l <= longUpBound) - return longCache[(int)l - longLowBound]; - return new Long(l); - } - -/* UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING */ - - public static boolean unboxToBoolean(Object b) { - return b == null ? false : ((Boolean)b).booleanValue(); - } - - public static char unboxToChar(Object c) { - return c == null ? 0 : ((Character)c).charValue(); - } - - public static byte unboxToByte(Object b) { - return b == null ? 0 : ((Byte)b).byteValue(); - } - - public static short unboxToShort(Object s) { - return s == null ? 0 : ((Short)s).shortValue(); - } - - public static int unboxToInt(Object i) { - return i == null ? 0 : ((Integer)i).intValue(); - } - - public static long unboxToLong(Object l) { - return l == null ? 0 : ((Long)l).longValue(); - } - - /* - public static boolean unboxToBoolean(Object b) { - if (b == null) - throw new ClassCastException("null is no Boolean value"); - return ((Boolean)b).booleanValue(); - } - - public static char unboxToChar(Object c) { - if (c == null) - throw new ClassCastException("null is no Char value"); - return ((Character)c).charValue(); - } - - public static byte unboxToByte(Object b) { - if (b == null) - throw new ClassCastException("null is no Byte value"); - return ((Byte)b).byteValue(); - } - - public static short unboxToShort(Object s) { - if (s == null) - throw new ClassCastException("null is no Short value"); - return ((Short)s).shortValue(); - } - - public static int unboxToInt(Object i) { - if (i == null) - throw new ClassCastException("null is no Int value"); - return ((Integer)i).intValue(); - } - - public static long unboxToLong(Object l) { - if (l == null) - throw new ClassCastException("null is no Long value"); - return ((Long)l).longValue(); - } - */ - -/* COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON */ - - /** A rich implementation of the equals method that overrides the - * default equals because Java's boxed primitives are utterly broken. This equals - * is inserted instead of a normal equals by the Scala compiler (in the - * ICode phase, method genEqEqPrimitive) only when either - * side of the comparison is a subclass of AnyVal, of - * java.lang.Number, of java.lang.Character or - * is exactly Any or AnyRef. */ - public static boolean equals(Object a, Object b) { - if (a == null) - return b == null; - if (b == null) - return false; - if (a.equals(b)) - return true; - - final long left = - (a instanceof Integer) ? ((Integer)a).intValue() : - (a instanceof Character) ? ((Character)a).charValue() : - (a instanceof Long) ? ((Long)a).longValue() : - (a instanceof Byte) ? ((Byte)a).byteValue() : - ((Short)a).shortValue(); - - final long right = - (b instanceof Integer) ? ((Integer)b).intValue() : - (b instanceof Character) ? ((Character)b).charValue() : - (b instanceof Long) ? ((Long)b).longValue() : - (b instanceof Byte) ? ((Byte)b).byteValue() : - ((Short)b).shortValue(); - - return left == right; - } - -/* OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS */ - - /** arg1 + arg2 */ - public static Object add(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 - arg2 */ - public static Object subtract(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 * arg2 */ - public static Object multiply(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 / arg2 */ - public static Object divide(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 % arg2 */ - public static Object takeModulo(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 >> arg2 */ - public static Object shiftSignedRight(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 << arg2 */ - public static Object shiftSignedLeft(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 >>> arg2 */ - public static Object shiftLogicalRight(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** -arg */ - public static Object negate(Object arg) throws Error { - throw new Error(); - } - - /** +arg */ - public static Object positive(Object arg) throws Error { - throw new Error(); - } - - /** arg1 & arg2 */ - public static Object takeAnd(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 | arg2 */ - public static Object takeOr(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 ^ arg2 */ - public static Object takeXor(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 && arg2 */ - public static Object takeConditionalAnd(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg1 || arg2 */ - public static Object takeConditionalOr(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** ~arg */ - public static Object complement(Object arg) throws Error { - throw new Error(); - } - - /** !arg */ - public static Object takeNot(Object arg) throws Error { - throw new Error(); - } - - public static Object testEqual(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - public static Object testNotEqual(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - public static Object testLessThan(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - public static Object testLessOrEqualThan(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - public static Object testGreaterOrEqualThan(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - public static Object testGreaterThan(Object arg1, Object arg2) throws Error { - throw new Error(); - } - - /** arg.toChar */ - public static Character toCharacter(Object arg) throws Error { - throw new Error(); - } - - /** arg.toByte */ - public static Byte toByte(Object arg) throws Error { - throw new Error(); - } - - /** arg.toShort */ - public static Short toShort(Object arg) throws Error { - throw new Error(); - } - - /** arg.toInt */ - public static Integer toInteger(Object arg) throws Error { - throw new Error(); - } - - /** arg.toLong */ - public static Long toLong(Object arg) throws Error { - throw new Error(); - } - -} diff --git a/src/library/jvm/cldc/scala/runtime/BoxesUtility.java b/src/library/jvm/cldc/scala/runtime/BoxesUtility.java deleted file mode 100644 index de33635e0f..0000000000 --- a/src/library/jvm/cldc/scala/runtime/BoxesUtility.java +++ /dev/null @@ -1,147 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - -/** - * @author Gilles Dubochet - * @version 1.0 - */ -public class BoxesUtility { - - private static int charLowBound = 0; - private static int charUpBound = 255; - private static Character[] charCache = new Character[charUpBound - charLowBound + 1]; - - private static int byteLowBound = -128; - private static int byteUpBound = 127; - private static Byte[] byteCache = new Byte[byteUpBound - byteLowBound + 1]; - - private static int shortLowBound = -128; - private static int shortUpBound = 127; - private static Short[] shortCache = new Short[shortUpBound - shortLowBound + 1]; - - private static int intLowBound = -128; - private static int intUpBound = 1024; - private static Integer[] intCache = new Integer[intUpBound - intLowBound + 1]; - - private static int longLowBound = -128; - private static int longUpBound = 1024; - private static Long[] longCache = new Long[longUpBound - longLowBound + 1]; - - static { - int idx = 0; - while (idx <= charUpBound - charLowBound) { - charCache[idx] = new Character((char)(idx + charLowBound)); - idx = idx + 1; - } - idx = 0; - while (idx <= byteUpBound - byteLowBound) { - byteCache[idx] = new Byte((byte)(idx + byteLowBound)); - idx = idx + 1; - } - idx = 0; - while (idx <= shortUpBound - shortLowBound) { - shortCache[idx] = new Short((short)(idx + shortLowBound)); - idx = idx + 1; - } - idx = 0; - while (idx <= intUpBound - intLowBound) { - intCache[idx] = new Integer((int)(idx + intLowBound)); - idx = idx + 1; - } - idx = 0; - while (idx <= longUpBound - longLowBound) { - longCache[idx] = new Long((long)(idx + longLowBound)); - idx = idx + 1; - } - } - private static final Boolean TRUE = new Boolean(true); - private static final Boolean FALSE = new Boolean(false); - public static Boolean boxToBoolean(boolean b) { - return b ? TRUE : FALSE; - } - - public static Character boxToCharacter(char c) { - if (c >= charLowBound && c <= charUpBound) - return charCache[(int)c - charLowBound]; - else - return new Character(c); - } - - public static Byte boxToByte(byte b) { - if (b >= byteLowBound && b <= byteUpBound) - return byteCache[(int)b - byteLowBound]; - else - return new Byte(b); - } - - public static Short boxToShort(short s) { - if (s >= shortLowBound && s <= shortUpBound) - return shortCache[(int)s - shortLowBound]; - else - return new Short(s); - } - - public static Integer boxToInteger(int i) { - if (i >= intLowBound && i <= intUpBound) - return intCache[(int)i - intLowBound]; - else - return new Integer(i); - } - - public static Long boxToLong(long l) { - if (l >= longLowBound && l <= longUpBound) - return longCache[(int)l - longLowBound]; - else - return new Long(l); - } - - public static boolean unboxToBoolean(Object b) { - return b == null ? false : ((Boolean)b).booleanValue(); - } - - public static char unboxToChar(Object c) { - if (c == null) - return 0; - else - return ((Character)c).charValue(); - } - - public static byte unboxToByte(Object b) { - if (b == null) - return 0; - else - return ((Byte)b).byteValue(); - } - - public static short unboxToShort(Object s) { - if (s == null) - return 0; - else - return ((Short)s).shortValue(); - } - - public static int unboxToInt(Object i) { - if (i == null) - return 0; - else - return ((Integer)i).intValue(); - } - - public static long unboxToLong(Object l) { - if (l == null) - return 0; - else - return ((Long)l).longValue(); - } - -} diff --git a/src/library/jvm/cldc/scala/runtime/ByteRef.java b/src/library/jvm/cldc/scala/runtime/ByteRef.java deleted file mode 100644 index f420362d03..0000000000 --- a/src/library/jvm/cldc/scala/runtime/ByteRef.java +++ /dev/null @@ -1,19 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - - -public class ByteRef { - public byte elem; - public ByteRef(byte elem) { this.elem = elem; } - public String toString() { return String.valueOf(elem); } -} diff --git a/src/library/jvm/cldc/scala/runtime/CharRef.java b/src/library/jvm/cldc/scala/runtime/CharRef.java deleted file mode 100644 index ea92945134..0000000000 --- a/src/library/jvm/cldc/scala/runtime/CharRef.java +++ /dev/null @@ -1,19 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - - -public class CharRef { - public char elem; - public CharRef(char elem) { this.elem = elem; } - public String toString() { return String.valueOf(elem); } -} diff --git a/src/library/jvm/cldc/scala/runtime/Comparator.java b/src/library/jvm/cldc/scala/runtime/Comparator.java deleted file mode 100644 index 75469e69b1..0000000000 --- a/src/library/jvm/cldc/scala/runtime/Comparator.java +++ /dev/null @@ -1,53 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - -/** - * @author Gilles Dubochet - * @author Martin Odersky - * @version 1.2 */ -public class Comparator { - - /** A rich implementation of the equals method that overrides the default - * equals because Java's boxed primitives are utterly broken. This equals - * is inserted instead of a normal equals by the Scala compiler (in the - * ICode phase, method genEqEqPrimitive) only when either - * side of the comparison is a subclass of AnyVal, of - * java.lang.Number, of java.lang.Character or - * is exactly Any or AnyRef, but when both sides - * have different types. */ - public static boolean equals(Object a, Object b) { - if (a == null) - return b == null; - if (b == null) - return false; - if (a.equals(b)) - return true; - - final long left = - (a instanceof Integer) ? ((Integer)a).intValue() : - (a instanceof Character) ? ((Character)a).charValue() : - (a instanceof Long) ? ((Long)a).longValue() : - (a instanceof Byte) ? ((Byte)a).byteValue() : - ((Short)a).shortValue(); - - final long right = - (b instanceof Integer) ? ((Integer)b).intValue() : - (b instanceof Character) ? ((Character)b).charValue() : - (b instanceof Long) ? ((Long)b).longValue() : - (b instanceof Byte) ? ((Byte)b).byteValue() : - ((Short)b).shortValue(); - - return left == right; - } - -} diff --git a/src/library/jvm/cldc/scala/runtime/IntRef.java b/src/library/jvm/cldc/scala/runtime/IntRef.java deleted file mode 100644 index dde9b18d17..0000000000 --- a/src/library/jvm/cldc/scala/runtime/IntRef.java +++ /dev/null @@ -1,19 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - - -public class IntRef { - public int elem; - public IntRef(int elem) { this.elem = elem; } - public String toString() { return String.valueOf(elem); } -} diff --git a/src/library/jvm/cldc/scala/runtime/LongRef.java b/src/library/jvm/cldc/scala/runtime/LongRef.java deleted file mode 100644 index 50a5133d87..0000000000 --- a/src/library/jvm/cldc/scala/runtime/LongRef.java +++ /dev/null @@ -1,19 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - - -public class LongRef { - public long elem; - public LongRef(long elem) { this.elem = elem; } - public String toString() { return String.valueOf(elem); } -} diff --git a/src/library/jvm/cldc/scala/runtime/ObjectRef.java b/src/library/jvm/cldc/scala/runtime/ObjectRef.java deleted file mode 100644 index 895fb472ef..0000000000 --- a/src/library/jvm/cldc/scala/runtime/ObjectRef.java +++ /dev/null @@ -1,19 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - - -public class ObjectRef { - public Object elem; - public ObjectRef(Object elem) { this.elem = elem; } - public String toString() { return "" + elem; } -} diff --git a/src/library/jvm/cldc/scala/runtime/RichChar.scala b/src/library/jvm/cldc/scala/runtime/RichChar.scala deleted file mode 100644 index 9c7bd95d4e..0000000000 --- a/src/library/jvm/cldc/scala/runtime/RichChar.scala +++ /dev/null @@ -1,71 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -import java.lang.Character -import Predef.NoSuchElementException - -/**

- * For example, in the following code - *

- *
- *    object test extends Application {
- *      Console.println('\40'.isWhitespace)
- *      Console.println('\011'.isWhitespace)
- *      Console.println('1'.asDigit == 1)
- *      Console.println('A'.asDigit == 10)
- *    }
- *

- * the implicit conversions are performed using the predefined view - * Predef.charWrapper. - *

- */ -final class RichChar(x: Char) extends Proxy with Ordered[Char] { - - // Proxy.self - def self: Any = x - - // Ordered[Char].compare - def compare (y: Char): Int = if (x < y) -1 else if (x > y) 1 else 0 - - def asDigit: Int = Character.digit(x, Character.MAX_RADIX) - - //def isControl: Boolean = Character.isISOControl(x) - def isDigit: Boolean = Character.isDigit(x) - //def isLetter: Boolean = Character.isLetter(x) - //def isLetterOrDigit: Boolean = Character.isLetterOrDigit(x) - def isLowerCase: Boolean = Character.isLowerCase(x) - def isUpperCase: Boolean = Character.isUpperCase(x) - //def isWhitespace: Boolean = Character.isWhitespace(x) - - def toLowerCase: Char = Character.toLowerCase(x) - def toUpperCase: Char = Character.toUpperCase(x) - - /** Create an Iterator[Char] over the characters from 'x' to 'y' - 1 - */ - def until(limit: Char): Iterator[Char] = new Iterator[Char] { - private var ch = x - def hasNext: Boolean = ch < limit - def next: Char = - if (hasNext) { val j = ch; ch = (ch + 1).toChar; j } - else throw new NoSuchElementException("next on empty iterator") - } - - //def until(y: Char): Iterator[Char] = to(y) - - /** Create an Iterator[Char] over the characters from 'x' to 'y' - */ - def to(y: Char): Iterator[Char] = until((y + 1).toChar) - -} diff --git a/src/library/jvm/cldc/scala/runtime/RichException.scala b/src/library/jvm/cldc/scala/runtime/RichException.scala deleted file mode 100644 index 9acab2e052..0000000000 --- a/src/library/jvm/cldc/scala/runtime/RichException.scala +++ /dev/null @@ -1,29 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id - - -package scala.runtime - -import Predef._ -import compat.Platform.EOL - -final class RichException(exc: Throwable) { - - def getStackTraceString: String = { - throw new UnsupportedOperationException(exc.toString) -// val s = new StringBuilder() -// for (trElem <- exc.getStackTrace()) { -// s.append(trElem.toString()) -// s.append(EOL) -// } -// s.toString() - } - -} diff --git a/src/library/jvm/cldc/scala/runtime/RichLong.scala b/src/library/jvm/cldc/scala/runtime/RichLong.scala deleted file mode 100644 index 2df4fdc23d..0000000000 --- a/src/library/jvm/cldc/scala/runtime/RichLong.scala +++ /dev/null @@ -1,30 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -final class RichLong(x: Long) extends Proxy with Ordered[Long] { - - // Proxy.self - def self: Any = x - - // Ordered[Long].compare - def compare(y: Long): Int = if (x < y) -1 else if (x > y) 1 else 0 - - def min(y: Long): Long = if (x < y) x else y - def max(y: Long): Long = if (x > y) x else y - def abs: Long = if (x < 0) -x else x - - def toBinaryString: String = java.lang.Long.toString(x, 2) - def toHexString: String = java.lang.Long.toString(x, 16) - def toOctalString: String = java.lang.Long.toString(x, 8) -} diff --git a/src/library/jvm/cldc/scala/runtime/RichString.scala b/src/library/jvm/cldc/scala/runtime/RichString.scala deleted file mode 100644 index 40e208246d..0000000000 --- a/src/library/jvm/cldc/scala/runtime/RichString.scala +++ /dev/null @@ -1,219 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -import Predef._ - -final class RichString(val self: String) extends Proxy with RandomAccessSeq[Char] with Ordered[String] { - import RichString._ - override def apply(n: Int) = self charAt n - override def length = self.length - override def toString = self - override def mkString = self - - override def slice(from: Int, until: Int): RichString = { - val len = self.length - new RichString( - if (from >= until || from >= len) - "" - else { - val from0 = if (from < 0) 0 else from - val until0 = if (until > len) len else until - self.substring(from0, until0) - } - ) - } - - //override def ++ [B >: A](that: Iterable[B]): Seq[B] = { - override def ++[B >: Char](that: Iterable[B]): RandomAccessSeq[B] = that match { - case that: RichString => new RichString(self + that.self) - case that => super.++(that) - } - - override def take(until: Int): RichString = slice(0, until) - - override def drop(from: Int): RichString = slice(from, self.length) - - override def startsWith[B](that: Seq[B]) = that match { - case that: RichString => self startsWith that.self - case that => super.startsWith(that) - } - - override def endsWith[B](that: Seq[B]) = that match { - case that: RichString => self endsWith that.self - case that => super.endsWith(that) - } - - override def indexOf[B](that: Seq[B]) = that match { - case that: RichString => self indexOf that.self - case that => super.indexOf(that) - } - - override def containsSlice[B](that: Seq[B]) = that match { - case that: RichString => self contains that.self - case that => super.containsSlice(that) - } - - override def reverse: RichString = { - val buf = new StringBuilder - var i = self.length - 1 - while (i >= 0) { - buf append (self charAt i) - i -= 1 - } - new RichString(buf.toString) - } - - override def compare(other: String) = self compareTo other - - private def isLineBreak(c: Char) = c == LF || c == FF - - /**

- * Strip trailing line end character from this string if it has one. - * A line end character is one of - *

- * - *

- * If a line feed character LF is preceded by a carriage return CR - * (0x0D hex), the CR character is also stripped (Windows convention). - *

- */ - def stripLineEnd: String = { - val len = self.length - if (len == 0) self - else { - val last = apply(len - 1) - if (isLineBreak(last)) - self.substring(0, if (last == LF && len >= 2 && apply(len - 2) == CR) len - 2 else len - 1) - else - self - } - } - - /**

- * Return all lines in this string in an iterator, including trailing - * line end characters. - *

- *

- * The number of strings returned is one greater than the number of line - * end characters in this string. For an empty string, a single empty - * line is returned. A line end character is one of - *

- * - */ - def linesWithSeparators = new Iterator[String] { - val len = self.length - var index = 0 - def hasNext: Boolean = index < len - def next(): String = { - if (index >= len) throw new NoSuchElementException("next on empty iterator") - val start = index - while (index < len && !isLineBreak(apply(index))) index += 1 - index += 1 - self.substring(start, index min len) - } - } - - /** Return all lines in this string in an iterator, excluding trailing line - * end characters, i.e. apply .stripLineEnd to all lines - * returned by linesWithSeparators. - */ - def lines: Iterator[String] = - linesWithSeparators map (line => new RichString(line).stripLineEnd) - - /** Returns this string with first character converted to upper case */ - def capitalize: String = - if (self == null) null - else if (self.length == 0) "" - else { - val chars = self.toCharArray - chars(0) = chars(0).toUpperCase - new String(chars) - } - - /**

- * For every line in this string: - *

- *
- * Strip a leading prefix consisting of blanks or control characters - * followed by marginChar from the line. - *
- */ - def stripMargin(marginChar: Char): String = { - val buf = new StringBuilder() - for (line <- linesWithSeparators) { - val len = line.length - var index = 0 - while (index < len && line.charAt(index) <= ' ') index += 1 - buf append - (if (index < len && line.charAt(index) == marginChar) line.substring(index + 1) else line) - } - buf.toString - } - - /**

- * For every line in this string: - *

- *
- * Strip a leading prefix consisting of blanks or control characters - * followed by | from the line. - *
- */ - def stripMargin: String = stripMargin('|') -/* - private def escape(ch: Char): String = ch match { - case '.' | '$' | '^' | '\\' => "\\" + ch - case _ => "" + ch - } - - @throws(classOf[java.util.regex.PatternSyntaxException]) - def split(separator: Char): Array[String] = self.split(escape(separator)) - - @throws(classOf[java.util.regex.PatternSyntaxException]) - def split(separators: Array[Char]): Array[String] = { - val re = separators.foldLeft("[")(_+_) + "]" - self.split(re) - } -*/ - def toBoolean: Boolean = parseBoolean(self) - def toByte: Byte = java.lang.Byte.parseByte(self) - def toShort: Short = java.lang.Short.parseShort(self) - def toInt: Int = java.lang.Integer.parseInt(self) - def toLong: Long = java.lang.Long.parseLong(self) - //def toFloat: Float = java.lang.Float.parseFloat(self) - //def toDouble: Double = java.lang.Double.parseDouble(self) -} - -object RichString { - // just statics for rich string. - private final val LF: Char = 0x0A - private final val FF: Char = 0x0C - private final val CR: Char = 0x0D - private final val SU: Char = 0x1A - - private def parseBoolean(s: String): Boolean = - if (s != null) s.toLowerCase match { - case "true" => true - case "false" => false - case _ => throw new NumberFormatException("For input string: \""+s+"\"") - } - else - throw new NumberFormatException("For input string: \"null\"") -} - diff --git a/src/library/jvm/cldc/scala/runtime/ScalaRunTime.scala b/src/library/jvm/cldc/scala/runtime/ScalaRunTime.scala deleted file mode 100644 index 004234af8f..0000000000 --- a/src/library/jvm/cldc/scala/runtime/ScalaRunTime.scala +++ /dev/null @@ -1,142 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - - -import Predef._ - -/* The object ScalaRunTime provides ... - */ -object ScalaRunTime { - - /** Names for primitive types, used by array unboxing */ - val ByteTag = ".Byte" - val ShortTag = ".Short" - val CharTag = ".Char" - val IntTag = ".Int" - val LongTag = ".Long" - val BooleanTag = ".Boolean" - - def isArray(x: AnyRef): Boolean = - (x != null && x.getClass.isArray) || (x != null && x.isInstanceOf[BoxedArray]) - - def isValueTag(tag: String) = tag.charAt(0) == '.' - - def isValueClass(clazz: Class[_]) = - clazz == classOf[Boolean] || clazz == classOf[Byte] || - clazz == classOf[Short ] || clazz == classOf[Char] || - clazz == classOf[Int ] || clazz == classOf[Long] - - def checkInitialized[T <: AnyRef](x: T): T = - if (x == null) throw new UninitializedError else x - - abstract class Try[A] { - def Catch[B >: A](handler: PartialFunction[Throwable, B]): B - def Finally(handler: Unit): A - } - - def Try[A](block: => A): Try[A] = new Try[A] with Runnable { - var result: A = _ - var exception: Throwable = ExceptionHandling.tryCatch(this) - - def run() { result = block } - - def Catch[B >: A](handler: PartialFunction[Throwable, B]): B = - if (exception eq null) - result.asInstanceOf[B] - // !!! else if (exception is LocalReturn) - // !!! // ... - else if (handler isDefinedAt exception) - handler(exception) - else - throw exception - - def Finally(handler: Unit): A = - if (exception eq null) - result.asInstanceOf[A] - else - throw exception - } - - def caseFields(x: Product): List[Any] = { - val arity = x.productArity - def fields(from: Int): List[Any] = - if (from == arity) List() - else x.productElement(from) :: fields(from + 1) - fields(0) - } - - def _toString(x: Product): String = - caseFields(x).mkString(x.productPrefix + "(", ",", ")") - - def _hashCode(x: Product): Int = { - var code = x.getClass().hashCode() - val arr = x.productArity - var i = 0 - while (i < arr) { - code = code * 41 + x.productElement(i).hashCode() - i += 1 - } - code - } - - def _equals(x: Product, y: Any): Boolean = y match { - case y1: Product if x.productArity == y1.productArity => - val arity = x.productArity - var i = 0 - while (i < arity && x.productElement(i) == y1.productElement(i)) - i += 1 - i == arity - case _ => - false - } - - def _equalsWithVarArgs(x: Product, y: Any): Boolean = y match { - case y1: Product if x.productArity == y1.productArity => - val arity = x.productArity - var i = 0 - while (i < arity - 1 && x.productElement(i) == y1.productElement(i)) - i += 1 - i == arity - 1 && { - x.productElement(i) match { - case xs: Seq[_] => - y1.productElement(i) match { - case ys: Seq[_] => xs sameElements ys - } - } - } - case _ => - false - } - - //def checkDefined[T >: Null](x: T): T = - // if (x == null) throw new UndefinedException else x - - def Seq[A](xs: A*): Seq[A] = null // interpreted specially by new backend. - - def arrayValue(x: BoxedArray, elemTag: String): AnyRef = - if (x eq null) null else x.unbox(elemTag) - - def arrayValue(x: BoxedArray, elemClass: Class[_]): AnyRef = - if (x eq null) null else x.unbox(elemClass) - - def boxArray(value: AnyRef): BoxedArray = value match { - case x: Array[Byte] => new BoxedByteArray(x) - case x: Array[Short] => new BoxedShortArray(x) - case x: Array[Char] => new BoxedCharArray(x) - case x: Array[Int] => new BoxedIntArray(x) - case x: Array[Long] => new BoxedLongArray(x) - case x: Array[Boolean] => new BoxedBooleanArray(x) - case x: Array[AnyRef] => new BoxedObjectArray(x) - case x: BoxedArray => x - } -} diff --git a/src/library/jvm/cldc/scala/runtime/ShortRef.java b/src/library/jvm/cldc/scala/runtime/ShortRef.java deleted file mode 100644 index fc844c07a8..0000000000 --- a/src/library/jvm/cldc/scala/runtime/ShortRef.java +++ /dev/null @@ -1,19 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime; - - -public class ShortRef { - public short elem; - public ShortRef(short elem) { this.elem = elem; } - public String toString() { return String.valueOf(elem); } -} diff --git a/src/library/jvm/cldc/scala/runtime/SquareRoot.scala b/src/library/jvm/cldc/scala/runtime/SquareRoot.scala deleted file mode 100644 index edfa7f7f1d..0000000000 --- a/src/library/jvm/cldc/scala/runtime/SquareRoot.scala +++ /dev/null @@ -1,151 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2007-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime - -import Predef._ - -/** - *

- * Integer Square Root function (see http://atoms.alife.co.uk/sqrt/index.html). - *

- *

- * Contributors include Arne Steinarson for the basic approximation idea, Dann - * Corbit and Mathew Hendry for the first cut at the algorithm, Lawrence Kirby - * for the rearrangement, improvments and range optimization, Paul Hsieh - * for the round-then-adjust idea, Tim Tyler, for the Java port - * and Jeff Lawson for a bug-fix and some code to improve accuracy. - *

- * - * @version v0.02 - 2003/09/07 - */ - -/** - * Faster replacements for (int)(java.lang.Math.sqrt(integer)) - */ -object SquareRoot { - private val table = Array( - 0, 16, 22, 27, 32, 35, 39, 42, 45, 48, 50, 53, 55, 57, - 59, 61, 64, 65, 67, 69, 71, 73, 75, 76, 78, 80, 81, 83, - 84, 86, 87, 89, 90, 91, 93, 94, 96, 97, 98, 99, 101, 102, - 103, 104, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, - 119, 120, 121, 122, 123, 124, 125, 126, 128, 128, 129, 130, 131, 132, - 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 144, 145, - 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155, 156, 157, - 158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166, 167, 167, 168, - 169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178, - 179, 180, 181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, - 189, 189, 190, 191, 192, 192, 193, 193, 194, 195, 195, 196, 197, 197, - 198, 199, 199, 200, 201, 201, 202, 203, 203, 204, 204, 205, 206, 206, - 207, 208, 208, 209, 209, 210, 211, 211, 212, 212, 213, 214, 214, 215, - 215, 216, 217, 217, 218, 218, 219, 219, 220, 221, 221, 222, 222, 223, - 224, 224, 225, 225, 226, 226, 227, 227, 228, 229, 229, 230, 230, 231, - 231, 232, 232, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, - 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, - 246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, - 253, 254, 254, 255 - ) - - /** - *

- * A faster replacement for (int)(java.lang.Math.sqrt(x)). - * Completely accurate for x < 2147483648 (i.e. 2^31)... - *

- *

- * Adjusted to more closely approximate "(int)(java.lang.Math.sqrt(x) + 0.5)" - * by Jeff Lawson. - *

- */ - @throws(classOf[IllegalArgumentException]) - def accurateSqrt(x: Int): Int = { - if (x >= 0x10000) { - val xn = if (x >= 0x1000000) { - var xn0 = - if (x >= 0x10000000) - if (x >= 0x40000000) table(x >> 24) << 8 - else table(x >> 22) << 7 - else - if (x >= 0x4000000) table(x >> 20) << 6 - else table(x >> 18) << 5 - - xn0 = (xn0 + 1 + (x / xn0)) >> 1 - (xn0 + 1 + (x / xn0)) >> 1 - } else { - var xn0 = - if (x >= 0x100000) - if (x >= 0x400000) table(x >> 16) << 4 - else table(x >> 14) << 3 - else - if (x >= 0x40000) table(x >> 12) << 2 - else table(x >> 10) << 1 - - (xn0 + 1 + (x / xn0)) >> 1 - } - adjustment(x, xn) - } - else if (x >= 0x100) { - val xn = - if (x >= 0x1000) - if (x >= 0x4000) (table(x >> 8)) + 1 - else (table(x >> 6) >> 1) + 1 - else - if (x >= 0x400) (table(x >> 4) >> 2) + 1 - else (table(x >> 2) >> 3) + 1 - - adjustment(x, xn) - } - else if (x >= 0) { - adjustment(x, table(x) >> 4) - } - else { - throw new IllegalArgumentException("Attempt to take the square root of negative number") - -1 - } - } - - private def adjustment(x: Int, xn: Int): Int = { - // Added by Jeff Lawson: - // need to test: - // if |xn * xn - x| > |x - (xn-1) * (xn-1)| then xn-1 is more accurate - // if |xn * xn - x| > |(xn+1) * (xn+1) - x| then xn+1 is more accurate - // or, for all cases except x == 0: - // if |xn * xn - x| > x - xn * xn + 2 * xn - 1 then xn-1 is more accurate - // if |xn * xn - x| > xn * xn + 2 * xn + 1 - x then xn+1 is more accurate - val xn2 = xn * xn - - // |xn * xn - x| - var comparitor0 = xn2 - x - if (comparitor0 < 0) comparitor0 = -comparitor0 - - val twice_xn = xn << 1 - - // |x - (xn-1) * (xn-1)| - var comparitor1 = x - xn2 + twice_xn - 1 - if (comparitor1 < 0) comparitor1 = -comparitor1 // only gets here when x == 0 - - // |(xn+1) * (xn+1) - x| - val comparitor2 = xn2 + twice_xn + 1 - x - - if (comparitor0 > comparitor1) - if (comparitor1 > comparitor2) xn+1 else xn-1 - else - if (comparitor0 > comparitor2) xn+1 else xn - } - - def main(args: Array[String]) { - def toInt(s: String): Option[Int] = - try { Some(s.toInt) } catch { case e: NumberFormatException => None } - for (arg <- args; val x = toInt(arg); if !x.isEmpty) { - val n = x.get - println("sqrt("+n+") = "+accurateSqrt(n)) - } - } -} diff --git a/src/library/jvm/cldc/scala/runtime/StringAdd.scala b/src/library/jvm/cldc/scala/runtime/StringAdd.scala deleted file mode 100644 index ab74c6464b..0000000000 --- a/src/library/jvm/cldc/scala/runtime/StringAdd.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* *\ -** ________ ___ __ ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ |_| ** -** ** -\* */ - -// $Id$ - - -package scala.runtime - - -import Predef._ - -final class StringAdd(self: Any) { - - def +(other: String) = self.toString + other - -} - diff --git a/src/library/jvm/scala/Application.scala b/src/library/jvm/scala/Application.scala deleted file mode 100644 index da34a4d224..0000000000 --- a/src/library/jvm/scala/Application.scala +++ /dev/null @@ -1,60 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import java.lang.System.getProperty -import scala.compat.Platform.currentTime - -/**

- * The Application class can be used to quickly turn objects - * into executable programs. Here is an example: - *

- *  object Main extends Application {
- *    Console.println("Hello World!")
- *  }
- *  
- *

- * Here, object Main inherits the main method - * of Application. The body of the Main object - * defines the main program. This technique does not work if the main - * program depends on command-line arguments (which are not accessible - * with the technique presented here). - *

- *

- * It is possible to time the execution of objects that inherit from class - * Application by setting the global scala.time - * property. Here is an example for benchmarking object Main: - *

- *  java -Dscala.time Main
- *  
- * - * @author Matthias Zenger - * @version 1.0, 10/09/2003 - */ - -trait Application { - - /** The time when execution of this program started. - */ - val executionStart: Long = currentTime - - /** The default main method. - * - * @param args the arguments passed to the main method - */ - def main(args: Array[String]) = { - if (getProperty("scala.time") ne null) { - val total = currentTime - executionStart - Console.println("[total " + total + "ms]") - } - } -} diff --git a/src/library/jvm/scala/Array.scala b/src/library/jvm/scala/Array.scala deleted file mode 100644 index edd508e6ef..0000000000 --- a/src/library/jvm/scala/Array.scala +++ /dev/null @@ -1,452 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - - -import Predef._ -import compat.Platform.arraycopy - -/** This object contains utility methods operating on arrays. - * - * @author Martin Odersky - * @version 1.0 - */ -object Array { - - /** Copy one array to another. - * Equivalent to - * System.arraycopy(src, srcPos, dest, destPos, length), - * except that this works also for polymorphic and boxed arrays. - * - * @param src ... - * @param srcPos ... - * @param dest ... - * @param destPos ... - * @param length ... - */ - def copy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) { - src match { - case xs: runtime.BoxedArray => - xs.copyTo(srcPos, dest, destPos, length) - case _ => - dest match { - case xs: runtime.BoxedArray => - xs.copyFrom(src, srcPos, destPos, length) - case _ => - arraycopy(src, srcPos, dest, destPos, length) - } - } - } - - /** Concatenate all argument sequences into a single array. - * - * @param xs the given argument sequences - * @return the array created from the concatenated arguments - */ - def concat[T](xs: Seq[T]*): Array[T] = { - var len = 0 - for (x <- xs) len += x.length - val result = new Array[T](len) - var start = 0 - for (x <- xs) { - copy(x.toArray, 0, result, start, x.length) - start += x.length - } - result - } - - /** Create a an array containing of successive integers. - * - * @param from the value of the first element of the array - * @param end the value of the last element fo the array plus 1 - * @return the sorted array of all integers in range [from;end). - */ - def range(start: Int, end: Int): Array[Int] = { - val result = new Array[Int](end - start) - for (i <- start until end) result(i - start) = i - result - } - - /** Create an array with given elements. - * - * @param xs the elements to put in the array - * @return the array containing elements xs. - */ - def apply[A <: AnyRef](xs: A*): Array[A] = { - val array = new Array[A](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - -/* The following metod clashes with the previous one, and has therefore been - * removed. Note that this is a choice between efficiency and generality. - * The previous factory method is more efficient than the one that has been - * commented out. Since it is anyway possible to create a polymorphic array - * using - * new Array[T] - * it was preferred to restrict the definition of the factory method. - - def Array[A](xs: A*): Array[A] = { - val array = new Array[A](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } -*/ - - def apply(xs: Boolean*): Array[Boolean] = { - val array = new Array[Boolean](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - def apply(xs: Byte*): Array[Byte] = { - val array = new Array[Byte](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - def apply(xs: Short*): Array[Short] = { - val array = new Array[Short](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - def apply(xs: Char*): Array[Char] = { - val array = new Array[Char](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - def apply(xs: Int*): Array[Int] = { - val array = new Array[Int](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - def apply(xs: Long*): Array[Long] = { - val array = new Array[Long](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - def apply(xs: Float*): Array[Float] = { - val array = new Array[Float](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - def apply(xs: Double*): Array[Double] = { - val array = new Array[Double](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - def apply(xs: Unit*): Array[Unit] = { - val array = new Array[Unit](xs.length) - var i = 0 - for (x <- xs.elements) { array(i) = x; i += 1 } - array - } - - /** Create an array containing several copies of an element. - * - * @param n the length of the resulting array - * @param elem the element composing the resulting array - * @return an array composed of n elements all equal to elem - */ - def make[A](n: Int, elem: A): Array[A] = { - val a = new Array[A](n) - var i = 0 - while (i < n) { - a(i) = elem - i += 1 - } - a - } - - /** This method is called as a result of a pattern match { case Array(...) => } or val Array(...) = .... - * - * @param x the selector value - * @return array wrapped in an option - */ - def unapplySeq[A](x: Array[A]): Option[Seq[A]] = Some(x) - - trait ArrayLike[A] extends RandomAccessSeq.Mutable[A] { - def force : Array[A] - } - - trait Projection[A] extends RandomAccessSeq.MutableProjection[A] with ArrayLike[A] { - protected def newArray[B >: A](length : Int, elements : Iterator[A]) : Array[B] - override def toArray[B >: A] = (newArray(length, elements))//:Any).asInstanceOf[Array[B]] - override def force : Array[A] = toArray - override def drop( from: Int) = slice(from, length) - override def take(until: Int) = slice(0, until) - override def dropWhile(p: A => Boolean) = { - val c = length + 1 - drop((findIndexOf(!p(_)) + c) % c) - } - override def takeWhile(p: A => Boolean) = { - val c = length + 1 - take((findIndexOf(!p(_)) + c) % c) - } - override def slice(from0: Int, until0: Int): Projection[A] = new RandomAccessSeq.MutableSlice[A] with Projection[A] { - override def from = from0 - override def until = until0 - override def underlying = Projection.this - override protected def newArray[B >: A](length: Int, elements: Iterator[A]) = - underlying.newArray(length, elements) - override def slice(from0: Int, until0: Int) = - Projection.this.slice(from + from0, from + until0) - } - - - override def reverse : Projection[A] = new Projection[A] { - override protected def newArray[B >: A](length : Int, elements : Iterator[A]) = - Projection.this.newArray(length, elements) - def update(idx : Int, what : A) : Unit = Projection.this.update(length - idx - 1, what) - def length = Projection.this.length - def apply(idx : Int) = Projection.this.apply(length - idx - 1) - override def stringPrefix = Projection.this.stringPrefix + "R" - } - } - trait Array0[A] extends RandomAccessSeq.Mutable[A] with ArrayLike[A] { - override def projection : Projection[A] = throw new Error - override def slice(from : Int, until : Int) : Projection[A] = projection.slice(from, until) - override def take(until : Int) : Projection[A] = projection.take(until) - override def drop(from : Int) : Projection[A] = projection.drop(from) - override def dropWhile(p: A => Boolean) = projection.dropWhile(p) - override def takeWhile(p: A => Boolean) = projection.takeWhile(p) - override def reverse = projection.reverse - override def force = asInstanceOf[Array[A]] - } -} - -/** This class represents polymorphic arrays. Array[T] is Scala's representation - * for Java's T[]. - * - * @author Martin Odersky - * @version 1.0 - */ -final class Array[A](_length: Int) extends Array.Array0[A] { - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int) = { - this(dim1) - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int) = { - this(dim1) - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int) = { - this(dim1) - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int) = { - this(dim1); - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int) = { - this(dim1) - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int) = { - this(dim1) - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int) = { - this(dim1) - throw new Error() - } - - /** Multidimensional array creation */ - def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int, dim9: Int) = { - this(dim1) - throw new Error() - } - - /** The length of the array */ - def length: Int = throw new Error() - - /** The element at given index. - *

- * Indices start a 0; xs.apply(0) is the first - * element of array xs. - *

- *

- * Note the indexing syntax xs(i) is a shorthand for - * xs.apply(i). - *

- * - * @param i the index - * @throws ArrayIndexOutOfBoundsException if i < 0 or - * length <= i - */ - def apply(i: Int): A = throw new Error() - - /**

- * Update the element at given index. - *

- *

- * Indices start a 0; xs.apply(0) is the first - * element of array xs. - *

- *

- * Note the indexing syntax xs(i) = x is a shorthand - * for xs.update(i, x). - *

- * - * @param i the index - * @param x the value to be written at index i - * @throws ArrayIndexOutOfBoundsException if i < 0 or - * length <= i - */ - override def update(i: Int, x: A) { throw new Error() } - - /** An iterator returning the elements of this array, starting from 0. - */ - override def elements: Iterator[A] = throw new Error() - - /** @deprecated use slice(from,end).force instead */ - def subArray(from: Int, end: Int): Array[A] = throw new Error() - - /** Returns an array consisting of all elements of this array that satisfy the - * predicate p. The order of the elements is preserved. - * - * @param p the predicate used to filter the array. - * @return the elements of this array satisfying p. - */ - override def filter(p: A => Boolean): Array[A] = throw new Error() - - /** Returns an array consisting of all elements of this array followed - * by all elements of the argument iterable. - */ - override def ++[B >: A](that: Iterable[B]): Array[B] = throw new Error() - - /** Returns the array resulting from applying the given function f to each - * element of this array. - * - * @param f function to apply to each element. - * @return [f(a0), ..., f(an)] if this array is [a0, ..., an]. - */ - override def map[B](f: A => B): Array[B] = throw new Error() - - /** Applies the given function f to each element of - * this array, then concatenates the results. - * - * @param f the function to apply on each element. - * @return f(a0) ::: ... ::: f(an) if - * this array is [a0, ..., an]. - */ - override def flatMap[B](f: A => Iterable[B]): Array[B] = throw new Error() - - /** Returns an array formed from this array and the specified array - * that by associating each element of the former with - * the element at the same position in the latter. - * If one of the two arrays is longer than the other, its remaining elements are ignored. - * - * @return Array({a0,b0}, ..., - * {amin(m,n),bmin(m,n)}) when - * Array(a0, ..., am) - * zip Array(b0, ..., bn) is invoked. - */ - def zip[B](that: Array[B]): Array[(A, B)] = throw new Error() - - /** Returns an array that pairs each element of this array - * with its index, counting from 0. - * - * @return the array Array({a0,0}, {a1,1},...) - * where ai are the elements of this stream. - */ - def zipWithIndex: Array[(A, Int)] = throw new Error() - - /** Returns an array that contains all indices of this array */ - def indices: Array[Int] = throw new Error() - - /** - * @return a deep string representation of this array. - */ - def deepToString(): String = throw new Error() - - /**

- * Returns a string representation of this array object. The resulting string - * begins with the string start and is finished by the string - * end. Inside, the string representations of elements (w.r.t. - * the method deepToString()) are separated by the string - * sep. For example: - *

- *

- * Array(Array(1, 2), Array(3)).deepMkString("[", "; ", "]") = "[[1; 2]; [3]]" - *

- * - * @param start starting string. - * @param sep separator string. - * @param end ending string. - * @return a string representation of this array object. - */ - def deepMkString(start: String, sep: String, end: String): String = - throw new Error() - - /** Returns a string representation of this array object. The string - * representations of elements (w.r.t. the method deepToString()) - * are separated by the string sep. - * - * @param sep separator string. - * @return a string representation of this array object. - */ - def deepMkString(sep: String): String = throw new Error() - - /**

- * Returns true if the two specified arrays are - * deeply equal to one another. - *

- *

- * Two array references are considered deeply equal if both are null, - * or if they refer to arrays that contain the same number of elements - * and all corresponding pairs of elements in the two arrays are deeply - * equal. - *

- *

- * See also method deepEquals in the Java class - * java.utils.Arrays - *

- * - * @param that the second - * @return true iff both arrays are deeply equal. - */ - def deepEquals(that: Any): Boolean = throw new Error() - -} diff --git a/src/library/jvm/scala/BigDecimal.scala b/src/library/jvm/scala/BigDecimal.scala deleted file mode 100644 index 31cd6316ae..0000000000 --- a/src/library/jvm/scala/BigDecimal.scala +++ /dev/null @@ -1,266 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2007-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala - -import java.math.{BigDecimal => BigDec} - -/** - * @author Stephane Micheloud - * @version 1.0 - */ -object BigDecimal { - - object RoundingMode extends Enumeration { - type RoundingMode = Value - val ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_UP, - ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_UNNECESSARY = Value - } - - private val minCached = -512 - private val maxCached = 512 - private lazy val cache = new Array[BigDecimal](maxCached - minCached + 1) - - /** Constructs a BigDecimal whose value is equal to that of the - * specified Integer value. - * - * @param i the specified integer value - * @return the constructed BigDecimal - */ - def apply(i: Int): BigDecimal = - if (minCached <= i && i <= maxCached) { - val offset = i - minCached - var n = cache(offset) - if (n eq null) { n = new BigDecimal(BigDec.valueOf(i)); cache(offset) = n } - n - } else new BigDecimal(BigDec.valueOf(i)) - - /** Constructs a BigDecimal whose value is equal to that of the - * specified long value. - * - * @param l the specified long value - * @return the constructed BigDecimal - */ - def apply(l: Long): BigDecimal = - if (minCached <= l && l <= maxCached) apply(l.toInt) - else new BigDecimal(BigDec.valueOf(l)) - - /** Constructs a BigDecimal whose value is equal to that of the - * specified double value. - * - * @param d the specified Double value - * @return the constructed BigDecimal - */ - def apply(d: Double): BigDecimal = - new BigDecimal(new BigDec(d)) - - /** Translates a character array representation of a BigDecimal - * into a BigDecimal. - */ - def apply(x: Array[Char]): BigDecimal = - new BigDecimal(new BigDec(x.toString)) - - /** Translates the decimal String representation of a BigDecimal - * into a BigDecimal. - */ - def apply(x: String): BigDecimal = - new BigDecimal(new BigDec(x)) - - /** Constructs a BigDecimal whose value is equal to that of the - * specified BigInt value. - * - * @param x the specified BigInt value - * @return the constructed BigDecimal - */ - def apply(x: BigInt): BigDecimal = - new BigDecimal(new BigDec(x.bigInteger)) - - /** Implicit conversion from Int to BigDecimal. */ - implicit def int2bigDecimal(i: Int): BigDecimal = apply(i) - - /** Implicit copnversion from Long to BigDecimal. */ - implicit def long2bigDecimal(l: Long): BigDecimal = apply(l) - - /** Implicit copnversion from Double to BigDecimal. */ - implicit def double2bigDecimal(d: Double): BigDecimal = apply(d) - - /** Implicit conversion from BigDecimal to Ordered. */ - implicit def bigDecimal2ordered(x: BigDecimal): Ordered[BigDecimal] = - new Ordered[BigDecimal] with Proxy { - def self: Any = x - def compare(y: BigDecimal): Int = x.bigDecimal.compareTo(y.bigDecimal) - } -} - -/** - * @author Stephane Micheloud - * @version 1.0 - */ -@serializable -class BigDecimal(val bigDecimal: BigDec) extends java.lang.Number { - import BigDecimal.RoundingMode._ - - /** Returns the hash code for this BigDecimal. */ - override def hashCode(): Int = this.bigDecimal.hashCode() - - /** Compares this BigDecimal with the specified value for equality. - */ - override def equals (that: Any): Boolean = that match { - case that: BigDecimal => this equals that - case that: java.lang.Double => this.bigDecimal.doubleValue == that.doubleValue - case that: java.lang.Float => this.bigDecimal.floatValue == that.floatValue - case that: java.lang.Number => this equals BigDecimal(that.longValue) - case that: java.lang.Character => this equals BigDecimal(that.charValue.asInstanceOf[Int]) - case _ => false - } - - /** Compares this BigDecimal with the specified BigDecimal for equality. - */ - def equals (that: BigDecimal): Boolean = - this.bigDecimal.compareTo(that.bigDecimal) == 0 - - /** Compares this BigDecimal with the specified BigDecimal - */ - def compare (that: BigDecimal): Int = this.bigDecimal.compareTo(that.bigDecimal) - - /** Less-than-or-equals comparison of BigDecimals - */ - def <= (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) <= 0 - - /** Greater-than-or-equals comparison of BigDecimals - */ - def >= (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) >= 0 - - /** Less-than of BigDecimals - */ - def < (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) < 0 - - /** Greater-than comparison of BigDecimals - */ - def > (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) > 0 - - /** Addition of BigDecimals - */ - def + (that: BigDecimal): BigDecimal = - new BigDecimal(this.bigDecimal.add(that.bigDecimal)) - - /** Subtraction of BigDecimals - */ - def - (that: BigDecimal): BigDecimal = - new BigDecimal(this.bigDecimal.subtract(that.bigDecimal)) - - /** Multiplication of BigDecimals - */ - def * (that: BigDecimal): BigDecimal = - new BigDecimal(this.bigDecimal.multiply(that.bigDecimal)) - - /** Division of BigDecimals - */ - def / (that: BigDecimal): BigDecimal = - new BigDecimal(this.bigDecimal.divide(that.bigDecimal, this.scale - that.scale)) - - /** Returns the minimum of this and that - */ - def min (that: BigDecimal): BigDecimal = - new BigDecimal(this.bigDecimal.min(that.bigDecimal)) - - /** Returns the maximum of this and that - */ - def max (that: BigDecimal): BigDecimal = - new BigDecimal(this.bigDecimal.max(that.bigDecimal)) - - /** Returns a BigDecimal whose value is the negation of this BigDecimal - */ - def unary_- : BigDecimal = new BigDecimal(this.bigDecimal.negate()) - - /** Returns the absolute value of this BigDecimal - */ - def abs: BigDecimal = new BigDecimal(this.bigDecimal.abs()) - - /** Returns the sign of this BigDecimal, i.e. - * -1 if it is less than 0, - * +1 if it is greater than 0 - * 0 if it is equal to 0 - */ - def signum: Int = this.bigDecimal.signum() - - /** Returns the scale of this BigDecimal. - */ - def scale: Int = this.bigDecimal.scale() - - /** Returns a BigDecimal whose scale is the specified value, and whose value is - * numerically equal to this BigDecimal's. - */ - def setScale(scale: Int): BigDecimal = - new BigDecimal(this.bigDecimal setScale scale) - - def setScale(scale: Int, mode: RoundingMode): BigDecimal = - new BigDecimal(this.bigDecimal.setScale(scale, mode.id)) - - /** Converts this BigDecimal to a byte. - * If the BigDecimal is too big to fit in a byte, only the low-order 8 bits are returned. - * Note that this conversion can lose information about the overall magnitude of the - * BigDecimal value as well as return a result with the opposite sign. - */ - override def byteValue = intValue.toByte - - /** Converts this BigDecimal to a short. - * If the BigDecimal is too big to fit in a byte, only the low-order 16 bits are returned. - * Note that this conversion can lose information about the overall magnitude of the - * BigDecimal value as well as return a result with the opposite sign. - */ - override def shortValue = intValue.toShort - - /** Converts this BigDecimal to a char. - * If the BigDecimal is too big to fit in a char, only the low-order 16 bits are returned. - * Note that this conversion can lose information about the overall magnitude of the - * BigDecimal value and that it always returns a positive result. - */ - def charValue = intValue.toChar - - /** Converts this BigDecimal to an int. - * If the BigDecimal is too big to fit in a char, only the low-order 32 bits - * are returned. Note that this conversion can lose information about the - * overall magnitude of the BigDecimal value as well as return a result with - * the opposite sign. - */ - def intValue = this.bigDecimal.intValue - - /** Converts this BigDecimal to a Long. - * If the BigDecimal is too big to fit in a char, only the low-order 64 bits - * are returned. Note that this conversion can lose information about the - * overall magnitude of the BigDecimal value as well as return a result with - * the opposite sign. - */ - def longValue = this.bigDecimal.longValue - - /** Converts this BigDecimal to a float. - * if this BigDecimal has too great a magnitude to represent as a float, - * it will be converted to Float.NEGATIVE_INFINITY or - * Float.POSITIVE_INFINITY as appropriate. - */ - def floatValue = this.bigDecimal.floatValue - - /** Converts this BigDecimal to a Double. - * if this BigDecimal has too great a magnitude to represent as a float, - * it will be converted to Float.NEGATIVE_INFINITY or - * Float.POSITIVE_INFINITY as appropriate. - */ - def doubleValue = this.bigDecimal.doubleValue - - /** Converts this BigDecimal to a BigInteger. - */ - def toBigInt(): BigInt = new BigInt(this.bigDecimal.toBigInteger()) - - /** Returns the decimal String representation of this BigDecimal. - */ - override def toString(): String = this.bigDecimal.toString() - -} diff --git a/src/library/jvm/scala/BigInt.scala b/src/library/jvm/scala/BigInt.scala deleted file mode 100644 index a24d141aec..0000000000 --- a/src/library/jvm/scala/BigInt.scala +++ /dev/null @@ -1,365 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala - -import java.math.BigInteger - -/** - * @author Martin Odersky - * @version 1.0, 15/07/2003 - */ -object BigInt { - - private val minCached = -1024 - private val maxCached = 1024 - private val cache = new Array[BigInt](maxCached - minCached + 1) - - /** Constructs a BigInt whose value is equal to that of the - * specified integer value. - * - * @param i the specified integer value - * @return the constructed BigInt - */ - def apply(i: Int): BigInt = - if (minCached <= i && i <= maxCached) { - val offset = i - minCached - var n = cache(offset) - if (n eq null) { n = new BigInt(BigInteger.valueOf(i)); cache(offset) = n } - n - } else new BigInt(BigInteger.valueOf(i)) - - /** Constructs a BigInt whose value is equal to that of the - * specified long value. - * - * @param l the specified long value - * @return the constructed BigInt - */ - def apply(l: Long): BigInt = - if (minCached <= l && l <= maxCached) apply(l.toInt) - else new BigInt(BigInteger.valueOf(l)) - - /** Translates a byte array containing the two's-complement binary - * representation of a BigInt into a BigInt. - */ - def apply(x: Array[Byte]): BigInt = - new BigInt(new BigInteger(x)) - - /** Translates the sign-magnitude representation of a BigInt into a BigInt. - */ - def apply(signum: Int, magnitude: Array[Byte]): BigInt = - new BigInt(new BigInteger(signum, magnitude)) - - /** Constructs a randomly generated positive BigInt that is probably prime, - * with the specified bitLength. - */ - def apply(bitlength: Int, certaInty: Int, rnd: Random): BigInt = - new BigInt(new BigInteger(bitlength, certaInty, rnd.self)) - - /** Constructs a randomly generated BigInt, uniformly distributed over the - * range 0 to (2 ^ numBits - 1), inclusive. - * - * @param numbits ... - * @param rnd ... - * @return ... - */ - def apply(numbits: Int, rnd: Random): BigInt = - new BigInt(new BigInteger(numbits, rnd.self)) - - /** Translates the decimal String representation of a BigInt into a BigInt. - */ - def apply(x: String): BigInt = - new BigInt(new BigInteger(x)) - - /** Translates the string representation of a BigInt in the - * specified radix into a BigInt. - * - * @param x ... - * @param radix ... - * @return ... - */ - def apply(x: String, radix: Int): BigInt = - new BigInt(new BigInteger(x, radix)) - - /** Returns a positive BigInt that is probably prime, with the specified bitLength. - */ - def probablePrime(bitLength: Int, rnd: Random): BigInt = - new BigInt(BigInteger.probablePrime(bitLength, rnd.self)) - - /** Implicit conversion from int to BigInt. - */ - implicit def int2bigInt(i: Int): BigInt = apply(i) - - /** Implicit copnversion from long to BigInt - */ - implicit def long2bigInt(l: Long): BigInt = apply(l) - - /** Implicit conversion from BigInt to Ordered. - */ - implicit def bigInt2ordered(x: BigInt): Ordered[BigInt] = new Ordered[BigInt] with Proxy { - def self: Any = x; - def compare (y: BigInt): Int = x.bigInteger.compareTo(y.bigInteger) - } -} - -/** - * @author Martin Odersky - * @version 1.0, 15/07/2003 - */ -@serializable -class BigInt(val bigInteger: BigInteger) extends java.lang.Number { - - /** Returns the hash code for this BigInt. */ - override def hashCode(): Int = this.bigInteger.hashCode() - - /** Compares this BigInt with the specified value for equality. - */ - override def equals (that: Any): Boolean = that match { - case that: BigInt => this equals that - case that: java.lang.Double => this.bigInteger.doubleValue == that.doubleValue - case that: java.lang.Float => this.bigInteger.floatValue == that.floatValue - case that: java.lang.Number => this equals BigInt(that.longValue) - case that: java.lang.Character => this equals BigInt(that.charValue.asInstanceOf[Int]) - case _ => false - } - - /** Compares this BigInt with the specified BigInt for equality. - */ - def equals (that: BigInt): Boolean = - this.bigInteger.compareTo(that.bigInteger) == 0 - - /** Compares this BigInt with the specified BigInt - */ - def compare (that: BigInt): Int = this.bigInteger.compareTo(that.bigInteger) - - /** Less-than-or-equals comparison of BigInts - */ - def <= (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) <= 0 - - /** Greater-than-or-equals comparison of BigInts - */ - def >= (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) >= 0 - - /** Less-than of BigInts - */ - def < (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) < 0 - - /** Greater-than comparison of BigInts - */ - def > (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) > 0 - - /** Addition of BigInts - */ - def + (that: BigInt): BigInt = new BigInt(this.bigInteger.add(that.bigInteger)) - - /** Subtraction of BigInts - */ - def - (that: BigInt): BigInt = new BigInt(this.bigInteger.subtract(that.bigInteger)) - - /** Multiplication of BigInts - */ - def * (that: BigInt): BigInt = new BigInt(this.bigInteger.multiply(that.bigInteger)) - - /** Division of BigInts - */ - def / (that: BigInt): BigInt = new BigInt(this.bigInteger.divide(that.bigInteger)) - - /** Remainder of BigInts - */ - def % (that: BigInt): BigInt = new BigInt(this.bigInteger.remainder(that.bigInteger)) - - /** Returns a pair of two BigInts containing (this / that) and (this % that). - */ - def /% (that: BigInt): (BigInt, BigInt) = { - val dr = this.bigInteger.divideAndRemainder(that.bigInteger) - (new BigInt(dr(0)), new BigInt(dr(1))) - } - - /** Leftshift of BigInt - */ - def << (n: Int): BigInt = new BigInt(this.bigInteger.shiftLeft(n)) - - /** (Signed) rightshift of BigInt - */ - def >> (n: Int): BigInt = new BigInt(this.bigInteger.shiftRight(n)) - - /** Bitwise and of BigInts - */ - def & (that: BigInt): BigInt = new BigInt(this.bigInteger.and(that.bigInteger)) - - /** Bitwise or of BigInts - */ - def | (that: BigInt): BigInt = new BigInt(this.bigInteger.or (that.bigInteger)) - - /** Bitwise exclusive-or of BigInts - */ - def ^ (that: BigInt): BigInt = new BigInt(this.bigInteger.xor(that.bigInteger)) - - /** Bitwise and-not of BigInts. Returns a BigInt whose value is (this & ~that). - */ - def &~ (that: BigInt): BigInt = new BigInt(this.bigInteger.andNot(that.bigInteger)) - - /** Returns the greatest common divisor of abs(this) and abs(that) - */ - def gcd (that: BigInt): BigInt = new BigInt(this.bigInteger.gcd(that.bigInteger)) - - /** Returns a BigInt whose value is (this mod m). - * This method differs from `%' in that it always returns a non-negative BigInt. - */ - def mod (that: BigInt): BigInt = new BigInt(this.bigInteger.mod(that.bigInteger)) - - /** Returns the minimum of this and that - */ - def min (that: BigInt): BigInt = new BigInt(this.bigInteger.min(that.bigInteger)) - - /** Returns the maximum of this and that - */ - def max (that: BigInt): BigInt = new BigInt(this.bigInteger.max(that.bigInteger)) - - /** Returns a BigInt whose value is (this raised to the power of exp). - */ - def pow (exp: Int): BigInt = new BigInt(this.bigInteger.pow(exp)) - - /** Returns a BigInt whose value is - * (this raised to the power of exp modulo m). - */ - def modPow (exp: BigInt, m: BigInt): BigInt = - new BigInt(this.bigInteger.modPow(exp.bigInteger, m.bigInteger)) - - /** Returns a BigInt whose value is (the inverse of this modulo m). - */ - def modInverse (m: BigInt): BigInt = new BigInt(this.bigInteger.modInverse(m.bigInteger)) - - /** Returns a BigInt whose value is the negation of this BigInt - */ - def unary_- : BigInt = new BigInt(this.bigInteger.negate()) - - /** Returns the absolute value of this BigInt - */ - def abs: BigInt = new BigInt(this.bigInteger.abs()) - - /** Returns the sign of this BigInt, i.e. - * -1 if it is less than 0, - * +1 if it is greater than 0 - * 0 if it is equal to 0 - */ - def signum: Int = this.bigInteger.signum() - - /** Returns the bitwise complement of this BigNum - */ - def ~ : BigInt = new BigInt(this.bigInteger.not()) - - /** Returns true if and only if the designated bit is set. - */ - def testBit (n: Int): Boolean = this.bigInteger.testBit(n) - - /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit set. - */ - def setBit (n: Int): BigInt = new BigInt(this.bigInteger.setBit(n)) - - /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit cleared. - */ - def clearBit(n: Int): BigInt = new BigInt(this.bigInteger.clearBit(n)) - - /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit flipped. - */ - def flipBit (n: Int): BigInt = new BigInt(this.bigInteger.flipBit(n)) - - /** Returns the index of the rightmost (lowest-order) one bit in this BigInt - * (the number of zero bits to the right of the rightmost one bit). - */ - def lowestSetBit: Int = this.bigInteger.getLowestSetBit() - - /** Returns the number of bits in the minimal two's-complement representation of this BigInt, - * excluding a sign bit. - */ - def bitLength: Int = this.bigInteger.bitLength() - - /** Returns the number of bits in the two's complement representation of this BigInt - * that differ from its sign bit. - */ - def bitCount: Int = this.bigInteger.bitCount() - - /** Returns true if this BigInt is probably prime, false if it's definitely composite. - * @param certainty a measure of the uncertainty that the caller is willing to tolerate: - * if the call returns true the probability that this BigInt is prime - * exceeds (1 - 1/2 ^ certainty). - * The execution time of this method is proportional to the value of - * this parameter. - */ - def isProbablePrime(certainty: Int) = this.bigInteger.isProbablePrime(certainty) - - /** Converts this BigInt to a byte. - * If the BigInt is too big to fit in a byte, only the low-order 8 bits are returned. - * Note that this conversion can lose information about the overall magnitude of the - * BigInt value as well as return a result with the opposite sign. - */ - override def byteValue = intValue.toByte - - /** Converts this BigInt to a short. - * If the BigInt is too big to fit in a byte, only the low-order 16 bits are returned. - * Note that this conversion can lose information about the overall magnitude of the - * BigInt value as well as return a result with the opposite sign. - */ - override def shortValue = intValue.toShort - - /** Converts this BigInt to a char. - * If the BigInt is too big to fit in a char, only the low-order 16 bits are returned. - * Note that this conversion can lose information about the overall magnitude of the - * BigInt value and that it always returns a positive result. - */ - def charValue = intValue.toChar - - /** Converts this BigInt to an int. - * If the BigInt is too big to fit in a char, only the low-order 32 bits - * are returned. Note that this conversion can lose information about the - * overall magnitude of the BigInt value as well as return a result with - * the opposite sign. - */ - def intValue = this.bigInteger.intValue - - /** Converts this BigInt to a long. - * If the BigInt is too big to fit in a char, only the low-order 64 bits - * are returned. Note that this conversion can lose information about the - * overall magnitude of the BigInt value as well as return a result with - * the opposite sign. - */ - def longValue = this.bigInteger.longValue - - /** Converts this BigInt to a float. - * if this BigInt has too great a magnitude to represent as a float, - * it will be converted to Float.NEGATIVE_INFINITY or - * Float.POSITIVE_INFINITY as appropriate. - */ - def floatValue = this.bigInteger.floatValue - - /** Converts this BigInt to a double. - * if this BigInt has too great a magnitude to represent as a float, - * it will be converted to Float.NEGATIVE_INFINITY or - * Float.POSITIVE_INFINITY as appropriate. - */ - def doubleValue = this.bigInteger.doubleValue - - /** Returns the decimal String representation of this BigInt. - */ - override def toString(): String = this.bigInteger.toString() - - /** Returns the String representation in the specified radix of this BigInt. - */ - def toString(radix: Int): String = this.bigInteger.toString(radix) - - /** Returns a byte array containing the two's-complement representation of - * this BigInt. The byte array will be in big-endian byte-order: the most - * significant byte is in the zeroth element. The array will contain the - * minimum number of bytes required to represent this BigInt, including at - * least one sign bit. - */ - def toByteArray: Array[Byte] = this.bigInteger.toByteArray() -} diff --git a/src/library/jvm/scala/CharSequence.scala b/src/library/jvm/scala/CharSequence.scala deleted file mode 100644 index 651650471c..0000000000 --- a/src/library/jvm/scala/CharSequence.scala +++ /dev/null @@ -1,172 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id: - - -package scala - -import java.io._ -import collection._ -import util.matching.Regex - -/** A Scala abstraction of character sequences, similar to, but richer than, - * java.lang.CharSequence. Sequences can be fixed or lazy. A lazy - * character sequence may be constructed only while it is read. - * - * @author Martin Odersky - */ -trait CharSequence extends java.lang.CharSequence with Seq[Char] { - - /** The length of the character sequence - * Note: if char sequence is lazy, calling this method - * will force sequence to be read until the end. - */ - def length: Int - - /** The character at position `index'. - */ - def charAt(index: Int): Char - - /** Is character sequence defined at `index'? - * Unlike `length' this operation does not force reading - * a lazy sequence to the end. - * (the implementation of that method is inherited from Seq). - */ - def isDefinedAt(index: Int): Boolean - - /** Optionally the character at position `index'. None is not in range. - */ - def get(index: Int): Option[Char] = - if (isDefinedAt(index)) Some(charAt(index)) - else None - - /** The character at position `index'. (same as `charAt') - */ - def apply(index: Int): Char = charAt(index) - - /** the subsequence from index `start' up to and excluding - * the minimum of index `end' and the length of current sequence. - */ - def subSequence(start: Int, end: Int): CharSequence - - /** The subsequence from index `start' until the end of the current sequence - * If sequence is lazy, this operation does not force reading to the end. - */ - def subSequence(start: Int): CharSequence = - subSequence(start, length) - - /** Convert sequence to string */ - def toString: String - - /** the elements of this sequence */ - def elements: Iterator[Char] = new Iterator[Char] { - private var index = 0 - def hasNext: Boolean = isDefinedAt(index) - def next: Char = { - val ch = charAt(index) - index += 1 - ch - } - } - - /** Return all matches of given regexp in this character sequence as an iterator - */ - def findAll(regex: Regex): Regex.MatchIterator = regex findAllIn this - - /** Return first match of given regexp in this character sequence as an optional value - */ - def findFirst(regex: Regex): Option[String] = regex findFirstIn this - - /** Return first match of given regexp in this character sequence as an optional value - */ - def findFirstMatch(regex: Regex): Option[Regex.Match] = regex findFirstMatchIn this - - /** Return optionally string matching given regexp at the beginning of this - * character sequence, or None if regexp matches no prefix - * of the character sequence. - */ - def findPrefix(regex: Regex): Option[String] = regex findPrefixOf this - - /** Return optionally match for given regexp at the beginning of this - * character sequence, or None if regexp matches no prefix - * of the character sequence. - */ - def findPrefixMatch(regex: Regex): Option[Regex.Match] = regex findPrefixMatchOf this - - /** Replaces all matches of given regexp by a string. - * - * @param regex The regex to match with - * @param replacement The string that will replace each match - * @return The resulting string - */ - def replaceAll(regex: Regex, replacement: String): String = regex replaceAllIn (this, replacement) - - /** Replaces the first match of given regexp by a string. - * - * @param target The string to match - * @param replacement The string that will replace the match - * @return The resulting string - */ - def replaceFirst(regex: Regex, replacement: String): String = regex replaceFirstIn (this, replacement) - - def toArray: Array[Char] = { - val len = length - val result = new Array[Char](len) - var i = 0 - while (i < len) { - result(i) = charAt(i) - i += 1 - } - result - } -} - -/** The CharSequence object defines variance implementations of character sequences - */ -object CharSequence { - - def fromJava(source: java.lang.CharSequence): CharSequence = - new JavaWrapper(source) - - def fromArray(source: Array[Char]): CharSequence = - new AsArray(source, 0, source.length) - def fromArray(source: Array[Char], start: Int): CharSequence = - new AsArray(source, start, source.length) - def fromArray(source: Array[Char], start: Int, end: Int): CharSequence = - new AsArray(source, start, end) - - private class JavaWrapper(source: java.lang.CharSequence) extends CharSequence { - def length: Int = source.length - def charAt(index: Int): Char = source.charAt(index) - def subSequence(start: Int, end: Int): CharSequence = new JavaWrapper(source.subSequence(start, end)) - override def toString: String = source.toString - } - - private class AsArray(source: scala.Array[Char], start: Int, end: Int) extends CharSequence { - if (start < 0) throw new IndexOutOfBoundsException - if (end > source.length) throw new IndexOutOfBoundsException - - def charAt(index: Int) = - if (start + index < end) source(index + start) - else throw new IndexOutOfBoundsException - - def length: Int = if (end < start) 0 else end - start - - def subSequence(_start: Int, _end: Int) = - new AsArray(source, start + _start, start + _end) - - override def toArray: Array[Char] = { - val result = new Array[Char](length) - compat.Platform.arraycopy(source, start, result, 0, length) - result - } - - override def toString = new String(source, start, end - start) - } -} diff --git a/src/library/jvm/scala/ClassfileAnnotation.scala b/src/library/jvm/scala/ClassfileAnnotation.scala deleted file mode 100644 index d5577a4523..0000000000 --- a/src/library/jvm/scala/ClassfileAnnotation.scala +++ /dev/null @@ -1,23 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -/**

- * A base class for classfile annotations. These are stored as - * Java annotations in classfiles. - *

- * - * @author Martin Odersky - * @version 1.1, 2/02/2007 - */ -trait ClassfileAnnotation extends Annotation diff --git a/src/library/jvm/scala/ClassfileAttribute.scala b/src/library/jvm/scala/ClassfileAttribute.scala deleted file mode 100644 index 23d48409b9..0000000000 --- a/src/library/jvm/scala/ClassfileAttribute.scala +++ /dev/null @@ -1,26 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -/**

- * A base class for classfile attributes. These are stored as - * Java annotations in classfiles. - *

- * - * @deprecated use ClassfileAnnotation instead - * @author Martin Odersky - * @version 1.1, 2/02/2007 - */ -@deprecated -trait ClassfileAttribute extends Attribute {} diff --git a/src/library/jvm/scala/Console.scala b/src/library/jvm/scala/Console.scala deleted file mode 100644 index fe29150caa..0000000000 --- a/src/library/jvm/scala/Console.scala +++ /dev/null @@ -1,345 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import java.io.{BufferedReader, InputStream, InputStreamReader, - OutputStream, PrintStream, Reader} -import java.text.MessageFormat - -import scala.util.DynamicVariable -import Predef._ - - -/** The Console object implements functionality for - * printing Scala values on the terminal. There are also functions - * for reading specific values. Console also defines - * constants for marking up text on ANSI terminals. - * - * @author Matthias Zenger - * @version 1.0, 03/09/2003 - */ -object Console { - - // ANSI colors foreground - final val BLACK = "\033[30m" - final val RED = "\033[31m" - final val GREEN = "\033[32m" - final val YELLOW = "\033[33m" - final val BLUE = "\033[34m" - final val MAGENTA = "\033[35m" - final val CYAN = "\033[36m" - final val WHITE = "\033[37m" - - // ANSI colors background - final val BLACK_B = "\033[40m" - final val RED_B = "\033[41m" - final val GREEN_B = "\033[42m" - final val YELLOW_B = "\033[43m" - final val BLUE_B = "\033[44m" - final val MAGENTA_B = "\033[45m" - final val CYAN_B = "\033[46m" - final val WHITE_B = "\033[47m" - - // ANSI styles - final val RESET = "\033[0m" - final val BOLD = "\033[1m" - final val UNDERLINED = "\033[4m" - final val BLINK = "\033[5m" - final val REVERSED = "\033[7m" - final val INVISIBLE = "\033[8m" - - private val outVar = new DynamicVariable[PrintStream](java.lang.System.out) - private val inVar = new DynamicVariable[BufferedReader]( - new BufferedReader(new InputStreamReader(java.lang.System.in))) - - def out = outVar.value - def in = inVar.value - - val err = java.lang.System.err - - /** Set the default output stream. - * - * @param out the new output stream. - */ - def setOut(out: PrintStream) { outVar.value = out } - - /** Set the default output stream for the duration - * of execution of one thunk. - * - * @param out the new output stream. - * @param thunk the code to execute with - * the new output stream active - * @return ... - */ - def withOut[T](out: PrintStream)(thunk: =>T): T = - outVar.withValue(out)(thunk) - - /** Set the default output stream. - * - * @param@ out the new output stream. - */ - def setOut(out: OutputStream): Unit = - setOut(new PrintStream(out)) - - /** Set the default output stream for the duration - * of execution of one thunk. - * - * @param out the new output stream. - * @param thunk the code to execute with - * the new output stream active - * @return ... - */ - def withOut[T](out: OutputStream)(thunk: =>T): T = - withOut(new PrintStream(out))(thunk) - - - /** Set the default input stream. - * - * @param reader specifies the new input stream. - */ - def setIn(reader: Reader): Unit = { - inVar.value = new BufferedReader(reader) - } - - /** Set the default input stream for the duration - * of execution of one thunk. - * - * @param in the new input stream. - * @param thunk the code to execute with - * the new input stream active - */ - def withIn[T](reader: Reader)(thunk: =>T): T = - inVar.withValue(new BufferedReader(reader))(thunk) - - - /** Set the default input stream. - * - * @param in the new input stream. - */ - def setIn(in: InputStream): Unit = - setIn(new InputStreamReader(in)) - - /** Set the default input stream for the duration - * of execution of one thunk. - * - * @param in the new input stream. - * @param thunk the code to execute with - * the new input stream active - */ - def withIn[T](in: InputStream)(thunk: =>T): T = - withIn(new InputStreamReader(in))(thunk) - - /** Print an object on the terminal. - * - * @param obj the object to print. - */ - def print(obj: Any): Unit = - out.print(if (null == obj) "null" else obj.toString()) - - /** Flush the output stream. This function is required when partial - * output (i.e. output not terminated by a new line character) has - * to be made visible on the terminal. - */ - def flush() { out.flush() } - - /** Print a new line character on the terminal. - */ - def println(): Unit = out.println() - - /** Print out an object followed by a new line character. - * - * @param x the object to print. - */ - def println(x: Any): Unit = out.println(x) - - /**

- * Prints its arguments as a formatted string, based on a string - * pattern (in a fashion similar to printf in C). - *

- *

- * The interpretation of the formatting patterns is described in - * - * java.text.MessageFormat. - *

- * - * @param text the pattern for formatting the arguments. - * @param args the arguments used to instantiating the pattern. - * @throws java.lang.IllegalArgumentException - */ - def printf(text: String, args: Any*) { format(text, args: _*) } - - /** - * @see Console.printf. - */ - def format(text: String, args: Any*): Unit = - out.print( - if (text eq null) "null" - else MessageFormat.format(text, textParams(args)) - ) - - /** Read a full line from the terminal. - * - * @return the string read from the terminal. - */ - def readLine(): String = in.readLine() - - /** Print a formatted text and read a full line from the terminal - * - * @param text the format of the text to print out. - * @param args the parameters used to instantiate the format. - * @return the string read from the terminal. - */ - def readLine(text: String, args: Any*): String = { - format(text, args: _*) - readLine() - } - - - /** Read a boolean value from the terminal. - * - * @return the boolean value read from the terminal. - */ - def readBoolean(): Boolean = readLine().toLowerCase() match { - case "true" => true - case "t" => true - case "yes" => true - case "y" => true - case _ => false - } - - /** Read a byte value from the terminal. - */ - def readByte(): Byte = readLine().toByte - - /** Read a short value from the terminal. - */ - def readShort(): Short = readLine().toShort - - /** Read a char value from the terminal. - */ - def readChar(): Char = readLine() charAt 0 - - /** Read an int value from the terminal. - */ - def readInt(): Int = readLine().toInt - - /** Read an int value from the terminal. - */ - def readLong(): Long = readLine().toLong - - /** Read a float value from the terminal. - */ - def readFloat(): Float = readLine().toFloat - - /** Read a double value from the terminal. - */ - def readDouble(): Double = readLine().toDouble - - /** Read in some structured input, specified by a format specifier. - * See class java.text.MessageFormat for details of - * the format specification. - * - * @param format the format of the input. - * @return a list of all extracted values. - */ - def readf(format: String): List[Any] = - textComponents(new MessageFormat(format).parse(readLine())) - - /** Read in some structured input, specified by a format specifier. - * Opposed to readf, this function only returns the - * first value extracted from the input according to the format - * specification. - * - * @param format ... - * @return ... - */ - def readf1(format: String): Any = readf(format).head - - /** Read in some structured input, specified by a format specifier. - * Opposed to readf, this function only returns the - * first two values extracted from the input according to the format - * specification. - * - * @param format ... - * @return ... - */ - def readf2(format: String): (Any, Any) = { - val res = readf(format) - (res.head, res.tail.head) - } - - /** Read in some structured input, specified by a format specifier. - * Opposed to readf, this function only returns the - * first three values extracted from the input according to the format - * specification. - * - * @param format ... - * @return ... - */ - def readf3(format: String): (Any, Any, Any) = { - val res = readf(format) - (res.head, res.tail.head, res.tail.tail.head) - } - - private def textComponents(a: Array[AnyRef]): List[Any] = { - var i: Int = a.length - 1 - var res: List[Any] = Nil - while (i >= 0) { - res = (a(i) match { - case x: java.lang.Boolean => x.booleanValue() - case x: java.lang.Byte => x.byteValue() - case x: java.lang.Short => x.shortValue() - case x: java.lang.Character => x.charValue() - case x: java.lang.Integer => x.intValue() - case x: java.lang.Long => x.longValue() - case x: java.lang.Float => x.floatValue() - case x: java.lang.Double => x.doubleValue() - case x => x - }) :: res; - i -= 1 - } - res - } - - private def textParams(s: Seq[Any]): Array[AnyRef] = { - val res = new Array[AnyRef](s.length) - var i: Int = 0 - val iter = s.elements - while (iter.hasNext) { - res(i) = iter.next match { - case x: Boolean => java.lang.Boolean.valueOf(x) - /** Should use java.lang.Byte.valueOf(Byte), but only available - * in Java 1.5 and above. */ - case x: Byte => new java.lang.Byte(x) - /** Should use java.lang.Short.valueOf(Short), but only available - * in Java 1.5 and above. */ - case x: Short => new java.lang.Short(x) - /** Should use java.lang.Character.valueOf(Char), but only available - * in Java 1.5 and above. */ - case x: Char => new java.lang.Character(x) - /** Should use java.lang.Integer.valueOf(Int), but only available - * in Java 1.5 and above. */ - case x: Int => new java.lang.Integer(x) - /** Should use java.lang.Long.valueOf(Long), but only available - * in Java 1.5 and above. */ - case x: Long => new java.lang.Long(x) - case x: Float => new java.lang.Float(x) - case x: Double => new java.lang.Double(x) - case x: Unit => "()" - case x: AnyRef => x - } - i += 1 - } - res - } -} diff --git a/src/library/jvm/scala/LazyCharSequence.scala b/src/library/jvm/scala/LazyCharSequence.scala deleted file mode 100644 index bde51f8bd1..0000000000 --- a/src/library/jvm/scala/LazyCharSequence.scala +++ /dev/null @@ -1,265 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import java.io._ -import util.matching.Regex - - -/** The CharSequence object defines variance implementations of character sequences - */ -object LazyCharSequence { - final val UndeterminedEnd = Math.MAX_INT - - /** Constructs a character sequence from a character iterator */ - def fromChars(source: Iterator[Char]): CharSequence = - new LazyCharSequence ((chars: Array[Char], start: Int, len: Int) => { - var i = 0 - while (i < len && source.hasNext) { - chars(start + i) = source.next - i += 1 - } - if (i == 0) -1 else i - }) - - /** Constructs a character sequence from a character iterable */ - def fromChars(source: Iterable[Char]): CharSequence = - fromChars(source.elements) - - /** Constructs a character sequence from a string iterator */ - def fromStrings(source: Iterator[String]): CharSequence = { - var current: String = "" - def more(chars: Array[Char], start: Int, len: Int): Int = - if (current.length != 0) { - val nchars = current.length min len - current.getChars(0, nchars, chars, start) - current = current.substring(nchars) - if (nchars == len) nchars - else (more(chars, start + nchars, len - nchars) max 0) + nchars - } else if (source.hasNext) { - current = source.next - more(chars, start, len) - } else -1 - new LazyCharSequence(more(_: Array[Char], _: Int, _: Int)) - } - - /** Constructs a character sequence from a string iterable */ - def fromStrings(source: Iterable[String]): CharSequence = - fromStrings(source.elements) - - /** Constructs a character sequence from a line iterator - * Lines do not contain trailing `\n' characters; The method inserts - * a line separator `\n' between any two lines in the sequence. - */ - def fromLines(source: Iterator[String]): CharSequence = { - var isFirst = true - fromStrings(source map { line => - if (isFirst) line - else { - isFirst = false - "\n"+line - } - }) - } - - /** Constructs a character sequence from a line iterable - * Lines do not contain trailing `\n' characters; The method inserts - * a line separator `\n' between any two lines in the sequence. - */ - def fromLines(source: Iterable[String]): CharSequence = - fromLines(source.elements) - - /** Constructs a character sequence from an input reader - */ - def fromReader(source: Reader): CharSequence = - new LazyCharSequence(source) - - /** Constructs a character sequence from an input file - */ - def fromFile(source: File) = - new LazyCharSequence(source) - - /** Constructs a character sequence from a file with given name - */ - def fromFile(source: String) = - new LazyCharSequence(source) - - /** Constructs a character sequence from a scala.io.Source value - */ - def fromSource(source: io.Source) = - fromLines(source.getLines) -} - - -import LazyCharSequence._ - -/** An implementation of lazily computed character sequences - * - * @author Martin Odersky - */ -class LazyCharSequence protected (more: (Array[Char], Int, Int) => Int, - first: Page, start: Int, end: Int) extends CharSequence { - - /** Constructs a character sequence from a method that produces more characters when asked. - * The producer method is analogous to the read method in java.io.Reader. - * It takes three parameters: an array of characters, a start index, and an end index. - * It should try to fill the array between start and end indices (not including end index). - * It returns the number of characters produced, or -1 if end of logical input stream was reached - * before any character was read. - */ - def this(more: (Array[Char], Int, Int) => Int) = this(more, new Page(0), 0, UndeterminedEnd) - - /** Constructs a character sequence from an input reader - */ - def this(source: Reader) = - this(source.read(_: Array[Char], _: Int, _: Int)) - - /** Constructs a character sequence from an input file - */ - def this(source: File) = - this(new FileReader(source)) - - /** Constructs a character sequence from a file with given name - */ - def this(source: String) = - this(new File(source)) - - private var current: Page = first - - private def latest = first.latest - - private def addMore() = latest.addMore(more) - - private def page(absindex: Int) = { - if (absindex < current.start) - current = first - while (absindex >= current.end && current.next != null) - current = current.next - while (absindex >= current.end && !current.isLast) { - current = addMore() - } - current - } - - /** The length of the character sequence - * Note: calling this method will force sequence to be read until the end. - */ - def length: Int = { - while (!latest.isLast) addMore() - (latest.end min end) - start - } - - /** The character at position `index'. - */ - def charAt(index: Int) = - if (isDefinedAt(index)) page(index + start)(index + start) - else throw new IndexOutOfBoundsException(index.toString) - - /** Is character sequence defined at `index'? - * Unlike `length' this operation does not force reading - * a lazy sequence to the end. - */ - override def isDefinedAt(index: Int) = - index >= 0 && index < end - start && { - val p = page(index + start); index + start < p.end - } - - /** Optionally the character at position `index'. None is not in range. - */ - override def get(index: Int) = - if (isDefinedAt(index)) Some(page(index + start)(index + start)) - else None - - /** the subsequence from index `start' up to and excluding - * the minimum of index `end' and the length of current sequence. - */ - def subSequence(_start: Int, _end: Int) = { - page(start) - val s = start + _start - val e = if (_end == UndeterminedEnd) _end else start + _end - var f = first - while (f.end <= s && !f.isLast) f = f.next - new LazyCharSequence(more, f, s, e) - } - - /** The subsequence from index `start' until the end of the current sequence - * This operation does not force reading to the end. - */ - override def subSequence(start: Int): CharSequence = - subSequence(start, UndeterminedEnd) - - /** Convert sequence to string */ - override def toString = { - val buf = new StringBuilder - for (ch <- elements) buf append ch - buf.toString - } -} - - -/** Page containing up to PageSize characters of the input sequence. - */ -private class Page(val num: Int) { - - private final val PageSize = 4096 - - /** The next page in the sequence */ - var next : Page = null - - /** A later page in the sequence, serves a cachae for pointing to last page */ - var later : Page = this - - /** The number of characters read into this page */ - var filled: Int = 0 - - /** Is this page the permamnently last one in the sequence? Only true once `more' - * method has returned -1 to signal end of input. */ - var isLast: Boolean = false - - /** The character array */ - final val chars = new Array[Char](PageSize) - - /** The index of the first character in this page relative to the whole sequence */ - final def start = num * PageSize - - /** The index of the character following the last charcater in this page relative - * to the whole sequence */ - final def end = start + filled - - /** The currently last page in the sequence; might change as more charcaters are appended */ - final def latest: Page = { - if (later.next != null) later = later.next.latest - later - } - - /** The character at given sequence index. - * That index is relative to the whole sequence, not the page. */ - def apply(index: Int) = { - if (index < start || index - start >= filled) throw new IndexOutOfBoundsException(index.toString) - chars(index - start) - } - - /** produces more characters by calling `more' and appends them on the current page, - * or fills a subsequent page if current page is full - * pre: if current page is full, it is the last one in the sequence. - */ - final def addMore(more: (Array[Char], Int, Int) => Int): Page = - if (filled == PageSize) { - next = new Page(num + 1) - next.addMore(more) - } else { - val count = more(chars, filled, PageSize - filled) - if (count < 0) isLast = true - else filled += count - this - } -} diff --git a/src/library/jvm/scala/List.scala b/src/library/jvm/scala/List.scala deleted file mode 100644 index f87b034cde..0000000000 --- a/src/library/jvm/scala/List.scala +++ /dev/null @@ -1,1339 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import scala.collection.mutable.ListBuffer -import Predef._ - -/** This object provides methods for creating specialized lists, and for - * transforming special kinds of lists (e.g. lists of lists). - * - * @author Martin Odersky and others - * @version 1.0, 15/07/2003 - */ -object List { - - /** Create a list with given elements. - * - * @param xs the elements to put in the list - * @return the list containing elements xs. - */ - def apply[A](xs: A*): List[A] = xs.toList - - /** for unapply matching - */ - def unapplySeq[A](x: List[A]): Some[List[A]] = Some(x) - - /** Create a sorted list of all integers in a range. - * - * @param from the start value of the list - * @param end the end value of the list - * @return the sorted list of all integers in range [from;end). - */ - def range(start: Int, end: Int): List[Int] = - range(start, end, 1) - - /** Create a list with element values - * vn+1 = vn + step - * where v0 = start - * and elements are in the range between start (inclusive) - * and end (exclusive) - * - * @param start the start value of the list - * @param end the end value of the list - * @param step the increment value of the list - * @return the sorted list of all integers in range [start;end). - */ - def range(start: Int, end: Int, step: Int): List[Int] = { - val b = new ListBuffer[Int] - var i = start - while ((step <= 0 || i < end) && (step >= 0 || i > end)) { - b += i - i += step - } - b.toList - } - - /** Create a sorted list with element values - * vn+1 = step(vn) - * where v0 = start - * and elements are in the range between start (inclusive) - * and end (exclusive) - * - * @param start the start value of the list - * @param end the end value of the list - * @param step the increment function of the list, must be monotonically increasing or decreasing - * @return the sorted list of all integers in range [start;end). - */ - def range(start: Int, end: Int, step: Int => Int): List[Int] = { - val up = step(start) > start - val down = step(start) < start - val b = new ListBuffer[Int] - var i = start - while ((!up || i < end) && (!down || i > end)) { - b += i - i += step(i) - } - b.toList - } - - /** Create a list containing several copies of an element. - * - * @param n the length of the resulting list - * @param elem the element composing the resulting list - * @return a list composed of n elements all equal to elem - */ - def make[A](n: Int, elem: A): List[A] = { - val b = new ListBuffer[A] - var i = 0 - while (i < n) { - b += elem - i += 1 - } - b.toList - } - - /** Create a list by applying a function to successive integers. - * - * @param n the length of the resulting list - * @param maker the procedure which, given an integer n, - * returns the nth element of the resulting list, where - * n is in interval [0;n). - * @return the list obtained by applying the maker function to - * successive integers from 0 to n (exclusive). - */ - def tabulate[A](n: Int, maker: Int => A): List[A] = { - val b = new ListBuffer[A] - var i = 0 - while (i < n) { - b += maker(i) - i += 1 - } - b.toList - } - - /** Concatenate all the elements of a given list of lists. - * - * @param xss the list of lists that are to be concatenated - * @return the concatenation of all the lists - */ - def flatten[A](xss: List[List[A]]): List[A] = concat(xss: _*) - - /** Concatenate all the argument lists into a single list. - * - * @param xss the lists that are to be concatenated - * @return the concatenation of all the lists - */ - def concat[A](xss: List[A]*): List[A] = { - val b = new ListBuffer[A] - for (xs <- xss) { - var xc = xs - while (!xc.isEmpty) { - b += xc.head - xc = xc.tail - } - } - b.toList - } - - /** Transforms a list of pair into a pair of lists. - * - * @param xs the list of pairs to unzip - * @return a pair of lists: the first list in the pair contains the list - */ - def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = { - val b1 = new ListBuffer[A] - val b2 = new ListBuffer[B] - var xc = xs - while (!xc.isEmpty) { - b1 += xc.head._1 - b2 += xc.head._2 - xc = xc.tail - } - (b1.toList, b2.toList) - } - - /** Converts an iterator to a list. - * - * @param it the iterator to convert - * @return a list that contains the elements returned by successive - * calls to it.next - */ - def fromIterator[A](it: Iterator[A]): List[A] = it.toList - - /** Converts an array into a list. - * - * @param arr the array to convert - * @return a list that contains the same elements than arr - * in the same order - */ - def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length) - - /** Converts a range of an array into a list. - * - * @param arr the array to convert - * @param start the first index to consider - * @param len the lenght of the range to convert - * @return a list that contains the same elements than arr - * in the same order - */ - def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = { - var res: List[A] = Nil - var i = start + len - while (i > start) { - i -= 1 - res = arr(i) :: res - } - res - } - - /** Parses a string which contains substrings separated by a - * separator character and returns a list of all substrings. - * - * @param str the string to parse - * @param separator the separator character - * @return the list of substrings - */ - def fromString(str: String, separator: Char): List[String] = { - var words: List[String] = Nil - var pos = str.length() - while (pos > 0) { - val pos1 = str.lastIndexOf(separator, pos - 1) - if (pos1 + 1 < pos) - words = str.substring(pos1 + 1, pos) :: words - pos = pos1 - } - words - } - - /** Returns the given string as a list of characters. - * - * @param str the string to convert. - * @return the string as a list of characters. - * @deprecated use str.toList instead - */ - @deprecated def fromString(str: String): List[Char] = - str.toList - - /** Returns the given list of characters as a string. - * - * @param xs the list to convert. - * @return the list in form of a string. - */ - def toString(xs: List[Char]): String = { - val sb = new StringBuilder() - var xc = xs - while (!xc.isEmpty) { - sb.append(xc.head) - xc = xc.tail - } - sb.toString() - } - - /** Like xs map f, but returns xs unchanged if function - * f maps all elements to themselves. - * - * @param xs ... - * @param f ... - * @return ... - */ - def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = { - def loop(ys: List[A]): List[A] = - if (ys.isEmpty) xs - else { - val head0 = ys.head - val head1 = f(head0) - if (head1 eq head0) { - loop(ys.tail) - } else { - val ys1 = head1 :: mapConserve(ys.tail)(f) - if (xs eq ys) ys1 - else { - val b = new ListBuffer[A] - var xc = xs - while (xc ne ys) { - b += xc.head - xc = xc.tail - } - b.prependToList(ys1) - } - } - } - loop(xs) - } - - /** Returns the list resulting from applying the given function f - * to corresponding elements of the argument lists. - * - * @param f function to apply to each pair of elements. - * @return [f(a0,b0), ..., f(an,bn)] if the lists are - * [a0, ..., ak], [b0, ..., bl] and - * n = min(k,l) - */ - def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = { - val b = new ListBuffer[C] - var xc = xs - var yc = ys - while (!xc.isEmpty && !yc.isEmpty) { - b += f(xc.head, yc.head) - xc = xc.tail - yc = yc.tail - } - b.toList - } - - /** Returns the list resulting from applying the given function - * f to corresponding elements of the argument lists. - * - * @param f function to apply to each pair of elements. - * @return [f(a0,b0,c0), - * ..., f(an,bn,cn)] - * if the lists are [a0, ..., ak], - * [b0, ..., bl], - * [c0, ..., cm] and - * n = min(k,l,m) - */ - def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = { - val b = new ListBuffer[D] - var xc = xs - var yc = ys - var zc = zs - while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) { - b += f(xc.head, yc.head, zc.head) - xc = xc.tail - yc = yc.tail - zc = zc.tail - } - b.toList - } - - /** Tests whether the given predicate p holds - * for all corresponding elements of the argument lists. - * - * @param p function to apply to each pair of elements. - * @return (p(a0,b0) && - * ... && p(an,bn))] - * if the lists are [a0, ..., ak]; - * [b0, ..., bl] - * and n = min(k,l) - */ - def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { - var xc = xs - var yc = ys - while (!xc.isEmpty && !yc.isEmpty) { - if (!f(xc.head, yc.head)) return false - xc = xc.tail - yc = yc.tail - } - true - } - - /** Tests whether the given predicate p holds - * for some corresponding elements of the argument lists. - * - * @param p function to apply to each pair of elements. - * @return n != 0 && (p(a0,b0) || - * ... || p(an,bn))] if the lists are - * [a0, ..., ak], - * [b0, ..., bl] and - * n = min(k,l) - */ - def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { - var xc = xs - var yc = ys - while (!xc.isEmpty && !yc.isEmpty) { - if (f(xc.head, yc.head)) return true - xc = xc.tail - yc = yc.tail - } - false - } - - /** Transposes a list of lists. - * pre: All element lists have the same length. - * - * @param xss the list of lists - * @return the transposed list of lists - */ - def transpose[A](xss: List[List[A]]): List[List[A]] = { - val buf = new ListBuffer[List[A]] - var yss = xss - while (!yss.head.isEmpty) { - buf += (yss map (_.head)) - yss = (yss map (_.tail)) - } - buf.toList - } - - /** Lists with ordered elements are ordered - implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] { - def compare [b >: List[a] <% Ordered[b]](y: b): Int = y match { - case y1: List[a] => compareLists(x, y1); - case _ => -(y compare x) - } - private def compareLists(xs: List[a], ys: List[a]): Int = { - if (xs.isEmpty && ys.isEmpty) 0 - else if (xs.isEmpty) -1 - else if (ys.isEmpty) 1 - else { - val s = xs.head compare ys.head; - if (s != 0) s - else compareLists(xs.tail, ys.tail) - } - } - } - */ -} - -/** A class representing an ordered collection of elements of type - * a. This class comes with two implementing case - * classes scala.Nil and scala.:: that - * implement the abstract members isEmpty, - * head and tail. - * - * @author Martin Odersky and others - * @version 1.0, 16/07/2003 - */ -sealed abstract class List[+A] extends Seq[A] { - - /** Returns true if the list does not contain any elements. - * @return true, iff the list is empty. - */ - override def isEmpty: Boolean - - /** Returns this first element of the list. - * - * @return the first element of this list. - * @throws Predef.NoSuchElementException if the list is empty. - */ - def head: A - - /** returns length - l, without calling length - */ - override def lengthCompare(l: Int) = { - if (isEmpty) 0 - l - else if (l <= 0) 1 - else tail.lengthCompare(l - 1) - } - - /** Returns this list without its first element. - * - * @return this list without its first element. - * @throws Predef.NoSuchElementException if the list is empty. - */ - def tail: List[A] - - /**

- * Add an element x at the beginning of this list. - *

- * - * @param x the element to prepend. - * @return the list with x added at the beginning. - * @ex 1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3) - */ - def ::[B >: A] (x: B): List[B] = - new scala.::(x, this) - - /**

- * Add an element x at the end of this list. - *

- * - * @param x the element to append. - * @return the list with x added at the end. - */ - def +[B >: A](x: B): List[B] = - if (isEmpty) List(x) - else { - val buf = new ListBuffer[B] - this copyToBuffer buf - buf += x - buf.toList - } - - /**

- * Returns a list resulting from the concatenation of the given - * list prefix and this list. - *

- * - * @param prefix the list to concatenate at the beginning of this list. - * @return the concatenation of the two lists. - * @ex List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4) - */ - def :::[B >: A](prefix: List[B]): List[B] = - if (isEmpty) prefix - else { - val b = new ListBuffer[B] - var those = prefix - while (!those.isEmpty) { - b += those.head - those = those.tail - } - b.prependToList(this) - } - - /** Appends two list objects. - */ - override def ++[B >: A](that: Iterable[B]): List[B] = { - val buf = new ListBuffer[B] - this copyToBuffer buf - that copyToBuffer buf - buf.toList - } - - /** Reverse the given prefix and append the current list to that. - * This function is equivalent to an application of reverse - * on the prefix followed by a call to :::, but more - * efficient (and tail recursive). - * - * @param prefix the prefix to reverse and then prepend - * @return the concatenation of the reversed prefix and the current list. - */ - def reverse_:::[B >: A](prefix: List[B]): List[B] = { - var these: List[B] = this - var pres = prefix - while (!pres.isEmpty) { - these = pres.head :: these - pres = pres.tail - } - these - } - - /** Returns the number of elements in the list. - * - * @return the number of elements in the list. - */ - def length: Int = { - var these = this - var len = 0 - while (!these.isEmpty) { - len += 1 - these = these.tail - } - len - } - - /** Creates a list with all indices in the list. This is - * equivalent to a call to List.range(0, xs.length). - * - * @return a list of all indices in the list. - */ - def indices: List[Int] = { - val b = new ListBuffer[Int] - var i = 0 - var these = this - while (!these.isEmpty) { - b += i - i += 1 - these = these.tail - } - b.toList - } - - /** Returns the elements in the list as an iterator - * - * @return an iterator on the list elements. - */ - override def elements: Iterator[A] = new Iterator[A] { - var these = List.this - def hasNext: Boolean = !these.isEmpty - def next: A = - if (!hasNext) - throw new NoSuchElementException("next on empty Iterator") - else { - val result = these.head; these = these.tail; result - } - override def toList: List[A] = these - } - - /** Overrides the method in Iterable for efficiency. - * - * @return the list itself - */ - override def toList: List[A] = this - - /** Returns the list without its last element. - * - * @return the list without its last element. - * @throws Predef.UnsupportedOperationException if the list is empty. - */ - def init: List[A] = - if (isEmpty) throw new UnsupportedOperationException("Nil.init") - else { - val b = new ListBuffer[A] - var elem = head - var next = tail - while (!next.isEmpty) { - b += elem - elem = next.head - next = next.tail - } - b.toList - } - - /** Returns the last element of this list. - * - * @return the last element of the list. - * @throws Predef.NoSuchElementException if the list is empty. - */ - override def last: A = - if (isEmpty) throw new Predef.NoSuchElementException("Nil.last") - else { - var cur = this - var next = this.tail - while (!next.isEmpty) { - cur = next - next = next.tail - } - cur.head - } - - /** Returns the n first elements of this list, or else the whole - * list, if it has less than n elements. - * - * @param n the number of elements to take. - * @return the n first elements of this list. - */ - override def take(n: Int): List[A] = { - val b = new ListBuffer[A] - var i = 0 - var these = this - while (!these.isEmpty && i < n) { - i += 1 - b += these.head - these = these.tail - } - if (these.isEmpty) this - else b.toList - } - - /** Returns the list with elements belonging to the given index range. - * - * @param start the start position of the list slice. - * @param end the end position (exclusive) of the list slice. - * @return the list with elements belonging to the given index range. - */ - override def slice(start: Int, end: Int): List[A] = { - val s = start max 0 - val e = end min this.length - drop(s) take (e - s) - } - - /** Returns the list without its n first elements. - * If this list has less than n elements, the empty list is returned. - * - * @param n the number of elements to drop. - * @return the list without its n first elements. - */ - override def drop(n: Int): List[A] = { - var these = this - var count = n - while (!these.isEmpty && count > 0) { - these = these.tail - count -= 1 - } - these - } - - /** Returns the rightmost n elements from this list. - * - * @param n the number of elements to take - * @return the suffix of length n of the list - */ - def takeRight(n: Int): List[A] = { - def loop(lead: List[A], lag: List[A]): List[A] = lead match { - case Nil => lag - case _ :: tail => loop(tail, lag.tail) - } - loop(drop(n), this) - } - - /** Returns the list wihout its rightmost n elements. - * - * @param n the number of elements to take - * @return the suffix of length n of the list - */ - def dropRight(n: Int): List[A] = { - def loop(lead: List[A], lag: List[A]): List[A] = lead match { - case Nil => Nil - case _ :: tail => lag.head :: loop(tail, lag.tail) - } - loop(drop(n), this) - } - - /** Split the list at a given point and return the two parts thus - * created. - * - * @param n the position at which to split - * @return a pair of lists composed of the first n - * elements, and the other elements. - */ - def splitAt(n: Int): (List[A], List[A]) = { - val b = new ListBuffer[A] - var i = 0 - var these = this - while (!these.isEmpty && i < n) { - i += 1 - b += these.head - these = these.tail - } - (b.toList, these) - } - - /** Returns the longest prefix of this list whose elements satisfy - * the predicate p. - * - * @param p the test predicate. - * @return the longest prefix of this list whose elements satisfy - * the predicate p. - */ - override def takeWhile(p: A => Boolean): List[A] = { - val b = new ListBuffer[A] - var these = this - while (!these.isEmpty && p(these.head)) { - b += these.head - these = these.tail - } - b.toList - } - - /** Returns the longest suffix of this list whose first element - * does not satisfy the predicate p. - * - * @param p the test predicate. - * @return the longest suffix of the list whose first element - * does not satisfy the predicate p. - */ - override def dropWhile(p: A => Boolean): List[A] = - if (isEmpty || !p(head)) this - else tail dropWhile p - - /** Returns the longest prefix of the list whose elements all satisfy - * the given predicate, and the rest of the list. - * - * @param p the test predicate - * @return a pair consisting of the longest prefix of the list whose - * elements all satisfy p, and the rest of the list. - */ - def span(p: A => Boolean): (List[A], List[A]) = { - val b = new ListBuffer[A] - var these = this - while (!these.isEmpty && p(these.head)) { - b += these.head - these = these.tail - } - (b.toList, these) - } - - /** Like span but with the predicate inverted. - */ - def break(p: A => Boolean): (List[A], List[A]) = span { x => !p(x) } - - /** Returns the n-th element of this list. The first element - * (head of the list) is at position 0. - * - * @param n index of the element to return - * @return the element at position n in this list. - * @throws Predef.NoSuchElementException if the list is too short. - */ - def apply(n: Int): A = drop(n).head - - /** Returns the list resulting from applying the given function f to each - * element of this list. - * - * @param f function to apply to each element. - * @return [f(a0), ..., f(an)] if this list is [a0, ..., an]. - */ - final override def map[B](f: A => B): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - b += f(these.head) - these = these.tail - } - b.toList - } - - /** Apply a function to all the elements of the list, and return the - * reversed list of results. This is equivalent to a call to map - * followed by a call to reverse, but more efficient. - * - * @param f the function to apply to each elements. - * @return the reversed list of results. - */ - def reverseMap[B](f: A => B): List[B] = { - def loop(l: List[A], res: List[B]): List[B] = l match { - case Nil => res - case head :: tail => loop(tail, f(head) :: res) - } - loop(this, Nil) - } - - /** Apply the given function f to each element of this list - * (while respecting the order of the elements). - * - * @param f the treatment to apply to each element. - */ - final override def foreach(f: A => Unit) { - var these = this - while (!these.isEmpty) { - f(these.head) - these = these.tail - } - } - - /** Returns all the elements of this list that satisfy the - * predicate p. The order of the elements is preserved. - * It is guarenteed that the receiver list itself is returned iff all its - * elements satisfy the predicate `p'. Hence the following equality is valid: - * - * (xs filter p) eq xs == xs forall p - * - * @param p the predicate used to filter the list. - * @return the elements of this list satisfying p. - */ - final override def filter(p: A => Boolean): List[A] = { - // return same list if all elements satisfy p - var these = this - while (!these.isEmpty && p(these.head)) { - these = these.tail - } - if (these.isEmpty) this - else { - val b = new ListBuffer[A] - var these1 = this - while (these1 ne these) { - b += these1.head - these1 = these1.tail - } - - these = these.tail // prevent the second evaluation of the predicate - // on the element on which it first failed - while (!these.isEmpty) { - if (p(these.head)) b += these.head - these = these.tail - } - b.toList - } - } - -// final def filterMap[B](f: PartialFunction[A, B]): List[B] = -// this filter f.isDefinedAt map f - - /** Removes all elements of the list which satisfy the predicate - * p. This is like filter with the - * predicate inversed. - * - * @param p the predicate to use to test elements - * @return the list without all elements which satisfy p - */ - def remove(p: A => Boolean): List[A] = filter (x => !p(x)) - - /** Partition the list in two sub-lists according to a predicate. - * - * @param p the predicate on which to partition - * @return a pair of lists: the list of all elements which satisfy - * p and the list of all elements which do not. - * The relative order of the elements in the sub-lists is the - * same as in the original list. - */ - override def partition(p: A => Boolean): (List[A], List[A]) = { - val btrue = new ListBuffer[A] - val bfalse = new ListBuffer[A] - var these = this - while (!these.isEmpty) { - (if (p(these.head)) btrue else bfalse) += these.head - these = these.tail - } - (btrue.toList, bfalse.toList) - } - - /**

- * Sort the list according to the comparison function - * <(e1: a, e2: a) => Boolean, - * which should be true iff e1 is smaller than - * e2. - *

- * - * @param lt the comparison function - * @return a list sorted according to the comparison function - * <(e1: a, e2: a) => Boolean. - * @ex
-   *    List("Steve", "Tom", "John", "Bob")
-   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
-   *    List("Bob", "John", "Steve", "Tom")
- */ - def sort(lt : (A,A) => Boolean): List[A] = { - /** Merge two already-sorted lists */ - def merge(l1: List[A], l2: List[A]): List[A] = { - val res = new ListBuffer[A] - var left1 = l1 - var left2 = l2 - - while (!left1.isEmpty && !left2.isEmpty) { - if(lt(left1.head, left2.head)) { - res += left1.head - left1 = left1.tail - } else { - res += left2.head - left2 = left2.tail - } - } - - res ++= left1 - res ++= left2 - - res.toList - } - - /** Split a list into two lists of about the same size */ - def split(lst: List[A]) = { - val res1 = new ListBuffer[A] - val res2 = new ListBuffer[A] - var left = lst - - while (!left.isEmpty) { - res1 += left.head - left = left.tail - if (!left.isEmpty) { - res2 += left.head - left = left.tail - } - } - - (res1.toList, res2.toList) - } - - - /** Merge-sort the specified list */ - def ms(lst: List[A]): List[A] = - lst match { - case Nil => lst - case x :: Nil => lst - case x :: y :: Nil => - if (lt(x,y)) - lst - else - y :: x :: Nil - - case lst => - val (l1, l2) = split(lst) - val l1s = ms(l1) - val l2s = ms(l2) - merge(l1s, l2s) - } - - ms(this) - } - - - /** Count the number of elements in the list which satisfy a predicate. - * - * @param p the predicate for which to count - * @return the number of elements satisfying the predicate p. - */ - def count(p: A => Boolean): Int = { - var cnt = 0 - var these = this - while (!these.isEmpty) { - if (p(these.head)) cnt += 1 - these = these.tail - } - cnt - } - - /** Tests if the predicate p is satisfied by all elements - * in this list. - * - * @param p the test predicate. - * @return true iff all elements of this list satisfy the - * predicate p. - */ - override def forall(p: A => Boolean): Boolean = { - var these = this - while (!these.isEmpty) { - if (!p(these.head)) return false - these = these.tail - } - true - } - - /** Tests the existence in this list of an element that satisfies the - * predicate p. - * - * @param p the test predicate. - * @return true iff there exists an element in this list that - * satisfies the predicate p. - */ - override def exists(p: A => Boolean): Boolean = { - var these = this - while (!these.isEmpty) { - if (p(these.head)) return true - these = these.tail - } - false - } - - /** Find and return the first element of the list satisfying a - * predicate, if any. - * - * @param p the predicate - * @return the first element in the list satisfying p, - * or None if none exists. - */ - override def find(p: A => Boolean): Option[A] = { - var these = this - while (!these.isEmpty) { - if (p(these.head)) return Some(these.head) - these = these.tail - } - None - } - - /** Combines the elements of this list together using the binary - * function f, from left to right, and starting with - * the value z. - * - * @return f(... (f(f(z, a0), a1) ...), - * an) if the list is - * [a0, a1, ..., an]. - */ - override def foldLeft[B](z: B)(f: (B, A) => B): B = { - var acc = z - var these = this - while (!these.isEmpty) { - acc = f(acc, these.head) - these = these.tail - } - acc - } - - /** Combines the elements of this list together using the binary - * function f, from right to left, and starting with - * the value z. - * - * @return f(a0, f(a1, f(..., f(an, z)...))) - * if the list is [a0, a1, ..., an]. - */ - override def foldRight[B](z: B)(f: (A, B) => B): B = this match { - case Nil => z - case x :: xs => f(x, xs.foldRight(z)(f)) - } - - /** Combines the elements of this list together using the binary - * operator op, from left to right - * @param op The operator to apply - * @return op(... op(a0,a1), ..., an) - if the list has elements - * a0, a1, ..., an. - * @throws Predef.UnsupportedOperationException if the list is empty. - */ - override def reduceLeft[B >: A](f: (B, A) => B): B = this match { - case Nil => throw new UnsupportedOperationException("Nil.reduceLeft") - case x :: Nil => x - case x0 :: x1 :: xs => - var acc : B = f(x0, x1) - var these : List[A] = xs - while (!these.isEmpty) { - acc = f(acc, these.head) - these = these.tail - } - acc - } - - /** Combines the elements of this list together using the binary - * operator op, from right to left - * @param op The operator to apply - * - * @return a0 op (... op (an-1 op an)...) - * if the list has elements a0, a1, ..., - * an. - * - * @throws Predef.UnsupportedOperationException if the list is empty. - */ - override def reduceRight[B >: A](f: (A, B) => B): B = this match { - case Nil => throw new UnsupportedOperationException("Nil.reduceRight") - case x :: Nil => x - case x :: xs => f(x, xs reduceRight f) - } - - /** Applies the given function f to each element of - * this list, then concatenates the results. - * - * @param f the function to apply on each element. - * @return f(a0) ::: ... ::: f(an) if - * this list is [a0, ..., an]. - */ - final override def flatMap[B](f: A => Iterable[B]): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - var those = f(these.head).elements - while (those.hasNext) { - b += those.next - } - these = these.tail - } - b.toList - } - - /** A list consisting of all elements of this list in reverse order. - */ - override def reverse: List[A] = { - var result: List[A] = Nil - var these = this - while (!these.isEmpty) { - result = these.head :: result - these = these.tail - } - result - } - - /** Returns a list formed from this list and the specified list - * that by associating each element of the former with - * the element at the same position in the latter. - * If one of the two lists is longer than the other, its remaining elements are ignored. - * - * @return List((a0,b0), ..., - * (amin(m,n),bmin(m,n))) when - * List(a0, ..., am) - * zip List(b0, ..., bn) is invoked. - */ - def zip[B](that: List[B]): List[(A, B)] = { - val b = new ListBuffer[(A, B)] - var these = this - var those = that - while (!these.isEmpty && !those.isEmpty) { - b += (these.head, those.head) - these = these.tail - those = those.tail - } - b.toList - } - - /** Returns a list that pairs each element of this list - * with its index, counting from 0. - * - * @return the list List((a0,0), (a1,1), ...) - * where ai are the elements of this list. - */ - def zipWithIndex: List[(A, Int)] = { - val b = new ListBuffer[(A, Int)] - var these = this - var idx = 0 - - while(!these.isEmpty) { - b += (these.head, idx) - these = these.tail - idx += 1 - } - - b.toList - } - - /** Returns a list formed from this list and the specified list - * that by associating each element of the former with - * the element at the same position in the latter. - * - * @param that list that may have a different length - * as the self list. - * @param thisElem element thisElem is used to fill up the - * resulting list if the self list is shorter than - * that - * @param thatElem element thatElem is used to fill up the - * resulting list if that is shorter than - * the self list - * @return List((a0,b0), ..., - * (an,bn), (elem,bn+1), - * ..., {elem,bm}) - * when [a0, ..., an] zip - * [b0, ..., bm] is - * invoked where m > n. - */ - def zipAll[B, C >: A, D >: B](that: List[B], thisElem: C, thatElem: D): List[(C, D)] = { - val b = new ListBuffer[(C, D)] - var these = this - var those = that - while (!these.isEmpty && !those.isEmpty) { - b += (these.head, those.head) - these = these.tail - those = those.tail - } - while (!these.isEmpty) { - b += (these.head, thatElem) - these = these.tail - } - while (!those.isEmpty) { - b += (thisElem, those.head) - those = those.tail - } - b.toList - } - - /** Computes the union of this list and the given list - * that. - * - * @param that the list of elements to add to the list. - * @return a list without doubles containing the elements of this - * list and those of the given list that. - */ - def union[B >: A](that: List[B]): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - if (!that.contains(these.head)) b += these.head - these = these.tail - } - b.prependToList(that) - } - - /** Computes the difference between this list and the given list - * that. - * - * @param that the list of elements to remove from this list. - * @return this list without the elements of the given list - * that. - * @deprecated use -- instead - */ - @deprecated - def diff[B >: A](that: List[B]): List[B] = this -- that - - /** Computes the difference between this list and the given list - * that. - * - * @param that the list of elements to remove from this list. - * @return this list without the elements of the given list - * that. - */ - def -- [B >: A](that: List[B]): List[B] = { - val b = new ListBuffer[B] - var these = this - while (!these.isEmpty) { - if (!that.contains(these.head)) b += these.head - these = these.tail - } - b.toList - } - - /** Computes the difference between this list and the given object - * x. - * - * @param x the object to remove from this list. - * @return this list without the elements of the given object - * x. - */ - def - [B >: A](x: B): List[B] = - this -- List(x) - - def flatten[B](implicit f : A => Iterable[B]) : List[B] = { - val buf = new ListBuffer[B] - foreach(f(_).foreach(buf += _)) - buf.toList - } - - /** Computes the intersection between this list and the given list - * that. - * - * @param that the list to intersect. - * @return the list of elements contained both in this list and - * in the given list that. - */ - def intersect[B >: A](that: List[B]): List[B] = filter(x => that contains x) - - /** Removes redundant elements from the list. Uses the method == - * to decide if two elements are identical. - * - * @return the list without doubles. - */ - def removeDuplicates: List[A] = { - val b = new ListBuffer[A] - var these = this - while (!these.isEmpty) { - if (!these.tail.contains(these.head)) b += these.head - these = these.tail - } - b.toList - } - - override protected def stringPrefix = "List" - override def projection = toStream - override def toStream : Stream[A] = new Stream.Definite[A] { - override def force : List[A] = List.this - override def isEmpty = List.this.isEmpty - override def head = List.this.head - override def tail = List.this.tail.toStream - protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = if (!isEmpty) { - var prefix0 = prefix - var buf1 = buf.append(prefix0).append(head) - prefix0 = ", " - var tail0 = tail - while (!tail0.isEmpty) { - buf1 = buf.append(prefix0).append(tail0.head) - tail0 = tail0.tail - } - buf1 - } else buf - } - -} - -/** The empty list. - * - * @author Martin Odersky - * @version 1.0, 15/07/2003 - */ -@SerialVersionUID(0 - 8256821097970055419L) -case object Nil extends List[Nothing] { - override def isEmpty = true - def head: Nothing = - throw new NoSuchElementException("head of empty list") - def tail: List[Nothing] = - throw new NoSuchElementException("tail of empty list") -} - -/** A non empty list characterized by a head and a tail. - * - * @author Martin Odersky - * @version 1.0, 15/07/2003 - */ -@SerialVersionUID(0L - 8476791151983527571L) -final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] { - def head : B = hd - def tail : List[B] = tl - override def isEmpty: Boolean = false - - import java.io._ - - private def writeObject(out: ObjectOutputStream) { - var xs: List[B] = this - while (!xs.isEmpty) { out.writeObject(xs.head); xs = xs.tail } - out.writeObject(ListSerializeEnd) - } - - private def readObject(in: ObjectInputStream) { - hd = in.readObject.asInstanceOf[B] - assert(hd != ListSerializeEnd) - var current: ::[B] = this - while (true) in.readObject match { - case ListSerializeEnd => - current.tl = Nil - return - case a : Any => - val list : ::[B] = new ::(a.asInstanceOf[B], Nil) - current.tl = list - current = list - } - } -} - -/** Only used for list serialization */ -@SerialVersionUID(0L - 8476791151975527571L) -private[scala] case object ListSerializeEnd diff --git a/src/library/jvm/scala/Math.scala b/src/library/jvm/scala/Math.scala deleted file mode 100644 index c27b740842..0000000000 --- a/src/library/jvm/scala/Math.scala +++ /dev/null @@ -1,204 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -/** The object Math contains methods for performing basic numeric - * operations such as the elementary exponential, logarithm, square root, and - * trigonometric functions. - */ -object Math { - - /** The smallest possible value for scala.Byte. */ - val MIN_BYTE = java.lang.Byte.MIN_VALUE - /** The greatest possible value for scala.Byte. */ - val MAX_BYTE = java.lang.Byte.MAX_VALUE - - /** The smallest possible value for scala.Short. */ - val MIN_SHORT = java.lang.Short.MIN_VALUE - /** The greatest possible value for scala.Short. */ - val MAX_SHORT = java.lang.Short.MAX_VALUE - - /** The smallest possible value for scala.Char. */ - val MIN_CHAR = java.lang.Character.MIN_VALUE - /** The greatest possible value for scala.Char. */ - val MAX_CHAR = java.lang.Character.MAX_VALUE - - /** The smallest possible value for scala.Int. */ - val MIN_INT = java.lang.Integer.MIN_VALUE - /** The greatest possible value for scala.Int. */ - val MAX_INT = java.lang.Integer.MAX_VALUE - - /** The smallest possible value for scala.Long. */ - val MIN_LONG = java.lang.Long.MIN_VALUE - /** The greatest possible value for scala.Long. */ - val MAX_LONG = java.lang.Long.MAX_VALUE - - /** The smallest possible value for scala.Float. */ - val MIN_FLOAT = -java.lang.Float.MAX_VALUE - /** The smallest difference between two values of scala.Float. */ - val EPS_FLOAT = java.lang.Float.MIN_VALUE - /** The greatest possible value for scala.Float. */ - val MAX_FLOAT = java.lang.Float.MAX_VALUE - /** A value of type scala.Float that represents no number. */ - val NaN_FLOAT = java.lang.Float.NaN - /** Negative infinity of type scala.Float. */ - val NEG_INF_FLOAT = java.lang.Float.NEGATIVE_INFINITY - /** Positive infinity of type scala.Float. */ - val POS_INF_FLOAT = java.lang.Float.POSITIVE_INFINITY - - /** The smallest possible value for scala.Double. */ - val MIN_DOUBLE = -java.lang.Double.MAX_VALUE - /** The smallest difference between two values of scala.Double. */ - val EPS_DOUBLE = java.lang.Double.MIN_VALUE - /** The greatest possible value for scala.Double. */ - val MAX_DOUBLE = java.lang.Double.MAX_VALUE - /** A value of type scala.Double that represents no number. */ - val NaN_DOUBLE = java.lang.Double.NaN - /** Negative infinity of type scala.Double. */ - val NEG_INF_DOUBLE = java.lang.Double.NEGATIVE_INFINITY - /** Positive infinity of type scala.Double. */ - val POS_INF_DOUBLE = java.lang.Double.POSITIVE_INFINITY - - /** The double value that is closer than any other to - * e, the base of the natural logarithms. - */ - val E = java.lang.Math.E - - /** The double value that is closer than any other to - * pi, the ratio of the circumference of a circle to its - * diameter. - */ - val Pi = java.lang.Math.PI - - /** Returns a double value with a positive sign, greater than - * or equal to 0.0 and less than 1.0. - */ - def random: Double = java.lang.Math.random() - - def sin(x: Double): Double = java.lang.Math.sin(x) - def cos(x: Double): Double = java.lang.Math.cos(x) - def tan(x: Double): Double = java.lang.Math.tan(x) - def asin(x: Double): Double = java.lang.Math.asin(x) - def acos(x: Double): Double = java.lang.Math.acos(x) - def atan(x: Double): Double = java.lang.Math.atan(x) - - /** Converts an angle measured in degrees to an approximately equivalent - * angle measured in radians. - * - * @param x an angle, in degrees - * @return the measurement of the angle x in radians. - */ - def toRadians(x: Double): Double = java.lang.Math.toRadians(x) - - /** Converts an angle measured in radians to an approximately equivalent - * angle measured in degrees. - * - * @param x angle, in radians - * @return the measurement of the angle x in degrees. - */ - def toDegrees(x: Double): Double = java.lang.Math.toDegrees(x) - - /** Returns Euler's number e raised to the power of a - * double value. - * - * @param x the exponent to raise e to. - * @return the value ea, where e - * is the base of the natural logarithms. - */ - def exp(x: Double): Double = java.lang.Math.exp(x) - def log(x: Double): Double = java.lang.Math.log(x) - def sqrt(x: Double): Double = java.lang.Math.sqrt(x) - def sqrt(x: Int): Int = java.lang.Math.sqrt(x.toDouble).toInt - def IEEEremainder(x: Double, y: Double): Double = java.lang.Math.IEEEremainder(x, y) - - def ceil(x: Double): Double = java.lang.Math.ceil(x) - def floor(x: Double): Double = java.lang.Math.floor(x) - - /** Returns the double value that is closest in value to the - * argument and is equal to a mathematical integer. - * - * @param x a double value - * @return the closest floating-point value to a that is equal to a - * mathematical integer. - */ - def rint(x: Double): Double = java.lang.Math.rint(x) - - /** Converts rectangular coordinates (x, y) to polar - * (r, theta). - * - * @param x the ordinate coordinate - * @param y the abscissa coordinate - * @return the theta component of the point (r, theta) - * in polar coordinates that corresponds to the point - * (x, y) in Cartesian coordinates. - */ - def atan2(y: Double, x: Double): Double = java.lang.Math.atan2(y, x) - - /** Returns the value of the first argument raised to the power of the - * second argument. - * - * @param x the base. - * @param y the exponent. - * @return the value xy. - */ - def pow(x: Double, y: Double): Double = java.lang.Math.pow(x, y) - - /** Returns the closest long to the argument. - * - * @param x a floating-point value to be rounded to a long. - * @return the value of the argument rounded to the nearest - * long value. - */ - def round(x: Float): Int = java.lang.Math.round(x) - def round(x: Double): Long = java.lang.Math.round(x) - def abs(x: Int): Int = java.lang.Math.abs(x) - def abs(x: Long): Long = java.lang.Math.abs(x) - def abs(x: Float): Float = java.lang.Math.abs(x) - def abs(x: Double): Double = java.lang.Math.abs(x) - - def max(x: Int, y: Int): Int = java.lang.Math.max(x, y) - def max(x: Long, y: Long): Long = java.lang.Math.max(x, y) - def max(x: Float, y: Float): Float = java.lang.Math.max(x, y) - def max(x: Double, y: Double): Double = java.lang.Math.max(x, y) - - def min(x: Int, y: Int): Int = java.lang.Math.min(x, y) - def min(x: Long, y: Long): Long = java.lang.Math.min(x, y) - def min(x: Float, y: Float): Float = java.lang.Math.min(x, y) - def min(x: Double, y: Double): Double = java.lang.Math.min(x, y) - - def signum(x: Double): Double = x match { case 0 => 0 - case y if y < 0 => -1.0 - case y if y > 0 => 1.0 } - def signum(x: Float): Float = x match { case 0f => 0f - case y if y < 0f => -1.0f - case y if y > 0f => 1.0f } - def signum(x: Long): Long = x match { case 0l => 0l - case y if y < 0l => -1l - case y if y > 0l => 1l } - def signum(x: Int): Int = x match { case 0 => 0 - case y if y < 0 => -1 - case y if y > 0 => 1} - - // from Java 1.5 -// def log10(x: Double): Double = java.lang.Math.log10(x) -// def cbrt(x: Double): Double = java.lang.Math.cbrt(x) - -// def ulp(x: Double): Double = java.lang.Math.ulp(x) -// def ulp(x: Float): Float = java.lang.Math.ulp(x) -// def sinh(x: Double): Double = java.lang.Math.sinh(x) -// def cosh(x: Double): Double = java.lang.Math.cosh(x) -// def tanh(x: Double):Double = java.lang.Math.tanh(x) -// def hypot(x: Double, y: Double): Double = java.lang.Math.hypot(x, y) -// def expm1(x: Double): Double = java.lang.Math.expm1(x) -// def log1p(x: Double): Double = java.lang.Math.log1p(x) - -} diff --git a/src/library/jvm/scala/Predef.scala b/src/library/jvm/scala/Predef.scala deleted file mode 100644 index c7a01d6642..0000000000 --- a/src/library/jvm/scala/Predef.scala +++ /dev/null @@ -1,349 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - - -/** The Predef object provides definitions that are - * accessible in all Scala compilation units without explicit - * qualification. - */ -object Predef { - - // classOf dummy ------------------------------------------------------ - - /** Return the runtime representation of a class type. */ - def classOf[T]: Class[T] = null - - // aliases ------------------------------------------------------------ - - type byte = scala.Byte - type short = scala.Short - type char = scala.Char - type int = scala.Int - type long = scala.Long - type float = scala.Float - type double = scala.Double - type boolean = scala.Boolean - type unit = scala.Unit - - /** @deprecated use java.lang.Integer instead */ - @deprecated type Integer = java.lang.Integer - /** @deprecated use java.lang.Character instead */ - @deprecated type Character = java.lang.Character - - type String = java.lang.String - type Class[T] = java.lang.Class[T] - type Runnable = java.lang.Runnable - - type Throwable = java.lang.Throwable - type Exception = java.lang.Exception - type Error = java.lang.Error - - type RuntimeException = java.lang.RuntimeException - type NullPointerException = java.lang.NullPointerException - type ClassCastException = java.lang.ClassCastException - type IndexOutOfBoundsException = java.lang.IndexOutOfBoundsException - type ArrayIndexOutOfBoundsException = java.lang.ArrayIndexOutOfBoundsException - type StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException - type UnsupportedOperationException = java.lang.UnsupportedOperationException - type IllegalArgumentException = java.lang.IllegalArgumentException - type NoSuchElementException = java.util.NoSuchElementException - type NumberFormatException = java.lang.NumberFormatException - - // miscelleaneous ----------------------------------------------------- - - val $scope = scala.xml.TopScope - - type Function[-A, +B] = Function1[A, B] - - type Map[A, B] = collection.immutable.Map[A, B] - type Set[A] = collection.immutable.Set[A] - - val Map = collection.immutable.Map - val Set = collection.immutable.Set - - // errors and asserts ------------------------------------------------- - - def error(message: String): Nothing = throw new RuntimeException(message) - - def exit: Nothing = exit(0) - - def exit(status: Int): Nothing = { - java.lang.System.exit(status) - throw new Throwable() - } - - def assert(assertion: Boolean) { - if (!assertion) - throw new java.lang.AssertionError("assertion failed") - } - - def assert(assertion: Boolean, message: Any) { - if (!assertion) - throw new java.lang.AssertionError("assertion failed: "+ message) - } - - def assume(assumption: Boolean) { - if (!assumption) - throw new java.lang.AssertionError("assumption failed") - } - - def assume(assumption: Boolean, message: Any) { - if (!assumption) - throw new java.lang.AssertionError("assumptopm failed: "+ message) - } - - def require(requirement: Boolean) { - if (!requirement) - throw new IllegalArgumentException("requirement failed") - } - - def require(requirement: Boolean, message: Any) { - if (!requirement) - throw new IllegalArgumentException("requirement failed: "+ message) - } - - // tupling ------------------------------------------------------------ - - type Pair[+A, +B] = Tuple2[A, B] - object Pair { - def apply[A, B](x: A, y: B) = Tuple2(x, y) - def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x) - } - - type Triple[+A, +B, +C] = Tuple3[A, B, C] - object Triple { - def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z) - def unapply[A, B, C](x: Tuple3[A, B, C]): Option[Tuple3[A, B, C]] = Some(x) - } - - class Ensuring[A](x: A) { - def ensuring(cond: Boolean): A = { assert(cond); x } - def ensuring(cond: Boolean, msg: Any): A = { assert(cond, msg); x } - def ensuring(cond: A => Boolean): A = { assert(cond(x)); x } - def ensuring(cond: A => Boolean, msg: Any): A = { assert(cond(x), msg); x } - } - implicit def any2Ensuring[A](x: A): Ensuring[A] = new Ensuring(x) - - class ArrowAssoc[A](x: A) { - def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y) - } - implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x) - - def Tuple[A1](x1: A1) = Tuple1(x1) - def Tuple[A1, A2](x1: A1, x2: A2) = Tuple2(x1, x2) - def Tuple[A1, A2, A3](x1: A1, x2: A2, x3: A3) = Tuple3(x1, x2, x3) - def Tuple[A1, A2, A3, A4](x1: A1, x2: A2, x3: A3, x4: A4) = Tuple4(x1, x2, x3, x4) - def Tuple[A1, A2, A3, A4, A5](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5) = Tuple5(x1, x2, x3, x4, x5) - def Tuple[A1, A2, A3, A4, A5, A6](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6) = Tuple6(x1, x2, x3, x4, x5, x6) - def Tuple[A1, A2, A3, A4, A5, A6, A7](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7) = Tuple7(x1, x2, x3, x4, x5, x6, x7) - def Tuple[A1, A2, A3, A4, A5, A6, A7, A8](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8) = Tuple8(x1, x2, x3, x4, x5, x6, x7, x8) - def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9) = Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9) - - // printing and reading ----------------------------------------------- - - def print(x: Any) = Console.print(x) - def println() = Console.println() - def println(x: Any) = Console.println(x) - def printf(text: String, xs: Any*) = Console.printf(text, xs: _*) - def format(text: String, xs: Any*) = Console.format(text, xs: _*) - - def readLine(): String = Console.readLine() - def readLine(text: String, args: Any*) = Console.readLine(text, args) - def readBoolean() = Console.readBoolean() - def readByte() = Console.readByte() - def readShort() = Console.readShort() - def readChar() = Console.readChar() - def readInt() = Console.readInt() - def readLong() = Console.readLong() - def readFloat() = Console.readFloat() - def readDouble() = Console.readDouble() - def readf(format: String) = Console.readf(format) - def readf1(format: String) = Console.readf1(format) - def readf2(format: String) = Console.readf2(format) - def readf3(format: String) = Console.readf3(format) - - // views -------------------------------------------------------------- - - implicit def identity[A](x: A): A = x - - implicit def byteWrapper(x: Byte) = new runtime.RichByte(x) - implicit def shortWrapper(x: Short) = new runtime.RichShort(x) - implicit def intWrapper(x: Int) = new runtime.RichInt(x) - implicit def charWrapper(c: Char) = new runtime.RichChar(c) - implicit def longWrapper(x: Long) = new runtime.RichLong(x) - implicit def floatWrapper(x: Float) = new runtime.RichFloat(x) - implicit def doubleWrapper(x: Double) = new runtime.RichDouble(x) - - implicit def booleanWrapper(x: Boolean) = new runtime.RichBoolean(x) - - implicit def stringWrapper(x: String) = new runtime.RichString(x) - implicit def stringBuilderWrapper(x : StringBuilder): runtime.RichStringBuilder = new runtime.RichStringBuilder(x) - - implicit def any2stringadd(x: Any) = new runtime.StringAdd(x) - - implicit def exceptionWrapper(exc: Throwable) = new runtime.RichException(exc) - - implicit def unit2ordered(x: Unit): Ordered[Unit] = new Ordered[Unit] with Proxy { - def self: Any = x - def compare(y: Unit): Int = 0 - } - - implicit def iterable2ordered[A <% Ordered[A]](xs: Iterable[A]): Ordered[Iterable[A]] = - new Ordered[Iterable[A]] with Proxy { - val self = xs - def compare(that: Iterable[A]): Int = { - var res = 0 - val these = xs.elements - val those = that.elements - while (res == 0 && these.hasNext) - res = if (those.hasNext) these.next compare those.next else 1 - if (res == 0) { - if (those.hasNext) -1 else 0 - } else - res - } - } - - implicit def tuple22ordered[A1 <% Ordered[A1], A2 <% Ordered[A2]](x: Tuple2[A1, A2]): Ordered[Tuple2[A1, A2]] = - new Ordered[Tuple2[A1, A2]] with Proxy { - val self = x - def compare(y: Tuple2[A1, A2]): Int = { - val res = x._1 compare y._1 - if (res == 0) x._2 compare y._2 - else res - } - } - - implicit def tuple32ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3]](x: Tuple3[A1, A2, A3]): Ordered[Tuple3[A1, A2, A3]] = - new Ordered[Tuple3[A1, A2, A3]] with Proxy { - val self = x - def compare(y: Tuple3[A1, A2, A3]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple2(x._2, x._3) compare Tuple2(y._2, y._3) - else res - } - } - - implicit def tuple42ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4]](x: Tuple4[A1, A2, A3, A4]): Ordered[Tuple4[A1, A2, A3, A4]] = - new Ordered[Tuple4[A1, A2, A3, A4]] with Proxy { - val self = x - def compare(y: Tuple4[A1, A2, A3, A4]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple3(x._2, x._3, x._4) compare Tuple3(y._2, y._3, y._4) - else res - } - } - - implicit def tuple52ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5]](x: Tuple5[A1, A2, A3, A4, A5]): Ordered[Tuple5[A1, A2, A3, A4, A5]] = - new Ordered[Tuple5[A1, A2, A3, A4, A5]] with Proxy { - val self = x - def compare(y: Tuple5[A1, A2, A3, A4, A5]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple4(x._2, x._3, x._4, x._5) compare Tuple4(y._2, y._3, y._4, y._5) - else res - } - } - - implicit def tuple62ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6]](x: Tuple6[A1, A2, A3, A4, A5, A6]): Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] = - new Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] with Proxy { - val self = x - def compare(y: Tuple6[A1, A2, A3, A4, A5, A6]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple5(x._2, x._3, x._4, x._5, x._6) compare Tuple5(y._2, y._3, y._4, y._5, y._6) - else res - } - } - - implicit def tuple72ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7]](x: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] = - new Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] with Proxy { - val self = x - def compare(y: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple6(x._2, x._3, x._4, x._5, x._6, x._7) compare Tuple6(y._2, y._3, y._4, y._5, y._6, y._7) - else res - } - } - - implicit def tuple82ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8]](x: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] = - new Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] with Proxy { - val self = x - def compare(y: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple7(x._2, x._3, x._4, x._5, x._6, x._7, x._8) compare Tuple7(y._2, y._3, y._4, y._5, y._6, y._7, y._8) - else res - } - } - - implicit def tuple92ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8], A9 <% Ordered[A9]](x: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] = - new Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] with Proxy { - val self = x - def compare(y: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Int = { - val res = x._1 compare y._1 - if (res == 0) Tuple8(x._2, x._3, x._4, x._5, x._6, x._7, x._8, x._9) compare Tuple8(y._2, y._3, y._4, y._5, y._6, y._7, y._8, y._9) - else res - } - } - - implicit def byte2short(x: Byte): Short = x.toShort - implicit def byte2int(x: Byte): Int = x.toInt - implicit def byte2long(x: Byte): Long = x.toLong - implicit def byte2float(x: Byte): Float = x.toFloat - implicit def byte2double(x: Byte): Double = x.toDouble - - implicit def short2int(x: Short): Int = x.toInt - implicit def short2long(x: Short): Long = x.toLong - implicit def short2float(x: Short): Float = x.toFloat - implicit def short2double(x: Short): Double = x.toDouble - - implicit def char2int(x: Char): Int = x.toInt - implicit def char2long(x: Char): Long = x.toLong - implicit def char2float(x: Char): Float = x.toFloat - implicit def char2double(x: Char): Double = x.toDouble - - implicit def int2long(x: Int): Long = x.toLong - implicit def int2float(x: Int): Float = x.toFloat - implicit def int2double(x: Int): Double = x.toDouble - - implicit def long2float(x: Long): Float = x.toFloat - implicit def long2double(x: Long): Double = x.toDouble - - implicit def float2double(x: Float): Double = x.toDouble - - /** Should use java.lang.Byte.valueOf(Byte), but only available - * in Java 1.5 and above. */ - implicit def byte2Byte(x: Byte) = new java.lang.Byte(x) - /** Should use java.lang.Short.valueOf(Short), but only available - * in Java 1.5 and above. */ - implicit def short2Short(x: Short) = new java.lang.Short(x) - /** Should use java.lang.Character.valueOf(Char), but only available - * in Java 1.5 and above. */ - implicit def char2Character(x: Char) = new java.lang.Character(x) - /** Should use java.lang.Integer.valueOf(Int), but only available - * in Java 1.5 and above. */ - implicit def int2Integer(x: Int) = new java.lang.Integer(x) - /** Should use java.lang.Long.valueOf(Long), but only available - * in Java 1.5 and above. */ - implicit def long2Long(x: Long) = new java.lang.Long(x) - implicit def float2Float(x: Float) = new java.lang.Float(x) - implicit def double2Double(x: Double) = new java.lang.Double(x) - implicit def boolean2Boolean(x: Boolean) = java.lang.Boolean.valueOf(x) - - /** any array projection can be automatically converted into an array */ - implicit def forceArrayProjection[A](x: Array.Projection[A]): Array[A] = x.force - /** any random access character seq (including rich string can be converted into a string */ - implicit def forceRandomAccessCharSeq(x: runtime.RichString): String = x.mkString - implicit def lazyStreamToConsable[A](xs: => Stream[A]) = new runtime.StreamCons(xs) - - def currentThread = java.lang.Thread.currentThread() - -} diff --git a/src/library/jvm/scala/Random.scala b/src/library/jvm/scala/Random.scala deleted file mode 100644 index c1e8801bf4..0000000000 --- a/src/library/jvm/scala/Random.scala +++ /dev/null @@ -1,72 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -/** - * @author Stephane Micheloud - */ -class Random(val self: java.util.Random) { - - /** Creates a new random number generator using a single long seed. */ - def this(seed: Long) = this(new java.util.Random(seed)) - - /** Creates a new random number generator using a single integer seed. */ - def this(seed: Int) = this(seed.toLong) - - /** Creates a new random number generator. */ - def this() = this(compat.Platform.currentTime) - - /** Returns the next pseudorandom, uniformly distributed boolean value - * from this random number generator's sequence. - */ - def nextBoolean(): Boolean = self.nextBoolean() - - /** Generates random bytes and places them into a user-supplied byte - * array. - */ - def nextBytes(bytes: Array[Byte]) { self.nextBytes(bytes) } - - /** Returns the next pseudorandom, uniformly distributed double value - * between 0.0 and 1.0 from this random number generator's sequence. - */ - def nextDouble(): Double = self.nextDouble() - - /** Returns the next pseudorandom, uniformly distributed float value - * between 0.0 and 1.0 from this random number generator's sequence. - */ - def nextFloat(): Float = self.nextFloat() - - /** Returns the next pseudorandom, Gaussian ("normally") distributed - * double value with mean 0.0 and standard deviation 1.0 from this - * random number generator's sequence. - */ - //def nextGaussian(): Double = self.nextGaussian() - - /** Returns the next pseudorandom, uniformly distributed int value - * from this random number generator's sequence. - */ - def nextInt(): Int = self.nextInt() - - /** Returns a pseudorandom, uniformly distributed int value between 0 - * (inclusive) and the specified value (exclusive), drawn from this - * random number generator's sequence. - */ - def nextInt(n: Int): Int = self.nextInt(n) - - /** Returns the next pseudorandom, uniformly distributed long value - * from this random number generator's sequence. - */ - def nextLong(): Long = self.nextLong() - - def setSeed(seed: Long) { self.setSeed(seed) } - -} diff --git a/src/library/jvm/scala/StringBuilder.scala b/src/library/jvm/scala/StringBuilder.scala deleted file mode 100644 index 92ee3b9ac8..0000000000 --- a/src/library/jvm/scala/StringBuilder.scala +++ /dev/null @@ -1,946 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import Predef._ - -/**

- * A mutable sequence of characters. This class provides an API compatible - * with java.lang.StringBuilder, but with no guarantee of - * synchronization. - *

- * - * @author Stephane Micheloud - * @version 1.0 - */ -@SerialVersionUID(0 - 8525408645367278351L) -final class StringBuilder(initCapacity: Int, private val initValue: String) -extends (Int => Char) with Proxy { - if (initCapacity < 0) throw new IllegalArgumentException - if (initValue eq null) throw new NullPointerException - - /** The value is used for character storage. */ - private var value = new Array[Char](initCapacity + initValue.length) - - /** The count is the number of characters used. */ - private var count: Int = 0 - - /** Constructs a string builder with no characters in it and an - * initial capacity of 16 characters. - */ - def this() = this(16, "") - - /** Constructs a string builder with no characters in it and an - * initial capacity specified by the capacity argument. - * - * @param capacity the initial capacity. - * @throws NegativeArraySizeException if the capacity - * argument is less than 0. - */ - def this(capacity: Int) = this(capacity, "") - - def this(str: String) = this(16, str) - - append(initValue) - - def self = this - - def toArray: Array[Char] = value - - def length: Int = count - - def length_=(n: Int) { setLength(n) } - - /** Sets the length of the character sequence. - * - * @param newLength the new length - * @throws IndexOutOfBoundsException if the n argument is negative. - */ - def setLength(n: Int) { - if (n < 0) - throw new StringIndexOutOfBoundsException(n) - if (n > value.length) expandCapacity(n) - if (count < n) - while (count < n) { - value(count) = '\0'; count += 1 - } - else - count = n - } - - /** Returns the current capacity. The capacity is the amount of storage - * available for newly inserted characters, beyond which an allocation - * will occur. - * - * @return the current capacity - */ - def capacity: Int = value.length - - /** Same as ensureCapacity. */ - def capacity_=(n: Int) { ensureCapacity(n) } - - /**

- * Ensures that the capacity is at least equal to the specified minimum. - * If the current capacity is less than the argument, then a new internal - * array is allocated with greater capacity. The new capacity is the larger of: - *

- * - *

- * If the n argument is non-positive, this - * method takes no action and simply returns. - *

- * - * @param n the minimum desired capacity. - */ - def ensureCapacity(n: Int) { - if (n > value.length) expandCapacity(n) - } - - private def expandCapacity(n: Int) { - val newCapacity = (value.length + 1) * 2 - value = StringBuilder.copyOf( - value, - if (newCapacity < 0) Math.MAX_INT else if (n > newCapacity) n else newCapacity - ) - } - - /**

- * Returns the Char value in this sequence at the specified index. - * The first Char value is at index 0, the next at index - * 1, and so on, as in array indexing. - *

- *

- * The index argument must be greater than or equal to - * 0, and less than the length of this sequence. - *

- * - * @param index the index of the desired Char value. - * @return the Char value at the specified index. - * @throws IndexOutOfBoundsException if index is - * negative or greater than or equal to length(). - */ - def charAt(index: Int): Char = { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException(index) - value(index) - } - - /** Same as charAt. */ - def apply(i: Int): Char = charAt(i) - - /**

- * Removes the Char at the specified position in this - * sequence. This sequence is shortened by one Char. - *

- * - * @param index Index of Char to remove - * @return This object. - * @throws StringIndexOutOfBoundsException if the index - * is negative or greater than or equal to length(). - */ - def deleteCharAt(index: Int): StringBuilder = { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException(index) - compat.Platform.arraycopy(value, index + 1, value, index, count - index - 1) - count -= 1 - this - } - - /**

- * The character at the specified index is set to ch. This - * sequence is altered to represent a new character sequence that is - * identical to the old character sequence, except that it contains the - * character ch at position index. - *

- *

- * The index argument must be greater than or equal to - * 0, and less than the length of this sequence. - *

- * - * @param index the index of the character to modify. - * @param ch the new character. - * @throws IndexOutOfBoundsException if index is - * negative or greater than or equal to length(). - */ - def setCharAt(index: Int, ch: Char) { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException(index) - value(index) = ch - } - - /** Same as setCharAt. */ - def update(i: Int, c: Char) { setCharAt(i, c) } - - /** Returns a new String that contains a subsequence of - * characters currently contained in this character sequence. The - * substring begins at the specified index and extends to the end of - * this sequence. - * - * @param start The beginning index, inclusive. - * @return The new string. - * @throws StringIndexOutOfBoundsException if start is - * less than zero, or greater than the length of this object. - */ - def substring(start: Int): String = substring(start, count) - - /** Returns a new String that contains a subsequence of - * characters currently contained in this sequence. The - * substring begins at the specified start and - * extends to the character at index end - 1. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @return The new string. - * @throws StringIndexOutOfBoundsException if start - * or end are negative or greater than - * length(), or start is - * greater than end. - */ - def substring(start: Int, end: Int): String = { - if (start < 0) - throw new StringIndexOutOfBoundsException(start) - if (end > count) - throw new StringIndexOutOfBoundsException(end) - if (start > end) - throw new StringIndexOutOfBoundsException(end - start) - new String(value, start, end - start) - } - - /**

- * Appends the string representation of the Any - * argument. - *

- *

- * The argument is converted to a string as if by the method - * String.valueOf, and the characters of that - * string are then appended to this sequence. - *

- * - * @param x an Any object. - * @return a reference to this object. - */ - def append(x: Any): StringBuilder = - append(String.valueOf(x)) - - /** Appends the specified string to this character sequence. - * - * @param s a string. - * @return a reference to this object. - */ - def append(s: String): StringBuilder = { - val str = if (s == null) "null" else s - val len = str.length - if (len > 0) { - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(str.toCharArray, 0, value, count, len) - count = newCount - } - this - } - - /** Appends the specified string builder to this sequence. - * - * @param sb - * @return - */ - def append(sb: StringBuilder): StringBuilder = - if (sb == null) - append("null") - else { - val len = sb.length - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(sb.toArray, 0, value, count, len) - count = newCount - this - } - - /**

- * Appends the string representation of the Char sequence - * argument to this sequence. - *

- *

- * The characters of the sequence argument are appended, in order, - * to the contents of this sequence. The length of this sequence - * increases by the length of the argument. - *

- * - * @param x the characters to be appended. - * @return a reference to this object. - */ - def append(x: Seq[Char]): StringBuilder = - append(x.toArray, 0, x.length) - - /**

- * Appends the string representation of the Char array - * argument to this sequence. - *

- *

- * The characters of the array argument are appended, in order, to - * the contents of this sequence. The length of this sequence - * increases by the length of the argument. - *

- * - * @param x the characters to be appended. - * @return a reference to this object. - */ - def append(x: Array[Char]): StringBuilder = - append(x, 0, x.length) - - /**

- * Appends the string representation of a subarray of the - * char array argument to this sequence. - *

- *

- * Characters of the Char array x, starting at - * index offset, are appended, in order, to the contents - * of this sequence. The length of this sequence increases - * by the value of len. - *

- * - * @param x the characters to be appended. - * @param offset the index of the first Char to append. - * @param len the number of Chars to append. - * @return a reference to this object. - */ - def append(x: Array[Char], offset: Int, len: Int): StringBuilder = { - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(x, offset, value, count, len) - count = newCount - this - } - - /**

- * Appends the string representation of the Boolean - * argument to the sequence. - *

- *

- * The argument is converted to a string as if by the method - * String.valueOf, and the characters of that - * string are then appended to this sequence. - *

- * - * @param x a Boolean. - * @return a reference to this object. - */ - def append(x: Boolean): StringBuilder = { - if (x) { - val newCount = count + 4 - if (newCount > value.length) expandCapacity(newCount) - value(count) = 't'; count += 1 - value(count) = 'r'; count += 1 - value(count) = 'u'; count += 1 - value(count) = 'e'; count += 1 - } else { - val newCount = count + 5 - if (newCount > value.length) expandCapacity(newCount) - value(count) = 'f'; count += 1 - value(count) = 'a'; count += 1 - value(count) = 'l'; count += 1 - value(count) = 's'; count += 1 - value(count) = 'e'; count += 1 - } - this - } - - def append(x: Byte): StringBuilder = - append(String.valueOf(x)) - - def append(x: Char): StringBuilder = { - val newCount = count + 1 - if (newCount > value.length) expandCapacity(newCount) - value(count) = x; count += 1 - this - } - - def append(x: Short): StringBuilder = - append(String.valueOf(x)) - - def append(x: Int): StringBuilder = - append(String.valueOf(x)) - - def append(x: Long): StringBuilder = - append(String.valueOf(x)) - - def append(x: Float): StringBuilder = - append(String.valueOf(x)) - - def append(x: Double): StringBuilder = - append(String.valueOf(x)) - - /** Removes the characters in a substring of this sequence. - * The substring begins at the specified start and extends to - * the character at index end - 1 or to the end of the - * sequence if no such character exists. If - * start is equal to end, no changes are made. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @return This object. - * @throws StringIndexOutOfBoundsException if start - * is negative, greater than length(), or - * greater than end. - */ - def delete(start: Int, end: Int): StringBuilder = { - if (start < 0 || start > end) - throw new StringIndexOutOfBoundsException(start) - val end0 = if (end > count) count else end - val len = end0 - start - if (len > 0) { - compat.Platform.arraycopy(value, start + len, value, start, count - end0) - count -= len - } - this - } - - /** Replaces the characters in a substring of this sequence - * with characters in the specified String. The substring - * begins at the specified start and extends to the character - * at index end - 1 or to the end of the sequence if no such - * character exists. First the characters in the substring are removed and - * then the specified String is inserted at start. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @param str String that will replace previous contents. - * @return This object. - * @throws StringIndexOutOfBoundsException if start - * is negative, greater than length(), or - * greater than end. - */ - def replace(start: Int, end: Int, str: String) { - if (start < 0 || start > count || start > end) - throw new StringIndexOutOfBoundsException(start) - - val end0 = if (end > count) count else end - val len = str.length() - val newCount = count + len - (end0 - start) - if (newCount > value.length) expandCapacity(newCount) - - compat.Platform.arraycopy(value, end, value, start + len, count - end) - compat.Platform.arraycopy(str.toCharArray, 0, value, start, len) - count = newCount - this - } - - /** Inserts the string representation of a subarray of the str - * array argument into this sequence. The subarray begins at the specified - * offset and extends len chars. - * The characters of the subarray are inserted into this sequence at - * the position indicated by index. The length of this - * sequence increases by len Chars. - * - * @param index position at which to insert subarray. - * @param str a Char array. - * @param offset the index of the first char in subarray to - * be inserted. - * @param len the number of Chars in the subarray to - * be inserted. - * @return This object - * @throws StringIndexOutOfBoundsException if index - * is negative or greater than length(), or - * offset or len are negative, or - * (offset+len) is greater than - * str.length. - */ - def insert(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = { - if (index < 0 || index > count) - throw new StringIndexOutOfBoundsException(index) - if (offset < 0 || len < 0 || offset > str.length - len) - throw new StringIndexOutOfBoundsException( - "offset " + offset + ", len " + len + - ", str.length " + str.length) - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, index, value, index + len, count - index) - compat.Platform.arraycopy(str, offset, value, index, len) - count = newCount - this - } - - /**

- * Inserts the string representation of the Any - * argument into this character sequence. - *

- *

- * The second argument is converted to a string as if by the method - * String.valueOf, and the characters of that - * string are then inserted into this sequence at the indicated - * offset. - *

- *

- * The offset argument must be greater than or equal to - * 0, and less than or equal to the length of this - * sequence. - *

- * - * @param offset the offset. - * @param x an Any value. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: Any): StringBuilder = - insert(at, String.valueOf(x)) - - /** Inserts the string into this character sequence. - * - * @param at the offset position. - * @param x a string. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: String): StringBuilder = { - if (at < 0 || at > count) - throw new StringIndexOutOfBoundsException(at) - val str = if (x == null) "null" else x - val len = str.length - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, at, value, at + len, count - at) - compat.Platform.arraycopy(str.toCharArray, 0, value, at, len) - count = newCount - this - } - - /** Inserts the string representation of the Char sequence - * argument into this sequence. - * - * @param at the offset position. - * @param x a character sequence. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: Seq[Char]): StringBuilder = - insert(at, x.toArray) - - /** Inserts the string representation of the Char array - * argument into this sequence. - * - * @param at the offset position. - * @param x a character array. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - def insert(at: Int, x: Array[Char]): StringBuilder = { - if (at < 0 || at > count) - throw new StringIndexOutOfBoundsException(at) - val len = x.length - val newCount = count + len - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, at, value, at + len, count - at) - compat.Platform.arraycopy(x, 0, value, at, len) - count = newCount - this - } - - /**

- * Inserts the string representation of the Boolean argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Boolean value. - * @return a reference to this object. - */ - def insert(at: Int, x: Boolean): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Inserts the string representation of the Byte argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Byte value. - * @return a reference to this object. - */ - def insert(at: Int, x: Byte): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Inserts the string representation of the Char argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Char value. - * @return a reference to this object. - */ - def insert(at: Int, x: Char): StringBuilder = { - if (at < 0 || at > count) - throw new StringIndexOutOfBoundsException(at) - val newCount = count + 1 - if (newCount > value.length) expandCapacity(newCount) - compat.Platform.arraycopy(value, at, value, at + 1, count - at) - value(at) = x - count = newCount - this - } - - /**

- * Inserts the string representation of the Short argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Short value. - * @return a reference to this object. - */ - def insert(at: Int, x: Short): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Inserts the string representation of the Int argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Int value. - * @return a reference to this object. - */ - def insert(at: Int, x: Int): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Inserts the string representation of the Long argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Long value. - * @return a reference to this object. - */ - def insert(at: Int, x: Long): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Inserts the string representation of the Float argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Float value. - * @return a reference to this object. - */ - def insert(at: Int, x: Float): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Inserts the string representation of the Double argument - * into this sequence. - *

- *

- * The offset argument must be greater than or equal to 0, and less than - * or equal to the length of this sequence. - *

- * - * @param at the offset position. - * @param x a Double value. - * @return a reference to this object. - */ - def insert(at: Int, x: Double): StringBuilder = - insert(at, String.valueOf(x)) - - /**

- * Returns the index within this string of the first occurrence of the - * specified substring. The integer returned is the smallest value - * k such that: - *

- *
-   *  this.toString().startsWith(str, k)
- *
- *

- * is true. - *

- * - * @param str any string. - * @return if the string argument occurs as a substring within this - * object, then the index of the first character of the first - * such substring is returned; if it does not occur as a - * substring, -1 is returned. - * @throws NullPointerException if str is null. - */ - def indexOf(str: String): Int = indexOf(str, 0) - - /**

- * Returns the index within this string of the first occurrence of the - * specified substring, starting at the specified index. The integer - * returned is the smallest value k for which: - *

-   *    k >= Math.min(fromIndex, str.length()) &&
-   *                   this.toString().startsWith(str, k)
- *

- * If no such value of k exists, then -1 - * is returned. - *

- * - * @param str the substring for which to search. - * @param fromIndex the index from which to start the search. - * @return the index within this string of the first occurrence - * of the specified substring, starting at the specified index. - */ - def indexOf(str: String, fromIndex: Int): Int = - StringBuilder.indexOf(value, 0, count, str.toCharArray, 0, str.length(), fromIndex) - - /**

- * Returns the index within this string of the rightmost occurrence - * of the specified substring. The rightmost empty string "" is - * considered to occur at the index value this.length(). - * The returned index is the largest value k such that - *

- *
-   *  this.toString().startsWith(str, k)
- *
- *

- * is true. - *

- * - * @param str the substring to search for. - * @return if the string argument occurs one or more times as a substring - * within this object, then the index of the first character of - * the last such substring is returned. If it does not occur as - * a substring, -1 is returned. - * @throws NullPointerException if str is null. - */ - def lastIndexOf(str: String): Int = lastIndexOf(str, count) - - /**

- * Returns the index within this string of the last occurrence of the - * specified substring. The integer returned is the largest value - * k such that: - *

-   *    k <= Math.min(fromIndex, str.length()) &&
-   *                   this.toString().startsWith(str, k)
- *

- * If no such value of k exists, then -1 - * is returned. - *

- * - * @param str the substring to search for. - * @param fromIndex the index to start the search from. - * @return the index within this sequence of the last occurrence - * of the specified substring. - */ - def lastIndexOf(str: String, fromIndex: Int): Int = - StringBuilder.lastIndexOf(value, 0, count, str.toCharArray, 0, str.length(), fromIndex) - - /**

- * Causes this character sequence to be replaced by the reverse of the - * sequence. If there are any surrogate pairs included in the sequence, - * these are treated as single characters for the reverse operation. - * Thus, the order of the high-low surrogates is never reversed. - *

- *

- * Let n be the character length of this character sequence - * (not the length in Char values) just prior to - * execution of the reverse method. Then the - * character at index k in the new character sequence is - * equal to the character at index n-k-1 in the old - * character sequence. - *

- * - * @return a reference to this object. - */ - def reverse(): StringBuilder = { - var hasSurrogate = false - val n = count - 1 - var j = (n-1) >> 1 - while (j >= 0) { - val temp = value(j) - val temp2 = value(n - j) - if (!hasSurrogate) - hasSurrogate = - (temp >= StringBuilder.MIN_SURROGATE && temp <= StringBuilder.MAX_SURROGATE) || - (temp2 >= StringBuilder.MIN_SURROGATE && temp2 <= StringBuilder.MAX_SURROGATE) - value(j) = temp2 - value(n - j) = temp - j -= 1 - } - if (hasSurrogate) { - // Reverse back all valid surrogate pairs - var i = 0 - while (i < count - 1) { - val c2 = value(i) - if (StringBuilder.isLowSurrogate(c2)) { - val c1 = value(i + 1) - if (StringBuilder.isHighSurrogate(c1)) { - value(i) = c1; i += 1 - value(i) = c2 - } - } - i += 1 - } - } - this - } - - /** Returns a string representing the data in this sequence. - * A new String object is allocated and initialized to - * contain the character sequence currently represented by this - * object. This String is then returned. Subsequent - * changes to this sequence do not affect the contents of the - * String. - * - * @return a string representation of this sequence of characters. - */ - override def toString(): String = new String(value, 0, count) - - @throws(classOf[java.io.IOException]) - private def writeObject(s: java.io.ObjectOutputStream) { - s.defaultWriteObject() - s.writeInt(count) - s.writeObject(value) - } - - @throws(classOf[java.io.IOException]) - private def readObject(s: java.io.ObjectInputStream ) { - s.defaultReadObject() - count = s.readInt() - value = s.readObject().asInstanceOf[Array[Char]] - } - -} - - -object StringBuilder { - - private val MIN_HIGH_SURROGATE = '\uD800' - private val MAX_HIGH_SURROGATE = '\uDBFF' - - private val MIN_LOW_SURROGATE = '\uDC00' - private val MAX_LOW_SURROGATE = '\uDFFF' - - // constants java.langCharacter.MIN-/MAX_SURROGATE exist since 1.5 - private val MIN_SURROGATE = MIN_HIGH_SURROGATE - private val MAX_SURROGATE = MAX_LOW_SURROGATE - - // methods java.langCharacter.isLow-/isHighSurrogate exist since 1.5 - private def isLowSurrogate(ch: Char): Boolean = - MIN_LOW_SURROGATE <= ch && ch <= MAX_LOW_SURROGATE - - private def isHighSurrogate(ch: Char): Boolean = - MIN_HIGH_SURROGATE <= ch && ch <= MAX_HIGH_SURROGATE - - // method java.util.Arrays.copyOf exists since 1.6 - private def copyOf(src: Array[Char], newLength: Int): Array[Char] = { - val dest = new Array[Char](newLength) - compat.Platform.arraycopy(src, 0, dest, 0, Math.min(src.length, newLength)) - dest - } - - private def indexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, - target: Array[Char], targetOffset: Int, targetCount: Int, - fromIndex: Int): Int = - if (fromIndex >= sourceCount) - if (targetCount == 0) sourceCount else -1 - else { - val inx = if (fromIndex < 0) 0 else fromIndex - if (targetCount == 0) - inx - else { - val first = target(targetOffset) - val max = sourceOffset + (sourceCount - targetCount) - - var i = sourceOffset + inx - while (i <= max) { - /* Look for first character. */ - if (source(i) != first) { - i += 1 - while (i <= max && source(i) != first) i += 1 - } - /* Found first character, now look at the rest of v2 */ - if (i <= max) { - var j = i + 1 - val end = j + targetCount - 1 - var k = targetOffset + 1 - while (j < end && source(j) == target(k)) { - j += 1 - k += 1 - } - if (j == end) { - /* Found whole string. */ - return i - sourceOffset - } - } // if - i += 1 - } // while - -1 - } - } - - private def lastIndexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, - target: Array[Char], targetOffset: Int, targetCount: Int, - fromIndex: Int): Int = { - val rightIndex = sourceCount - targetCount - if (fromIndex < 0) return -1 - val inx = if (fromIndex > rightIndex) rightIndex else fromIndex - // Empty string always matches - if (targetCount == 0) return inx - - val strLastIndex = targetOffset + targetCount - 1 - val strLastChar = target(strLastIndex) - val min = sourceOffset + targetCount - 1 - var i = min + fromIndex - - while (true) { - while (i >= min && source(i) != strLastChar) i -= 1 - if (i < min) return -1 - var j = i - 1 - val start = j - (targetCount - 1) - var k = strLastIndex - 1 - var outerWhile = false - while (j > start && !outerWhile) { - if (source(j) != target(k)) { - j -= 1 - k -= 1 - i -= 1 - outerWhile = true - } - } - if (!outerWhile) return start - sourceOffset + 1 - } - -1 - } -} diff --git a/src/library/jvm/scala/Symbol.scala b/src/library/jvm/scala/Symbol.scala deleted file mode 100644 index 6f7ca958c7..0000000000 --- a/src/library/jvm/scala/Symbol.scala +++ /dev/null @@ -1,69 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala - -import scala.collection.jcl - -private[scala] object internedSymbols extends jcl.WeakHashMap[String, ref.WeakReference[Symbol]] - -/**

- * This class provides a simple way to get unique objects for - * equal strings. Since symbols are interned, they can be compared using - * reference equality. Instances of - * Symbol can be created easily with Scala's built-in -* quote mechanism. - *

- *

- * For instance, the Scala - * term 'mysym will invoke the constructor of the - * Symbol class in the following way: - * Symbol("mysym"). - *

- * - * @author Martin Odersky, Iulian Dragos - * @version 1.8 - */ -@serializable -final class Symbol private (val name: String) { - - /** Converts this symbol to a string. - */ - override def toString(): String = "'" + name - - @throws(classOf[java.io.ObjectStreamException]) - private def readResolve(): Any = Symbol.apply(name) -} - -object Symbol { - - /**

- * Makes this symbol into a unique reference. - *

- *

- * If two interened symbols are equal (i.e. they have the same name) - * then they must be identical (wrt reference equality). - *

- * - * @return the unique reference to this string. - */ - def apply(name: String): Symbol = internedSymbols.synchronized { - internedSymbols.get(name).flatMap(_.get) match { - case Some(sym) => sym - case _ => - val sym = new Symbol(name) - internedSymbols(name) = new ref.WeakReference(sym) - sym - } - } - - def unapply(other: Symbol): Option[String] = Some(other.name) -} diff --git a/src/library/jvm/scala/compat/Platform.scala b/src/library/jvm/scala/compat/Platform.scala deleted file mode 100644 index 03cf1d28e2..0000000000 --- a/src/library/jvm/scala/compat/Platform.scala +++ /dev/null @@ -1,60 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.compat - - -import java.lang.System -import Predef._ - -object Platform { - - type StackOverflowError = java.lang.StackOverflowError - type ConcurrentModificationException = java.util.ConcurrentModificationException - - /** - * @param src .. - * @param srcPos .. - * @param dest .. - * @param destPos .. - * @param length .. - */ - def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) { - System.arraycopy(src, srcPos, dest, destPos, length) - } - - /** Create array of the same type as arrayInstance with the given - * length. - * - * @param elemClass .. - * @param length .. - * @return .. - */ - def createArray(elemClass: Class[_], length: Int): AnyRef = - java.lang.reflect.Array.newInstance(elemClass, length) - - def arrayclear(arr: Array[Int]) { java.util.Arrays.fill(arr, 0) } - - def getClassForName(name: String): Class[_] = java.lang.Class.forName(name) - - val EOL = System.getProperty("line.separator", "\n") - - def currentTime: Long = System.currentTimeMillis() - - def collectGarbage: Unit = System.gc() - - /** The name of the default character set encoding as a string */ - def defaultCharsetName: String = { - import java.io._ - new OutputStreamWriter(new ByteArrayOutputStream).getEncoding() - } - -} diff --git a/src/library/jvm/scala/mobile/Code.scala b/src/library/jvm/scala/mobile/Code.scala deleted file mode 100644 index 822a4aaa6c..0000000000 --- a/src/library/jvm/scala/mobile/Code.scala +++ /dev/null @@ -1,247 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.mobile - - -import java.lang.reflect.{Constructor, Method, Modifier} -import java.lang.NoSuchMethodException - -/** The class Code provides apply methods - * with different arities (actually up to 9 parameters) to invoke - * a function simply by specifying its name and argument types.

- * - * Example:

- *    val url = new URL("http://scala-lang.org/classes/examples.jar");
- *    val obj = new Location(url) create "examples.sort";
- *    val ar = Array(6, 2, 8, 5, 1);
- *    obj[Array[Int], Unit]("println")(ar);
- *    obj[Array[Int], Unit]("sort")(ar);
- *    obj[Array[Int], Unit]("println")(ar);
- * - * @see Location - * - * @author Stephane Micheloud - * @version 1.0, 04/05/2004 - */ -class Code(clazz: java.lang.Class[_]) { - - private type JObject = java.lang.Object - - private var instance: JObject = _ - - ///////////////////////////// apply methods /////////////////////////////// - - type AnyClass = Class[T] forSome { type T } - - def apply[R](funName: String) = - () => { - val args = Array[JObject]() - val types = Array[AnyClass]() - applyFun(funName, args, types).asInstanceOf[R] - } - - def apply[A0, R](funName: String) = - (_0: A0) => { - val p = boxValue(_0) - val args = Array(p._1) - val types = Array[AnyClass](p._2) - applyFun(funName, args, types).asInstanceOf[R] - } - - def apply[A0, A1, R](funName: String) = - (_0: A0, _1: A1) => { - val p0 = boxValue(_0) - val p1 = boxValue(_1) - val args = Array(p0._1, p1._1) - val types = Array[AnyClass](p0._2, p1._2) - applyFun(funName, args, types).asInstanceOf[R] - } - - def apply[A0, A1, A2, R](funName: String) = - (_0: A0, _1: A1, _2: A2) => { - val p0 = boxValue(_0) - val p1 = boxValue(_1) - val p2 = boxValue(_2) - val args = Array(p0._1, p1._1, p2._1) - val types = Array[AnyClass](p0._2, p1._2, p2._2) - applyFun(funName, args, types).asInstanceOf[R] - } - - def apply[A0, A1, A2, A3, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3) => { - val p0 = boxValue(_0) - val p1 = boxValue(_1) - val p2 = boxValue(_2) - val p3 = boxValue(_3) - val args = Array(p0._1, p1._1, p2._1, p3._1) - val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2) - applyFun(funName, args, types).asInstanceOf[R] - } - - def apply[A0, A1, A2, A3, A4, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4) => { - val p0 = boxValue(_0) - val p1 = boxValue(_1) - val p2 = boxValue(_2) - val p3 = boxValue(_3) - val p4 = boxValue(_4) - val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1) - val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2) - applyFun(funName, args, types).asInstanceOf[R] - } - - def apply[A0, A1, A2, A3, A4, A5, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5) => { - val p0 = boxValue(_0) - val p1 = boxValue(_1) - val p2 = boxValue(_2) - val p3 = boxValue(_3) - val p4 = boxValue(_4) - val p5 = boxValue(_5) - val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1) - val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2) - applyFun(funName, args, types).asInstanceOf[R] - } - - def apply[A0, A1, A2, A3, A4, A5, A6, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6) => { - val p0 = boxValue(_0) - val p1 = boxValue(_1) - val p2 = boxValue(_2) - val p3 = boxValue(_3) - val p4 = boxValue(_4) - val p5 = boxValue(_5) - val p6 = boxValue(_6) - val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1) - val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2) - applyFun(funName, args, types).asInstanceOf[R] - } - - def apply[A0, A1, A2, A3, A4, A5, A6, A7, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6, _7: A7) => { - val p0 = boxValue(_0) - val p1 = boxValue(_1) - val p2 = boxValue(_2) - val p3 = boxValue(_3) - val p4 = boxValue(_4) - val p5 = boxValue(_5) - val p6 = boxValue(_6) - val p7 = boxValue(_7) - val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1, p7._1) - val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2, p7._2) - applyFun(funName, args, types).asInstanceOf[R] - } - - def apply[A0, A1, A2, A3, A4, A5, A6, A7, A8, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6, _7: A7, _8: A8) => { - val p0 = boxValue(_0) - val p1 = boxValue(_1) - val p2 = boxValue(_2) - val p3 = boxValue(_3) - val p4 = boxValue(_4) - val p5 = boxValue(_5) - val p6 = boxValue(_6) - val p7 = boxValue(_7) - val p8 = boxValue(_8) - val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1, p7._1, p8._1) - val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2, p7._2, p8._2) - applyFun(funName, args, types).asInstanceOf[R] - } - - ////////////////////// private functions /////////////////////// - - private def boxValue(value: Any) = value match { - /** Should use java.lang.Byte.valueOf(Byte), but only available - * in Java 1.5 and above. */ - case x: Byte => (new java.lang.Byte(x), java.lang.Byte.TYPE) - case x: Boolean => (java.lang.Boolean.valueOf(x), java.lang.Boolean.TYPE) - /** Should use java.lang.Character.valueOf(Char), but only available - * in Java 1.5 and above. */ - case x: Char => (new java.lang.Character(x), java.lang.Character.TYPE) - /** Should use java.lang.Short.valueOf(Short), but only available - * in Java 1.5 and above. */ - case x: Short => (new java.lang.Short(x), java.lang.Short.TYPE) - /** Should use java.lang.Integer.valueOf(Int), but only available - * in Java 1.5 and above. */ - case x: Int => (new java.lang.Integer(x), java.lang.Integer.TYPE) - /** Should use java.lang.Long.valueOf(Long), but only available - * in Java 1.5 and above. */ - case x: Long => (new java.lang.Long(x), java.lang.Long.TYPE) - case x: Float => (new java.lang.Float(x), java.lang.Float.TYPE) - case x: Double => (new java.lang.Double(x), java.lang.Double.TYPE) - case _ => - val x = value.asInstanceOf[JObject] - (x, x.getClass()) - } - - private def isConstructorName(methName: String) = { - var className = clazz.getName() - val classInx = className.lastIndexOf(".") - val methInx = methName.lastIndexOf(".") - if (classInx > 0 && methInx < 0) - className = className.substring(classInx + 1, className.length()) - methName.equals(className) - } - - private def applyFun(methName: String, args: Array[JObject], - argTypes: Array[Class[T] forSome { type T }]): JObject = { - try { - val method = clazz.getMethod(methName, argTypes) - var obj: JObject = null - if (! Modifier.isStatic(method.getModifiers())) { - if (instance eq null) { - instance = try { - clazz.newInstance().asInstanceOf[AnyRef] - } catch { case _ => - val cs = clazz.getConstructors() -//Console.println("cs.length=" + cs.length); - if (cs.length > 0) { - cs(0).newInstance(Array("")).asInstanceOf[AnyRef] - } else { - error("class " + clazz.getName() + " has no public constructor") - null - } - } - } - obj = instance - } - val result = method.invoke(obj, args) - if (result eq null) ().asInstanceOf[JObject] else result - } - catch { - case me: NoSuchMethodException => - if (isConstructorName(methName)) { - try { - val cstr = clazz.getConstructor(argTypes) - instance = cstr.newInstance(args).asInstanceOf[AnyRef] - instance - } - catch { - case e: Exception => - Console.println(e.getMessage()) - e.printStackTrace() - } - } - else { - Console.println(me.getMessage()) - me.printStackTrace() - } - null - case e: Exception => - Console.println(e.getMessage()) - e.printStackTrace() - null - } - } - -} - diff --git a/src/library/jvm/scala/mobile/Location.scala b/src/library/jvm/scala/mobile/Location.scala deleted file mode 100644 index 1048b403e7..0000000000 --- a/src/library/jvm/scala/mobile/Location.scala +++ /dev/null @@ -1,100 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.mobile - - -import java.lang.ClassLoader -import java.net._ - -import scala.collection.mutable._ - -/** The class Location provides a create - * method to instantiate objects from a network location by - * specifying the URL address of the jar/class file.

- * - * An update of the jar/class file should not break your code as far - * as the used class names and method signatures are the same.

- * - * Example:

- *    val url = new URL("http://scala-lang.org/classes/examples.jar");
- *    val obj = new Location(url) create "examples.sort";
- * - * @see Code - * - * @author Stephane Micheloud - * @version 1.0, 04/05/2004 - */ -class Location(url: URL) { - - /** A cache containing all class loaders of this location. - */ - private var lcache: Map[URL, ClassLoader] = new HashMap - - /** The class loader associated with this location. - */ - private val loader = if (url eq null) - ClassLoader.getSystemClassLoader() - else - lcache.get(url) match { - case Some(cl) => - cl - case _ => - val cl = new URLClassLoader(Array(url)) - lcache(url) = cl - cl - } - - /** A cache containing all classes of this location. - */ - private var ccache: Map[String, java.lang.Class[T] forSome { type T }] = new HashMap - - /** Return the code description for the string className - * at this location. - * - * @param classname the name of the class - * @return the code description corresponding to - * className. - */ - def create(className: String) = new Code( - ccache.get(className) match { - case Some(clazz) => - clazz - case _ => - val clazz = if (loader.loadClass(className).isInterface()) { - // Scala source: class A { ... }; - // Java bytecode: interface A.class + class A$class.class - loader.loadClass(className + "$class") - } - else { - // Scala source: object A { ... }; - // Java bytecode: interface A.class + class A$.class - loader.loadClass(className + "$") - } - ccache(className) = clazz - clazz - } - ) - -} - -/** The object Location can be used to instantiate - * objects on the same Java VM. It is just provided to illustrate - * the special case where resources are available locally.

- * - * Example:

- *    val obj = Location.create("xcode.Math");
- *    val x = obj[Int, Int]("square")(5);
- * - * @author Stephane Micheloud - * @version 1.0, 04/05/2004 - */ -object Location extends Location(null) diff --git a/src/library/jvm/scala/ref/PhantomReference.scala b/src/library/jvm/scala/ref/PhantomReference.scala deleted file mode 100644 index 5be4e39117..0000000000 --- a/src/library/jvm/scala/ref/PhantomReference.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.ref - -/** - * @author Sean McDirmid - */ -class PhantomReference[+T <: AnyRef](value: T, queue: ReferenceQueue[T]) extends ReferenceWrapper[T] { - val underlying: java.lang.ref.PhantomReference[_ <: T] = - new java.lang.ref.PhantomReference[T](value, queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]]) -} - diff --git a/src/library/jvm/scala/ref/Reference.scala b/src/library/jvm/scala/ref/Reference.scala deleted file mode 100644 index f36d355831..0000000000 --- a/src/library/jvm/scala/ref/Reference.scala +++ /dev/null @@ -1,27 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.ref - -/** - * @see java.lang.ref.Reference - * @author Sean McDirmid - */ -trait Reference[+T <: AnyRef] extends Function0[T] { - @deprecated def isValid: Boolean - /** return the underlying value */ - def apply(): T - /** return Some underlying if it hasn't been collected, otherwise None */ - def get : Option[T] - override def toString = get.map(_.toString).getOrElse("") - def clear(): Unit - def enqueue(): Boolean - def isEnqueued(): Boolean -} diff --git a/src/library/jvm/scala/ref/ReferenceQueue.scala b/src/library/jvm/scala/ref/ReferenceQueue.scala deleted file mode 100644 index 1a4e9ea2e0..0000000000 --- a/src/library/jvm/scala/ref/ReferenceQueue.scala +++ /dev/null @@ -1,27 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.ref - -/** - * @author Sean McDirmid - */ -class ReferenceQueue[+T <: AnyRef] { - private[ref] val underlying: java.lang.ref.ReferenceQueue[_ <: T] = new java.lang.ref.ReferenceQueue[T] - override def toString = underlying.toString - protected class Wrapper[U <: AnyRef](val underlying: java.lang.ref.Reference[U]) extends ReferenceWrapper[U] - protected def Wrapper[U <: AnyRef](ref: java.lang.ref.Reference[U]) = ref match { - case null => None - case ref => Some(new Wrapper(ref)) - } - def poll: Option[Reference[T]] = Wrapper(underlying.poll) - def remove: Option[Reference[T]] = Wrapper(underlying.remove) - def remove(timeout: Long): Option[Reference[T]] = Wrapper(underlying.remove(timeout)) -} diff --git a/src/library/jvm/scala/ref/ReferenceWrapper.scala b/src/library/jvm/scala/ref/ReferenceWrapper.scala deleted file mode 100644 index b93e98b880..0000000000 --- a/src/library/jvm/scala/ref/ReferenceWrapper.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.ref - -/** - * @author Sean McDirmid - */ -trait ReferenceWrapper[+T <: AnyRef] extends Reference[T] with Proxy { - val underlying: java.lang.ref.Reference[_ <: T] - @deprecated def isValid = underlying.get != null - override def get = { - val ret = underlying.get.asInstanceOf[T] - if (ret eq null) None else Some(ret) - } - def apply() = { - val ret = underlying.get.asInstanceOf[T] - if (ret eq null) throw new NoSuchElementException - ret - } - def clear = underlying.clear - def enqueue = underlying.enqueue - def isEnqueued = underlying.isEnqueued - - def self = underlying -} diff --git a/src/library/jvm/scala/ref/SoftReference.scala b/src/library/jvm/scala/ref/SoftReference.scala deleted file mode 100644 index fc6313f6ef..0000000000 --- a/src/library/jvm/scala/ref/SoftReference.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.ref - -/** - * @author Sean McDirmid - */ -class SoftReference[+T <: AnyRef](value : T, queue : ReferenceQueue[T]) extends ReferenceWrapper[T] { - def this(value : T) = this(value, null); - val underlying: java.lang.ref.SoftReference[_ <: T] = - if (queue == null) new java.lang.ref.SoftReference[T](value); - else new java.lang.ref.SoftReference[T](value, queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]]) -} diff --git a/src/library/jvm/scala/ref/WeakReference.scala b/src/library/jvm/scala/ref/WeakReference.scala deleted file mode 100644 index 0d2e29d601..0000000000 --- a/src/library/jvm/scala/ref/WeakReference.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.ref - -/** - * @author Sean McDirmid - */ -class WeakReference[+T <: AnyRef](value: T, queue: ReferenceQueue[T]) extends ReferenceWrapper[T] { - def this(value: T) = this(value, null) - val underlying: java.lang.ref.WeakReference[_ <: T] = - if (queue == null) new java.lang.ref.WeakReference[T](value) - else new java.lang.ref.WeakReference[T](value, queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]]) -} diff --git a/src/library/jvm/scala/testing/Benchmark.scala b/src/library/jvm/scala/testing/Benchmark.scala deleted file mode 100644 index bd69de430a..0000000000 --- a/src/library/jvm/scala/testing/Benchmark.scala +++ /dev/null @@ -1,97 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.testing - - -import compat.Platform - -/**

- * Benchmark can be used to quickly turn an existing - * class into a benchmark. Here is a short example: - *

- *  object sort1 extends Sorter with Benchmark {
- *    def run = sort(List.range(1, 1000))
- *  }
- *  
- *

- * The run method has to be defined by the user, who - * will perform the timed operation there. - * Run the benchmark as follows: - *

- *
- *  > scala sort1 5 times.log
- *  
- *

- * This will run the benchmark 5 times and log the execution times in - * a file called times.log - *

- * - * @author Iulian Dragos, Burak Emir - */ -trait Benchmark { - - /** this method should be implemented by the concrete benchmark */ - def run() - - var multiplier = 1 - - /** Run the benchmark the specified number of times - * and return a list with the execution times in milliseconds - * in reverse order of the execution - * - * @param noTimes ... - * @return ... - */ - def runBenchmark(noTimes: Int): List[Long] = - for (i <- List.range(1, noTimes + 1)) yield { - val startTime = Platform.currentTime - var i = 0; while (i < multiplier) { - run() - i += 1 - } - val stopTime = Platform.currentTime - Platform.collectGarbage - - stopTime - startTime - } - - /** a string that is written at the beginning of the output line - * that contains the timings. By default, this is the class name. - */ - def prefix: String = getClass().getName() - - /** - * The entry point. It takes two arguments (n), (name) - * and an optional argument multiplier (mult). - * (n) is the number of consecutive runs, (name) the name - * of a log file where to append the times. - * if (mult) is present, the same thing is repeated (mult) - * times. - */ - def main(args: Array[String]) { - if (args.length > 1) { - val logFile = new java.io.FileWriter(args(1), true) // append, not overwrite - if (args.length >= 3) - multiplier = args(2).toInt - logFile.write(prefix) - for (t <- runBenchmark(args(0).toInt)) - logFile.write("\t\t" + t) - - logFile.write(Platform.EOL) - logFile.flush() - } else { - Console.println("Usage: scala benchmarks.program ") - Console.println(" or: scala benchmarks.program ") - } - } -} - diff --git a/src/library/jvm/scala/testing/SUnit.scala b/src/library/jvm/scala/testing/SUnit.scala deleted file mode 100644 index 1a87c64b0e..0000000000 --- a/src/library/jvm/scala/testing/SUnit.scala +++ /dev/null @@ -1,253 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.testing - -import scala.collection.mutable.ArrayBuffer - -/** - *

- * Unit testing methods in the spirit of - * JUnit framework. - *

- *

- * Use these classes like this: - *

- *
- * import scala.testing.SUnit
- * import SUnit._
- *
- * class MyTest(n: String) extends TestCase(n) {
- *
- *   override def runTest() = n match {
- *     case "myTest1" => assertTrue(true)
- *     case "myTest2" => assertTrue("hello", false)
- *   }
- * }
- *
- * val r = new TestResult()
- * suite.run(r)
- * for (tf <- r.failures()) {
- *   println(tf.toString())
- * }
- * 
- *

- * The trait TestConsoleMain contains this code as - * a main method, for convenience. - *

- * - * @author Burak Emir - */ -object SUnit { - - /**

- * Convenience trait, mix it in a TestMain object and - * implement "suite" to get this code. - *

-   *  val r = new TestResult()
-   *  suite.run(r)
-   *  for (val tf <- r.failures()) {
-   *    println(tf.toString())
-   *  
- */ - trait TestConsoleMain { - def suite: TestSuite - def main(args: Array[String]) { - val r = new TestResult() - suite.run(r) - for (tf <- r.failures()) - println(tf.toString()) - } - } - - /** a Test can be run with its result being collected */ - trait Test { - def run(r: TestResult): Unit - } - - /** The class TestCase defines the fixture to run multiple - * tests. - * - * @param name ... - */ - abstract class TestCase(val name: String) extends Test with Assert { - - protected def runTest(): Unit - - def run(r: TestResult) { - try { - runTest() - } catch { - case t:Throwable => r.addFailure(this, t) - } - } - - def setUp() {} - - def tearDown() {} - - override def toString() = name - } - - /** The class TestFailure collects a failed test together - * with the thrown exception. - */ - class TestFailure(val failedTest: Test, val thrownException: Throwable) { - - def this(p: (Test, Throwable)) = this(p._1, p._2) - - override def toString() = - failedTest.toString() + " failed due to " + thrownException.toString() - - def trace(): String = thrownException.getStackTraceString - - } - - /** a TestResult collects the result of executing a test case */ - class TestResult { - val buf = new ArrayBuffer[(Test, Throwable)]() - - def addFailure(test: Test, t: Throwable) { - buf += (test, t) - } - - def failureCount() = - buf.length - - def failures() = - buf.elements map { x => new TestFailure(x) } - } - - /** The class TestSuite runs a composite of test cases. - */ - class TestSuite(tests: Test*) extends Test { - - def this(names: Seq[String], constr: String => Test) = - this((names map constr):_*) - - val buf = new ArrayBuffer[Test]() - - buf ++= tests - - def addTest(t: Test) { - buf += t - } - - def run(r: TestResult) { - for (t <- buf) t.run(r) - } - } - - /** an AssertFailed is thrown for a failed assertion */ - case class AssertFailed(msg: String, stackTrace: Boolean) extends RuntimeException { - private val msg0 = if (stackTrace) { - import java.io._ - val wrt = new StringWriter - printStackTrace(new PrintWriter(wrt)) - wrt.toString - } else msg - override def toString() = - if (msg0 eq null) "failed assertion: " + msg else msg0 - } - - /** this class defines useful assert methods */ - trait Assert { - - def enableStackTrace: Boolean = true - - /** fails if ! actual.sameElements(expected) */ - def assertSameElements[A](actual: Seq[A], expected: Seq[A]) { - if (! actual.sameElements(expected)) - fail("(no message)", actual.toString, expected.toString) - } - - /** fails if expected != actual */ - def assertEquals[A](msg: String, expected: A, actual: A) { - if (expected != actual) fail(msg, expected, actual) - } - - /** fails if expected != actual */ - def assertEquals[A](expected: A, actual: A) { - assertEquals("(no message)", expected, actual) - } - - /** succeeds if actual is false */ - def assertFalse(msg: String, actual: Boolean) { - assertEquals(msg, false, actual) - } - - /** succeeds if actual is false */ - def assertFalse(actual: Boolean) { - assertFalse("(no message)", actual) - } - - /** fails if null eq actual */ - def assertNotNull(msg: String, actual: AnyRef) { - if (null eq actual) fail(msg) - } - - /** fails if null eq actual */ - def assertNotNull(actual: AnyRef): Unit = - assertNotNull("(no message)", actual) - - /** fails if expected eq actual */ - def assertNotEq(msg: String, expected: AnyRef, actual: AnyRef) { - if (expected eq actual) fail(msg) - } - - /** fails if expected eq actual */ - def assertNotEq(expected: AnyRef, actual: AnyRef) { - assertNotEq("(no message)", expected, actual) - } - - /** fails if actual ne null */ - def assertNull(msg: String, actual: AnyRef) { - if (null ne actual) fail(msg) - } - - /** fails if actual ne null */ - def assertNull(actual: AnyRef) { - assertNull("(no message)", actual) - } - - /** fails if expected ne actual */ - def assertEq(msg: String, expected: AnyRef, actual: AnyRef) { - if (expected ne actual) fail(msg) - } - - /** fails if expected ne actual */ - def assertEq(expected: AnyRef, actual: AnyRef) { - assertEq("(no message)", expected, actual) - } - - /** succeeds if actual == true */ - def assertTrue(msg: String, actual: Boolean) { - assertEquals(msg, true, actual) - } - - /** succeeds if actual == true */ - def assertTrue(actual: Boolean) { - assertTrue("(no message)", actual) - } - - /** throws AssertFailed with given message msg. - */ - def fail(msg: String) { - throw AssertFailed(msg, enableStackTrace) - } - - def fail[A](msg: String, expected: A, actual: A) { - throw AssertFailed(msg + - ", expected: " + expected + - ", actual: " + actual, enableStackTrace) - } - } -} diff --git a/src/library/jvm/scala/text/Document.scala b/src/library/jvm/scala/text/Document.scala deleted file mode 100644 index 39aea9ec81..0000000000 --- a/src/library/jvm/scala/text/Document.scala +++ /dev/null @@ -1,122 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.text - - -import java.io.Writer - -case object DocNil extends Document -case object DocBreak extends Document -case class DocText(txt: String) extends Document -case class DocGroup(doc: Document) extends Document -case class DocNest(indent: Int, doc: Document) extends Document -case class DocCons(hd: Document, tl: Document) extends Document - -/** - * A basic pretty-printing library, based on Lindig's strict version - * of Wadler's adaptation of Hughes' pretty-printer. - * - * @author Michel Schinz - * @version 1.0 - */ -abstract class Document { - def ::(hd: Document): Document = DocCons(hd, this) - def ::(hd: String): Document = DocCons(DocText(hd), this) - def :/:(hd: Document): Document = hd :: DocBreak :: this - def :/:(hd: String): Document = hd :: DocBreak :: this - - /** - * Format this document on writer and try to set line - * breaks so that the result fits in width columns. - * - * @param width ... - * @param writer ... - */ - def format(width: Int, writer: Writer) { - type FmtState = (Int, Boolean, Document) - - def fits(w: Int, state: List[FmtState]): Boolean = state match { - case _ if w < 0 => - false - case List() => - true - case (_, _, DocNil) :: z => - fits(w, z) - case (i, b, DocCons(h, t)) :: z => - fits(w, (i,b,h) :: (i,b,t) :: z) - case (_, _, DocText(t)) :: z => - fits(w - t.length(), z) - case (i, b, DocNest(ii, d)) :: z => - fits(w, (i + ii, b, d) :: z) - case (_, false, DocBreak) :: z => - fits(w - 1, z) - case (_, true, DocBreak) :: z => - true - case (i, _, DocGroup(d)) :: z => - fits(w, (i, false, d) :: z) - } - - def spaces(n: Int) { - var rem = n - while (rem >= 16) { writer write " "; rem -= 16 } - if (rem >= 8) { writer write " "; rem -= 8 } - if (rem >= 4) { writer write " "; rem -= 4 } - if (rem >= 2) { writer write " "; rem -= 2} - if (rem == 1) { writer write " " } - } - - def fmt(k: Int, state: List[FmtState]): Unit = state match { - case List() => () - case (_, _, DocNil) :: z => - fmt(k, z) - case (i, b, DocCons(h, t)) :: z => - fmt(k, (i, b, h) :: (i, b, t) :: z) - case (i, _, DocText(t)) :: z => - writer write t - fmt(k + t.length(), z) - case (i, b, DocNest(ii, d)) :: z => - fmt(k, (i + ii, b, d) :: z) - case (i, true, DocBreak) :: z => - writer write "\n" - spaces(i); - fmt(i, z) - case (i, false, DocBreak) :: z => - writer write " " - fmt(k + 1, z) - case (i, b, DocGroup(d)) :: z => - val fitsFlat = fits(width - k, (i, false, d) :: z) - fmt(k, (i, !fitsFlat, d) :: z) - } - - fmt(0, (0, false, DocGroup(this)) :: Nil) - } -} - -object Document { - /** The empty document */ - def empty = DocNil - - /** A break, which will either be turned into a space or a line break */ - def break = DocBreak - - /** A document consisting of some text literal */ - def text(s: String): Document = DocText(s) - - /** - * A group, whose components will either be printed with all breaks - * rendered as spaces, or with all breaks rendered as line breaks. - */ - def group(d: Document): Document = DocGroup(d) - - /** A nested document, which will be indented as specified. */ - def nest(i: Int, d: Document): Document = DocNest(i, d) -} diff --git a/src/library/jvm/scala/throws.scala b/src/library/jvm/scala/throws.scala deleted file mode 100644 index 463a01b3f9..0000000000 --- a/src/library/jvm/scala/throws.scala +++ /dev/null @@ -1,30 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -*/ - -// $Id$ - - -package scala - -import Predef._ - -/**

- * Annotation for specifying the exceptions thrown by a method. - * For example: - *

- *    class Reader(fname: String) {
- *      private val in =
- *        new BufferedReader(new FileReader(fname))
- *      @throws(classOf[IOException])
- *      def read() = in.read()
- *    }
- * - * @author Nikolay Mihaylov - * @version 1.0, 19/05/2006 - */ -class throws(clazz: Class[_]) extends Annotation diff --git a/src/library/scala/Application.scala b/src/library/scala/Application.scala new file mode 100644 index 0000000000..da34a4d224 --- /dev/null +++ b/src/library/scala/Application.scala @@ -0,0 +1,60 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import java.lang.System.getProperty +import scala.compat.Platform.currentTime + +/**

+ * The Application class can be used to quickly turn objects + * into executable programs. Here is an example: + *

+ *  object Main extends Application {
+ *    Console.println("Hello World!")
+ *  }
+ *  
+ *

+ * Here, object Main inherits the main method + * of Application. The body of the Main object + * defines the main program. This technique does not work if the main + * program depends on command-line arguments (which are not accessible + * with the technique presented here). + *

+ *

+ * It is possible to time the execution of objects that inherit from class + * Application by setting the global scala.time + * property. Here is an example for benchmarking object Main: + *

+ *  java -Dscala.time Main
+ *  
+ * + * @author Matthias Zenger + * @version 1.0, 10/09/2003 + */ + +trait Application { + + /** The time when execution of this program started. + */ + val executionStart: Long = currentTime + + /** The default main method. + * + * @param args the arguments passed to the main method + */ + def main(args: Array[String]) = { + if (getProperty("scala.time") ne null) { + val total = currentTime - executionStart + Console.println("[total " + total + "ms]") + } + } +} diff --git a/src/library/scala/Array.scala b/src/library/scala/Array.scala new file mode 100644 index 0000000000..edd508e6ef --- /dev/null +++ b/src/library/scala/Array.scala @@ -0,0 +1,452 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + + +import Predef._ +import compat.Platform.arraycopy + +/** This object contains utility methods operating on arrays. + * + * @author Martin Odersky + * @version 1.0 + */ +object Array { + + /** Copy one array to another. + * Equivalent to + * System.arraycopy(src, srcPos, dest, destPos, length), + * except that this works also for polymorphic and boxed arrays. + * + * @param src ... + * @param srcPos ... + * @param dest ... + * @param destPos ... + * @param length ... + */ + def copy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) { + src match { + case xs: runtime.BoxedArray => + xs.copyTo(srcPos, dest, destPos, length) + case _ => + dest match { + case xs: runtime.BoxedArray => + xs.copyFrom(src, srcPos, destPos, length) + case _ => + arraycopy(src, srcPos, dest, destPos, length) + } + } + } + + /** Concatenate all argument sequences into a single array. + * + * @param xs the given argument sequences + * @return the array created from the concatenated arguments + */ + def concat[T](xs: Seq[T]*): Array[T] = { + var len = 0 + for (x <- xs) len += x.length + val result = new Array[T](len) + var start = 0 + for (x <- xs) { + copy(x.toArray, 0, result, start, x.length) + start += x.length + } + result + } + + /** Create a an array containing of successive integers. + * + * @param from the value of the first element of the array + * @param end the value of the last element fo the array plus 1 + * @return the sorted array of all integers in range [from;end). + */ + def range(start: Int, end: Int): Array[Int] = { + val result = new Array[Int](end - start) + for (i <- start until end) result(i - start) = i + result + } + + /** Create an array with given elements. + * + * @param xs the elements to put in the array + * @return the array containing elements xs. + */ + def apply[A <: AnyRef](xs: A*): Array[A] = { + val array = new Array[A](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + +/* The following metod clashes with the previous one, and has therefore been + * removed. Note that this is a choice between efficiency and generality. + * The previous factory method is more efficient than the one that has been + * commented out. Since it is anyway possible to create a polymorphic array + * using + * new Array[T] + * it was preferred to restrict the definition of the factory method. + + def Array[A](xs: A*): Array[A] = { + val array = new Array[A](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } +*/ + + def apply(xs: Boolean*): Array[Boolean] = { + val array = new Array[Boolean](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + def apply(xs: Byte*): Array[Byte] = { + val array = new Array[Byte](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + def apply(xs: Short*): Array[Short] = { + val array = new Array[Short](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + def apply(xs: Char*): Array[Char] = { + val array = new Array[Char](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + def apply(xs: Int*): Array[Int] = { + val array = new Array[Int](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + def apply(xs: Long*): Array[Long] = { + val array = new Array[Long](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + def apply(xs: Float*): Array[Float] = { + val array = new Array[Float](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + def apply(xs: Double*): Array[Double] = { + val array = new Array[Double](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + def apply(xs: Unit*): Array[Unit] = { + val array = new Array[Unit](xs.length) + var i = 0 + for (x <- xs.elements) { array(i) = x; i += 1 } + array + } + + /** Create an array containing several copies of an element. + * + * @param n the length of the resulting array + * @param elem the element composing the resulting array + * @return an array composed of n elements all equal to elem + */ + def make[A](n: Int, elem: A): Array[A] = { + val a = new Array[A](n) + var i = 0 + while (i < n) { + a(i) = elem + i += 1 + } + a + } + + /** This method is called as a result of a pattern match { case Array(...) => } or val Array(...) = .... + * + * @param x the selector value + * @return array wrapped in an option + */ + def unapplySeq[A](x: Array[A]): Option[Seq[A]] = Some(x) + + trait ArrayLike[A] extends RandomAccessSeq.Mutable[A] { + def force : Array[A] + } + + trait Projection[A] extends RandomAccessSeq.MutableProjection[A] with ArrayLike[A] { + protected def newArray[B >: A](length : Int, elements : Iterator[A]) : Array[B] + override def toArray[B >: A] = (newArray(length, elements))//:Any).asInstanceOf[Array[B]] + override def force : Array[A] = toArray + override def drop( from: Int) = slice(from, length) + override def take(until: Int) = slice(0, until) + override def dropWhile(p: A => Boolean) = { + val c = length + 1 + drop((findIndexOf(!p(_)) + c) % c) + } + override def takeWhile(p: A => Boolean) = { + val c = length + 1 + take((findIndexOf(!p(_)) + c) % c) + } + override def slice(from0: Int, until0: Int): Projection[A] = new RandomAccessSeq.MutableSlice[A] with Projection[A] { + override def from = from0 + override def until = until0 + override def underlying = Projection.this + override protected def newArray[B >: A](length: Int, elements: Iterator[A]) = + underlying.newArray(length, elements) + override def slice(from0: Int, until0: Int) = + Projection.this.slice(from + from0, from + until0) + } + + + override def reverse : Projection[A] = new Projection[A] { + override protected def newArray[B >: A](length : Int, elements : Iterator[A]) = + Projection.this.newArray(length, elements) + def update(idx : Int, what : A) : Unit = Projection.this.update(length - idx - 1, what) + def length = Projection.this.length + def apply(idx : Int) = Projection.this.apply(length - idx - 1) + override def stringPrefix = Projection.this.stringPrefix + "R" + } + } + trait Array0[A] extends RandomAccessSeq.Mutable[A] with ArrayLike[A] { + override def projection : Projection[A] = throw new Error + override def slice(from : Int, until : Int) : Projection[A] = projection.slice(from, until) + override def take(until : Int) : Projection[A] = projection.take(until) + override def drop(from : Int) : Projection[A] = projection.drop(from) + override def dropWhile(p: A => Boolean) = projection.dropWhile(p) + override def takeWhile(p: A => Boolean) = projection.takeWhile(p) + override def reverse = projection.reverse + override def force = asInstanceOf[Array[A]] + } +} + +/** This class represents polymorphic arrays. Array[T] is Scala's representation + * for Java's T[]. + * + * @author Martin Odersky + * @version 1.0 + */ +final class Array[A](_length: Int) extends Array.Array0[A] { + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int) = { + this(dim1) + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int) = { + this(dim1) + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int) = { + this(dim1) + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int) = { + this(dim1); + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int) = { + this(dim1) + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int) = { + this(dim1) + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int) = { + this(dim1) + throw new Error() + } + + /** Multidimensional array creation */ + def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int, dim9: Int) = { + this(dim1) + throw new Error() + } + + /** The length of the array */ + def length: Int = throw new Error() + + /** The element at given index. + *

+ * Indices start a 0; xs.apply(0) is the first + * element of array xs. + *

+ *

+ * Note the indexing syntax xs(i) is a shorthand for + * xs.apply(i). + *

+ * + * @param i the index + * @throws ArrayIndexOutOfBoundsException if i < 0 or + * length <= i + */ + def apply(i: Int): A = throw new Error() + + /**

+ * Update the element at given index. + *

+ *

+ * Indices start a 0; xs.apply(0) is the first + * element of array xs. + *

+ *

+ * Note the indexing syntax xs(i) = x is a shorthand + * for xs.update(i, x). + *

+ * + * @param i the index + * @param x the value to be written at index i + * @throws ArrayIndexOutOfBoundsException if i < 0 or + * length <= i + */ + override def update(i: Int, x: A) { throw new Error() } + + /** An iterator returning the elements of this array, starting from 0. + */ + override def elements: Iterator[A] = throw new Error() + + /** @deprecated use slice(from,end).force instead */ + def subArray(from: Int, end: Int): Array[A] = throw new Error() + + /** Returns an array consisting of all elements of this array that satisfy the + * predicate p. The order of the elements is preserved. + * + * @param p the predicate used to filter the array. + * @return the elements of this array satisfying p. + */ + override def filter(p: A => Boolean): Array[A] = throw new Error() + + /** Returns an array consisting of all elements of this array followed + * by all elements of the argument iterable. + */ + override def ++[B >: A](that: Iterable[B]): Array[B] = throw new Error() + + /** Returns the array resulting from applying the given function f to each + * element of this array. + * + * @param f function to apply to each element. + * @return [f(a0), ..., f(an)] if this array is [a0, ..., an]. + */ + override def map[B](f: A => B): Array[B] = throw new Error() + + /** Applies the given function f to each element of + * this array, then concatenates the results. + * + * @param f the function to apply on each element. + * @return f(a0) ::: ... ::: f(an) if + * this array is [a0, ..., an]. + */ + override def flatMap[B](f: A => Iterable[B]): Array[B] = throw new Error() + + /** Returns an array formed from this array and the specified array + * that by associating each element of the former with + * the element at the same position in the latter. + * If one of the two arrays is longer than the other, its remaining elements are ignored. + * + * @return Array({a0,b0}, ..., + * {amin(m,n),bmin(m,n)}) when + * Array(a0, ..., am) + * zip Array(b0, ..., bn) is invoked. + */ + def zip[B](that: Array[B]): Array[(A, B)] = throw new Error() + + /** Returns an array that pairs each element of this array + * with its index, counting from 0. + * + * @return the array Array({a0,0}, {a1,1},...) + * where ai are the elements of this stream. + */ + def zipWithIndex: Array[(A, Int)] = throw new Error() + + /** Returns an array that contains all indices of this array */ + def indices: Array[Int] = throw new Error() + + /** + * @return a deep string representation of this array. + */ + def deepToString(): String = throw new Error() + + /**

+ * Returns a string representation of this array object. The resulting string + * begins with the string start and is finished by the string + * end. Inside, the string representations of elements (w.r.t. + * the method deepToString()) are separated by the string + * sep. For example: + *

+ *

+ * Array(Array(1, 2), Array(3)).deepMkString("[", "; ", "]") = "[[1; 2]; [3]]" + *

+ * + * @param start starting string. + * @param sep separator string. + * @param end ending string. + * @return a string representation of this array object. + */ + def deepMkString(start: String, sep: String, end: String): String = + throw new Error() + + /** Returns a string representation of this array object. The string + * representations of elements (w.r.t. the method deepToString()) + * are separated by the string sep. + * + * @param sep separator string. + * @return a string representation of this array object. + */ + def deepMkString(sep: String): String = throw new Error() + + /**

+ * Returns true if the two specified arrays are + * deeply equal to one another. + *

+ *

+ * Two array references are considered deeply equal if both are null, + * or if they refer to arrays that contain the same number of elements + * and all corresponding pairs of elements in the two arrays are deeply + * equal. + *

+ *

+ * See also method deepEquals in the Java class + * java.utils.Arrays + *

+ * + * @param that the second + * @return true iff both arrays are deeply equal. + */ + def deepEquals(that: Any): Boolean = throw new Error() + +} diff --git a/src/library/scala/BigDecimal.scala b/src/library/scala/BigDecimal.scala new file mode 100644 index 0000000000..31cd6316ae --- /dev/null +++ b/src/library/scala/BigDecimal.scala @@ -0,0 +1,266 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2007-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +package scala + +import java.math.{BigDecimal => BigDec} + +/** + * @author Stephane Micheloud + * @version 1.0 + */ +object BigDecimal { + + object RoundingMode extends Enumeration { + type RoundingMode = Value + val ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_UP, + ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_UNNECESSARY = Value + } + + private val minCached = -512 + private val maxCached = 512 + private lazy val cache = new Array[BigDecimal](maxCached - minCached + 1) + + /** Constructs a BigDecimal whose value is equal to that of the + * specified Integer value. + * + * @param i the specified integer value + * @return the constructed BigDecimal + */ + def apply(i: Int): BigDecimal = + if (minCached <= i && i <= maxCached) { + val offset = i - minCached + var n = cache(offset) + if (n eq null) { n = new BigDecimal(BigDec.valueOf(i)); cache(offset) = n } + n + } else new BigDecimal(BigDec.valueOf(i)) + + /** Constructs a BigDecimal whose value is equal to that of the + * specified long value. + * + * @param l the specified long value + * @return the constructed BigDecimal + */ + def apply(l: Long): BigDecimal = + if (minCached <= l && l <= maxCached) apply(l.toInt) + else new BigDecimal(BigDec.valueOf(l)) + + /** Constructs a BigDecimal whose value is equal to that of the + * specified double value. + * + * @param d the specified Double value + * @return the constructed BigDecimal + */ + def apply(d: Double): BigDecimal = + new BigDecimal(new BigDec(d)) + + /** Translates a character array representation of a BigDecimal + * into a BigDecimal. + */ + def apply(x: Array[Char]): BigDecimal = + new BigDecimal(new BigDec(x.toString)) + + /** Translates the decimal String representation of a BigDecimal + * into a BigDecimal. + */ + def apply(x: String): BigDecimal = + new BigDecimal(new BigDec(x)) + + /** Constructs a BigDecimal whose value is equal to that of the + * specified BigInt value. + * + * @param x the specified BigInt value + * @return the constructed BigDecimal + */ + def apply(x: BigInt): BigDecimal = + new BigDecimal(new BigDec(x.bigInteger)) + + /** Implicit conversion from Int to BigDecimal. */ + implicit def int2bigDecimal(i: Int): BigDecimal = apply(i) + + /** Implicit copnversion from Long to BigDecimal. */ + implicit def long2bigDecimal(l: Long): BigDecimal = apply(l) + + /** Implicit copnversion from Double to BigDecimal. */ + implicit def double2bigDecimal(d: Double): BigDecimal = apply(d) + + /** Implicit conversion from BigDecimal to Ordered. */ + implicit def bigDecimal2ordered(x: BigDecimal): Ordered[BigDecimal] = + new Ordered[BigDecimal] with Proxy { + def self: Any = x + def compare(y: BigDecimal): Int = x.bigDecimal.compareTo(y.bigDecimal) + } +} + +/** + * @author Stephane Micheloud + * @version 1.0 + */ +@serializable +class BigDecimal(val bigDecimal: BigDec) extends java.lang.Number { + import BigDecimal.RoundingMode._ + + /** Returns the hash code for this BigDecimal. */ + override def hashCode(): Int = this.bigDecimal.hashCode() + + /** Compares this BigDecimal with the specified value for equality. + */ + override def equals (that: Any): Boolean = that match { + case that: BigDecimal => this equals that + case that: java.lang.Double => this.bigDecimal.doubleValue == that.doubleValue + case that: java.lang.Float => this.bigDecimal.floatValue == that.floatValue + case that: java.lang.Number => this equals BigDecimal(that.longValue) + case that: java.lang.Character => this equals BigDecimal(that.charValue.asInstanceOf[Int]) + case _ => false + } + + /** Compares this BigDecimal with the specified BigDecimal for equality. + */ + def equals (that: BigDecimal): Boolean = + this.bigDecimal.compareTo(that.bigDecimal) == 0 + + /** Compares this BigDecimal with the specified BigDecimal + */ + def compare (that: BigDecimal): Int = this.bigDecimal.compareTo(that.bigDecimal) + + /** Less-than-or-equals comparison of BigDecimals + */ + def <= (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) <= 0 + + /** Greater-than-or-equals comparison of BigDecimals + */ + def >= (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) >= 0 + + /** Less-than of BigDecimals + */ + def < (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) < 0 + + /** Greater-than comparison of BigDecimals + */ + def > (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) > 0 + + /** Addition of BigDecimals + */ + def + (that: BigDecimal): BigDecimal = + new BigDecimal(this.bigDecimal.add(that.bigDecimal)) + + /** Subtraction of BigDecimals + */ + def - (that: BigDecimal): BigDecimal = + new BigDecimal(this.bigDecimal.subtract(that.bigDecimal)) + + /** Multiplication of BigDecimals + */ + def * (that: BigDecimal): BigDecimal = + new BigDecimal(this.bigDecimal.multiply(that.bigDecimal)) + + /** Division of BigDecimals + */ + def / (that: BigDecimal): BigDecimal = + new BigDecimal(this.bigDecimal.divide(that.bigDecimal, this.scale - that.scale)) + + /** Returns the minimum of this and that + */ + def min (that: BigDecimal): BigDecimal = + new BigDecimal(this.bigDecimal.min(that.bigDecimal)) + + /** Returns the maximum of this and that + */ + def max (that: BigDecimal): BigDecimal = + new BigDecimal(this.bigDecimal.max(that.bigDecimal)) + + /** Returns a BigDecimal whose value is the negation of this BigDecimal + */ + def unary_- : BigDecimal = new BigDecimal(this.bigDecimal.negate()) + + /** Returns the absolute value of this BigDecimal + */ + def abs: BigDecimal = new BigDecimal(this.bigDecimal.abs()) + + /** Returns the sign of this BigDecimal, i.e. + * -1 if it is less than 0, + * +1 if it is greater than 0 + * 0 if it is equal to 0 + */ + def signum: Int = this.bigDecimal.signum() + + /** Returns the scale of this BigDecimal. + */ + def scale: Int = this.bigDecimal.scale() + + /** Returns a BigDecimal whose scale is the specified value, and whose value is + * numerically equal to this BigDecimal's. + */ + def setScale(scale: Int): BigDecimal = + new BigDecimal(this.bigDecimal setScale scale) + + def setScale(scale: Int, mode: RoundingMode): BigDecimal = + new BigDecimal(this.bigDecimal.setScale(scale, mode.id)) + + /** Converts this BigDecimal to a byte. + * If the BigDecimal is too big to fit in a byte, only the low-order 8 bits are returned. + * Note that this conversion can lose information about the overall magnitude of the + * BigDecimal value as well as return a result with the opposite sign. + */ + override def byteValue = intValue.toByte + + /** Converts this BigDecimal to a short. + * If the BigDecimal is too big to fit in a byte, only the low-order 16 bits are returned. + * Note that this conversion can lose information about the overall magnitude of the + * BigDecimal value as well as return a result with the opposite sign. + */ + override def shortValue = intValue.toShort + + /** Converts this BigDecimal to a char. + * If the BigDecimal is too big to fit in a char, only the low-order 16 bits are returned. + * Note that this conversion can lose information about the overall magnitude of the + * BigDecimal value and that it always returns a positive result. + */ + def charValue = intValue.toChar + + /** Converts this BigDecimal to an int. + * If the BigDecimal is too big to fit in a char, only the low-order 32 bits + * are returned. Note that this conversion can lose information about the + * overall magnitude of the BigDecimal value as well as return a result with + * the opposite sign. + */ + def intValue = this.bigDecimal.intValue + + /** Converts this BigDecimal to a Long. + * If the BigDecimal is too big to fit in a char, only the low-order 64 bits + * are returned. Note that this conversion can lose information about the + * overall magnitude of the BigDecimal value as well as return a result with + * the opposite sign. + */ + def longValue = this.bigDecimal.longValue + + /** Converts this BigDecimal to a float. + * if this BigDecimal has too great a magnitude to represent as a float, + * it will be converted to Float.NEGATIVE_INFINITY or + * Float.POSITIVE_INFINITY as appropriate. + */ + def floatValue = this.bigDecimal.floatValue + + /** Converts this BigDecimal to a Double. + * if this BigDecimal has too great a magnitude to represent as a float, + * it will be converted to Float.NEGATIVE_INFINITY or + * Float.POSITIVE_INFINITY as appropriate. + */ + def doubleValue = this.bigDecimal.doubleValue + + /** Converts this BigDecimal to a BigInteger. + */ + def toBigInt(): BigInt = new BigInt(this.bigDecimal.toBigInteger()) + + /** Returns the decimal String representation of this BigDecimal. + */ + override def toString(): String = this.bigDecimal.toString() + +} diff --git a/src/library/scala/BigInt.scala b/src/library/scala/BigInt.scala new file mode 100644 index 0000000000..a24d141aec --- /dev/null +++ b/src/library/scala/BigInt.scala @@ -0,0 +1,365 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +package scala + +import java.math.BigInteger + +/** + * @author Martin Odersky + * @version 1.0, 15/07/2003 + */ +object BigInt { + + private val minCached = -1024 + private val maxCached = 1024 + private val cache = new Array[BigInt](maxCached - minCached + 1) + + /** Constructs a BigInt whose value is equal to that of the + * specified integer value. + * + * @param i the specified integer value + * @return the constructed BigInt + */ + def apply(i: Int): BigInt = + if (minCached <= i && i <= maxCached) { + val offset = i - minCached + var n = cache(offset) + if (n eq null) { n = new BigInt(BigInteger.valueOf(i)); cache(offset) = n } + n + } else new BigInt(BigInteger.valueOf(i)) + + /** Constructs a BigInt whose value is equal to that of the + * specified long value. + * + * @param l the specified long value + * @return the constructed BigInt + */ + def apply(l: Long): BigInt = + if (minCached <= l && l <= maxCached) apply(l.toInt) + else new BigInt(BigInteger.valueOf(l)) + + /** Translates a byte array containing the two's-complement binary + * representation of a BigInt into a BigInt. + */ + def apply(x: Array[Byte]): BigInt = + new BigInt(new BigInteger(x)) + + /** Translates the sign-magnitude representation of a BigInt into a BigInt. + */ + def apply(signum: Int, magnitude: Array[Byte]): BigInt = + new BigInt(new BigInteger(signum, magnitude)) + + /** Constructs a randomly generated positive BigInt that is probably prime, + * with the specified bitLength. + */ + def apply(bitlength: Int, certaInty: Int, rnd: Random): BigInt = + new BigInt(new BigInteger(bitlength, certaInty, rnd.self)) + + /** Constructs a randomly generated BigInt, uniformly distributed over the + * range 0 to (2 ^ numBits - 1), inclusive. + * + * @param numbits ... + * @param rnd ... + * @return ... + */ + def apply(numbits: Int, rnd: Random): BigInt = + new BigInt(new BigInteger(numbits, rnd.self)) + + /** Translates the decimal String representation of a BigInt into a BigInt. + */ + def apply(x: String): BigInt = + new BigInt(new BigInteger(x)) + + /** Translates the string representation of a BigInt in the + * specified radix into a BigInt. + * + * @param x ... + * @param radix ... + * @return ... + */ + def apply(x: String, radix: Int): BigInt = + new BigInt(new BigInteger(x, radix)) + + /** Returns a positive BigInt that is probably prime, with the specified bitLength. + */ + def probablePrime(bitLength: Int, rnd: Random): BigInt = + new BigInt(BigInteger.probablePrime(bitLength, rnd.self)) + + /** Implicit conversion from int to BigInt. + */ + implicit def int2bigInt(i: Int): BigInt = apply(i) + + /** Implicit copnversion from long to BigInt + */ + implicit def long2bigInt(l: Long): BigInt = apply(l) + + /** Implicit conversion from BigInt to Ordered. + */ + implicit def bigInt2ordered(x: BigInt): Ordered[BigInt] = new Ordered[BigInt] with Proxy { + def self: Any = x; + def compare (y: BigInt): Int = x.bigInteger.compareTo(y.bigInteger) + } +} + +/** + * @author Martin Odersky + * @version 1.0, 15/07/2003 + */ +@serializable +class BigInt(val bigInteger: BigInteger) extends java.lang.Number { + + /** Returns the hash code for this BigInt. */ + override def hashCode(): Int = this.bigInteger.hashCode() + + /** Compares this BigInt with the specified value for equality. + */ + override def equals (that: Any): Boolean = that match { + case that: BigInt => this equals that + case that: java.lang.Double => this.bigInteger.doubleValue == that.doubleValue + case that: java.lang.Float => this.bigInteger.floatValue == that.floatValue + case that: java.lang.Number => this equals BigInt(that.longValue) + case that: java.lang.Character => this equals BigInt(that.charValue.asInstanceOf[Int]) + case _ => false + } + + /** Compares this BigInt with the specified BigInt for equality. + */ + def equals (that: BigInt): Boolean = + this.bigInteger.compareTo(that.bigInteger) == 0 + + /** Compares this BigInt with the specified BigInt + */ + def compare (that: BigInt): Int = this.bigInteger.compareTo(that.bigInteger) + + /** Less-than-or-equals comparison of BigInts + */ + def <= (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) <= 0 + + /** Greater-than-or-equals comparison of BigInts + */ + def >= (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) >= 0 + + /** Less-than of BigInts + */ + def < (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) < 0 + + /** Greater-than comparison of BigInts + */ + def > (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) > 0 + + /** Addition of BigInts + */ + def + (that: BigInt): BigInt = new BigInt(this.bigInteger.add(that.bigInteger)) + + /** Subtraction of BigInts + */ + def - (that: BigInt): BigInt = new BigInt(this.bigInteger.subtract(that.bigInteger)) + + /** Multiplication of BigInts + */ + def * (that: BigInt): BigInt = new BigInt(this.bigInteger.multiply(that.bigInteger)) + + /** Division of BigInts + */ + def / (that: BigInt): BigInt = new BigInt(this.bigInteger.divide(that.bigInteger)) + + /** Remainder of BigInts + */ + def % (that: BigInt): BigInt = new BigInt(this.bigInteger.remainder(that.bigInteger)) + + /** Returns a pair of two BigInts containing (this / that) and (this % that). + */ + def /% (that: BigInt): (BigInt, BigInt) = { + val dr = this.bigInteger.divideAndRemainder(that.bigInteger) + (new BigInt(dr(0)), new BigInt(dr(1))) + } + + /** Leftshift of BigInt + */ + def << (n: Int): BigInt = new BigInt(this.bigInteger.shiftLeft(n)) + + /** (Signed) rightshift of BigInt + */ + def >> (n: Int): BigInt = new BigInt(this.bigInteger.shiftRight(n)) + + /** Bitwise and of BigInts + */ + def & (that: BigInt): BigInt = new BigInt(this.bigInteger.and(that.bigInteger)) + + /** Bitwise or of BigInts + */ + def | (that: BigInt): BigInt = new BigInt(this.bigInteger.or (that.bigInteger)) + + /** Bitwise exclusive-or of BigInts + */ + def ^ (that: BigInt): BigInt = new BigInt(this.bigInteger.xor(that.bigInteger)) + + /** Bitwise and-not of BigInts. Returns a BigInt whose value is (this & ~that). + */ + def &~ (that: BigInt): BigInt = new BigInt(this.bigInteger.andNot(that.bigInteger)) + + /** Returns the greatest common divisor of abs(this) and abs(that) + */ + def gcd (that: BigInt): BigInt = new BigInt(this.bigInteger.gcd(that.bigInteger)) + + /** Returns a BigInt whose value is (this mod m). + * This method differs from `%' in that it always returns a non-negative BigInt. + */ + def mod (that: BigInt): BigInt = new BigInt(this.bigInteger.mod(that.bigInteger)) + + /** Returns the minimum of this and that + */ + def min (that: BigInt): BigInt = new BigInt(this.bigInteger.min(that.bigInteger)) + + /** Returns the maximum of this and that + */ + def max (that: BigInt): BigInt = new BigInt(this.bigInteger.max(that.bigInteger)) + + /** Returns a BigInt whose value is (this raised to the power of exp). + */ + def pow (exp: Int): BigInt = new BigInt(this.bigInteger.pow(exp)) + + /** Returns a BigInt whose value is + * (this raised to the power of exp modulo m). + */ + def modPow (exp: BigInt, m: BigInt): BigInt = + new BigInt(this.bigInteger.modPow(exp.bigInteger, m.bigInteger)) + + /** Returns a BigInt whose value is (the inverse of this modulo m). + */ + def modInverse (m: BigInt): BigInt = new BigInt(this.bigInteger.modInverse(m.bigInteger)) + + /** Returns a BigInt whose value is the negation of this BigInt + */ + def unary_- : BigInt = new BigInt(this.bigInteger.negate()) + + /** Returns the absolute value of this BigInt + */ + def abs: BigInt = new BigInt(this.bigInteger.abs()) + + /** Returns the sign of this BigInt, i.e. + * -1 if it is less than 0, + * +1 if it is greater than 0 + * 0 if it is equal to 0 + */ + def signum: Int = this.bigInteger.signum() + + /** Returns the bitwise complement of this BigNum + */ + def ~ : BigInt = new BigInt(this.bigInteger.not()) + + /** Returns true if and only if the designated bit is set. + */ + def testBit (n: Int): Boolean = this.bigInteger.testBit(n) + + /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit set. + */ + def setBit (n: Int): BigInt = new BigInt(this.bigInteger.setBit(n)) + + /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit cleared. + */ + def clearBit(n: Int): BigInt = new BigInt(this.bigInteger.clearBit(n)) + + /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit flipped. + */ + def flipBit (n: Int): BigInt = new BigInt(this.bigInteger.flipBit(n)) + + /** Returns the index of the rightmost (lowest-order) one bit in this BigInt + * (the number of zero bits to the right of the rightmost one bit). + */ + def lowestSetBit: Int = this.bigInteger.getLowestSetBit() + + /** Returns the number of bits in the minimal two's-complement representation of this BigInt, + * excluding a sign bit. + */ + def bitLength: Int = this.bigInteger.bitLength() + + /** Returns the number of bits in the two's complement representation of this BigInt + * that differ from its sign bit. + */ + def bitCount: Int = this.bigInteger.bitCount() + + /** Returns true if this BigInt is probably prime, false if it's definitely composite. + * @param certainty a measure of the uncertainty that the caller is willing to tolerate: + * if the call returns true the probability that this BigInt is prime + * exceeds (1 - 1/2 ^ certainty). + * The execution time of this method is proportional to the value of + * this parameter. + */ + def isProbablePrime(certainty: Int) = this.bigInteger.isProbablePrime(certainty) + + /** Converts this BigInt to a byte. + * If the BigInt is too big to fit in a byte, only the low-order 8 bits are returned. + * Note that this conversion can lose information about the overall magnitude of the + * BigInt value as well as return a result with the opposite sign. + */ + override def byteValue = intValue.toByte + + /** Converts this BigInt to a short. + * If the BigInt is too big to fit in a byte, only the low-order 16 bits are returned. + * Note that this conversion can lose information about the overall magnitude of the + * BigInt value as well as return a result with the opposite sign. + */ + override def shortValue = intValue.toShort + + /** Converts this BigInt to a char. + * If the BigInt is too big to fit in a char, only the low-order 16 bits are returned. + * Note that this conversion can lose information about the overall magnitude of the + * BigInt value and that it always returns a positive result. + */ + def charValue = intValue.toChar + + /** Converts this BigInt to an int. + * If the BigInt is too big to fit in a char, only the low-order 32 bits + * are returned. Note that this conversion can lose information about the + * overall magnitude of the BigInt value as well as return a result with + * the opposite sign. + */ + def intValue = this.bigInteger.intValue + + /** Converts this BigInt to a long. + * If the BigInt is too big to fit in a char, only the low-order 64 bits + * are returned. Note that this conversion can lose information about the + * overall magnitude of the BigInt value as well as return a result with + * the opposite sign. + */ + def longValue = this.bigInteger.longValue + + /** Converts this BigInt to a float. + * if this BigInt has too great a magnitude to represent as a float, + * it will be converted to Float.NEGATIVE_INFINITY or + * Float.POSITIVE_INFINITY as appropriate. + */ + def floatValue = this.bigInteger.floatValue + + /** Converts this BigInt to a double. + * if this BigInt has too great a magnitude to represent as a float, + * it will be converted to Float.NEGATIVE_INFINITY or + * Float.POSITIVE_INFINITY as appropriate. + */ + def doubleValue = this.bigInteger.doubleValue + + /** Returns the decimal String representation of this BigInt. + */ + override def toString(): String = this.bigInteger.toString() + + /** Returns the String representation in the specified radix of this BigInt. + */ + def toString(radix: Int): String = this.bigInteger.toString(radix) + + /** Returns a byte array containing the two's-complement representation of + * this BigInt. The byte array will be in big-endian byte-order: the most + * significant byte is in the zeroth element. The array will contain the + * minimum number of bytes required to represent this BigInt, including at + * least one sign bit. + */ + def toByteArray: Array[Byte] = this.bigInteger.toByteArray() +} diff --git a/src/library/scala/CharSequence.scala b/src/library/scala/CharSequence.scala new file mode 100644 index 0000000000..651650471c --- /dev/null +++ b/src/library/scala/CharSequence.scala @@ -0,0 +1,172 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id: + + +package scala + +import java.io._ +import collection._ +import util.matching.Regex + +/** A Scala abstraction of character sequences, similar to, but richer than, + * java.lang.CharSequence. Sequences can be fixed or lazy. A lazy + * character sequence may be constructed only while it is read. + * + * @author Martin Odersky + */ +trait CharSequence extends java.lang.CharSequence with Seq[Char] { + + /** The length of the character sequence + * Note: if char sequence is lazy, calling this method + * will force sequence to be read until the end. + */ + def length: Int + + /** The character at position `index'. + */ + def charAt(index: Int): Char + + /** Is character sequence defined at `index'? + * Unlike `length' this operation does not force reading + * a lazy sequence to the end. + * (the implementation of that method is inherited from Seq). + */ + def isDefinedAt(index: Int): Boolean + + /** Optionally the character at position `index'. None is not in range. + */ + def get(index: Int): Option[Char] = + if (isDefinedAt(index)) Some(charAt(index)) + else None + + /** The character at position `index'. (same as `charAt') + */ + def apply(index: Int): Char = charAt(index) + + /** the subsequence from index `start' up to and excluding + * the minimum of index `end' and the length of current sequence. + */ + def subSequence(start: Int, end: Int): CharSequence + + /** The subsequence from index `start' until the end of the current sequence + * If sequence is lazy, this operation does not force reading to the end. + */ + def subSequence(start: Int): CharSequence = + subSequence(start, length) + + /** Convert sequence to string */ + def toString: String + + /** the elements of this sequence */ + def elements: Iterator[Char] = new Iterator[Char] { + private var index = 0 + def hasNext: Boolean = isDefinedAt(index) + def next: Char = { + val ch = charAt(index) + index += 1 + ch + } + } + + /** Return all matches of given regexp in this character sequence as an iterator + */ + def findAll(regex: Regex): Regex.MatchIterator = regex findAllIn this + + /** Return first match of given regexp in this character sequence as an optional value + */ + def findFirst(regex: Regex): Option[String] = regex findFirstIn this + + /** Return first match of given regexp in this character sequence as an optional value + */ + def findFirstMatch(regex: Regex): Option[Regex.Match] = regex findFirstMatchIn this + + /** Return optionally string matching given regexp at the beginning of this + * character sequence, or None if regexp matches no prefix + * of the character sequence. + */ + def findPrefix(regex: Regex): Option[String] = regex findPrefixOf this + + /** Return optionally match for given regexp at the beginning of this + * character sequence, or None if regexp matches no prefix + * of the character sequence. + */ + def findPrefixMatch(regex: Regex): Option[Regex.Match] = regex findPrefixMatchOf this + + /** Replaces all matches of given regexp by a string. + * + * @param regex The regex to match with + * @param replacement The string that will replace each match + * @return The resulting string + */ + def replaceAll(regex: Regex, replacement: String): String = regex replaceAllIn (this, replacement) + + /** Replaces the first match of given regexp by a string. + * + * @param target The string to match + * @param replacement The string that will replace the match + * @return The resulting string + */ + def replaceFirst(regex: Regex, replacement: String): String = regex replaceFirstIn (this, replacement) + + def toArray: Array[Char] = { + val len = length + val result = new Array[Char](len) + var i = 0 + while (i < len) { + result(i) = charAt(i) + i += 1 + } + result + } +} + +/** The CharSequence object defines variance implementations of character sequences + */ +object CharSequence { + + def fromJava(source: java.lang.CharSequence): CharSequence = + new JavaWrapper(source) + + def fromArray(source: Array[Char]): CharSequence = + new AsArray(source, 0, source.length) + def fromArray(source: Array[Char], start: Int): CharSequence = + new AsArray(source, start, source.length) + def fromArray(source: Array[Char], start: Int, end: Int): CharSequence = + new AsArray(source, start, end) + + private class JavaWrapper(source: java.lang.CharSequence) extends CharSequence { + def length: Int = source.length + def charAt(index: Int): Char = source.charAt(index) + def subSequence(start: Int, end: Int): CharSequence = new JavaWrapper(source.subSequence(start, end)) + override def toString: String = source.toString + } + + private class AsArray(source: scala.Array[Char], start: Int, end: Int) extends CharSequence { + if (start < 0) throw new IndexOutOfBoundsException + if (end > source.length) throw new IndexOutOfBoundsException + + def charAt(index: Int) = + if (start + index < end) source(index + start) + else throw new IndexOutOfBoundsException + + def length: Int = if (end < start) 0 else end - start + + def subSequence(_start: Int, _end: Int) = + new AsArray(source, start + _start, start + _end) + + override def toArray: Array[Char] = { + val result = new Array[Char](length) + compat.Platform.arraycopy(source, start, result, 0, length) + result + } + + override def toString = new String(source, start, end - start) + } +} diff --git a/src/library/scala/ClassfileAnnotation.scala b/src/library/scala/ClassfileAnnotation.scala new file mode 100644 index 0000000000..d5577a4523 --- /dev/null +++ b/src/library/scala/ClassfileAnnotation.scala @@ -0,0 +1,23 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +/**

+ * A base class for classfile annotations. These are stored as + * Java annotations in classfiles. + *

+ * + * @author Martin Odersky + * @version 1.1, 2/02/2007 + */ +trait ClassfileAnnotation extends Annotation diff --git a/src/library/scala/ClassfileAttribute.scala b/src/library/scala/ClassfileAttribute.scala new file mode 100644 index 0000000000..23d48409b9 --- /dev/null +++ b/src/library/scala/ClassfileAttribute.scala @@ -0,0 +1,26 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +/**

+ * A base class for classfile attributes. These are stored as + * Java annotations in classfiles. + *

+ * + * @deprecated use ClassfileAnnotation instead + * @author Martin Odersky + * @version 1.1, 2/02/2007 + */ +@deprecated +trait ClassfileAttribute extends Attribute {} diff --git a/src/library/scala/Console.scala b/src/library/scala/Console.scala new file mode 100644 index 0000000000..fe29150caa --- /dev/null +++ b/src/library/scala/Console.scala @@ -0,0 +1,345 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import java.io.{BufferedReader, InputStream, InputStreamReader, + OutputStream, PrintStream, Reader} +import java.text.MessageFormat + +import scala.util.DynamicVariable +import Predef._ + + +/** The Console object implements functionality for + * printing Scala values on the terminal. There are also functions + * for reading specific values. Console also defines + * constants for marking up text on ANSI terminals. + * + * @author Matthias Zenger + * @version 1.0, 03/09/2003 + */ +object Console { + + // ANSI colors foreground + final val BLACK = "\033[30m" + final val RED = "\033[31m" + final val GREEN = "\033[32m" + final val YELLOW = "\033[33m" + final val BLUE = "\033[34m" + final val MAGENTA = "\033[35m" + final val CYAN = "\033[36m" + final val WHITE = "\033[37m" + + // ANSI colors background + final val BLACK_B = "\033[40m" + final val RED_B = "\033[41m" + final val GREEN_B = "\033[42m" + final val YELLOW_B = "\033[43m" + final val BLUE_B = "\033[44m" + final val MAGENTA_B = "\033[45m" + final val CYAN_B = "\033[46m" + final val WHITE_B = "\033[47m" + + // ANSI styles + final val RESET = "\033[0m" + final val BOLD = "\033[1m" + final val UNDERLINED = "\033[4m" + final val BLINK = "\033[5m" + final val REVERSED = "\033[7m" + final val INVISIBLE = "\033[8m" + + private val outVar = new DynamicVariable[PrintStream](java.lang.System.out) + private val inVar = new DynamicVariable[BufferedReader]( + new BufferedReader(new InputStreamReader(java.lang.System.in))) + + def out = outVar.value + def in = inVar.value + + val err = java.lang.System.err + + /** Set the default output stream. + * + * @param out the new output stream. + */ + def setOut(out: PrintStream) { outVar.value = out } + + /** Set the default output stream for the duration + * of execution of one thunk. + * + * @param out the new output stream. + * @param thunk the code to execute with + * the new output stream active + * @return ... + */ + def withOut[T](out: PrintStream)(thunk: =>T): T = + outVar.withValue(out)(thunk) + + /** Set the default output stream. + * + * @param@ out the new output stream. + */ + def setOut(out: OutputStream): Unit = + setOut(new PrintStream(out)) + + /** Set the default output stream for the duration + * of execution of one thunk. + * + * @param out the new output stream. + * @param thunk the code to execute with + * the new output stream active + * @return ... + */ + def withOut[T](out: OutputStream)(thunk: =>T): T = + withOut(new PrintStream(out))(thunk) + + + /** Set the default input stream. + * + * @param reader specifies the new input stream. + */ + def setIn(reader: Reader): Unit = { + inVar.value = new BufferedReader(reader) + } + + /** Set the default input stream for the duration + * of execution of one thunk. + * + * @param in the new input stream. + * @param thunk the code to execute with + * the new input stream active + */ + def withIn[T](reader: Reader)(thunk: =>T): T = + inVar.withValue(new BufferedReader(reader))(thunk) + + + /** Set the default input stream. + * + * @param in the new input stream. + */ + def setIn(in: InputStream): Unit = + setIn(new InputStreamReader(in)) + + /** Set the default input stream for the duration + * of execution of one thunk. + * + * @param in the new input stream. + * @param thunk the code to execute with + * the new input stream active + */ + def withIn[T](in: InputStream)(thunk: =>T): T = + withIn(new InputStreamReader(in))(thunk) + + /** Print an object on the terminal. + * + * @param obj the object to print. + */ + def print(obj: Any): Unit = + out.print(if (null == obj) "null" else obj.toString()) + + /** Flush the output stream. This function is required when partial + * output (i.e. output not terminated by a new line character) has + * to be made visible on the terminal. + */ + def flush() { out.flush() } + + /** Print a new line character on the terminal. + */ + def println(): Unit = out.println() + + /** Print out an object followed by a new line character. + * + * @param x the object to print. + */ + def println(x: Any): Unit = out.println(x) + + /**

+ * Prints its arguments as a formatted string, based on a string + * pattern (in a fashion similar to printf in C). + *

+ *

+ * The interpretation of the formatting patterns is described in + * + * java.text.MessageFormat. + *

+ * + * @param text the pattern for formatting the arguments. + * @param args the arguments used to instantiating the pattern. + * @throws java.lang.IllegalArgumentException + */ + def printf(text: String, args: Any*) { format(text, args: _*) } + + /** + * @see Console.printf. + */ + def format(text: String, args: Any*): Unit = + out.print( + if (text eq null) "null" + else MessageFormat.format(text, textParams(args)) + ) + + /** Read a full line from the terminal. + * + * @return the string read from the terminal. + */ + def readLine(): String = in.readLine() + + /** Print a formatted text and read a full line from the terminal + * + * @param text the format of the text to print out. + * @param args the parameters used to instantiate the format. + * @return the string read from the terminal. + */ + def readLine(text: String, args: Any*): String = { + format(text, args: _*) + readLine() + } + + + /** Read a boolean value from the terminal. + * + * @return the boolean value read from the terminal. + */ + def readBoolean(): Boolean = readLine().toLowerCase() match { + case "true" => true + case "t" => true + case "yes" => true + case "y" => true + case _ => false + } + + /** Read a byte value from the terminal. + */ + def readByte(): Byte = readLine().toByte + + /** Read a short value from the terminal. + */ + def readShort(): Short = readLine().toShort + + /** Read a char value from the terminal. + */ + def readChar(): Char = readLine() charAt 0 + + /** Read an int value from the terminal. + */ + def readInt(): Int = readLine().toInt + + /** Read an int value from the terminal. + */ + def readLong(): Long = readLine().toLong + + /** Read a float value from the terminal. + */ + def readFloat(): Float = readLine().toFloat + + /** Read a double value from the terminal. + */ + def readDouble(): Double = readLine().toDouble + + /** Read in some structured input, specified by a format specifier. + * See class java.text.MessageFormat for details of + * the format specification. + * + * @param format the format of the input. + * @return a list of all extracted values. + */ + def readf(format: String): List[Any] = + textComponents(new MessageFormat(format).parse(readLine())) + + /** Read in some structured input, specified by a format specifier. + * Opposed to readf, this function only returns the + * first value extracted from the input according to the format + * specification. + * + * @param format ... + * @return ... + */ + def readf1(format: String): Any = readf(format).head + + /** Read in some structured input, specified by a format specifier. + * Opposed to readf, this function only returns the + * first two values extracted from the input according to the format + * specification. + * + * @param format ... + * @return ... + */ + def readf2(format: String): (Any, Any) = { + val res = readf(format) + (res.head, res.tail.head) + } + + /** Read in some structured input, specified by a format specifier. + * Opposed to readf, this function only returns the + * first three values extracted from the input according to the format + * specification. + * + * @param format ... + * @return ... + */ + def readf3(format: String): (Any, Any, Any) = { + val res = readf(format) + (res.head, res.tail.head, res.tail.tail.head) + } + + private def textComponents(a: Array[AnyRef]): List[Any] = { + var i: Int = a.length - 1 + var res: List[Any] = Nil + while (i >= 0) { + res = (a(i) match { + case x: java.lang.Boolean => x.booleanValue() + case x: java.lang.Byte => x.byteValue() + case x: java.lang.Short => x.shortValue() + case x: java.lang.Character => x.charValue() + case x: java.lang.Integer => x.intValue() + case x: java.lang.Long => x.longValue() + case x: java.lang.Float => x.floatValue() + case x: java.lang.Double => x.doubleValue() + case x => x + }) :: res; + i -= 1 + } + res + } + + private def textParams(s: Seq[Any]): Array[AnyRef] = { + val res = new Array[AnyRef](s.length) + var i: Int = 0 + val iter = s.elements + while (iter.hasNext) { + res(i) = iter.next match { + case x: Boolean => java.lang.Boolean.valueOf(x) + /** Should use java.lang.Byte.valueOf(Byte), but only available + * in Java 1.5 and above. */ + case x: Byte => new java.lang.Byte(x) + /** Should use java.lang.Short.valueOf(Short), but only available + * in Java 1.5 and above. */ + case x: Short => new java.lang.Short(x) + /** Should use java.lang.Character.valueOf(Char), but only available + * in Java 1.5 and above. */ + case x: Char => new java.lang.Character(x) + /** Should use java.lang.Integer.valueOf(Int), but only available + * in Java 1.5 and above. */ + case x: Int => new java.lang.Integer(x) + /** Should use java.lang.Long.valueOf(Long), but only available + * in Java 1.5 and above. */ + case x: Long => new java.lang.Long(x) + case x: Float => new java.lang.Float(x) + case x: Double => new java.lang.Double(x) + case x: Unit => "()" + case x: AnyRef => x + } + i += 1 + } + res + } +} diff --git a/src/library/scala/LazyCharSequence.scala b/src/library/scala/LazyCharSequence.scala new file mode 100644 index 0000000000..bde51f8bd1 --- /dev/null +++ b/src/library/scala/LazyCharSequence.scala @@ -0,0 +1,265 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import java.io._ +import util.matching.Regex + + +/** The CharSequence object defines variance implementations of character sequences + */ +object LazyCharSequence { + final val UndeterminedEnd = Math.MAX_INT + + /** Constructs a character sequence from a character iterator */ + def fromChars(source: Iterator[Char]): CharSequence = + new LazyCharSequence ((chars: Array[Char], start: Int, len: Int) => { + var i = 0 + while (i < len && source.hasNext) { + chars(start + i) = source.next + i += 1 + } + if (i == 0) -1 else i + }) + + /** Constructs a character sequence from a character iterable */ + def fromChars(source: Iterable[Char]): CharSequence = + fromChars(source.elements) + + /** Constructs a character sequence from a string iterator */ + def fromStrings(source: Iterator[String]): CharSequence = { + var current: String = "" + def more(chars: Array[Char], start: Int, len: Int): Int = + if (current.length != 0) { + val nchars = current.length min len + current.getChars(0, nchars, chars, start) + current = current.substring(nchars) + if (nchars == len) nchars + else (more(chars, start + nchars, len - nchars) max 0) + nchars + } else if (source.hasNext) { + current = source.next + more(chars, start, len) + } else -1 + new LazyCharSequence(more(_: Array[Char], _: Int, _: Int)) + } + + /** Constructs a character sequence from a string iterable */ + def fromStrings(source: Iterable[String]): CharSequence = + fromStrings(source.elements) + + /** Constructs a character sequence from a line iterator + * Lines do not contain trailing `\n' characters; The method inserts + * a line separator `\n' between any two lines in the sequence. + */ + def fromLines(source: Iterator[String]): CharSequence = { + var isFirst = true + fromStrings(source map { line => + if (isFirst) line + else { + isFirst = false + "\n"+line + } + }) + } + + /** Constructs a character sequence from a line iterable + * Lines do not contain trailing `\n' characters; The method inserts + * a line separator `\n' between any two lines in the sequence. + */ + def fromLines(source: Iterable[String]): CharSequence = + fromLines(source.elements) + + /** Constructs a character sequence from an input reader + */ + def fromReader(source: Reader): CharSequence = + new LazyCharSequence(source) + + /** Constructs a character sequence from an input file + */ + def fromFile(source: File) = + new LazyCharSequence(source) + + /** Constructs a character sequence from a file with given name + */ + def fromFile(source: String) = + new LazyCharSequence(source) + + /** Constructs a character sequence from a scala.io.Source value + */ + def fromSource(source: io.Source) = + fromLines(source.getLines) +} + + +import LazyCharSequence._ + +/** An implementation of lazily computed character sequences + * + * @author Martin Odersky + */ +class LazyCharSequence protected (more: (Array[Char], Int, Int) => Int, + first: Page, start: Int, end: Int) extends CharSequence { + + /** Constructs a character sequence from a method that produces more characters when asked. + * The producer method is analogous to the read method in java.io.Reader. + * It takes three parameters: an array of characters, a start index, and an end index. + * It should try to fill the array between start and end indices (not including end index). + * It returns the number of characters produced, or -1 if end of logical input stream was reached + * before any character was read. + */ + def this(more: (Array[Char], Int, Int) => Int) = this(more, new Page(0), 0, UndeterminedEnd) + + /** Constructs a character sequence from an input reader + */ + def this(source: Reader) = + this(source.read(_: Array[Char], _: Int, _: Int)) + + /** Constructs a character sequence from an input file + */ + def this(source: File) = + this(new FileReader(source)) + + /** Constructs a character sequence from a file with given name + */ + def this(source: String) = + this(new File(source)) + + private var current: Page = first + + private def latest = first.latest + + private def addMore() = latest.addMore(more) + + private def page(absindex: Int) = { + if (absindex < current.start) + current = first + while (absindex >= current.end && current.next != null) + current = current.next + while (absindex >= current.end && !current.isLast) { + current = addMore() + } + current + } + + /** The length of the character sequence + * Note: calling this method will force sequence to be read until the end. + */ + def length: Int = { + while (!latest.isLast) addMore() + (latest.end min end) - start + } + + /** The character at position `index'. + */ + def charAt(index: Int) = + if (isDefinedAt(index)) page(index + start)(index + start) + else throw new IndexOutOfBoundsException(index.toString) + + /** Is character sequence defined at `index'? + * Unlike `length' this operation does not force reading + * a lazy sequence to the end. + */ + override def isDefinedAt(index: Int) = + index >= 0 && index < end - start && { + val p = page(index + start); index + start < p.end + } + + /** Optionally the character at position `index'. None is not in range. + */ + override def get(index: Int) = + if (isDefinedAt(index)) Some(page(index + start)(index + start)) + else None + + /** the subsequence from index `start' up to and excluding + * the minimum of index `end' and the length of current sequence. + */ + def subSequence(_start: Int, _end: Int) = { + page(start) + val s = start + _start + val e = if (_end == UndeterminedEnd) _end else start + _end + var f = first + while (f.end <= s && !f.isLast) f = f.next + new LazyCharSequence(more, f, s, e) + } + + /** The subsequence from index `start' until the end of the current sequence + * This operation does not force reading to the end. + */ + override def subSequence(start: Int): CharSequence = + subSequence(start, UndeterminedEnd) + + /** Convert sequence to string */ + override def toString = { + val buf = new StringBuilder + for (ch <- elements) buf append ch + buf.toString + } +} + + +/** Page containing up to PageSize characters of the input sequence. + */ +private class Page(val num: Int) { + + private final val PageSize = 4096 + + /** The next page in the sequence */ + var next : Page = null + + /** A later page in the sequence, serves a cachae for pointing to last page */ + var later : Page = this + + /** The number of characters read into this page */ + var filled: Int = 0 + + /** Is this page the permamnently last one in the sequence? Only true once `more' + * method has returned -1 to signal end of input. */ + var isLast: Boolean = false + + /** The character array */ + final val chars = new Array[Char](PageSize) + + /** The index of the first character in this page relative to the whole sequence */ + final def start = num * PageSize + + /** The index of the character following the last charcater in this page relative + * to the whole sequence */ + final def end = start + filled + + /** The currently last page in the sequence; might change as more charcaters are appended */ + final def latest: Page = { + if (later.next != null) later = later.next.latest + later + } + + /** The character at given sequence index. + * That index is relative to the whole sequence, not the page. */ + def apply(index: Int) = { + if (index < start || index - start >= filled) throw new IndexOutOfBoundsException(index.toString) + chars(index - start) + } + + /** produces more characters by calling `more' and appends them on the current page, + * or fills a subsequent page if current page is full + * pre: if current page is full, it is the last one in the sequence. + */ + final def addMore(more: (Array[Char], Int, Int) => Int): Page = + if (filled == PageSize) { + next = new Page(num + 1) + next.addMore(more) + } else { + val count = more(chars, filled, PageSize - filled) + if (count < 0) isLast = true + else filled += count + this + } +} diff --git a/src/library/scala/List.scala b/src/library/scala/List.scala new file mode 100644 index 0000000000..f87b034cde --- /dev/null +++ b/src/library/scala/List.scala @@ -0,0 +1,1339 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import scala.collection.mutable.ListBuffer +import Predef._ + +/** This object provides methods for creating specialized lists, and for + * transforming special kinds of lists (e.g. lists of lists). + * + * @author Martin Odersky and others + * @version 1.0, 15/07/2003 + */ +object List { + + /** Create a list with given elements. + * + * @param xs the elements to put in the list + * @return the list containing elements xs. + */ + def apply[A](xs: A*): List[A] = xs.toList + + /** for unapply matching + */ + def unapplySeq[A](x: List[A]): Some[List[A]] = Some(x) + + /** Create a sorted list of all integers in a range. + * + * @param from the start value of the list + * @param end the end value of the list + * @return the sorted list of all integers in range [from;end). + */ + def range(start: Int, end: Int): List[Int] = + range(start, end, 1) + + /** Create a list with element values + * vn+1 = vn + step + * where v0 = start + * and elements are in the range between start (inclusive) + * and end (exclusive) + * + * @param start the start value of the list + * @param end the end value of the list + * @param step the increment value of the list + * @return the sorted list of all integers in range [start;end). + */ + def range(start: Int, end: Int, step: Int): List[Int] = { + val b = new ListBuffer[Int] + var i = start + while ((step <= 0 || i < end) && (step >= 0 || i > end)) { + b += i + i += step + } + b.toList + } + + /** Create a sorted list with element values + * vn+1 = step(vn) + * where v0 = start + * and elements are in the range between start (inclusive) + * and end (exclusive) + * + * @param start the start value of the list + * @param end the end value of the list + * @param step the increment function of the list, must be monotonically increasing or decreasing + * @return the sorted list of all integers in range [start;end). + */ + def range(start: Int, end: Int, step: Int => Int): List[Int] = { + val up = step(start) > start + val down = step(start) < start + val b = new ListBuffer[Int] + var i = start + while ((!up || i < end) && (!down || i > end)) { + b += i + i += step(i) + } + b.toList + } + + /** Create a list containing several copies of an element. + * + * @param n the length of the resulting list + * @param elem the element composing the resulting list + * @return a list composed of n elements all equal to elem + */ + def make[A](n: Int, elem: A): List[A] = { + val b = new ListBuffer[A] + var i = 0 + while (i < n) { + b += elem + i += 1 + } + b.toList + } + + /** Create a list by applying a function to successive integers. + * + * @param n the length of the resulting list + * @param maker the procedure which, given an integer n, + * returns the nth element of the resulting list, where + * n is in interval [0;n). + * @return the list obtained by applying the maker function to + * successive integers from 0 to n (exclusive). + */ + def tabulate[A](n: Int, maker: Int => A): List[A] = { + val b = new ListBuffer[A] + var i = 0 + while (i < n) { + b += maker(i) + i += 1 + } + b.toList + } + + /** Concatenate all the elements of a given list of lists. + * + * @param xss the list of lists that are to be concatenated + * @return the concatenation of all the lists + */ + def flatten[A](xss: List[List[A]]): List[A] = concat(xss: _*) + + /** Concatenate all the argument lists into a single list. + * + * @param xss the lists that are to be concatenated + * @return the concatenation of all the lists + */ + def concat[A](xss: List[A]*): List[A] = { + val b = new ListBuffer[A] + for (xs <- xss) { + var xc = xs + while (!xc.isEmpty) { + b += xc.head + xc = xc.tail + } + } + b.toList + } + + /** Transforms a list of pair into a pair of lists. + * + * @param xs the list of pairs to unzip + * @return a pair of lists: the first list in the pair contains the list + */ + def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = { + val b1 = new ListBuffer[A] + val b2 = new ListBuffer[B] + var xc = xs + while (!xc.isEmpty) { + b1 += xc.head._1 + b2 += xc.head._2 + xc = xc.tail + } + (b1.toList, b2.toList) + } + + /** Converts an iterator to a list. + * + * @param it the iterator to convert + * @return a list that contains the elements returned by successive + * calls to it.next + */ + def fromIterator[A](it: Iterator[A]): List[A] = it.toList + + /** Converts an array into a list. + * + * @param arr the array to convert + * @return a list that contains the same elements than arr + * in the same order + */ + def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length) + + /** Converts a range of an array into a list. + * + * @param arr the array to convert + * @param start the first index to consider + * @param len the lenght of the range to convert + * @return a list that contains the same elements than arr + * in the same order + */ + def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = { + var res: List[A] = Nil + var i = start + len + while (i > start) { + i -= 1 + res = arr(i) :: res + } + res + } + + /** Parses a string which contains substrings separated by a + * separator character and returns a list of all substrings. + * + * @param str the string to parse + * @param separator the separator character + * @return the list of substrings + */ + def fromString(str: String, separator: Char): List[String] = { + var words: List[String] = Nil + var pos = str.length() + while (pos > 0) { + val pos1 = str.lastIndexOf(separator, pos - 1) + if (pos1 + 1 < pos) + words = str.substring(pos1 + 1, pos) :: words + pos = pos1 + } + words + } + + /** Returns the given string as a list of characters. + * + * @param str the string to convert. + * @return the string as a list of characters. + * @deprecated use str.toList instead + */ + @deprecated def fromString(str: String): List[Char] = + str.toList + + /** Returns the given list of characters as a string. + * + * @param xs the list to convert. + * @return the list in form of a string. + */ + def toString(xs: List[Char]): String = { + val sb = new StringBuilder() + var xc = xs + while (!xc.isEmpty) { + sb.append(xc.head) + xc = xc.tail + } + sb.toString() + } + + /** Like xs map f, but returns xs unchanged if function + * f maps all elements to themselves. + * + * @param xs ... + * @param f ... + * @return ... + */ + def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = { + def loop(ys: List[A]): List[A] = + if (ys.isEmpty) xs + else { + val head0 = ys.head + val head1 = f(head0) + if (head1 eq head0) { + loop(ys.tail) + } else { + val ys1 = head1 :: mapConserve(ys.tail)(f) + if (xs eq ys) ys1 + else { + val b = new ListBuffer[A] + var xc = xs + while (xc ne ys) { + b += xc.head + xc = xc.tail + } + b.prependToList(ys1) + } + } + } + loop(xs) + } + + /** Returns the list resulting from applying the given function f + * to corresponding elements of the argument lists. + * + * @param f function to apply to each pair of elements. + * @return [f(a0,b0), ..., f(an,bn)] if the lists are + * [a0, ..., ak], [b0, ..., bl] and + * n = min(k,l) + */ + def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = { + val b = new ListBuffer[C] + var xc = xs + var yc = ys + while (!xc.isEmpty && !yc.isEmpty) { + b += f(xc.head, yc.head) + xc = xc.tail + yc = yc.tail + } + b.toList + } + + /** Returns the list resulting from applying the given function + * f to corresponding elements of the argument lists. + * + * @param f function to apply to each pair of elements. + * @return [f(a0,b0,c0), + * ..., f(an,bn,cn)] + * if the lists are [a0, ..., ak], + * [b0, ..., bl], + * [c0, ..., cm] and + * n = min(k,l,m) + */ + def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = { + val b = new ListBuffer[D] + var xc = xs + var yc = ys + var zc = zs + while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) { + b += f(xc.head, yc.head, zc.head) + xc = xc.tail + yc = yc.tail + zc = zc.tail + } + b.toList + } + + /** Tests whether the given predicate p holds + * for all corresponding elements of the argument lists. + * + * @param p function to apply to each pair of elements. + * @return (p(a0,b0) && + * ... && p(an,bn))] + * if the lists are [a0, ..., ak]; + * [b0, ..., bl] + * and n = min(k,l) + */ + def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { + var xc = xs + var yc = ys + while (!xc.isEmpty && !yc.isEmpty) { + if (!f(xc.head, yc.head)) return false + xc = xc.tail + yc = yc.tail + } + true + } + + /** Tests whether the given predicate p holds + * for some corresponding elements of the argument lists. + * + * @param p function to apply to each pair of elements. + * @return n != 0 && (p(a0,b0) || + * ... || p(an,bn))] if the lists are + * [a0, ..., ak], + * [b0, ..., bl] and + * n = min(k,l) + */ + def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = { + var xc = xs + var yc = ys + while (!xc.isEmpty && !yc.isEmpty) { + if (f(xc.head, yc.head)) return true + xc = xc.tail + yc = yc.tail + } + false + } + + /** Transposes a list of lists. + * pre: All element lists have the same length. + * + * @param xss the list of lists + * @return the transposed list of lists + */ + def transpose[A](xss: List[List[A]]): List[List[A]] = { + val buf = new ListBuffer[List[A]] + var yss = xss + while (!yss.head.isEmpty) { + buf += (yss map (_.head)) + yss = (yss map (_.tail)) + } + buf.toList + } + + /** Lists with ordered elements are ordered + implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] { + def compare [b >: List[a] <% Ordered[b]](y: b): Int = y match { + case y1: List[a] => compareLists(x, y1); + case _ => -(y compare x) + } + private def compareLists(xs: List[a], ys: List[a]): Int = { + if (xs.isEmpty && ys.isEmpty) 0 + else if (xs.isEmpty) -1 + else if (ys.isEmpty) 1 + else { + val s = xs.head compare ys.head; + if (s != 0) s + else compareLists(xs.tail, ys.tail) + } + } + } + */ +} + +/** A class representing an ordered collection of elements of type + * a. This class comes with two implementing case + * classes scala.Nil and scala.:: that + * implement the abstract members isEmpty, + * head and tail. + * + * @author Martin Odersky and others + * @version 1.0, 16/07/2003 + */ +sealed abstract class List[+A] extends Seq[A] { + + /** Returns true if the list does not contain any elements. + * @return true, iff the list is empty. + */ + override def isEmpty: Boolean + + /** Returns this first element of the list. + * + * @return the first element of this list. + * @throws Predef.NoSuchElementException if the list is empty. + */ + def head: A + + /** returns length - l, without calling length + */ + override def lengthCompare(l: Int) = { + if (isEmpty) 0 - l + else if (l <= 0) 1 + else tail.lengthCompare(l - 1) + } + + /** Returns this list without its first element. + * + * @return this list without its first element. + * @throws Predef.NoSuchElementException if the list is empty. + */ + def tail: List[A] + + /**

+ * Add an element x at the beginning of this list. + *

+ * + * @param x the element to prepend. + * @return the list with x added at the beginning. + * @ex 1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3) + */ + def ::[B >: A] (x: B): List[B] = + new scala.::(x, this) + + /**

+ * Add an element x at the end of this list. + *

+ * + * @param x the element to append. + * @return the list with x added at the end. + */ + def +[B >: A](x: B): List[B] = + if (isEmpty) List(x) + else { + val buf = new ListBuffer[B] + this copyToBuffer buf + buf += x + buf.toList + } + + /**

+ * Returns a list resulting from the concatenation of the given + * list prefix and this list. + *

+ * + * @param prefix the list to concatenate at the beginning of this list. + * @return the concatenation of the two lists. + * @ex List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4) + */ + def :::[B >: A](prefix: List[B]): List[B] = + if (isEmpty) prefix + else { + val b = new ListBuffer[B] + var those = prefix + while (!those.isEmpty) { + b += those.head + those = those.tail + } + b.prependToList(this) + } + + /** Appends two list objects. + */ + override def ++[B >: A](that: Iterable[B]): List[B] = { + val buf = new ListBuffer[B] + this copyToBuffer buf + that copyToBuffer buf + buf.toList + } + + /** Reverse the given prefix and append the current list to that. + * This function is equivalent to an application of reverse + * on the prefix followed by a call to :::, but more + * efficient (and tail recursive). + * + * @param prefix the prefix to reverse and then prepend + * @return the concatenation of the reversed prefix and the current list. + */ + def reverse_:::[B >: A](prefix: List[B]): List[B] = { + var these: List[B] = this + var pres = prefix + while (!pres.isEmpty) { + these = pres.head :: these + pres = pres.tail + } + these + } + + /** Returns the number of elements in the list. + * + * @return the number of elements in the list. + */ + def length: Int = { + var these = this + var len = 0 + while (!these.isEmpty) { + len += 1 + these = these.tail + } + len + } + + /** Creates a list with all indices in the list. This is + * equivalent to a call to List.range(0, xs.length). + * + * @return a list of all indices in the list. + */ + def indices: List[Int] = { + val b = new ListBuffer[Int] + var i = 0 + var these = this + while (!these.isEmpty) { + b += i + i += 1 + these = these.tail + } + b.toList + } + + /** Returns the elements in the list as an iterator + * + * @return an iterator on the list elements. + */ + override def elements: Iterator[A] = new Iterator[A] { + var these = List.this + def hasNext: Boolean = !these.isEmpty + def next: A = + if (!hasNext) + throw new NoSuchElementException("next on empty Iterator") + else { + val result = these.head; these = these.tail; result + } + override def toList: List[A] = these + } + + /** Overrides the method in Iterable for efficiency. + * + * @return the list itself + */ + override def toList: List[A] = this + + /** Returns the list without its last element. + * + * @return the list without its last element. + * @throws Predef.UnsupportedOperationException if the list is empty. + */ + def init: List[A] = + if (isEmpty) throw new UnsupportedOperationException("Nil.init") + else { + val b = new ListBuffer[A] + var elem = head + var next = tail + while (!next.isEmpty) { + b += elem + elem = next.head + next = next.tail + } + b.toList + } + + /** Returns the last element of this list. + * + * @return the last element of the list. + * @throws Predef.NoSuchElementException if the list is empty. + */ + override def last: A = + if (isEmpty) throw new Predef.NoSuchElementException("Nil.last") + else { + var cur = this + var next = this.tail + while (!next.isEmpty) { + cur = next + next = next.tail + } + cur.head + } + + /** Returns the n first elements of this list, or else the whole + * list, if it has less than n elements. + * + * @param n the number of elements to take. + * @return the n first elements of this list. + */ + override def take(n: Int): List[A] = { + val b = new ListBuffer[A] + var i = 0 + var these = this + while (!these.isEmpty && i < n) { + i += 1 + b += these.head + these = these.tail + } + if (these.isEmpty) this + else b.toList + } + + /** Returns the list with elements belonging to the given index range. + * + * @param start the start position of the list slice. + * @param end the end position (exclusive) of the list slice. + * @return the list with elements belonging to the given index range. + */ + override def slice(start: Int, end: Int): List[A] = { + val s = start max 0 + val e = end min this.length + drop(s) take (e - s) + } + + /** Returns the list without its n first elements. + * If this list has less than n elements, the empty list is returned. + * + * @param n the number of elements to drop. + * @return the list without its n first elements. + */ + override def drop(n: Int): List[A] = { + var these = this + var count = n + while (!these.isEmpty && count > 0) { + these = these.tail + count -= 1 + } + these + } + + /** Returns the rightmost n elements from this list. + * + * @param n the number of elements to take + * @return the suffix of length n of the list + */ + def takeRight(n: Int): List[A] = { + def loop(lead: List[A], lag: List[A]): List[A] = lead match { + case Nil => lag + case _ :: tail => loop(tail, lag.tail) + } + loop(drop(n), this) + } + + /** Returns the list wihout its rightmost n elements. + * + * @param n the number of elements to take + * @return the suffix of length n of the list + */ + def dropRight(n: Int): List[A] = { + def loop(lead: List[A], lag: List[A]): List[A] = lead match { + case Nil => Nil + case _ :: tail => lag.head :: loop(tail, lag.tail) + } + loop(drop(n), this) + } + + /** Split the list at a given point and return the two parts thus + * created. + * + * @param n the position at which to split + * @return a pair of lists composed of the first n + * elements, and the other elements. + */ + def splitAt(n: Int): (List[A], List[A]) = { + val b = new ListBuffer[A] + var i = 0 + var these = this + while (!these.isEmpty && i < n) { + i += 1 + b += these.head + these = these.tail + } + (b.toList, these) + } + + /** Returns the longest prefix of this list whose elements satisfy + * the predicate p. + * + * @param p the test predicate. + * @return the longest prefix of this list whose elements satisfy + * the predicate p. + */ + override def takeWhile(p: A => Boolean): List[A] = { + val b = new ListBuffer[A] + var these = this + while (!these.isEmpty && p(these.head)) { + b += these.head + these = these.tail + } + b.toList + } + + /** Returns the longest suffix of this list whose first element + * does not satisfy the predicate p. + * + * @param p the test predicate. + * @return the longest suffix of the list whose first element + * does not satisfy the predicate p. + */ + override def dropWhile(p: A => Boolean): List[A] = + if (isEmpty || !p(head)) this + else tail dropWhile p + + /** Returns the longest prefix of the list whose elements all satisfy + * the given predicate, and the rest of the list. + * + * @param p the test predicate + * @return a pair consisting of the longest prefix of the list whose + * elements all satisfy p, and the rest of the list. + */ + def span(p: A => Boolean): (List[A], List[A]) = { + val b = new ListBuffer[A] + var these = this + while (!these.isEmpty && p(these.head)) { + b += these.head + these = these.tail + } + (b.toList, these) + } + + /** Like span but with the predicate inverted. + */ + def break(p: A => Boolean): (List[A], List[A]) = span { x => !p(x) } + + /** Returns the n-th element of this list. The first element + * (head of the list) is at position 0. + * + * @param n index of the element to return + * @return the element at position n in this list. + * @throws Predef.NoSuchElementException if the list is too short. + */ + def apply(n: Int): A = drop(n).head + + /** Returns the list resulting from applying the given function f to each + * element of this list. + * + * @param f function to apply to each element. + * @return [f(a0), ..., f(an)] if this list is [a0, ..., an]. + */ + final override def map[B](f: A => B): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + b += f(these.head) + these = these.tail + } + b.toList + } + + /** Apply a function to all the elements of the list, and return the + * reversed list of results. This is equivalent to a call to map + * followed by a call to reverse, but more efficient. + * + * @param f the function to apply to each elements. + * @return the reversed list of results. + */ + def reverseMap[B](f: A => B): List[B] = { + def loop(l: List[A], res: List[B]): List[B] = l match { + case Nil => res + case head :: tail => loop(tail, f(head) :: res) + } + loop(this, Nil) + } + + /** Apply the given function f to each element of this list + * (while respecting the order of the elements). + * + * @param f the treatment to apply to each element. + */ + final override def foreach(f: A => Unit) { + var these = this + while (!these.isEmpty) { + f(these.head) + these = these.tail + } + } + + /** Returns all the elements of this list that satisfy the + * predicate p. The order of the elements is preserved. + * It is guarenteed that the receiver list itself is returned iff all its + * elements satisfy the predicate `p'. Hence the following equality is valid: + * + * (xs filter p) eq xs == xs forall p + * + * @param p the predicate used to filter the list. + * @return the elements of this list satisfying p. + */ + final override def filter(p: A => Boolean): List[A] = { + // return same list if all elements satisfy p + var these = this + while (!these.isEmpty && p(these.head)) { + these = these.tail + } + if (these.isEmpty) this + else { + val b = new ListBuffer[A] + var these1 = this + while (these1 ne these) { + b += these1.head + these1 = these1.tail + } + + these = these.tail // prevent the second evaluation of the predicate + // on the element on which it first failed + while (!these.isEmpty) { + if (p(these.head)) b += these.head + these = these.tail + } + b.toList + } + } + +// final def filterMap[B](f: PartialFunction[A, B]): List[B] = +// this filter f.isDefinedAt map f + + /** Removes all elements of the list which satisfy the predicate + * p. This is like filter with the + * predicate inversed. + * + * @param p the predicate to use to test elements + * @return the list without all elements which satisfy p + */ + def remove(p: A => Boolean): List[A] = filter (x => !p(x)) + + /** Partition the list in two sub-lists according to a predicate. + * + * @param p the predicate on which to partition + * @return a pair of lists: the list of all elements which satisfy + * p and the list of all elements which do not. + * The relative order of the elements in the sub-lists is the + * same as in the original list. + */ + override def partition(p: A => Boolean): (List[A], List[A]) = { + val btrue = new ListBuffer[A] + val bfalse = new ListBuffer[A] + var these = this + while (!these.isEmpty) { + (if (p(these.head)) btrue else bfalse) += these.head + these = these.tail + } + (btrue.toList, bfalse.toList) + } + + /**

+ * Sort the list according to the comparison function + * <(e1: a, e2: a) => Boolean, + * which should be true iff e1 is smaller than + * e2. + *

+ * + * @param lt the comparison function + * @return a list sorted according to the comparison function + * <(e1: a, e2: a) => Boolean. + * @ex
+   *    List("Steve", "Tom", "John", "Bob")
+   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
+   *    List("Bob", "John", "Steve", "Tom")
+ */ + def sort(lt : (A,A) => Boolean): List[A] = { + /** Merge two already-sorted lists */ + def merge(l1: List[A], l2: List[A]): List[A] = { + val res = new ListBuffer[A] + var left1 = l1 + var left2 = l2 + + while (!left1.isEmpty && !left2.isEmpty) { + if(lt(left1.head, left2.head)) { + res += left1.head + left1 = left1.tail + } else { + res += left2.head + left2 = left2.tail + } + } + + res ++= left1 + res ++= left2 + + res.toList + } + + /** Split a list into two lists of about the same size */ + def split(lst: List[A]) = { + val res1 = new ListBuffer[A] + val res2 = new ListBuffer[A] + var left = lst + + while (!left.isEmpty) { + res1 += left.head + left = left.tail + if (!left.isEmpty) { + res2 += left.head + left = left.tail + } + } + + (res1.toList, res2.toList) + } + + + /** Merge-sort the specified list */ + def ms(lst: List[A]): List[A] = + lst match { + case Nil => lst + case x :: Nil => lst + case x :: y :: Nil => + if (lt(x,y)) + lst + else + y :: x :: Nil + + case lst => + val (l1, l2) = split(lst) + val l1s = ms(l1) + val l2s = ms(l2) + merge(l1s, l2s) + } + + ms(this) + } + + + /** Count the number of elements in the list which satisfy a predicate. + * + * @param p the predicate for which to count + * @return the number of elements satisfying the predicate p. + */ + def count(p: A => Boolean): Int = { + var cnt = 0 + var these = this + while (!these.isEmpty) { + if (p(these.head)) cnt += 1 + these = these.tail + } + cnt + } + + /** Tests if the predicate p is satisfied by all elements + * in this list. + * + * @param p the test predicate. + * @return true iff all elements of this list satisfy the + * predicate p. + */ + override def forall(p: A => Boolean): Boolean = { + var these = this + while (!these.isEmpty) { + if (!p(these.head)) return false + these = these.tail + } + true + } + + /** Tests the existence in this list of an element that satisfies the + * predicate p. + * + * @param p the test predicate. + * @return true iff there exists an element in this list that + * satisfies the predicate p. + */ + override def exists(p: A => Boolean): Boolean = { + var these = this + while (!these.isEmpty) { + if (p(these.head)) return true + these = these.tail + } + false + } + + /** Find and return the first element of the list satisfying a + * predicate, if any. + * + * @param p the predicate + * @return the first element in the list satisfying p, + * or None if none exists. + */ + override def find(p: A => Boolean): Option[A] = { + var these = this + while (!these.isEmpty) { + if (p(these.head)) return Some(these.head) + these = these.tail + } + None + } + + /** Combines the elements of this list together using the binary + * function f, from left to right, and starting with + * the value z. + * + * @return f(... (f(f(z, a0), a1) ...), + * an) if the list is + * [a0, a1, ..., an]. + */ + override def foldLeft[B](z: B)(f: (B, A) => B): B = { + var acc = z + var these = this + while (!these.isEmpty) { + acc = f(acc, these.head) + these = these.tail + } + acc + } + + /** Combines the elements of this list together using the binary + * function f, from right to left, and starting with + * the value z. + * + * @return f(a0, f(a1, f(..., f(an, z)...))) + * if the list is [a0, a1, ..., an]. + */ + override def foldRight[B](z: B)(f: (A, B) => B): B = this match { + case Nil => z + case x :: xs => f(x, xs.foldRight(z)(f)) + } + + /** Combines the elements of this list together using the binary + * operator op, from left to right + * @param op The operator to apply + * @return op(... op(a0,a1), ..., an) + if the list has elements + * a0, a1, ..., an. + * @throws Predef.UnsupportedOperationException if the list is empty. + */ + override def reduceLeft[B >: A](f: (B, A) => B): B = this match { + case Nil => throw new UnsupportedOperationException("Nil.reduceLeft") + case x :: Nil => x + case x0 :: x1 :: xs => + var acc : B = f(x0, x1) + var these : List[A] = xs + while (!these.isEmpty) { + acc = f(acc, these.head) + these = these.tail + } + acc + } + + /** Combines the elements of this list together using the binary + * operator op, from right to left + * @param op The operator to apply + * + * @return a0 op (... op (an-1 op an)...) + * if the list has elements a0, a1, ..., + * an. + * + * @throws Predef.UnsupportedOperationException if the list is empty. + */ + override def reduceRight[B >: A](f: (A, B) => B): B = this match { + case Nil => throw new UnsupportedOperationException("Nil.reduceRight") + case x :: Nil => x + case x :: xs => f(x, xs reduceRight f) + } + + /** Applies the given function f to each element of + * this list, then concatenates the results. + * + * @param f the function to apply on each element. + * @return f(a0) ::: ... ::: f(an) if + * this list is [a0, ..., an]. + */ + final override def flatMap[B](f: A => Iterable[B]): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + var those = f(these.head).elements + while (those.hasNext) { + b += those.next + } + these = these.tail + } + b.toList + } + + /** A list consisting of all elements of this list in reverse order. + */ + override def reverse: List[A] = { + var result: List[A] = Nil + var these = this + while (!these.isEmpty) { + result = these.head :: result + these = these.tail + } + result + } + + /** Returns a list formed from this list and the specified list + * that by associating each element of the former with + * the element at the same position in the latter. + * If one of the two lists is longer than the other, its remaining elements are ignored. + * + * @return List((a0,b0), ..., + * (amin(m,n),bmin(m,n))) when + * List(a0, ..., am) + * zip List(b0, ..., bn) is invoked. + */ + def zip[B](that: List[B]): List[(A, B)] = { + val b = new ListBuffer[(A, B)] + var these = this + var those = that + while (!these.isEmpty && !those.isEmpty) { + b += (these.head, those.head) + these = these.tail + those = those.tail + } + b.toList + } + + /** Returns a list that pairs each element of this list + * with its index, counting from 0. + * + * @return the list List((a0,0), (a1,1), ...) + * where ai are the elements of this list. + */ + def zipWithIndex: List[(A, Int)] = { + val b = new ListBuffer[(A, Int)] + var these = this + var idx = 0 + + while(!these.isEmpty) { + b += (these.head, idx) + these = these.tail + idx += 1 + } + + b.toList + } + + /** Returns a list formed from this list and the specified list + * that by associating each element of the former with + * the element at the same position in the latter. + * + * @param that list that may have a different length + * as the self list. + * @param thisElem element thisElem is used to fill up the + * resulting list if the self list is shorter than + * that + * @param thatElem element thatElem is used to fill up the + * resulting list if that is shorter than + * the self list + * @return List((a0,b0), ..., + * (an,bn), (elem,bn+1), + * ..., {elem,bm}) + * when [a0, ..., an] zip + * [b0, ..., bm] is + * invoked where m > n. + */ + def zipAll[B, C >: A, D >: B](that: List[B], thisElem: C, thatElem: D): List[(C, D)] = { + val b = new ListBuffer[(C, D)] + var these = this + var those = that + while (!these.isEmpty && !those.isEmpty) { + b += (these.head, those.head) + these = these.tail + those = those.tail + } + while (!these.isEmpty) { + b += (these.head, thatElem) + these = these.tail + } + while (!those.isEmpty) { + b += (thisElem, those.head) + those = those.tail + } + b.toList + } + + /** Computes the union of this list and the given list + * that. + * + * @param that the list of elements to add to the list. + * @return a list without doubles containing the elements of this + * list and those of the given list that. + */ + def union[B >: A](that: List[B]): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + if (!that.contains(these.head)) b += these.head + these = these.tail + } + b.prependToList(that) + } + + /** Computes the difference between this list and the given list + * that. + * + * @param that the list of elements to remove from this list. + * @return this list without the elements of the given list + * that. + * @deprecated use -- instead + */ + @deprecated + def diff[B >: A](that: List[B]): List[B] = this -- that + + /** Computes the difference between this list and the given list + * that. + * + * @param that the list of elements to remove from this list. + * @return this list without the elements of the given list + * that. + */ + def -- [B >: A](that: List[B]): List[B] = { + val b = new ListBuffer[B] + var these = this + while (!these.isEmpty) { + if (!that.contains(these.head)) b += these.head + these = these.tail + } + b.toList + } + + /** Computes the difference between this list and the given object + * x. + * + * @param x the object to remove from this list. + * @return this list without the elements of the given object + * x. + */ + def - [B >: A](x: B): List[B] = + this -- List(x) + + def flatten[B](implicit f : A => Iterable[B]) : List[B] = { + val buf = new ListBuffer[B] + foreach(f(_).foreach(buf += _)) + buf.toList + } + + /** Computes the intersection between this list and the given list + * that. + * + * @param that the list to intersect. + * @return the list of elements contained both in this list and + * in the given list that. + */ + def intersect[B >: A](that: List[B]): List[B] = filter(x => that contains x) + + /** Removes redundant elements from the list. Uses the method == + * to decide if two elements are identical. + * + * @return the list without doubles. + */ + def removeDuplicates: List[A] = { + val b = new ListBuffer[A] + var these = this + while (!these.isEmpty) { + if (!these.tail.contains(these.head)) b += these.head + these = these.tail + } + b.toList + } + + override protected def stringPrefix = "List" + override def projection = toStream + override def toStream : Stream[A] = new Stream.Definite[A] { + override def force : List[A] = List.this + override def isEmpty = List.this.isEmpty + override def head = List.this.head + override def tail = List.this.tail.toStream + protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = if (!isEmpty) { + var prefix0 = prefix + var buf1 = buf.append(prefix0).append(head) + prefix0 = ", " + var tail0 = tail + while (!tail0.isEmpty) { + buf1 = buf.append(prefix0).append(tail0.head) + tail0 = tail0.tail + } + buf1 + } else buf + } + +} + +/** The empty list. + * + * @author Martin Odersky + * @version 1.0, 15/07/2003 + */ +@SerialVersionUID(0 - 8256821097970055419L) +case object Nil extends List[Nothing] { + override def isEmpty = true + def head: Nothing = + throw new NoSuchElementException("head of empty list") + def tail: List[Nothing] = + throw new NoSuchElementException("tail of empty list") +} + +/** A non empty list characterized by a head and a tail. + * + * @author Martin Odersky + * @version 1.0, 15/07/2003 + */ +@SerialVersionUID(0L - 8476791151983527571L) +final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] { + def head : B = hd + def tail : List[B] = tl + override def isEmpty: Boolean = false + + import java.io._ + + private def writeObject(out: ObjectOutputStream) { + var xs: List[B] = this + while (!xs.isEmpty) { out.writeObject(xs.head); xs = xs.tail } + out.writeObject(ListSerializeEnd) + } + + private def readObject(in: ObjectInputStream) { + hd = in.readObject.asInstanceOf[B] + assert(hd != ListSerializeEnd) + var current: ::[B] = this + while (true) in.readObject match { + case ListSerializeEnd => + current.tl = Nil + return + case a : Any => + val list : ::[B] = new ::(a.asInstanceOf[B], Nil) + current.tl = list + current = list + } + } +} + +/** Only used for list serialization */ +@SerialVersionUID(0L - 8476791151975527571L) +private[scala] case object ListSerializeEnd diff --git a/src/library/scala/Math.scala b/src/library/scala/Math.scala new file mode 100644 index 0000000000..c27b740842 --- /dev/null +++ b/src/library/scala/Math.scala @@ -0,0 +1,204 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +/** The object Math contains methods for performing basic numeric + * operations such as the elementary exponential, logarithm, square root, and + * trigonometric functions. + */ +object Math { + + /** The smallest possible value for scala.Byte. */ + val MIN_BYTE = java.lang.Byte.MIN_VALUE + /** The greatest possible value for scala.Byte. */ + val MAX_BYTE = java.lang.Byte.MAX_VALUE + + /** The smallest possible value for scala.Short. */ + val MIN_SHORT = java.lang.Short.MIN_VALUE + /** The greatest possible value for scala.Short. */ + val MAX_SHORT = java.lang.Short.MAX_VALUE + + /** The smallest possible value for scala.Char. */ + val MIN_CHAR = java.lang.Character.MIN_VALUE + /** The greatest possible value for scala.Char. */ + val MAX_CHAR = java.lang.Character.MAX_VALUE + + /** The smallest possible value for scala.Int. */ + val MIN_INT = java.lang.Integer.MIN_VALUE + /** The greatest possible value for scala.Int. */ + val MAX_INT = java.lang.Integer.MAX_VALUE + + /** The smallest possible value for scala.Long. */ + val MIN_LONG = java.lang.Long.MIN_VALUE + /** The greatest possible value for scala.Long. */ + val MAX_LONG = java.lang.Long.MAX_VALUE + + /** The smallest possible value for scala.Float. */ + val MIN_FLOAT = -java.lang.Float.MAX_VALUE + /** The smallest difference between two values of scala.Float. */ + val EPS_FLOAT = java.lang.Float.MIN_VALUE + /** The greatest possible value for scala.Float. */ + val MAX_FLOAT = java.lang.Float.MAX_VALUE + /** A value of type scala.Float that represents no number. */ + val NaN_FLOAT = java.lang.Float.NaN + /** Negative infinity of type scala.Float. */ + val NEG_INF_FLOAT = java.lang.Float.NEGATIVE_INFINITY + /** Positive infinity of type scala.Float. */ + val POS_INF_FLOAT = java.lang.Float.POSITIVE_INFINITY + + /** The smallest possible value for scala.Double. */ + val MIN_DOUBLE = -java.lang.Double.MAX_VALUE + /** The smallest difference between two values of scala.Double. */ + val EPS_DOUBLE = java.lang.Double.MIN_VALUE + /** The greatest possible value for scala.Double. */ + val MAX_DOUBLE = java.lang.Double.MAX_VALUE + /** A value of type scala.Double that represents no number. */ + val NaN_DOUBLE = java.lang.Double.NaN + /** Negative infinity of type scala.Double. */ + val NEG_INF_DOUBLE = java.lang.Double.NEGATIVE_INFINITY + /** Positive infinity of type scala.Double. */ + val POS_INF_DOUBLE = java.lang.Double.POSITIVE_INFINITY + + /** The double value that is closer than any other to + * e, the base of the natural logarithms. + */ + val E = java.lang.Math.E + + /** The double value that is closer than any other to + * pi, the ratio of the circumference of a circle to its + * diameter. + */ + val Pi = java.lang.Math.PI + + /** Returns a double value with a positive sign, greater than + * or equal to 0.0 and less than 1.0. + */ + def random: Double = java.lang.Math.random() + + def sin(x: Double): Double = java.lang.Math.sin(x) + def cos(x: Double): Double = java.lang.Math.cos(x) + def tan(x: Double): Double = java.lang.Math.tan(x) + def asin(x: Double): Double = java.lang.Math.asin(x) + def acos(x: Double): Double = java.lang.Math.acos(x) + def atan(x: Double): Double = java.lang.Math.atan(x) + + /** Converts an angle measured in degrees to an approximately equivalent + * angle measured in radians. + * + * @param x an angle, in degrees + * @return the measurement of the angle x in radians. + */ + def toRadians(x: Double): Double = java.lang.Math.toRadians(x) + + /** Converts an angle measured in radians to an approximately equivalent + * angle measured in degrees. + * + * @param x angle, in radians + * @return the measurement of the angle x in degrees. + */ + def toDegrees(x: Double): Double = java.lang.Math.toDegrees(x) + + /** Returns Euler's number e raised to the power of a + * double value. + * + * @param x the exponent to raise e to. + * @return the value ea, where e + * is the base of the natural logarithms. + */ + def exp(x: Double): Double = java.lang.Math.exp(x) + def log(x: Double): Double = java.lang.Math.log(x) + def sqrt(x: Double): Double = java.lang.Math.sqrt(x) + def sqrt(x: Int): Int = java.lang.Math.sqrt(x.toDouble).toInt + def IEEEremainder(x: Double, y: Double): Double = java.lang.Math.IEEEremainder(x, y) + + def ceil(x: Double): Double = java.lang.Math.ceil(x) + def floor(x: Double): Double = java.lang.Math.floor(x) + + /** Returns the double value that is closest in value to the + * argument and is equal to a mathematical integer. + * + * @param x a double value + * @return the closest floating-point value to a that is equal to a + * mathematical integer. + */ + def rint(x: Double): Double = java.lang.Math.rint(x) + + /** Converts rectangular coordinates (x, y) to polar + * (r, theta). + * + * @param x the ordinate coordinate + * @param y the abscissa coordinate + * @return the theta component of the point (r, theta) + * in polar coordinates that corresponds to the point + * (x, y) in Cartesian coordinates. + */ + def atan2(y: Double, x: Double): Double = java.lang.Math.atan2(y, x) + + /** Returns the value of the first argument raised to the power of the + * second argument. + * + * @param x the base. + * @param y the exponent. + * @return the value xy. + */ + def pow(x: Double, y: Double): Double = java.lang.Math.pow(x, y) + + /** Returns the closest long to the argument. + * + * @param x a floating-point value to be rounded to a long. + * @return the value of the argument rounded to the nearest + * long value. + */ + def round(x: Float): Int = java.lang.Math.round(x) + def round(x: Double): Long = java.lang.Math.round(x) + def abs(x: Int): Int = java.lang.Math.abs(x) + def abs(x: Long): Long = java.lang.Math.abs(x) + def abs(x: Float): Float = java.lang.Math.abs(x) + def abs(x: Double): Double = java.lang.Math.abs(x) + + def max(x: Int, y: Int): Int = java.lang.Math.max(x, y) + def max(x: Long, y: Long): Long = java.lang.Math.max(x, y) + def max(x: Float, y: Float): Float = java.lang.Math.max(x, y) + def max(x: Double, y: Double): Double = java.lang.Math.max(x, y) + + def min(x: Int, y: Int): Int = java.lang.Math.min(x, y) + def min(x: Long, y: Long): Long = java.lang.Math.min(x, y) + def min(x: Float, y: Float): Float = java.lang.Math.min(x, y) + def min(x: Double, y: Double): Double = java.lang.Math.min(x, y) + + def signum(x: Double): Double = x match { case 0 => 0 + case y if y < 0 => -1.0 + case y if y > 0 => 1.0 } + def signum(x: Float): Float = x match { case 0f => 0f + case y if y < 0f => -1.0f + case y if y > 0f => 1.0f } + def signum(x: Long): Long = x match { case 0l => 0l + case y if y < 0l => -1l + case y if y > 0l => 1l } + def signum(x: Int): Int = x match { case 0 => 0 + case y if y < 0 => -1 + case y if y > 0 => 1} + + // from Java 1.5 +// def log10(x: Double): Double = java.lang.Math.log10(x) +// def cbrt(x: Double): Double = java.lang.Math.cbrt(x) + +// def ulp(x: Double): Double = java.lang.Math.ulp(x) +// def ulp(x: Float): Float = java.lang.Math.ulp(x) +// def sinh(x: Double): Double = java.lang.Math.sinh(x) +// def cosh(x: Double): Double = java.lang.Math.cosh(x) +// def tanh(x: Double):Double = java.lang.Math.tanh(x) +// def hypot(x: Double, y: Double): Double = java.lang.Math.hypot(x, y) +// def expm1(x: Double): Double = java.lang.Math.expm1(x) +// def log1p(x: Double): Double = java.lang.Math.log1p(x) + +} diff --git a/src/library/scala/Predef.scala b/src/library/scala/Predef.scala new file mode 100644 index 0000000000..c7a01d6642 --- /dev/null +++ b/src/library/scala/Predef.scala @@ -0,0 +1,349 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + + +/** The Predef object provides definitions that are + * accessible in all Scala compilation units without explicit + * qualification. + */ +object Predef { + + // classOf dummy ------------------------------------------------------ + + /** Return the runtime representation of a class type. */ + def classOf[T]: Class[T] = null + + // aliases ------------------------------------------------------------ + + type byte = scala.Byte + type short = scala.Short + type char = scala.Char + type int = scala.Int + type long = scala.Long + type float = scala.Float + type double = scala.Double + type boolean = scala.Boolean + type unit = scala.Unit + + /** @deprecated use java.lang.Integer instead */ + @deprecated type Integer = java.lang.Integer + /** @deprecated use java.lang.Character instead */ + @deprecated type Character = java.lang.Character + + type String = java.lang.String + type Class[T] = java.lang.Class[T] + type Runnable = java.lang.Runnable + + type Throwable = java.lang.Throwable + type Exception = java.lang.Exception + type Error = java.lang.Error + + type RuntimeException = java.lang.RuntimeException + type NullPointerException = java.lang.NullPointerException + type ClassCastException = java.lang.ClassCastException + type IndexOutOfBoundsException = java.lang.IndexOutOfBoundsException + type ArrayIndexOutOfBoundsException = java.lang.ArrayIndexOutOfBoundsException + type StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException + type UnsupportedOperationException = java.lang.UnsupportedOperationException + type IllegalArgumentException = java.lang.IllegalArgumentException + type NoSuchElementException = java.util.NoSuchElementException + type NumberFormatException = java.lang.NumberFormatException + + // miscelleaneous ----------------------------------------------------- + + val $scope = scala.xml.TopScope + + type Function[-A, +B] = Function1[A, B] + + type Map[A, B] = collection.immutable.Map[A, B] + type Set[A] = collection.immutable.Set[A] + + val Map = collection.immutable.Map + val Set = collection.immutable.Set + + // errors and asserts ------------------------------------------------- + + def error(message: String): Nothing = throw new RuntimeException(message) + + def exit: Nothing = exit(0) + + def exit(status: Int): Nothing = { + java.lang.System.exit(status) + throw new Throwable() + } + + def assert(assertion: Boolean) { + if (!assertion) + throw new java.lang.AssertionError("assertion failed") + } + + def assert(assertion: Boolean, message: Any) { + if (!assertion) + throw new java.lang.AssertionError("assertion failed: "+ message) + } + + def assume(assumption: Boolean) { + if (!assumption) + throw new java.lang.AssertionError("assumption failed") + } + + def assume(assumption: Boolean, message: Any) { + if (!assumption) + throw new java.lang.AssertionError("assumptopm failed: "+ message) + } + + def require(requirement: Boolean) { + if (!requirement) + throw new IllegalArgumentException("requirement failed") + } + + def require(requirement: Boolean, message: Any) { + if (!requirement) + throw new IllegalArgumentException("requirement failed: "+ message) + } + + // tupling ------------------------------------------------------------ + + type Pair[+A, +B] = Tuple2[A, B] + object Pair { + def apply[A, B](x: A, y: B) = Tuple2(x, y) + def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x) + } + + type Triple[+A, +B, +C] = Tuple3[A, B, C] + object Triple { + def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z) + def unapply[A, B, C](x: Tuple3[A, B, C]): Option[Tuple3[A, B, C]] = Some(x) + } + + class Ensuring[A](x: A) { + def ensuring(cond: Boolean): A = { assert(cond); x } + def ensuring(cond: Boolean, msg: Any): A = { assert(cond, msg); x } + def ensuring(cond: A => Boolean): A = { assert(cond(x)); x } + def ensuring(cond: A => Boolean, msg: Any): A = { assert(cond(x), msg); x } + } + implicit def any2Ensuring[A](x: A): Ensuring[A] = new Ensuring(x) + + class ArrowAssoc[A](x: A) { + def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y) + } + implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x) + + def Tuple[A1](x1: A1) = Tuple1(x1) + def Tuple[A1, A2](x1: A1, x2: A2) = Tuple2(x1, x2) + def Tuple[A1, A2, A3](x1: A1, x2: A2, x3: A3) = Tuple3(x1, x2, x3) + def Tuple[A1, A2, A3, A4](x1: A1, x2: A2, x3: A3, x4: A4) = Tuple4(x1, x2, x3, x4) + def Tuple[A1, A2, A3, A4, A5](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5) = Tuple5(x1, x2, x3, x4, x5) + def Tuple[A1, A2, A3, A4, A5, A6](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6) = Tuple6(x1, x2, x3, x4, x5, x6) + def Tuple[A1, A2, A3, A4, A5, A6, A7](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7) = Tuple7(x1, x2, x3, x4, x5, x6, x7) + def Tuple[A1, A2, A3, A4, A5, A6, A7, A8](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8) = Tuple8(x1, x2, x3, x4, x5, x6, x7, x8) + def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9) = Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9) + + // printing and reading ----------------------------------------------- + + def print(x: Any) = Console.print(x) + def println() = Console.println() + def println(x: Any) = Console.println(x) + def printf(text: String, xs: Any*) = Console.printf(text, xs: _*) + def format(text: String, xs: Any*) = Console.format(text, xs: _*) + + def readLine(): String = Console.readLine() + def readLine(text: String, args: Any*) = Console.readLine(text, args) + def readBoolean() = Console.readBoolean() + def readByte() = Console.readByte() + def readShort() = Console.readShort() + def readChar() = Console.readChar() + def readInt() = Console.readInt() + def readLong() = Console.readLong() + def readFloat() = Console.readFloat() + def readDouble() = Console.readDouble() + def readf(format: String) = Console.readf(format) + def readf1(format: String) = Console.readf1(format) + def readf2(format: String) = Console.readf2(format) + def readf3(format: String) = Console.readf3(format) + + // views -------------------------------------------------------------- + + implicit def identity[A](x: A): A = x + + implicit def byteWrapper(x: Byte) = new runtime.RichByte(x) + implicit def shortWrapper(x: Short) = new runtime.RichShort(x) + implicit def intWrapper(x: Int) = new runtime.RichInt(x) + implicit def charWrapper(c: Char) = new runtime.RichChar(c) + implicit def longWrapper(x: Long) = new runtime.RichLong(x) + implicit def floatWrapper(x: Float) = new runtime.RichFloat(x) + implicit def doubleWrapper(x: Double) = new runtime.RichDouble(x) + + implicit def booleanWrapper(x: Boolean) = new runtime.RichBoolean(x) + + implicit def stringWrapper(x: String) = new runtime.RichString(x) + implicit def stringBuilderWrapper(x : StringBuilder): runtime.RichStringBuilder = new runtime.RichStringBuilder(x) + + implicit def any2stringadd(x: Any) = new runtime.StringAdd(x) + + implicit def exceptionWrapper(exc: Throwable) = new runtime.RichException(exc) + + implicit def unit2ordered(x: Unit): Ordered[Unit] = new Ordered[Unit] with Proxy { + def self: Any = x + def compare(y: Unit): Int = 0 + } + + implicit def iterable2ordered[A <% Ordered[A]](xs: Iterable[A]): Ordered[Iterable[A]] = + new Ordered[Iterable[A]] with Proxy { + val self = xs + def compare(that: Iterable[A]): Int = { + var res = 0 + val these = xs.elements + val those = that.elements + while (res == 0 && these.hasNext) + res = if (those.hasNext) these.next compare those.next else 1 + if (res == 0) { + if (those.hasNext) -1 else 0 + } else + res + } + } + + implicit def tuple22ordered[A1 <% Ordered[A1], A2 <% Ordered[A2]](x: Tuple2[A1, A2]): Ordered[Tuple2[A1, A2]] = + new Ordered[Tuple2[A1, A2]] with Proxy { + val self = x + def compare(y: Tuple2[A1, A2]): Int = { + val res = x._1 compare y._1 + if (res == 0) x._2 compare y._2 + else res + } + } + + implicit def tuple32ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3]](x: Tuple3[A1, A2, A3]): Ordered[Tuple3[A1, A2, A3]] = + new Ordered[Tuple3[A1, A2, A3]] with Proxy { + val self = x + def compare(y: Tuple3[A1, A2, A3]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple2(x._2, x._3) compare Tuple2(y._2, y._3) + else res + } + } + + implicit def tuple42ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4]](x: Tuple4[A1, A2, A3, A4]): Ordered[Tuple4[A1, A2, A3, A4]] = + new Ordered[Tuple4[A1, A2, A3, A4]] with Proxy { + val self = x + def compare(y: Tuple4[A1, A2, A3, A4]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple3(x._2, x._3, x._4) compare Tuple3(y._2, y._3, y._4) + else res + } + } + + implicit def tuple52ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5]](x: Tuple5[A1, A2, A3, A4, A5]): Ordered[Tuple5[A1, A2, A3, A4, A5]] = + new Ordered[Tuple5[A1, A2, A3, A4, A5]] with Proxy { + val self = x + def compare(y: Tuple5[A1, A2, A3, A4, A5]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple4(x._2, x._3, x._4, x._5) compare Tuple4(y._2, y._3, y._4, y._5) + else res + } + } + + implicit def tuple62ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6]](x: Tuple6[A1, A2, A3, A4, A5, A6]): Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] = + new Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] with Proxy { + val self = x + def compare(y: Tuple6[A1, A2, A3, A4, A5, A6]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple5(x._2, x._3, x._4, x._5, x._6) compare Tuple5(y._2, y._3, y._4, y._5, y._6) + else res + } + } + + implicit def tuple72ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7]](x: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] = + new Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] with Proxy { + val self = x + def compare(y: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple6(x._2, x._3, x._4, x._5, x._6, x._7) compare Tuple6(y._2, y._3, y._4, y._5, y._6, y._7) + else res + } + } + + implicit def tuple82ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8]](x: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] = + new Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] with Proxy { + val self = x + def compare(y: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple7(x._2, x._3, x._4, x._5, x._6, x._7, x._8) compare Tuple7(y._2, y._3, y._4, y._5, y._6, y._7, y._8) + else res + } + } + + implicit def tuple92ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8], A9 <% Ordered[A9]](x: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] = + new Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] with Proxy { + val self = x + def compare(y: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Int = { + val res = x._1 compare y._1 + if (res == 0) Tuple8(x._2, x._3, x._4, x._5, x._6, x._7, x._8, x._9) compare Tuple8(y._2, y._3, y._4, y._5, y._6, y._7, y._8, y._9) + else res + } + } + + implicit def byte2short(x: Byte): Short = x.toShort + implicit def byte2int(x: Byte): Int = x.toInt + implicit def byte2long(x: Byte): Long = x.toLong + implicit def byte2float(x: Byte): Float = x.toFloat + implicit def byte2double(x: Byte): Double = x.toDouble + + implicit def short2int(x: Short): Int = x.toInt + implicit def short2long(x: Short): Long = x.toLong + implicit def short2float(x: Short): Float = x.toFloat + implicit def short2double(x: Short): Double = x.toDouble + + implicit def char2int(x: Char): Int = x.toInt + implicit def char2long(x: Char): Long = x.toLong + implicit def char2float(x: Char): Float = x.toFloat + implicit def char2double(x: Char): Double = x.toDouble + + implicit def int2long(x: Int): Long = x.toLong + implicit def int2float(x: Int): Float = x.toFloat + implicit def int2double(x: Int): Double = x.toDouble + + implicit def long2float(x: Long): Float = x.toFloat + implicit def long2double(x: Long): Double = x.toDouble + + implicit def float2double(x: Float): Double = x.toDouble + + /** Should use java.lang.Byte.valueOf(Byte), but only available + * in Java 1.5 and above. */ + implicit def byte2Byte(x: Byte) = new java.lang.Byte(x) + /** Should use java.lang.Short.valueOf(Short), but only available + * in Java 1.5 and above. */ + implicit def short2Short(x: Short) = new java.lang.Short(x) + /** Should use java.lang.Character.valueOf(Char), but only available + * in Java 1.5 and above. */ + implicit def char2Character(x: Char) = new java.lang.Character(x) + /** Should use java.lang.Integer.valueOf(Int), but only available + * in Java 1.5 and above. */ + implicit def int2Integer(x: Int) = new java.lang.Integer(x) + /** Should use java.lang.Long.valueOf(Long), but only available + * in Java 1.5 and above. */ + implicit def long2Long(x: Long) = new java.lang.Long(x) + implicit def float2Float(x: Float) = new java.lang.Float(x) + implicit def double2Double(x: Double) = new java.lang.Double(x) + implicit def boolean2Boolean(x: Boolean) = java.lang.Boolean.valueOf(x) + + /** any array projection can be automatically converted into an array */ + implicit def forceArrayProjection[A](x: Array.Projection[A]): Array[A] = x.force + /** any random access character seq (including rich string can be converted into a string */ + implicit def forceRandomAccessCharSeq(x: runtime.RichString): String = x.mkString + implicit def lazyStreamToConsable[A](xs: => Stream[A]) = new runtime.StreamCons(xs) + + def currentThread = java.lang.Thread.currentThread() + +} diff --git a/src/library/scala/Random.scala b/src/library/scala/Random.scala new file mode 100644 index 0000000000..c1e8801bf4 --- /dev/null +++ b/src/library/scala/Random.scala @@ -0,0 +1,72 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +/** + * @author Stephane Micheloud + */ +class Random(val self: java.util.Random) { + + /** Creates a new random number generator using a single long seed. */ + def this(seed: Long) = this(new java.util.Random(seed)) + + /** Creates a new random number generator using a single integer seed. */ + def this(seed: Int) = this(seed.toLong) + + /** Creates a new random number generator. */ + def this() = this(compat.Platform.currentTime) + + /** Returns the next pseudorandom, uniformly distributed boolean value + * from this random number generator's sequence. + */ + def nextBoolean(): Boolean = self.nextBoolean() + + /** Generates random bytes and places them into a user-supplied byte + * array. + */ + def nextBytes(bytes: Array[Byte]) { self.nextBytes(bytes) } + + /** Returns the next pseudorandom, uniformly distributed double value + * between 0.0 and 1.0 from this random number generator's sequence. + */ + def nextDouble(): Double = self.nextDouble() + + /** Returns the next pseudorandom, uniformly distributed float value + * between 0.0 and 1.0 from this random number generator's sequence. + */ + def nextFloat(): Float = self.nextFloat() + + /** Returns the next pseudorandom, Gaussian ("normally") distributed + * double value with mean 0.0 and standard deviation 1.0 from this + * random number generator's sequence. + */ + //def nextGaussian(): Double = self.nextGaussian() + + /** Returns the next pseudorandom, uniformly distributed int value + * from this random number generator's sequence. + */ + def nextInt(): Int = self.nextInt() + + /** Returns a pseudorandom, uniformly distributed int value between 0 + * (inclusive) and the specified value (exclusive), drawn from this + * random number generator's sequence. + */ + def nextInt(n: Int): Int = self.nextInt(n) + + /** Returns the next pseudorandom, uniformly distributed long value + * from this random number generator's sequence. + */ + def nextLong(): Long = self.nextLong() + + def setSeed(seed: Long) { self.setSeed(seed) } + +} diff --git a/src/library/scala/StringBuilder.scala b/src/library/scala/StringBuilder.scala new file mode 100644 index 0000000000..92ee3b9ac8 --- /dev/null +++ b/src/library/scala/StringBuilder.scala @@ -0,0 +1,946 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import Predef._ + +/**

+ * A mutable sequence of characters. This class provides an API compatible + * with java.lang.StringBuilder, but with no guarantee of + * synchronization. + *

+ * + * @author Stephane Micheloud + * @version 1.0 + */ +@SerialVersionUID(0 - 8525408645367278351L) +final class StringBuilder(initCapacity: Int, private val initValue: String) +extends (Int => Char) with Proxy { + if (initCapacity < 0) throw new IllegalArgumentException + if (initValue eq null) throw new NullPointerException + + /** The value is used for character storage. */ + private var value = new Array[Char](initCapacity + initValue.length) + + /** The count is the number of characters used. */ + private var count: Int = 0 + + /** Constructs a string builder with no characters in it and an + * initial capacity of 16 characters. + */ + def this() = this(16, "") + + /** Constructs a string builder with no characters in it and an + * initial capacity specified by the capacity argument. + * + * @param capacity the initial capacity. + * @throws NegativeArraySizeException if the capacity + * argument is less than 0. + */ + def this(capacity: Int) = this(capacity, "") + + def this(str: String) = this(16, str) + + append(initValue) + + def self = this + + def toArray: Array[Char] = value + + def length: Int = count + + def length_=(n: Int) { setLength(n) } + + /** Sets the length of the character sequence. + * + * @param newLength the new length + * @throws IndexOutOfBoundsException if the n argument is negative. + */ + def setLength(n: Int) { + if (n < 0) + throw new StringIndexOutOfBoundsException(n) + if (n > value.length) expandCapacity(n) + if (count < n) + while (count < n) { + value(count) = '\0'; count += 1 + } + else + count = n + } + + /** Returns the current capacity. The capacity is the amount of storage + * available for newly inserted characters, beyond which an allocation + * will occur. + * + * @return the current capacity + */ + def capacity: Int = value.length + + /** Same as ensureCapacity. */ + def capacity_=(n: Int) { ensureCapacity(n) } + + /**

+ * Ensures that the capacity is at least equal to the specified minimum. + * If the current capacity is less than the argument, then a new internal + * array is allocated with greater capacity. The new capacity is the larger of: + *

+ *
    + *
  • The n argument. + *
  • Twice the old capacity, plus 2. + *
+ *

+ * If the n argument is non-positive, this + * method takes no action and simply returns. + *

+ * + * @param n the minimum desired capacity. + */ + def ensureCapacity(n: Int) { + if (n > value.length) expandCapacity(n) + } + + private def expandCapacity(n: Int) { + val newCapacity = (value.length + 1) * 2 + value = StringBuilder.copyOf( + value, + if (newCapacity < 0) Math.MAX_INT else if (n > newCapacity) n else newCapacity + ) + } + + /**

+ * Returns the Char value in this sequence at the specified index. + * The first Char value is at index 0, the next at index + * 1, and so on, as in array indexing. + *

+ *

+ * The index argument must be greater than or equal to + * 0, and less than the length of this sequence. + *

+ * + * @param index the index of the desired Char value. + * @return the Char value at the specified index. + * @throws IndexOutOfBoundsException if index is + * negative or greater than or equal to length(). + */ + def charAt(index: Int): Char = { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException(index) + value(index) + } + + /** Same as charAt. */ + def apply(i: Int): Char = charAt(i) + + /**

+ * Removes the Char at the specified position in this + * sequence. This sequence is shortened by one Char. + *

+ * + * @param index Index of Char to remove + * @return This object. + * @throws StringIndexOutOfBoundsException if the index + * is negative or greater than or equal to length(). + */ + def deleteCharAt(index: Int): StringBuilder = { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException(index) + compat.Platform.arraycopy(value, index + 1, value, index, count - index - 1) + count -= 1 + this + } + + /**

+ * The character at the specified index is set to ch. This + * sequence is altered to represent a new character sequence that is + * identical to the old character sequence, except that it contains the + * character ch at position index. + *

+ *

+ * The index argument must be greater than or equal to + * 0, and less than the length of this sequence. + *

+ * + * @param index the index of the character to modify. + * @param ch the new character. + * @throws IndexOutOfBoundsException if index is + * negative or greater than or equal to length(). + */ + def setCharAt(index: Int, ch: Char) { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException(index) + value(index) = ch + } + + /** Same as setCharAt. */ + def update(i: Int, c: Char) { setCharAt(i, c) } + + /** Returns a new String that contains a subsequence of + * characters currently contained in this character sequence. The + * substring begins at the specified index and extends to the end of + * this sequence. + * + * @param start The beginning index, inclusive. + * @return The new string. + * @throws StringIndexOutOfBoundsException if start is + * less than zero, or greater than the length of this object. + */ + def substring(start: Int): String = substring(start, count) + + /** Returns a new String that contains a subsequence of + * characters currently contained in this sequence. The + * substring begins at the specified start and + * extends to the character at index end - 1. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @return The new string. + * @throws StringIndexOutOfBoundsException if start + * or end are negative or greater than + * length(), or start is + * greater than end. + */ + def substring(start: Int, end: Int): String = { + if (start < 0) + throw new StringIndexOutOfBoundsException(start) + if (end > count) + throw new StringIndexOutOfBoundsException(end) + if (start > end) + throw new StringIndexOutOfBoundsException(end - start) + new String(value, start, end - start) + } + + /**

+ * Appends the string representation of the Any + * argument. + *

+ *

+ * The argument is converted to a string as if by the method + * String.valueOf, and the characters of that + * string are then appended to this sequence. + *

+ * + * @param x an Any object. + * @return a reference to this object. + */ + def append(x: Any): StringBuilder = + append(String.valueOf(x)) + + /** Appends the specified string to this character sequence. + * + * @param s a string. + * @return a reference to this object. + */ + def append(s: String): StringBuilder = { + val str = if (s == null) "null" else s + val len = str.length + if (len > 0) { + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(str.toCharArray, 0, value, count, len) + count = newCount + } + this + } + + /** Appends the specified string builder to this sequence. + * + * @param sb + * @return + */ + def append(sb: StringBuilder): StringBuilder = + if (sb == null) + append("null") + else { + val len = sb.length + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(sb.toArray, 0, value, count, len) + count = newCount + this + } + + /**

+ * Appends the string representation of the Char sequence + * argument to this sequence. + *

+ *

+ * The characters of the sequence argument are appended, in order, + * to the contents of this sequence. The length of this sequence + * increases by the length of the argument. + *

+ * + * @param x the characters to be appended. + * @return a reference to this object. + */ + def append(x: Seq[Char]): StringBuilder = + append(x.toArray, 0, x.length) + + /**

+ * Appends the string representation of the Char array + * argument to this sequence. + *

+ *

+ * The characters of the array argument are appended, in order, to + * the contents of this sequence. The length of this sequence + * increases by the length of the argument. + *

+ * + * @param x the characters to be appended. + * @return a reference to this object. + */ + def append(x: Array[Char]): StringBuilder = + append(x, 0, x.length) + + /**

+ * Appends the string representation of a subarray of the + * char array argument to this sequence. + *

+ *

+ * Characters of the Char array x, starting at + * index offset, are appended, in order, to the contents + * of this sequence. The length of this sequence increases + * by the value of len. + *

+ * + * @param x the characters to be appended. + * @param offset the index of the first Char to append. + * @param len the number of Chars to append. + * @return a reference to this object. + */ + def append(x: Array[Char], offset: Int, len: Int): StringBuilder = { + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(x, offset, value, count, len) + count = newCount + this + } + + /**

+ * Appends the string representation of the Boolean + * argument to the sequence. + *

+ *

+ * The argument is converted to a string as if by the method + * String.valueOf, and the characters of that + * string are then appended to this sequence. + *

+ * + * @param x a Boolean. + * @return a reference to this object. + */ + def append(x: Boolean): StringBuilder = { + if (x) { + val newCount = count + 4 + if (newCount > value.length) expandCapacity(newCount) + value(count) = 't'; count += 1 + value(count) = 'r'; count += 1 + value(count) = 'u'; count += 1 + value(count) = 'e'; count += 1 + } else { + val newCount = count + 5 + if (newCount > value.length) expandCapacity(newCount) + value(count) = 'f'; count += 1 + value(count) = 'a'; count += 1 + value(count) = 'l'; count += 1 + value(count) = 's'; count += 1 + value(count) = 'e'; count += 1 + } + this + } + + def append(x: Byte): StringBuilder = + append(String.valueOf(x)) + + def append(x: Char): StringBuilder = { + val newCount = count + 1 + if (newCount > value.length) expandCapacity(newCount) + value(count) = x; count += 1 + this + } + + def append(x: Short): StringBuilder = + append(String.valueOf(x)) + + def append(x: Int): StringBuilder = + append(String.valueOf(x)) + + def append(x: Long): StringBuilder = + append(String.valueOf(x)) + + def append(x: Float): StringBuilder = + append(String.valueOf(x)) + + def append(x: Double): StringBuilder = + append(String.valueOf(x)) + + /** Removes the characters in a substring of this sequence. + * The substring begins at the specified start and extends to + * the character at index end - 1 or to the end of the + * sequence if no such character exists. If + * start is equal to end, no changes are made. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @return This object. + * @throws StringIndexOutOfBoundsException if start + * is negative, greater than length(), or + * greater than end. + */ + def delete(start: Int, end: Int): StringBuilder = { + if (start < 0 || start > end) + throw new StringIndexOutOfBoundsException(start) + val end0 = if (end > count) count else end + val len = end0 - start + if (len > 0) { + compat.Platform.arraycopy(value, start + len, value, start, count - end0) + count -= len + } + this + } + + /** Replaces the characters in a substring of this sequence + * with characters in the specified String. The substring + * begins at the specified start and extends to the character + * at index end - 1 or to the end of the sequence if no such + * character exists. First the characters in the substring are removed and + * then the specified String is inserted at start. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @param str String that will replace previous contents. + * @return This object. + * @throws StringIndexOutOfBoundsException if start + * is negative, greater than length(), or + * greater than end. + */ + def replace(start: Int, end: Int, str: String) { + if (start < 0 || start > count || start > end) + throw new StringIndexOutOfBoundsException(start) + + val end0 = if (end > count) count else end + val len = str.length() + val newCount = count + len - (end0 - start) + if (newCount > value.length) expandCapacity(newCount) + + compat.Platform.arraycopy(value, end, value, start + len, count - end) + compat.Platform.arraycopy(str.toCharArray, 0, value, start, len) + count = newCount + this + } + + /** Inserts the string representation of a subarray of the str + * array argument into this sequence. The subarray begins at the specified + * offset and extends len chars. + * The characters of the subarray are inserted into this sequence at + * the position indicated by index. The length of this + * sequence increases by len Chars. + * + * @param index position at which to insert subarray. + * @param str a Char array. + * @param offset the index of the first char in subarray to + * be inserted. + * @param len the number of Chars in the subarray to + * be inserted. + * @return This object + * @throws StringIndexOutOfBoundsException if index + * is negative or greater than length(), or + * offset or len are negative, or + * (offset+len) is greater than + * str.length. + */ + def insert(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = { + if (index < 0 || index > count) + throw new StringIndexOutOfBoundsException(index) + if (offset < 0 || len < 0 || offset > str.length - len) + throw new StringIndexOutOfBoundsException( + "offset " + offset + ", len " + len + + ", str.length " + str.length) + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, index, value, index + len, count - index) + compat.Platform.arraycopy(str, offset, value, index, len) + count = newCount + this + } + + /**

+ * Inserts the string representation of the Any + * argument into this character sequence. + *

+ *

+ * The second argument is converted to a string as if by the method + * String.valueOf, and the characters of that + * string are then inserted into this sequence at the indicated + * offset. + *

+ *

+ * The offset argument must be greater than or equal to + * 0, and less than or equal to the length of this + * sequence. + *

+ * + * @param offset the offset. + * @param x an Any value. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: Any): StringBuilder = + insert(at, String.valueOf(x)) + + /** Inserts the string into this character sequence. + * + * @param at the offset position. + * @param x a string. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: String): StringBuilder = { + if (at < 0 || at > count) + throw new StringIndexOutOfBoundsException(at) + val str = if (x == null) "null" else x + val len = str.length + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, at, value, at + len, count - at) + compat.Platform.arraycopy(str.toCharArray, 0, value, at, len) + count = newCount + this + } + + /** Inserts the string representation of the Char sequence + * argument into this sequence. + * + * @param at the offset position. + * @param x a character sequence. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: Seq[Char]): StringBuilder = + insert(at, x.toArray) + + /** Inserts the string representation of the Char array + * argument into this sequence. + * + * @param at the offset position. + * @param x a character array. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + def insert(at: Int, x: Array[Char]): StringBuilder = { + if (at < 0 || at > count) + throw new StringIndexOutOfBoundsException(at) + val len = x.length + val newCount = count + len + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, at, value, at + len, count - at) + compat.Platform.arraycopy(x, 0, value, at, len) + count = newCount + this + } + + /**

+ * Inserts the string representation of the Boolean argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Boolean value. + * @return a reference to this object. + */ + def insert(at: Int, x: Boolean): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Inserts the string representation of the Byte argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Byte value. + * @return a reference to this object. + */ + def insert(at: Int, x: Byte): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Inserts the string representation of the Char argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Char value. + * @return a reference to this object. + */ + def insert(at: Int, x: Char): StringBuilder = { + if (at < 0 || at > count) + throw new StringIndexOutOfBoundsException(at) + val newCount = count + 1 + if (newCount > value.length) expandCapacity(newCount) + compat.Platform.arraycopy(value, at, value, at + 1, count - at) + value(at) = x + count = newCount + this + } + + /**

+ * Inserts the string representation of the Short argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Short value. + * @return a reference to this object. + */ + def insert(at: Int, x: Short): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Inserts the string representation of the Int argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Int value. + * @return a reference to this object. + */ + def insert(at: Int, x: Int): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Inserts the string representation of the Long argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Long value. + * @return a reference to this object. + */ + def insert(at: Int, x: Long): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Inserts the string representation of the Float argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Float value. + * @return a reference to this object. + */ + def insert(at: Int, x: Float): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Inserts the string representation of the Double argument + * into this sequence. + *

+ *

+ * The offset argument must be greater than or equal to 0, and less than + * or equal to the length of this sequence. + *

+ * + * @param at the offset position. + * @param x a Double value. + * @return a reference to this object. + */ + def insert(at: Int, x: Double): StringBuilder = + insert(at, String.valueOf(x)) + + /**

+ * Returns the index within this string of the first occurrence of the + * specified substring. The integer returned is the smallest value + * k such that: + *

+ *
+   *  this.toString().startsWith(str, k)
+ *
+ *

+ * is true. + *

+ * + * @param str any string. + * @return if the string argument occurs as a substring within this + * object, then the index of the first character of the first + * such substring is returned; if it does not occur as a + * substring, -1 is returned. + * @throws NullPointerException if str is null. + */ + def indexOf(str: String): Int = indexOf(str, 0) + + /**

+ * Returns the index within this string of the first occurrence of the + * specified substring, starting at the specified index. The integer + * returned is the smallest value k for which: + *

+   *    k >= Math.min(fromIndex, str.length()) &&
+   *                   this.toString().startsWith(str, k)
+ *

+ * If no such value of k exists, then -1 + * is returned. + *

+ * + * @param str the substring for which to search. + * @param fromIndex the index from which to start the search. + * @return the index within this string of the first occurrence + * of the specified substring, starting at the specified index. + */ + def indexOf(str: String, fromIndex: Int): Int = + StringBuilder.indexOf(value, 0, count, str.toCharArray, 0, str.length(), fromIndex) + + /**

+ * Returns the index within this string of the rightmost occurrence + * of the specified substring. The rightmost empty string "" is + * considered to occur at the index value this.length(). + * The returned index is the largest value k such that + *

+ *
+   *  this.toString().startsWith(str, k)
+ *
+ *

+ * is true. + *

+ * + * @param str the substring to search for. + * @return if the string argument occurs one or more times as a substring + * within this object, then the index of the first character of + * the last such substring is returned. If it does not occur as + * a substring, -1 is returned. + * @throws NullPointerException if str is null. + */ + def lastIndexOf(str: String): Int = lastIndexOf(str, count) + + /**

+ * Returns the index within this string of the last occurrence of the + * specified substring. The integer returned is the largest value + * k such that: + *

+   *    k <= Math.min(fromIndex, str.length()) &&
+   *                   this.toString().startsWith(str, k)
+ *

+ * If no such value of k exists, then -1 + * is returned. + *

+ * + * @param str the substring to search for. + * @param fromIndex the index to start the search from. + * @return the index within this sequence of the last occurrence + * of the specified substring. + */ + def lastIndexOf(str: String, fromIndex: Int): Int = + StringBuilder.lastIndexOf(value, 0, count, str.toCharArray, 0, str.length(), fromIndex) + + /**

+ * Causes this character sequence to be replaced by the reverse of the + * sequence. If there are any surrogate pairs included in the sequence, + * these are treated as single characters for the reverse operation. + * Thus, the order of the high-low surrogates is never reversed. + *

+ *

+ * Let n be the character length of this character sequence + * (not the length in Char values) just prior to + * execution of the reverse method. Then the + * character at index k in the new character sequence is + * equal to the character at index n-k-1 in the old + * character sequence. + *

+ * + * @return a reference to this object. + */ + def reverse(): StringBuilder = { + var hasSurrogate = false + val n = count - 1 + var j = (n-1) >> 1 + while (j >= 0) { + val temp = value(j) + val temp2 = value(n - j) + if (!hasSurrogate) + hasSurrogate = + (temp >= StringBuilder.MIN_SURROGATE && temp <= StringBuilder.MAX_SURROGATE) || + (temp2 >= StringBuilder.MIN_SURROGATE && temp2 <= StringBuilder.MAX_SURROGATE) + value(j) = temp2 + value(n - j) = temp + j -= 1 + } + if (hasSurrogate) { + // Reverse back all valid surrogate pairs + var i = 0 + while (i < count - 1) { + val c2 = value(i) + if (StringBuilder.isLowSurrogate(c2)) { + val c1 = value(i + 1) + if (StringBuilder.isHighSurrogate(c1)) { + value(i) = c1; i += 1 + value(i) = c2 + } + } + i += 1 + } + } + this + } + + /** Returns a string representing the data in this sequence. + * A new String object is allocated and initialized to + * contain the character sequence currently represented by this + * object. This String is then returned. Subsequent + * changes to this sequence do not affect the contents of the + * String. + * + * @return a string representation of this sequence of characters. + */ + override def toString(): String = new String(value, 0, count) + + @throws(classOf[java.io.IOException]) + private def writeObject(s: java.io.ObjectOutputStream) { + s.defaultWriteObject() + s.writeInt(count) + s.writeObject(value) + } + + @throws(classOf[java.io.IOException]) + private def readObject(s: java.io.ObjectInputStream ) { + s.defaultReadObject() + count = s.readInt() + value = s.readObject().asInstanceOf[Array[Char]] + } + +} + + +object StringBuilder { + + private val MIN_HIGH_SURROGATE = '\uD800' + private val MAX_HIGH_SURROGATE = '\uDBFF' + + private val MIN_LOW_SURROGATE = '\uDC00' + private val MAX_LOW_SURROGATE = '\uDFFF' + + // constants java.langCharacter.MIN-/MAX_SURROGATE exist since 1.5 + private val MIN_SURROGATE = MIN_HIGH_SURROGATE + private val MAX_SURROGATE = MAX_LOW_SURROGATE + + // methods java.langCharacter.isLow-/isHighSurrogate exist since 1.5 + private def isLowSurrogate(ch: Char): Boolean = + MIN_LOW_SURROGATE <= ch && ch <= MAX_LOW_SURROGATE + + private def isHighSurrogate(ch: Char): Boolean = + MIN_HIGH_SURROGATE <= ch && ch <= MAX_HIGH_SURROGATE + + // method java.util.Arrays.copyOf exists since 1.6 + private def copyOf(src: Array[Char], newLength: Int): Array[Char] = { + val dest = new Array[Char](newLength) + compat.Platform.arraycopy(src, 0, dest, 0, Math.min(src.length, newLength)) + dest + } + + private def indexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, + target: Array[Char], targetOffset: Int, targetCount: Int, + fromIndex: Int): Int = + if (fromIndex >= sourceCount) + if (targetCount == 0) sourceCount else -1 + else { + val inx = if (fromIndex < 0) 0 else fromIndex + if (targetCount == 0) + inx + else { + val first = target(targetOffset) + val max = sourceOffset + (sourceCount - targetCount) + + var i = sourceOffset + inx + while (i <= max) { + /* Look for first character. */ + if (source(i) != first) { + i += 1 + while (i <= max && source(i) != first) i += 1 + } + /* Found first character, now look at the rest of v2 */ + if (i <= max) { + var j = i + 1 + val end = j + targetCount - 1 + var k = targetOffset + 1 + while (j < end && source(j) == target(k)) { + j += 1 + k += 1 + } + if (j == end) { + /* Found whole string. */ + return i - sourceOffset + } + } // if + i += 1 + } // while + -1 + } + } + + private def lastIndexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int, + target: Array[Char], targetOffset: Int, targetCount: Int, + fromIndex: Int): Int = { + val rightIndex = sourceCount - targetCount + if (fromIndex < 0) return -1 + val inx = if (fromIndex > rightIndex) rightIndex else fromIndex + // Empty string always matches + if (targetCount == 0) return inx + + val strLastIndex = targetOffset + targetCount - 1 + val strLastChar = target(strLastIndex) + val min = sourceOffset + targetCount - 1 + var i = min + fromIndex + + while (true) { + while (i >= min && source(i) != strLastChar) i -= 1 + if (i < min) return -1 + var j = i - 1 + val start = j - (targetCount - 1) + var k = strLastIndex - 1 + var outerWhile = false + while (j > start && !outerWhile) { + if (source(j) != target(k)) { + j -= 1 + k -= 1 + i -= 1 + outerWhile = true + } + } + if (!outerWhile) return start - sourceOffset + 1 + } + -1 + } +} diff --git a/src/library/scala/Symbol.scala b/src/library/scala/Symbol.scala new file mode 100644 index 0000000000..6f7ca958c7 --- /dev/null +++ b/src/library/scala/Symbol.scala @@ -0,0 +1,69 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala + +import scala.collection.jcl + +private[scala] object internedSymbols extends jcl.WeakHashMap[String, ref.WeakReference[Symbol]] + +/**

+ * This class provides a simple way to get unique objects for + * equal strings. Since symbols are interned, they can be compared using + * reference equality. Instances of + * Symbol can be created easily with Scala's built-in +* quote mechanism. + *

+ *

+ * For instance, the Scala + * term 'mysym will invoke the constructor of the + * Symbol class in the following way: + * Symbol("mysym"). + *

+ * + * @author Martin Odersky, Iulian Dragos + * @version 1.8 + */ +@serializable +final class Symbol private (val name: String) { + + /** Converts this symbol to a string. + */ + override def toString(): String = "'" + name + + @throws(classOf[java.io.ObjectStreamException]) + private def readResolve(): Any = Symbol.apply(name) +} + +object Symbol { + + /**

+ * Makes this symbol into a unique reference. + *

+ *

+ * If two interened symbols are equal (i.e. they have the same name) + * then they must be identical (wrt reference equality). + *

+ * + * @return the unique reference to this string. + */ + def apply(name: String): Symbol = internedSymbols.synchronized { + internedSymbols.get(name).flatMap(_.get) match { + case Some(sym) => sym + case _ => + val sym = new Symbol(name) + internedSymbols(name) = new ref.WeakReference(sym) + sym + } + } + + def unapply(other: Symbol): Option[String] = Some(other.name) +} diff --git a/src/library/scala/compat/Platform.scala b/src/library/scala/compat/Platform.scala new file mode 100644 index 0000000000..03cf1d28e2 --- /dev/null +++ b/src/library/scala/compat/Platform.scala @@ -0,0 +1,60 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.compat + + +import java.lang.System +import Predef._ + +object Platform { + + type StackOverflowError = java.lang.StackOverflowError + type ConcurrentModificationException = java.util.ConcurrentModificationException + + /** + * @param src .. + * @param srcPos .. + * @param dest .. + * @param destPos .. + * @param length .. + */ + def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) { + System.arraycopy(src, srcPos, dest, destPos, length) + } + + /** Create array of the same type as arrayInstance with the given + * length. + * + * @param elemClass .. + * @param length .. + * @return .. + */ + def createArray(elemClass: Class[_], length: Int): AnyRef = + java.lang.reflect.Array.newInstance(elemClass, length) + + def arrayclear(arr: Array[Int]) { java.util.Arrays.fill(arr, 0) } + + def getClassForName(name: String): Class[_] = java.lang.Class.forName(name) + + val EOL = System.getProperty("line.separator", "\n") + + def currentTime: Long = System.currentTimeMillis() + + def collectGarbage: Unit = System.gc() + + /** The name of the default character set encoding as a string */ + def defaultCharsetName: String = { + import java.io._ + new OutputStreamWriter(new ByteArrayOutputStream).getEncoding() + } + +} diff --git a/src/library/scala/mobile/Code.scala b/src/library/scala/mobile/Code.scala new file mode 100644 index 0000000000..822a4aaa6c --- /dev/null +++ b/src/library/scala/mobile/Code.scala @@ -0,0 +1,247 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.mobile + + +import java.lang.reflect.{Constructor, Method, Modifier} +import java.lang.NoSuchMethodException + +/** The class Code provides apply methods + * with different arities (actually up to 9 parameters) to invoke + * a function simply by specifying its name and argument types.

+ * + * Example:

+ *    val url = new URL("http://scala-lang.org/classes/examples.jar");
+ *    val obj = new Location(url) create "examples.sort";
+ *    val ar = Array(6, 2, 8, 5, 1);
+ *    obj[Array[Int], Unit]("println")(ar);
+ *    obj[Array[Int], Unit]("sort")(ar);
+ *    obj[Array[Int], Unit]("println")(ar);
+ * + * @see Location + * + * @author Stephane Micheloud + * @version 1.0, 04/05/2004 + */ +class Code(clazz: java.lang.Class[_]) { + + private type JObject = java.lang.Object + + private var instance: JObject = _ + + ///////////////////////////// apply methods /////////////////////////////// + + type AnyClass = Class[T] forSome { type T } + + def apply[R](funName: String) = + () => { + val args = Array[JObject]() + val types = Array[AnyClass]() + applyFun(funName, args, types).asInstanceOf[R] + } + + def apply[A0, R](funName: String) = + (_0: A0) => { + val p = boxValue(_0) + val args = Array(p._1) + val types = Array[AnyClass](p._2) + applyFun(funName, args, types).asInstanceOf[R] + } + + def apply[A0, A1, R](funName: String) = + (_0: A0, _1: A1) => { + val p0 = boxValue(_0) + val p1 = boxValue(_1) + val args = Array(p0._1, p1._1) + val types = Array[AnyClass](p0._2, p1._2) + applyFun(funName, args, types).asInstanceOf[R] + } + + def apply[A0, A1, A2, R](funName: String) = + (_0: A0, _1: A1, _2: A2) => { + val p0 = boxValue(_0) + val p1 = boxValue(_1) + val p2 = boxValue(_2) + val args = Array(p0._1, p1._1, p2._1) + val types = Array[AnyClass](p0._2, p1._2, p2._2) + applyFun(funName, args, types).asInstanceOf[R] + } + + def apply[A0, A1, A2, A3, R](funName: String) = + (_0: A0, _1: A1, _2: A2, _3: A3) => { + val p0 = boxValue(_0) + val p1 = boxValue(_1) + val p2 = boxValue(_2) + val p3 = boxValue(_3) + val args = Array(p0._1, p1._1, p2._1, p3._1) + val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2) + applyFun(funName, args, types).asInstanceOf[R] + } + + def apply[A0, A1, A2, A3, A4, R](funName: String) = + (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4) => { + val p0 = boxValue(_0) + val p1 = boxValue(_1) + val p2 = boxValue(_2) + val p3 = boxValue(_3) + val p4 = boxValue(_4) + val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1) + val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2) + applyFun(funName, args, types).asInstanceOf[R] + } + + def apply[A0, A1, A2, A3, A4, A5, R](funName: String) = + (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5) => { + val p0 = boxValue(_0) + val p1 = boxValue(_1) + val p2 = boxValue(_2) + val p3 = boxValue(_3) + val p4 = boxValue(_4) + val p5 = boxValue(_5) + val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1) + val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2) + applyFun(funName, args, types).asInstanceOf[R] + } + + def apply[A0, A1, A2, A3, A4, A5, A6, R](funName: String) = + (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6) => { + val p0 = boxValue(_0) + val p1 = boxValue(_1) + val p2 = boxValue(_2) + val p3 = boxValue(_3) + val p4 = boxValue(_4) + val p5 = boxValue(_5) + val p6 = boxValue(_6) + val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1) + val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2) + applyFun(funName, args, types).asInstanceOf[R] + } + + def apply[A0, A1, A2, A3, A4, A5, A6, A7, R](funName: String) = + (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6, _7: A7) => { + val p0 = boxValue(_0) + val p1 = boxValue(_1) + val p2 = boxValue(_2) + val p3 = boxValue(_3) + val p4 = boxValue(_4) + val p5 = boxValue(_5) + val p6 = boxValue(_6) + val p7 = boxValue(_7) + val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1, p7._1) + val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2, p7._2) + applyFun(funName, args, types).asInstanceOf[R] + } + + def apply[A0, A1, A2, A3, A4, A5, A6, A7, A8, R](funName: String) = + (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6, _7: A7, _8: A8) => { + val p0 = boxValue(_0) + val p1 = boxValue(_1) + val p2 = boxValue(_2) + val p3 = boxValue(_3) + val p4 = boxValue(_4) + val p5 = boxValue(_5) + val p6 = boxValue(_6) + val p7 = boxValue(_7) + val p8 = boxValue(_8) + val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1, p7._1, p8._1) + val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2, p7._2, p8._2) + applyFun(funName, args, types).asInstanceOf[R] + } + + ////////////////////// private functions /////////////////////// + + private def boxValue(value: Any) = value match { + /** Should use java.lang.Byte.valueOf(Byte), but only available + * in Java 1.5 and above. */ + case x: Byte => (new java.lang.Byte(x), java.lang.Byte.TYPE) + case x: Boolean => (java.lang.Boolean.valueOf(x), java.lang.Boolean.TYPE) + /** Should use java.lang.Character.valueOf(Char), but only available + * in Java 1.5 and above. */ + case x: Char => (new java.lang.Character(x), java.lang.Character.TYPE) + /** Should use java.lang.Short.valueOf(Short), but only available + * in Java 1.5 and above. */ + case x: Short => (new java.lang.Short(x), java.lang.Short.TYPE) + /** Should use java.lang.Integer.valueOf(Int), but only available + * in Java 1.5 and above. */ + case x: Int => (new java.lang.Integer(x), java.lang.Integer.TYPE) + /** Should use java.lang.Long.valueOf(Long), but only available + * in Java 1.5 and above. */ + case x: Long => (new java.lang.Long(x), java.lang.Long.TYPE) + case x: Float => (new java.lang.Float(x), java.lang.Float.TYPE) + case x: Double => (new java.lang.Double(x), java.lang.Double.TYPE) + case _ => + val x = value.asInstanceOf[JObject] + (x, x.getClass()) + } + + private def isConstructorName(methName: String) = { + var className = clazz.getName() + val classInx = className.lastIndexOf(".") + val methInx = methName.lastIndexOf(".") + if (classInx > 0 && methInx < 0) + className = className.substring(classInx + 1, className.length()) + methName.equals(className) + } + + private def applyFun(methName: String, args: Array[JObject], + argTypes: Array[Class[T] forSome { type T }]): JObject = { + try { + val method = clazz.getMethod(methName, argTypes) + var obj: JObject = null + if (! Modifier.isStatic(method.getModifiers())) { + if (instance eq null) { + instance = try { + clazz.newInstance().asInstanceOf[AnyRef] + } catch { case _ => + val cs = clazz.getConstructors() +//Console.println("cs.length=" + cs.length); + if (cs.length > 0) { + cs(0).newInstance(Array("")).asInstanceOf[AnyRef] + } else { + error("class " + clazz.getName() + " has no public constructor") + null + } + } + } + obj = instance + } + val result = method.invoke(obj, args) + if (result eq null) ().asInstanceOf[JObject] else result + } + catch { + case me: NoSuchMethodException => + if (isConstructorName(methName)) { + try { + val cstr = clazz.getConstructor(argTypes) + instance = cstr.newInstance(args).asInstanceOf[AnyRef] + instance + } + catch { + case e: Exception => + Console.println(e.getMessage()) + e.printStackTrace() + } + } + else { + Console.println(me.getMessage()) + me.printStackTrace() + } + null + case e: Exception => + Console.println(e.getMessage()) + e.printStackTrace() + null + } + } + +} + diff --git a/src/library/scala/mobile/Location.scala b/src/library/scala/mobile/Location.scala new file mode 100644 index 0000000000..1048b403e7 --- /dev/null +++ b/src/library/scala/mobile/Location.scala @@ -0,0 +1,100 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.mobile + + +import java.lang.ClassLoader +import java.net._ + +import scala.collection.mutable._ + +/** The class Location provides a create + * method to instantiate objects from a network location by + * specifying the URL address of the jar/class file.

+ * + * An update of the jar/class file should not break your code as far + * as the used class names and method signatures are the same.

+ * + * Example:

+ *    val url = new URL("http://scala-lang.org/classes/examples.jar");
+ *    val obj = new Location(url) create "examples.sort";
+ * + * @see Code + * + * @author Stephane Micheloud + * @version 1.0, 04/05/2004 + */ +class Location(url: URL) { + + /** A cache containing all class loaders of this location. + */ + private var lcache: Map[URL, ClassLoader] = new HashMap + + /** The class loader associated with this location. + */ + private val loader = if (url eq null) + ClassLoader.getSystemClassLoader() + else + lcache.get(url) match { + case Some(cl) => + cl + case _ => + val cl = new URLClassLoader(Array(url)) + lcache(url) = cl + cl + } + + /** A cache containing all classes of this location. + */ + private var ccache: Map[String, java.lang.Class[T] forSome { type T }] = new HashMap + + /** Return the code description for the string className + * at this location. + * + * @param classname the name of the class + * @return the code description corresponding to + * className. + */ + def create(className: String) = new Code( + ccache.get(className) match { + case Some(clazz) => + clazz + case _ => + val clazz = if (loader.loadClass(className).isInterface()) { + // Scala source: class A { ... }; + // Java bytecode: interface A.class + class A$class.class + loader.loadClass(className + "$class") + } + else { + // Scala source: object A { ... }; + // Java bytecode: interface A.class + class A$.class + loader.loadClass(className + "$") + } + ccache(className) = clazz + clazz + } + ) + +} + +/** The object Location can be used to instantiate + * objects on the same Java VM. It is just provided to illustrate + * the special case where resources are available locally.

+ * + * Example:

+ *    val obj = Location.create("xcode.Math");
+ *    val x = obj[Int, Int]("square")(5);
+ * + * @author Stephane Micheloud + * @version 1.0, 04/05/2004 + */ +object Location extends Location(null) diff --git a/src/library/scala/ref/PhantomReference.scala b/src/library/scala/ref/PhantomReference.scala new file mode 100644 index 0000000000..5be4e39117 --- /dev/null +++ b/src/library/scala/ref/PhantomReference.scala @@ -0,0 +1,20 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +package scala.ref + +/** + * @author Sean McDirmid + */ +class PhantomReference[+T <: AnyRef](value: T, queue: ReferenceQueue[T]) extends ReferenceWrapper[T] { + val underlying: java.lang.ref.PhantomReference[_ <: T] = + new java.lang.ref.PhantomReference[T](value, queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]]) +} + diff --git a/src/library/scala/ref/Reference.scala b/src/library/scala/ref/Reference.scala new file mode 100644 index 0000000000..f36d355831 --- /dev/null +++ b/src/library/scala/ref/Reference.scala @@ -0,0 +1,27 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +package scala.ref + +/** + * @see java.lang.ref.Reference + * @author Sean McDirmid + */ +trait Reference[+T <: AnyRef] extends Function0[T] { + @deprecated def isValid: Boolean + /** return the underlying value */ + def apply(): T + /** return Some underlying if it hasn't been collected, otherwise None */ + def get : Option[T] + override def toString = get.map(_.toString).getOrElse("") + def clear(): Unit + def enqueue(): Boolean + def isEnqueued(): Boolean +} diff --git a/src/library/scala/ref/ReferenceQueue.scala b/src/library/scala/ref/ReferenceQueue.scala new file mode 100644 index 0000000000..1a4e9ea2e0 --- /dev/null +++ b/src/library/scala/ref/ReferenceQueue.scala @@ -0,0 +1,27 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +package scala.ref + +/** + * @author Sean McDirmid + */ +class ReferenceQueue[+T <: AnyRef] { + private[ref] val underlying: java.lang.ref.ReferenceQueue[_ <: T] = new java.lang.ref.ReferenceQueue[T] + override def toString = underlying.toString + protected class Wrapper[U <: AnyRef](val underlying: java.lang.ref.Reference[U]) extends ReferenceWrapper[U] + protected def Wrapper[U <: AnyRef](ref: java.lang.ref.Reference[U]) = ref match { + case null => None + case ref => Some(new Wrapper(ref)) + } + def poll: Option[Reference[T]] = Wrapper(underlying.poll) + def remove: Option[Reference[T]] = Wrapper(underlying.remove) + def remove(timeout: Long): Option[Reference[T]] = Wrapper(underlying.remove(timeout)) +} diff --git a/src/library/scala/ref/ReferenceWrapper.scala b/src/library/scala/ref/ReferenceWrapper.scala new file mode 100644 index 0000000000..b93e98b880 --- /dev/null +++ b/src/library/scala/ref/ReferenceWrapper.scala @@ -0,0 +1,33 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +package scala.ref + +/** + * @author Sean McDirmid + */ +trait ReferenceWrapper[+T <: AnyRef] extends Reference[T] with Proxy { + val underlying: java.lang.ref.Reference[_ <: T] + @deprecated def isValid = underlying.get != null + override def get = { + val ret = underlying.get.asInstanceOf[T] + if (ret eq null) None else Some(ret) + } + def apply() = { + val ret = underlying.get.asInstanceOf[T] + if (ret eq null) throw new NoSuchElementException + ret + } + def clear = underlying.clear + def enqueue = underlying.enqueue + def isEnqueued = underlying.isEnqueued + + def self = underlying +} diff --git a/src/library/scala/ref/SoftReference.scala b/src/library/scala/ref/SoftReference.scala new file mode 100644 index 0000000000..fc6313f6ef --- /dev/null +++ b/src/library/scala/ref/SoftReference.scala @@ -0,0 +1,21 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +package scala.ref + +/** + * @author Sean McDirmid + */ +class SoftReference[+T <: AnyRef](value : T, queue : ReferenceQueue[T]) extends ReferenceWrapper[T] { + def this(value : T) = this(value, null); + val underlying: java.lang.ref.SoftReference[_ <: T] = + if (queue == null) new java.lang.ref.SoftReference[T](value); + else new java.lang.ref.SoftReference[T](value, queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]]) +} diff --git a/src/library/scala/ref/WeakReference.scala b/src/library/scala/ref/WeakReference.scala new file mode 100644 index 0000000000..0d2e29d601 --- /dev/null +++ b/src/library/scala/ref/WeakReference.scala @@ -0,0 +1,21 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2006-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +package scala.ref + +/** + * @author Sean McDirmid + */ +class WeakReference[+T <: AnyRef](value: T, queue: ReferenceQueue[T]) extends ReferenceWrapper[T] { + def this(value: T) = this(value, null) + val underlying: java.lang.ref.WeakReference[_ <: T] = + if (queue == null) new java.lang.ref.WeakReference[T](value) + else new java.lang.ref.WeakReference[T](value, queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]]) +} diff --git a/src/library/scala/testing/Benchmark.scala b/src/library/scala/testing/Benchmark.scala new file mode 100644 index 0000000000..bd69de430a --- /dev/null +++ b/src/library/scala/testing/Benchmark.scala @@ -0,0 +1,97 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.testing + + +import compat.Platform + +/**

+ * Benchmark can be used to quickly turn an existing + * class into a benchmark. Here is a short example: + *

+ *  object sort1 extends Sorter with Benchmark {
+ *    def run = sort(List.range(1, 1000))
+ *  }
+ *  
+ *

+ * The run method has to be defined by the user, who + * will perform the timed operation there. + * Run the benchmark as follows: + *

+ *
+ *  > scala sort1 5 times.log
+ *  
+ *

+ * This will run the benchmark 5 times and log the execution times in + * a file called times.log + *

+ * + * @author Iulian Dragos, Burak Emir + */ +trait Benchmark { + + /** this method should be implemented by the concrete benchmark */ + def run() + + var multiplier = 1 + + /** Run the benchmark the specified number of times + * and return a list with the execution times in milliseconds + * in reverse order of the execution + * + * @param noTimes ... + * @return ... + */ + def runBenchmark(noTimes: Int): List[Long] = + for (i <- List.range(1, noTimes + 1)) yield { + val startTime = Platform.currentTime + var i = 0; while (i < multiplier) { + run() + i += 1 + } + val stopTime = Platform.currentTime + Platform.collectGarbage + + stopTime - startTime + } + + /** a string that is written at the beginning of the output line + * that contains the timings. By default, this is the class name. + */ + def prefix: String = getClass().getName() + + /** + * The entry point. It takes two arguments (n), (name) + * and an optional argument multiplier (mult). + * (n) is the number of consecutive runs, (name) the name + * of a log file where to append the times. + * if (mult) is present, the same thing is repeated (mult) + * times. + */ + def main(args: Array[String]) { + if (args.length > 1) { + val logFile = new java.io.FileWriter(args(1), true) // append, not overwrite + if (args.length >= 3) + multiplier = args(2).toInt + logFile.write(prefix) + for (t <- runBenchmark(args(0).toInt)) + logFile.write("\t\t" + t) + + logFile.write(Platform.EOL) + logFile.flush() + } else { + Console.println("Usage: scala benchmarks.program ") + Console.println(" or: scala benchmarks.program ") + } + } +} + diff --git a/src/library/scala/testing/SUnit.scala b/src/library/scala/testing/SUnit.scala new file mode 100644 index 0000000000..1a87c64b0e --- /dev/null +++ b/src/library/scala/testing/SUnit.scala @@ -0,0 +1,253 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.testing + +import scala.collection.mutable.ArrayBuffer + +/** + *

+ * Unit testing methods in the spirit of + * JUnit framework. + *

+ *

+ * Use these classes like this: + *

+ *
+ * import scala.testing.SUnit
+ * import SUnit._
+ *
+ * class MyTest(n: String) extends TestCase(n) {
+ *
+ *   override def runTest() = n match {
+ *     case "myTest1" => assertTrue(true)
+ *     case "myTest2" => assertTrue("hello", false)
+ *   }
+ * }
+ *
+ * val r = new TestResult()
+ * suite.run(r)
+ * for (tf <- r.failures()) {
+ *   println(tf.toString())
+ * }
+ * 
+ *

+ * The trait TestConsoleMain contains this code as + * a main method, for convenience. + *

+ * + * @author Burak Emir + */ +object SUnit { + + /**

+ * Convenience trait, mix it in a TestMain object and + * implement "suite" to get this code. + *

+   *  val r = new TestResult()
+   *  suite.run(r)
+   *  for (val tf <- r.failures()) {
+   *    println(tf.toString())
+   *  
+ */ + trait TestConsoleMain { + def suite: TestSuite + def main(args: Array[String]) { + val r = new TestResult() + suite.run(r) + for (tf <- r.failures()) + println(tf.toString()) + } + } + + /** a Test can be run with its result being collected */ + trait Test { + def run(r: TestResult): Unit + } + + /** The class TestCase defines the fixture to run multiple + * tests. + * + * @param name ... + */ + abstract class TestCase(val name: String) extends Test with Assert { + + protected def runTest(): Unit + + def run(r: TestResult) { + try { + runTest() + } catch { + case t:Throwable => r.addFailure(this, t) + } + } + + def setUp() {} + + def tearDown() {} + + override def toString() = name + } + + /** The class TestFailure collects a failed test together + * with the thrown exception. + */ + class TestFailure(val failedTest: Test, val thrownException: Throwable) { + + def this(p: (Test, Throwable)) = this(p._1, p._2) + + override def toString() = + failedTest.toString() + " failed due to " + thrownException.toString() + + def trace(): String = thrownException.getStackTraceString + + } + + /** a TestResult collects the result of executing a test case */ + class TestResult { + val buf = new ArrayBuffer[(Test, Throwable)]() + + def addFailure(test: Test, t: Throwable) { + buf += (test, t) + } + + def failureCount() = + buf.length + + def failures() = + buf.elements map { x => new TestFailure(x) } + } + + /** The class TestSuite runs a composite of test cases. + */ + class TestSuite(tests: Test*) extends Test { + + def this(names: Seq[String], constr: String => Test) = + this((names map constr):_*) + + val buf = new ArrayBuffer[Test]() + + buf ++= tests + + def addTest(t: Test) { + buf += t + } + + def run(r: TestResult) { + for (t <- buf) t.run(r) + } + } + + /** an AssertFailed is thrown for a failed assertion */ + case class AssertFailed(msg: String, stackTrace: Boolean) extends RuntimeException { + private val msg0 = if (stackTrace) { + import java.io._ + val wrt = new StringWriter + printStackTrace(new PrintWriter(wrt)) + wrt.toString + } else msg + override def toString() = + if (msg0 eq null) "failed assertion: " + msg else msg0 + } + + /** this class defines useful assert methods */ + trait Assert { + + def enableStackTrace: Boolean = true + + /** fails if ! actual.sameElements(expected) */ + def assertSameElements[A](actual: Seq[A], expected: Seq[A]) { + if (! actual.sameElements(expected)) + fail("(no message)", actual.toString, expected.toString) + } + + /** fails if expected != actual */ + def assertEquals[A](msg: String, expected: A, actual: A) { + if (expected != actual) fail(msg, expected, actual) + } + + /** fails if expected != actual */ + def assertEquals[A](expected: A, actual: A) { + assertEquals("(no message)", expected, actual) + } + + /** succeeds if actual is false */ + def assertFalse(msg: String, actual: Boolean) { + assertEquals(msg, false, actual) + } + + /** succeeds if actual is false */ + def assertFalse(actual: Boolean) { + assertFalse("(no message)", actual) + } + + /** fails if null eq actual */ + def assertNotNull(msg: String, actual: AnyRef) { + if (null eq actual) fail(msg) + } + + /** fails if null eq actual */ + def assertNotNull(actual: AnyRef): Unit = + assertNotNull("(no message)", actual) + + /** fails if expected eq actual */ + def assertNotEq(msg: String, expected: AnyRef, actual: AnyRef) { + if (expected eq actual) fail(msg) + } + + /** fails if expected eq actual */ + def assertNotEq(expected: AnyRef, actual: AnyRef) { + assertNotEq("(no message)", expected, actual) + } + + /** fails if actual ne null */ + def assertNull(msg: String, actual: AnyRef) { + if (null ne actual) fail(msg) + } + + /** fails if actual ne null */ + def assertNull(actual: AnyRef) { + assertNull("(no message)", actual) + } + + /** fails if expected ne actual */ + def assertEq(msg: String, expected: AnyRef, actual: AnyRef) { + if (expected ne actual) fail(msg) + } + + /** fails if expected ne actual */ + def assertEq(expected: AnyRef, actual: AnyRef) { + assertEq("(no message)", expected, actual) + } + + /** succeeds if actual == true */ + def assertTrue(msg: String, actual: Boolean) { + assertEquals(msg, true, actual) + } + + /** succeeds if actual == true */ + def assertTrue(actual: Boolean) { + assertTrue("(no message)", actual) + } + + /** throws AssertFailed with given message msg. + */ + def fail(msg: String) { + throw AssertFailed(msg, enableStackTrace) + } + + def fail[A](msg: String, expected: A, actual: A) { + throw AssertFailed(msg + + ", expected: " + expected + + ", actual: " + actual, enableStackTrace) + } + } +} diff --git a/src/library/scala/text/Document.scala b/src/library/scala/text/Document.scala new file mode 100644 index 0000000000..39aea9ec81 --- /dev/null +++ b/src/library/scala/text/Document.scala @@ -0,0 +1,122 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2007, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + + +package scala.text + + +import java.io.Writer + +case object DocNil extends Document +case object DocBreak extends Document +case class DocText(txt: String) extends Document +case class DocGroup(doc: Document) extends Document +case class DocNest(indent: Int, doc: Document) extends Document +case class DocCons(hd: Document, tl: Document) extends Document + +/** + * A basic pretty-printing library, based on Lindig's strict version + * of Wadler's adaptation of Hughes' pretty-printer. + * + * @author Michel Schinz + * @version 1.0 + */ +abstract class Document { + def ::(hd: Document): Document = DocCons(hd, this) + def ::(hd: String): Document = DocCons(DocText(hd), this) + def :/:(hd: Document): Document = hd :: DocBreak :: this + def :/:(hd: String): Document = hd :: DocBreak :: this + + /** + * Format this document on writer and try to set line + * breaks so that the result fits in width columns. + * + * @param width ... + * @param writer ... + */ + def format(width: Int, writer: Writer) { + type FmtState = (Int, Boolean, Document) + + def fits(w: Int, state: List[FmtState]): Boolean = state match { + case _ if w < 0 => + false + case List() => + true + case (_, _, DocNil) :: z => + fits(w, z) + case (i, b, DocCons(h, t)) :: z => + fits(w, (i,b,h) :: (i,b,t) :: z) + case (_, _, DocText(t)) :: z => + fits(w - t.length(), z) + case (i, b, DocNest(ii, d)) :: z => + fits(w, (i + ii, b, d) :: z) + case (_, false, DocBreak) :: z => + fits(w - 1, z) + case (_, true, DocBreak) :: z => + true + case (i, _, DocGroup(d)) :: z => + fits(w, (i, false, d) :: z) + } + + def spaces(n: Int) { + var rem = n + while (rem >= 16) { writer write " "; rem -= 16 } + if (rem >= 8) { writer write " "; rem -= 8 } + if (rem >= 4) { writer write " "; rem -= 4 } + if (rem >= 2) { writer write " "; rem -= 2} + if (rem == 1) { writer write " " } + } + + def fmt(k: Int, state: List[FmtState]): Unit = state match { + case List() => () + case (_, _, DocNil) :: z => + fmt(k, z) + case (i, b, DocCons(h, t)) :: z => + fmt(k, (i, b, h) :: (i, b, t) :: z) + case (i, _, DocText(t)) :: z => + writer write t + fmt(k + t.length(), z) + case (i, b, DocNest(ii, d)) :: z => + fmt(k, (i + ii, b, d) :: z) + case (i, true, DocBreak) :: z => + writer write "\n" + spaces(i); + fmt(i, z) + case (i, false, DocBreak) :: z => + writer write " " + fmt(k + 1, z) + case (i, b, DocGroup(d)) :: z => + val fitsFlat = fits(width - k, (i, false, d) :: z) + fmt(k, (i, !fitsFlat, d) :: z) + } + + fmt(0, (0, false, DocGroup(this)) :: Nil) + } +} + +object Document { + /** The empty document */ + def empty = DocNil + + /** A break, which will either be turned into a space or a line break */ + def break = DocBreak + + /** A document consisting of some text literal */ + def text(s: String): Document = DocText(s) + + /** + * A group, whose components will either be printed with all breaks + * rendered as spaces, or with all breaks rendered as line breaks. + */ + def group(d: Document): Document = DocGroup(d) + + /** A nested document, which will be indented as specified. */ + def nest(i: Int, d: Document): Document = DocNest(i, d) +} diff --git a/src/library/scala/throws.scala b/src/library/scala/throws.scala new file mode 100644 index 0000000000..463a01b3f9 --- /dev/null +++ b/src/library/scala/throws.scala @@ -0,0 +1,30 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2002-2008, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +*/ + +// $Id$ + + +package scala + +import Predef._ + +/**

+ * Annotation for specifying the exceptions thrown by a method. + * For example: + *

+ *    class Reader(fname: String) {
+ *      private val in =
+ *        new BufferedReader(new FileReader(fname))
+ *      @throws(classOf[IOException])
+ *      def read() = in.read()
+ *    }
+ * + * @author Nikolay Mihaylov + * @version 1.0, 19/05/2006 + */ +class throws(clazz: Class[_]) extends Annotation -- cgit v1.2.3