compiler: cleanup 'public', property access syntax

This commit is contained in:
Dmitry Jemerov
2016-01-07 17:57:35 +01:00
parent b72ea1ff07
commit 117a0d8b7b
488 changed files with 3147 additions and 3287 deletions
@@ -62,5 +62,5 @@ object LightClassTestCommon {
// Actual text for light class is generated with ClsElementImpl.appendMirrorText() that can find empty DefaultImpl inner class in stubs
// for all interfaces. This inner class can't be used in Java as it generally is not seen from light classes built from Kotlin sources.
// It is also omitted during classes generation in backend so it also absent in light classes built from compiled code.
public fun removeEmptyDefaultImpls(text: String) : String = text.replace("\n final class DefaultImpls {\n }\n", "")
fun removeEmptyDefaultImpls(text: String) : String = text.replace("\n final class DefaultImpls {\n }\n", "")
}
@@ -28,13 +28,13 @@ import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
import java.util.*
public abstract class AbstractPseudoValueTest : AbstractPseudocodeTest() {
abstract class AbstractPseudoValueTest : AbstractPseudocodeTest() {
override fun dumpInstructions(pseudocode: PseudocodeImpl, out: StringBuilder, bindingContext: BindingContext) {
val expectedTypePredicateMap = HashMap<PseudoValue, TypePredicate>()
fun getElementToValueMap(pseudocode: PseudocodeImpl): Map<KtElement, PseudoValue> {
val elementToValues = LinkedHashMap<KtElement, PseudoValue>()
pseudocode.getCorrespondingElement().accept(object : KtTreeVisitorVoid() {
pseudocode.correspondingElement.accept(object : KtTreeVisitorVoid() {
override fun visitKtElement(element: KtElement) {
super.visitKtElement(element)
@@ -48,7 +48,7 @@ public abstract class AbstractPseudoValueTest : AbstractPseudocodeTest() {
}
fun elementText(element: KtElement?): String =
element?.getText()?.replace("\\s+".toRegex(), " ") ?: ""
element?.text?.replace("\\s+".toRegex(), " ") ?: ""
fun valueDecl(value: PseudoValue): String {
val typePredicate = expectedTypePredicateMap.getOrPut(value) {
@@ -65,7 +65,7 @@ public abstract class AbstractPseudoValueTest : AbstractPseudocodeTest() {
}
val elementToValues = getElementToValueMap(pseudocode)
val unboundValues = pseudocode.getInstructions()
val unboundValues = pseudocode.instructions
.mapNotNull { (it as? InstructionWithValue)?.outputValue }
.filter { it.element == null }
.sortedBy { it.debugName }
@@ -24,17 +24,17 @@ import org.jetbrains.kotlin.js.facade.MainCallParameters
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.BindingTrace
public abstract class AbstractDiagnosticsTestWithJsStdLibAndBackendCompilation : AbstractDiagnosticsTestWithJsStdLib() {
abstract class AbstractDiagnosticsTestWithJsStdLibAndBackendCompilation : AbstractDiagnosticsTestWithJsStdLib() {
override fun analyzeModuleContents(
moduleContext: ModuleContext,
jetFiles: MutableList<KtFile>,
moduleTrace: BindingTrace
) {
val analysisResult = TopDownAnalyzerFacadeForJS.analyzeFilesWithGivenTrace(jetFiles, moduleTrace, moduleContext, getConfig())
val diagnostics = analysisResult.bindingTrace.getBindingContext().getDiagnostics()
val analysisResult = TopDownAnalyzerFacadeForJS.analyzeFilesWithGivenTrace(jetFiles, moduleTrace, moduleContext, config)
val diagnostics = analysisResult.bindingTrace.bindingContext.diagnostics
if (!hasError(diagnostics)) {
val translator = K2JSTranslator(getConfig())
val translator = K2JSTranslator(config)
translator.translate(jetFiles, MainCallParameters.noCall(), analysisResult)
}
}
@@ -54,12 +54,12 @@ class LazyOperationsLog(
private val records = ArrayList<Record>()
public val addRecordFunction: (lambda: Any, LoggingStorageManager.CallData) -> Unit = {
val addRecordFunction: (lambda: Any, LoggingStorageManager.CallData) -> Unit = {
lambda, data ->
records.add(Record(lambda, data))
}
public fun getText(): String {
fun getText(): String {
val groupedByOwner = records.groupByTo(IdentityHashMap()) {
it.data.fieldOwner
}.map { Pair(it.key, it.value) }
@@ -109,7 +109,7 @@ class LazyOperationsLog(
val data = record.data
val sb = StringBuilder()
sb.append(data.field?.getName() ?: "in ${data.lambdaCreatedIn.getDeclarationName()}")
sb.append(data.field?.name ?: "in ${data.lambdaCreatedIn.getDeclarationName()}")
if (!data.arguments.isEmpty()) {
data.arguments.joinTo(sb, ", ", "(", ")") { render(it) }
@@ -135,23 +135,23 @@ class LazyOperationsLog(
val id = objectId(o)
val aClass = o.javaClass
sb.append(if (aClass.isAnonymousClass()) aClass.getName().substringAfterLast('.') else aClass.getSimpleName()).append("@$id")
sb.append(if (aClass.isAnonymousClass) aClass.name.substringAfterLast('.') else aClass.simpleName).append("@$id")
fun Any.appendQuoted() {
sb.append("['").append(this).append("']")
}
when {
o is Named -> o.getName().appendQuoted()
o.javaClass.getSimpleName() == "LazyJavaClassifierType" -> {
o is Named -> o.name.appendQuoted()
o.javaClass.simpleName == "LazyJavaClassifierType" -> {
val javaType = o.field<JavaTypeImpl<*>>("javaType")
javaType.getPsi().getPresentableText().appendQuoted()
javaType.psi.presentableText.appendQuoted()
}
o.javaClass.getSimpleName() == "LazyJavaClassTypeConstructor" -> {
o.javaClass.simpleName == "LazyJavaClassTypeConstructor" -> {
val javaClass = o.field<Any>("this\$0").field<JavaClassImpl>("jClass")
javaClass.getPsi().getName()!!.appendQuoted()
javaClass.psi.name!!.appendQuoted()
}
o.javaClass.getSimpleName() == "DeserializedType" -> {
o.javaClass.simpleName == "DeserializedType" -> {
val typeDeserializer = o.field<TypeDeserializer>("typeDeserializer")
val context = typeDeserializer.field<DeserializationContext>("c")
val typeProto = o.field<ProtoBuf.Type>("typeProto")
@@ -166,10 +166,10 @@ class LazyOperationsLog(
text.appendQuoted()
}
o is JavaNamedElement -> {
o.getName().appendQuoted()
o.name.appendQuoted()
}
o is JavaTypeImpl<*> -> {
o.getPsi().getPresentableText().appendQuoted()
o.psi.presentableText.appendQuoted()
}
o is Collection<*> -> {
if (o.isEmpty()) {
@@ -182,14 +182,14 @@ class LazyOperationsLog(
}
o is KotlinTypeImpl -> {
StringBuilder().apply {
append(o.getConstructor())
if (!o.getArguments().isEmpty()) {
append("<${o.getArguments().size}>")
append(o.constructor)
if (!o.arguments.isEmpty()) {
append("<${o.arguments.size}>")
}
}.appendQuoted()
}
o is ResolutionCandidate<*> -> DescriptorRenderer.COMPACT.render(o.getDescriptor()).appendQuoted()
o is ResolutionTaskHolder<*, *> -> o.field<BasicCallResolutionContext>("basicCallResolutionContext").call.getCallElement().getDebugText().appendQuoted()
o is ResolutionCandidate<*> -> DescriptorRenderer.COMPACT.render(o.descriptor).appendQuoted()
o is ResolutionTaskHolder<*, *> -> o.field<BasicCallResolutionContext>("basicCallResolutionContext").call.callElement.getDebugText().appendQuoted()
}
return sb.toString()
}
@@ -197,7 +197,7 @@ class LazyOperationsLog(
private fun <T> Any.field(name: String): T {
val field = this.javaClass.getDeclaredField(name)
field.setAccessible(true)
field.isAccessible = true
@Suppress("UNCHECKED_CAST")
return field.get(this) as T
}
@@ -212,7 +212,7 @@ private fun Printer.indent(body: Printer.() -> Unit): Printer {
private fun GenericDeclaration?.getDeclarationName(): String? {
return when (this) {
is Class<*> -> getName().substringAfterLast(".")
is Method -> getDeclaringClass().getDeclarationName() + "::" + getName() + "()"
is Method -> declaringClass.getDeclarationName() + "::" + name + "()"
is Constructor<*> -> getDeclaringClass().getDeclarationName() + "::" + getName() + "()"
else -> "<no name>"
}
@@ -21,11 +21,11 @@ import org.jetbrains.kotlin.storage.StorageManager
import java.lang.reflect.Field
import java.lang.reflect.GenericDeclaration
public class LoggingStorageManager(
class LoggingStorageManager(
private val delegate: StorageManager,
private val callHandler: (lambda: Any, call: LoggingStorageManager.CallData?) -> Unit) : ObservableStorageManager(delegate) {
public class CallData(
class CallData(
val fieldOwner: Any?,
val field: Field?,
val lambdaCreatedIn: GenericDeclaration?,
@@ -56,26 +56,26 @@ public class LoggingStorageManager(
private fun computeCallerData(lambda: Any, wrapper: Any, arguments: List<Any?>, result: Any?): CallData {
val lambdaClass = lambda.javaClass
val outerClass: Class<out Any?>? = lambdaClass.getEnclosingClass()
val outerClass: Class<out Any?>? = lambdaClass.enclosingClass
// fields named "this" or "this$0"
val referenceToOuter = lambdaClass.getAllDeclaredFields().firstOrNull {
field ->
field.getType() == outerClass && field.getName()!!.contains("this")
field.type == outerClass && field.name!!.contains("this")
}
referenceToOuter?.setAccessible(true)
referenceToOuter?.isAccessible = true
val outerInstance = referenceToOuter?.get(lambda)
fun Class<*>.findFunctionField(): Field? {
return this.getAllDeclaredFields().firstOrNull {
it.getType()?.getName()?.startsWith("kotlin.Function") ?: false
it.type?.name?.startsWith("kotlin.Function") ?: false
}
}
val containingField = if (outerInstance == null) null
else outerClass?.getAllDeclaredFields()?.firstOrNull {
field ->
field.setAccessible(true)
field.isAccessible = true
val value = field.get(outerInstance)
if (value == null) return@firstOrNull false
@@ -83,7 +83,7 @@ public class LoggingStorageManager(
val functionField = valueClass.findFunctionField()
if (functionField == null) return@firstOrNull false
functionField.setAccessible(true)
functionField.isAccessible = true
val functionValue = functionField.get(value)
functionValue == wrapper
}
@@ -91,7 +91,7 @@ public class LoggingStorageManager(
if (containingField == null) {
val wrappedLambdaField = lambdaClass.findFunctionField()
if (wrappedLambdaField != null) {
wrappedLambdaField.setAccessible(true)
wrappedLambdaField.isAccessible = true
val wrappedLambda = wrappedLambdaField.get(lambda)
return CallData(outerInstance, null, enclosingEntity(wrappedLambda.javaClass), arguments, result)
}
@@ -103,9 +103,9 @@ public class LoggingStorageManager(
}
private fun enclosingEntity(_class: Class<Any>): GenericDeclaration? {
val result = _class.getEnclosingConstructor()
?: _class.getEnclosingMethod()
?: _class.getEnclosingClass()
val result = _class.enclosingConstructor
?: _class.enclosingMethod
?: _class.enclosingClass
return result as GenericDeclaration?
}
@@ -115,9 +115,9 @@ public class LoggingStorageManager(
var c = this
while (true) {
result.addAll(c.getDeclaredFields().toList())
result.addAll(c.declaredFields.toList())
@Suppress("UNCHECKED_CAST")
val superClass = (c as Class<Any>).getSuperclass() as Class<Any>?
val superClass = (c as Class<Any>).superclass as Class<Any>?
if (superClass == null) break
if (c == superClass) break
c = superClass
@@ -30,8 +30,8 @@ import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
//Partial copy of CoreJavaFileManagerTest
public class KotlinCliJavaFileManagerTest : PsiTestCase() {
public fun testCommon() {
class KotlinCliJavaFileManagerTest : PsiTestCase() {
fun testCommon() {
val manager = configureManager("package foo;\n\n" + "public class TopLevel {\n" + "public class Inner {\n" + " public class Inner {}\n" + "}\n" + "\n" + "}", "TopLevel")
assertCanFind(manager, "foo", "TopLevel")
@@ -43,7 +43,7 @@ public class KotlinCliJavaFileManagerTest : PsiTestCase() {
assertCannotFind(manager, "foo", "TopLevel.Inner.Inner.Inner")
}
public fun testInnerClassesWithDollars() {
fun testInnerClassesWithDollars() {
val manager = configureManager("package foo;\n\n" + "public class TopLevel {\n" +
"public class I\$nner {" + " public class I\$nner{}" + " public class \$Inner{}" + " public class In\$ne\$r\${}" + " public class Inner\$\${}" + " public class \$\$\$\$\${}" + "}\n" + "public class Inner\$ {" + " public class I\$nner{}" + " public class \$Inner{}" + " public class In\$ne\$r\${}" + " public class Inner\$\${}" + " public class \$\$\$\$\${}" + "}\n" + "public class In\$ner\$\$ {" + " public class I\$nner{}" + " public class \$Inner{}" + " public class In\$ne\$r\${}" + " public class Inner\$\${}" + " public class \$\$\$\$\${}" + "}\n" + "\n" + "}", "TopLevel")
@@ -77,7 +77,7 @@ public class KotlinCliJavaFileManagerTest : PsiTestCase() {
assertCannotFind(manager, "foo", "TopLevel.In.ner\$\$.\$\$\$\$\$")
}
public fun testTopLevelClassesWithDollars() {
fun testTopLevelClassesWithDollars() {
val inTheMiddle = configureManager("package foo;\n\n public class Top\$Level {}", "Top\$Level")
assertCanFind(inTheMiddle, "foo", "Top\$Level")
@@ -92,7 +92,7 @@ public class KotlinCliJavaFileManagerTest : PsiTestCase() {
assertCanFind(twoBucks, "foo", "\$\$")
}
public fun testTopLevelClassWithDollarsAndInners() {
fun testTopLevelClassWithDollarsAndInners() {
val manager = configureManager("package foo;\n\n" + "public class Top\$Level\$\$ {\n" +
"public class I\$nner {" + " public class I\$nner{}" + " public class In\$ne\$r\${}" + " public class Inner\$\$\$\$\${}" + " public class \$Inner{}" + " public class \${}" + " public class \$\$\$\$\${}" + "}\n" + "public class Inner {" + " public class Inner{}" + "}\n" + "\n" + "}", "Top\$Level\$\$")
@@ -112,16 +112,16 @@ public class KotlinCliJavaFileManagerTest : PsiTestCase() {
assertCannotFind(manager, "foo", "Top.Level\$\$.I\$nner.\$\$\$\$\$")
}
public fun testDoNotThrowOnMalformedInput() {
fun testDoNotThrowOnMalformedInput() {
val fileWithEmptyName = configureManager("package foo;\n\n public class Top\$Level {}", "")
val allScope = GlobalSearchScope.allScope(getProject())
val allScope = GlobalSearchScope.allScope(project)
fileWithEmptyName.findClass("foo.", allScope)
fileWithEmptyName.findClass(".", allScope)
fileWithEmptyName.findClass("..", allScope)
fileWithEmptyName.findClass(".foo", allScope)
}
public fun testSeveralClassesInOneFile() {
fun testSeveralClassesInOneFile() {
val manager = configureManager("package foo;\n\n" + "public class One {}\n" + "class Two {}\n" + "class Three {}", "One")
assertCanFind(manager, "foo", "One")
@@ -131,10 +131,10 @@ public class KotlinCliJavaFileManagerTest : PsiTestCase() {
assertCannotFind(manager, "foo", "Three")
}
public fun testScopeCheck() {
fun testScopeCheck() {
val manager = configureManager("package foo;\n\n" + "public class Test {}\n", "Test")
TestCase.assertNotNull("Should find class in all scope", manager.findClass("foo.Test", GlobalSearchScope.allScope(getProject())))
TestCase.assertNotNull("Should find class in all scope", manager.findClass("foo.Test", GlobalSearchScope.allScope(project)))
TestCase.assertNull("Should not find class in empty scope", manager.findClass("foo.Test", GlobalSearchScope.EMPTY_SCOPE))
}
@@ -144,7 +144,7 @@ public class KotlinCliJavaFileManagerTest : PsiTestCase() {
val dir = myPsiManager.findDirectory(pkg)
TestCase.assertNotNull(dir)
dir!!
dir.add(PsiFileFactory.getInstance(getProject()).createFileFromText(className + ".java", JavaFileType.INSTANCE, text))
dir.add(PsiFileFactory.getInstance(project).createFileFromText(className + ".java", JavaFileType.INSTANCE, text))
val coreJavaFileManagerExt = KotlinCliJavaFileManagerImpl(myPsiManager)
coreJavaFileManagerExt.initIndex(JvmDependenciesIndex(listOf(JavaRoot(root, JavaRoot.RootType.SOURCE))))
coreJavaFileManagerExt.addToClasspath(root)
@@ -152,7 +152,7 @@ public class KotlinCliJavaFileManagerTest : PsiTestCase() {
}
private fun assertCanFind(manager: KotlinCliJavaFileManagerImpl, packageFQName: String, classFqName: String) {
val allScope = GlobalSearchScope.allScope(getProject())
val allScope = GlobalSearchScope.allScope(project)
val classId = ClassId(FqName(packageFQName), FqName(classFqName), false)
val stringRequest = classId.asSingleFqName().asString()
@@ -164,13 +164,13 @@ public class KotlinCliJavaFileManagerTest : PsiTestCase() {
TestCase.assertNotNull("Could not find: $stringRequest", foundByString)
TestCase.assertEquals(foundByClassId, foundByString)
TestCase.assertEquals("Found ${foundByClassId!!.getQualifiedName()} instead of $packageFQName", packageFQName + "." + classFqName,
foundByClassId.getQualifiedName())
TestCase.assertEquals("Found ${foundByClassId!!.qualifiedName} instead of $packageFQName", packageFQName + "." + classFqName,
foundByClassId.qualifiedName)
}
private fun assertCannotFind(manager: KotlinCliJavaFileManagerImpl, packageFQName: String, classFqName: String) {
val classId = ClassId(FqName(packageFQName), FqName(classFqName), false)
val foundClass = manager.findClass(classId, GlobalSearchScope.allScope(getProject()))
val foundClass = manager.findClass(classId, GlobalSearchScope.allScope(project))
TestCase.assertNull("Found, but shouldn't have: $classId", foundClass)
}
}
@@ -22,7 +22,7 @@ import java.io.File
import java.util.*
import java.util.regex.Pattern
public class CodeConformanceTest : TestCase() {
class CodeConformanceTest : TestCase() {
companion object {
private val JAVA_FILE_PATTERN = Pattern.compile(".+\\.java")
private val SOURCES_FILE_PATTERN = Pattern.compile("(.+\\.java|.+\\.kt|.+\\.js)")
@@ -43,7 +43,7 @@ public class CodeConformanceTest : TestCase() {
).map { File(it) }
}
public fun testParserCode() {
fun testParserCode() {
val pattern = Pattern.compile("assert.*?\\b[^_]at.*?$", Pattern.MULTILINE)
for (sourceFile in FileUtil.findFilesByMask(JAVA_FILE_PATTERN, File("compiler/frontend/src/org/jetbrains/kotlin/parsing"))) {
@@ -54,7 +54,7 @@ public class CodeConformanceTest : TestCase() {
}
}
public fun testNoBadSubstringsInProjectCode() {
fun testNoBadSubstringsInProjectCode() {
class TestData(val message: String, val filter: (String) -> Boolean) {
val result: MutableList<File> = ArrayList()
}
@@ -21,9 +21,9 @@ import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.org.objectweb.asm.*
import java.io.File
public abstract class AbstractBytecodeListingTest : CodegenTestCase() {
abstract class AbstractBytecodeListingTest : CodegenTestCase() {
public fun doTest(filename: String) {
fun doTest(filename: String) {
createEnvironmentWithMockJdkAndIdeaAnnotations(ConfigurationKind.ALL)
loadFileByFullPath(filename)
val ktFile = File(filename)
@@ -70,7 +70,7 @@ public abstract class AbstractBytecodeListingTest : CodegenTestCase() {
if ((access and Opcodes.ACC_STATIC) != 0) addModifier("static", list)
}
public val text: String
val text: String
get() = StringBuilder().apply {
append(classAnnotations.joinToString("\n", postfix = "\n"))
arrayListOf<String>().apply { handleModifiers(classAccess, this) }.forEach { append(it) }
@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.codegen
import com.intellij.testFramework.UsefulTestCase
import org.jetbrains.kotlin.test.ConfigurationKind
public class CustomBytecodeTextTest : AbstractBytecodeTextTest() {
class CustomBytecodeTextTest : AbstractBytecodeTextTest() {
fun testEnumMapping() {
createEnvironmentWithMockJdkAndIdeaAnnotations(ConfigurationKind.ALL)
myFiles = CodegenTestFiles.create("whenMappingOrder.kt", """
@@ -45,7 +45,7 @@ object InlineTestUtil {
val skipParameterChecking =
sourceFiles.asSequence().filter {
InTextDirectivesUtils.isDirectiveDefined(it.getText(), "NO_CHECK_LAMBDA_INLINING")
InTextDirectivesUtils.isDirectiveDefined(it.text, "NO_CHECK_LAMBDA_INLINING")
}.any()
if (!skipParameterChecking) {
@@ -105,7 +105,7 @@ object InlineTestUtil {
}
return object : MethodNode(Opcodes.ASM5, access, name, desc, signature, exceptions) {
public override fun visitMethodInsn(opcode: Int, owner: String, name: String, desc: String, itf: Boolean) {
override fun visitMethodInsn(opcode: Int, owner: String, name: String, desc: String, itf: Boolean) {
val methodCall = MethodInfo(owner, name, desc)
if (inlinedMethods.contains(methodCall)) {
val fromCall = MethodInfo(className, this.name, this.desc)
@@ -136,7 +136,7 @@ object InlineTestUtil {
cr.accept(object : ClassVisitorWithName() {
override fun visitMethod(access: Int, name: String, desc: String, signature: String?, exceptions: Array<String>?): MethodVisitor? {
JvmClassName.byInternalName(className).getFqNameForClassNameWithoutDollars()
JvmClassName.byInternalName(className).fqNameForClassNameWithoutDollars
val declaration = MethodInfo(className, name, desc)
//do not check anonymous object creation in inline functions and in package facades
if (declaration in inlinedMethods) {
@@ -146,7 +146,7 @@ object InlineTestUtil {
return object : MethodNode(Opcodes.ASM5, access, name, desc, signature, exceptions) {
private fun isInlineParameterLikeOwner(owner: String) = owner.contains("$") && !isTopLevelOrInnerOrPackageClass(owner, inlineInfo)
public override fun visitMethodInsn(opcode: Int, owner: String, name: String, desc: String, itf: Boolean) {
override fun visitMethodInsn(opcode: Int, owner: String, name: String, desc: String, itf: Boolean) {
if ("<init>".equals(name) && isInlineParameterLikeOwner(owner)) {
/*constuctor creation*/
val fromCall = MethodInfo(className, this.name, this.desc)
@@ -191,7 +191,7 @@ object InlineTestUtil {
override fun equals(other: Any?): Boolean = throw UnsupportedOperationException()
override fun toString(): String = throw UnsupportedOperationException()
}
}!!.getClassHeader()
}!!.classHeader
}
private class InlineInfo(val inlineMethods: Set<MethodInfo>, val classHeaders: Map<String, KotlinClassHeader>)
@@ -24,8 +24,8 @@ import org.jetbrains.asm4.Opcodes
import org.jetbrains.kotlin.test.ConfigurationKind
import java.util.*
public class MethodOrderTest: CodegenTestCase() {
public fun testDelegatedMethod() {
class MethodOrderTest: CodegenTestCase() {
fun testDelegatedMethod() {
doTest(
"""
interface Trait {
@@ -48,7 +48,7 @@ public class MethodOrderTest: CodegenTestCase() {
)
}
public fun testLambdaClosureOrdering() {
fun testLambdaClosureOrdering() {
doTest(
"""
class Klass {
@@ -62,7 +62,7 @@ public class MethodOrderTest: CodegenTestCase() {
)
}
public fun testAnonymousObjectClosureOrdering() {
fun testAnonymousObjectClosureOrdering() {
doTest(
"""
class Klass {
@@ -80,7 +80,7 @@ public class MethodOrderTest: CodegenTestCase() {
)
}
public fun testMemberAccessor() {
fun testMemberAccessor() {
doTest(
"""
class Outer(private val a: Int, private var b: String) {
@@ -16,8 +16,8 @@
package org.jetbrains.kotlin.codegen
public data class OuterClassInfo(
public val owner: String,
public val methodName: String?,
public val methodDesc: String?
data class OuterClassInfo(
val owner: String,
val methodName: String?,
val methodDesc: String?
)
@@ -18,7 +18,7 @@ package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.test.ConfigurationKind
public class ReflectionClassLoaderTest : CodegenTestCase() {
class ReflectionClassLoaderTest : CodegenTestCase() {
override fun getPrefix() = "reflection/classLoaders"
override fun setUp() {
@@ -26,7 +26,7 @@ public class ReflectionClassLoaderTest : CodegenTestCase() {
createEnvironmentWithMockJdkAndIdeaAnnotations(ConfigurationKind.ALL)
}
private fun Class<*>.methodByName(name: String) = getDeclaredMethods().single { it.getName() == name }
private fun Class<*>.methodByName(name: String) = declaredMethods.single { it.name == name }
fun doTest(cl1: ClassLoader, cl2: ClassLoader) {
val t1 = cl1.loadClass("test.Test")
@@ -38,7 +38,7 @@ public class ReflectionClassLoaderTest : CodegenTestCase() {
}
fun testSimpleDifferentClassLoaders() {
loadFile(getPrefix() + "/differentClassLoaders.kt")
loadFile(prefix + "/differentClassLoaders.kt")
doTest(
createClassLoader(),
@@ -49,7 +49,7 @@ public class ReflectionClassLoaderTest : CodegenTestCase() {
fun testClassLoaderWithNonTrivialEqualsAndHashCode() {
// Check that class loaders do not participate as keys in hash maps (use identity hash maps instead)
loadFile(getPrefix() + "/differentClassLoaders.kt")
loadFile(prefix + "/differentClassLoaders.kt")
class BrokenEqualsClassLoader(parent: ClassLoader) : ClassLoader(parent) {
override fun equals(other: Any?) = true
@@ -65,7 +65,7 @@ public class ReflectionClassLoaderTest : CodegenTestCase() {
fun testParentFirst() {
// Check that for a child class loader, a class reference would be the same as for his parent
loadFile(getPrefix() + "/parentFirst.kt")
loadFile(prefix + "/parentFirst.kt")
class ChildClassLoader(parent: ClassLoader) : ClassLoader(parent)
@@ -22,23 +22,21 @@ import java.io.File
import java.io.FileInputStream
import java.util.zip.ZipInputStream
public class TestStdlibWithDxTest {
@Test
public fun testRuntimeWithDx() {
class TestStdlibWithDxTest {
@Test fun testRuntimeWithDx() {
doTest(ForTestCompileRuntime.runtimeJarForTests())
}
@Test
public fun testReflectWithDx() {
@Test fun testReflectWithDx() {
doTest(ForTestCompileRuntime.reflectJarForTests())
}
private fun doTest(file: File) {
val zip = ZipInputStream(FileInputStream(file))
zip.use {
sequence { zip.getNextEntry() }.forEach {
if (it.getName().endsWith(".class")) {
DxChecker.checkFileWithDx(zip.readBytes(), it.getName())
sequence { zip.nextEntry }.forEach {
if (it.name.endsWith(".class")) {
DxChecker.checkFileWithDx(zip.readBytes(), it.name)
}
}
}
@@ -22,16 +22,16 @@ import org.jetbrains.kotlin.codegen.getClassFiles
import org.jetbrains.kotlin.jvm.compiler.AbstractSMAPBaseTest
import java.io.File
public abstract class AbstractBlackBoxInlineCodegenTest : AbstractBlackBoxCodegenTest(), AbstractSMAPBaseTest {
abstract class AbstractBlackBoxInlineCodegenTest : AbstractBlackBoxCodegenTest(), AbstractSMAPBaseTest {
public fun doTestMultiFileWithInlineCheck(firstFileName: String) {
fun doTestMultiFileWithInlineCheck(firstFileName: String) {
val fileName = relativePath(File(firstFileName))
val inputFiles = listOf(fileName, fileName.substringBeforeLast("1.kt") + "2.kt")
doTestMultiFile(inputFiles)
try {
InlineTestUtil.checkNoCallsToInline(initializedClassLoader.allGeneratedFiles.filterClassFiles(), myFiles.getPsiFiles())
checkSMAP(myFiles.getPsiFiles(), generateClassesInFile().getClassFiles())
InlineTestUtil.checkNoCallsToInline(initializedClassLoader.allGeneratedFiles.filterClassFiles(), myFiles.psiFiles)
checkSMAP(myFiles.psiFiles, generateClassesInFile().getClassFiles())
}
catch (e: Throwable) {
System.out.println(generateToText())
@@ -32,7 +32,7 @@ import kotlin.test.fail
val TIMEOUT_DAEMON_RUNNER_EXIT_MS = 10000L
public class CompilerDaemonTest : KotlinIntegrationTestBase() {
class CompilerDaemonTest : KotlinIntegrationTestBase() {
data class CompilerResults(val resultCode: Int, val out: String)
@@ -65,7 +65,7 @@ public class CompilerDaemonTest : KotlinIntegrationTestBase() {
private fun run(logName: String, vararg args: String): Int = runJava(getTestBaseDir(), logName, *args)
public fun testHelloApp() {
fun testHelloApp() {
withFlagFile(getTestName(true), ".alive") { flagFile ->
val daemonOptions = DaemonOptions(runFilesPath = File(tmpdir, getTestName(true)).absolutePath,
verbose = true,
@@ -113,7 +113,7 @@ public class CompilerDaemonTest : KotlinIntegrationTestBase() {
}
}
public fun testDaemonJvmOptionsParsing() {
fun testDaemonJvmOptionsParsing() {
val backupJvmOptions = System.getProperty(COMPILE_DAEMON_JVM_OPTIONS_PROPERTY)
try {
System.setProperty(COMPILE_DAEMON_JVM_OPTIONS_PROPERTY, "-aaa,-bbb\\,ccc,-ddd,-Xmx200m,-XX:MaxPermSize=10k,-XX:ReservedCodeCacheSize=100,-xxx\\,yyy")
@@ -128,7 +128,7 @@ public class CompilerDaemonTest : KotlinIntegrationTestBase() {
}
}
public fun testDaemonOptionsParsing() {
fun testDaemonOptionsParsing() {
val backupOptions = System.getProperty(COMPILE_DAEMON_OPTIONS_PROPERTY)
try {
System.setProperty(COMPILE_DAEMON_OPTIONS_PROPERTY, "runFilesPath=abcd,autoshutdownIdleSeconds=1111")
@@ -141,7 +141,7 @@ public class CompilerDaemonTest : KotlinIntegrationTestBase() {
}
}
public fun testDaemonInstancesSimple() {
fun testDaemonInstancesSimple() {
withFlagFile(getTestName(true), ".alive") { flagFile ->
val daemonOptions = DaemonOptions(runFilesPath = File(tmpdir, getTestName(true)).absolutePath)
val compilerId2 = CompilerId.makeCompilerId(compilerClassPath +
@@ -185,7 +185,7 @@ public class CompilerDaemonTest : KotlinIntegrationTestBase() {
}
}
public fun testDaemonAutoshutdownOnUnused() {
fun testDaemonAutoshutdownOnUnused() {
withFlagFile(getTestName(true), ".alive") { flagFile ->
val daemonOptions = DaemonOptions(autoshutdownUnusedSeconds = 1, runFilesPath = File(tmpdir, getTestName(true)).absolutePath)
KotlinCompilerClient.shutdownCompileService(compilerId, daemonOptions)
@@ -212,7 +212,7 @@ public class CompilerDaemonTest : KotlinIntegrationTestBase() {
}
}
public fun testDaemonAutoshutdownOnIdle() {
fun testDaemonAutoshutdownOnIdle() {
withFlagFile(getTestName(true), ".alive") { flagFile ->
val daemonOptions = DaemonOptions(autoshutdownIdleSeconds = 1, runFilesPath = File(tmpdir, getTestName(true)).absolutePath)
KotlinCompilerClient.shutdownCompileService(compilerId, daemonOptions)
@@ -244,7 +244,7 @@ public class CompilerDaemonTest : KotlinIntegrationTestBase() {
}
}
public fun testDaemonGracefulShutdown() {
fun testDaemonGracefulShutdown() {
withFlagFile(getTestName(true), ".alive") { flagFile ->
val daemonOptions = DaemonOptions(autoshutdownIdleSeconds = 1, runFilesPath = File(tmpdir, getTestName(true)).absolutePath)
KotlinCompilerClient.shutdownCompileService(compilerId, daemonOptions)
@@ -291,7 +291,7 @@ public class CompilerDaemonTest : KotlinIntegrationTestBase() {
* This seems a known problem, e.g. gradle uses a library with native code that prevents io handles inheritance when launching it's daemon
* (the same solution is used in kotlin daemon client - see next commit)
*/
public fun testDaemonExecutionViaIntermediateProcess() {
fun testDaemonExecutionViaIntermediateProcess() {
val clientAliveFile = createTempFile("kotlin-daemon-transitive-run-test", ".run")
val runFilesPath = File(tmpdir, getTestName(true)).absolutePath
val daemonOptions = DaemonOptions(runFilesPath = runFilesPath)
@@ -329,7 +329,7 @@ public class CompilerDaemonTest : KotlinIntegrationTestBase() {
}
}
private class SynchronizationTracer(public val startSignal: CountDownLatch, public val doneSignal: CountDownLatch, port: Int) : RemoteOperationsTracer,
private class SynchronizationTracer(val startSignal: CountDownLatch, val doneSignal: CountDownLatch, port: Int) : RemoteOperationsTracer,
java.rmi.server.UnicastRemoteObject(port, LoopbackNetworkInterface.clientLoopbackSocketFactory, LoopbackNetworkInterface.serverLoopbackSocketFactory)
{
override fun before(id: String) {
@@ -343,7 +343,7 @@ public class CompilerDaemonTest : KotlinIntegrationTestBase() {
private val PARALLEL_THREADS_TO_COMPILE = 10
private val PARALLEL_WAIT_TIMEOUT_S = 60L
public fun testParallelCompilationOnDaemon() {
fun testParallelCompilationOnDaemon() {
assertTrue(PARALLEL_THREADS_TO_COMPILE <= LoopbackNetworkInterface.SERVER_SOCKET_BACKLOG_SIZE)
@@ -20,8 +20,8 @@ import org.jetbrains.kotlin.codegen.generated.AbstractBlackBoxCodegenTest
import java.io.File
public abstract class AbstractBlackBoxMultifileClassCodegenTest: AbstractBlackBoxCodegenTest() {
public fun doTestMultifileClassAgainstSources(firstFileName: String) {
abstract class AbstractBlackBoxMultifileClassCodegenTest: AbstractBlackBoxCodegenTest() {
fun doTestMultifileClassAgainstSources(firstFileName: String) {
val fileName = relativePath(File(firstFileName))
val inputFiles = listOf(fileName, fileName.substringBeforeLast("1.kt") + "2.kt")
@@ -22,16 +22,16 @@ import org.jetbrains.kotlin.codegen.filterClassFiles
import java.io.File
import java.util.Collections
public abstract class AbstractCompileKotlinAgainstInlineKotlinTest : AbstractCompileKotlinAgainstKotlinTest(), AbstractSMAPBaseTest {
abstract class AbstractCompileKotlinAgainstInlineKotlinTest : AbstractCompileKotlinAgainstKotlinTest(), AbstractSMAPBaseTest {
public fun doBoxTestWithInlineCheck(firstFileName: String) {
fun doBoxTestWithInlineCheck(firstFileName: String) {
val inputFiles = listOf(firstFileName, firstFileName.substringBeforeLast("1.kt") + "2.kt")
val (factory1, factory2) = doBoxTest(inputFiles)
val allGeneratedFiles = factory1.asList() + factory2.asList()
try {
val sourceFiles = factory1.getInputFiles() + factory2.getInputFiles()
val sourceFiles = factory1.inputFiles + factory2.inputFiles
InlineTestUtil.checkNoCallsToInline(allGeneratedFiles.filterClassFiles(), sourceFiles)
checkSMAP(sourceFiles, allGeneratedFiles.filterClassFiles())
}
@@ -22,9 +22,9 @@ import org.jetbrains.kotlin.codegen.filterClassFiles
import java.io.File
import java.util.Collections
public abstract class AbstractCompileKotlinAgainstMultifileKotlinTest : AbstractCompileKotlinAgainstKotlinTest(), AbstractSMAPBaseTest {
abstract class AbstractCompileKotlinAgainstMultifileKotlinTest : AbstractCompileKotlinAgainstKotlinTest(), AbstractSMAPBaseTest {
public fun doBoxTest(firstFileName: String) {
fun doBoxTest(firstFileName: String) {
val inputFiles = listOf(firstFileName, firstFileName.substringBeforeLast("1.kt") + "2.kt")
doBoxTest(inputFiles)
}
@@ -27,7 +27,7 @@ import org.jetbrains.org.objectweb.asm.Opcodes
import org.junit.Assert
import java.io.File
public interface AbstractSMAPBaseTest {
interface AbstractSMAPBaseTest {
private fun extractSMAPFromClasses(outputFiles: Iterable<OutputFile>): List<SMAPAndFile> {
return outputFiles.mapNotNull { outputFile ->
@@ -43,7 +43,7 @@ public interface AbstractSMAPBaseTest {
}
private fun extractSmapFromSource(file: KtFile): SMAPAndFile? {
val fileContent = file.getText()
val fileContent = file.text
val smapPrefix = "//SMAP"
if (InTextDirectivesUtils.isDirectiveDefined(fileContent, smapPrefix)) {
InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileContent, smapPrefix)
@@ -51,7 +51,7 @@ public interface AbstractSMAPBaseTest {
smapData = smapData.replace("//", "").trim()
return SMAPAndFile(if (smapData.startsWith("SMAP ABSENT")) null else smapData,
SMAPAndFile.getPath(file.getVirtualFile().getCanonicalPath()!!))
SMAPAndFile.getPath(file.virtualFile.canonicalPath!!))
}
return null;
}
@@ -91,11 +91,11 @@ public interface AbstractSMAPBaseTest {
companion object {
fun SMAPAndFile(smap: String?, sourceFile: File) = SMAPAndFile(smap, getPath(sourceFile))
public fun getPath(file: File): String {
return getPath(file.getCanonicalPath())
fun getPath(file: File): String {
return getPath(file.canonicalPath)
}
public fun getPath(canonicalPath: String): String {
fun getPath(canonicalPath: String): String {
//There are some problems with disk name on windows cause LightVirtualFile return it without disk name
return FileUtil.toSystemIndependentName(canonicalPath).substringAfter(":")
}
@@ -38,7 +38,7 @@ import java.util.regex.Pattern
import kotlin.text.Regex
public abstract class AbstractWriteSignatureTest : TestCaseWithTmpdir() {
abstract class AbstractWriteSignatureTest : TestCaseWithTmpdir() {
private var jetCoreEnvironment: KotlinCoreEnvironment? = null
override fun setUp() {
@@ -55,7 +55,7 @@ public abstract class AbstractWriteSignatureTest : TestCaseWithTmpdir() {
val ktFile = File(ktFileName)
val text = FileUtil.loadFile(ktFile, true)
val psiFile = KotlinTestUtils.createFile(ktFile.getName(), text, jetCoreEnvironment!!.project)
val psiFile = KotlinTestUtils.createFile(ktFile.name, text, jetCoreEnvironment!!.project)
val outputFiles = GenerationUtils.compileFileGetClassFileFactoryForTest(psiFile, jetCoreEnvironment!!)
@@ -119,8 +119,8 @@ public abstract class AbstractWriteSignatureTest : TestCaseWithTmpdir() {
private fun checkPackageParts(checker: Checker, classFile: File) {
// Look for package parts in the same directory.
// Package part file names for package SomePackage look like SomePackage$<hash>.class.
val classDir = classFile.getParentFile()
val classLastName = classFile.getName()
val classDir = classFile.parentFile
val classLastName = classFile.name
val packageFacadePrefix = classLastName.replace(".class", "\$")
classDir.listFiles { dir, lastName ->
lastName.startsWith(packageFacadePrefix) && lastName.endsWith(".class")
@@ -38,7 +38,7 @@ private fun validateDeserializedScope(scopeOwner: DeclarationDescriptor, scope:
val isPackageViewScope = scopeOwner is PackageViewDescriptor
if (scope is DeserializedMemberScope || isPackageViewScope) {
val relevantDescriptors = scope.getContributedDescriptors().filter { member ->
member is CallableMemberDescriptor && member.getKind().isReal() || (!isPackageViewScope && member is ClassDescriptor)
member is CallableMemberDescriptor && member.kind.isReal || (!isPackageViewScope && member is ClassDescriptor)
}
checkSorted(relevantDescriptors, scopeOwner)
}
@@ -34,7 +34,7 @@ import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
public class KotlinClassFinderTest : KotlinTestWithEnvironmentManagement() {
class KotlinClassFinderTest : KotlinTestWithEnvironmentManagement() {
fun testAbsentClass() {
val tmpdir = KotlinTestUtils.tmpDirForTest(this)
@@ -49,7 +49,7 @@ public class KotlinClassFinderTest : KotlinTestWithEnvironmentManagement() {
fun testNestedClass() {
val tmpdir = KotlinTestUtils.tmpDirForTest(this)
KotlinTestUtils.compileKotlinWithJava(
listOf(), listOf(File("compiler/testData/kotlinClassFinder/nestedClass.kt")), tmpdir, getTestRootDisposable()!!, null
listOf(), listOf(File("compiler/testData/kotlinClassFinder/nestedClass.kt")), tmpdir, testRootDisposable!!, null
)
val environment = createEnvironment(tmpdir)
@@ -63,11 +63,11 @@ public class KotlinClassFinderTest : KotlinTestWithEnvironmentManagement() {
val binaryClass = JvmVirtualFileFinder.SERVICE.getInstance(project).findKotlinClass(JavaClassImpl(psiClass!!))
assertNotNull(binaryClass, "No binary class for $className")
assertEquals("test/A.B.C", binaryClass?.getClassId()?.toString())
assertEquals("test/A.B.C", binaryClass?.classId?.toString())
}
private fun createEnvironment(tmpdir: File?): KotlinCoreEnvironment {
val environment = KotlinCoreEnvironment.createForTests(getTestRootDisposable()!!,
val environment = KotlinCoreEnvironment.createForTests(testRootDisposable!!,
KotlinTestUtils.compilerConfigurationForTests(
ConfigurationKind.ALL, TestJdkKind.MOCK_JDK, tmpdir),
EnvironmentConfigFiles.JVM_CONFIG_FILES)
@@ -45,7 +45,7 @@ import org.junit.Assert
import java.io.File
import java.util.HashMap
public class MultiModuleJavaAnalysisCustomTest : UsefulTestCase() {
class MultiModuleJavaAnalysisCustomTest : UsefulTestCase() {
private class TestModule(val _name: String, val kotlinFiles: List<KtFile>, val javaFilesScope: GlobalSearchScope,
val _dependencies: TestModule.() -> List<TestModule>) :
@@ -55,7 +55,7 @@ public class MultiModuleJavaAnalysisCustomTest : UsefulTestCase() {
}
fun testJavaEntitiesBelongToCorrectModule() {
val moduleDirs = File(PATH_TO_TEST_ROOT_DIR).listFiles { it -> it.isDirectory() }!!
val moduleDirs = File(PATH_TO_TEST_ROOT_DIR).listFiles { it -> it.isDirectory }!!
val environment = createEnvironment(moduleDirs)
val modules = setupModules(environment, moduleDirs)
val resolverForProject = JvmAnalyzerFacade.setupResolverForProject(
@@ -64,7 +64,7 @@ public class MultiModuleJavaAnalysisCustomTest : UsefulTestCase() {
{ m -> ModuleContent(m.kotlinFiles, m.javaFilesScope) },
JvmPlatformParameters {
javaClass ->
val moduleName = javaClass.getName().asString().toLowerCase().first().toString()
val moduleName = javaClass.name.asString().toLowerCase().first().toString()
modules.first { it._name == moduleName }
},
CompilerEnvironment,
@@ -77,20 +77,20 @@ public class MultiModuleJavaAnalysisCustomTest : UsefulTestCase() {
private fun createEnvironment(moduleDirs: Array<File>): KotlinCoreEnvironment {
val configuration = CompilerConfiguration()
configuration.addJavaSourceRoots(moduleDirs.toList())
return KotlinCoreEnvironment.createForTests(getTestRootDisposable()!!, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES)
return KotlinCoreEnvironment.createForTests(testRootDisposable!!, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES)
}
private fun setupModules(environment: KotlinCoreEnvironment, moduleDirs: Array<File>): List<TestModule> {
val project = environment.project
val modules = HashMap<String, TestModule>()
for (dir in moduleDirs) {
val name = dir.getName()
val name = dir.name
val kotlinFiles = KotlinTestUtils.loadToJetFiles(environment, dir.listFiles { it -> it.extension == "kt" }?.toList().orEmpty())
val javaFilesScope = object : DelegatingGlobalSearchScope(GlobalSearchScope.allScope(project)) {
override fun contains(file: VirtualFile): Boolean {
if (file !in myBaseScope!!) return false
if (file.isDirectory()) return true
return file.getParent()!!.getParent()!!.getName() == name
if (file.isDirectory) return true
return file.parent!!.parent!!.name == name
}
}
modules[name] = TestModule(name, kotlinFiles, javaFilesScope) {
@@ -123,7 +123,7 @@ public class MultiModuleJavaAnalysisCustomTest : UsefulTestCase() {
}
private fun checkClass(classDescriptor: ClassDescriptor) {
classDescriptor.getDefaultType().getMemberScope().getContributedDescriptors().filterIsInstance<CallableDescriptor>().forEach {
classDescriptor.defaultType.memberScope.getContributedDescriptors().filterIsInstance<CallableDescriptor>().forEach {
checkCallable(it)
}
@@ -131,28 +131,28 @@ public class MultiModuleJavaAnalysisCustomTest : UsefulTestCase() {
}
private fun checkCallable(callable: CallableDescriptor) {
val name = callable.getName().asString()
val name = callable.name.asString()
if (name in setOf("equals", "hashCode", "toString")) return
val returnType = callable.getReturnType()!!
val returnType = callable.returnType!!
if (!KotlinBuiltIns.isUnit(returnType)) {
checkDescriptor(returnType.getConstructor().getDeclarationDescriptor()!!, callable)
checkDescriptor(returnType.constructor.declarationDescriptor!!, callable)
}
callable.getValueParameters().map {
it.getType().getConstructor().getDeclarationDescriptor()!!
callable.valueParameters.map {
it.type.constructor.declarationDescriptor!!
}.forEach { checkDescriptor(it, callable) }
callable.getAnnotations().map {
it.getType().getConstructor().getDeclarationDescriptor()!!
callable.annotations.map {
it.type.constructor.declarationDescriptor!!
}.forEach { checkDescriptor(it, callable) }
}
private fun checkSupertypes(classDescriptor: ClassDescriptor) {
classDescriptor.getDefaultType().getConstructor().getSupertypes().filter {
classDescriptor.defaultType.constructor.supertypes.filter {
!KotlinBuiltIns.isAnyOrNullableAny(it)
}.map {
it.getConstructor().getDeclarationDescriptor()!!
it.constructor.declarationDescriptor!!
}.forEach {
checkDescriptor(it, classDescriptor)
}
@@ -161,9 +161,9 @@ public class MultiModuleJavaAnalysisCustomTest : UsefulTestCase() {
private fun checkDescriptor(referencedDescriptor: ClassifierDescriptor, context: DeclarationDescriptor) {
assert(!ErrorUtils.isError(referencedDescriptor)) { "Error descriptor: $referencedDescriptor" }
val descriptorName = referencedDescriptor.getName().asString()
val descriptorName = referencedDescriptor.name.asString()
val expectedModuleName = "<${descriptorName.toLowerCase().first().toString()}>"
val moduleName = referencedDescriptor.module.getName().asString()
val moduleName = referencedDescriptor.module.name.asString()
Assert.assertEquals(
"Java class $descriptorName in $context should be in module $expectedModuleName, but instead was in $moduleName",
expectedModuleName, moduleName
@@ -59,7 +59,7 @@ import java.net.URLClassLoader
import java.util.*
import java.util.regex.Pattern
public abstract class AbstractJvmRuntimeDescriptorLoaderTest : TestCaseWithTmpdir() {
abstract class AbstractJvmRuntimeDescriptorLoaderTest : TestCaseWithTmpdir() {
companion object {
private val renderer = DescriptorRenderer.withOptions {
withDefinedIn = false
@@ -23,8 +23,8 @@ import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression
import org.jetbrains.kotlin.test.KotlinLiteFixture
import org.junit.Assert
public class KtSimpleNameExpressionTest : KotlinLiteFixture() {
public fun testGetReceiverExpressionIdentifier() {
class KtSimpleNameExpressionTest : KotlinLiteFixture() {
fun testGetReceiverExpressionIdentifier() {
// Binary Expressions
assertReceiver("1 + 2", "1")
assertReceiver("1 in array(1)", "array(1)")
@@ -32,10 +32,10 @@ public class KtSimpleNameExpressionTest : KotlinLiteFixture() {
assertReceiver("1 to 2", "1")
}
private fun assertReceiver(exprString: String, expected: String) {
val expression = KtPsiFactory(getProject()).createExpression(exprString) as KtBinaryExpression
Assert.assertEquals(expected, expression.getOperationReference().getReceiverExpression()!!.getText())
val expression = KtPsiFactory(project).createExpression(exprString) as KtBinaryExpression
Assert.assertEquals(expected, expression.operationReference.getReceiverExpression()!!.text)
}
override fun createEnvironment(): KotlinCoreEnvironment {
return KotlinCoreEnvironment.createForTests(getTestRootDisposable()!!, CompilerConfiguration(), EnvironmentConfigFiles.JVM_CONFIG_FILES)
return KotlinCoreEnvironment.createForTests(testRootDisposable!!, CompilerConfiguration(), EnvironmentConfigFiles.JVM_CONFIG_FILES)
}
}
@@ -42,7 +42,7 @@ import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
import java.util.ArrayList
public abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment() {
abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment() {
protected open fun getDescriptor(declaration: KtDeclaration, container: ComponentProvider): DeclarationDescriptor {
return container.get<ResolveSession>().resolveToDescriptor(declaration)
}
@@ -50,11 +50,11 @@ public abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment
protected open val targetEnvironment: TargetEnvironment
get() = CompilerEnvironment
public fun doTest(path: String) {
fun doTest(path: String) {
val fileText = FileUtil.loadFile(File(path), true)
val psiFile = KtPsiFactory(getProject()).createFile(fileText)
val psiFile = KtPsiFactory(project).createFile(fileText)
val context = TopDownAnalyzerFacadeForJVM.createContextWithSealedModule(getProject(), environment.getModuleName())
val context = TopDownAnalyzerFacadeForJVM.createContextWithSealedModule(project, environment.getModuleName())
val container = createContainerForLazyResolve(
@@ -67,14 +67,14 @@ public abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment
val resolveSession = container.get<ResolveSession>()
context.initializeModuleContents(resolveSession.getPackageFragmentProvider())
context.initializeModuleContents(resolveSession.packageFragmentProvider)
val descriptors = ArrayList<DeclarationDescriptor>()
psiFile.accept(object : KtVisitorVoid() {
override fun visitKtFile(file: KtFile) {
val fqName = file.getPackageFqName()
if (!fqName.isRoot()) {
val fqName = file.packageFqName
if (!fqName.isRoot) {
val packageDescriptor = context.module.getPackage(fqName)
descriptors.add(packageDescriptor)
}
@@ -82,7 +82,7 @@ public abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment
}
override fun visitParameter(parameter: KtParameter) {
val declaringElement = parameter.getParent().getParent()
val declaringElement = parameter.parent.parent
when (declaringElement) {
is KtFunctionType -> return
is KtNamedFunction ->
@@ -90,7 +90,7 @@ public abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment
is KtPrimaryConstructor -> {
val ktClassOrObject: KtClassOrObject = declaringElement.getContainingClassOrObject()
val classDescriptor = getDescriptor(ktClassOrObject, container) as ClassDescriptor
addCorrespondingParameterDescriptor(classDescriptor.getUnsubstitutedPrimaryConstructor()!!, parameter)
addCorrespondingParameterDescriptor(classDescriptor.unsubstitutedPrimaryConstructor!!, parameter)
}
else -> super.visitParameter(parameter)
}
@@ -99,11 +99,11 @@ public abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
val property = accessor.property
val propertyDescriptor = getDescriptor(property, container) as PropertyDescriptor
if (accessor.isGetter()) {
descriptors.add(propertyDescriptor.getGetter()!!)
if (accessor.isGetter) {
descriptors.add(propertyDescriptor.getter!!)
}
else {
descriptors.add(propertyDescriptor.getSetter()!!)
descriptors.add(propertyDescriptor.setter!!)
}
accessor.acceptChildren(this)
}
@@ -118,8 +118,8 @@ public abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment
if (descriptor is ClassDescriptor) {
// if class has primary constructor then we visit it later, otherwise add it artificially
if (element !is KtClassOrObject || !element.hasExplicitPrimaryConstructor()) {
if (descriptor.getUnsubstitutedPrimaryConstructor() != null) {
descriptors.add(descriptor.getUnsubstitutedPrimaryConstructor()!!)
if (descriptor.unsubstitutedPrimaryConstructor != null) {
descriptors.add(descriptor.unsubstitutedPrimaryConstructor!!)
}
}
}
@@ -131,8 +131,8 @@ public abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment
}
private fun addCorrespondingParameterDescriptor(functionDescriptor: FunctionDescriptor, parameter: KtParameter) {
for (valueParameterDescriptor in functionDescriptor.getValueParameters()) {
if (valueParameterDescriptor.getName() == parameter.getNameAsName()) {
for (valueParameterDescriptor in functionDescriptor.valueParameters) {
if (valueParameterDescriptor.name == parameter.nameAsName) {
descriptors.add(valueParameterDescriptor)
}
}
@@ -146,7 +146,7 @@ public abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment
}
val renderedDescriptors = descriptors.map { renderer.render(it) }.joinToString(separator = "\n")
val document = DocumentImpl(psiFile.getText())
val document = DocumentImpl(psiFile.text)
UsefulTestCase.assertSameLines(KotlinTestUtils.getLastCommentedLines(document), renderedDescriptors.toString())
}
@@ -34,10 +34,10 @@ import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.utils.addIfNotNull
import java.io.File
abstract public class AbstractFunctionDescriptorInExpressionRendererTest : KotlinTestWithEnvironment() {
public fun doTest(path: String) {
abstract class AbstractFunctionDescriptorInExpressionRendererTest : KotlinTestWithEnvironment() {
fun doTest(path: String) {
val fileText = FileUtil.loadFile(File(path), true)
val file = KtPsiFactory(getProject()).createFile(fileText)
val file = KtPsiFactory(project).createFile(fileText)
val bindingContext = JvmResolveUtil.analyzeOneFileWithJavaIntegration(file).bindingContext
val descriptors = arrayListOf<DeclarationDescriptor>()
@@ -49,7 +49,7 @@ abstract public class AbstractFunctionDescriptorInExpressionRendererTest : Kotli
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
lambdaExpression.acceptChildren(this)
descriptors.add(bindingContext.get(BindingContext.FUNCTION, lambdaExpression.getFunctionLiteral())!!)
descriptors.add(bindingContext.get(BindingContext.FUNCTION, lambdaExpression.functionLiteral)!!)
}
})
@@ -60,7 +60,7 @@ abstract public class AbstractFunctionDescriptorInExpressionRendererTest : Kotli
}
val renderedDescriptors = descriptors.map { renderer.render(it) }.joinToString(separator = "\n")
val document = DocumentImpl(file.getText())
val document = DocumentImpl(file.text)
UsefulTestCase.assertSameLines(KotlinTestUtils.getLastCommentedLines(document), renderedDescriptors.toString())
}
@@ -38,7 +38,7 @@ private val TRAILING_NEWLINE_REGEX = Regex("\n$")
private val INCOMPLETE_LINE_MESSAGE = "incomplete line"
public abstract class AbstractReplInterpreterTest : UsefulTestCase() {
abstract class AbstractReplInterpreterTest : UsefulTestCase() {
init {
System.setProperty("java.awt.headless", "true")
}
@@ -82,7 +82,7 @@ public abstract class AbstractReplInterpreterTest : UsefulTestCase() {
protected fun doTest(path: String) {
val configuration = KotlinTestUtils.compilerConfigurationForTests(ConfigurationKind.ALL, TestJdkKind.MOCK_JDK)
val repl = ReplInterpreter(getTestRootDisposable()!!, configuration, false, null)
val repl = ReplInterpreter(testRootDisposable!!, configuration, false, null)
for ((code, expected) in loadLines(File(path))) {
val lineResult = repl.eval(code)
@@ -91,10 +91,10 @@ public abstract class AbstractReplInterpreterTest : UsefulTestCase() {
repl.dumpClasses(PrintWriter(System.out))
}
val actual = when (lineResult.getType()) {
val actual = when (lineResult.type) {
ReplInterpreter.LineResultType.SUCCESS -> if (!lineResult.isUnit) "${lineResult.value}" else ""
ReplInterpreter.LineResultType.RUNTIME_ERROR,
ReplInterpreter.LineResultType.COMPILE_ERROR -> lineResult.getErrorText()
ReplInterpreter.LineResultType.COMPILE_ERROR -> lineResult.errorText
ReplInterpreter.LineResultType.INCOMPLETE -> INCOMPLETE_LINE_MESSAGE
}
@@ -30,16 +30,16 @@ import org.jetbrains.kotlin.psi.*
class MutableDiagnosticsTest : KotlinTestWithEnvironment() {
override fun createEnvironment(): KotlinCoreEnvironment? {
return KotlinCoreEnvironment.createForTests(getTestRootDisposable()!!, CompilerConfiguration(), EnvironmentConfigFiles.JVM_CONFIG_FILES)
return KotlinCoreEnvironment.createForTests(testRootDisposable!!, CompilerConfiguration(), EnvironmentConfigFiles.JVM_CONFIG_FILES)
}
private val BindingTrace.diagnostics: Diagnostics
get() = getBindingContext().getDiagnostics()
get() = bindingContext.diagnostics
fun testPropagatingModification() {
val base = BindingTraceContext()
val middle = DelegatingBindingTrace(base.getBindingContext(), "middle")
val derived = DelegatingBindingTrace(middle.getBindingContext(), "derived")
val middle = DelegatingBindingTrace(base.bindingContext, "middle")
val derived = DelegatingBindingTrace(middle.bindingContext, "derived")
Assert.assertTrue(base.diagnostics.isEmpty())
Assert.assertTrue(middle.diagnostics.isEmpty())
@@ -81,8 +81,8 @@ class MutableDiagnosticsTest : KotlinTestWithEnvironment() {
fun testCaching() {
val base = BindingTraceContext()
val middle = DelegatingBindingTrace(base.getBindingContext(), "middle")
val derived = DelegatingBindingTrace(middle.getBindingContext(), "derived")
val middle = DelegatingBindingTrace(base.bindingContext, "middle")
val derived = DelegatingBindingTrace(middle.bindingContext, "derived")
base.reportDiagnostic()
middle.reportDiagnostic()
@@ -128,14 +128,14 @@ class MutableDiagnosticsTest : KotlinTestWithEnvironment() {
//NOTE: cannot simply call all() since it applies filter on every query and produces new collection
private fun Diagnostics.contents(): MutableCollection<Diagnostic> {
return (this as MutableDiagnosticsWithSuppression).getReadonlyView().getDiagnostics()
return (this as MutableDiagnosticsWithSuppression).getReadonlyView().diagnostics
}
private class DummyDiagnosticFactory : DiagnosticFactory<DummyDiagnostic>("DUMMY", Severity.ERROR)
private inner class DummyDiagnostic : Diagnostic {
private val factory = DummyDiagnosticFactory()
private val dummyElement = KtPsiFactory(getEnvironment().project).createType("Int")
private val dummyElement = KtPsiFactory(environment.project).createType("Int")
init {
dummyElement.getContainingKtFile().doNotAnalyze = null
@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.test.InTextDirectivesUtils
import java.io.File
import org.jetbrains.kotlin.test.KotlinTestUtils
public abstract class AbstractAnnotationParameterTest : AbstractAnnotationDescriptorResolveTest() {
abstract class AbstractAnnotationParameterTest : AbstractAnnotationDescriptorResolveTest() {
fun doTest(path: String) {
val fileText = FileUtil.loadFile(File(path), true)
val packageView = getPackage(fileText)
@@ -41,19 +41,19 @@ import org.jetbrains.kotlin.psi.KtFile
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.resolve.scopes.receivers.*
public abstract class AbstractResolvedCallsTest : KotlinLiteFixture() {
abstract class AbstractResolvedCallsTest : KotlinLiteFixture() {
override fun createEnvironment(): KotlinCoreEnvironment = createEnvironmentWithMockJdk(ConfigurationKind.ALL)
public fun doTest(filePath: String) {
fun doTest(filePath: String) {
val text = KotlinTestUtils.doLoadFile(File(filePath))!!
val jetFile = KtPsiFactory(getProject()).createFile(text.replace("<caret>", ""))
val jetFile = KtPsiFactory(project).createFile(text.replace("<caret>", ""))
val bindingContext = JvmResolveUtil.analyzeOneFileWithJavaIntegration(jetFile, environment).bindingContext
val (element, cachedCall) = buildCachedCall(bindingContext, jetFile, text)
val resolvedCall = if (cachedCall !is VariableAsFunctionResolvedCall) cachedCall
else if ("(" == element?.getText()) cachedCall.functionCall
else if ("(" == element?.text) cachedCall.functionCall
else cachedCall.variableCall
val resolvedCallInfoFileName = FileUtil.getNameWithoutExtension(filePath) + ".txt"
@@ -73,25 +73,25 @@ public abstract class AbstractResolvedCallsTest : KotlinLiteFixture() {
}
private fun Receiver?.getText() = when (this) {
is ExpressionReceiver -> "${expression.getText()} {${getType()}}"
is ImplicitClassReceiver -> "Class{${getType()}}"
is ExtensionReceiver -> "${getType()}Ext{${declarationDescriptor.getText()}}"
is ExpressionReceiver -> "${expression.text} {${type}}"
is ImplicitClassReceiver -> "Class{${type}}"
is ExtensionReceiver -> "${type}Ext{${declarationDescriptor.getText()}}"
null -> "NO_RECEIVER"
else -> toString()
}
private fun ValueArgument.getText() = this.getArgumentExpression()?.getText()?.replace("\n", " ") ?: ""
private fun ValueArgument.getText() = this.getArgumentExpression()?.text?.replace("\n", " ") ?: ""
private fun ArgumentMapping.getText() = when (this) {
is ArgumentMatch -> {
val parameterType = DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(valueParameter.getType())
"${status.name} ${valueParameter.getName()} : ${parameterType} ="
val parameterType = DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(valueParameter.type)
"${status.name} ${valueParameter.name} : ${parameterType} ="
}
else -> "ARGUMENT UNMAPPED: "
}
private fun DeclarationDescriptor.getText(): String = when (this) {
is ReceiverParameterDescriptor -> "${getValue().getText()}::this"
is ReceiverParameterDescriptor -> "${value.getText()}::this"
else -> DescriptorRenderer.COMPACT_WITH_SHORT_TYPES.render(this)
}
@@ -100,17 +100,17 @@ private fun ResolvedCall<*>.renderToText(): String {
appendln("Resolved call:")
appendln()
if (getCandidateDescriptor() != getResultingDescriptor()) {
appendln("Candidate descriptor: ${getCandidateDescriptor()!!.getText()}")
if (candidateDescriptor != resultingDescriptor) {
appendln("Candidate descriptor: ${candidateDescriptor!!.getText()}")
}
appendln("Resulting descriptor: ${getResultingDescriptor()!!.getText()}")
appendln("Resulting descriptor: ${resultingDescriptor!!.getText()}")
appendln()
appendln("Explicit receiver kind = ${getExplicitReceiverKind()}")
appendln("Dispatch receiver = ${getDispatchReceiver().getText()}")
appendln("Extension receiver = ${getExtensionReceiver().getText()}")
appendln("Explicit receiver kind = ${explicitReceiverKind}")
appendln("Dispatch receiver = ${dispatchReceiver.getText()}")
appendln("Extension receiver = ${extensionReceiver.getText()}")
val valueArguments = getCall().getValueArguments()
val valueArguments = call.valueArguments
if (!valueArguments.isEmpty()) {
appendln()
appendln("Value arguments mapping:")
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.psi.debugText.getDebugText
import org.jetbrains.kotlin.resolve.calls.callUtil.getParentResolvedCall
abstract public class AbstractResolvedConstructorDelegationCallsTests : AbstractResolvedCallsTest() {
abstract class AbstractResolvedConstructorDelegationCallsTests : AbstractResolvedCallsTest() {
override fun buildCachedCall(
bindingContext: BindingContext, jetFile: KtFile, text: String
): Pair<PsiElement?, ResolvedCall<out CallableDescriptor>?> {
@@ -31,13 +31,13 @@ import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
import java.util.regex.Pattern
public abstract class AbstractCompileTimeConstantEvaluatorTest : AbstractAnnotationDescriptorResolveTest() {
abstract class AbstractCompileTimeConstantEvaluatorTest : AbstractAnnotationDescriptorResolveTest() {
// Test directives should look like [// val testedPropertyName: expectedValue]
fun doConstantTest(path: String) {
doTest(path) {
property, context ->
val compileTimeConstant = property.getCompileTimeInitializer()
val compileTimeConstant = property.compileTimeInitializer
if (compileTimeConstant is StringValue) {
"\\\"${compileTimeConstant.value}\\\""
} else {
@@ -65,9 +65,9 @@ public abstract class AbstractCompileTimeConstantEvaluatorTest : AbstractAnnotat
private fun evaluateInitializer(context: BindingContext, property: VariableDescriptor): CompileTimeConstant<*>? {
val propertyDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(property) as KtProperty
val compileTimeConstant = ConstantExpressionEvaluator(property.builtIns).evaluateExpression(
propertyDeclaration.getInitializer()!!,
propertyDeclaration.initializer!!,
DelegatingBindingTrace(context, "trace for evaluating compile time constant"),
property.getType()
property.type
)
return compileTimeConstant
}
@@ -34,7 +34,7 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.Variance
import java.io.File
abstract public class AbstractConstraintSystemTest() : KotlinLiteFixture() {
abstract class AbstractConstraintSystemTest() : KotlinLiteFixture() {
private var _typeResolver: TypeResolver? = null
private val typeResolver: TypeResolver
@@ -51,7 +51,7 @@ abstract public class AbstractConstraintSystemTest() : KotlinLiteFixture() {
override fun setUp() {
super.setUp()
_typeResolver = createContainerForTests(getProject(), KotlinTestUtils.createEmptyModule()).typeResolver
_typeResolver = createContainerForTests(project, KotlinTestUtils.createEmptyModule()).typeResolver
_testDeclarations = analyzeDeclarations()
}
@@ -70,10 +70,10 @@ abstract public class AbstractConstraintSystemTest() : KotlinLiteFixture() {
val psiFile = createPsiFile(null, fileName, loadFile(fileName))!!
val bindingContext = JvmResolveUtil.analyzeOneFileWithJavaIntegrationAndCheckForErrors(psiFile).bindingContext
return ConstraintSystemTestData(bindingContext, getProject(), typeResolver)
return ConstraintSystemTestData(bindingContext, project, typeResolver)
}
public fun doTest(filePath: String) {
fun doTest(filePath: String) {
val constraintsFile = File(filePath)
val constraintsFileText = constraintsFile.readLines()
@@ -114,9 +114,9 @@ abstract public class AbstractConstraintSystemTest() : KotlinLiteFixture() {
val resultingSubstitutor = system.resultingSubstitutor
val result = typeParameterDescriptors.map {
val parameterType = testDeclarations.getType(it.getName().asString())
val parameterType = testDeclarations.getType(it.name.asString())
val resultType = resultingSubstitutor.substitute(parameterType, Variance.INVARIANT)
"${it.getName()}=${resultType?.let { DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(it) }}"
"${it.name}=${resultType?.let { DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(it) }}"
}.joinToString("\n", prefix = "result:\n")
val boundsFile = File(filePath.replace("constraints", "bounds"))
@@ -34,7 +34,7 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.KotlinTypeImpl
import java.util.regex.Pattern
public class ConstraintSystemTestData(
class ConstraintSystemTestData(
context: BindingContext,
private val project: Project,
private val typeResolver: TypeResolver
@@ -46,17 +46,17 @@ public class ConstraintSystemTestData(
val functions = context.getSliceContents(BindingContext.FUNCTION)
functionFoo = findFunctionByName(functions.values, "foo")
val function = DescriptorToSourceUtils.descriptorToDeclaration(functionFoo) as KtFunction
val fooBody = function.getBodyExpression()
val fooBody = function.bodyExpression
scopeToResolveTypeParameters = context.get(BindingContext.LEXICAL_SCOPE, fooBody)!!
}
private fun findFunctionByName(functions: Collection<FunctionDescriptor>, name: String): FunctionDescriptor {
return functions.firstOrNull { it.getName().asString() == name } ?:
return functions.firstOrNull { it.name.asString() == name } ?:
throw AssertionError("Function ${name} is not declared")
}
fun getParameterDescriptor(name: String): TypeParameterDescriptor {
return functionFoo.getTypeParameters().firstOrNull { it.getName().asString() == name } ?:
return functionFoo.typeParameters.firstOrNull { it.name.asString() == name } ?:
throw AssertionError("Unsupported type parameter name: $name. You may add it to constraintSystem/declarations.kt")
}
@@ -28,7 +28,7 @@ import org.jetbrains.kotlin.resolve.CompilerEnvironment
import org.jetbrains.kotlin.resolve.jvm.JvmAnalyzerFacade
import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters
public fun createResolveSessionForFiles(
fun createResolveSessionForFiles(
project: Project,
syntheticFiles: Collection<KtFile>,
addBuiltIns: Boolean
@@ -36,24 +36,24 @@ import org.jetbrains.kotlin.types.typesApproximation.approximateCapturedTypesIfN
import java.io.File
import java.util.*
public class CapturedTypeApproximationTest() : KotlinLiteFixture() {
class CapturedTypeApproximationTest() : KotlinLiteFixture() {
override fun getTestDataPath() = "compiler/testData/capturedTypeApproximation/"
override fun createEnvironment(): KotlinCoreEnvironment = createEnvironmentWithMockJdk(ConfigurationKind.JDK_ONLY)
public fun doTest(filePath: String, vararg substitutions: String) {
fun doTest(filePath: String, vararg substitutions: String) {
assert(substitutions.size in 1..2) { "Captured type approximation test requires substitutions for (T) or (T, R)" }
val oneTypeVariable = substitutions.size == 1
val declarationsText = KotlinTestUtils.doLoadFile(File(getTestDataPath() + "/declarations.kt"))
val declarationsText = KotlinTestUtils.doLoadFile(File(testDataPath + "/declarations.kt"))
fun analyzeTestFile(testType: String) = run {
val test = declarationsText.replace("#TestType#", testType)
val testFile = KtPsiFactory(getProject()).createFile(test)
val testFile = KtPsiFactory(project).createFile(test)
val bindingContext = JvmResolveUtil.analyzeOneFileWithJavaIntegration(testFile).bindingContext
val functions = bindingContext.getSliceContents(BindingContext.FUNCTION)
val functionFoo = functions.values.firstOrNull { it.getName().asString() == "foo" } ?:
val functionFoo = functions.values.firstOrNull { it.name.asString() == "foo" } ?:
throw AssertionError("Function 'foo' is not declared")
Pair(bindingContext, functionFoo)
}
@@ -94,12 +94,12 @@ public class CapturedTypeApproximationTest() : KotlinLiteFixture() {
for ((index, testTypeWithUnsubstitutedTypeVars) in testTypes.withIndex()) {
val testType = createTestType(testTypeWithUnsubstitutedTypeVars)
val (bindingContext, functionFoo) = analyzeTestFile(testType)
val typeParameters = functionFoo.getTypeParameters()
val type = functionFoo.getReturnType()
val typeParameters = functionFoo.typeParameters
val type = functionFoo.returnType
appendln(testType)
if (bindingContext.getDiagnostics().noSuppression().any { it.getSeverity() == Severity.ERROR }) {
if (bindingContext.diagnostics.noSuppression().any { it.severity == Severity.ERROR }) {
appendln(" compiler error\n")
continue
}
@@ -107,7 +107,7 @@ public class CapturedTypeApproximationTest() : KotlinLiteFixture() {
val testSubstitutions = createTestSubstitutions(typeParameters)
for (testSubstitution in testSubstitutions) {
val typeSubstitutor = createTestSubstitutor(testSubstitution)
val typeWithCapturedType = typeSubstitutor.substituteWithoutApproximation(TypeProjectionImpl(INVARIANT, type!!))!!.getType()
val typeWithCapturedType = typeSubstitutor.substituteWithoutApproximation(TypeProjectionImpl(INVARIANT, type!!))!!.type
val (lower, upper) = approximateCapturedTypes(typeWithCapturedType)
val substitution =
@@ -116,7 +116,7 @@ public class CapturedTypeApproximationTest() : KotlinLiteFixture() {
append(" ")
for (typeParameter in testSubstitution.keys) {
if (testSubstitution.size > 1) append("${typeParameter.getName()} = ")
if (testSubstitution.size > 1) append("${typeParameter.name} = ")
append("${testSubstitution[typeParameter]}. ")
}
appendln("lower: $lower; upper: $upper; substitution: $substitution")
@@ -125,7 +125,7 @@ public class CapturedTypeApproximationTest() : KotlinLiteFixture() {
}
}
KotlinTestUtils.assertEqualsToFile(File(getTestDataPath() + "/" + filePath), result)
KotlinTestUtils.assertEqualsToFile(File(testDataPath + "/" + filePath), result)
}
private fun getTypePatternsForOneTypeVariable() = listOf("In<#T#>", "Out<#T#>", "Inv<#T#>", "Inv<in #T#>", "Inv<out #T#>")
@@ -170,31 +170,31 @@ public class CapturedTypeApproximationTest() : KotlinLiteFixture() {
return result
}
public fun testSimpleT() {
fun testSimpleT() {
doTest("simpleT.txt", "T");
}
public fun testNullableT() {
fun testNullableT() {
doTest("nullableT.txt", "T?")
}
public fun testUseSiteInT() {
fun testUseSiteInT() {
doTest("useSiteInT.txt", "in T");
}
public fun testUseSiteInNullableT() {
fun testUseSiteInNullableT() {
doTest("useSiteInNullableT.txt", "in T?");
}
public fun testUseSiteOutT() {
fun testUseSiteOutT() {
doTest("useSiteOutT.txt", "out T");
}
public fun testUseSiteOutNullableT() {
fun testUseSiteOutNullableT() {
doTest("useSiteOutNullableT.txt", "out T?");
}
public fun testTwoVariables() {
fun testTwoVariables() {
doTest("twoVariables.txt", "T", "R")
}
}
@@ -29,6 +29,6 @@ class TestScriptDefinition(
val parameters: List<ScriptParameter>
) : KotlinScriptDefinition {
override fun getScriptParameters(scriptDescriptor: ScriptDescriptor) = parameters
override fun isScript(file: PsiFile): Boolean = file.getName().endsWith(extension)
override fun isScript(file: PsiFile): Boolean = file.name.endsWith(extension)
override fun getScriptName(script: KtScript): Name = ScriptNameUtil.fileNameWithExtensionStripped(script, extension)
}
@@ -35,7 +35,7 @@ import org.jetbrains.kotlin.test.util.RecursiveDescriptorComparator
import java.io.File
import java.net.URLClassLoader
public abstract class AbstractLocalClassProtoTest : TestCaseWithTmpdir() {
abstract class AbstractLocalClassProtoTest : TestCaseWithTmpdir() {
protected fun doTest(filename: String) {
val source = File(filename)
LoadDescriptorUtil.compileKotlinToDirAndGetAnalysisResult(listOf(source), tmpdir, testRootDisposable, ConfigurationKind.ALL, false)
@@ -28,7 +28,7 @@ import org.jetbrains.kotlin.test.util.RecursiveDescriptorComparator
import java.io.File
import java.io.FileInputStream
public class BuiltInsSerializerTest : TestCaseWithTmpdir() {
class BuiltInsSerializerTest : TestCaseWithTmpdir() {
private fun doTest(fileName: String) {
val source = "compiler/testData/serialization/builtinsSerializer/$fileName"
BuiltInsSerializer(dependOnOldBuiltIns = true).serialize(
@@ -38,7 +38,7 @@ import org.jetbrains.kotlin.utils.KotlinJavascriptMetadataUtils
import org.jetbrains.kotlin.utils.sure
import java.io.File
public class KotlinJavascriptSerializerTest : TestCaseWithTmpdir() {
class KotlinJavascriptSerializerTest : TestCaseWithTmpdir() {
private final val MODULE_NAME = "module"
private final val BASE_DIR = "compiler/testData/serialization"
@@ -16,9 +16,9 @@
package org.jetbrains.kotlin.test
public enum class ConfigurationKind(
public val withRuntime: Boolean,
public val withReflection: Boolean
enum class ConfigurationKind(
val withRuntime: Boolean,
val withReflection: Boolean
) {
JDK_ONLY(withRuntime = false, withReflection = false),
NO_KOTLIN_REFLECT(withRuntime = true, withReflection = false),
@@ -26,17 +26,17 @@ import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
import java.io.File
public fun String.trimTrailingWhitespacesAndAddNewlineAtEOF(): String =
fun String.trimTrailingWhitespacesAndAddNewlineAtEOF(): String =
this.split('\n').map { it.trimEnd() }.joinToString(separator = "\n").let {
result -> if (result.endsWith("\n")) result else result + "\n"
}
public fun CodeInsightTestFixture.configureWithExtraFileAbs(path: String, vararg extraNameParts: String) {
fun CodeInsightTestFixture.configureWithExtraFileAbs(path: String, vararg extraNameParts: String) {
configureWithExtraFile(path, *extraNameParts, relativePaths = false)
}
public fun CodeInsightTestFixture.configureWithExtraFile(path: String, vararg extraNameParts: String = arrayOf(".Data"), relativePaths: Boolean = false) {
fun String.toFile(): File = if (relativePaths) File(getTestDataPath(), this) else File(this)
fun CodeInsightTestFixture.configureWithExtraFile(path: String, vararg extraNameParts: String = arrayOf(".Data"), relativePaths: Boolean = false) {
fun String.toFile(): File = if (relativePaths) File(testDataPath, this) else File(this)
val noExtensionPath = FileUtil.getNameWithoutExtension(path)
val extensions = arrayOf("kt", "java")
@@ -47,17 +47,17 @@ public fun CodeInsightTestFixture.configureWithExtraFile(path: String, vararg ex
configureByFiles(*(listOf(path) + extraPaths).toTypedArray())
}
public fun PsiFile.findElementByCommentPrefix(commentText: String): PsiElement? =
fun PsiFile.findElementByCommentPrefix(commentText: String): PsiElement? =
findElementsByCommentPrefix(commentText).keys.singleOrNull()
public fun PsiFile.findElementsByCommentPrefix(prefix: String): Map<PsiElement, String> {
fun PsiFile.findElementsByCommentPrefix(prefix: String): Map<PsiElement, String> {
var result = SmartFMap.emptyMap<PsiElement, String>()
accept(
object : KtTreeVisitorVoid() {
override fun visitComment(comment: PsiComment) {
val commentText = comment.getText()
val commentText = comment.text
if (commentText.startsWith(prefix)) {
val parent = comment.getParent()
val parent = comment.parent
val elementToAdd = when (parent) {
is KtDeclaration -> parent
is PsiMember -> parent
@@ -29,7 +29,7 @@ import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
import org.jetbrains.kotlin.types.expressions.FakeCallResolver
public fun createContainerForTests(project: Project, module: ModuleDescriptor): ContainerForTests {
fun createContainerForTests(project: Project, module: ModuleDescriptor): ContainerForTests {
return ContainerForTests(createContainer("Tests") {
configureModule(ModuleContext(module, project), JvmPlatform)
useInstance(LookupTracker.DO_NOTHING)
@@ -34,11 +34,11 @@ abstract class AbstractTypeBindingTest : KotlinLiteFixture() {
protected fun doTest(path: String) {
val testFile = File(path)
val testKtFile = loadJetFile(getProject(), testFile)
val testKtFile = loadJetFile(project, testFile)
val analyzeResult = JvmResolveUtil.analyzeFilesWithJavaIntegration(getProject(), listOf(testKtFile), environment)
val analyzeResult = JvmResolveUtil.analyzeFilesWithJavaIntegration(project, listOf(testKtFile), environment)
val testDeclaration = testKtFile.getDeclarations().last()!! as KtCallableDeclaration
val testDeclaration = testKtFile.declarations.last()!! as KtCallableDeclaration
val typeBinding = testDeclaration.createTypeBindingForReturnType(analyzeResult.bindingContext)
@@ -56,7 +56,7 @@ abstract class AbstractTypeBindingTest : KotlinLiteFixture() {
}
private fun removeLastComment(file: KtFile): String {
val fileText = file.getText()
val fileText = file.text
val lastIndex = fileText.indexOf("/*")
return if (lastIndex > 0) {
fileText.substring(0, lastIndex)
@@ -75,7 +75,7 @@ abstract class AbstractTypeBindingTest : KotlinLiteFixture() {
}
println("typeParameter: ${argument.typeParameterDescriptor.render()}")
val projection = argument.typeProjection.getProjectionKind().label.let {
val projection = argument.typeProjection.projectionKind.label.let {
if (it.isNotEmpty())
"$it "
else
@@ -83,9 +83,9 @@ abstract class AbstractTypeBindingTest : KotlinLiteFixture() {
}
print("typeProjection: ")
if (argument.typeProjection.isStarProjection())
if (argument.typeProjection.isStarProjection)
printlnWithNoIndent("*")
else printlnWithNoIndent("${projection}${argument.typeProjection.getType().render()}")
else printlnWithNoIndent("${projection}${argument.typeProjection.type.render()}")
print(argument.typeBinding)
return this
}
@@ -96,7 +96,7 @@ abstract class AbstractTypeBindingTest : KotlinLiteFixture() {
return this
}
println("psi: ${binding.psiElement.getText()}")
println("psi: ${binding.psiElement.text}")
println("type: ${binding.kotlinType.render()}")
printCollection(binding.getArgumentBindings()) {
@@ -24,4 +24,4 @@ import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
import org.jetbrains.kotlin.utils.Printer
fun KotlinBuiltIns.builtInPackageAsLexicalScope()
= LexicalScope.empty(getBuiltInsPackageScope().memberScopeAsImportingScope(), getBuiltInsModule())
= LexicalScope.empty(builtInsPackageScope.memberScopeAsImportingScope(), builtInsModule)