Fix most of the missing visibilities in stdlib

Specify visibilities and reformat surrounding code
Add test checking that there is no internal visibility specified in stdlib sources
Internal visibility does not make sense in stdlib
because it is either missed public or private would be more appropriate
This commit is contained in:
Pavel V. Talanov
2014-07-29 19:26:08 +04:00
parent af616e731b
commit 7f173fe764
33 changed files with 544 additions and 318 deletions
+2
View File
@@ -91,6 +91,8 @@
<module>tools/kdoc-maven-plugin</module> <module>tools/kdoc-maven-plugin</module>
<module>stdlib</module> <module>stdlib</module>
<module>stdlib/validator</module>
<module>kunit</module> <module>kunit</module>
<module>kotlin-jdbc</module> <module>kotlin-jdbc</module>
<module>kotlin-swing</module> <module>kotlin-swing</module>
+2 -2
View File
@@ -19,12 +19,12 @@ import kotlin.InlineOption.ONLY_LOCAL_RETURN
* String readFile(String name) throws IOException {...} * String readFile(String name) throws IOException {...}
*/ */
Retention(RetentionPolicy.SOURCE) Retention(RetentionPolicy.SOURCE)
public annotation class throws(vararg val exceptionClasses: Class<out Throwable>) public annotation class throws(public vararg val exceptionClasses: Class<out Throwable>)
[Intrinsic("kotlin.javaClass.property")] public val <T> T.javaClass : Class<T> [Intrinsic("kotlin.javaClass.property")] public val <T> T.javaClass : Class<T>
get() = (this as java.lang.Object).getClass() as Class<T> get() = (this as java.lang.Object).getClass() as Class<T>
[Intrinsic("kotlin.javaClass.function")] fun <reified T> javaClass() : Class<T> = null as Class<T> [Intrinsic("kotlin.javaClass.function")] public fun <reified T> javaClass(): Class<T> = null as Class<T>
public inline fun <R> synchronized(lock: Any, [inlineOptions(ONLY_LOCAL_RETURN)] block: () -> R): R { public inline fun <R> synchronized(lock: Any, [inlineOptions(ONLY_LOCAL_RETURN)] block: () -> R): R {
monitorEnter(lock) monitorEnter(lock)
+2 -2
View File
@@ -4,10 +4,10 @@ package kotlin
* Returns {@code true} if the specified number is a * Returns {@code true} if the specified number is a
* Not-a-Number (NaN) value, {@code false} otherwise. * Not-a-Number (NaN) value, {@code false} otherwise.
*/ */
fun Double.isNaN() = this != this public fun Double.isNaN(): Boolean = this != this
/** /**
* Returns {@code true} if the specified number is a * Returns {@code true} if the specified number is a
* Not-a-Number (NaN) value, {@code false} otherwise. * Not-a-Number (NaN) value, {@code false} otherwise.
*/ */
fun Float.isNaN() = this != this public fun Float.isNaN(): Boolean = this != this
+4 -3
View File
@@ -6,7 +6,7 @@ import java.util.Comparator
* Helper method for implementing [[Comparable]] methods using a list of functions * Helper method for implementing [[Comparable]] methods using a list of functions
* to calculate the values to compare * to calculate the values to compare
*/ */
fun <T : Any> compareBy(a: T?, b: T?, vararg functions: T.() -> Comparable<*>?): Int { public fun <T : Any> compareBy(a: T?, b: T?, vararg functions: T.() -> Comparable<*>?): Int {
require(functions.size > 0) require(functions.size > 0)
if (a === b) return 0 if (a === b) return 0
if (a == null) return - 1 if (a == null) return - 1
@@ -41,7 +41,7 @@ public fun <T> comparator(vararg functions: T.() -> Comparable<*>?): Comparator<
} }
private class FunctionComparator<T>(vararg val functions: T.() -> Comparable<*>?): Comparator<T> { private class FunctionComparator<T>(private vararg val functions: T.() -> Comparable<*>?) : Comparator<T> {
public override fun toString(): String { public override fun toString(): String {
return "FunctionComparator${functions.toList()}" return "FunctionComparator${functions.toList()}"
@@ -62,7 +62,8 @@ private class FunctionComparator<T>(vararg val functions: T.() -> Comparable<*>?
public fun <T> comparator(fn: (T,T) -> Int): Comparator<T> { public fun <T> comparator(fn: (T,T) -> Int): Comparator<T> {
return Function2Comparator<T>(fn) return Function2Comparator<T>(fn)
} }
private class Function2Comparator<T>(val compareFn: (T,T) -> Int): Comparator<T> {
private class Function2Comparator<T>(private val compareFn: (T, T) -> Int) : Comparator<T> {
public override fun toString(): String { public override fun toString(): String {
return "Function2Comparator${compareFn}" return "Function2Comparator${compareFn}"
@@ -6,7 +6,7 @@ import java.util.NoSuchElementException
import java.lang.UnsupportedOperationException import java.lang.UnsupportedOperationException
// not using an enum for now as JS generation doesn't support it // not using an enum for now as JS generation doesn't support it
object State { private object State {
val Ready = 0 val Ready = 0
val NotReady = 1 val NotReady = 1
val Done = 2 val Done = 2
@@ -1,5 +1,5 @@
package kotlin package kotlin
public class EmptyIterableException(val it : Iterable<*>) : RuntimeException("$it is empty") public class EmptyIterableException(private val it: Iterable<*>) : RuntimeException("$it is empty")
public class DuplicateKeyException(message : String = "Duplicate keys detected") : RuntimeException(message) public class DuplicateKeyException(message : String = "Duplicate keys detected") : RuntimeException(message)
@@ -2,11 +2,11 @@ package kotlin
import java.util.* import java.util.*
class stdlib_emptyListClass : List<Any> by ArrayList<Any>() {} private class stdlib_emptyListClass : List<Any> by ArrayList<Any>() {}
private val stdlib_emptyList : List<Any> = ArrayList<Any>() // TODO: Change to stdlib_emptyListClass() when KT-5192 is fixed private val stdlib_emptyList : List<Any> = ArrayList<Any>() // TODO: Change to stdlib_emptyListClass() when KT-5192 is fixed
private fun stdlib_emptyList<T>() = stdlib_emptyList as List<T> private fun stdlib_emptyList<T>() = stdlib_emptyList as List<T>
class stdlib_emptyMapClass : Map<Any, Any> by HashMap<Any, Any>() {} private class stdlib_emptyMapClass : Map<Any, Any> by HashMap<Any, Any>() {}
private val stdlib_emptyMap : Map<Any, Any> = HashMap<Any, Any>() // TODO: Change to stdlib_emptyMapClass() when KT-5192 is fixed private val stdlib_emptyMap : Map<Any, Any> = HashMap<Any, Any>() // TODO: Change to stdlib_emptyMapClass() when KT-5192 is fixed
private fun stdlib_emptyMap<K,V>() = stdlib_emptyMap as Map<K,V> private fun stdlib_emptyMap<K,V>() = stdlib_emptyMap as Map<K,V>
@@ -71,7 +71,7 @@ public val Int.indices: IntRange
public fun <T> Collection<T>.isNotEmpty(): Boolean = !this.isEmpty() public fun <T> Collection<T>.isNotEmpty(): Boolean = !this.isEmpty()
/** Returns true if this collection is not empty */ /** Returns true if this collection is not empty */
val Collection<*>.notEmpty: Boolean public val Collection<*>.notEmpty: Boolean
get() = isNotEmpty() get() = isNotEmpty()
/** Returns the Collection if its not null otherwise it returns the empty list */ /** Returns the Collection if its not null otherwise it returns the empty list */
@@ -105,7 +105,7 @@ answer.sort(comparator)
* *
* @includeFunctionBody ../../test/collections/ListSpecificTest.kt first * @includeFunctionBody ../../test/collections/ListSpecificTest.kt first
*/ */
val <T> List<T>.first: T? public val <T> List<T>.first: T?
get() = this.head get() = this.head
@@ -114,7 +114,7 @@ val <T> List<T>.first: T?
* *
* @includeFunctionBody ../../test/collections/ListSpecificTest.kt last * @includeFunctionBody ../../test/collections/ListSpecificTest.kt last
*/ */
val <T> List<T>.last: T? public val <T> List<T>.last: T?
get() { get() {
val s = this.size val s = this.size
return if (s > 0) this[s - 1] else null return if (s > 0) this[s - 1] else null
@@ -125,7 +125,7 @@ val <T> List<T>.last: T?
* *
* @includeFunctionBody ../../test/collections/ListSpecificTest.kt lastIndex * @includeFunctionBody ../../test/collections/ListSpecificTest.kt lastIndex
*/ */
val <T> List<T>.lastIndex: Int public val <T> List<T>.lastIndex: Int
get() = this.size - 1 get() = this.size - 1
/** /**
@@ -133,7 +133,7 @@ val <T> List<T>.lastIndex: Int
* *
* @includeFunctionBody ../../test/collections/ListSpecificTest.kt head * @includeFunctionBody ../../test/collections/ListSpecificTest.kt head
*/ */
val <T> List<T>.head: T? public val <T> List<T>.head: T?
get() = if (this.isNotEmpty()) this[0] else null get() = if (this.isNotEmpty()) this[0] else null
/** /**
@@ -141,7 +141,7 @@ val <T> List<T>.head: T?
* *
* @includeFunctionBody ../../test/collections/ListSpecificTest.kt tail * @includeFunctionBody ../../test/collections/ListSpecificTest.kt tail
*/ */
val <T> List<T>.tail: List<T> public val <T> List<T>.tail: List<T>
get() { get() {
return this.drop(1) return this.drop(1)
} }
@@ -46,4 +46,4 @@ public fun <T> Set<T>?.orEmpty(): Set<T>
* specified enumeration in the order they are returned by the * specified enumeration in the order they are returned by the
* enumeration. * enumeration.
*/ */
fun <T> Enumeration<T>.toList(): List<T> = Collections.list(this) public fun <T> Enumeration<T>.toList(): List<T> = Collections.list(this)
@@ -27,17 +27,17 @@ public val <K, V> Map.Entry<K, V>.value: V
get() = getValue() get() = getValue()
/** Returns the key of the entry */ /** Returns the key of the entry */
fun <K, V> Map.Entry<K, V>.component1(): K { public fun <K, V> Map.Entry<K, V>.component1(): K {
return getKey() return getKey()
} }
/** Returns the value of the entry */ /** Returns the value of the entry */
fun <K, V> Map.Entry<K, V>.component2(): V { public fun <K, V> Map.Entry<K, V>.component2(): V {
return getValue() return getValue()
} }
/** Converts entry to Pair with key being first component and value being second */ /** Converts entry to Pair with key being first component and value being second */
fun <K, V> Map.Entry<K, V>.toPair(): Pair<K, V> { public fun <K, V> Map.Entry<K, V>.toPair(): Pair<K, V> {
return Pair(getKey(), getValue()) return Pair(getKey(), getValue())
} }
@@ -9,7 +9,9 @@ public trait Stream<out T> {
public fun <T> streamOf(vararg elements: T): Stream<T> = elements.stream() public fun <T> streamOf(vararg elements: T): Stream<T> = elements.stream()
public class FilteringStream<T>(val stream: Stream<T>, val sendWhen: Boolean = true, val predicate: (T) -> Boolean) : Stream<T> { public class FilteringStream<T>(
private val stream: Stream<T>, private val sendWhen: Boolean = true, private val predicate: (T) -> Boolean
) : Stream<T> {
override fun iterator(): Iterator<T> = object : AbstractIterator<T>() { override fun iterator(): Iterator<T> = object : AbstractIterator<T>() {
val iterator = stream.iterator() val iterator = stream.iterator()
override fun computeNext() { override fun computeNext() {
@@ -25,7 +27,7 @@ public class FilteringStream<T>(val stream: Stream<T>, val sendWhen: Boolean = t
} }
} }
public class TransformingStream<T, R>(val stream: Stream<T>, val transformer: (T) -> R) : Stream<R> { public class TransformingStream<T, R>(private val stream: Stream<T>, private val transformer: (T) -> R) : Stream<R> {
override fun iterator(): Iterator<R> = object : AbstractIterator<R>() { override fun iterator(): Iterator<R> = object : AbstractIterator<R>() {
val iterator = stream.iterator() val iterator = stream.iterator()
override fun computeNext() { override fun computeNext() {
@@ -38,7 +40,9 @@ public class TransformingStream<T, R>(val stream: Stream<T>, val transformer: (T
} }
} }
public class MergingStream<T1, T2, V>(val stream1: Stream<T1>, val stream2: Stream<T2>, val transform: (T1, T2) -> V) : Stream<V> { public class MergingStream<T1, T2, V>(
private val stream1: Stream<T1>, private val stream2: Stream<T2>, private val transform: (T1, T2) -> V
) : Stream<V> {
override fun iterator(): Iterator<V> = object : AbstractIterator<V>() { override fun iterator(): Iterator<V> = object : AbstractIterator<V>() {
val iterator1 = stream1.iterator() val iterator1 = stream1.iterator()
val iterator2 = stream2.iterator() val iterator2 = stream2.iterator()
@@ -52,7 +56,9 @@ public class MergingStream<T1, T2, V>(val stream1: Stream<T1>, val stream2: Stre
} }
} }
public class FlatteningStream<T, R>(val stream: Stream<T>, val transformer: (T) -> Stream<R>) : Stream<R> { public class FlatteningStream<T, R>(
private val stream: Stream<T>, private val transformer: (T) -> Stream<R>
) : Stream<R> {
override fun iterator(): Iterator<R> = object : AbstractIterator<R>() { override fun iterator(): Iterator<R> = object : AbstractIterator<R>() {
val iterator = stream.iterator() val iterator = stream.iterator()
var itemIterator: Iterator<R>? = null var itemIterator: Iterator<R>? = null
@@ -81,7 +87,7 @@ public class FlatteningStream<T, R>(val stream: Stream<T>, val transformer: (T)
} }
} }
public class Multistream<T>(val streams: Stream<Stream<T>>) : Stream<T> { public class Multistream<T>(private val streams: Stream<Stream<T>>) : Stream<T> {
override fun iterator(): Iterator<T> = object : AbstractIterator<T>() { override fun iterator(): Iterator<T> = object : AbstractIterator<T>() {
val iterator = streams.iterator() val iterator = streams.iterator()
var streamIterator: Iterator<T>? = null var streamIterator: Iterator<T>? = null
@@ -110,7 +116,9 @@ public class Multistream<T>(val streams: Stream<Stream<T>>) : Stream<T> {
} }
} }
public class LimitedStream<T>(val stream: Stream<T>, val stopWhen: Boolean = true, val predicate: (T) -> Boolean) : Stream<T> { public class LimitedStream<T>(
private val stream: Stream<T>, private val stopWhen: Boolean = true, private val predicate: (T) -> Boolean
) : Stream<T> {
override fun iterator(): Iterator<T> = object : AbstractIterator<T>() { override fun iterator(): Iterator<T> = object : AbstractIterator<T>() {
val iterator = stream.iterator() val iterator = stream.iterator()
override fun computeNext() { override fun computeNext() {
@@ -128,7 +136,7 @@ public class LimitedStream<T>(val stream: Stream<T>, val stopWhen: Boolean = tru
} }
} }
public class FunctionStream<T : Any>(val producer: () -> T?) : Stream<T> { public class FunctionStream<T : Any>(private val producer: () -> T?) : Stream<T> {
override fun iterator(): Iterator<T> = object : AbstractIterator<T>() { override fun iterator(): Iterator<T> = object : AbstractIterator<T>() {
override fun computeNext() { override fun computeNext() {
@@ -33,7 +33,8 @@ deprecated("Replace Iterator<T> with Stream<T> by using stream() function instea
public fun <T> Iterator<T>.skip(n: Int): Iterator<T> = SkippingIterator(this, n) public fun <T> Iterator<T>.skip(n: Int): Iterator<T> = SkippingIterator(this, n)
deprecated("Use FilteringStream<T> instead") deprecated("Use FilteringStream<T> instead")
class FilterIterator<T>(val iterator : Iterator<T>, val predicate: (T)-> Boolean) : AbstractIterator<T>() { public class FilterIterator<T>(private val iterator: Iterator<T>, private val predicate: (T) -> Boolean) :
AbstractIterator<T>() {
override protected fun computeNext(): Unit { override protected fun computeNext(): Unit {
while (iterator.hasNext()) { while (iterator.hasNext()) {
val next = iterator.next() val next = iterator.next()
@@ -47,7 +48,7 @@ class FilterIterator<T>(val iterator : Iterator<T>, val predicate: (T)-> Boolean
} }
deprecated("Use FilteringStream<T> instead") deprecated("Use FilteringStream<T> instead")
class FilterNotNullIterator<T:Any>(val iterator : Iterator<T?>?) : AbstractIterator<T>() { public class FilterNotNullIterator<T : Any>(private val iterator: Iterator<T?>?) : AbstractIterator<T>() {
override protected fun computeNext(): Unit { override protected fun computeNext(): Unit {
if (iterator != null) { if (iterator != null) {
while (iterator.hasNext()) { while (iterator.hasNext()) {
@@ -63,8 +64,9 @@ class FilterNotNullIterator<T:Any>(val iterator : Iterator<T?>?) : AbstractItera
} }
deprecated("Use TransformingStream<T> instead") deprecated("Use TransformingStream<T> instead")
class MapIterator<T, R>(val iterator : Iterator<T>, val transform: (T) -> R) : AbstractIterator<R>() { public class MapIterator<T, R>(private val iterator: Iterator<T>, private val transform: (T) -> R) :
override protected fun computeNext() : Unit { AbstractIterator<R>() {
override protected fun computeNext(): Unit {
if (iterator.hasNext()) { if (iterator.hasNext()) {
setNext((transform)(iterator.next())) setNext((transform)(iterator.next()))
} else { } else {
@@ -74,10 +76,11 @@ class MapIterator<T, R>(val iterator : Iterator<T>, val transform: (T) -> R) : A
} }
deprecated("Use FlatteningStream<T> instead") deprecated("Use FlatteningStream<T> instead")
class FlatMapIterator<T, R>(val iterator : Iterator<T>, val transform: (T) -> Iterator<R>) : AbstractIterator<R>() { public class FlatMapIterator<T, R>(private val iterator: Iterator<T>, private val transform: (T) -> Iterator<R>) :
var transformed: Iterator<R> = iterate<R> { null } AbstractIterator<R>() {
private var transformed: Iterator<R> = iterate<R> { null }
override protected fun computeNext() : Unit { override protected fun computeNext(): Unit {
while (true) { while (true) {
if (transformed.hasNext()) { if (transformed.hasNext()) {
setNext(transformed.next()) setNext(transformed.next())
@@ -94,7 +97,8 @@ class FlatMapIterator<T, R>(val iterator : Iterator<T>, val transform: (T) -> It
} }
deprecated("Use LimitedStream<T> instead") deprecated("Use LimitedStream<T> instead")
class TakeWhileIterator<T>(val iterator: Iterator<T>, val predicate: (T) -> Boolean) : AbstractIterator<T>() { public class TakeWhileIterator<T>(private val iterator: Iterator<T>, private val predicate: (T) -> Boolean) :
AbstractIterator<T>() {
override protected fun computeNext() : Unit { override protected fun computeNext() : Unit {
if (iterator.hasNext()) { if (iterator.hasNext()) {
val item = iterator.next() val item = iterator.next()
@@ -109,7 +113,7 @@ class TakeWhileIterator<T>(val iterator: Iterator<T>, val predicate: (T) -> Bool
/** An [[Iterator]] which invokes a function to calculate the next value in the iteration until the function returns *null* */ /** An [[Iterator]] which invokes a function to calculate the next value in the iteration until the function returns *null* */
deprecated("Use FunctionStream<T> instead") deprecated("Use FunctionStream<T> instead")
class FunctionIterator<T:Any>(val nextFunction: () -> T?): AbstractIterator<T>() { public class FunctionIterator<T : Any>(private val nextFunction: () -> T?) : AbstractIterator<T>() {
override protected fun computeNext(): Unit { override protected fun computeNext(): Unit {
val next = (nextFunction)() val next = (nextFunction)()
@@ -123,12 +127,12 @@ class FunctionIterator<T:Any>(val nextFunction: () -> T?): AbstractIterator<T>()
/** An [[Iterator]] which iterates over a number of iterators in sequence */ /** An [[Iterator]] which iterates over a number of iterators in sequence */
deprecated("Use Multistream<T> instead") deprecated("Use Multistream<T> instead")
fun CompositeIterator<T>(vararg iterators: Iterator<T>): CompositeIterator<T> = CompositeIterator(iterators.iterator()) public fun CompositeIterator<T>(vararg iterators: Iterator<T>): CompositeIterator<T> = CompositeIterator(iterators.iterator())
deprecated("Use Multistream<T> instead") deprecated("Use Multistream<T> instead")
class CompositeIterator<T>(val iterators: Iterator<Iterator<T>>): AbstractIterator<T>() { public class CompositeIterator<T>(private val iterators: Iterator<Iterator<T>>) : AbstractIterator<T>() {
var currentIter: Iterator<T>? = null private var currentIter: Iterator<T>? = null
override protected fun computeNext(): Unit { override protected fun computeNext(): Unit {
while (true) { while (true) {
@@ -155,8 +159,8 @@ class CompositeIterator<T>(val iterators: Iterator<Iterator<T>>): AbstractIterat
/** A singleton [[Iterator]] which invokes once over a value */ /** A singleton [[Iterator]] which invokes once over a value */
deprecated("Use streams for lazy collection operations.") deprecated("Use streams for lazy collection operations.")
class SingleIterator<T>(val value: T): AbstractIterator<T>() { public class SingleIterator<T>(private val value: T) : AbstractIterator<T>() {
var first = true private var first = true
override protected fun computeNext(): Unit { override protected fun computeNext(): Unit {
if (first) { if (first) {
@@ -169,8 +173,8 @@ class SingleIterator<T>(val value: T): AbstractIterator<T>() {
} }
deprecated("Use streams for lazy collection operations.") deprecated("Use streams for lazy collection operations.")
class IndexIterator<T>(val iterator : Iterator<T>): Iterator<Pair<Int, T>> { public class IndexIterator<T>(private val iterator: Iterator<T>) : Iterator<Pair<Int, T>> {
private var index : Int = 0 private var index: Int = 0
override fun next(): Pair<Int, T> { override fun next(): Pair<Int, T> {
return Pair(index++, iterator.next()) return Pair(index++, iterator.next())
@@ -183,7 +187,7 @@ class IndexIterator<T>(val iterator : Iterator<T>): Iterator<Pair<Int, T>> {
deprecated("Use ZippingStream<T> instead.") deprecated("Use ZippingStream<T> instead.")
public class PairIterator<T, S>( public class PairIterator<T, S>(
val iterator1 : Iterator<T>, val iterator2 : Iterator<S> private val iterator1: Iterator<T>, private val iterator2: Iterator<S>
): AbstractIterator<Pair<T, S>>() { ): AbstractIterator<Pair<T, S>>() {
protected override fun computeNext() { protected override fun computeNext() {
if (iterator1.hasNext() && iterator2.hasNext()) { if (iterator1.hasNext() && iterator2.hasNext()) {
@@ -196,7 +200,7 @@ public class PairIterator<T, S>(
} }
deprecated("Use streams for lazy collection operations.") deprecated("Use streams for lazy collection operations.")
class SkippingIterator<T>(val iterator: Iterator<T>, val n: Int): Iterator<T> { public class SkippingIterator<T>(private val iterator: Iterator<T>, private val n: Int) : Iterator<T> {
private var firstTime: Boolean = true private var firstTime: Boolean = true
private fun skip() { private fun skip() {
@@ -4,10 +4,11 @@ import kotlin.support.*
/** Returns an iterator over elements that are instances of a given type *R* which is a subclass of *T* */ /** Returns an iterator over elements that are instances of a given type *R* which is a subclass of *T* */
deprecated("Use streams for lazy collection operations.") deprecated("Use streams for lazy collection operations.")
public fun <T, R: T> Iterator<T>.filterIsInstance(klass: Class<R>): Iterator<R> = FilterIsIterator<T,R>(this, klass) public fun <T, R : T> Iterator<T>.filterIsInstance(klass: Class<R>): Iterator<R> = FilterIsIterator<T, R>(this, klass)
deprecated("Use streams for lazy collection operations.") deprecated("Use streams for lazy collection operations.")
private class FilterIsIterator<T, R :T>(val iterator : Iterator<T>, val klass: Class<R>) : AbstractIterator<R>() { public class FilterIsIterator<T, R : T>(private val iterator: Iterator<T>, private val klass: Class<R>) :
AbstractIterator<R>() {
override protected fun computeNext(): Unit { override protected fun computeNext(): Unit {
while (iterator.hasNext()) { while (iterator.hasNext()) {
val next = iterator.next() val next = iterator.next()
@@ -1,15 +1,15 @@
package kotlin.concurrent package kotlin.concurrent
abstract class FunctionalList<T>(public val size: Int) { public abstract class FunctionalList<T>(public val size: Int) {
public abstract val head: T public abstract val head: T
public abstract val tail: FunctionalList<T> public abstract val tail: FunctionalList<T>
val empty : Boolean public val empty: Boolean
get() = size == 0 get() = size == 0
public fun add(element: T) : FunctionalList<T> = FunctionalList.Standard(element, this) public fun add(element: T): FunctionalList<T> = FunctionalList.Standard(element, this)
public fun reversed() : FunctionalList<T> { public fun reversed(): FunctionalList<T> {
if(empty) if(empty)
return this return this
@@ -39,18 +39,18 @@ abstract class FunctionalList<T>(public val size: Int) {
} }
class object { class object {
class Empty<T>() : FunctionalList<T>(0) { private class Empty<T>() : FunctionalList<T>(0) {
override val head: T override val head: T
get() = throw java.util.NoSuchElementException() get() = throw java.util.NoSuchElementException()
override val tail: FunctionalList<T> override val tail: FunctionalList<T>
get() = throw java.util.NoSuchElementException() get() = throw java.util.NoSuchElementException()
} }
class Standard<T>(override val head: T, override val tail: FunctionalList<T>) : FunctionalList<T>(tail.size+1) private class Standard<T>(override val head: T, override val tail: FunctionalList<T>) : FunctionalList<T>(tail.size + 1)
public fun <T> emptyList() : FunctionalList<T> = Empty<T>() public fun <T> emptyList(): FunctionalList<T> = Empty<T>()
public fun <T> of(element: T) : FunctionalList<T> = FunctionalList.Standard<T>(element,emptyList()) public fun <T> of(element: T): FunctionalList<T> = FunctionalList.Standard<T>(element, emptyList())
} }
} }
@@ -2,28 +2,29 @@ package kotlin.concurrent
import java.util.concurrent.Executor import java.util.concurrent.Executor
class FunctionalQueue<T> ( public class FunctionalQueue<T> (
val input: FunctionalList<T> = FunctionalList.emptyList<T>(), private val input: FunctionalList<T> = FunctionalList.emptyList<T>(),
val output: FunctionalList<T> = FunctionalList.emptyList<T>()) { private val output: FunctionalList<T> = FunctionalList.emptyList<T>()
) {
val size : Int public val size: Int
get() = input.size + output.size get() = input.size + output.size
val empty : Boolean public val empty: Boolean
get() = size == 0 get() = size == 0
public fun add(element: T) : FunctionalQueue<T> = FunctionalQueue<T>(input add element, output) public fun add(element: T): FunctionalQueue<T> = FunctionalQueue<T>(input add element, output)
public fun addFirst(element: T) : FunctionalQueue<T> = FunctionalQueue<T>(input, output add element) public fun addFirst(element: T): FunctionalQueue<T> = FunctionalQueue<T>(input, output add element)
public fun removeFirst() : Pair<T, FunctionalQueue<T>> = public fun removeFirst(): Pair<T, FunctionalQueue<T>> =
if(output.empty) { if (output.empty) {
if(input.empty) if (input.empty)
throw java.util.NoSuchElementException() throw java.util.NoSuchElementException()
else else
FunctionalQueue<T>(FunctionalList.emptyList<T>(), input.reversed()).removeFirst() FunctionalQueue<T>(FunctionalList.emptyList<T>(), input.reversed()).removeFirst()
} }
else { else {
Pair(output.head, FunctionalQueue<T>(input, output.tail)) Pair(output.head, FunctionalQueue<T>(input, output.tail))
} }
} }
@@ -63,7 +63,7 @@ public inline fun <T> ReentrantReadWriteLock.write([inlineOptions(ONLY_LOCAL_RET
Execute given calculation and await for CountDownLatch Execute given calculation and await for CountDownLatch
Returns result of the calculation Returns result of the calculation
*/ */
fun <T> Int.latch(op: CountDownLatch.() -> T) : T { public fun <T> Int.latch(op: CountDownLatch.() -> T): T {
val cdl = CountDownLatch(this) val cdl = CountDownLatch(this)
val res = cdl.op() val res = cdl.op()
cdl.await() cdl.await()
@@ -5,43 +5,43 @@ import java.util.concurrent.ExecutorService
import java.util.concurrent.Future import java.util.concurrent.Future
import java.util.concurrent.Callable import java.util.concurrent.Callable
val currentThread : Thread public val currentThread: Thread
get() = Thread.currentThread() get() = Thread.currentThread()
var Thread.name : String public var Thread.name: String
get() = getName() get() = getName()
set(name: String) { setName(name) } set(name: String) { setName(name) }
var Thread.daemon : Boolean public var Thread.daemon: Boolean
get() = isDaemon() get() = isDaemon()
set(on: Boolean) { setDaemon(on) } set(on: Boolean) { setDaemon(on) }
val Thread.alive : Boolean public val Thread.alive: Boolean
get() = isAlive() get() = isAlive()
var Thread.priority : Int public var Thread.priority: Int
get() = getPriority() get() = getPriority()
set(prio: Int) { setPriority(prio) } set(prio: Int) { setPriority(prio) }
var Thread.contextClassLoader : ClassLoader? public var Thread.contextClassLoader: ClassLoader?
get() = getContextClassLoader() get() = getContextClassLoader()
set(loader: ClassLoader?) { setContextClassLoader(loader) } set(loader: ClassLoader?) { setContextClassLoader(loader) }
public fun thread(start: Boolean = true, daemon: Boolean = false, contextClassLoader: ClassLoader? = null, name: String? = null, priority: Int = -1, block: ()->Unit) : Thread { public fun thread(start: Boolean = true, daemon: Boolean = false, contextClassLoader: ClassLoader? = null, name: String? = null, priority: Int = -1, block: () -> Unit): Thread {
val thread = object: Thread() { val thread = object : Thread() {
public override fun run() { public override fun run() {
block() block()
} }
} }
if(daemon) if (daemon)
thread.setDaemon(true) thread.setDaemon(true)
if(priority > 0) if (priority > 0)
thread.setPriority(priority) thread.setPriority(priority)
if(name != null) if (name != null)
thread.setName(name) thread.setName(name)
if(contextClassLoader != null) if (contextClassLoader != null)
thread.setContextClassLoader(contextClassLoader) thread.setContextClassLoader(contextClassLoader)
if(start) if (start)
thread.start() thread.start()
return thread return thread
} }
@@ -50,7 +50,7 @@ public fun thread(start: Boolean = true, daemon: Boolean = false, contextClassLo
* Allows you to use the executor as a function to * Allows you to use the executor as a function to
* execute the given block on the [[Executor]]. * execute the given block on the [[Executor]].
*/ */
public /*inline*/ fun Executor.invoke(action: ()->Unit) { public /*inline*/ fun Executor.invoke(action: () -> Unit) {
execute(runnable(action)) execute(runnable(action))
} }
@@ -58,6 +58,6 @@ public /*inline*/ fun Executor.invoke(action: ()->Unit) {
* Allows you to use the executor as a function to * Allows you to use the executor as a function to
* execute the given block on the [[Executor]]. * execute the given block on the [[Executor]].
*/ */
public /*inline*/ fun <T>ExecutorService.invoke(action: ()->T):Future<T> { public /*inline*/ fun <T>ExecutorService.invoke(action: () -> T): Future<T> {
return submit(action) return submit(action)
} }
+74 -73
View File
@@ -13,15 +13,15 @@ import java.lang.IndexOutOfBoundsException
private fun emptyElementList(): List<Element> = Collections.emptyList<Element>() private fun emptyElementList(): List<Element> = Collections.emptyList<Element>()
private fun emptyNodeList(): List<Node> = Collections.emptyList<Node>() private fun emptyNodeList(): List<Node> = Collections.emptyList<Node>()
var Node.text : String public var Node.text: String
get() { get() {
return textContent return textContent
} }
set(value) { set(value) {
textContent = value textContent = value
} }
var Element.childrenText: String public var Element.childrenText: String
get() { get() {
val buffer = StringBuilder() val buffer = StringBuilder()
val nodeList = this.childNodes val nodeList = this.childNodes
@@ -49,77 +49,77 @@ var Element.childrenText: String
element.addText(value) element.addText(value)
} }
var Element.id : String public var Element.id: String
get() = this.getAttribute("id")?: "" get() = this.getAttribute("id") ?: ""
set(value) { set(value) {
this.setAttribute("id", value) this.setAttribute("id", value)
this.setIdAttribute("id", true) this.setIdAttribute("id", true)
} }
var Element.style : String public var Element.style: String
get() = this.getAttribute("style")?: "" get() = this.getAttribute("style") ?: ""
set(value) { set(value) {
this.setAttribute("style", value) this.setAttribute("style", value)
} }
var Element.classes : String public var Element.classes: String
get() = this.getAttribute("class")?: "" get() = this.getAttribute("class") ?: ""
set(value) { set(value) {
this.setAttribute("class", value) this.setAttribute("class", value)
} }
/** Returns true if the element has the given CSS class style in its 'class' attribute */ /** Returns true if the element has the given CSS class style in its 'class' attribute */
fun Element.hasClass(cssClass: String): Boolean { public fun Element.hasClass(cssClass: String): Boolean {
val c = this.classes val c = this.classes
return c.matches("""(^|.*\s+)$cssClass($|\s+.*)""") return c.matches("""(^|.*\s+)$cssClass($|\s+.*)""")
} }
/** Returns the children of the element as a list */ /** Returns the children of the element as a list */
fun Element?.children(): List<Node> { public fun Element?.children(): List<Node> {
return this?.childNodes.toList() return this?.childNodes.toList()
} }
/** Returns the child elements of this element */ /** Returns the child elements of this element */
fun Element?.childElements(): List<Element> { public fun Element?.childElements(): List<Element> {
return children().filter<Node>{ it.nodeType == Node.ELEMENT_NODE }.map { it as Element } return children().filter<Node>{ it.nodeType == Node.ELEMENT_NODE }.map { it as Element }
} }
/** Returns the child elements of this element with the given name */ /** Returns the child elements of this element with the given name */
fun Element?.childElements(name: String): List<Element> { public fun Element?.childElements(name: String): List<Element> {
return children().filter<Node>{ it.nodeType == Node.ELEMENT_NODE && it.nodeName == name }.map { it as Element } return children().filter<Node>{ it.nodeType == Node.ELEMENT_NODE && it.nodeName == name }.map { it as Element }
} }
/** The descendent elements of this document */ /** The descendent elements of this document */
val Document?.elements : List<Element> public val Document?.elements: List<Element>
get() = this?.getElementsByTagName("*").toElementList() get() = this?.getElementsByTagName("*").toElementList()
/** The descendant elements of this elements */ /** The descendant elements of this elements */
val Element?.elements : List<Element> public val Element?.elements: List<Element>
get() = this?.getElementsByTagName("*").toElementList() get() = this?.getElementsByTagName("*").toElementList()
/** Returns all the descendant elements given the local element name */ /** Returns all the descendant elements given the local element name */
fun Element?.elements(localName: String): List<Element> { public fun Element?.elements(localName: String): List<Element> {
return this?.getElementsByTagName(localName).toElementList() return this?.getElementsByTagName(localName).toElementList()
} }
/** Returns all the descendant elements given the local element name */ /** Returns all the descendant elements given the local element name */
fun Document?.elements(localName: String): List<Element> { public fun Document?.elements(localName: String): List<Element> {
return this?.getElementsByTagName(localName).toElementList() return this?.getElementsByTagName(localName).toElementList()
} }
/** Returns all the descendant elements given the namespace URI and local element name */ /** Returns all the descendant elements given the namespace URI and local element name */
fun Element?.elements(namespaceUri: String, localName: String): List<Element> { public fun Element?.elements(namespaceUri: String, localName: String): List<Element> {
return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList() return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList()
} }
/** Returns all the descendant elements given the namespace URI and local element name */ /** Returns all the descendant elements given the namespace URI and local element name */
fun Document?.elements(namespaceUri: String, localName: String): List<Element> { public fun Document?.elements(namespaceUri: String, localName: String): List<Element> {
return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList() return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList()
} }
fun NodeList?.toList(): List<Node> { public fun NodeList?.toList(): List<Node> {
return if (this == null) { return if (this == null) {
// TODO the following is easier to convert to JS // TODO the following is easier to convert to JS
emptyNodeList() emptyNodeList()
@@ -129,7 +129,7 @@ fun NodeList?.toList(): List<Node> {
} }
} }
fun NodeList?.toElementList(): List<Element> { public fun NodeList?.toElementList(): List<Element> {
return if (this == null) { return if (this == null) {
// TODO the following is easier to convert to JS // TODO the following is easier to convert to JS
//emptyElementList() //emptyElementList()
@@ -141,7 +141,7 @@ fun NodeList?.toElementList(): List<Element> {
} }
/** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */ /** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */
fun Document?.get(selector: String): List<Element> { public fun Document?.get(selector: String): List<Element> {
val root = this?.documentElement val root = this?.documentElement
return if (root != null) { return if (root != null) {
if (selector == "*") { if (selector == "*") {
@@ -165,7 +165,7 @@ fun Document?.get(selector: String): List<Element> {
} }
/** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */ /** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */
fun Element.get(selector: String): List<Element> { public fun Element.get(selector: String): List<Element> {
return if (selector == "*") { return if (selector == "*") {
elements elements
} else if (selector.startsWith(".")) { } else if (selector.startsWith(".")) {
@@ -216,7 +216,7 @@ fun Element.removeClass(varargs cssClasses: Array<String>): Boolean {
} }
*/ */
class NodeListAsList(val nodeList: NodeList): AbstractList<Node>() { private class NodeListAsList(private val nodeList: NodeList) : AbstractList<Node>() {
override fun get(index: Int): Node { override fun get(index: Int): Node {
val node = nodeList.item(index) val node = nodeList.item(index)
if (node == null) { if (node == null) {
@@ -229,7 +229,7 @@ class NodeListAsList(val nodeList: NodeList): AbstractList<Node>() {
override fun size(): Int = nodeList.length override fun size(): Int = nodeList.length
} }
class ElementListAsList(val nodeList: NodeList): AbstractList<Element>() { private class ElementListAsList(private val nodeList: NodeList) : AbstractList<Element>() {
override fun get(index: Int): Element { override fun get(index: Int): Element {
val node = nodeList.item(index) val node = nodeList.item(index)
if (node == null) { if (node == null) {
@@ -246,7 +246,7 @@ class ElementListAsList(val nodeList: NodeList): AbstractList<Element>() {
} }
/** Removes all the children from this node */ /** Removes all the children from this node */
fun Node.clear(): Unit { public fun Node.clear(): Unit {
while (true) { while (true) {
val child = firstChild val child = firstChild
if (child == null) { if (child == null) {
@@ -258,9 +258,9 @@ fun Node.clear(): Unit {
} }
/** Returns an [[Iterator]] over the next siblings of this node */ /** Returns an [[Iterator]] over the next siblings of this node */
fun Node.nextSiblings() : Iterable<Node> = NextSiblings(this) public fun Node.nextSiblings(): Iterable<Node> = NextSiblings(this)
class NextSiblings(var node: Node) : Iterable<Node> { private class NextSiblings(private var node: Node) : Iterable<Node> {
override fun iterator(): Iterator<Node> = object : AbstractIterator<Node>() { override fun iterator(): Iterator<Node> = object : AbstractIterator<Node>() {
override fun computeNext(): Unit { override fun computeNext(): Unit {
val nextValue = node.nextSibling val nextValue = node.nextSibling
@@ -275,9 +275,9 @@ class NextSiblings(var node: Node) : Iterable<Node> {
} }
/** Returns an [[Iterator]] over the next siblings of this node */ /** Returns an [[Iterator]] over the next siblings of this node */
fun Node.previousSiblings() : Iterable<Node> = PreviousSiblings(this) public fun Node.previousSiblings(): Iterable<Node> = PreviousSiblings(this)
class PreviousSiblings(var node: Node) : Iterable<Node> { private class PreviousSiblings(private var node: Node) : Iterable<Node> {
override fun iterator(): Iterator<Node> = object : AbstractIterator<Node>() { override fun iterator(): Iterator<Node> = object : AbstractIterator<Node>() {
override fun computeNext(): Unit { override fun computeNext(): Unit {
val nextValue = node.previousSibling val nextValue = node.previousSibling
@@ -292,38 +292,39 @@ class PreviousSiblings(var node: Node) : Iterable<Node> {
} }
/** Returns true if this node is a Text node or a CDATA node */ /** Returns true if this node is a Text node or a CDATA node */
fun Node.isText(): Boolean { public fun Node.isText(): Boolean {
val nt = nodeType val nt = nodeType
return nt == Node.TEXT_NODE || nt == Node.CDATA_SECTION_NODE return nt == Node.TEXT_NODE || nt == Node.CDATA_SECTION_NODE
} }
/** Returns the attribute value or empty string if its not present */ /** Returns the attribute value or empty string if its not present */
fun Element.attribute(name: String): String { public fun Element.attribute(name: String): String {
return this.getAttribute(name) ?: "" return this.getAttribute(name) ?: ""
} }
val NodeList?.head : Node? public val NodeList?.head: Node?
get() = if (this != null && this.length > 0) this.item(0) else null get() = if (this != null && this.length > 0) this.item(0) else null
val NodeList?.first : Node? public val NodeList?.first: Node?
get() = this.head get() = this.head
val NodeList?.tail : Node? public val NodeList?.tail: Node?
get() { get() {
if (this == null) { if (this == null) {
return null return null
} else { }
val s = this.length else {
return if (s > 0) this.item(s - 1) else null val s = this.length
return if (s > 0) this.item(s - 1) else null
}
} }
}
val NodeList?.last : Node? public val NodeList?.last: Node?
get() = this.tail get() = this.tail
/** Converts the node list to an XML String */ /** Converts the node list to an XML String */
fun NodeList?.toXmlString(xmlDeclaration: Boolean = false): String { public fun NodeList?.toXmlString(xmlDeclaration: Boolean = false): String {
return if (this == null) return if (this == null)
"" else { "" else {
nodesToXmlString(this.toList(), xmlDeclaration) nodesToXmlString(this.toList(), xmlDeclaration)
@@ -343,16 +344,16 @@ public fun nodesToXmlString(nodes: Iterable<Node>, xmlDeclaration: Boolean = fal
// Syntax sugar // Syntax sugar
fun Node.plus(child: Node?): Node { public fun Node.plus(child: Node?): Node {
if (child != null) { if (child != null) {
this.appendChild(child) this.appendChild(child)
} }
return this return this
} }
fun Element.plus(text: String?): Element = this.addText(text) public fun Element.plus(text: String?): Element = this.addText(text)
fun Element.plusAssign(text: String?): Element = this.addText(text) public fun Element.plusAssign(text: String?): Element = this.addText(text)
// Builder // Builder
@@ -360,7 +361,7 @@ fun Element.plusAssign(text: String?): Element = this.addText(text)
/** /**
* Creates a new element which can be configured via a function * Creates a new element which can be configured via a function
*/ */
fun Document.createElement(name: String, init: Element.()-> Unit): Element { public fun Document.createElement(name: String, init: Element.() -> Unit): Element {
val elem = this.createElement(name)!! val elem = this.createElement(name)!!
elem.init() elem.init()
return elem return elem
@@ -369,14 +370,14 @@ fun Document.createElement(name: String, init: Element.()-> Unit): Element {
/** /**
* Creates a new element to an element which has an owner Document which can be configured via a function * Creates a new element to an element which has an owner Document which can be configured via a function
*/ */
fun Element.createElement(name: String, doc: Document? = null, init: Element.()-> Unit): Element { public fun Element.createElement(name: String, doc: Document? = null, init: Element.() -> Unit): Element {
val elem = ownerDocument(doc).createElement(name)!! val elem = ownerDocument(doc).createElement(name)!!
elem.init() elem.init()
return elem return elem
} }
/** Returns the owner document of the element or uses the provided document */ /** Returns the owner document of the element or uses the provided document */
fun Node.ownerDocument(doc: Document? = null): Document { public fun Node.ownerDocument(doc: Document? = null): Document {
val answer = if (this.nodeType == Node.DOCUMENT_NODE) this as Document val answer = if (this.nodeType == Node.DOCUMENT_NODE) this as Document
else if (doc == null) this.ownerDocument else if (doc == null) this.ownerDocument
else doc else doc
@@ -391,7 +392,7 @@ fun Node.ownerDocument(doc: Document? = null): Document {
/** /**
Adds a newly created element which can be configured via a function Adds a newly created element which can be configured via a function
*/ */
fun Document.addElement(name: String, init: Element.()-> Unit): Element { public fun Document.addElement(name: String, init: Element.() -> Unit): Element {
val child = createElement(name, init) val child = createElement(name, init)
this.appendChild(child) this.appendChild(child)
return child return child
@@ -400,7 +401,7 @@ fun Document.addElement(name: String, init: Element.()-> Unit): Element {
/** /**
Adds a newly created element to an element which has an owner Document which can be configured via a function Adds a newly created element to an element which has an owner Document which can be configured via a function
*/ */
fun Element.addElement(name: String, doc: Document? = null, init: Element.()-> Unit): Element { public fun Element.addElement(name: String, doc: Document? = null, init: Element.() -> Unit): Element {
val child = createElement(name, doc, init) val child = createElement(name, doc, init)
this.appendChild(child) this.appendChild(child)
return child return child
@@ -409,7 +410,7 @@ fun Element.addElement(name: String, doc: Document? = null, init: Element.()-> U
/** /**
Adds a newly created text node to an element which either already has an owner Document or one must be provided as a parameter Adds a newly created text node to an element which either already has an owner Document or one must be provided as a parameter
*/ */
fun Element.addText(text: String?, doc: Document? = null): Element { public fun Element.addText(text: String?, doc: Document? = null): Element {
if (text != null) { if (text != null) {
val child = this.ownerDocument(doc).createTextNode(text)!! val child = this.ownerDocument(doc).createTextNode(text)!!
this.appendChild(child) this.appendChild(child)
+9 -4
View File
@@ -7,11 +7,11 @@ import org.w3c.dom.events.*
/** /**
* Turns an event handler function into an [EventListener] * Turns an event handler function into an [EventListener]
*/ */
fun eventHandler(handler: (Event) -> Unit): EventListener { public fun eventHandler(handler: (Event) -> Unit): EventListener {
return EventListenerHandler(handler) return EventListenerHandler(handler)
} }
private class EventListenerHandler(val handler: (Event) -> Unit): EventListener { private class EventListenerHandler(private val handler: (Event) -> Unit) : EventListener {
public override fun handleEvent(e: Event) { public override fun handleEvent(e: Event) {
if (e != null) { if (e != null) {
handler(e) handler(e)
@@ -24,7 +24,7 @@ private class EventListenerHandler(val handler: (Event) -> Unit): EventListener
*/ */
} }
fun mouseEventHandler(handler: (MouseEvent) -> Unit): EventListener { public fun mouseEventHandler(handler: (MouseEvent) -> Unit): EventListener {
return eventHandler { e -> return eventHandler { e ->
if (e is MouseEvent) { if (e is MouseEvent) {
handler(e) handler(e)
@@ -51,7 +51,12 @@ public fun Node?.on(name: String, capture: Boolean, listener: EventListener): Cl
} }
} }
private class CloseableEventListener(val target: EventTarget, val listener: EventListener, val name: String, val capture: Boolean): Closeable { private class CloseableEventListener(
private val target: EventTarget,
private val listener: EventListener,
private val name: String,
private val capture: Boolean
) : Closeable {
public override fun close() { public override fun close() {
target.removeEventListener(name, listener, capture) target.removeEventListener(name, listener, capture)
} }
+17 -17
View File
@@ -4,55 +4,55 @@ import org.w3c.dom.Node
import org.w3c.dom.events.* import org.w3c.dom.events.*
// JavaScript style properties for JVM : TODO could auto-generate these // JavaScript style properties for JVM : TODO could auto-generate these
val Event.bubbles: Boolean public val Event.bubbles: Boolean
get() = getBubbles() get() = getBubbles()
val Event.cancelable: Boolean public val Event.cancelable: Boolean
get() = getCancelable() get() = getCancelable()
val Event.getCurrentTarget: EventTarget? public val Event.getCurrentTarget: EventTarget?
get() = getCurrentTarget() get() = getCurrentTarget()
val Event.eventPhase: Short public val Event.eventPhase: Short
get() = getEventPhase() get() = getEventPhase()
val Event.target: EventTarget? public val Event.target: EventTarget?
get() = getTarget() get() = getTarget()
val Event.timeStamp: Long public val Event.timeStamp: Long
get() = getTimeStamp() get() = getTimeStamp()
// TODO we can't use 'type' as the property name in Kotlin so we should fix it in JS // TODO we can't use 'type' as the property name in Kotlin so we should fix it in JS
val Event.eventType: String public val Event.eventType: String
get() = getType()!! get() = getType()!!
val MouseEvent.altKey: Boolean public val MouseEvent.altKey: Boolean
get() = getAltKey() get() = getAltKey()
val MouseEvent.button: Short public val MouseEvent.button: Short
get() = getButton() get() = getButton()
val MouseEvent.clientX: Int public val MouseEvent.clientX: Int
get() = getClientX() get() = getClientX()
val MouseEvent.clientY: Int public val MouseEvent.clientY: Int
get() = getClientY() get() = getClientY()
val MouseEvent.ctrlKey: Boolean public val MouseEvent.ctrlKey: Boolean
get() = getCtrlKey() get() = getCtrlKey()
val MouseEvent.metaKey: Boolean public val MouseEvent.metaKey: Boolean
get() = getMetaKey() get() = getMetaKey()
val MouseEvent.relatedTarget: EventTarget? public val MouseEvent.relatedTarget: EventTarget?
get() = getRelatedTarget() get() = getRelatedTarget()
val MouseEvent.screenX: Int public val MouseEvent.screenX: Int
get() = getScreenX() get() = getScreenX()
val MouseEvent.screenY: Int public val MouseEvent.screenY: Int
get() = getScreenY() get() = getScreenY()
val MouseEvent.shiftKey: Boolean public val MouseEvent.shiftKey: Boolean
get() = getShiftKey() get() = getShiftKey()
+68 -69
View File
@@ -20,121 +20,121 @@ import org.w3c.dom.*
import org.xml.sax.InputSource import org.xml.sax.InputSource
// JavaScript style properties - TODO could auto-generate these // JavaScript style properties - TODO could auto-generate these
val Node.nodeName: String public val Node.nodeName: String
get() = getNodeName() ?: "" get() = getNodeName() ?: ""
val Node.nodeValue: String public val Node.nodeValue: String
get() = getNodeValue() ?: "" get() = getNodeValue() ?: ""
val Node.nodeType: Short public val Node.nodeType: Short
get() = getNodeType() get() = getNodeType()
val Node.parentNode: Node? public val Node.parentNode: Node?
get() = getParentNode() get() = getParentNode()
val Node.childNodes: NodeList public val Node.childNodes: NodeList
get() = getChildNodes()!! get() = getChildNodes()!!
val Node.firstChild: Node? public val Node.firstChild: Node?
get() = getFirstChild() get() = getFirstChild()
val Node.lastChild: Node? public val Node.lastChild: Node?
get() = getLastChild() get() = getLastChild()
val Node.nextSibling: Node? public val Node.nextSibling: Node?
get() = getNextSibling() get() = getNextSibling()
val Node.previousSibling: Node? public val Node.previousSibling: Node?
get() = getPreviousSibling() get() = getPreviousSibling()
val Node.attributes: NamedNodeMap? public val Node.attributes: NamedNodeMap?
get() = getAttributes() get() = getAttributes()
val Node.ownerDocument: Document? public val Node.ownerDocument: Document?
get() = getOwnerDocument() get() = getOwnerDocument()
val Document.documentElement: Element? public val Document.documentElement: Element?
get() = this.getDocumentElement() get() = this.getDocumentElement()
val Node.namespaceURI: String public val Node.namespaceURI: String
get() = getNamespaceURI() ?: "" get() = getNamespaceURI() ?: ""
val Node.prefix: String public val Node.prefix: String
get() = getPrefix() ?: "" get() = getPrefix() ?: ""
val Node.localName: String public val Node.localName: String
get() = getLocalName() ?: "" get() = getLocalName() ?: ""
val Node.baseURI: String public val Node.baseURI: String
get() = getBaseURI() ?: "" get() = getBaseURI() ?: ""
var Node.textContent: String public var Node.textContent: String
get() = getTextContent() ?: "" get() = getTextContent() ?: ""
set(value) { set(value) {
setTextContent(value) setTextContent(value)
} }
val DOMStringList.length: Int public val DOMStringList.length: Int
get() = this.getLength() get() = this.getLength()
val NameList.length: Int public val NameList.length: Int
get() = this.getLength() get() = this.getLength()
val DOMImplementationList.length: Int public val DOMImplementationList.length: Int
get() = this.getLength() get() = this.getLength()
val NodeList.length: Int public val NodeList.length: Int
get() = this.getLength() get() = this.getLength()
val CharacterData.length: Int public val CharacterData.length: Int
get() = this.getLength() get() = this.getLength()
val NamedNodeMap.length: Int public val NamedNodeMap.length: Int
get() = this.getLength() get() = this.getLength()
/** /**
* Returns the HTML representation of the node * Returns the HTML representation of the node
*/ */
public val Node.outerHTML: String public val Node.outerHTML: String
get() = toXmlString() get() = toXmlString()
/** /**
* Returns the HTML representation of the node * Returns the HTML representation of the node
*/ */
public val Node.innerHTML: String public val Node.innerHTML: String
get() = childNodes.outerHTML get() = childNodes.outerHTML
/** /**
* Returns the HTML representation of the nodes * Returns the HTML representation of the nodes
*/ */
public val NodeList.outerHTML: String public val NodeList.outerHTML: String
get() = toList().map { it.innerHTML }.join("") get() = toList().map { it.innerHTML }.join("")
/** Returns an [[Iterator]] of all the next [[Element]] siblings */ /** Returns an [[Iterator]] of all the next [[Element]] siblings */
fun Node.nextElements(): List<Element> = nextSiblings().filterIsInstance<Node, Element>(javaClass<Element>()) public fun Node.nextElements(): List<Element> = nextSiblings().filterIsInstance<Node, Element>(javaClass<Element>())
/** Returns an [[Iterator]] of all the previous [[Element]] siblings */ /** Returns an [[Iterator]] of all the previous [[Element]] siblings */
fun Node.previousElements(): List<Element> = previousSiblings().filterIsInstance<Node, Element>(javaClass<Element>()) public fun Node.previousElements(): List<Element> = previousSiblings().filterIsInstance<Node, Element>(javaClass<Element>())
var Element.classSet : MutableSet<String> public var Element.classSet: MutableSet<String>
get() { get() {
val answer = LinkedHashSet<String>() val answer = LinkedHashSet<String>()
val array = this.classes.split("""\s""") val array = this.classes.split("""\s""")
for (s in array) { for (s in array) {
if (s.size > 0) { if (s.size > 0) {
answer.add(s) answer.add(s)
}
} }
return answer
}
set(value) {
this.classes = value.join(" ")
} }
return answer
}
set(value) {
this.classes = value.join(" ")
}
/** Adds the given CSS class to this element's 'class' attribute */ /** Adds the given CSS class to this element's 'class' attribute */
fun Element.addClass(cssClass: String): Boolean { public fun Element.addClass(cssClass: String): Boolean {
val classSet = this.classSet val classSet = this.classSet
val answer = classSet.add(cssClass) val answer = classSet.add(cssClass)
if (answer) { if (answer) {
@@ -144,7 +144,7 @@ fun Element.addClass(cssClass: String): Boolean {
} }
/** Removes the given CSS class to this element's 'class' attribute */ /** Removes the given CSS class to this element's 'class' attribute */
fun Element.removeClass(cssClass: String): Boolean { public fun Element.removeClass(cssClass: String): Boolean {
val classSet = this.classSet val classSet = this.classSet
val answer = classSet.remove(cssClass) val answer = classSet.remove(cssClass)
if (answer) { if (answer) {
@@ -154,7 +154,6 @@ fun Element.removeClass(cssClass: String): Boolean {
} }
/** Creates a new document with the given document builder*/ /** Creates a new document with the given document builder*/
public fun createDocument(builder: DocumentBuilder): Document { public fun createDocument(builder: DocumentBuilder): Document {
return builder.newDocument()!! return builder.newDocument()!!
+22 -21
View File
@@ -23,40 +23,41 @@ public fun File.recurse(block: (File) -> Unit): Unit {
/** /**
* Returns this if the file is a directory or the parent if its a file inside a directory * Returns this if the file is a directory or the parent if its a file inside a directory
*/ */
val File.directory: File public val File.directory: File
get() = if (this.isDirectory()) this else this.getParentFile()!! get() = if (this.isDirectory()) this else this.getParentFile()!!
/** /**
* Returns the canonical path of the file * Returns the canonical path of the file
*/ */
val File.canonicalPath: String public val File.canonicalPath: String
get() = getCanonicalPath() get() = getCanonicalPath()
/** /**
* Returns the file name or "" for an empty name * Returns the file name or "" for an empty name
*/ */
val File.name: String public val File.name: String
get() = getName() get() = getName()
/** /**
* Returns the file path or "" for an empty name * Returns the file path or "" for an empty name
*/ */
val File.path: String public val File.path: String
get() = getPath() get() = getPath()
/** /**
* Returns true if the file ends with the given extension * Returns true if the file ends with the given extension
*/ */
val File.extension: String public val File.extension: String
get() { get() {
val text = this.name val text = this.name
val idx = text.lastIndexOf('.') val idx = text.lastIndexOf('.')
return if (idx >= 0) { return if (idx >= 0) {
text.substring(idx + 1) text.substring(idx + 1)
} else { }
"" else {
""
}
} }
}
/** /**
* Returns true if the given file is in the same directory or a descendant directory * Returns true if the given file is in the same directory or a descendant directory
@@ -168,7 +169,7 @@ public fun File.copyTo(file: File, bufferSize: Int = defaultBufferSize): Long {
* *
* You can use this function for huge files * You can use this function for huge files
*/ */
fun File.forEachBlock(closure : (ByteArray, Int) -> Unit) : Unit { public fun File.forEachBlock(closure: (ByteArray, Int) -> Unit): Unit {
val arr = ByteArray(4096) val arr = ByteArray(4096)
val fis = FileInputStream(this) val fis = FileInputStream(this)
@@ -191,7 +192,7 @@ fun File.forEachBlock(closure : (ByteArray, Int) -> Unit) : Unit {
* *
* You may use this function on huge files * You may use this function on huge files
*/ */
fun File.forEachLine (charset : String = "UTF-8", closure : (line : String) -> Unit) : Unit { public fun File.forEachLine(charset: String = "UTF-8", closure: (line: String) -> Unit): Unit {
val reader = BufferedReader(InputStreamReader(FileInputStream(this), charset)) val reader = BufferedReader(InputStreamReader(FileInputStream(this), charset))
try { try {
reader.forEachLine(closure) reader.forEachLine(closure)
@@ -205,7 +206,7 @@ fun File.forEachLine (charset : String = "UTF-8", closure : (line : String) -> U
* *
* Do not use this function for huge files. * Do not use this function for huge files.
*/ */
fun File.readLines(charset : String = "UTF-8") : List<String> { public fun File.readLines(charset: String = "UTF-8"): List<String> {
val rs = ArrayList<String>() val rs = ArrayList<String>()
this.forEachLine(charset) { (line : String) : Unit -> this.forEachLine(charset) { (line : String) : Unit ->
@@ -218,7 +219,7 @@ fun File.readLines(charset : String = "UTF-8") : List<String> {
/** /**
* Returns an array of files and directories in the directory that satisfy the specified filter. * Returns an array of files and directories in the directory that satisfy the specified filter.
*/ */
fun File.listFiles(filter : (file : File) -> Boolean) : Array<File>? = listFiles( public fun File.listFiles(filter: (file: File) -> Boolean): Array<File>? = listFiles(
object : FileFilter { object : FileFilter {
override fun accept(file: File) = filter(file) override fun accept(file: File) = filter(file)
} }
+1 -1
View File
@@ -215,7 +215,7 @@ public fun BufferedReader.lines(): Stream<String> = LinesStream(this)
deprecated("Use lines() function which returns Stream<String>") deprecated("Use lines() function which returns Stream<String>")
public fun BufferedReader.lineIterator(): Iterator<String> = lines().iterator() public fun BufferedReader.lineIterator(): Iterator<String> = lines().iterator()
class LinesStream(val reader: BufferedReader) : Stream<String> { private class LinesStream(private val reader: BufferedReader) : Stream<String> {
override fun iterator(): Iterator<String> { override fun iterator(): Iterator<String> {
return object : Iterator<String> { return object : Iterator<String> {
private var nextValue: String? = null private var nextValue: String? = null
@@ -2,6 +2,6 @@ package kotlin.modules
import java.util.ArrayList import java.util.ArrayList
object AllModules : ThreadLocal<ArrayList<Module>>() { public object AllModules : ThreadLocal<ArrayList<Module>>() {
override fun initialValue() = ArrayList<Module>() override fun initialValue() = ArrayList<Module>()
} }
@@ -8,38 +8,38 @@ public fun module(name: String, outputDir: String, callback: ModuleBuilder.() ->
AllModules.get()?.add(builder) AllModules.get()?.add(builder)
} }
class SourcesBuilder(val parent: ModuleBuilder) { public class SourcesBuilder(private val parent: ModuleBuilder) {
public fun plusAssign(pattern: String) { public fun plusAssign(pattern: String) {
parent.addSourceFiles(pattern) parent.addSourceFiles(pattern)
} }
} }
class ClasspathBuilder(val parent: ModuleBuilder) { public class ClasspathBuilder(private val parent: ModuleBuilder) {
public fun plusAssign(name: String) { public fun plusAssign(name: String) {
parent.addClasspathEntry(name) parent.addClasspathEntry(name)
} }
} }
class AnnotationsPathBuilder(val parent: ModuleBuilder) { public class AnnotationsPathBuilder(private val parent: ModuleBuilder) {
public fun plusAssign(name: String) { public fun plusAssign(name: String) {
parent.addAnnotationsPathEntry(name) parent.addAnnotationsPathEntry(name)
} }
} }
open class ModuleBuilder(val name: String, val outputDir: String): Module { public open class ModuleBuilder(private val name: String, private val outputDir: String) : Module {
// http://youtrack.jetbrains.net/issue/KT-904 // http://youtrack.jetbrains.net/issue/KT-904
private val sourceFiles0 = ArrayList<String>() private val sourceFiles0 = ArrayList<String>()
private val classpathRoots0 = ArrayList<String>() private val classpathRoots0 = ArrayList<String>()
private val annotationsRoots0 = ArrayList<String>() private val annotationsRoots0 = ArrayList<String>()
val sources: SourcesBuilder public val sources: SourcesBuilder
get() = SourcesBuilder(this) get() = SourcesBuilder(this)
val classpath: ClasspathBuilder public val classpath: ClasspathBuilder
get() = ClasspathBuilder(this) get() = ClasspathBuilder(this)
val annotationsPath: AnnotationsPathBuilder public val annotationsPath: AnnotationsPathBuilder
get() = AnnotationsPathBuilder(this) get() = AnnotationsPathBuilder(this)
public fun addSourceFiles(pattern: String) { public fun addSourceFiles(pattern: String) {
sourceFiles0.add(pattern) sourceFiles0.add(pattern)
@@ -16,4 +16,4 @@
package kotlin.platform package kotlin.platform
public annotation class platformName(val name: String) public annotation class platformName(public val name: String)
@@ -50,7 +50,9 @@ private class NotNullVar<T: Any>() : ReadWriteProperty<Any?, T> {
} }
} }
class ObservableProperty<T>(initialValue: T, val onChange: (name: PropertyMetadata, oldValue: T, newValue: T) -> Boolean): ReadWriteProperty<Any?, T> { public class ObservableProperty<T>(
initialValue: T, private val onChange: (name: PropertyMetadata, oldValue: T, newValue: T) -> Boolean
) : ReadWriteProperty<Any?, T> {
private var value = initialValue private var value = initialValue
public override fun get(thisRef: Any?, desc: PropertyMetadata): T { public override fun get(thisRef: Any?, desc: PropertyMetadata): T {
@@ -3,7 +3,12 @@ package kotlin.properties
import java.util.HashMap import java.util.HashMap
import java.util.ArrayList import java.util.ArrayList
public class ChangeEvent(val source: Any, val name: String, val oldValue: Any?, val newValue: Any?) { public class ChangeEvent(
public val source: Any,
public val name: String,
public val oldValue: Any?,
public val newValue: Any?
) {
var propogationId: Any? = null var propogationId: Any? = null
override fun toString(): String = "ChangeEvent($name, $oldValue, $newValue)" override fun toString(): String = "ChangeEvent($name, $oldValue, $newValue)"
@@ -10,21 +10,21 @@ import java.util.Date
// TODO this class should move into the runtime // TODO this class should move into the runtime
// in kotlin.StringTemplate // in kotlin.StringTemplate
class StringTemplate(val values : Array<Any?>) { public class StringTemplate(private val values: Array<Any?>) {
/** /**
* Converts the template into a String * Converts the template into a String
*/ */
override fun toString() : String { override fun toString(): String {
val out = StringBuilder() val out = StringBuilder()
forEach{ out.append(it) } forEach { out.append(it) }
return out.toString() return out.toString()
} }
/** /**
* Performs the given function on each value in the collection * Performs the given function on each value in the collection
*/ */
public fun forEach(fn : (Any?) -> Unit) : Unit { public fun forEach(fn: (Any?) -> Unit): Unit {
for (v in values) { for (v in values) {
fn(v) fn(v)
} }
@@ -38,7 +38,7 @@ class StringTemplate(val values : Array<Any?>) {
* *
* See [[HtmlFormatter] and [[LocaleFormatter] respectively. * See [[HtmlFormatter] and [[LocaleFormatter] respectively.
*/ */
public fun StringTemplate.toString(formatter : Formatter) : String { public fun StringTemplate.toString(formatter: Formatter): String {
val buffer = StringBuilder() val buffer = StringBuilder()
append(buffer, formatter) append(buffer, formatter)
return buffer.toString() return buffer.toString()
@@ -48,7 +48,7 @@ public fun StringTemplate.toString(formatter : Formatter) : String {
* Appends the text representation of this string template to the given output * Appends the text representation of this string template to the given output
* using the supplied formatter * using the supplied formatter
*/ */
public fun StringTemplate.append(out : Appendable, formatter : Formatter) : Unit { public fun StringTemplate.append(out: Appendable, formatter: Formatter): Unit {
var constantText = true var constantText = true
this.forEach { this.forEach {
if (constantText) { if (constantText) {
@@ -69,12 +69,12 @@ public fun StringTemplate.append(out : Appendable, formatter : Formatter) : Unit
* Converts this string template to internationalised text using the supplied * Converts this string template to internationalised text using the supplied
* [[LocaleFormatter]] * [[LocaleFormatter]]
*/ */
public fun StringTemplate.toLocale(formatter : LocaleFormatter = LocaleFormatter()) : String = toString(formatter) public fun StringTemplate.toLocale(formatter: LocaleFormatter = LocaleFormatter()): String = toString(formatter)
/** /**
* Converts this string template to HTML text * Converts this string template to HTML text
*/ */
public fun StringTemplate.toHtml(formatter : HtmlFormatter = HtmlFormatter()) : String = toString(formatter) public fun StringTemplate.toHtml(formatter: HtmlFormatter = HtmlFormatter()): String = toString(formatter)
/** /**
* Represents a formatter and encoder of values in a [[StringTemplate]] which understands * Represents a formatter and encoder of values in a [[StringTemplate]] which understands
@@ -82,7 +82,7 @@ public fun StringTemplate.toHtml(formatter : HtmlFormatter = HtmlFormatter()) :
* to escape particular characters in different output formats such as [[HtmlFormatter] * to escape particular characters in different output formats such as [[HtmlFormatter]
*/ */
public trait Formatter { public trait Formatter {
public fun format(buffer : Appendable, value : Any?) : Unit public fun format(buffer: Appendable, value: Any?): Unit
} }
/** /**
@@ -91,11 +91,11 @@ public trait Formatter {
*/ */
public open class ToStringFormatter : Formatter { public open class ToStringFormatter : Formatter {
var nullString : String = "null" private val nullString: String = "null"
override fun toString() : String = "ToStringFormatter" override fun toString(): String = "ToStringFormatter"
public override fun format(out : Appendable, value : Any?) { public override fun format(out: Appendable, value: Any?) {
if (value == null) { if (value == null) {
format(out, nullString) format(out, nullString)
} else if (value is StringTemplate) { } else if (value is StringTemplate) {
@@ -109,25 +109,25 @@ public open class ToStringFormatter : Formatter {
* Formats the given string allowing derived classes to override this method * Formats the given string allowing derived classes to override this method
* to escape strings with special characters such as for HTML * to escape strings with special characters such as for HTML
*/ */
public open fun format(out : Appendable, text : String) : Unit { public open fun format(out: Appendable, text: String): Unit {
out.append(text) out.append(text)
} }
} }
public val defaultLocale : Locale = Locale.getDefault() public val defaultLocale: Locale = Locale.getDefault()
/** /**
* Formats values using a given [[Locale]] for internationalisation * Formats values using a given [[Locale]] for internationalisation
*/ */
public open class LocaleFormatter(val locale : Locale = defaultLocale) : ToStringFormatter() { public open class LocaleFormatter(protected val locale: Locale = defaultLocale) : ToStringFormatter() {
override fun toString() : String = "LocaleFormatter{$locale}" override fun toString(): String = "LocaleFormatter{$locale}"
public var numberFormat : NumberFormat = NumberFormat.getInstance(locale)!! public var numberFormat: NumberFormat = NumberFormat.getInstance(locale)!!
public var dateFormat : DateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale)!! public var dateFormat: DateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale)!!
public override fun format(out : Appendable, value : Any?) { public override fun format(out: Appendable, value: Any?) {
if (value is Number) { if (value is Number) {
format(out, format(value)) format(out, format(value))
} else if (value is Date) { } else if (value is Date) {
@@ -137,11 +137,11 @@ public open class LocaleFormatter(val locale : Locale = defaultLocale) : ToStrin
} }
} }
public fun format(number : Number) : String { public fun format(number: Number): String {
return numberFormat.format(number) ?: "" return numberFormat.format(number) ?: ""
} }
public fun format(date : Date) : String { public fun format(date: Date): String {
return dateFormat.format(date) ?: "" return dateFormat.format(date) ?: ""
} }
} }
@@ -149,11 +149,11 @@ public open class LocaleFormatter(val locale : Locale = defaultLocale) : ToStrin
/** /**
* Formats values for HTML encoding, escaping special characters in HTML. * Formats values for HTML encoding, escaping special characters in HTML.
*/ */
public class HtmlFormatter(locale : Locale = defaultLocale) : LocaleFormatter(locale) { public class HtmlFormatter(locale: Locale = defaultLocale) : LocaleFormatter(locale) {
override fun toString() : String = "HtmlFormatter{$locale}" override fun toString(): String = "HtmlFormatter{$locale}"
public override fun format(out : Appendable, value : Any?) { public override fun format(out: Appendable, value: Any?) {
if (value is Node) { if (value is Node) {
out.append(value.toXmlString()) out.append(value.toXmlString())
} else { } else {
@@ -161,7 +161,7 @@ public class HtmlFormatter(locale : Locale = defaultLocale) : LocaleFormatter(lo
} }
} }
public override fun format(buffer : Appendable, text : String) : Unit { public override fun format(buffer: Appendable, text: String): Unit {
for (c in text) { for (c in text) {
if (c == '<') buffer.append("&lt;") if (c == '<') buffer.append("&lt;")
else if (c == '>') buffer.append("&gt;") else if (c == '>') buffer.append("&gt;")
+1 -1
View File
@@ -53,7 +53,7 @@ public var asserter: Asserter
/** /**
* Default implementation to avoid dependency on JUnit or TestNG * Default implementation to avoid dependency on JUnit or TestNG
*/ */
class DefaultAsserter() : Asserter { private class DefaultAsserter() : Asserter {
public override fun assertTrue(message : String, actual : Boolean) { public override fun assertTrue(message : String, actual : Boolean) {
if (!actual) { if (!actual) {
@@ -3,7 +3,7 @@ package kotlin
import kotlin.properties.* import kotlin.properties.*
/** Line separator for current system. */ /** Line separator for current system. */
val LINE_SEPARATOR: String by Delegates.lazy { System.getProperty("line.separator")!! } private val LINE_SEPARATOR: String by Delegates.lazy { System.getProperty("line.separator")!! }
/** Appends line separator to Appendable. */ /** Appends line separator to Appendable. */
public fun Appendable.appendln(): Appendable = append(LINE_SEPARATOR) public fun Appendable.appendln(): Appendable = append(LINE_SEPARATOR)
@@ -174,7 +174,7 @@ public fun String.toRegex(flags: Int = 0): java.util.regex.Pattern {
return java.util.regex.Pattern.compile(this, flags) return java.util.regex.Pattern.compile(this, flags)
} }
val String.reader: StringReader public val String.reader: StringReader
get() = StringReader(this) get() = StringReader(this)
/** /**
+52
View File
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-project</artifactId>
<version>0.1-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>kotlin-stdlib-validator</artifactId>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-compiler</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-runtime</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<testSourceDirectory>src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${project.version}</version>
<executions>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,144 @@
/*
* Copyright 2010-2014 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.
*/
import org.junit.Test
import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment
import com.intellij.openapi.util.Disposer
import org.jetbrains.jet.config.CompilerConfiguration
import org.jetbrains.jet.config.CommonConfigurationKeys
import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM
import org.jetbrains.jet.lang.resolve.BindingTraceContext
import org.jetbrains.jet.lang.resolve.name.Name
import org.jetbrains.jet.lang.resolve.name.FqName
import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor
import org.jetbrains.jet.lang.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.jet.lang.descriptors.Visibilities
import org.jetbrains.jet.lang.resolve.DescriptorToSourceUtils
import org.jetbrains.jet.lang.descriptors.ClassDescriptor
import org.jetbrains.jet.lang.descriptors.PackageViewDescriptor
import java.util.ArrayList
import org.jetbrains.jet.lang.psi.JetFile
import org.jetbrains.jet.renderer.DescriptorRenderer
import kotlin.test.fail
import org.jetbrains.jet.cli.jvm.JVMConfigurationKeys
import org.jetbrains.jet.utils.PathUtil
import org.jetbrains.jet.lang.resolve.DescriptorUtils
import org.jetbrains.jet.lang.descriptors.ModuleDescriptor
import org.junit.Assert
import java.util.HashSet
// this list is not designed to contain all packages, it is need for sanity check in case test code breaks
private val PACKAGES_SHOULD_BE_VALIDATED = listOf("kotlin", "kotlin.concurrent", "kotlin.jvm") map { FqName(it) }
class NoInternalVisibilityInStdLibTest {
private class OutputSink {
private val internalDescriptors = ArrayList<DeclarationDescriptor>()
private val validatedPackages = HashSet<FqName>()
fun reportInternalVisibility(descriptor: DeclarationDescriptor) {
internalDescriptors.add(descriptor)
}
fun reportValidatedPackage(packageFqName: FqName) {
validatedPackages.add(packageFqName)
}
fun reportErrors() {
println("Validated packages: ")
validatedPackages.forEach { println(" $it") }
Assert.assertTrue(
"Some of the expected stdlib packages were not validated, check code of the test",
validatedPackages.containsAll(PACKAGES_SHOULD_BE_VALIDATED)
)
if (internalDescriptors.isEmpty()) return
val byFile = internalDescriptors.groupBy { descriptor ->
DescriptorToSourceUtils.descriptorToDeclarations(descriptor).firstOrNull()?.getContainingFile() as JetFile
}
val byPackage = byFile.keySet().groupBy { it.getPackageFqName() }
val message = StringBuilder {
appendln("There are ${internalDescriptors.size} descriptors that have internal visibility:")
for ((packageFqName, files) in byPackage) {
appendln("In package ${packageFqName}:")
for (file in files) {
appendln("In file ${file.getName()}")
appendln("--------------")
val descriptors = byFile[file]!!
descriptors.forEach {
descriptor ->
appendln("* " + DescriptorRenderer.SHORT_NAMES_IN_TYPES.render(descriptor))
}
appendln("--------------")
}
appendln()
}
}.toString()
fail(message)
}
}
Test fun testNoInternalVisibility() {
val disposable = Disposer.newDisposable()
val module = try {
val configuration = CompilerConfiguration()
configuration.add(CommonConfigurationKeys.SOURCE_ROOTS_KEY, "../src/kotlin")
configuration.addAll(JVMConfigurationKeys.CLASSPATH_KEY, PathUtil.getJdkClassesRoots())
val environment = JetCoreEnvironment.createForProduction(disposable, configuration)
AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(
environment.getProject(),
environment.getSourceFiles(),
BindingTraceContext(),
{ true },
AnalyzerFacadeForJVM.createJavaModule("<module for validating std lib>"),
null,
null
).getModuleDescriptor()
}
finally {
Disposer.dispose(disposable)
}
val kotlinPackage = module.getPackage(FqName("kotlin"))!!
val sink = OutputSink()
validateDescriptor(module, kotlinPackage, sink)
sink.reportErrors()
}
private fun validateDescriptor(module: ModuleDescriptor, descriptor: DeclarationDescriptor, sink: OutputSink) {
if (DescriptorUtils.getContainingModule(descriptor) != module) return
if (descriptor is DeclarationDescriptorWithVisibility) {
if (descriptor.getVisibility() == Visibilities.INTERNAL) {
sink.reportInternalVisibility(descriptor)
}
}
when (descriptor) {
is ClassDescriptor -> descriptor.getDefaultType().getMemberScope().getAllDescriptors().forEach {
validateDescriptor(module, it, sink)
}
is PackageViewDescriptor -> {
sink.reportValidatedPackage(DescriptorUtils.getFqName(descriptor).toSafe())
descriptor.getMemberScope().getAllDescriptors().forEach {
validateDescriptor(module, it, sink)
}
}
}
}
}