Experimental framework for inline constants

This commit is contained in:
Valentin Kipyatkov
2015-06-09 19:09:26 +03:00
parent 657abffea2
commit 76e501c7ea
2 changed files with 22 additions and 2 deletions
@@ -16,8 +16,10 @@
package org.jetbrains.kotlin.utils.addToStdlib
import java.lang.reflect.Modifier
import java.util.Collections
import java.util.NoSuchElementException
import java.util.concurrent.ConcurrentHashMap
public fun <T: Any> T?.singletonOrEmptyList(): List<T> = if (this != null) Collections.singletonList(this) else Collections.emptyList()
@@ -75,4 +77,21 @@ public fun <T> streamOfLazyValues(vararg elements: () -> T): Stream<T> = element
public fun <T1, T2> Pair<T1, T2>.swap(): Pair<T2, T1> = Pair(second, first)
public fun <T: Any> T.check(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
public fun <T: Any> T.check(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
public fun <T : Any> constant(calculator: () -> T): T {
val cached = constantMap[calculator]
if (cached != null) return cached as T
// safety check
val fields = calculator.javaClass.getDeclaredFields().filter { it.getModifiers().and(Modifier.STATIC) == 0 }
assert(fields.isEmpty()) {
"No fields in the passed lambda expected but ${fields.joinToString()} found"
}
val value = calculator()
constantMap[calculator] = value
return value
}
private val constantMap = ConcurrentHashMap<Function0<*>, Any>()
@@ -43,6 +43,7 @@ import org.jetbrains.kotlin.renderer.RenderingFormat
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.source.PsiSourceElement
import org.jetbrains.kotlin.utils.addToStdlib.constant
public class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
@@ -140,7 +141,7 @@ public class KotlinQuickDocumentationProvider : AbstractDocumentationProvider()
private fun mixKotlinToJava(declarationDescriptor: DeclarationDescriptor, element: PsiElement, originalElement: PsiElement?): String? {
val originalInfo = JavaDocumentationProvider().getQuickNavigateInfo(element, originalElement)
if (originalInfo != null) {
val renderedDecl = MIX_KOTLIN_TO_JAVA_RENDERER.render(declarationDescriptor)
val renderedDecl = constant { DESCRIPTOR_RENDERER.withOptions { withDefinedIn = false } }.render(declarationDescriptor)
return renderedDecl + "<br/>Java declaration:<br/>" + originalInfo
}