diff --git a/examples/.idea/ant.xml b/examples/.idea/ant.xml deleted file mode 100644 index 2581ca3fe84..00000000000 --- a/examples/.idea/ant.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/examples/.idea/compiler.xml b/examples/.idea/compiler.xml deleted file mode 100644 index 97c9ca5c8b0..00000000000 --- a/examples/.idea/compiler.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/examples/.idea/copyright/profiles_settings.xml b/examples/.idea/copyright/profiles_settings.xml deleted file mode 100644 index 3572571ad83..00000000000 --- a/examples/.idea/copyright/profiles_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/examples/.idea/encodings.xml b/examples/.idea/encodings.xml deleted file mode 100644 index e206d70d859..00000000000 --- a/examples/.idea/encodings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/examples/.idea/misc.xml b/examples/.idea/misc.xml deleted file mode 100644 index acfed7b332c..00000000000 --- a/examples/.idea/misc.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - http://www.w3.org/1999/xhtml - - - - - - - - diff --git a/examples/.idea/modules.xml b/examples/.idea/modules.xml deleted file mode 100644 index 7fedc34aae5..00000000000 --- a/examples/.idea/modules.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/examples/.idea/projectCodeStyle.xml b/examples/.idea/projectCodeStyle.xml deleted file mode 100644 index c621643589d..00000000000 --- a/examples/.idea/projectCodeStyle.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - diff --git a/examples/.idea/uiDesigner.xml b/examples/.idea/uiDesigner.xml deleted file mode 100644 index 3b000203088..00000000000 --- a/examples/.idea/uiDesigner.xml +++ /dev/null @@ -1,125 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/.idea/vcs.xml b/examples/.idea/vcs.xml deleted file mode 100644 index 275077f8255..00000000000 --- a/examples/.idea/vcs.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/examples/example-vfs/.idea/ant.xml b/examples/example-vfs/.idea/ant.xml deleted file mode 100644 index 2581ca3fe84..00000000000 --- a/examples/example-vfs/.idea/ant.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/examples/example-vfs/.idea/compiler.xml b/examples/example-vfs/.idea/compiler.xml deleted file mode 100644 index a1b41c52c72..00000000000 --- a/examples/example-vfs/.idea/compiler.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - diff --git a/examples/example-vfs/.idea/copyright/profiles_settings.xml b/examples/example-vfs/.idea/copyright/profiles_settings.xml deleted file mode 100644 index 3572571ad83..00000000000 --- a/examples/example-vfs/.idea/copyright/profiles_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/examples/example-vfs/.idea/encodings.xml b/examples/example-vfs/.idea/encodings.xml deleted file mode 100644 index e206d70d859..00000000000 --- a/examples/example-vfs/.idea/encodings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/examples/example-vfs/.idea/libraries/KotlinRuntime.xml b/examples/example-vfs/.idea/libraries/KotlinRuntime.xml deleted file mode 100644 index a23ee66a5c9..00000000000 --- a/examples/example-vfs/.idea/libraries/KotlinRuntime.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/examples/example-vfs/.idea/misc.xml b/examples/example-vfs/.idea/misc.xml deleted file mode 100644 index c1273a20eab..00000000000 --- a/examples/example-vfs/.idea/misc.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - http://www.w3.org/1999/xhtml - - - - - - diff --git a/examples/example-vfs/.idea/modules.xml b/examples/example-vfs/.idea/modules.xml deleted file mode 100644 index 5cc489aa93a..00000000000 --- a/examples/example-vfs/.idea/modules.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/examples/example-vfs/.idea/scopes/scope_settings.xml b/examples/example-vfs/.idea/scopes/scope_settings.xml deleted file mode 100644 index 922003b8433..00000000000 --- a/examples/example-vfs/.idea/scopes/scope_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/examples/example-vfs/.idea/uiDesigner.xml b/examples/example-vfs/.idea/uiDesigner.xml deleted file mode 100644 index 3b000203088..00000000000 --- a/examples/example-vfs/.idea/uiDesigner.xml +++ /dev/null @@ -1,125 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/example-vfs/.idea/vcs.xml b/examples/example-vfs/.idea/vcs.xml deleted file mode 100644 index 9ab281ac88c..00000000000 --- a/examples/example-vfs/.idea/vcs.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/examples/example-vfs/example-vfs.iml b/examples/example-vfs/example-vfs.iml deleted file mode 100644 index e15dafa3168..00000000000 --- a/examples/example-vfs/example-vfs.iml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/examples/example-vfs/src/FileSystem.kt b/examples/example-vfs/src/FileSystem.kt deleted file mode 100644 index 1f27aaadca9..00000000000 --- a/examples/example-vfs/src/FileSystem.kt +++ /dev/null @@ -1,139 +0,0 @@ -package org.jetbrains.jet.samples.vfs; - -import kotlin.concurrent.* -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import org.jetbrains.jet.samples.vfs.utils.*; -import java.util.concurrent.locks.Lock -import java.io.File -import java.util.List -import java.util.ArrayList -import java.util.HashMap -import java.util.Arrays -import java.util.Map - -import kotlin.util.* -import java.util.TimerTask - -/** - * File system singleton. To work with virtual file system, read/write locks should be - * acquired: use read() and write() higher-order functions. - */ -public object FileSystem { - private val lock = ReentrantReadWriteLock() - internal val watchedDirectories = ArrayList - - /** - * Mapping from virtual files to metainformation - */ - internal val fileToInfo = HashMap() - private val listeners = ArrayList() - - /** - * Returns corresponding virtual file for java.io.File. - * - * @param ioFile file - */ - public fun getFileByIoFile(ioFile : File) : VirtualFile { - FileSystem.assertCanRead() - return PhysicalVirtualFile(ioFile.getAbsolutePath()!!.toSystemIndependentPath()) - } - - /** - * Returns virtual file for path to it. - * - * @param path path to file - */ - public fun getFileByPath(path : String) : VirtualFile { - return getFileByIoFile(File(path)) - } - - /** - * Runs function with read lock. - */ - public inline fun read(task : () -> T) : T { - return lock.read(task) - } - - /** - * Runs function with write lock. - */ - public inline fun write(task : () -> T) : T { - return lock.write(task) - } - - /** - * Adds directory to list of watched directories. Watched directories are - * periodically refreshed and corresponding events are sent to file system listeners. - * - * @param dir directory which should be watched - */ - public fun addWatchedDirectory(dir : VirtualFile) { - assertCanRead() - if (dir.isDirectory) { - watchedDirectories.add(dir) - scanAndAddRecursivelyNoEvents(dir) - - RefreshQueue.scheduleRefresh() - } - } - - /* Scans file recursively and adds info about it to fileToInfo map */ - private fun scanAndAddRecursivelyNoEvents(file : VirtualFile) { - require(FileSystem.fileToInfo[file.path] == null) - - val fileInfo = VirtualFileInfo(file) - FileSystem.fileToInfo[file] = fileInfo - fileInfo.children.forEach{ scanAndAddRecursivelyNoEvents(it) } - } - - internal inline fun assertCanRead() { - check(lock.getReadHoldCount() != 0 || lock.isWriteLockedByCurrentThread()) - } - - internal inline fun assertCanWrite() { - check(lock.isWriteLockedByCurrentThread()) - } - - /** - * Adds file system listener which should be notified about changing of file system. - */ - public fun addVirtualFileListener(listener : VirtualFileListener) { - listeners.add(listener) - } - - /** - * Adds file system listener which should be notified about changing of file system. - */ - public fun addVirtualFileListener(listener : (VirtualFileEvent)->Unit) : VirtualFileListener { - val vfl = SimpleVirtualFileListener(listener) - addVirtualFileListener(vfl) - return vfl - } - - /** - * Removes file system listener. - */ - public fun removeVirtualFileListener(listener : VirtualFileListener) { - listeners.remove(listener) - } - - /* Notifies all listeners */ - internal fun notifyEventHappened(event : VirtualFileEvent) { - for (listener in listeners) { - listener.eventHappened(event) - } - } -} - -private class VirtualFileInfo(file : VirtualFile) { - /* Last modification time */ - var lastModified : Long = 0 - /* List of known children */ - val children : List = ArrayList; - - { - children.addAll(file.children) - lastModified = file.modificationTime - } -} diff --git a/examples/example-vfs/src/Main.kt b/examples/example-vfs/src/Main.kt deleted file mode 100644 index 0e32b334e53..00000000000 --- a/examples/example-vfs/src/Main.kt +++ /dev/null @@ -1,36 +0,0 @@ -package org.jetbrains.jet.samples.vfs.sandbox; - -import org.jetbrains.jet.samples.vfs.*; -import java.io.InputStreamReader -import java.util.Scanner - -/** - * Receives list of directories which should be watched, adds them to virtual file system, - * adds virtual file system listener and waits for 1 minutes, printing out all received event. - */ -fun main(args : Array) { - if (args.size == 0) { - println("Provide list of watched directories as command line arguments") - return - } - - // add watched directory - FileSystem.write { - for (arg in args) { - val virtualFile = FileSystem.getFileByPath(arg) - FileSystem.addWatchedDirectory(virtualFile) - } - } - - // add listener which prints out everything - FileSystem.addVirtualFileListener{ event -> - println(event) - if (event is VirtualFileChangedEvent) { - // FIXME explicit type casting to avoid overload ambiguity (KT-1461) - println("new file size is ${(event as VirtualFileChangedEvent).file.size}") - } - } - - // wait for 1 minute - Thread.sleep(60000) -} \ No newline at end of file diff --git a/examples/example-vfs/src/RefreshQueue.kt b/examples/example-vfs/src/RefreshQueue.kt deleted file mode 100644 index d757d285c89..00000000000 --- a/examples/example-vfs/src/RefreshQueue.kt +++ /dev/null @@ -1,123 +0,0 @@ -package org.jetbrains.jet.samples.vfs; - -import java.util.concurrent.ConcurrentLinkedQueue -import java.util.List -import java.util.concurrent.locks.ReentrantLock -import java.util.concurrent.LinkedBlockingQueue -import java.util.ArrayList - -import kotlin.util.* -import kotlin.concurrent.* -import java.util.Timer -import java.util.TimerTask - -import org.jetbrains.jet.samples.vfs.utils.* - -/** - * Singleton which creates thread for periodically checking if there are changes in - * file system and notifying file system listeners. - */ -internal object RefreshQueue { - private val taskQueue = LinkedBlockingQueue>(); - - { - thread(daemon=true, name="refresher thread") { - while (!currentThread.isInterrupted()) { - try { - takeAndRefreshFiles() - } catch (e : InterruptedException) { - } - } - } - - fixedRateTimer(daemon=true, name="refresher timer", period=5000.toLong()) { - scheduleRefresh(FileSystem.watchedDirectories) - } - } - - private fun takeAndRefreshFiles() { - refreshFiles(taskQueue.take()!!) - } - - /* Acquires write lock and refreshes file system */ - private fun refreshFiles(files : List) { - FileSystem.write { - files.forEach{ refreshFile(it) } - } - } - - /* Checks for changes in virtual file recursively, notifying listeners. */ - private fun refreshFile(file : VirtualFile) { - FileSystem.assertCanWrite() - val fileInfo = FileSystem.fileToInfo[file.path] - check(fileInfo != null) - if (fileInfo == null) { - return - } - if (file.isDirectory) { - val oldChildren = fileInfo.children - val newChildren = file.children - - - val addedChildren = listDifference(newChildren, oldChildren) - val deletedChildren = listDifference(oldChildren, newChildren) - val commonChildren = listIntersection(oldChildren, newChildren) - - addedChildren.forEach{ addRecursively(it) } - deletedChildren.forEach{ deleteRecursively(it) } - - fileInfo.children.clear() - fileInfo.children.addAll(newChildren) - - commonChildren.forEach{ refreshFile(it) } - } else { - val newModificationTime = file.modificationTime - if (fileInfo.lastModified != newModificationTime) { - fileInfo.lastModified = newModificationTime - - FileSystem.notifyEventHappened(VirtualFileChangedEvent(file)) - } - } - } - - /* Adds file to file system recursively, notifying listeners */ - private fun addRecursively(file : VirtualFile) { - require(FileSystem.fileToInfo[file] == null) - - val fileInfo = VirtualFileInfo(file) - - FileSystem.fileToInfo[file] = fileInfo - FileSystem.notifyEventHappened(VirtualFileCreateEvent(file)) - - fileInfo.children.forEach{ addRecursively(it) } - } - - /* Deletes file from file system recursively, notifying listeners */ - private fun deleteRecursively(file : VirtualFile) { - val fileInfoMaybe : VirtualFileInfo? = FileSystem.fileToInfo[file.path] - val fileInfo = fileInfoMaybe!! - fileInfo.children.forEach{ deleteRecursively(it) } - FileSystem.notifyEventHappened(VirtualFileDeletedEvent(file)) - FileSystem.fileToInfo.remove(file) - } - - /** - * Schedules refresh for given list of files. - */ - public fun scheduleRefresh(files : List) { - taskQueue.put(files) - } - - /** - * Schedules refresh for given list of files. - */ - public fun scheduleRefresh(vararg files : VirtualFile) { - // FIXME This could be written more concise, using map() & toList() (KT-1164 & KT-1172) - val filesList = ArrayList() - files.forEach{ filesList.add(it) } - taskQueue.put(filesList) - - // taskQueue.put(ArrayList(files.map{ it })) - // taskQueue.put(files.map{ it }.toList()) - } -} diff --git a/examples/example-vfs/src/Utils.kt b/examples/example-vfs/src/Utils.kt deleted file mode 100644 index 8709d9e17c1..00000000000 --- a/examples/example-vfs/src/Utils.kt +++ /dev/null @@ -1,31 +0,0 @@ -package org.jetbrains.jet.samples.vfs.utils; - -import java.util.concurrent.locks.Lock -import java.util.List -import kotlin.util.* - -/** - * Executes task with given lock acquired. - */ -private fun locked(lock : Lock, body : () -> T) : T { - lock.lock() - try { - return body() - } finally { - lock.unlock(); - } -} - -/** - * Returns list containing all elements which first contains and second does not. - */ -public fun listDifference(first : List, second : List) : List { - return first.filter{ !second.contains(it) }.toList() -} - -/** - * Returns list containing all elements which both lists contain. - */ -public fun listIntersection(first : List, second : List) : List { - return first.filter{ second.contains(it) }.toList() -} diff --git a/examples/example-vfs/src/VirtualFile.kt b/examples/example-vfs/src/VirtualFile.kt deleted file mode 100644 index dded4e1d2ef..00000000000 --- a/examples/example-vfs/src/VirtualFile.kt +++ /dev/null @@ -1,168 +0,0 @@ -package org.jetbrains.jet.samples.vfs; - -import org.jetbrains.jet.samples.vfs.utils.*; -import java.io.File -import java.io.InputStream -import java.io.FileInputStream -import java.util.ArrayList -import java.util.List - -import kotlin.util.* - -/** - * Abstract virtual file. - */ -public abstract class VirtualFile(public val path : String) : Hashable { - protected abstract val kind : String - - /** - * Returns file size. - */ - public abstract val size : Long - /** - * Returns the time that the virtual file was last modified (milliseconds since - * the epoch (00:00:00 GMT, January 1, 1970). - */ - public abstract val modificationTime : Long - /** - * Returns if virtual file exists. - */ - public abstract val exists : Boolean - /** - * Returns if virtual file is directory - */ - public abstract val isDirectory : Boolean - /** - * Returns list of virtual files which are children for this. - */ - public abstract val children : List - - /** - * Opens input stream for reading. After reading, stream should be closed. - * Reading from stream should be performed with read lock acquired. - */ - public abstract fun openInputStream() : InputStream - - public override fun equals(other : Any?) : Boolean { - return other is VirtualFile && kind == other.kind && path == other.path - } - - public override fun hashCode() : Int { - // FIXME rewrite without casting when it will be possible (KT-1741) - return (kind as java.lang.String).hashCode() * 31 + (path as java.lang.String).hashCode() - } - - fun toString(): String { - return "${kind}[path=$path]" - } -} - -/** - * Type of virtual file which corresponds to real file in file system of OS. - */ -public class PhysicalVirtualFile(path : String) : VirtualFile(path) { - override public val kind : String = "Physical" - - private val ioFile : File - get() = File(this.path.toSystemDependentPath()) - - override public val exists: Boolean - get() { - FileSystem.assertCanRead() - return ioFile.exists() - } - - override public val size: Long - get() { - FileSystem.assertCanRead() - return ioFile.length() - } - - override public val modificationTime: Long - get() { - FileSystem.assertCanRead() - return ioFile.lastModified() - } - - override public val isDirectory: Boolean - get() { - FileSystem.assertCanRead() - return ioFile.isDirectory() - } - - override public val children: List - get() { - FileSystem.assertCanRead() - return (ioFile.listFiles() ?: array()). - map{ FileSystem.getFileByIoFile(it!!) }?.toList() - } - - override public fun openInputStream(): InputStream { - FileSystem.assertCanRead() - if (isDirectory) { - throw IllegalArgumentException("Can't open directory for reading"); - } - return CheckedInputStream(FileInputStream(ioFile)) - } -} - -private val OS_SEPARATOR = java.io.File.separator!! -private val VFS_SEPARATOR = "/" - -private fun String.toSystemDependentPath() : String { - return this.replaceAll(VFS_SEPARATOR, OS_SEPARATOR) -} - -private fun String.toSystemIndependentPath() : String { - return this.replaceAll(OS_SEPARATOR, VFS_SEPARATOR) -} - -/** - * InputStream wrapper which checks that file system read lock is acquired on each operation. - */ -private class CheckedInputStream(private val wrapped : InputStream) : InputStream() { - override public fun read(): Int { - FileSystem.assertCanRead() - return wrapped.read() - } - - override public fun read(b: ByteArray?, off: Int, len: Int) : Int { - FileSystem.assertCanRead() - return wrapped.read(b, off, len) - } - - override public fun markSupported(): Boolean { - FileSystem.assertCanRead() - return wrapped.markSupported() - } - - override public fun skip(n: Long): Long { - FileSystem.assertCanRead() - return wrapped.skip(n) - } - - override public fun close() { - FileSystem.assertCanRead() - return wrapped.close() - } - - override public fun mark(readlimit: Int) { - FileSystem.assertCanRead() - return wrapped.mark(readlimit) - } - - override public fun read(b: ByteArray?): Int { - FileSystem.assertCanRead() - return wrapped.read(b) - } - - override public fun reset() { - FileSystem.assertCanRead() - return wrapped.reset() - } - - override public fun available(): Int { - FileSystem.assertCanRead() - return wrapped.available() - } -} \ No newline at end of file diff --git a/examples/example-vfs/src/VirtualFileEvent.kt b/examples/example-vfs/src/VirtualFileEvent.kt deleted file mode 100644 index 910538b2529..00000000000 --- a/examples/example-vfs/src/VirtualFileEvent.kt +++ /dev/null @@ -1,50 +0,0 @@ -package org.jetbrains.jet.samples.vfs; - -/** - * Listener for receiving virtual file event - */ -public trait VirtualFileListener : java.util.EventListener { - fun eventHappened(val event : VirtualFileEvent) -} - -// FIXME using this wrapper because of codegen bug KT-1737, should be replaced with -private class SimpleVirtualFileListener(val listenerFunction : (VirtualFileEvent)->Unit) : VirtualFileListener { - override fun eventHappened(event : VirtualFileEvent) { - val f = listenerFunction // FIXME saving to local variable because of the bug in codegen (KT-1739) - f(event) - } -} - -/** - * Base type of virtual file events - * @property file affected by event - */ -public abstract class VirtualFileEvent(val file : VirtualFile) : Object() { -} - -/** - * Event of creating file - */ -public class VirtualFileCreateEvent(file : VirtualFile) : VirtualFileEvent(file) { - override public fun toString(): String? { - return "created ${file}" - } -} - -/** - * Event of deleting file - */ -public class VirtualFileDeletedEvent(file : VirtualFile) : VirtualFileEvent(file) { - override public fun toString(): String? { - return "deleted ${file}" - } -} - -/** - * Event of changing file contents - */ -public class VirtualFileChangedEvent(file : VirtualFile) : VirtualFileEvent(file) { - override public fun toString(): String? { - return "changed ${file}" - } -} diff --git a/examples/examples.iml b/examples/examples.iml deleted file mode 100644 index a5c58f1a1c6..00000000000 --- a/examples/examples.iml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/examples/src/AnonymousObjects.jetl b/examples/src/AnonymousObjects.jetl deleted file mode 100644 index 6c5a97b66b1..00000000000 --- a/examples/src/AnonymousObjects.jetl +++ /dev/null @@ -1,24 +0,0 @@ -fun foo() { - -addMouseListener(object MouseAdapter() { - - private var clickCount = 0; - - override fun mouseClicked(e : MouseEvent) { - clickCount++; - if (clickCount > 3) GOD.sendMessage(GodMEssages.TOO_MANY_CLICKS); - } -}) - -enum class GodMessages { - TOO_MANY_CLICKS - ONE_MORE_MESSAGE -} - -// Type of this variable is GOD_AnonymousClass -val GOD = object { - fun sendMessage(message : GodMEssage) = throw new RuntimeException(message.name) -}; - - -} \ No newline at end of file diff --git a/examples/src/BinaryTree.jetl b/examples/src/BinaryTree.jetl deleted file mode 100644 index 6fc21937a98..00000000000 --- a/examples/src/BinaryTree.jetl +++ /dev/null @@ -1,195 +0,0 @@ -class BinaryTree : IMutableSet { - private class TreeNode( - var value : T, var parent : TreeNode - ) { - var left : TreeNode - var right : TreeNode - - } - - private val compare : MatchableComparison - private var root : TreeNode - private var version = 0 - -// override var size : Int { get; private set; } - - this(compare : Comparison) { - this.compare = asMatchableComparison(comparison) - } - - this() : this(naturalOrder()) { - } - - private [operator] fun T.compareTo(other : T) : Int = compare(this, other) - - override fun contains(item : T) : Boolean { - return contains(root, item) - - fun contains(node : TreeNode, item : T) : Boolean { - if (node == null) return false - when (compare(item, node.value)) { - EQ => true - LS => contains(node.left, item) - GT => contains(node.right, item) - } - } - } - - override fun add(item : T) : Boolean { - if (add(ref root, null)) { - size++ - version++ - return true - } - return false - - // In principle, this has access to item anyway, but then it's unreachable code - // BAD: the naive implementation of ref will create H(T) ref objects, but can be optimized to create only one - fun add(ref node : TreeNode, parent : TreeNode) : Boolean { - if (node == null) { - node = TreeNode(item, parent) - return true - } - when (compare(item, node.value)) { - EQ => false - LS => add(ref node.left, node) - GT => add(ref node.right, node) - } - } - - // In principle, this has access to item anyway - fun addNoRef(node : TreeNode) : Boolean { - if (node == null) { - root = TreeNode(item, null) - return true - } - when (compare(item, node.value)) { - EQ => return false - LS => - if (node.left == null) { - node.left = TreeNode(item, node) - return true - } else return add(node.left) - GT => - if (node.right == null) { - node.right = TreeNode(item, node) - return true - } else return add(node.right) - } - } - } - - override fun remove(item : T) : Boolean { - val toRemove = find(root, item) - if (toRemove == null) return false - remove(toRemove) - size-- - version++ - return true - - fun find(node : TreeNode) : TreeNode { - if (node == null) return null - when (compare(item, node.value)) { - EQ => node - LS => find(node.left) - GT => find(node.right) - } - } - } - - private fun remove(node : TreeNode) { - when (node) { - is TreeNode(null, null) => replace(node, null) - is TreeNode(null, ?right) => replace(node, right) - is TreeNode(?left, null) => replace(node, left) - is TreeNode(?left, ?right) => { - val min = min(node.right) - node.value = min.value - remove(min) - } - } - - fun replace(node : TreeNode, replace : TreeNode) { - if (node == root) { - root = replace - return - } - if (node.parent.left == node) { - node.parent.left = replace - } else if (node.parent.right == node) { - node.parent.right = replace - } else Assert(false) - } - } - - // Relies on tail-recursion optimization - private fun min(node : TreeNode) { - if (node.left == null) node else min(node.left) - } - - override fun iterator() : IIterator = mutableIterator() - - override fun mutableIterator() : IMutableIterator = object IMutableIterator { - val version = BinaryTree.this.version - val down = Stack() - val up = Stack() - var lastNode : TreeNode - - this() { - if (root != null) - down.push(root) - } - - override fun next() : T { - if (!hasNext) - throw NoMoreElementsException() - checkVersion() - - lastNode = nextNode() - return lastNode.value - } - - private fun nextNode() : TreeNode { - while (true) { - if (!down.isEmpty) { - val curNode = down.pop() - if (curNode.left != null) { - up.push(curNode) - down.push(curNode.left) - } else { - if (curNode.right != null) { - down.push(curNode.right) - } - return curNode; - } - } else { - val curNode = up.pop() - if (curNode.right != null) { - down.push(curNode.right) - } - return curNode - } - } - } - - override val hasNext : Boolean - get() = !down.isEmpty || !up.isEmpty - - - override fun remove() { - checkVersion() - if (lastNode == null) - throw IterationException("Nothing to remove") - remove(lastNode) - version++ - BinaryTree.this.version = version - } - - private fun checkVersion() { - if (version != BinaryTree.this.version) { - throw ConcurrentModificationException() - } - } - } - -} \ No newline at end of file diff --git a/examples/src/BitArith.jetl b/examples/src/BitArith.jetl deleted file mode 100644 index 6a410c1677c..00000000000 --- a/examples/src/BitArith.jetl +++ /dev/null @@ -1,29 +0,0 @@ -fun oneBit(index : Int) = 1 shl index - -fun setBit(x : Int, index : Int) = x or oneBit(index) -fun unsetBit(x : Int, index : Int) = x and not(oneBit(index)) - -fun getBit(x : Int, index : Int) = x and oneBit(index) != 0 -fun getBit(x : Int, index : Int) = (x shr index) shl 31 != 0 - -fun countOnes(x : INumber) { - var result = 0 - while (x != 0) { - result += x and 1 - x = x ushr 1 - } - result -} - -fun mostSignificantBit(x : INumber) = (x and oneBit(x.bits - 1) != 0) as Int - -fun countOnes(x : INumber) = if (x == 0) 0 else mostSignificantBit(x) + countOnes(x shl 1) - -fun Int.matchMask(mask : Int) = this and mask == mask - -open class INumber : IComparable { - val bits : Int - [operator] fun plus(other : T) : T - [operator] fun shl(bits : Int) : T - // ... -} \ No newline at end of file diff --git a/examples/src/Bottles.kt b/examples/src/Bottles.kt deleted file mode 100644 index ca621424f79..00000000000 --- a/examples/src/Bottles.kt +++ /dev/null @@ -1,23 +0,0 @@ -package bottles; - -fun main(args: Array) { - var bottles: Int = 99; - while(bottles > 0) { - System.out?.print(bottlesOfBeer(bottles) + " on the wall, ") - System.out?.println(bottlesOfBeer(bottles) + ".") - System.out?.print("Take one down, pass it around, ") - if (--bottles == 0) { - System.out?.println("no more bottles of beer on the wall.") - } - else { - System.out?.println(bottlesOfBeer(bottles) + " on the wall.") - } - } -} - -fun bottlesOfBeer(count: Int): String { - val result = StringBuilder() - result.append(count) - result.append(if (count > 1) " bottles of beer" else " bottle of beer") - return result.toString() ?: "" -} diff --git a/examples/src/Builder.jetl b/examples/src/Builder.jetl deleted file mode 100644 index 8aaf8c6dc85..00000000000 --- a/examples/src/Builder.jetl +++ /dev/null @@ -1,43 +0,0 @@ -val foo = object AntBuilder() { - - lazy val groovy = library { - classpath("$libs/groovy-...") - } - - lazy val gant = library { - new File("$gantHome/lib").files.each { - classpath(it) - } - } - - lazy val JPS = module { - targetLevel = "1.5" - classpath(antLayout, gant, groovy) - src("$projectHome/antLayout/src") - } - -}.build() - -class AntBuilder { - abstract class ClassPathEntry {} - - class Module : ClassPathEntry { - fun classpath(entries : ClassPathEntry/*...*/) { /*...*/ } - var targetLevel : String - fun src(src : String) { /*...*/ } - } - - class Library : ClassPathEntry { - fun classpath(entries : ClassPathEntry/*...*/) { /*...*/ } - } - - fun library(initializer : { Library.() : Library}) { - val lib = new Library() - lib.initializer() - return lib - } - - fun classpath(/*...*/) - - fun module(/*...*/) -} \ No newline at end of file diff --git a/examples/src/Color.jetl b/examples/src/Color.jetl deleted file mode 100644 index c4642656639..00000000000 --- a/examples/src/Color.jetl +++ /dev/null @@ -1,5 +0,0 @@ -enum class Color(val r : Int , val g :Int , val b : Int) { - RED : Color(255, 0, 0) - GREEN : Color(0, 255, 0) - BLUE : Color(0, 0, 255) -} \ No newline at end of file diff --git a/examples/src/ColossalCave.kt b/examples/src/ColossalCave.kt deleted file mode 100644 index 0ad42980a6a..00000000000 --- a/examples/src/ColossalCave.kt +++ /dev/null @@ -1,225 +0,0 @@ -package ColossalCave - -import java.util.* -import java.io.* - -open class Thing(val name : String) { - open val ldesc : String get() = "This is a nondescript thing" -} - -open class Room(name : String) : Thing(name) { - open val west : Room? get() = null - open val east : Room? get() = null - open val north : Room? get() = null - open val south : Room? get() = null - var seen : Boolean = false -} - -public val items : ArrayList = ArrayList() - -open class Item(name : String, var room : Room?) : Thing(name) { - open val isFixed : Boolean get() = false - open val isListed : Boolean get() = true - - { - items.add(this) - } -} - -open class FixedItem(name : String, room : Room?) : Item(name, room) { - override val isFixed : Boolean get() = true - override val isListed : Boolean get() = false -} - -fun describeRoom(room : Room) { - println(room.name) - if (!room.seen) { - println(room.ldesc) - room.seen = true - } - for(val item in items) { - if (item.room === room && item.isListed) { - println("You see " + item.name) - } - } -} - -object AtEndOfRoad: Room("At End of Road") { - override val ldesc : String = "You are standing at the end of the road before a small brick building." + - " Around you is a forest. A small stream flows out of the building and down a gully." - - override val west : Room? get() = AtHillInRoad - override val east : Room? get() = InsideBuilding - override val south : Room? get() = InAValley -} - -object AtHillInRoad: Room("At Hill in Road") { - override val ldesc : String = "You have walked up a hill, still in the forest. The road slopes back down " + - "the other side of the hill. There is a building in the distance." - - override val east : Room? get() = AtEndOfRoad -} - -val Hill = object: FixedItem("Hill", AtHillInRoad) { - override val ldesc : String = "It's just a typical hill." -} - -object InsideBuilding: Room("Inside Building") { - override val ldesc : String = "You are inside a building, a well house for a large spring." - - override val west : Room? get() = AtEndOfRoad -} - -object InAValley: Room("In A Valley") { - override val ldesc : String = "You are in a valley in the forest beside a stream tumbling along a rocky bed." - override val north : Room get() = AtEndOfRoad - override val south : Room get() = AtSlitInStreambed -} - -object AtSlitInStreambed: Room("At Slit In Streambed") { - override val ldesc : String = "At your feet all the water of the stream splashs into a 2-inch slit in the rock." + - " Downstream the streambed is bare rock." - override val north : Room get() = InAValley - override val south : Room get() = OutsideGrate -} - -object OutsideGrate: Room("Outside Grate") { - override val ldesc : String = "You are in a 20-foot depression floored with bare dirt. Set into the dirt " + - "is a strong steel grate mounted in concrete. A dry streambed leads into the depression." - override val north : Room get() = AtSlitInStreambed -} - -val brassLantern = object: Item("Brass Lantern", InsideBuilding) { -} - -val setOfKeys = object: Item("A Set of Keys", InsideBuilding) { -} - -fun startRoom() = AtEndOfRoad - -class Player(var room : Room) { - val inventory : ArrayList = ArrayList() -} - -abstract class Command { - abstract fun execute(p : Player) : Unit -} - -object QuitCommand : Command() { - override fun execute(p : Player) { - System.exit(0) - } -} - -abstract class MoveCommand : Command() { - fun moveTo(p : Player, room : Room?) { - if (room === null) { - println("You can't go that way") - return - } - p.room = room as Room - describeRoom(p.room) - } -} - -object NorthCommand: MoveCommand() { - override fun execute(p : Player) { - moveTo(p, p.room.north) - } -} - -object SouthCommand: MoveCommand() { - override fun execute(p : Player) { - moveTo(p, p.room.south) - } -} - -object WestCommand: MoveCommand() { - override fun execute(p : Player) { - moveTo(p, p.room.west) - } -} - -object EastCommand: MoveCommand() { - override fun execute(p : Player) { - moveTo(p, p.room.east) - } -} - -abstract class CommandOnObject(val target : String) : Command() { - override fun execute(p : Player) { - for(val item in items) { - if (item.name.equalsIgnoreCase(target) && item.room == p.room) { - executeOn(p, item) - return - } - } - println("I don't see any " + target + " here.") - } - - abstract fun executeOn(p : Player, item : Item) -} - -class TakeCommand(target : String) : CommandOnObject(target) { - override fun executeOn(p : Player, item : Item) { - if (item.isFixed) { - print("You can't have " + item.name) - return - } - item.room = null - p.inventory.add(item) - println("Taken") - } -} - -class ExamineCommand(target : String) : CommandOnObject(target) { - override fun executeOn(p : Player, item : Item) { - println(item.ldesc) - } -} - -object InventoryCommand: Command() { - override fun execute(p : Player) { - if (p.inventory.size() == 0) - println("You are empty-handed.") - else { - println("You are carrying:") - for(val item in p.inventory) { - println(item.name) - } - } - } -} - -fun parse(cmd : String) : Command? { - if (cmd == "quit") return QuitCommand - if (cmd == "north") return NorthCommand - if (cmd == "south") return SouthCommand - if (cmd == "west") return WestCommand - if (cmd == "east") return EastCommand - if (cmd == "inventory") return InventoryCommand - if (cmd.startsWith("take")) { - val target = cmd.substring(4).trim() - return TakeCommand(target) - } - if (cmd.startsWith("examine")) { - val target = cmd.substring(7).trim() - return ExamineCommand(target) - } - return null -} - -fun main(args : Array) { - val p = Player(startRoom()) - describeRoom(p.room) - val reader = BufferedReader(InputStreamReader(System.`in`)) - while(true) { - print("> ") - val cmd = reader.readLine() as String - val command = parse(cmd) - if (command === null) - println("Unrecognized command"); - else - command.execute(p) - } -} diff --git a/examples/src/Factories.jetl b/examples/src/Factories.jetl deleted file mode 100644 index 53d4b78ca33..00000000000 --- a/examples/src/Factories.jetl +++ /dev/null @@ -1,34 +0,0 @@ -class Foo(bar : Bar) { - class object { - private val cache = HashMap() - -// Factory method: - fun Foo() = Foo(null); - -// Factory method: - fun Foo(bar : Bar) = cache.cachedLookup(bar, this(bar)) - } - - fun doFoo() { - // ... - } -} - -// To create an object of Foo -val foo = Foo() -// or -val foo = Foo(Bar()) - -// Subclass (Foo must be marked as extendable/open, i.e. ont sealed) -class FooSub(S : String) : Foo() { // Delegates to Foo created as a result of the factory method Foo() - -} - -fun Map.cachedLookup(key : K, lazy value : V) : V { - var v = this[key] - if (v == null) { - v = value - this[key] = value - } - return v -} \ No newline at end of file diff --git a/examples/src/FunctionsAndTypes.jetl b/examples/src/FunctionsAndTypes.jetl deleted file mode 100644 index 623e765c4ac..00000000000 --- a/examples/src/FunctionsAndTypes.jetl +++ /dev/null @@ -1,34 +0,0 @@ -type f1 = {(T) : X} -// type f1 = {(T) => X} -type f2 = {(T, E) : X} -// type f2 = {(T, E) => X} -type f_tuple = {((T, E)) : X} -//type f_tuple = {((T, E)) => X} -type hof = { (X) : {(T) : Y} } -//type hof = { (X) => {(T) => Y} } -type hof2 = { ({(X) : Y}) : {(Y) : Z} } -//type hof2 = { {(X) => Y} => {(Y) => Z} } - - -type Comparison = {(a : T, b : T) : Int} -//type Comparison = {(a : T, b : T) => Int} -type Equality = {(a : T, b : T) : Boolean} -//type Equality = {(a : T, b : T) => Boolean} -type HashFunction = {(obj : T) : Int} -//type HashFunction = {(obj : T) => Int} -type Runnable = {() : ()} -//type Runnable = {() => ()} -type Function1 = {(input : T) : R} -//type Function1 = {(input : T) => R} - - -val f1 = {(t : T) : X => something(t)} -fun f1(t : T) : X = something(t) - -val f1 = {(t : T) => something(t)} -val f1 = {(T) : X => something(it)} -val f1 = {t => something(t)} -val f1 = {something(it)} - -val f1 : {(T) : X} = {X()} - diff --git a/examples/src/Generics.jet b/examples/src/Generics.jet deleted file mode 100644 index 537bb96c5a8..00000000000 --- a/examples/src/Generics.jet +++ /dev/null @@ -1,39 +0,0 @@ -package generics; - -import java.util.* - -class Box(t: T) { - var value = t -} - -fun isIntBox(box: Box): Boolean { - return box is Box; -} - -abstract class Source { - fun nextT() : T -} - -fun demo(strs : Source) { - val objects : Source = strs // This is OK, since T is an out-parameter - // ... -} - -fun singletonList(item: T): List { - val result = ArrayList() - result.add(item) - return result -} - -//fun T.basicToString(): String { -// return typeinfo(this) + "@" + System.identityHashCode(this) -//} - -fun main(args: Array) { - val box: Box = Box(1) - System.out?.println(box.value) - System.out?.println(if (isIntBox(box)) "int" else "not int"); - - val singleString: List = singletonList("foo") - System.out?.println(singleString.get(0)) -} diff --git a/examples/src/Graph.jetl b/examples/src/Graph.jetl deleted file mode 100644 index 225d387f10d..00000000000 --- a/examples/src/Graph.jetl +++ /dev/null @@ -1,60 +0,0 @@ -class Vertex(val data : V) - -class Edge(val from : V, val data : E, val to : V) - -class Graph { - - private val mutableEdges = new ArrayList>() // type is ArrayList, but I want IMutableList -/* options: - private val edges : IMutableList> = new ArrayList>() - private val edges : IMutableList> = new ArrayList() // not an erasure, but a request to infer parameters -*/ - - private val mutableVertices = new HashSet>() - - val edges : IList> = mutableEdges; - val vertices : ISet> = mutableVertices; - - fun addEdge(from : V, data : E, to : V) { - mutableEdges.add(new Edge(from, data, to)) // constructor parameters are inferred - } - fun addVertex(v : V) { - mutableEdges.add(new Edge(from, data, to)) // constructor parameters are inferred - } - - fun neighbours(v : Vertex) = edges.filter{it.from == v}.map{it.to} // type is IIterable> - - fun dfs(handler : {(V) : Unit}) { - val visited = new HashSet>() - vertices.foreach{dfs(it, visited, handler)} - - fun dfs(current : Vertex, visited : ISet>, handler : {(V) : Unit}) { - if (!visited.add(current)) - return - handler(current) - neighbours(current).foreach{dfs(it, visited, handler)} - } - } - - public fun traverse(pending : IPushPop>, visited : ISet>, handler : {(V) : Unit}) { - vertices.foreach { - if (!visited.add(it)) - continue - pending.push(it) - while (!pending.isEmpty) { - val current = pending.pop() - handler(current); - neighbours(current).foreach { n => - if (visited.add(n)) { - pending.push(n) - } - } - /* alternative - pending->push(neighbours(current).filter{n => !visited[n])}) - // -> means that if push(x : T) and actual parameter y is IIterable, this compiles into - y.foreach{ n => push(n) } - */ - } - } - } -} diff --git a/examples/src/Hello.kts b/examples/src/Hello.kts deleted file mode 100644 index c7086636e56..00000000000 --- a/examples/src/Hello.kts +++ /dev/null @@ -1,7 +0,0 @@ -import kotlin.modules.ModuleSetBuilder - -fun defineModules(builder: ModuleSetBuilder) { - builder.module("hello") { - source files "HelloNames.kt" - } -} diff --git a/examples/src/HelloNames.kt b/examples/src/HelloNames.kt deleted file mode 100644 index 923609192a4..00000000000 --- a/examples/src/HelloNames.kt +++ /dev/null @@ -1,18 +0,0 @@ -package HelloNames - -fun main(args : Array) { - var names = "" - - for (i in args.indices) { - names += args[i] - if (i + 1 < args.size) - names += ", " - } - // string templates - println("Hello, $names!") -} - -fun println(message : String) { - // System.out is a nullable field - System.out?.println(message) -} diff --git a/examples/src/HelloNamesFaster.kt b/examples/src/HelloNamesFaster.kt deleted file mode 100644 index ee69a623086..00000000000 --- a/examples/src/HelloNamesFaster.kt +++ /dev/null @@ -1,22 +0,0 @@ -package HelloNamesFaster - -fun main(args : Array) { - var names = StringBuilder() - - for (i in args.indices) { - names += args[i] - if (i + 1 < args.size) - names += ", " - } - // string templates - println("Hello, $names!") -} - -fun println(message : String) { - // System.out is a nullable field - System.out?.println(message) -} - -fun StringBuilder.plusAssign(s : String) { - this.append(s) -} diff --git a/examples/src/HelloNamesRealistic.kt b/examples/src/HelloNamesRealistic.kt deleted file mode 100644 index e3c74d82f8a..00000000000 --- a/examples/src/HelloNamesRealistic.kt +++ /dev/null @@ -1,32 +0,0 @@ -package HelloNamesRealistic - -fun main(args : Array) { - val names = args.join(", ") - println("Hello, $names!") -} - -fun println(message : String) { - // System.out is a nullable field - System.out?.println(message) -} - -fun Iterable.join(separator : String) : String? { - val names = StringBuilder() - forit (this) {(it: Iterator): Unit => - names += it.next() - if (it.hasNext()) - names += separator - } - return names.toString() -} - -fun forit(col : Iterable, f : fun(Iterator) : Unit) { - val it = col.iterator() - while (it.hasNext()) { - f(it) - } -} - -fun StringBuilder.plusAssign(s : String) { - this.append(s) -} diff --git a/examples/src/IPushPop.jetl b/examples/src/IPushPop.jetl deleted file mode 100644 index 84725423fdc..00000000000 --- a/examples/src/IPushPop.jetl +++ /dev/null @@ -1,5 +0,0 @@ -open class IPushPop { - val isEmpty : Boolean - fun push(item : T) - fun pop() : T -} \ No newline at end of file diff --git a/examples/src/JavaInterop.jet b/examples/src/JavaInterop.jet deleted file mode 100644 index 6c5bafc2293..00000000000 --- a/examples/src/JavaInterop.jet +++ /dev/null @@ -1,9 +0,0 @@ -package JavaInterop - -import java.util.* - -fun main(args: Array) { - val list = ArrayList() - list.add("foo") - System.out?.println(list[0]) -} diff --git a/examples/src/LINQ.jetl b/examples/src/LINQ.jetl deleted file mode 100644 index e492a0c22d3..00000000000 --- a/examples/src/LINQ.jetl +++ /dev/null @@ -1,3 +0,0 @@ -fun foo() { - l filter {it.x} map {it.foo} aggregate {(a, b) => a + b} -} \ No newline at end of file diff --git a/examples/src/LambdaTheGathering.kt b/examples/src/LambdaTheGathering.kt deleted file mode 100644 index 5a2864ce843..00000000000 --- a/examples/src/LambdaTheGathering.kt +++ /dev/null @@ -1,213 +0,0 @@ -package LambdaTheGathering - -/** - * Incomplete solution to the IFCP Contest 2011 - * @author yole - */ - -class GameError(msg: String): Exception(msg) { -} - -abstract class Function(val name: String) { - abstract fun apply(x: Value, proponent: Player): Value - fun toString() = name - open fun asNumber(): Int { throw GameError("could not get numeric value of a function") } -} - -object Identity: Function("I") { - override fun apply(x: Value, proponent: Player): Value = x -} - -object IdentityValue: Value(Identity) - -object Zero: Function("zero") { - override fun apply(x: Value, proponent: Player): Value = Value(0) - override fun asNumber(): Int = 0 -} - -object Succ: Function("succ") { - override fun apply(x: Value, proponent: Player): Value = Value(x.asNumber() + 1) -} - -object Get: Function("get") { - override fun apply(x: Value, proponent: Player): Value = proponent.getSlot(x.asNumber()).field -} - -object Dbl: Function("dbl") { - override fun apply(x: Value, proponent: Player): Value = Value(x.asNumber() * 2) -} - -class HelpFunc2(val i: Value, val j: Value): Function("help(" + i + ")(" + j + ")") { - override fun apply(x: Value, proponent: Player): Value { - val n = x.asNumber() - proponent.getSlot(i.asNumber()).decreaseVitality(n) - proponent.getSlot(j.asNumber()).increaseVitality(n * 11 / 10); - return Value(Identity) - } -} - -class HelpFunc(val i: Value): Function("help(" + i + ")") { - override fun apply(x: Value, proponent: Player): Value = Value(HelpFunc2(i, x)) -} - -object Help: Function("help") { - override fun apply(x: Value, proponent: Player): Value = Value(HelpFunc(x)) -} - -class KFunc(val arg: Value): Function("K(" + arg + ")") { - override fun apply(x: Value, proponent: Player): Value = arg -} - -object K: Function("K") { - override fun apply(x: Value, proponent: Player): Value = Value(KFunc(x)) -} - -class SFunc2(val f: Value, val g: Value): Function("S(" + f + ")(" + g + ")") { - override fun apply(x: Value, proponent: Player): Value { - val h = f.apply(x, proponent) - val y = g.apply(x, proponent) - val z = h.apply(y, proponent) - return z - } -} - -class SFunc(val f: Value): Function("S(" + f + ")") { - override fun apply(x: Value, proponent: Player): Value = Value(SFunc2(f, x)) -} - -object S: Function("S") { - override fun apply(x: Value, proponent: Player): Value = Value(SFunc(x)) -} - -open class Value(val n: Int, val f: Function, val isFunction: Boolean) { - this(n: Int): this(if (n > 65535) 65535 else n, Identity, false) {} - this(f: Function): this(0, f, true) {} - - fun equals(rhs: Any?): Boolean { - if (rhs is Value) { - val rhsValue = rhs as Value - if (rhsValue.isFunction) { - return isFunction && f === rhsValue.f - } - else { - return ! isFunction && n == rhsValue.n - } - } - return false - } - - fun apply(x: Value, proponent: Player): Value { - if (isFunction) return f.apply(x, proponent) - throw GameError("could not apply non-function value"); - } - - fun asNumber(): Int { - if (! isFunction) return n; - return f.asNumber() - } - - fun toString() = if (isFunction) f.name else Integer.toString(n) -} - -class Slot() { - var vitality: Int = 10000 - var field: Value = Value(Identity) - - val alive: Boolean get() = vitality > 0 - - fun isDefault() = vitality == 10000 && field == Value(Identity) - - fun increaseVitality(delta: Int) { - if (alive) { - vitality += delta - if (vitality > 65535) vitality = 65535; - } - } - - fun decreaseVitality(delta: Int) { - if (!alive || delta > vitality) throw GameError("cannot decrease vitality") - vitality -= delta - } - - fun toString() = "{" + vitality + "," + field.toString() + "}"; -} - -class Player() { - var opponent: Player? = null - - val slots: Array = Array(256, { i -> Slot() }) - - fun getSlot(i: Int): Slot { - if (i < 0 || i > 255) throw GameError("invalid slot index") - if (!slots[i].alive) throw GameError("the slot is dead") - return slots[i] - } - - fun printSlots() { - println("(slots {10000,I} are omitted)") - for(val i in 0..255) { - if (!slots[i].isDefault()) { - println("" + i + "=" + slots[i].toString()) - } - } - } - - fun applyCardToSlot(index: Int, card: Function) { - println("applying card " + card + " to slot " + index) - slots[index].field = card.apply(slots[index].field, this) - } - - fun applySlotToCard(index: Int, card: Function) { - println("applying slot " + index + " to card " + card) - slots[index].field = slots[index].field.apply(Value(card), this) - } -} - -val p0 = Player() -val p1 = Player() - -fun main(args: Array) { - p0.opponent = p1 - p1.opponent = p0 - - print("player 0") - p0.printSlots() - p0.applySlotToCard(0, Help) - p0.printSlots() - p0.applySlotToCard(0, Zero) - p0.printSlots() - p0.applyCardToSlot(0, K) - p0.printSlots() - p0.applyCardToSlot(0, S) - p0.printSlots() - p0.applySlotToCard(0, Succ) - p0.printSlots() - p0.applySlotToCard(0, Zero) - p0.printSlots() - p0.applySlotToCard(1, Zero) - p0.printSlots() - p0.applyCardToSlot(1, Succ) - p0.printSlots() - p0.applyCardToSlot(1, Dbl) - p0.printSlots() - p0.applyCardToSlot(1, Dbl) - p0.printSlots() - p0.applyCardToSlot(1, Dbl) - p0.printSlots() - p0.applyCardToSlot(1, Dbl) - p0.printSlots() - p0.applyCardToSlot(0, K) - p0.printSlots() - p0.applyCardToSlot(0, S) - p0.printSlots() - p0.applySlotToCard(0, Get) - p0.printSlots() - p0.applyCardToSlot(0, K) - p0.printSlots() - p0.applyCardToSlot(0, S) - p0.printSlots() - p0.applySlotToCard(0, Succ) - p0.printSlots() - p0.applySlotToCard(0, Zero) - p0.printSlots() -} diff --git a/examples/src/NullSafety.jet b/examples/src/NullSafety.jet deleted file mode 100644 index c795d1804da..00000000000 --- a/examples/src/NullSafety.jet +++ /dev/null @@ -1,12 +0,0 @@ -package NullSafety - -fun T?.npe() : T = - if (this == null) - throw NullPointerException() - else - this - -fun main(args: Array) { - val s: String? = null - s.npe().length() -} diff --git a/examples/src/Point.kt b/examples/src/Point.kt deleted file mode 100644 index 01175fb9c0d..00000000000 --- a/examples/src/Point.kt +++ /dev/null @@ -1,17 +0,0 @@ -class Point(val x: Int, val y: Int) { - fun toString() = "($x,$y)" - - fun distanceTo(other: Point): Double { - val dx = x - other.x - val dy = y - other.y - return Math.sqrt((dx*dx + dy*dy).toDouble()) - } -} - -fun main(args: Array) { - var p = Point(0, 0) - var q = Point(1, 1) - p.distanceTo(q) - - -} \ No newline at end of file diff --git a/examples/src/PolymorphicClassObjects.jetl b/examples/src/PolymorphicClassObjects.jetl deleted file mode 100644 index 57ba9826889..00000000000 --- a/examples/src/PolymorphicClassObjects.jetl +++ /dev/null @@ -1,31 +0,0 @@ -open class Builder { - [operator] fun plusAssign(item : E) - fun result() : R -} - -open class Buildable { - fun newBuilder() : Builder -} - -class List { - - class object Buildable { - override fun newBuilder() : Builder - - } - -} - -extension Map - where - T : Iterable, - class object T : Buildable for T { - - fun map(f : {(E) : R}) : T = { - val builder = T.newBuilder() - for (e in this) { - builder += f(e) - } - builder.result() - } -} \ No newline at end of file diff --git a/examples/src/Queue.jetl b/examples/src/Queue.jetl deleted file mode 100644 index 375f9babd53..00000000000 --- a/examples/src/Queue.jetl +++ /dev/null @@ -1,33 +0,0 @@ -class Queue : IPushPop { - private class Item(val data : T, var next : Item) - - private var head : Item = null - private var tail : Item = null - - override fun push(item : T) { - val i = new Item(item) - if (tail == null) { - head = i - tail = head - } else { - tail.next = i - tail = i - } - } - - override fun pop() = - if (head == null) - throw new UnderflowException() - else { - val result = head.data - head = head.next - if (head == null) - tail = null - result - } - - override val isEmpty - get() = head == null - - -} \ No newline at end of file diff --git a/examples/src/Stack.jetl b/examples/src/Stack.jetl deleted file mode 100644 index 426bc28c9a9..00000000000 --- a/examples/src/Stack.jetl +++ /dev/null @@ -1,13 +0,0 @@ -class Stack : IPushPop { - private val data = new ArrayList(); - - override fun push(item : T) { - data.add(item) // Problem: I would like to write push(...) = data.add(...), but the types do not match - } - - override fun pop() = data.removeLast() - - override val isEmpty - get() = data.isEmpty - -} \ No newline at end of file diff --git a/examples/src/TwentyFourGame.kt b/examples/src/TwentyFourGame.kt deleted file mode 100644 index 09fa2c13ea9..00000000000 --- a/examples/src/TwentyFourGame.kt +++ /dev/null @@ -1,95 +0,0 @@ -package TwentyFourGame - -/** - * @author yole - */ -import java.util.* -import java.io.* - -fun StringBuilder.takeFirst(): Char { - if (this.length() == 0) return 0.toChar() - val c = this.charAt(0) - this.deleteCharAt(0) - return c -} - -class Evaluator(val expr: StringBuilder, val numbers: ArrayList) { - fun checkFirst(expect: Char): Boolean { - if (expr.length() > 0 && expr.charAt(0) == expect) { - expr.deleteCharAt(0) - return true - } - return false - } - - fun evaluateArg(): Int { - val c = expr.takeFirst() - when(c) { - in '0'..'9' -> { - val n = c - '0' - val index = numbers.indexOf(n) - if (index < 0) throw Exception("You used incorrect number: " + n) - numbers.remove(index) // gotcha: conflict between remove(Object) and remove(int) - return n - } - '(' -> { - val result = evaluate() - if (expr.takeFirst() != ')') throw Exception(") expected") - return result - } - 0.toChar() -> throw Exception("Syntax error: Character expected") - else -> throw Exception("Syntax error: Unrecognized character " + c) - } - } - - fun evaluateMult(): Int { - val lhs = evaluateArg() - if (checkFirst('*')) - return lhs * evaluateMult() - if (checkFirst('/')) - return lhs / evaluateMult() - return lhs - } - - fun evaluate(): Int { - val lhs = evaluateMult() - if (checkFirst('+')) - return lhs + evaluate() - if (checkFirst('-')) - return lhs - evaluate() - return lhs - } - - fun evaluateAll(): Int { - val result = evaluate() - if (expr.length() > 0) throw Exception("unexpected text: " + expr) - return result - } -} - -fun main(args: Array) { - println("24 game") - val numbers = ArrayList(4) - val rnd = Random(); - val prompt = StringBuilder() - for(val i in 0..3) { - val n = rnd.nextInt(9) + 1 - numbers.add(n) - if (i > 0) prompt.append(" "); - prompt.append(n) - } - println("Your numbers: " + prompt) - println("Enter your expression:") - val reader = BufferedReader(InputStreamReader(System.`in`)) - val expr = StringBuilder(reader.readLine()) - try { - val result = Evaluator(expr, numbers).evaluateAll() - if (result != 24) - println("Sorry, that's " + result) - else - println("You won!"); - } - catch(e: Throwable) { - println(e.getMessage()) - } -} \ No newline at end of file diff --git a/examples/src/UnionFind.jetl b/examples/src/UnionFind.jetl deleted file mode 100644 index 917d724d9b0..00000000000 --- a/examples/src/UnionFind.jetl +++ /dev/null @@ -1,33 +0,0 @@ -class UnionFind { - private val data = IMutableList() - - fun add() : Int { - val size = data.size - data.add(size) - size - } - - private fun parent(x : Int) : Int { - val p = data[x]; - if (p == x) { - return x; - } - val result = parent(p); - data[x] = result; - } - - fun union(a : Int, b : Int) { - val pa = parent(a) - val pb = parent(b) - if (pa != pb) { - if (Random.nextInt().isOdd) { - data[pb] = pa - } else { - data[pa] = pb - } - } - } -} - -val Int.isOdd : Boolean - get() = this % 2 != 0 diff --git a/examples/src/UpdfateOperation.jetl b/examples/src/UpdfateOperation.jetl deleted file mode 100644 index 4d2aa3586f5..00000000000 --- a/examples/src/UpdfateOperation.jetl +++ /dev/null @@ -1,14 +0,0 @@ -class Pair(x : Int, y : Int) { - class object { - fun copy(from : Pair, x : Int = from.x, y : Int = from.y) = new Pair(x, y) - } -} - -// One can say: -val p = new Point(1, 2) -val p1 = Point.Copy(p, x = 2) -val p2 = Point.Copy(p1, y = -1) -val p3 = Point.Copy(p) - -// Such copy(...) methods can be automatically generated by the compiler -// whenever there is a primary constructor \ No newline at end of file diff --git a/examples/src/With.jetl b/examples/src/With.jetl deleted file mode 100644 index 8dc0a46640b..00000000000 --- a/examples/src/With.jetl +++ /dev/null @@ -1,15 +0,0 @@ -[inline] fun with(receiver : T, body : {T.() : Unit}) = receiver.body() - -fun example() { - - with(java.lang.System.out) { - println("foo"); - print("bar"); - } - - System.out.{ - println("foo"); - print("bar"); - }() - -} \ No newline at end of file diff --git a/examples/src/actors/actors.iml b/examples/src/actors/actors.iml deleted file mode 100644 index 00069f36085..00000000000 --- a/examples/src/actors/actors.iml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/examples/src/actors/actors.ipr b/examples/src/actors/actors.ipr deleted file mode 100644 index d7df3849c28..00000000000 --- a/examples/src/actors/actors.ipr +++ /dev/null @@ -1,173 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/src/actors/actors.iws b/examples/src/actors/actors.iws deleted file mode 100644 index fac93df883a..00000000000 --- a/examples/src/actors/actors.iws +++ /dev/null @@ -1,523 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - localhost - 5050 - - - - - - - 1328866126960 - 1328866126960 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - No facets are configured - - - - - - - - - - - - - - - 1.6 - - - - - - - - actors - - - - - - - - 1.6 - - - - - - - - KotlinRuntime - - - - - - - - - diff --git a/examples/src/actors/src/Actors.kt b/examples/src/actors/src/Actors.kt deleted file mode 100644 index 3c858b82829..00000000000 --- a/examples/src/actors/src/Actors.kt +++ /dev/null @@ -1,184 +0,0 @@ -package org.jetbrains.kotlin.examples.actors - -import kotlin.concurrent.* -import kotlin.util.* - -import java.util.concurrent.* -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater -import java.util.Date -import java.util.concurrent.atomic.AtomicInteger -import java.util.concurrent.atomic.AtomicReference -import java.util.concurrent.atomic.AtomicLong - -/* -Message handling class which process only one message at any given moment - -Three main ways to use it -- post and forget -- post and await result -- post and assign callback to be called when message processed -*/ -abstract class Actor(protected val executor: Executor, val fair: Boolean = false) { - private val queue = Ref() - - class Ref() : AtomicReference>(emptyQueue), Runnable { - override fun run() { - if (!fair) - runUnfair() - else - runFair() - } - - private fun runFair() { - while(true) { - val q = get() - if(q.identityEquals(busyEmptyQueue)) { - if(compareAndSet(busyEmptyQueue, emptyQueue)) { - break - } - } - else { - val removed = q.removeFirst() - val newQueue = if(removed.second.empty) busyEmptyQueue else removed.second - if(compareAndSet(q, newQueue)) { - doProcess(removed.first) - executor.execute(this) - break - } - } - } - } - - private fun runUnfair() { - while (true) { - val q = get() - if(q.identityEquals(busyEmptyQueue)) { - if (compareAndSet(q, emptyQueue)) { - break - } - } - else { - if (compareAndSet(q, busyEmptyQueue)) { - var l = q.output - while (!l.empty) { - doProcess(l.head) - l = l.tail - } - l = q.input.reversed() - while (!l.empty) { - doProcess(l.head) - l = l.tail - } - } - } - } - } - - override fun toString(): String? = null - } - - /* - Handle message and return result - This method guaranteed to be executed only one per object at any given time - */ - protected abstract fun onMessage(message: Any) : Any? - - /* - Post message to the actor. - The method returns immediately and the message itself will be processed later - */ - fun post(message: Any) { - messagesSent.incrementAndGet() - while(true) { - val q = queue.get() - val newQueue = (if (q.identityEquals(busyEmptyQueue)) emptyQueue else q) add message - if(queue.compareAndSet(q, newQueue)) { - if (q.identityEquals(emptyQueue)) { - executor.execute(queue) - } - break - } - } - } - - fun postFirst(message: Any) { - messagesSent.incrementAndGet() - while(true) { - val q = queue.get() - val newQueue = (if (q.identityEquals(busyEmptyQueue)) emptyQueue else q) addFirst message - if(queue.compareAndSet(q, newQueue)) { - if (q.identityEquals(emptyQueue)) { - executor.execute(queue) - } - break - } - } - } - - /* - Post message to the actor and schedule callback to be executed on given executor when message processed - */ - fun post(message: Any, executor: Executor = this.executor, callback: (Any?)->Unit) = - post(Callback(message, executor, callback)) - - /* - Send message to the actor and await result - */ - fun send(message: Any) : Any? { - val request = Request(message) - post(request) - request.await() - return request.result - } - - private fun doProcess(message: Any) { - messagesProcessed.incrementAndGet() - when(message) { - is Request -> { - message.result = onMessage(message.message) - message.countDown() - } - is Callback -> { - val result = onMessage(message.message) - message.executor execute { - val callback = message.callback; - callback(result) - } - } - else -> onMessage(message) - } - } - - /* - Create actor on the same executor - */ - fun actor(handler: (Any)->Any?) = executor.actor(handler) - - class object { - val emptyQueue = FunctionalQueue() - val busyEmptyQueue = FunctionalQueue() add "busy empty queue" - - class Request(val message: Any) : java.util.concurrent.CountDownLatch(1) { - var result: Any? = null - } - - class Callback(val message: Any, val executor: Executor, val callback: (Any?) -> Unit) - - val messagesSent = AtomicLong() - val messagesProcessed = AtomicLong() - - val timer = fixedRateTimer(daemon=true, period=5000.toLong()) { - val sent = messagesSent.get() - val received = messagesProcessed.get() - println("Actors stat: Sent: $sent Processed: $received Pending: ${sent-received}") - } - } -} - -fun Executor.actor(handler: (Any)->Any?) : Actor = object: Actor(this) { - override fun onMessage(message: Any) { - handler(message) - } -} - -fun singleThreadActor(handler: (Any)->Any?) : Actor = Executors.newSingleThreadExecutor()!!.actor(handler) diff --git a/examples/src/actors/src/Main.kt b/examples/src/actors/src/Main.kt deleted file mode 100644 index 44ae975a68f..00000000000 --- a/examples/src/actors/src/Main.kt +++ /dev/null @@ -1,32 +0,0 @@ -package org.jetbrains.kotlin.examples.actors - -import java.util.concurrent.Executors - -fun main(args: Array) { - val numberOfSymbols = 10000 - val numberOfShards = 10 - val numberOfClients = 100000 - val stocksPerClient = 4 - - val stockServer = StockServer(numberOfShards) - - for (i in 0..numberOfSymbols) - stockServer post RegisterStock(i.toString()) - - println("Stock server started") - - val executor = Executors.newFixedThreadPool(4*Runtime.getRuntime()!!.availableProcessors())!! - - for(i in 0..numberOfClients) { - val client = executor.actor{ message -> - // println(message) - } - - for (k in 1..stocksPerClient) { - val stock = (Math.random() * numberOfSymbols).toInt() - stockServer post Subscribe(stock.toString(), client) - } - } - - println("clients connected") -} diff --git a/examples/src/actors/src/Messages.kt b/examples/src/actors/src/Messages.kt deleted file mode 100644 index 1f1751942c6..00000000000 --- a/examples/src/actors/src/Messages.kt +++ /dev/null @@ -1,23 +0,0 @@ -package org.jetbrains.kotlin.examples.actors - -import kotlin.concurrent.* -import java.util.concurrent.Executor -import java.util.LinkedList -import java.util.concurrent.Executors -import java.util.HashMap -import java.util.HashSet - -open class StockMessage(val symbol: String) { - class object { - val UpdateModel = "update" - val DoUpdateModel = "do update" - } -} - -class RegisterStock(symbol: String) : StockMessage(symbol) - -class Subscribe(symbol: String, val subscriber: Actor) : StockMessage(symbol) - -class Unsubscribe(symbol: String, val subscriber: Actor) : StockMessage(symbol) - -class PriceUpdate(symbol: String, val price: Double) : StockMessage(symbol) diff --git a/examples/src/actors/src/StatCalculator.kt b/examples/src/actors/src/StatCalculator.kt deleted file mode 100644 index ade9ede32f7..00000000000 --- a/examples/src/actors/src/StatCalculator.kt +++ /dev/null @@ -1,34 +0,0 @@ -package org.jetbrains.kotlin.examples.actors - -import kotlin.concurrent.* -import org.jetbrains.kotlin.examples.actors.Actor -import java.util.concurrent.Executors -import java.util.LinkedList - -class StatCalculator() : Actor(Executors.newSingleThreadExecutor()!!) { - val list = LinkedList () - var average = 0.toLong() - var sum = 0.toLong() - var cnt = 0.toLong() - - val timer = fixedRateTimer(period=2000.toLong(), daemon=true) { - this@StatCalculator post "print" - } - - override fun onMessage(msg: Any) { - when(msg) { - is Long -> { - list.add(msg) - sum += msg - if (list.size() > 20) - sum -= list.removeFirst() - average = sum / list.size() - cnt++ - } - "print" -> { - println("Avr. period:[${average}ms] # updates:[$cnt]") - } - else -> {} - } - } -} diff --git a/examples/src/actors/src/Stock.kt b/examples/src/actors/src/Stock.kt deleted file mode 100644 index 680295566b2..00000000000 --- a/examples/src/actors/src/Stock.kt +++ /dev/null @@ -1,22 +0,0 @@ -package org.jetbrains.kotlin.examples.actors - -import kotlin.concurrent.* -import java.util.concurrent.Executor -import java.util.LinkedList -import java.util.concurrent.Executors -import java.util.HashMap -import java.util.HashSet - -class Stock(val symbol: String) { - val subscribers = HashSet() - - var price = 10*Math.random() - - fun update() { - price += Math.random() - 0.5 - val priceUpdate = PriceUpdate(symbol, price) - for(s in subscribers) { - s post priceUpdate - } - } -} diff --git a/examples/src/actors/src/StockServer.kt b/examples/src/actors/src/StockServer.kt deleted file mode 100644 index 50c7e8d0098..00000000000 --- a/examples/src/actors/src/StockServer.kt +++ /dev/null @@ -1,38 +0,0 @@ -package org.jetbrains.kotlin.examples.actors - -import kotlin.concurrent.* -import java.util.concurrent.Executor -import java.util.LinkedList -import java.util.concurrent.Executors -import java.util.HashMap -import java.util.HashSet - -class StockServer(val numberOfShards : Int) : Actor(Executors.newFixedThreadPool(numberOfShards+1)!!) { - private val stockToServer = HashMap () - - private val statCalculator = StatCalculator() - - private val shards = Array (numberOfShards, { (i: Int) -> StockServerShard(statCalculator, executor) }) - - private val timer = fixedRateTimer(period=1000.toLong(), daemon=true) { - for(s in shards) - s post StockMessage.UpdateModel - } - - override fun onMessage(message: Any): Unit { - when (message) { - is RegisterStock -> { - val shard = shards[stockToServer.size() % shards.size] - stockToServer.put(message.symbol, shard) - shard post message - } - is Subscribe -> { - stockToServer.get(message.symbol)?.post(message) - } - is Unsubscribe -> { - stockToServer.get(message.symbol)?.post(message) - } - else -> {} - } - } -} \ No newline at end of file diff --git a/examples/src/actors/src/StockServerShard.kt b/examples/src/actors/src/StockServerShard.kt deleted file mode 100644 index 96b20d0b4b7..00000000000 --- a/examples/src/actors/src/StockServerShard.kt +++ /dev/null @@ -1,44 +0,0 @@ -package org.jetbrains.kotlin.examples.actors - -import kotlin.concurrent.* -import java.util.concurrent.Executor -import java.util.LinkedList -import java.util.concurrent.Executors -import java.util.HashMap -import java.util.HashSet - -class StockServerShard(val statCalculator : StatCalculator, executor: Executor) : Actor(executor) { - private val stocks = HashMap(); - - private var previousTime = System.currentTimeMillis(); - - private var updateScheduled = false - - override fun onMessage(message: Any) { - when(message) { - StockMessage.DoUpdateModel -> { - val timeMillis = System.currentTimeMillis() - for(s in stocks.values()) { - s.update() - } - statCalculator post (timeMillis - previousTime) - previousTime = timeMillis - updateScheduled = false - } - StockMessage.UpdateModel -> { - if (!updateScheduled) { - this post StockMessage.DoUpdateModel - updateScheduled = true - } - } - is RegisterStock -> - stocks.put(message.symbol, Stock(message.symbol)) - is Subscribe -> - stocks.get(message.symbol)?.subscribers?.add(message.subscriber) - is Unsubscribe -> - stocks.get(message.symbol)?.subscribers?.add(message.subscriber) - else -> {} - } - } -} - diff --git a/examples/src/array/MutableArray.jetl b/examples/src/array/MutableArray.jetl deleted file mode 100644 index cb270fa33a8..00000000000 --- a/examples/src/array/MutableArray.jetl +++ /dev/null @@ -1,13 +0,0 @@ -/** - These declarations are "shallow" in the sense that they are not really compiled, only the type-checker uses them -*/ - -open class ReadOnlyArray : ISized { - [operator] fun get(index : Int) : T -} - -open class WriteOnlyArray : ISized { // This is needed to keep IIterator's covariant - [operator] fun set(index : Int, value : T) -} - -class MutableArray : ReadOnlyArray, WriteOnlyArray {/*...*/} \ No newline at end of file diff --git a/examples/src/benchmarks/src/binary_trees/BinaryTrees.java b/examples/src/benchmarks/src/binary_trees/BinaryTrees.java deleted file mode 100644 index c9e202d0705..00000000000 --- a/examples/src/benchmarks/src/binary_trees/BinaryTrees.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package binary_trees; - -public class BinaryTrees { - - private final static int minDepth = 4; - - public static void main(String[] args){ - final long millis = System.currentTimeMillis(); - - int n = 20; - if (args.length > 0) n = Integer.parseInt(args[0]); - - int maxDepth = (minDepth + 2 > n) ? minDepth + 2 : n; - int stretchDepth = maxDepth + 1; - - int check = (TreeNode.bottomUpTree(0,stretchDepth)).itemCheck(); - System.out.println("stretch tree of depth "+stretchDepth+"\t check: " + check); - - TreeNode longLivedTree = TreeNode.bottomUpTree(0,maxDepth); - - for (int depth=minDepth; depth<=maxDepth; depth+=2){ - int iterations = 1 << (maxDepth - depth + minDepth); - check = 0; - - for (int i=1; i<=iterations; i++){ - check += (TreeNode.bottomUpTree(i,depth)).itemCheck(); - check += (TreeNode.bottomUpTree(-i,depth)).itemCheck(); - } - System.out.println((iterations*2) + "\t trees of depth " + depth + "\t check: " + check); - } - System.out.println("long lived tree of depth " + maxDepth + "\t check: "+ longLivedTree.itemCheck()); - - long total = System.currentTimeMillis() - millis; - System.out.println("[Binary Trees-" + System.getProperty("project.name")+ " Benchmark Result: " + total + "]"); - } - - - private static class TreeNode - { - private TreeNode left, right; - private int item; - - TreeNode(int item){ - this.item = item; - } - - private static TreeNode bottomUpTree(int item, int depth){ - if (depth>0){ - return new TreeNode( - bottomUpTree(2*item-1, depth-1) - , bottomUpTree(2*item, depth-1) - , item - ); - } - else { - return new TreeNode(item); - } - } - - TreeNode(TreeNode left, TreeNode right, int item){ - this.left = left; - this.right = right; - this.item = item; - } - - private int itemCheck(){ - // if necessary deallocate here - if (left==null) - return item; - else { - return item + left.itemCheck() - right.itemCheck(); - } - } - } -} - diff --git a/examples/src/benchmarks/src/binary_trees/BinaryTrees.kt b/examples/src/benchmarks/src/binary_trees/BinaryTrees.kt deleted file mode 100644 index a1ae06c51cb..00000000000 --- a/examples/src/benchmarks/src/binary_trees/BinaryTrees.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package binary_trees; - -val minDepth = 4 - -fun main(args: Array) { - val millis = System.currentTimeMillis() - - val n = if (args.size > 0) Integer.parseInt(args[0]) else 20; - - val maxDepth = if (minDepth + 2 > n) minDepth + 2 else n - val stretchDepth = maxDepth + 1 - - var check = bottomUpTree(0,stretchDepth).itemCheck() - System.out?.println("stretch tree of depth "+stretchDepth+"\t check: " + check); - - val longLivedTree = bottomUpTree(0,maxDepth); - - var depth = minDepth - while(depth<=maxDepth){ - val iterations = 1 shl (maxDepth - depth + minDepth) - check = 0 - - for (i in 1..iterations){ - check += bottomUpTree(i,depth).itemCheck() - check += bottomUpTree(-i,depth).itemCheck() - } - System.out?.println("${iterations*2}\t trees of depth $depth\t check: $check") - depth+=2 - } - System.out?.println("long lived tree of depth " + maxDepth + "\t check: "+ longLivedTree.itemCheck()); - - val total = System.currentTimeMillis() - millis - System.out?.println("[Binary Trees-" + System.getProperty("project.name") + " Benchmark Result: " + total + "]"); -} - -fun bottomUpTree(item: Int, depth: Int) : TreeNode = - if (depth>0){ - TreeNode(item, bottomUpTree(2*item-1, depth-1), bottomUpTree(2*item, depth-1)) - } - else { - TreeNode(item) - } - -class TreeNode(val item: Int, val left: TreeNode? = null, val right: TreeNode? = null) { - fun itemCheck() : Int { - var res = item - if(left != null) - res += left.itemCheck() - if(right != null) - res -= right.itemCheck() - return res - } -} diff --git a/examples/src/benchmarks/src/flist/FList.java b/examples/src/benchmarks/src/flist/FList.java deleted file mode 100644 index c0f2c276939..00000000000 --- a/examples/src/benchmarks/src/flist/FList.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package flist; - -import java.util.NoSuchElementException; - -abstract public class FList { - abstract T getHead(); - - abstract FList getTail(); - - abstract FList plus(T element); - - static class Empty extends FList { - - @Override - T getHead() { - throw new NoSuchElementException(); - } - - @Override - FList getTail() { - throw new NoSuchElementException(); - } - - @Override - FList plus(T element) { - return new OneElementList(element); - } - } - - static class OneElementList extends FList { - private T element; - - public OneElementList(T element) { - super(); - this.element = element; - } - - @Override - T getHead() { - return element; - } - - @Override - FList getTail() { - return new Empty(); - } - - @Override - FList plus(T element) { - return new StandardList(element, this); - } - } - - private static class StandardList extends FList { - private T head; - private FList tail; - - public StandardList(T head, FList tail) { - this.head = head; - this.tail = tail; - } - - @Override - T getHead() { - return head; - } - - @Override - FList getTail() { - return tail; - } - - @Override - FList plus(T element) { - return new StandardList(element, this); - } - } - - public static void main(String[] args) { - for(int k = 0; k != 10; ++k) { - long start = System.currentTimeMillis(); - FList list = new Empty(); - for(int i = 0; i != 5000000; ++i) - list = list.plus(i); - System.out.println(System.currentTimeMillis()-start); - } - } -} diff --git a/examples/src/benchmarks/src/flist/FList.kt b/examples/src/benchmarks/src/flist/FList.kt deleted file mode 100644 index c1db1c3af4d..00000000000 --- a/examples/src/benchmarks/src/flist/FList.kt +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flist_kotlin - -abstract class FList { - abstract val head : T - abstract val tail : FList - - abstract fun plus(element: T) : FList -} - -class EmptyFList() : FList() { - override val head: T - get() = throw java.util.NoSuchElementException() - - override val tail : EmptyFList - get() = EmptyFList() - - override fun plus(element: T) : FList = OneElementFList(element) -} - -class OneElementFList (override val head: T): FList() { - override val tail : EmptyFList - get() = EmptyFList() - - override fun plus(element: T) : FList = StandardFList(element, this) -} - -class StandardFList (override val head: T, override val tail: FList) : FList() { - override fun plus(element: T) : FList = StandardFList(element, this) -} - -fun FList.plus2(element: T): FList = - when(this) { - is EmptyFList<*> -> OneElementFList(element) - else -> StandardFList(element, this) - } - -fun FList.plus3(element: T) : FList = - if(this is EmptyFList<*>) - OneElementFList(element) - else - StandardFList(element, this) - -fun main(args: Array) { - for(k in 0..3) { - val start0 = System.currentTimeMillis() - - var flist0 : FList = EmptyFList() - for(i in 0..5000000) - flist0 = flist0 + i - - System.out?.println(System.currentTimeMillis() - start0) - - val start = System.currentTimeMillis() - - var flist : FList = EmptyFList() - for(i in 0..5000000) - flist = flist.plus2(i) - - System.out?.println(System.currentTimeMillis() - start) - - val start2 = System.currentTimeMillis() - - var flist2 : FList = EmptyFList() - for(i in 0..5000000) - flist2 = flist2.plus3(i) - - System.out?.println(System.currentTimeMillis() - start2) - System.out?.println() - } -} diff --git a/examples/src/benchmarks/src/lockperf/LockPerf.java b/examples/src/benchmarks/src/lockperf/LockPerf.java deleted file mode 100644 index 99ab0c4a334..00000000000 --- a/examples/src/benchmarks/src/lockperf/LockPerf.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package lockperf; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.ReentrantLock; - -public class LockPerf { - public static void main(String[] args) { - int processors = Runtime.getRuntime().availableProcessors(); - for (int threadNum = 1; threadNum <= 1024; threadNum = threadNum < 2 * processors ? threadNum + 1 : threadNum * 2) { - final AtomicInteger counter = new AtomicInteger(); - final CountDownLatch cdl = new CountDownLatch(threadNum); - - final ReentrantLock lock = new ReentrantLock(); - - long start = System.currentTimeMillis(); - for (int i = 0; i < threadNum; ++i) { - new Thread(new Runnable() { - public void run() { - while (true) { - lock.lock(); - try { - if (counter.get() == 100000000) { - cdl.countDown(); - break; - } - else { - counter.incrementAndGet(); - } - } finally { - lock.unlock(); - } - } - - } - }).start(); - } - - try { - cdl.await(); - } catch (InterruptedException e) {// - } - System.out.println(threadNum + " " + (System.currentTimeMillis() - start)); - } - } -} diff --git a/examples/src/benchmarks/src/lockperf/LockPerf.kt b/examples/src/benchmarks/src/lockperf/LockPerf.kt deleted file mode 100644 index bc06ec40bc0..00000000000 --- a/examples/src/benchmarks/src/lockperf/LockPerf.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package lockperf_kotlin - -import kotlin.io.* -import kotlin.util.* -import kotlin.concurrent.* - -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.locks.ReentrantLock; - -fun Int.latch(op: CountDownLatch.() -> T) : T { - val cdl = CountDownLatch(this) - val res = cdl.op() - cdl.await() - return res -} - -fun main(args: Array) { - val processors = Runtime.getRuntime()!!.availableProcessors() - var threadNum = 1 - while(threadNum <= 1024) { - val counter = AtomicInteger() - - val duration = measureTimeMillis { - threadNum.latch{ - val lock = ReentrantLock() - for(i in 0..threadNum-1) { - thread { - while(true) { - lock.lock() - try { - if (counter.get() == 100000000) { - countDown() - break; - } else { - counter.incrementAndGet() - } - } - finally { - lock.unlock() - } - } - } - } - } - } - - println(threadNum.toString() + " " + duration) - - if(threadNum < 2 * processors) threadNum++ else threadNum = 2*threadNum - } -} diff --git a/examples/src/benchmarks/src/quicksort/Quicksort.java b/examples/src/benchmarks/src/quicksort/Quicksort.java deleted file mode 100644 index 10343e86622..00000000000 --- a/examples/src/benchmarks/src/quicksort/Quicksort.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package quicksort; - -public class Quicksort { - - public static void swap(int[] a, int i, int j) { - int temp = a[i]; - a[i] = a[j]; - a[j] = temp; - } - - public static void quicksort(int[] a, int L, int R) { - int m = a[(L + R) / 2]; - int i = L; - int j = R; - while (i <= j) { - while (a[i] < m) - i++; - while (a[j] > m) - j--; - if (i <= j) { - swap(a, i++, j--); - } - } - if (L < j) - quicksort(a, L, j); - if (R > i) - quicksort(a, i, R); - } - - public static void quicksort(int[] a) { - quicksort(a, 0, a.length - 1); - } - - public static void main(String[] args) { - long start = System.currentTimeMillis(); - - // Sample data - int[] a = new int[100000000]; - for (int i = 0; i < a.length; i++) { - a[i] = i * 3 / 2 + 1; - if (i % 3 == 0) - a[i] = -a[i]; - } - - quicksort(a); - - long total = System.currentTimeMillis() - start; - System.out.println("[Quicksort-" + System.getProperty("project.name")+ " Benchmark Result: " + total + "]"); - } -} diff --git a/examples/src/benchmarks/src/quicksort/Quicksort.kt b/examples/src/benchmarks/src/quicksort/Quicksort.kt deleted file mode 100644 index 200a95bbd9e..00000000000 --- a/examples/src/benchmarks/src/quicksort/Quicksort.kt +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package quicksort - -fun IntArray.swap(i:Int, j:Int) { - val temp = this[i] - this[i] = this[j] - this[j] = temp -} - -fun IntArray.quicksort() = quicksort(0, size-1) - -fun IntArray.quicksort(L: Int, R:Int) { - val m = this[(L + R) / 2] - var i = L - var j = R - while (i <= j) { - while (this[i] < m) - i++ - while (this[j] > m) - j-- - if (i <= j) { - swap(i++, j--) - } - } - if (L < j) - quicksort(L, j) - if (R > i) - quicksort(i, R) -} - -fun main(array: Array) { - val start = System.currentTimeMillis() - - val a = IntArray(100000000) - var i = 0 - val len = a.size - while (i < len) { - a[i] = i * 3 / 2 + 1 - if (i % 3 == 0) - a[i] = -a[i] - i++ - } - - a.quicksort() - - val total = System.currentTimeMillis() - start - System.out?.println("[Quicksort-" + System.getProperty("project.name")+ " Benchmark Result: " + total + "]"); -} diff --git a/examples/src/benchmarks/src/spectralnorm/SpectralNorm.java b/examples/src/benchmarks/src/spectralnorm/SpectralNorm.java deleted file mode 100644 index 0e0c3c7dd80..00000000000 --- a/examples/src/benchmarks/src/spectralnorm/SpectralNorm.java +++ /dev/null @@ -1,186 +0,0 @@ -package spectralnorm_kotlin; -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* -The Computer Language Benchmarks Game -http://shootout.alioth.debian.org/ - -Based on C# entry by Isaac Gouy -contributed by Jarkko Miettinen -Parallel by The Anh Tran -*/ - -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.concurrent.CyclicBarrier; - -public class SpectralNorm -{ - private static final NumberFormat formatter = new DecimalFormat ("#.000000000"); - - public static void main (String[] args) - { - int n = 5500; - if (args.length > 0) n = Integer.parseInt (args[0]); - - final long millis = System.currentTimeMillis(); - System.out.println (formatter.format (spectralnormGame (n)) ); - long total = System.currentTimeMillis() - millis; - System.out.println("[SpectralNorm-" + System.getProperty("project.name")+ " Benchmark Result: " + total + "]"); - } - - - private static final double spectralnormGame (int n) - { - // create unit vector - double[] u = new double[n]; - double[] v = new double[n]; - double[] tmp = new double[n]; - - for (int i = 0; i < n; i++) - u[i] = 1.0; - - // get available processor, then set up syn object - int nthread = Runtime.getRuntime ().availableProcessors (); - Approximate.barrier = new CyclicBarrier (nthread); - - int chunk = n / nthread; - Approximate[] ap = new Approximate[nthread]; - - for (int i = 0; i < nthread; i++) - { - int r1 = i * chunk; - int r2 = (i < (nthread -1)) ? r1 + chunk : n; - - ap[i] = new Approximate (u, v, tmp, r1, r2); - } - - - double vBv = 0, vv = 0; - for (int i = 0; i < nthread; i++) - { - try - { - ap[i].join (); - - vBv += ap[i].m_vBv; - vv += ap[i].m_vv; - } - catch (Exception e) - { - e.printStackTrace (); - } - } - - return Math.sqrt (vBv/vv); - } - - - private static class Approximate extends Thread - { - private static CyclicBarrier barrier; - - private double[] _u; - private double[] _v; - private double[] _tmp; - - private int range_begin, range_end; - private double m_vBv = 0, m_vv = 0; - - - public Approximate (double[] u, double[] v, double[] tmp, int rbegin, int rend) - { - super (); - - _u = u; - _v = v; - _tmp = tmp; - - range_begin = rbegin; - range_end = rend; - - start (); - } - - public void run () - { - // 20 steps of the power method - for (int i = 0; i < 10; i++) - { - MultiplyAtAv (_u, _tmp, _v); - MultiplyAtAv (_v, _tmp, _u); - } - - for (int i = range_begin; i < range_end; i++) - { - m_vBv += _u[i] * _v[i]; - m_vv += _v[i] * _v[i]; - } - } - - /* return element i,j of infinite matrix A */ - private final static double eval_A (int i, int j) - { - int div = ( ((i+j) * (i+j+1) >>> 1) +i+1 ); - return 1.0 / div; - } - - /* multiply vector v by matrix A, each thread evaluate its range only */ - private final void MultiplyAv (final double[] v, double[] Av) - { - for (int i = range_begin; i < range_end; i++) - { - double sum = 0; - for (int j = 0; j < v.length; j++) - sum += eval_A (i, j) * v[j]; - - Av[i] = sum; - } - } - - /* multiply vector v by matrix A transposed */ - private final void MultiplyAtv (final double[] v, double[] Atv) - { - for (int i = range_begin; i < range_end; i++) - { - double sum = 0; - for (int j = 0; j < v.length; j++) - sum += eval_A (j, i) * v[j]; - - Atv[i] = sum; - } - } - - /* multiply vector v by matrix A and then by matrix A transposed */ - private final void MultiplyAtAv (final double[] v, double[] tmp, double[] AtAv) - { - try - { - MultiplyAv (v, tmp); - // all thread must syn at completion - barrier.await (); - MultiplyAtv (tmp, AtAv); - // all thread must syn at completion - barrier.await (); - } - catch (Exception e) - { - e.printStackTrace (); - } - } - } -} diff --git a/examples/src/benchmarks/src/spectralnorm/SpectralNorm.kt b/examples/src/benchmarks/src/spectralnorm/SpectralNorm.kt deleted file mode 100644 index 2e7aed8727d..00000000000 --- a/examples/src/benchmarks/src/spectralnorm/SpectralNorm.kt +++ /dev/null @@ -1,128 +0,0 @@ -package spectralnorm_kotlin - -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.concurrent.CyclicBarrier; - -val formatter = DecimalFormat ("#.000000000"); - -fun main (args : Array) { - var n = 5500 - if (args.size > 0) - n = Integer.parseInt (args[0]); - - val millis = System.currentTimeMillis() - System.out?.println (formatter.format (spectralnormGame (n)) ) - val total = System.currentTimeMillis() - millis; - System.out?.println("[SpectralNorm-" + System.getProperty("project.name")+ " Benchmark Result: " + total + "]"); -} - -fun spectralnormGame(n: Int) : Double { - val u = DoubleArray(n) - val v = DoubleArray(n) - val tmp = DoubleArray(n) - - for(i in u.indices) { - u[i] = 1.0 - } - - val nthread = Runtime.getRuntime ()!!.availableProcessors (); - barrier = CyclicBarrier (nthread); - - val chunk = n / nthread - val ap = Array(nthread,{ - val r1 = it * chunk; - val r2 = if(it < (nthread -1)) r1 + chunk else nthread; - - Approximate (u, v, tmp, r1, r2) - }) - - var vBv = 0.toDouble() - var vv = 0.toDouble(); - for (i in 0..nthread-1) { - try { - ap[i].join (); - - vBv += ap[i].m_vBv; - vv += ap[i].m_vv; - } - catch (e: Exception ) - { - e.printStackTrace (); - } - } - - return Math.sqrt (vBv/vv); -} - -fun eval_A (i: Int, j: Int) = 1.0 / ( ((i+j) * (i+j+1) shr 1) +i+1 ) - -var barrier : CyclicBarrier? = null - -class Approximate(val u: DoubleArray, val v: DoubleArray, val _tmp: DoubleArray, val rbegin: Int, val rend: Int) : Thread() { - class object { - } - - var m_vBv = 0.0 - var m_vv = 0.0 - - { - start() - } - - override fun run () { - for(i in 0..10) { - MultiplyAtAv (u, _tmp, v); - MultiplyAtAv (v, _tmp, u); - } - - for(i in rbegin..rend) { - m_vBv += u[i] * v[i]; - m_vv += v[i] * v[i]; - } - } - -/* multiply vector v by matrix A, each thread evaluate its range only */ - fun MultiplyAv (v: DoubleArray, Av: DoubleArray) - { - for (i in rbegin..rend) - { - var sum = 0.0; - for (j in v.indices) - sum += eval_A (i, j) * v[j]; - - Av[i] = sum; - } - } - -/* multiply vector v by matrix A transposed */ - fun MultiplyAtv (v: DoubleArray, Atv: DoubleArray) - { - for (i in rbegin..rend) - { - var sum = 0.toDouble() - for (j in v.indices) - sum += eval_A (j, i) * v[j]; - - Atv[i] = sum; - } - } - -/* multiply vector v by matrix A and then by matrix A transposed */ - fun MultiplyAtAv (v: DoubleArray, tmp: DoubleArray, AtAv: DoubleArray) - { - try - { - MultiplyAv (v, tmp); - // all thread must syn at completion - barrier?.await (); - MultiplyAtv (tmp, AtAv); - // all thread must syn at completion - barrier?.await (); - } - catch (e: Exception) - { - e.printStackTrace (); - } - } -} \ No newline at end of file diff --git a/examples/src/benchmarks/src/threadring/ThreadRing.java b/examples/src/benchmarks/src/threadring/ThreadRing.java deleted file mode 100644 index 8a67a941ec0..00000000000 --- a/examples/src/benchmarks/src/threadring/ThreadRing.java +++ /dev/null @@ -1,141 +0,0 @@ -package threadring; -/** - * The Computer Language Benchmarks Game - * http://shootout.alioth.debian.org/ - * - * contributed by Fabien Le Floc'h - * - * Java implementation of thread-ring benchmark. Best performance is achieved with - * MAX_THREAD=1 as the thread-ring test is bested with only 1 os thread. - * This implementation shows using a simple thread pool solves the thread context - * switch issue. - */ - -import java.util.concurrent.*; - -public class ThreadRing { - private static final int MAX_NODES = 503; - private static final int MAX_THREADS = 503; - - private ExecutorService executor; - private final int N; - - static final CountDownLatch cdl = new CountDownLatch(1); - - public static void main(String[] args) throws InterruptedException { - long start = System.currentTimeMillis(); - int n = 5000000; - try { - n = Integer.parseInt(args[0]); - } catch (Exception e) {} - ThreadRing ring = new ThreadRing(n); - Node node = ring.start(MAX_NODES); - node.sendMessage(new TokenMessage(1,0)); - cdl.await(); - - long total = System.currentTimeMillis() - start; - System.out.println("[ThreadRing-" + System.getProperty("project.name")+ " Benchmark Result: " + total + "]"); - } - - public ThreadRing(int n) { - N = n; - } - - public Node start(int n) { - Node[] nodes = spawnNodes(n); - connectNodes(n, nodes); - return nodes[0]; - } - - private Node[] spawnNodes(int n) { - executor = Executors.newFixedThreadPool(MAX_THREADS); - Node[] nodes = new Node[n+1]; - for (int i = 0; i < n ; i++) { - nodes[i] = new Node(i+1, null); - } - return nodes; - } - - public void connectNodes(int n, Node[] nodes) { - nodes[n] = nodes[0]; - for (int i=0; i queue = new LinkedBlockingQueue(); - private boolean isActive = false; - private int counter; - - public Node(int id, Node nextNode) { - this.nodeId = id; - this.nextNode = nextNode; - this.counter = 0; - } - - public void connect(Node node) { - this.nextNode = node; - isActive = true; - } - - public void sendMessage(TokenMessage m) { - queue.add(m); - executor.execute(this); - } - - - public void run() { - if (isActive) { - try { - TokenMessage m = queue.take(); - if (m.isStop) { - int nextValue = m.value+1; - if (nextValue == MAX_NODES) { -// System.out.println("last one"); - executor.shutdown(); - cdl.countDown(); - } - else { - m.value = nextValue; - nextNode.sendMessage(m); - } - isActive = false; -// System.out.println("ending node "+nodeId); - } - else { - if (m.value == N) { - System.out.println(nodeId); - nextNode.sendMessage(new TokenMessage(nodeId, 0, true)); - } - else { - m.value = m.value + 1; - nextNode.sendMessage(m); - } - } - } catch (InterruptedException ie) { - ie.printStackTrace(); - } - } - } - } -} diff --git a/examples/src/benchmarks/src/threadring/ThreadRing.kt b/examples/src/benchmarks/src/threadring/ThreadRing.kt deleted file mode 100644 index aad7de61627..00000000000 --- a/examples/src/benchmarks/src/threadring/ThreadRing.kt +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package threadring_kotlin - -import java.util.concurrent.*; -import java.util.concurrent.atomic.*; - -val MAX_NODES = 503 -val MAX_THREADS = 503 - -val cdl = CountDownLatch(1) - -fun main(args: Array) { - val start = System.currentTimeMillis() - var n = 5000000; - try { - n = Integer.parseInt(args[0]); - } catch (e: Throwable) { - } - - val ring = ThreadRing(n) - ring.sendMessage(TokenMessage(1,0,false)) - cdl.await(); - - val total = System.currentTimeMillis() - start - System.out?.println("[ThreadRing-" + System.getProperty("project.name")+ " Benchmark Result: " + total + "]") -} - -class TokenMessage(val nodeId : Int, value: Int, val isStop: Boolean) : AtomicInteger(value) - -class ThreadRing(val N: Int) { - val executor = Executors.newFixedThreadPool(MAX_THREADS)!! - - val nodes : Array = Array(MAX_NODES+1, { (it : Int) -> Node(it+1) }); - - { - nodes[nodes.size-1] = nodes[0] - for (i in 0..nodes.size-2) { - nodes[i].connect(nodes[i+1]); - } - } - - fun sendMessage(m : TokenMessage) { - nodes[0].sendMessage(m) - } - - class Node(val nodeId : Int) : Runnable { - val queue = LinkedBlockingQueue() - var isActive = false - var nextNode : Node? = null - - fun sendMessage(m: TokenMessage) { - queue.add(m) - executor.execute(this) - } - - fun connect(next: Node) { - nextNode = next - isActive = true - } - - override fun run() { - if(isActive) { - try { - val m = queue.take() - if(m.isStop) { - val nextValue = m.get()+1 - if (nextValue == MAX_NODES) { - executor.shutdown() - cdl.countDown() - } else { - m.set(nextValue) - nextNode!!.sendMessage(m) - } - isActive = false - } - else { - if (m.get() == N) { - System.out?.println(nodeId); - nextNode!!.sendMessage(TokenMessage(nodeId, 0, true)); - } else { - m.incrementAndGet() - nextNode!!.sendMessage(m); - } - } - } - catch(e: InterruptedException) { - e.printStackTrace() - } - } - } - } -} diff --git a/examples/src/collections/ArrayList.jetl b/examples/src/collections/ArrayList.jetl deleted file mode 100644 index 2f076052068..00000000000 --- a/examples/src/collections/ArrayList.jetl +++ /dev/null @@ -1,77 +0,0 @@ -class ArrayList : IMutableList { - private var data = MutableArray(10) - private var used = 0 - private var version = 0 - - override fun iterator() : IIterator = mutableIterator() - - override fun mutableIterator() : IMutableIterator = object IMutableIterator() { // T is inferred - private val index = 0 - private var myVersion = version - - private fun checkVersion() { - if (version != myVersion) - throw new ConcurrentModificationException() - } - - override fun next() { - checkVersion() - if (hasNext) - throw new NoMoreElementsException() - data[index++] - } - - override val hasNext - get() = index < used - - - override fun remove() { - checkVersion() - val result = ArrayList.this.remove(index - 1) - myVersion = version - result - } - } - - override fun get(index : Int) { - checkIndex(index) - data[index] - } - - private fun checkIndex(index : Int) { - if (index > used) - throw new IndexOutOfBoundsException(index) - } - - override val isEmpty - get() = used == 0 - - - override val size - get() = used - - - override fun set(index : Int, value : T) { - checkIndex(index) - var result = data[index] - data[index] = value - result - } - - override fun add(index : Int, value : T) { - ensureSize(used + 1) - if (index == used) { - data[used++] = value - } else if (index < used) { - for (i in used-1..index) // backwards, special operator... Need to optimize this to be a real indexed loop - data[i + 1] = data[i] - data[index] = value - used++ - } else throw IndexOutOfBoundsException(index) - } - - override fun remove(index : Int) { - for (i in index..used-1) - data[i] = data[i + 1] - } -} \ No newline at end of file diff --git a/examples/src/collections/HashMap.jetl b/examples/src/collections/HashMap.jetl deleted file mode 100644 index b7dc8d37f46..00000000000 --- a/examples/src/collections/HashMap.jetl +++ /dev/null @@ -1,58 +0,0 @@ -trait IEquality { - fun equals(other : Any) : Boolean - = (this as java.lang.Object).equals(other as java.lang.Object) -} - -trait IHashable : IEquality { - val hashCode : Integer - get() = (this as java.lang.Object).hashCode() - -} - -trait IMap { - fun get(key : K) : V - fun set(key : K, value : V) : V - fun remove(key : K) : V - fun containsKey(key : K) : Boolean -} - -class HashableWrapper wraps (val obj : Any) : IHashable - // equals and hashCode implementations are inherited - -[inline] fun Any.hashable() : HashableWrapper = new HashableWrapper(this) - -trait IHashingStrategy { - fun equals(a : K, b : K) : Boolean - fun hashCode(a : K) : Integer -} - -class DefaultHashingStrategy : IHashingStrategy { - override fun equals(a : K, b : K) : Boolean = a.equals(b) - override fun hashCode(a : K) : Integer = a.hashCode -} - -class JavaObjectHashingStrategy : IHashingStrategy { - override fun equals(a : K, b : K) : Boolean - = a.hashable().equals(b) - override fun hashCode(a : K) : Integer - = a.hashable().hashCode -} - -class HashMap : IMap { - private [inline] fun hashCode(a : K) = a.hashable().hashCode - private [inline] fun equals(a : K, b : K) = a.hashable() == b - - // everything else uses these equals() and hashCode()... - -} - -class StrategyHashMap(hashingStrategy : IHashingStrategy) : IMap { - - - // where !(K : IHashable) - this() : this(new JavaObjectHashingStrategy()) {} - - this() where (K : IHashable) : this(new DefaultHashingStrategy()) {} - //... - -} \ No newline at end of file diff --git a/examples/src/collections/IIterable.kt b/examples/src/collections/IIterable.kt deleted file mode 100644 index 69071c4bfb4..00000000000 --- a/examples/src/collections/IIterable.kt +++ /dev/null @@ -1,9 +0,0 @@ -package jet.collections.iterable - -import jet.collections.iterator.IIterator - -trait IIterable { - fun iterator() : IIterator - - inline fun foreach(operation: fun(element: T) : Unit) = iterator() foreach operation -} diff --git a/examples/src/collections/IList.kt b/examples/src/collections/IList.kt deleted file mode 100644 index 7f887a3a539..00000000000 --- a/examples/src/collections/IList.kt +++ /dev/null @@ -1,3 +0,0 @@ -trait IList : IIterable, ISized { - fun get(index : Int) : T -} \ No newline at end of file diff --git a/examples/src/collections/IMutableIterable.jetl b/examples/src/collections/IMutableIterable.jetl deleted file mode 100644 index 1ad49e2aec9..00000000000 --- a/examples/src/collections/IMutableIterable.jetl +++ /dev/null @@ -1,3 +0,0 @@ -open class IMutableIterable : IIterable { - fun mutableIterator() : IMutableIterator -} \ No newline at end of file diff --git a/examples/src/collections/IMutableIterator.jetl b/examples/src/collections/IMutableIterator.jetl deleted file mode 100644 index 1449ab40dca..00000000000 --- a/examples/src/collections/IMutableIterator.jetl +++ /dev/null @@ -1,13 +0,0 @@ -open class IMutableIterator : IIterator { - fun remove() : T - -/* - Considerations: - pro: why not + non iteration breaking - con: counter-intuitive for, e.g., TreeSet - - - fun addBefore(item : T) : Boolean - fun addAfter(item : T) : Boolean -*/ -} \ No newline at end of file diff --git a/examples/src/collections/IMutableList.jetl b/examples/src/collections/IMutableList.jetl deleted file mode 100644 index 55fd048e7a7..00000000000 --- a/examples/src/collections/IMutableList.jetl +++ /dev/null @@ -1,6 +0,0 @@ -open class IMutableList : IList, IMutableIterable { - fun set(index : Int, value : T) : T - fun add(index : Int, value : T) - fun remove(index : Int) : T - fun mutableIterator() : IMutableIterator -} \ No newline at end of file diff --git a/examples/src/collections/IMutableSet.jetl b/examples/src/collections/IMutableSet.jetl deleted file mode 100644 index 95eb05d2456..00000000000 --- a/examples/src/collections/IMutableSet.jetl +++ /dev/null @@ -1,4 +0,0 @@ -open class IMutableSet : ISet, IMutableIterable { - fun add(item : T) : Boolean - fun remove(item : T) : Boolean -} \ No newline at end of file diff --git a/examples/src/collections/ISet.kt b/examples/src/collections/ISet.kt deleted file mode 100644 index ac0d00956ec..00000000000 --- a/examples/src/collections/ISet.kt +++ /dev/null @@ -1,8 +0,0 @@ -package jet.collections.set - -import jet.collections.sized.ISized -import jet.collections.iterable.IIterable - -trait ISet : IIterable, ISized { - fun contains(item : T) : Boolean -} diff --git a/examples/src/collections/ISized.kt b/examples/src/collections/ISized.kt deleted file mode 100644 index 9a69e299b24..00000000000 --- a/examples/src/collections/ISized.kt +++ /dev/null @@ -1,11 +0,0 @@ -package jet.collections.sized - -trait ISized { - val size : Int - - val isEmpty : Boolean - get() = size == 0 - - val isNonEmpty : Boolean - get() = size != 0 -} \ No newline at end of file diff --git a/examples/src/collections/Iterator.kt b/examples/src/collections/Iterator.kt deleted file mode 100644 index 286ed2225fa..00000000000 --- a/examples/src/collections/Iterator.kt +++ /dev/null @@ -1,170 +0,0 @@ -package jet.collections - -import java.util.NoSuchElementException - -trait Iterator { - fun next() : T - val hasNext : Boolean - - fun map(transform: fun(element: T) : R) : Iterator = - object : Iterator { - override fun next() : R = transform(this@map.next()) - - override val hasNext : Boolean - get() = this@map.hasNext - } -} - -trait ISized { - val size : Int -} - -val ISized.isEmpty : Boolean - get() = size == 0 - -val ISized.isNonEmpty : Boolean - get() = size != 0 - -trait ISet : Iterable, ISized { - fun contains(item : T) : Boolean -} - -trait IList : Iterable, ISized { - fun get(index : Int) : T - - fun iterator() : Iterator = - object Iterator { - var index = 0 - - override fun next() : T = get(index++) - - override val hasNext : Boolean - get() = index < size - } - - fun toArray() : Array = Array(size) { index => get(index) } -} - -fun Array.asList() : IList = object IList { - override val size - get() = this@Array.size - - override fun get(index: Int) = this@asList[index] -} - -fun Iterator.foreach(operation: fun(element: T) : Unit) : Unit = while(hasNext) operation(next()) - -fun Iterator.foreach(operation: fun(index: Int, element: T) : Unit) : Unit { - var k = 0 - while(hasNext) - operation(k++, next()) -} - -fun Iterable.foreach(operation: fun(element: T) : Unit) : Unit = iterator() foreach operation - -fun Iterable.foreach(operation: fun(index: Int, element: T) : Unit) : Unit = iterator() foreach operation - -fun Iterable.foldLeft(init: R, operation: fun(accumulated: R, element: T) : R) : R = - iterator () foreach operation - -fun Iterable.foldLeft(init: R, operation: fun(accumulated: R, index: Int, element: T) : R) : R = - iterator () foreach operation - -fun Iterator.foldLeft(init: R, operation: fun(accumulated: R, element: T) : R) : R { - while(hasNext) - init = operation(init, next()) - return init -} - -fun Iterator.foldLeft(init: R, operation: fun(accumulated: R, index: Int, element: T) : R) : R { - var k = 0 - while(hasNext) - init = operation(init, k++, next()) - return init -} - -fun Iterator.map(transform: fun(element: T) : R) : Iterator = - object : Iterator { - override fun next() : R = transform(this@map.next()) - - override val hasNext : Boolean - get() = this@map.hasNext - } - -fun Iterator.map(transform: fun(index: Int, element: T) : R) : Iterator { - return object : Iterator { - var index = 0 - - override fun next() : R = transform(index++, this@map.next()) - - override val hasNext : Boolean - get() = this@map.hasNext - } -} - -fun Iterator.plus(other: Iterator) : Iterator = - object : Iterator { - override fun next() : T = if(this@plus.hasNext) this@plus.next() else other.next() - - override val hasNext : Boolean - get() = this@plus.hasNext || other.hasNext - } - -fun Iterator.filter(condition: fun(element: T) : Boolean) : Iterator { - return object : Iterator { - private var _next : T = null - private var _lookedAhead : Boolean = false - private var _hasNext : Boolean = false - - private fun lookAhead() : Boolean { - if(!_lookedAhead) { - _lookedAhead = true - while(this@filter.hasNext) { - _next = this@filter.next() - if(condition(_next)) { - _hasNext = true - return true - } - } - } - return _hasNext - } - - override fun next() : T { - lookAhead() - _lookedAhead = false - if(_hasNext) { - val res = _next - _next = null - _hasNext = false - return res - } - throw NoSuchElementException() - } - - override val hasNext : Boolean - get() = lookAhead() - } -} -/* - fun toArray(buffer : MutableArray) : Int { // T is still an in-parameter - return fillBuffer(buffer, 0, buffer.size) - } - - fun toArray(buffer : MutableArray, from : Int, length : Int) : Int { // T is still an in-parameter - if (from < 0 || from > buffer.lastIndex || length < 0 || length > buffer.size - from) { - throw IndexOutOfBoundsException(); - } - - if (len == 0) return 0 - - var count = 0; - for (i in from .. from + length - 1) { - if (!hasNext) - return count - buffer[i] = next() - count++ - } - return count - } -*/ diff --git a/examples/src/collections/LinkedList.jetl b/examples/src/collections/LinkedList.jetl deleted file mode 100644 index 9519bcefbb1..00000000000 --- a/examples/src/collections/LinkedList.jetl +++ /dev/null @@ -1,73 +0,0 @@ -class LinkedList : IMutableList { - private class Item(var value : Item) { - var next : Item - var previous : Item - } - - private var head : Item = null - private var tail : Item = null - override var size get private set - - override fun add(index : Int, value : T) { - size++ - checkIndex(index) - val newItem = Item(value) - if (index == 0) { - newItem.next = head - head = newItem - if (tail === null) { - tail = head - } - } else { - var insertAfter = itemAt(index) - newItem.next = insertAfter.next - insertAfter.next = newItem - if (tail === insertAfter) { - tail = newItem - } - } - } - - private fun checkIndex(index : Int) { - if (index !in 0..size-1) { - throw IndexOutOfBoundsException(index) - } - } - - override fun remove(index : Int) : T { - checkIndex(index) - val item = itemAt(index) - if (item === head) { - head = item.next - if (head === null) - tail= null - } else { - item.previous.next = item.next - if (item.next === null) { - item.next.previous = item.previous - } else { - tail = tail.previous - } - } - size-- - return item.value - } - - override fun set(index : Int, value : T) : T { - checkIndex(index) - val item = itemAt(index) - val result = item.value - item.value = value - return result - } - - private fun itemAt(index : Int) { - var result = head - for (i in 1..index) { - result = result.next - } - return result - } - - override fun mutableIterator() : IMutableIterator -} \ No newline at end of file diff --git a/examples/src/collections/List.jetl b/examples/src/collections/List.jetl deleted file mode 100644 index 0a8d852eb41..00000000000 --- a/examples/src/collections/List.jetl +++ /dev/null @@ -1,27 +0,0 @@ -enum class List(theSize : Int) : IList { - Nil : List(0) - - Cons(val value : T, val tail : List) : List(1 + tail.size) - - override val size : Int - get() = theSize - - - override val isEmpty : Boolean - get() = this == Nil - - - override fun iterator() = new IIterator() { - private var current = List.this - - override val hasNext { - get() = current == Nil - } - - override fun next() { - val result = current.value - current = current.tail - return result - } - } -} \ No newline at end of file diff --git a/examples/src/guice-kotlin/guice-kotlin.iml b/examples/src/guice-kotlin/guice-kotlin.iml deleted file mode 100644 index 252e4bdc816..00000000000 --- a/examples/src/guice-kotlin/guice-kotlin.iml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/examples/src/guice-kotlin/guice-kotlin.ipr b/examples/src/guice-kotlin/guice-kotlin.ipr deleted file mode 100644 index d6fde5afd1a..00000000000 --- a/examples/src/guice-kotlin/guice-kotlin.ipr +++ /dev/null @@ -1,192 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - http://www.w3.org/1999/xhtml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/src/guice-kotlin/guice-kotlin.iws b/examples/src/guice-kotlin/guice-kotlin.iws deleted file mode 100644 index 20a33e94f44..00000000000 --- a/examples/src/guice-kotlin/guice-kotlin.iws +++ /dev/null @@ -1,798 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - localhost - 5050 - - - - - - - - - 1328297603532 - 1328297603532 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Detection - - - - - - - - - - - - - - - 1.6 - - - - - - - - guice-kotlin - - - - - - - - 1.6 - - - - - - - - com.google.inject:guice:3.0 - - - - - - - - - diff --git a/examples/src/guice-kotlin/lib/aopalliance-1.0-sources.jar b/examples/src/guice-kotlin/lib/aopalliance-1.0-sources.jar deleted file mode 100644 index 07c51d09746..00000000000 Binary files a/examples/src/guice-kotlin/lib/aopalliance-1.0-sources.jar and /dev/null differ diff --git a/examples/src/guice-kotlin/lib/aopalliance-1.0.jar b/examples/src/guice-kotlin/lib/aopalliance-1.0.jar deleted file mode 100644 index 578b1a0c359..00000000000 Binary files a/examples/src/guice-kotlin/lib/aopalliance-1.0.jar and /dev/null differ diff --git a/examples/src/guice-kotlin/lib/guice-3.0-sources.jar b/examples/src/guice-kotlin/lib/guice-3.0-sources.jar deleted file mode 100644 index e24db11b88b..00000000000 Binary files a/examples/src/guice-kotlin/lib/guice-3.0-sources.jar and /dev/null differ diff --git a/examples/src/guice-kotlin/lib/guice-3.0.jar b/examples/src/guice-kotlin/lib/guice-3.0.jar deleted file mode 100644 index f313e2b089d..00000000000 Binary files a/examples/src/guice-kotlin/lib/guice-3.0.jar and /dev/null differ diff --git a/examples/src/guice-kotlin/lib/javax.inject-1-sources.jar b/examples/src/guice-kotlin/lib/javax.inject-1-sources.jar deleted file mode 100644 index 0c980535ddf..00000000000 Binary files a/examples/src/guice-kotlin/lib/javax.inject-1-sources.jar and /dev/null differ diff --git a/examples/src/guice-kotlin/lib/javax.inject-1.jar b/examples/src/guice-kotlin/lib/javax.inject-1.jar deleted file mode 100644 index b2a9d0bf7bd..00000000000 Binary files a/examples/src/guice-kotlin/lib/javax.inject-1.jar and /dev/null differ diff --git a/examples/src/guice-kotlin/src/GuiceDsl.kt b/examples/src/guice-kotlin/src/GuiceDsl.kt deleted file mode 100644 index 1811296f77c..00000000000 --- a/examples/src/guice-kotlin/src/GuiceDsl.kt +++ /dev/null @@ -1,50 +0,0 @@ -package org.jetbrains.kotlin.examples.guice - -import com.google.inject.* -import com.google.inject.binder.* -import java.util.logging.Logger -import java.util.ArrayList - -class GuiceInjectorBuilder() { - private val collected = ArrayList () - - fun module (config: Binder.()->Any?) : Module = object: Module { - override fun configure(binder: Binder?) { - binder!!.config() - } - } - - fun Module.plus() { - collected.add(this) - } - - class object { - fun injector(config: GuiceInjectorBuilder.() -> Any?) : Injector { - val collector = GuiceInjectorBuilder() - collector.config() - return Guice.createInjector(collector.collected)!! - } - } -} - -inline fun Binder.bind() = bind(javaClass())!! - -inline fun ScopedBindingBuilder.asSingleton() = `in`(javaClass()) - -inline fun AnnotatedBindingBuilder.to() = to(javaClass())!! - -inline fun AnnotatedBindingBuilder.toSingleton() = to(javaClass())!!.asSingleton() - -inline fun Injector.getInstance() = getInstance(javaClass())!! - -inline fun Injector.getProvider() = getProvider(javaClass())!! - -inline fun > LinkedBindingBuilder.toProvider() = toProvider(javaClass()) - -fun AnnotatedBindingBuilder.toProvider(provider: Injector.()->T) = toProvider(object: Provider { - [Inject] val injector : Injector? = null - - override fun get(): T = injector!!.provider() -})!! - -fun AnnotatedBindingBuilder.toSingletonProvider(provider: Injector.()->T) = toProvider(provider).asSingleton() diff --git a/examples/src/guice-kotlin/src/GuiceExample.kt b/examples/src/guice-kotlin/src/GuiceExample.kt deleted file mode 100644 index 5c9f4de57bf..00000000000 --- a/examples/src/guice-kotlin/src/GuiceExample.kt +++ /dev/null @@ -1,57 +0,0 @@ -package org.jetbrains.kotlin.examples.guice - -import java.util.logging.Logger -import java.util.ArrayList - -import com.google.inject.* -import com.google.inject.binder.* - -abstract class LoggingService() { - abstract fun info(message: String) -} - -class StdoutLoggingService() : LoggingService(){ - override fun info(message: String) = println("INFO: $message") -} - -class JdkLoggingService () : LoggingService() { - protected [Inject] var jdkLogger: Logger? = null - - override fun info(message: String) = jdkLogger!!.info(message) -} - -abstract class AppService(protected val mode: String) { - protected abstract val logger: LoggingService - - fun run() { - logger.info("Application started in '$mode' mode with ${logger.javaClass.getName()} logger") - logger.info("Hello, World!") - } -} - -class RealAppService [Inject] (override val logger: LoggingService) : AppService("real") - -class TestAppService (private val loggerProvider : Provider) : AppService("test") { - protected override val logger: LoggingService - get() = loggerProvider.get() -} - -fun main(args: Array) { - fun configureInjections(test: Boolean) = GuiceInjectorBuilder.injector { - +module { - if(test) { - bind().toInstance(StdoutLoggingService()) - bind().toSingletonProvider{ // Injector as receiver for ext.function - TestAppService(getProvider()) - } - } - else { - bind().to().asSingleton() - bind().toSingleton() - } - } - } - - configureInjections(test = false).getInstance().run() - configureInjections(test = true ).getInstance().run() -} \ No newline at end of file diff --git a/examples/src/io/IOSamples.jetl b/examples/src/io/IOSamples.jetl deleted file mode 100644 index 621b6c0033b..00000000000 --- a/examples/src/io/IOSamples.jetl +++ /dev/null @@ -1,62 +0,0 @@ -open class IAdder { - fun add(item : T) : Boolean -} - -open class ICloseable { - fun close() -} - -abstract class JavaCloseableWrapper(closeable : java.io.Closeable) : ICloseable(closeable) - -fun streamCopy(from : IIterable, to : IAdder) { - for (item in from) t.add(item) -} - -class FileInput : IIterator, JavaCloseableWrapper { - private val stream : InputStream - private var next : Int - private var nextUsed = false - - this(file : File) : JavaCloseableWrapper(stream) { // implicitly throws IOException - stream = FileInputStream(file) // throws IOException - } - - override fun next() { - if (!nextUsed) { - nextUsed = true - return next as Byte - } - return - } - - override val hasNext - get() { // implicitly throws IOException - if (nextUsed && next != -1) { - nextUsed = false - next = stream.read() // throws IOException - } - return next != -1 - } - -} - -class FileOutput : IAdder, JavaCloseableWrapper { - private val stream : OutputStream - - this(file : File) : JavaCloseableWrapper(stream) { - stream = FileOutputStream(file) - } - - override fun add(item : Byte) { - stream.write(item) - } -} - -fun example() { // this does not rethrow, no appropriate parameters given - - val f1 : File //= ... - val f2 : File //= ... - - streamCopy(FileInput(f1), f2) // throws IOException, you must catch or rethrow explicitly - -} \ No newline at end of file diff --git a/examples/src/io/IOSamplesChEx.jetl b/examples/src/io/IOSamplesChEx.jetl deleted file mode 100644 index 087f8ed7db7..00000000000 --- a/examples/src/io/IOSamplesChEx.jetl +++ /dev/null @@ -1,71 +0,0 @@ -interface class IIterable throws { - fun next() : T // implicitly throws - val hasNext : Boolean // implicitly throws , but actually may NOT!!! -} - -interface class IAdder throws { - fun add(item : T) : Boolean // implicitly throws -} - -interface class ICloseable throws { - fun close() -} - -abstract class JavaCloseableWrapper(closeable : java.io.Closeable) throws : ICloseable { // Maybe we can delegate here - override fun close() { - closeable.close() - } -} - -fun streamCopy(from : IIterable, to : IAdder) { // implicitly rethrows - for (item in from) t.add(item) // both implicitly throw -} - -class FileInput throws : IIterable, JavaCloseableWrapper { - private val stream : InputStream - private var next : Int - private var nextUsed = false - - this(file : File) : JavaCloseableWrapper(stream) { // implicitly throws IOException - stream = FileInputStream(file) // throws IOException - } - - override fun next() { - if (!nextUsed) { - nextUsed = true - return next.as - } - return - } - - override val hasNext { - get() { // implicitly throws IOException - if (nextUsed && next != -1) { - nextUsed = false - next = stream.read() // throws IOException - } - return next != -1 - } - } -} - -class FileOutput throws IOException : IAdder, JavaCloseableWrapper { - private val stream : OutputStream - - this(file : File) : JavaCloseableWrapper(stream) { - stream = FileOutputStream(file) - } - - override fun add(item : Byte) { - stream.write(item) - } -} - -fun example() { // this does not rethrow, no appropriate parameters given - - val f1 : File = ... - val f2 : File = ... - - streamCopy(FileInput(f1), f2) // throws IOException, you must catch or rethrow explicitly - -} \ No newline at end of file diff --git a/examples/src/luhny/solution.kt b/examples/src/luhny/solution.kt deleted file mode 100644 index ceb0061f3c8..00000000000 --- a/examples/src/luhny/solution.kt +++ /dev/null @@ -1,95 +0,0 @@ -package luhnybin - -import kotlin.io.* -import java.io.* -import java.util.ArrayDeque - -fun isCardChar(it : Char) : Boolean = it == ' ' || it == '-' || it.isDigit() - -fun applyMask(a : String) : String { - val luhny = Luhny() - for (c in a) { - luhny.process(c) - } - luhny.processEnd() - - return luhny.output.toString()!! -} - -class Luhny() { - private val buffer = ArrayDeque() - private val digits = ArrayDeque(16) - - private var toBeMasked = 0 - val output = StringBuilder() - - fun process(it : Char) { - buffer.addLast(it) - - when { - it.isDigit() -> digits.addLast(it.toDigit()) - it == ' ' || it == '-' -> { - } - else -> printAll() - } - - if (digits.size() > 16) { - printUntil { it.isDigit() } - digits.removeFirst() - } - - check() - } - - fun processEnd() { - while (digits.size() >= 14) { - check() - printUntil { it.isDigit() } - digits.removeFirst() - } - - printAll() - } - - private fun check() { - val size = digits.size() - if (size < 14) return - - var sum = 0 - var i = 0 - for (d in digits) { - sum += if (i % 2 == size % 2) double(d) else d - i++ - } - - if (sum % 10 == 0) - toBeMasked = size - } - - private fun double(d : Int) = d * 2 / 10 + d * 2 % 10 - - fun printAll() { - printUntil { false } - digits.clear() - } - - private fun printUntil(f : (Char) -> Boolean) { - while (!buffer.isEmpty()) { - val c = buffer.removeFirst() - printChar(c) - if (f(c)) return - } - } - - private fun printChar(c : Char) { - if (c.isDigit() && toBeMasked > 0) { - output.append('X') - toBeMasked-- - } else { - output.append(c) - } - } -} - -fun Char.isDigit() = Character.isDigit(this) -fun Char.toDigit() = this.toInt() - '0'.toInt() diff --git a/examples/src/luhny/test.kt b/examples/src/luhny/test.kt deleted file mode 100644 index b4ca55f9721..00000000000 --- a/examples/src/luhny/test.kt +++ /dev/null @@ -1,260 +0,0 @@ -package luhnybin - -import java.util.* - -fun main(args : Array) { - run() - System.out?.println("Success") -} - -// HELPER FUNCTIONS - -val MASK : Char = 'X' - -val MIN_LENGTH : Int = 14 -val MAX_LENGTH : Int = 16 - -val random = Random(0xDEADBEEF) - -class test(val testName : String) { - var input : String = "" - - fun send(input : String) : test { - this.input = input - return this - } - - fun expect(expected : String) { - val actual = applyMask(input) - - assertEquals( - actual, expected, - "${testName} failed on \"${input}\"\n" + - "applyMask(data) = \"${actual}\", but must be \"$expected\"") - } - - fun sendAndExpect(input : String) = send(input).expect(input) - - fun assertEquals(actual : T?, expected : T?, message : Any? = null) { - if (actual != expected) { - if (message == null) - throw AssertionError() - else - throw AssertionError(message) - } - } -} - -fun run() { - test("line feed preservation").sendAndExpect("LF only ->\n<- LF only") - - for (i in MIN_LENGTH..MAX_LENGTH) - test("valid " + i + "-digit #") - .send(randomNumber(i)) - .expect(mask(i)) - - for (i in MIN_LENGTH..MAX_LENGTH) - test("non-matching " + i + "-digit #").sendAndExpect(nonMatchingSequence(i)) - - test("not enough digits").sendAndExpect(nonMatchingSequence(MIN_LENGTH - 1)) - - var tooMany = nonMatchingSequence(MAX_LENGTH) - tooMany += computeLast(tooMany) - test("too many digits").sendAndExpect(tooMany) - - test("14-digit # prefixed with 0s") - .send("00" + randomNumber(14)) - .expect(mask(16)) - - test("2 non-matching digits followed by a 14-digit #") - .send("1256613959932537") - .expect("12XXXXXXXXXXXXXX") - - test("14-digit # embedded in a 16-digit #") - .send(nestedNumber()) - .expect(mask(16)) - - test("16-digit # flanked by non-matching digits") - .send("9875610591081018250321") - .expect("987XXXXXXXXXXXXXXXX321") - - testFormatted(' ') - testFormatted('-') - - test("exception message containing a card #") - .send("java.lang.FakeException: " + formattedNumber(' ') + " is a card #.") - .expect("java.lang.FakeException: " + formattedMask(' ') + " is a card #.") - - test("non-matching message").sendAndExpect("4111 1111 1111 111 doesn't have enough digits.") - - test("non-matching message").sendAndExpect("56613959932535089 has too many digits.") - - test("sequence of zeros") - .send(repeatingSequence('0', 1000)) - .expect(mask(1000)) - - test("long sequence of non-digits").sendAndExpect(nonDigits()) - - testOverlappingMatches() - - test("long sequence of digits with no matches").sendAndExpect(nonMatchingSequence(1000)) -} - -fun formatNumber(number : String, delimiter : Char) : String { - if (number.length != 16) - throw IllegalArgumentException("Expected length of 16.") - - val formatted = StringBuilder() - for (i in 0..3) { - formatted.append(number.substring(i * 4, (i * 4) + 4)) - if (i < 3) - formatted.append(delimiter) - } - - return formatted.toString() ?: "" -} - -fun formattedNumber(delimiter : Char) : String = formatNumber(randomNumber(16), delimiter) - -fun checkDigit(c : Char) : Char { - if (c < '0' || c > '9') - throw IllegalArgumentException("Not a digit: " + c) - - return c -} - -fun intValue(c : Char) : Int = checkDigit(c) - '0' - -/** Computes the last digit necessary to pass the Luhn check. */ -fun computeLast(allButLast : String) : Char { - var sum = 0 - - var i = allButLast.length - 1 - while (i >= 0) { - val value = intValue(allButLast[i]) shl 1 - sum += if (value > 9) value - 9 else value - - i -= 2 - } - - var j = allButLast.length - 2 - while (j >= 0) { - sum += intValue(allButLast[j]) - j -= 2 - } - - var remainder = sum % 10 - return if (remainder == 0) '0' else ('0' + (10 - remainder)).toChar() -} - -fun computeLast(allButLast : CharSequence) : Char = computeLast(allButLast.toString()!!) - -fun setRandomDigits(builder : StringBuilder, start : Int, end : Int) { - for (i in start..end-1) - builder.setCharAt(i, randomDigit()) -} - -/** Generates a random digit. */ -fun randomDigit() : Char = ('0' + random.nextInt(10)).toChar() - -fun nonDigits() : String { - val nonDigits = StringBuilder() - for (i in 0..999) - nonDigits.append((random.nextInt(68) + ':').toChar()) - return nonDigits.toString()!! -} - -fun testFormatted(delimiter : Char) { - test("16-digit # delimited with '" + delimiter + "'") - .send(formattedNumber(delimiter)) - .expect(formattedMask(delimiter)) -} - -fun formattedMask(delimiter : Char) : String { - val mask = StringBuilder() - - for (i in 0..3) { - mask.append(repeatingSequence(MASK, 4)) - if (i < 3) - mask.append(delimiter) - } - - return mask.toString()!! -} - -/** Computes a random, valid card # with the specified number of digits. */ -fun randomNumber(digits : Int) : String { - val number = StringBuilder(digits) - number.setLength(digits) - setRandomDigits(number, 0, digits - 1) - number.setCharAt(digits - 1, computeLast(number.subSequence(0, digits - 1)!!)) - return number.toString() ?: "" -} - -/** Creates a 16-digit card # with a 14-digit number embedded inside. */ -fun nestedNumber() : String { - val number = StringBuilder(16) - number.setLength(16); - setRandomDigits(number, 0, 14); - number.setCharAt(14, computeLast(number.subSequence(1, 14)!!)) - number.setCharAt(15, computeLast(number.subSequence(0, 15)!!)) - return number.toString()!! -} - -/** Creates a sequence of mask characters with the given length. */ -fun mask(length : Int) : String { - return repeatingSequence(MASK, length); -} - -/** Creates a sequence of c with the given length. */ -fun repeatingSequence(c : Char, length : Int) : String { - val sb = StringBuilder() - for (i in 1..length) - sb.append(c) - return sb.toString()!! -} - -class DigitSet() { - val bitSet = BitSet() - - fun add(digit : Char) = bitSet.set(intValue(digit)) - fun contains(digit : Char) : Boolean = bitSet.get(intValue(digit)) - fun clear() = bitSet.clear() -} - -fun testOverlappingMatches() { - val output = StringBuilder(randomNumber(MAX_LENGTH)) - for (i in 0..1000 - MAX_LENGTH - 1) - output.append(computeLast(output.subSequence(i + 1, i + MAX_LENGTH)!!)) - - test("long sequence of overlapping, valid #s") - .send(output.toString()!!) - .expect(mask(output.length())); -} - -/** Generates a sequence of digits with the specified length and no card #s. */ -fun nonMatchingSequence(length : Int) : String { - val builder = StringBuilder() - - for (lastIndex in 0..length-1) { - val excluded = DigitSet() - excluded.clear(); - - // Compute digits that would result in valid card #s. - for (subLength in MIN_LENGTH..MAX_LENGTH) { - val start = lastIndex - (subLength - 1); - if (start < 0) - break; - excluded.add(computeLast(builder.subSequence(start, lastIndex)!!)); - } - - // Find a digit that doesn't result in a valid card #. - var digit : Char = '0' - do { - digit = randomDigit() - } while (excluded.contains(digit)) - builder.append(digit); - } - - return builder.toString()!! -} diff --git a/examples/src/map/IMap.jetl b/examples/src/map/IMap.jetl deleted file mode 100644 index da51189c006..00000000000 --- a/examples/src/map/IMap.jetl +++ /dev/null @@ -1,4 +0,0 @@ -open class IMap { - - -} \ No newline at end of file diff --git a/examples/src/nettyserver/lib/netty-3.2.5.Final-sources.jar b/examples/src/nettyserver/lib/netty-3.2.5.Final-sources.jar deleted file mode 100644 index cb6cb9bf537..00000000000 Binary files a/examples/src/nettyserver/lib/netty-3.2.5.Final-sources.jar and /dev/null differ diff --git a/examples/src/nettyserver/lib/netty-3.2.5.Final.jar b/examples/src/nettyserver/lib/netty-3.2.5.Final.jar deleted file mode 100644 index f3b79fcbaa7..00000000000 Binary files a/examples/src/nettyserver/lib/netty-3.2.5.Final.jar and /dev/null differ diff --git a/examples/src/nettyserver/nettyserver.iml b/examples/src/nettyserver/nettyserver.iml deleted file mode 100644 index 6d0961b99e4..00000000000 --- a/examples/src/nettyserver/nettyserver.iml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/src/nettyserver/nettyserver.ipr b/examples/src/nettyserver/nettyserver.ipr deleted file mode 100644 index d7cc3bde365..00000000000 --- a/examples/src/nettyserver/nettyserver.ipr +++ /dev/null @@ -1,178 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - http://www.w3.org/1999/xhtml - - - - - - - - - - - - - - - - - - diff --git a/examples/src/nettyserver/nettyserver.iws b/examples/src/nettyserver/nettyserver.iws deleted file mode 100644 index 2873cd9a185..00000000000 --- a/examples/src/nettyserver/nettyserver.iws +++ /dev/null @@ -1,750 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - localhost - 5050 - - - - - - - 1328521187492 - 1328521187492 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - No facets are configured - - - - - - - - - - - - - - - 1.6 - - - - - - - - nettyserver - - - - - - - - 1.6 - - - - - - - - KotlinRuntime - - - - - - - - - diff --git a/examples/src/nettyserver/src/HttpHandler.kt b/examples/src/nettyserver/src/HttpHandler.kt deleted file mode 100644 index b9e10594fb2..00000000000 --- a/examples/src/nettyserver/src/HttpHandler.kt +++ /dev/null @@ -1,41 +0,0 @@ -package org.jetbrains.kotlin.examples.netty - -import org.jboss.netty.channel.SimpleChannelUpstreamHandler -import java.util.LinkedList -import org.jboss.netty.channel.ChannelHandlerContext -import org.jboss.netty.channel.MessageEvent -import org.jboss.netty.handler.codec.http.HttpResponseStatus.* -import org.jboss.netty.handler.codec.http.HttpMethod -import org.jboss.netty.handler.codec.http.HttpResponseStatus - -class HttpHandler(config: HttpHandler.() -> Unit) : SimpleChannelUpstreamHandler() { - private var processors = LinkedList(); - - var onNotFound : (RequestResponse)->Any? = { request -> request.setError(NOT_FOUND) }; - - { - this.bind(config)() - } - - fun messageReceived(ctx : ChannelHandlerContext, e : MessageEvent) { - val request = RequestResponse(e) - for(processor in processors) { - if(processor.tryToProcess(request)) { - request.write() - return - } - } - - (onNotFound)(request) - } - - fun static(prefix: String = "/", directory: String) { - processors.add(StaticFileProcessor(prefix, directory)) - } - - fun rest(prefix: String, config: RestBuilder.()->Any?) { - val builder = RestBuilder() - (builder.bind(config))() - processors.add(RestProcessor(prefix, builder)) - } -} diff --git a/examples/src/nettyserver/src/Main.kt b/examples/src/nettyserver/src/Main.kt deleted file mode 100644 index 3d104f90524..00000000000 --- a/examples/src/nettyserver/src/Main.kt +++ /dev/null @@ -1,40 +0,0 @@ -package org.jetbrains.kotlin.examples.netty - -import org.jboss.netty.handler.codec.http.HttpResponseStatus -import org.jboss.netty.handler.codec.http.DefaultHttpResponse -import org.jboss.netty.handler.codec.http.HttpVersion -import org.jboss.netty.buffer.ChannelBuffers -import java.nio.charset.Charset - -fun main(args : Array) { - if(args.size == 0) { - println("Please provide command line argument ") - System.exit(1) - } - else { - println("Please open http://localhost:8080/index.html page in your browser") - } - - httpServer(8080) { - static(directory = args[0]) - - rest("/sayhello") { - GET { - response.content = "Hello, World!" - } - POST { - response.content = "You said: ${request.getContent()!!.toString(Charset.defaultCharset())}" - } - } - - onNotFound = { requestResponse -> - when(requestResponse.path) { - "/prototype.js" -> { - requestResponse.redirect("https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js") - } - else -> - requestResponse.setError(HttpResponseStatus.FORBIDDEN) - } - } - } -} diff --git a/examples/src/nettyserver/src/Netty.kt b/examples/src/nettyserver/src/Netty.kt deleted file mode 100644 index eacc2ca9d7e..00000000000 --- a/examples/src/nettyserver/src/Netty.kt +++ /dev/null @@ -1,66 +0,0 @@ -package org.jetbrains.kotlin.examples.netty - -import java.util.concurrent.Executors -import java.net.* -import java.io.* - -import org.jboss.netty.bootstrap.ServerBootstrap -import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory -import org.jboss.netty.channel.* -import org.jboss.netty.handler.codec.http.* -import org.jboss.netty.handler.stream.ChunkedWriteHandler -import org.jboss.netty.handler.codec.frame.TooLongFrameException -import org.jboss.netty.buffer.ChannelBuffers -import org.jboss.netty.util.CharsetUtil -import org.jboss.netty.handler.codec.http.HttpResponseStatus.* - -import org.jboss.netty.bootstrap.ServerBootstrap -import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory -import org.jboss.netty.channel.* -import org.jboss.netty.handler.codec.http.* -import org.jboss.netty.handler.stream.ChunkedWriteHandler -import org.jboss.netty.handler.codec.frame.TooLongFrameException -import org.jboss.netty.buffer.ChannelBuffers -import org.jboss.netty.util.CharsetUtil -import org.jboss.netty.handler.codec.http.HttpResponseStatus.* -import java.util.LinkedList - -// This is workaround for compiler bug -fun T.bind(op: T.()->Any?) = { op() } - -fun HttpResponse.set(header: String, value: Any?) : Unit { - setHeader(header, value) -} - -var HttpResponse.content : Any? - get() = throw UnsupportedOperationException() - set(c: Any?) { - val buffer = ChannelBuffers.copiedBuffer(c.toString(), CharsetUtil.UTF_8)!! - setContent(buffer) - setHeader("Content-Length", buffer.readableBytes()) - } - -fun ServerBootstrap.configPipeline(config: ChannelPipeline.() -> Unit) = setPipelineFactory(object: ChannelPipelineFactory { - override fun getPipeline() : ChannelPipeline { - val pipeline = DefaultChannelPipeline() - pipeline.bind(config) () - return pipeline - } -}) - -fun httpServer(port: Int, handler: HttpHandler.() -> Unit) { - val bootstrap = ServerBootstrap( - NioServerSocketChannelFactory( - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool() - ) - ) - bootstrap.configPipeline { - addLast("decoder", HttpRequestDecoder()) - addLast("aggregator", HttpChunkAggregator(65536)) - addLast("encoder", HttpResponseEncoder()) - addLast("chunkedWriter", ChunkedWriteHandler()) - addLast("handler", HttpHandler(handler)) - } - bootstrap.bind(InetSocketAddress(port)) -} diff --git a/examples/src/nettyserver/src/Request.kt b/examples/src/nettyserver/src/Request.kt deleted file mode 100644 index e1a80f8843b..00000000000 --- a/examples/src/nettyserver/src/Request.kt +++ /dev/null @@ -1,80 +0,0 @@ -package org.jetbrains.kotlin.examples.netty - -import org.jboss.netty.channel.SimpleChannelUpstreamHandler -import java.util.LinkedList -import org.jboss.netty.channel.ChannelHandlerContext -import org.jboss.netty.channel.MessageEvent -import org.jboss.netty.handler.codec.http.HttpResponseStatus.* -import org.jboss.netty.handler.codec.http.HttpRequest -import org.jboss.netty.channel.Channel -import org.jboss.netty.handler.codec.http.HttpResponseStatus -import org.jboss.netty.handler.codec.http.DefaultHttpResponse -import org.jboss.netty.channel.ChannelFutureListener -import org.jboss.netty.handler.codec.http.HttpVersion -import java.io.File -import java.io.UnsupportedEncodingException -import java.net.URLDecoder -import org.jboss.netty.handler.codec.http.HttpHeaders.* -import org.jboss.netty.handler.codec.http.HttpMessage -import org.jboss.netty.channel.ChannelFuture - -class RequestResponse(e: MessageEvent) { - val request = e.getMessage() as HttpRequest - val response = DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN) - val channel = e.getChannel()!! - val path = request.getUri()!!.sanitizeUri() - - fun setError(status: HttpResponseStatus?) { - response.setStatus(status) - response["Content-Type"] = "text/plain; charset=UTF-8" - response.content = "Failure: " + status.toString() + "\r\n" - } - - fun redirect(path: String) { - response.setStatus(HttpResponseStatus.MOVED_PERMANENTLY) - response["Location"] = path - response["Content-Length"] = 0 - channel.write(response) - } - - fun ok() : RequestResponse { - response.setStatus(HttpResponseStatus.OK) - return this - } - - fun write() = - if(response.getStatus()!!.getCode() >= 400) { - channel.write(response)!!.addListener(ChannelFutureListener.CLOSE) - } - else { - channel.write(response) - } -} - - -fun String.sanitizeUri() : String { - val path = decodeURI("UTF-8") ?: decodeURI("ISO-8859-1") ?: throw Error() - - val localizedPath = path.replace('/', File.separatorChar) - - return if (localizedPath.contains(File.separator + ".") || - localizedPath.contains("." + File.separator) || - localizedPath.startsWith(".") || localizedPath.endsWith(".")) - throw Error() - else - localizedPath -} - -fun String.decodeURI(encoding : String) : String? { - try { - return URLDecoder.decode(this, encoding) - } - catch (e : UnsupportedEncodingException) { - return null - } -} - -trait Processor { - fun tryToProcess(request: RequestResponse) : Boolean -} - diff --git a/examples/src/nettyserver/src/RestProcessor.kt b/examples/src/nettyserver/src/RestProcessor.kt deleted file mode 100644 index d9a401a9873..00000000000 --- a/examples/src/nettyserver/src/RestProcessor.kt +++ /dev/null @@ -1,37 +0,0 @@ -package org.jetbrains.kotlin.examples.netty - -import org.jboss.netty.handler.codec.http.HttpMethod -import org.jboss.netty.handler.codec.http.HttpResponseStatus - -class RestBuilder() { - var onGet : (RequestResponse.()->Any?)? = null - var onPost : (RequestResponse.()->Any?)? = null - - fun GET(handler: RequestResponse.()->Unit) { - onGet = handler - } - - fun POST(handler: RequestResponse.()->Unit) { - onPost = handler - } -} - -class RestProcessor(val prefix: String, val builder: RestBuilder) : Processor { - override fun tryToProcess(request: RequestResponse): Boolean { - if(request.path.startsWith(prefix)) { - if(request.request.getMethod() == HttpMethod.GET && builder.onGet != null) { - request.ok() - request.(builder.onGet!!)() - } - else if(request.request.getMethod() == HttpMethod.POST && builder.onPost != null) { - request.ok() - request.(builder.onPost!!)() - } - else { - request.setError(HttpResponseStatus.METHOD_NOT_ALLOWED) - } - return true; - } - return false - } -} \ No newline at end of file diff --git a/examples/src/nettyserver/src/StaticFileProcessor.kt b/examples/src/nettyserver/src/StaticFileProcessor.kt deleted file mode 100644 index 6abd56d0812..00000000000 --- a/examples/src/nettyserver/src/StaticFileProcessor.kt +++ /dev/null @@ -1,46 +0,0 @@ -package org.jetbrains.kotlin.examples.netty - -import org.jboss.netty.handler.codec.http.HttpMethod -import java.io.File -import java.io.RandomAccessFile -import org.jboss.netty.handler.codec.http.DefaultHttpResponse -import org.jboss.netty.channel.DefaultFileRegion -import org.jboss.netty.handler.codec.http.HttpVersion -import org.jboss.netty.handler.codec.http.HttpResponseStatus.* - -class StaticFileProcessor(val prefix: String, val root: String) : Processor { - override fun tryToProcess(request: RequestResponse) : Boolean { - if(request.path.startsWith(prefix)) { - return request.processStaticFile() - } - return false; - } - - fun RequestResponse.processStaticFile() : Boolean { - val file = File(root + File.separator + path.substring(prefix.length)) - if(!file.exists()) - return false; - - if (request.getMethod() != HttpMethod.GET) { - setError(METHOD_NOT_ALLOWED); - return true; - } - - if (file.isHidden() || !file.isFile()) { - setError(FORBIDDEN) - return true - } - - var raf = RandomAccessFile(file, "r") - - val fileLength = raf.length() - - val response = DefaultHttpResponse(HttpVersion.HTTP_1_1, OK) - response["Content-Length"] = fileLength - - channel.write(response) - channel.write(DefaultFileRegion(raf.getChannel(), 0, fileLength)) - return true; - } -} - diff --git a/examples/src/nettyserver/static/index.html b/examples/src/nettyserver/static/index.html deleted file mode 100644 index 6ff68ee8c9f..00000000000 --- a/examples/src/nettyserver/static/index.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - -
Waiting...
- -
- - \ No newline at end of file diff --git a/examples/src/priorityqueues/BinaryHeap.jetl b/examples/src/priorityqueues/BinaryHeap.jetl deleted file mode 100644 index 98990fb32f6..00000000000 --- a/examples/src/priorityqueues/BinaryHeap.jetl +++ /dev/null @@ -1,105 +0,0 @@ -class BinaryHeap : IPriorityQueue { - private val data : IMutableList - private val compare : Comparison - - this(data : IIterable, compare : Comparison = naturalOrder) { - this.compare = compare - this.data = ArrayList(data) -// siftDown(* this.data.size / 2 .. 0) - - for (val i in data.size / 2 .. 0) { - siftDown(i) - } - - } - - this(compare : Comparison) { - this.compare = compare - this.data = ArrayList() - } - - this() { - this.data = ArrayList() - Assert(T is IComparable) - this.comparator = naturalOrder - } - - override fun extract() : T { - if (this.isEmpty) - throw UnderflowException() - data.swap(0, data.lastIndex) - data.remove(data.lastIndex) - siftDown(0) - } - - override fun add(item : T) { - data.add(item) - siftUp(data.lastItem) - } - - private fun siftDown(index : Int) { - var current = index - while (current.left.exists) { - var min = current - if (current.left.value < min.value) { - min = current.left - } - if (current.right.exists && current.right.value < min.value) { - min = current.right - } - if (min == current) break - data.swap(min, current) - current = min - } - } - - private fun siftUp(index : Int) { - if (!current.exists) return - var current = index - while (current.parent.exists) { - if (current.value < current.parent.value) { - data.swap(current, current.parent) - current = current.parent - } - } - } - - private extension HeapIndex for Int { - val parent : Int - get() = (this - 1) / 2 - - - val left : Int - get() = this * 2 + 1 - - - val right : Int - get() = this * 2 + 2 - - - val value : T = foo.bar() - get() = data[this] - set(it) { - $value = it - } - - - val exists : Boolean - get() = (this < data.size) && (this >= 0) - - } - - private extension for T { - [operator] fun compareTo(other : T) : Int = compare(this, other) - } - -} - -fun IMutableList.swap(a : Int, b : Int) { - val t = this[a] - this[a] = this[b] - this[b] = t -} - -val IList.lastIndex : Int - get() = this.size - 1 diff --git a/examples/src/priorityqueues/IPriorityQueue.jetl b/examples/src/priorityqueues/IPriorityQueue.jetl deleted file mode 100644 index ee694f5c9d4..00000000000 --- a/examples/src/priorityqueues/IPriorityQueue.jetl +++ /dev/null @@ -1,5 +0,0 @@ -open class IPriorityQueue { - fun extract() : T - fun add(item : T) - val isEmpty : Boolean -} diff --git a/examples/src/priorityqueues/PriorityQueueAsPushPop.jetl b/examples/src/priorityqueues/PriorityQueueAsPushPop.jetl deleted file mode 100644 index 2d20c5666e7..00000000000 --- a/examples/src/priorityqueues/PriorityQueueAsPushPop.jetl +++ /dev/null @@ -1,7 +0,0 @@ -class PriorityQueueAsPushPop wraps(wrapped : IPriorityQueue) : IPushPop { - override fun pop() = wrapped.extract() - override fun push(item : T) = wrapped.add(item) - override val isEmpty - get() = wrapped.isEmpty - -} \ No newline at end of file diff --git a/examples/src/swing/SwingBuilder.kt b/examples/src/swing/SwingBuilder.kt deleted file mode 100644 index afac474a18c..00000000000 --- a/examples/src/swing/SwingBuilder.kt +++ /dev/null @@ -1,80 +0,0 @@ -package kool.swing - -import javax.swing.* -import java.awt.* -import java.awt.event.* - -var Container.south : JComponent - get() = throw UnsupportedOperationException() - set(comp) {add(comp, BorderLayout.SOUTH)} - -var Container.north : JComponent - get() = throw UnsupportedOperationException() - set(comp) {add(comp, BorderLayout.NORTH)} - -var Container.east : JComponent - get() = throw UnsupportedOperationException() - set(comp) {add(comp, BorderLayout.EAST)} - -var Container.west : JComponent - get() = throw UnsupportedOperationException() - set(comp) {add(comp, BorderLayout.WEST)} - -var Container.center : JComponent - get() = throw UnsupportedOperationException() - set(comp) {add(comp, BorderLayout.CENTER)} - -class KFrame(title : String, init : KFrame.() -> Unit) : JFrame(title) { - { - this.init() - } - - fun T.toSouth() : T { - this@KFrame.add(this, BorderLayout.SOUTH) - return this - } -} - - -fun JPanel(init : JPanel.() -> Unit) : JPanel { - val p = JPanel() - p.init() - return p -} - -//fun KFrame(title : String, init : JFrame.() -> Unit) : JFrame { -// val result = JFrame(title) -// result.init() -// return result -//} - -fun JButton(text : String, action : (ActionEvent) -> Unit) : JButton { - val result = JButton(text) - result.addActionListener(object : ActionListener { - override fun actionPerformed(e: ActionEvent?) { - action(e!!) - } - }) - return result -} - -var JFrame.title : String - get() = getTitle()!! - set(t) {setTitle(t)} - -var JFrame.size : Pair - get() = Pair(getSize()!!.getWidth().toInt(), getSize()!!.getHeight().toInt()) - set(dim) {setSize(Dimension(dim.first, dim.second))} - -var JFrame.height : Int - get() = getSize()!!.getHeight().toInt() - set(h) {setSize(width, h)} - -var JFrame.width : Int - get() = getSize()!!.getWidth().toInt() - set(w) {setSize(height, w)} - -var JFrame.defaultCloseOperation : Int - get() = getDefaultCloseOperation() - set(def) {setDefaultCloseOperation(def)} - diff --git a/examples/src/swing/SwingBuilderTest.kt b/examples/src/swing/SwingBuilderTest.kt deleted file mode 100644 index b8030408b03..00000000000 --- a/examples/src/swing/SwingBuilderTest.kt +++ /dev/null @@ -1,29 +0,0 @@ -package demo - -import kool.swing.* -import javax.swing.* - -val greeting = "Hello,\n\nEnter some text here!" - -fun main(args : Array) { - KFrame("Demo") { - height = 100 - width = 100 - defaultCloseOperation = JFrame.EXIT_ON_CLOSE - - val text = JTextArea(greeting) - center = text - - val southPanel = JPanel { - west = JButton("Clear") { - text.setText("") - } - - east = JButton("Restore") { - text.setText(greeting) - } - } - - }.show() - -} \ No newline at end of file diff --git a/examples/src/util/Comparison.jetl b/examples/src/util/Comparison.jetl deleted file mode 100644 index 12a9fdc35c0..00000000000 --- a/examples/src/util/Comparison.jetl +++ /dev/null @@ -1,19 +0,0 @@ -type Comparison = {(T, T) : Int} - -fun naturalOrder>(a : T, b : T) : Int = a.compareTo(b) - -fun castingNaturalOrder(a : Object, b : Object) : Int = (a as Comparable).compareTo(b as Comparable) - -enum class ComparisonResult { - LS; EQ; GR -} - -type MatchableComparison = {(T, T) : ComparisonResult} - -fun asMatchableComparison(cmp : Comparison) : MatchableComparison = {(a, b) => - val res = cmp(a, b) - if (res == 0) return ComparisonResult.EQ - if (res < 0) return ComparisonResult.LS - return ComparisonResult.GR -} - diff --git a/examples/src/util/IComparable.jetl b/examples/src/util/IComparable.jetl deleted file mode 100644 index 1ce3f600ea6..00000000000 --- a/examples/src/util/IComparable.jetl +++ /dev/null @@ -1,3 +0,0 @@ -open class IComparable { - fun compareTo(other : T) : Int -} \ No newline at end of file