Serialization of flexible types supported

This commit is contained in:
Andrey Breslav
2014-10-11 01:10:39 +04:00
parent e76df4db11
commit 070a7d4d72
28 changed files with 1643 additions and 438 deletions
@@ -0,0 +1,7 @@
package test
import java.util.*
fun printStream() = System.out
fun list() = Collections.emptyList<String>()
fun array(a: Array<Int>) = Arrays.copyOf(a, 2)
@@ -0,0 +1,22 @@
import java.io.PrintStream
import java.util.ArrayList
import test.*
// To check that flexible types are loaded
class Inv<T>
fun <T> inv(t: T): Inv<T> = Inv<T>()
fun main(args: Array<String>) {
printStream().checkError()
val p: Inv<PrintStream> = inv(printStream())
val p1: Inv<PrintStream?> = inv(printStream())
list().size()
val l: Inv<List<String>> = inv(list())
val l1: Inv<MutableList<String>?> = inv(list())
val a = array(Array<Int>(1){0})
a[0] = 1
val a1: Inv<Array<Int>> = inv(a)
val a2: Inv<Array<out Int>?> = inv(a)
}
@@ -0,0 +1,8 @@
//ALLOW_AST_ACCESS
package test
import java.util.*
fun printStream() = System.out
fun list() = Collections.emptyList<String>()
fun array(a: Array<Int>) = Arrays.copyOf(a, 2)
@@ -0,0 +1,5 @@
package test
internal fun array(/*0*/ a: kotlin.Array<kotlin.Int>): kotlin.Array<(out) kotlin.Int!>!
internal fun list(): kotlin.(Mutable)List<kotlin.String!>!
internal fun printStream(): java.io.PrintStream!
File diff suppressed because it is too large Load Diff
@@ -128,6 +128,12 @@ public class CompileKotlinAgainstKotlinTestGenerated extends AbstractCompileKotl
doTest(fileName); doTest(fileName);
} }
@TestMetadata("PlatformTypes.A.kt")
public void testPlatformTypes() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/compileKotlinAgainstKotlin/PlatformTypes.A.kt");
doTest(fileName);
}
@TestMetadata("PropertyReference.A.kt") @TestMetadata("PropertyReference.A.kt")
public void testPropertyReference() throws Exception { public void testPropertyReference() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/compileKotlinAgainstKotlin/PropertyReference.A.kt"); String fileName = JetTestUtils.navigationMetadata("compiler/testData/compileKotlinAgainstKotlin/PropertyReference.A.kt");
@@ -4612,6 +4612,12 @@ public class LoadJavaTestGenerated extends AbstractLoadJavaTest {
doTestCompiledKotlin(fileName); doTestCompiledKotlin(fileName);
} }
@TestMetadata("platform.kt")
public void testPlatform() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/loadJava/compiledKotlin/type/platform.kt");
doTestCompiledKotlin(fileName);
}
@TestMetadata("String.kt") @TestMetadata("String.kt")
public void testString() throws Exception { public void testString() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/loadJava/compiledKotlin/type/String.kt"); String fileName = JetTestUtils.navigationMetadata("compiler/testData/loadJava/compiledKotlin/type/String.kt");
@@ -2826,6 +2826,12 @@ public class LazyResolveRecursiveComparingTestGenerated extends AbstractLazyReso
doTest(fileName); doTest(fileName);
} }
@TestMetadata("platform.kt")
public void testPlatform() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/loadJava/compiledKotlin/type/platform.kt");
doTest(fileName);
}
@TestMetadata("String.kt") @TestMetadata("String.kt")
public void testString() throws Exception { public void testString() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/loadJava/compiledKotlin/type/String.kt"); String fileName = JetTestUtils.navigationMetadata("compiler/testData/loadJava/compiledKotlin/type/String.kt");
@@ -32,15 +32,17 @@ import org.jetbrains.jet.storage.*
import java.util.HashSet import java.util.HashSet
import org.jetbrains.jet.lang.types.checker.JetTypeChecker import org.jetbrains.jet.lang.types.checker.JetTypeChecker
import org.jetbrains.jet.lang.resolve.java.PLATFORM_TYPES import org.jetbrains.jet.lang.resolve.java.PLATFORM_TYPES
import org.jetbrains.jet.lang.resolve.java.lazy.types.Flexibility.* import org.jetbrains.jet.lang.resolve.java.lazy.types.JavaTypeFlexibility.*
import org.jetbrains.jet.lang.descriptors.annotations.Annotations import org.jetbrains.jet.lang.descriptors.annotations.Annotations
import org.jetbrains.jet.lang.resolve.java.JvmAnnotationNames import org.jetbrains.jet.lang.resolve.java.JvmAnnotationNames
import org.jetbrains.jet.lang.resolve.name.FqName
import kotlin.platform.platformStatic
class LazyJavaTypeResolver( class LazyJavaTypeResolver(
private val c: LazyJavaResolverContext, private val c: LazyJavaResolverContext,
private val typeParameterResolver: TypeParameterResolver private val typeParameterResolver: TypeParameterResolver
) { ) {
public fun transformJavaType(javaType: JavaType, attr: JavaTypeAttributes): JetType { public fun transformJavaType(javaType: JavaType, attr: JavaTypeAttributes): JetType {
return when (javaType) { return when (javaType) {
is JavaPrimitiveType -> { is JavaPrimitiveType -> {
@@ -49,9 +51,13 @@ class LazyJavaTypeResolver(
assert(jetType != null, "Primitive type is not found: " + canonicalText) assert(jetType != null, "Primitive type is not found: " + canonicalText)
jetType!! jetType!!
} }
is JavaClassifierType -> if (PLATFORM_TYPES && attr.allowFlexible && attr.howThisTypeIsUsed != SUPERTYPE) is JavaClassifierType ->
LazyFlexibleJavaClassifierType(javaType, attr) if (PLATFORM_TYPES && attr.allowFlexible && attr.howThisTypeIsUsed != SUPERTYPE)
else LazyJavaClassifierType(javaType, attr) FlexibleJavaClassifierTypeCapabilities.create(
LazyJavaClassifierType(javaType, attr.toFlexible(FLEXIBLE_LOWER_BOUND)),
LazyJavaClassifierType(javaType, attr.toFlexible(FLEXIBLE_UPPER_BOUND))
)
else LazyJavaClassifierType(javaType, attr)
is JavaArrayType -> transformArrayType(javaType, attr) is JavaArrayType -> transformArrayType(javaType, attr)
else -> throw UnsupportedOperationException("Unsupported type: " + javaType) else -> throw UnsupportedOperationException("Unsupported type: " + javaType)
} }
@@ -63,7 +69,7 @@ class LazyJavaTypeResolver(
val jetType = JavaToKotlinClassMap.getInstance().mapPrimitiveKotlinClass("[" + javaComponentType.getCanonicalText()) val jetType = JavaToKotlinClassMap.getInstance().mapPrimitiveKotlinClass("[" + javaComponentType.getCanonicalText())
if (jetType != null) { if (jetType != null) {
return if (PLATFORM_TYPES && attr.allowFlexible) return if (PLATFORM_TYPES && attr.allowFlexible)
FlexibleJavaClassifierType.create(jetType, TypeUtils.makeNullable(jetType)) FlexibleJavaClassifierTypeCapabilities.create(jetType, TypeUtils.makeNullable(jetType))
else TypeUtils.makeNullableAsSpecified(jetType, !attr.isMarkedNotNull) else TypeUtils.makeNullableAsSpecified(jetType, !attr.isMarkedNotNull)
} }
} }
@@ -74,7 +80,7 @@ class LazyJavaTypeResolver(
val componentType = transformJavaType(javaComponentType, howArgumentTypeIsUsed.toAttributes(attr.allowFlexible)) val componentType = transformJavaType(javaComponentType, howArgumentTypeIsUsed.toAttributes(attr.allowFlexible))
val result = KotlinBuiltIns.getInstance().getArrayType(projectionKind, componentType) val result = KotlinBuiltIns.getInstance().getArrayType(projectionKind, componentType)
return if (PLATFORM_TYPES && attr.allowFlexible) return if (PLATFORM_TYPES && attr.allowFlexible)
FlexibleJavaClassifierType.create( FlexibleJavaClassifierTypeCapabilities.create(
KotlinBuiltIns.getInstance().getArrayType(INVARIANT, componentType), KotlinBuiltIns.getInstance().getArrayType(INVARIANT, componentType),
TypeUtils.makeNullable( TypeUtils.makeNullable(
KotlinBuiltIns.getInstance().getArrayType(OUT_VARIANCE, componentType) KotlinBuiltIns.getInstance().getArrayType(OUT_VARIANCE, componentType)
@@ -268,67 +274,60 @@ class LazyJavaTypeResolver(
override fun getAnnotations() = attr.annotations override fun getAnnotations() = attr.annotations
} }
public open class FlexibleJavaClassifierType protected ( public object FlexibleJavaClassifierTypeCapabilities : FlexibleTypeCapabilities {
lowerBound: JetType, platformStatic fun create(lowerBound: JetType, upperBound: JetType) = DelegatingFlexibleType.create(lowerBound, upperBound, this)
upperBound: JetType
) : DelegatingFlexibleType(lowerBound, upperBound), CustomTypeVariable, Specificity { override val id: String get() = "kotlin.jvm.PlatformType"
public class object {
public fun create(lowerBound: JetType, upperBound: JetType): JetType { override fun <T : TypeCapability> getCapability(capabilityClass: Class<T>, jetType: JetType, flexibility: Flexibility): T? {
if (lowerBound == upperBound) return lowerBound if (capabilityClass.isAssignableFrom(javaClass<Impl>()))
return FlexibleJavaClassifierType(lowerBound, upperBound) [suppress("UNCHECKED_CAST")]
return Impl(flexibility) as T
else return null
}
private class Impl(val flexibility: Flexibility) : CustomTypeVariable, Specificity {
private val lowerBound: JetType get() = flexibility.getLowerBound()
private val upperBound: JetType get() = flexibility.getUpperBound()
override val isTypeVariable: Boolean = lowerBound.getConstructor() == upperBound.getConstructor()
&& lowerBound.getConstructor().getDeclarationDescriptor() is TypeParameterDescriptor
override val typeParameterDescriptor: TypeParameterDescriptor? =
if (isTypeVariable) lowerBound.getConstructor().getDeclarationDescriptor() as TypeParameterDescriptor else null
override fun substitutionResult(replacement: JetType): JetType {
return if (replacement.isFlexible()) replacement
else create(TypeUtils.makeNotNullable(replacement), TypeUtils.makeNullable(replacement))
} }
}
override fun create(lowerBound: JetType, upperBound: JetType): JetType { override fun getSpecificityRelationTo(otherType: JetType): Specificity.Relation {
return FlexibleJavaClassifierType.create(lowerBound, upperBound) // For primitive types we have to take care of the case when there are two overloaded methods like
} // foo(int) and foo(Integer)
// if we do not discriminate one of them, any call to foo(kotlin.Int) will result in overload resolution ambiguity
override val isTypeVariable: Boolean = lowerBound.getConstructor() == upperBound.getConstructor() // so, for such cases, we discriminate Integer in favour of int
&& lowerBound.getConstructor().getDeclarationDescriptor() is TypeParameterDescriptor if (!KotlinBuiltIns.getInstance().isPrimitiveType(otherType) || !KotlinBuiltIns.getInstance().isPrimitiveType(lowerBound)) {
return Specificity.Relation.DONT_KNOW
override val typeParameterDescriptor: TypeParameterDescriptor? = if (isTypeVariable) lowerBound.getConstructor().getDeclarationDescriptor() as TypeParameterDescriptor else null }
// Int! >< Int?
override fun substitutionResult(replacement: JetType): JetType { if (otherType.isFlexible()) return Specificity.Relation.DONT_KNOW
return if (replacement.isFlexible()) replacement // Int? >< Int!
else FlexibleJavaClassifierType(TypeUtils.makeNotNullable(replacement), TypeUtils.makeNullable(replacement)) if (otherType.isNullable()) return Specificity.Relation.DONT_KNOW
} // Int! lessSpecific Int
return Specificity.Relation.LESS_SPECIFIC
override fun getSpecificityRelationTo(otherType: JetType): Specificity.Relation {
// For primitive types we have to take care of the case when there are two overloaded methods like
// foo(int) and foo(Integer)
// if we do not discriminate one of them, any call to foo(kotlin.Int) will result in overload resolution ambiguity
// so, for such cases, we discriminate Integer in favour of int
if (!KotlinBuiltIns.getInstance().isPrimitiveType(otherType) || !KotlinBuiltIns.getInstance().isPrimitiveType(getLowerBound())) {
return Specificity.Relation.DONT_KNOW
} }
// Int! >< Int?
if (otherType.isFlexible()) return Specificity.Relation.DONT_KNOW
// Int? >< Int!
if (otherType.isNullable()) return Specificity.Relation.DONT_KNOW
// Int! lessSpecific Int
return Specificity.Relation.LESS_SPECIFIC
} }
} }
/*
* For a java type like java.util.List<Foo>
* lowerBound = MutableList<Foo>
* upperBound = List<Foo?>
*/
private inner class LazyFlexibleJavaClassifierType(
javaType: JavaClassifierType,
attr: JavaTypeAttributes
) : FlexibleJavaClassifierType(
LazyJavaClassifierType(javaType, attr.toFlexible(FLEXIBLE_LOWER_BOUND)),
LazyJavaClassifierType(javaType, attr.toFlexible(FLEXIBLE_UPPER_BOUND))
)
} }
trait JavaTypeAttributes { trait JavaTypeAttributes {
val howThisTypeIsUsed: TypeUsage val howThisTypeIsUsed: TypeUsage
val howThisTypeIsUsedAccordingToAnnotations: TypeUsage val howThisTypeIsUsedAccordingToAnnotations: TypeUsage
val isMarkedNotNull: Boolean val isMarkedNotNull: Boolean
val flexibility: Flexibility val flexibility: JavaTypeFlexibility
get() = INFLEXIBLE get() = INFLEXIBLE
val allowFlexible: Boolean val allowFlexible: Boolean
get() = true get() = true
@@ -337,7 +336,7 @@ trait JavaTypeAttributes {
fun JavaTypeAttributes.isFlexible() = flexibility != INFLEXIBLE fun JavaTypeAttributes.isFlexible() = flexibility != INFLEXIBLE
enum class Flexibility { enum class JavaTypeFlexibility {
INFLEXIBLE INFLEXIBLE
FLEXIBLE_UPPER_BOUND FLEXIBLE_UPPER_BOUND
FLEXIBLE_LOWER_BOUND FLEXIBLE_LOWER_BOUND
@@ -375,7 +374,7 @@ fun TypeUsage.toAttributes(allowFlexible: Boolean = true) = object : JavaTypeAtt
override val annotations: Annotations = Annotations.EMPTY override val annotations: Annotations = Annotations.EMPTY
} }
fun JavaTypeAttributes.toFlexible(flexibility: Flexibility) = fun JavaTypeAttributes.toFlexible(flexibility: JavaTypeFlexibility) =
object : JavaTypeAttributes by this { object : JavaTypeAttributes by this {
override val flexibility = flexibility override val flexibility = flexibility
} }
@@ -102,7 +102,7 @@ public class SingleAbstractMethodUtils {
if (fixedProjections == null) return null; if (fixedProjections == null) return null;
if (JavaPackage.getPLATFORM_TYPES() && !isSamConstructor) { if (JavaPackage.getPLATFORM_TYPES() && !isSamConstructor) {
return LazyJavaTypeResolver.FlexibleJavaClassifierType.OBJECT$.create(fixedProjections, TypeUtils.makeNullable(fixedProjections)); return LazyJavaTypeResolver.FlexibleJavaClassifierTypeCapabilities.create(fixedProjections, TypeUtils.makeNullable(fixedProjections));
} }
return TypeUtils.makeNullableAsSpecified(fixedProjections, !isSamConstructor && samType.isNullable()); return TypeUtils.makeNullableAsSpecified(fixedProjections, !isSamConstructor && samType.isNullable());
@@ -30,4 +30,4 @@ public class DeserializationGlobalContextForJava(
constantLoader: ConstantDescriptorLoader, constantLoader: ConstantDescriptorLoader,
packageFragmentProvider: LazyJavaPackageFragmentProvider packageFragmentProvider: LazyJavaPackageFragmentProvider
) : DeserializationGlobalContext(storageManager, moduleDescriptor, classDataFinder, annotationLoader, ) : DeserializationGlobalContext(storageManager, moduleDescriptor, classDataFinder, annotationLoader,
constantLoader, packageFragmentProvider) constantLoader, packageFragmentProvider, JavaFlexibleTypeCapabilitiesDeserializer)
@@ -0,0 +1,32 @@
/*
* 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.
*/
package org.jetbrains.jet.lang.resolve.kotlin
import org.jetbrains.jet.descriptors.serialization.FlexibleTypeCapabilitiesDeserializer
import org.jetbrains.jet.lang.resolve.name.FqName
import org.jetbrains.jet.lang.resolve.java.lazy.types.LazyJavaTypeResolver
import org.jetbrains.jet.lang.types.FlexibleTypeCapabilities
import org.jetbrains.jet.lang.types
object JavaFlexibleTypeCapabilitiesDeserializer : FlexibleTypeCapabilitiesDeserializer {
override fun capabilitiesById(id: String): FlexibleTypeCapabilities? {
return if (id == LazyJavaTypeResolver.FlexibleJavaClassifierTypeCapabilities.id)
LazyJavaTypeResolver.FlexibleJavaClassifierTypeCapabilities
else null
}
}
@@ -80,11 +80,14 @@ public class CommonSupertypes {
boolean hasFlexible = false; boolean hasFlexible = false;
List<JetType> upper = new ArrayList<JetType>(types.size()); List<JetType> upper = new ArrayList<JetType>(types.size());
List<JetType> lower = new ArrayList<JetType>(types.size()); List<JetType> lower = new ArrayList<JetType>(types.size());
Set<FlexibleTypeCapabilities> capabilities = new LinkedHashSet<FlexibleTypeCapabilities>();
for (JetType type : types) { for (JetType type : types) {
if (TypesPackage.isFlexible(type)) { if (TypesPackage.isFlexible(type)) {
hasFlexible = true; hasFlexible = true;
upper.add(TypesPackage.flexibility(type).getUpperBound()); Flexibility flexibility = TypesPackage.flexibility(type);
lower.add(TypesPackage.flexibility(type).getLowerBound()); upper.add(flexibility.getUpperBound());
lower.add(flexibility.getLowerBound());
capabilities.add(flexibility.getExtraCapabilities());
} }
else { else {
upper.add(type); upper.add(type);
@@ -95,7 +98,8 @@ public class CommonSupertypes {
if (!hasFlexible) return commonSuperTypeForInflexible(types, recursionDepth, maxDepth); if (!hasFlexible) return commonSuperTypeForInflexible(types, recursionDepth, maxDepth);
return DelegatingFlexibleType.OBJECT$.create( return DelegatingFlexibleType.OBJECT$.create(
commonSuperTypeForInflexible(lower, recursionDepth, maxDepth), commonSuperTypeForInflexible(lower, recursionDepth, maxDepth),
commonSuperTypeForInflexible(upper, recursionDepth, maxDepth) commonSuperTypeForInflexible(upper, recursionDepth, maxDepth),
KotlinPackage.single(capabilities) // mixing different capabilities is not supported
); );
} }
@@ -16,6 +16,7 @@
package org.jetbrains.jet.lang.types; package org.jetbrains.jet.lang.types;
import kotlin.jvm.KotlinSignature;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.ReadOnly; import org.jetbrains.annotations.ReadOnly;
@@ -45,6 +46,7 @@ public interface JetType extends Annotated {
@Override @Override
boolean equals(Object other); boolean equals(Object other);
@KotlinSignature("fun <T : TypeCapability> getCapability(capabilityClass: Class<T>): T?")
@Nullable @Nullable
<T extends TypeCapability> T getCapability(@NotNull Class<T> capabilityClass); <T extends TypeCapability> T getCapability(@NotNull Class<T> capabilityClass);
} }
@@ -156,15 +156,17 @@ public class TypeSubstitutor {
JetType type = originalProjection.getType(); JetType type = originalProjection.getType();
Variance originalProjectionKind = originalProjection.getProjectionKind(); Variance originalProjectionKind = originalProjection.getProjectionKind();
if (TypesPackage.isFlexible(type) && !TypesPackage.isCustomTypeVariable(type)) { if (TypesPackage.isFlexible(type) && !TypesPackage.isCustomTypeVariable(type)) {
Flexibility flexibility = TypesPackage.flexibility(type);
TypeProjection substitutedLower = TypeProjection substitutedLower =
unsafeSubstitute(new TypeProjectionImpl(originalProjectionKind, TypesPackage.flexibility(type).getLowerBound()), recursionDepth + 1); unsafeSubstitute(new TypeProjectionImpl(originalProjectionKind, flexibility.getLowerBound()), recursionDepth + 1);
TypeProjection substitutedUpper = TypeProjection substitutedUpper =
unsafeSubstitute(new TypeProjectionImpl(originalProjectionKind, TypesPackage.flexibility(type).getUpperBound()), recursionDepth + 1); unsafeSubstitute(new TypeProjectionImpl(originalProjectionKind, flexibility.getUpperBound()), recursionDepth + 1);
// todo: projection kind is neglected // todo: projection kind is neglected
return new TypeProjectionImpl(originalProjectionKind, return new TypeProjectionImpl(originalProjectionKind,
DelegatingFlexibleType.OBJECT$.create( DelegatingFlexibleType.OBJECT$.create(
substitutedLower.getType(), substitutedLower.getType(),
substitutedUpper.getType() substitutedUpper.getType(),
flexibility.getExtraCapabilities()
) )
); );
} }
@@ -18,13 +18,25 @@ package org.jetbrains.jet.lang.types
import org.jetbrains.jet.lang.types.checker.JetTypeChecker import org.jetbrains.jet.lang.types.checker.JetTypeChecker
import org.jetbrains.jet.lang.types.Approximation.DataFlowExtras import org.jetbrains.jet.lang.types.Approximation.DataFlowExtras
import org.jetbrains.kotlin.util.printAndReturn import org.jetbrains.jet.lang.resolve.name.FqName
public trait FlexibleTypeCapabilities {
fun <T: TypeCapability> getCapability(capabilityClass: Class<T>, jetType: JetType, flexibility: Flexibility): T?
val id: String
object NONE : FlexibleTypeCapabilities {
override fun <T : TypeCapability> getCapability(capabilityClass: Class<T>, jetType: JetType, flexibility: Flexibility): T? = null
override val id: String get() = "NONE"
}
}
public trait Flexibility : TypeCapability { public trait Flexibility : TypeCapability {
// lowerBound is a subtype of upperBound // lowerBound is a subtype of upperBound
public fun getUpperBound(): JetType public fun getUpperBound(): JetType
public fun getLowerBound(): JetType public fun getLowerBound(): JetType
public fun getExtraCapabilities(): FlexibleTypeCapabilities
} }
public fun JetType.isFlexible(): Boolean = this.getCapability(javaClass<Flexibility>()) != null public fun JetType.isFlexible(): Boolean = this.getCapability(javaClass<Flexibility>()) != null
@@ -104,12 +116,13 @@ public fun JetType.getApproximationTo(
public open class DelegatingFlexibleType protected ( public open class DelegatingFlexibleType protected (
private val _lowerBound: JetType, private val _lowerBound: JetType,
private val _upperBound: JetType private val _upperBound: JetType,
private val _extraCapabilities: FlexibleTypeCapabilities
) : DelegatingType(), NullAwareness, Flexibility, Approximation { ) : DelegatingType(), NullAwareness, Flexibility, Approximation {
class object { class object {
public fun create(lowerBound: JetType, upperBound: JetType): JetType { fun create(lowerBound: JetType, upperBound: JetType, extraCapabilities: FlexibleTypeCapabilities): JetType {
if (lowerBound == upperBound) return lowerBound if (lowerBound == upperBound) return lowerBound
return DelegatingFlexibleType(lowerBound, upperBound) return DelegatingFlexibleType(lowerBound, upperBound, extraCapabilities)
} }
} }
@@ -125,12 +138,17 @@ public open class DelegatingFlexibleType protected (
override fun getUpperBound(): JetType = _upperBound override fun getUpperBound(): JetType = _upperBound
override fun getLowerBound(): JetType = _lowerBound override fun getLowerBound(): JetType = _lowerBound
protected open fun create(lowerBound: JetType, upperBound: JetType): JetType { override fun getExtraCapabilities() = _extraCapabilities
return DelegatingFlexibleType.create(lowerBound, upperBound)
override fun <T : TypeCapability> getCapability(capabilityClass: Class<T>): T? {
return getExtraCapabilities().getCapability(capabilityClass, this, this) ?: super<DelegatingType>.getCapability(capabilityClass)
} }
override fun makeNullableAsSpecified(nullable: Boolean): JetType { override fun makeNullableAsSpecified(nullable: Boolean): JetType {
return create(TypeUtils.makeNullableAsSpecified(_lowerBound, nullable), TypeUtils.makeNullableAsSpecified(_upperBound, nullable)) return create(
TypeUtils.makeNullableAsSpecified(_lowerBound, nullable),
TypeUtils.makeNullableAsSpecified(_upperBound, nullable),
getExtraCapabilities())
} }
override fun approximateToExpectedType(expectedType: JetType, dataFlowExtras: Approximation.DataFlowExtras): Approximation.Info? { override fun approximateToExpectedType(expectedType: JetType, dataFlowExtras: Approximation.DataFlowExtras): Approximation.Info? {
@@ -84,6 +84,7 @@ class BuiltinsPackageFragment extends PackageFragmentDescriptorImpl {
storageManager, module, builtInsClassDataFinder, storageManager, module, builtInsClassDataFinder,
// TODO: support annotations // TODO: support annotations
AnnotationLoader.UNSUPPORTED, ConstantLoader.UNSUPPORTED, packageFragmentProvider, AnnotationLoader.UNSUPPORTED, ConstantLoader.UNSUPPORTED, packageFragmentProvider,
FlexibleTypeCapabilitiesDeserializer.ThrowException.INSTANCE$,
new ClassDeserializer(storageManager, builtInsClassDataFinder), nameResolver new ClassDeserializer(storageManager, builtInsClassDataFinder), nameResolver
); );
members = new DeserializedPackageMemberScope(this, loadPackage(), deserializationContext, classNames); members = new DeserializedPackageMemberScope(this, loadPackage(), deserializationContext, classNames);
+17 -2
View File
@@ -20,14 +20,15 @@ option java_outer_classname = "ProtoBuf";
option optimize_for = LITE_RUNTIME; // Smaller runtime option optimize_for = LITE_RUNTIME; // Smaller runtime
option java_generic_services = false; // Less code option java_generic_services = false; // Less code
message SimpleNameTable { message StringTable {
repeated string name = 1; repeated string string = 1;
} }
message QualifiedNameTable { message QualifiedNameTable {
message QualifiedName { message QualifiedName {
optional int32 parent_qualified_name = 1 [default = -1]; optional int32 parent_qualified_name = 1 [default = -1];
// Id in the StringTable
required int32 short_name = 2; required int32 short_name = 2;
optional Kind kind = 3 [default = PACKAGE]; optional Kind kind = 3 [default = PACKAGE];
@@ -68,10 +69,21 @@ message Type {
repeated Argument argument = 2; repeated Argument argument = 2;
optional bool nullable = 3 [default = false]; optional bool nullable = 3 [default = false];
// Id in the StringTable
// If this field is set, the type is flexible.
// All the fields above represent its lower bound, and flexible_upper_bound must be set and represents its upper bound.
optional int32 flexible_type_capabilities_id = 4;
// While such an "indirect" encoding helps backwards compatibility with pre-flexible-types versions of this format,
// we use it mainly to save space: having a special mandatory tag on each an every type just to have an option
// to represent flexible types is too many wasted bytes.
optional Type flexible_upper_bound = 5;
} }
message TypeParameter { message TypeParameter {
required int32 id = 1; required int32 id = 1;
// Id in the StringTable
required int32 name = 2; required int32 name = 2;
optional bool reified = 3 [default = false]; optional bool reified = 3 [default = false];
@@ -188,6 +200,7 @@ message Callable {
optional Type receiver_type = 5; optional Type receiver_type = 5;
// Id in the StringTable
required int32 name = 6; required int32 name = 6;
message ValueParameter { message ValueParameter {
@@ -196,6 +209,8 @@ message Callable {
has_annotations has_annotations
*/ */
optional int32 flags = 1; optional int32 flags = 1;
// Id in the StringTable
required int32 name = 2; required int32 name = 2;
required Type type = 3; required Type type = 3;
optional Type vararg_element_type = 4; optional Type vararg_element_type = 4;
@@ -20,10 +20,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.descriptors.*;
import org.jetbrains.jet.lang.descriptors.annotations.Annotated; import org.jetbrains.jet.lang.descriptors.annotations.Annotated;
import org.jetbrains.jet.lang.resolve.DescriptorFactory; import org.jetbrains.jet.lang.resolve.DescriptorFactory;
import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.*;
import org.jetbrains.jet.lang.types.TypeConstructor;
import org.jetbrains.jet.lang.types.TypeProjection;
import org.jetbrains.jet.lang.types.Variance;
import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns; import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
import org.jetbrains.jet.renderer.DescriptorRenderer; import org.jetbrains.jet.renderer.DescriptorRenderer;
@@ -343,6 +340,8 @@ public class DescriptorSerializer {
public ProtoBuf.Type.Builder type(@NotNull JetType type) { public ProtoBuf.Type.Builder type(@NotNull JetType type) {
assert !type.isError() : "Can't serialize error types: " + type; // TODO assert !type.isError() : "Can't serialize error types: " + type; // TODO
if (TypesPackage.isFlexible(type)) return flexibleType(type);
ProtoBuf.Type.Builder builder = ProtoBuf.Type.newBuilder(); ProtoBuf.Type.Builder builder = ProtoBuf.Type.newBuilder();
builder.setConstructor(typeConstructor(type.getConstructor())); builder.setConstructor(typeConstructor(type.getConstructor()));
@@ -359,6 +358,18 @@ public class DescriptorSerializer {
return builder; return builder;
} }
private ProtoBuf.Type.Builder flexibleType(@NotNull JetType type) {
Flexibility flexibility = TypesPackage.flexibility(type);
ProtoBuf.Type.Builder builder = type(flexibility.getLowerBound());
builder.setFlexibleTypeCapabilitiesId(nameTable.getStringIndex(flexibility.getExtraCapabilities().getId()));
builder.setFlexibleUpperBound(type(flexibility.getUpperBound()));
return builder;
}
@NotNull @NotNull
private ProtoBuf.Type.Argument.Builder typeArgument(@NotNull TypeProjection typeProjection) { private ProtoBuf.Type.Argument.Builder typeArgument(@NotNull TypeProjection typeProjection) {
ProtoBuf.Type.Argument.Builder builder = ProtoBuf.Type.Argument.newBuilder(); ProtoBuf.Type.Argument.Builder builder = ProtoBuf.Type.Argument.newBuilder();
@@ -0,0 +1,30 @@
/*
* 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.
*/
package org.jetbrains.jet.descriptors.serialization
import org.jetbrains.jet.lang.resolve.name.FqName
import org.jetbrains.jet.lang.types.FlexibleTypeCapabilities
trait FlexibleTypeCapabilitiesDeserializer {
object ThrowException : FlexibleTypeCapabilitiesDeserializer {
override fun capabilitiesById(id: String): FlexibleTypeCapabilities? {
throw IllegalArgumentException("Capabilities not found by ThrowException manager: $id")
}
}
fun capabilitiesById(id: String): FlexibleTypeCapabilities?
}
@@ -26,20 +26,20 @@ import org.jetbrains.jet.lang.resolve.name.Name;
import static org.jetbrains.jet.descriptors.serialization.ProtoBuf.QualifiedNameTable.QualifiedName; import static org.jetbrains.jet.descriptors.serialization.ProtoBuf.QualifiedNameTable.QualifiedName;
public class NameResolver { public class NameResolver {
private final ProtoBuf.SimpleNameTable simpleNames; private final ProtoBuf.StringTable strings;
private final ProtoBuf.QualifiedNameTable qualifiedNames; private final ProtoBuf.QualifiedNameTable qualifiedNames;
public NameResolver( public NameResolver(
@NotNull ProtoBuf.SimpleNameTable simpleNames, @NotNull ProtoBuf.StringTable strings,
@NotNull ProtoBuf.QualifiedNameTable qualifiedNames @NotNull ProtoBuf.QualifiedNameTable qualifiedNames
) { ) {
this.simpleNames = simpleNames; this.strings = strings;
this.qualifiedNames = qualifiedNames; this.qualifiedNames = qualifiedNames;
} }
@NotNull @NotNull
public ProtoBuf.SimpleNameTable getSimpleNameTable() { public ProtoBuf.StringTable getStringTable() {
return simpleNames; return strings;
} }
@NotNull @NotNull
@@ -47,9 +47,14 @@ public class NameResolver {
return qualifiedNames; return qualifiedNames;
} }
@NotNull
public String getString(int index) {
return strings.getString(index);
}
@NotNull @NotNull
public Name getName(int index) { public Name getName(int index) {
String name = simpleNames.getName(index); String name = strings.getString(index);
return Name.guess(name); return Name.guess(name);
} }
@@ -89,7 +94,7 @@ public class NameResolver {
result = parentProto; result = parentProto;
} }
} }
sb.append(simpleNames.getName(fqNameProto.getShortName())); sb.append(strings.getString(fqNameProto.getShortName()));
return result; return result;
} }
@@ -30,7 +30,7 @@ public class NameSerializationUtil {
@NotNull @NotNull
public static NameResolver deserializeNameResolver(@NotNull InputStream in) { public static NameResolver deserializeNameResolver(@NotNull InputStream in) {
try { try {
ProtoBuf.SimpleNameTable simpleNames = ProtoBuf.SimpleNameTable.parseDelimitedFrom(in); ProtoBuf.StringTable simpleNames = ProtoBuf.StringTable.parseDelimitedFrom(in);
ProtoBuf.QualifiedNameTable qualifiedNames = ProtoBuf.QualifiedNameTable.parseDelimitedFrom(in); ProtoBuf.QualifiedNameTable qualifiedNames = ProtoBuf.QualifiedNameTable.parseDelimitedFrom(in);
return new NameResolver(simpleNames, qualifiedNames); return new NameResolver(simpleNames, qualifiedNames);
} }
@@ -40,20 +40,20 @@ public class NameSerializationUtil {
} }
public static void serializeNameResolver(@NotNull OutputStream out, @NotNull NameResolver nameResolver) { public static void serializeNameResolver(@NotNull OutputStream out, @NotNull NameResolver nameResolver) {
serializeNameTable(out, nameResolver.getSimpleNameTable(), nameResolver.getQualifiedNameTable()); serializeNameTable(out, nameResolver.getStringTable(), nameResolver.getQualifiedNameTable());
} }
public static void serializeNameTable(@NotNull OutputStream out, @NotNull NameTable nameTable) { public static void serializeNameTable(@NotNull OutputStream out, @NotNull NameTable nameTable) {
serializeNameTable(out, toSimpleNameTable(nameTable), toQualifiedNameTable(nameTable)); serializeNameTable(out, toStringTable(nameTable), toQualifiedNameTable(nameTable));
} }
private static void serializeNameTable( private static void serializeNameTable(
@NotNull OutputStream out, @NotNull OutputStream out,
@NotNull ProtoBuf.SimpleNameTable simpleNameTable, @NotNull ProtoBuf.StringTable stringTable,
@NotNull ProtoBuf.QualifiedNameTable qualifiedNameTable @NotNull ProtoBuf.QualifiedNameTable qualifiedNameTable
) { ) {
try { try {
simpleNameTable.writeDelimitedTo(out); stringTable.writeDelimitedTo(out);
qualifiedNameTable.writeDelimitedTo(out); qualifiedNameTable.writeDelimitedTo(out);
} }
catch (IOException e) { catch (IOException e) {
@@ -62,10 +62,10 @@ public class NameSerializationUtil {
} }
@NotNull @NotNull
public static ProtoBuf.SimpleNameTable toSimpleNameTable(@NotNull NameTable nameTable) { public static ProtoBuf.StringTable toStringTable(@NotNull NameTable nameTable) {
ProtoBuf.SimpleNameTable.Builder simpleNames = ProtoBuf.SimpleNameTable.newBuilder(); ProtoBuf.StringTable.Builder simpleNames = ProtoBuf.StringTable.newBuilder();
for (String simpleName : nameTable.getSimpleNames()) { for (String simpleName : nameTable.getStrings()) {
simpleNames.addName(simpleName); simpleNames.addString(simpleName);
} }
return simpleNames.build(); return simpleNames.build();
} }
@@ -81,6 +81,6 @@ public class NameSerializationUtil {
@NotNull @NotNull
public static NameResolver createNameResolver(@NotNull NameTable table) { public static NameResolver createNameResolver(@NotNull NameTable table) {
return new NameResolver(toSimpleNameTable(table), toQualifiedNameTable(table)); return new NameResolver(toStringTable(table), toQualifiedNameTable(table));
} }
} }
@@ -46,15 +46,15 @@ public class NameTable {
} }
}; };
private final Interner<String> simpleNames = new Interner<String>(); private final Interner<String> strings = new Interner<String>();
private final Interner<QualifiedName.Builder> qualifiedNames = new Interner<QualifiedName.Builder>(QUALIFIED_NAME_BUILDER_HASHING); private final Interner<QualifiedName.Builder> qualifiedNames = new Interner<QualifiedName.Builder>(QUALIFIED_NAME_BUILDER_HASHING);
public NameTable() { public NameTable() {
} }
@NotNull @NotNull
public List<String> getSimpleNames() { public List<String> getStrings() {
return simpleNames.getAllInternedObjects(); return strings.getAllInternedObjects();
} }
@NotNull @NotNull
@@ -63,7 +63,11 @@ public class NameTable {
} }
public int getSimpleNameIndex(@NotNull Name name) { public int getSimpleNameIndex(@NotNull Name name) {
return simpleNames.intern(name.asString()); return getStringIndex(name.asString());
}
public int getStringIndex(@NotNull String string) {
return strings.intern(string);
} }
public int getFqNameIndex(@NotNull ClassOrPackageFragmentDescriptor descriptor) { public int getFqNameIndex(@NotNull ClassOrPackageFragmentDescriptor descriptor) {
File diff suppressed because it is too large Load Diff
@@ -100,6 +100,18 @@ public class TypeDeserializer {
@NotNull @NotNull
public JetType type(@NotNull ProtoBuf.Type proto) { public JetType type(@NotNull ProtoBuf.Type proto) {
if (proto.hasFlexibleTypeCapabilitiesId()) {
String id = context.getNameResolver().getString(proto.getFlexibleTypeCapabilitiesId());
FlexibleTypeCapabilities capabilities = context.getFlexibleTypeCapabilitiesDeserializer().capabilitiesById(id);
if (capabilities == null) return ErrorUtils.createErrorType(new DeserializedType(proto) + ": Capabilities not found for id " + id);
return DelegatingFlexibleType.OBJECT$.create(
new DeserializedType(proto),
new DeserializedType(proto.getFlexibleUpperBound()),
capabilities
);
}
return new DeserializedType(proto); return new DeserializedType(proto);
} }
@@ -32,6 +32,7 @@ import org.jetbrains.jet.lang.descriptors.ModuleDescriptor
import org.jetbrains.jet.lang.descriptors.ClassDescriptor import org.jetbrains.jet.lang.descriptors.ClassDescriptor
import org.jetbrains.jet.lang.resolve.name.ClassId import org.jetbrains.jet.lang.resolve.name.ClassId
import org.jetbrains.jet.descriptors.serialization.ClassDeserializer import org.jetbrains.jet.descriptors.serialization.ClassDeserializer
import org.jetbrains.jet.descriptors.serialization.FlexibleTypeCapabilitiesDeserializer
public open class DeserializationGlobalContext( public open class DeserializationGlobalContext(
public val storageManager: StorageManager, public val storageManager: StorageManager,
@@ -40,6 +41,7 @@ public open class DeserializationGlobalContext(
public val annotationLoader: AnnotationLoader, public val annotationLoader: AnnotationLoader,
public val constantLoader: ConstantLoader, public val constantLoader: ConstantLoader,
public val packageFragmentProvider: PackageFragmentProvider, public val packageFragmentProvider: PackageFragmentProvider,
public val flexibleTypeCapabilitiesDeserializer: FlexibleTypeCapabilitiesDeserializer,
public val classDeserializer: ClassDeserializer = ClassDeserializer(storageManager, classDataFinder) public val classDeserializer: ClassDeserializer = ClassDeserializer(storageManager, classDataFinder)
) { ) {
{ {
@@ -48,7 +50,7 @@ public open class DeserializationGlobalContext(
public fun withNameResolver(nameResolver: NameResolver): DeserializationContext { public fun withNameResolver(nameResolver: NameResolver): DeserializationContext {
return DeserializationContext(storageManager, moduleDescriptor, classDataFinder, annotationLoader, return DeserializationContext(storageManager, moduleDescriptor, classDataFinder, annotationLoader,
constantLoader, packageFragmentProvider, classDeserializer, nameResolver) constantLoader, packageFragmentProvider, flexibleTypeCapabilitiesDeserializer, classDeserializer, nameResolver)
} }
} }
@@ -60,10 +62,11 @@ public open class DeserializationContext(
annotationLoader: AnnotationLoader, annotationLoader: AnnotationLoader,
constantLoader: ConstantLoader, constantLoader: ConstantLoader,
packageFragmentProvider: PackageFragmentProvider, packageFragmentProvider: PackageFragmentProvider,
flexibleTypeCapabilitiesDeserializer: FlexibleTypeCapabilitiesDeserializer,
classDeserializer: ClassDeserializer, classDeserializer: ClassDeserializer,
public val nameResolver: NameResolver public val nameResolver: NameResolver
) : DeserializationGlobalContext(storageManager, moduleDescriptor, classDataFinder, annotationLoader, ) : DeserializationGlobalContext(storageManager, moduleDescriptor, classDataFinder, annotationLoader,
constantLoader, packageFragmentProvider, classDeserializer) { constantLoader, packageFragmentProvider, flexibleTypeCapabilitiesDeserializer, classDeserializer) {
fun withTypes(containingDeclaration: DeclarationDescriptor): DeserializationContextWithTypes { fun withTypes(containingDeclaration: DeclarationDescriptor): DeserializationContextWithTypes {
val typeDeserializer = TypeDeserializer(this, null, "Deserializer for ${containingDeclaration.getName()}", val typeDeserializer = TypeDeserializer(this, null, "Deserializer for ${containingDeclaration.getName()}",
TypeDeserializer.TypeParameterResolver.NONE) TypeDeserializer.TypeParameterResolver.NONE)
@@ -73,7 +76,7 @@ public open class DeserializationContext(
fun withTypes(containingDeclaration: DeclarationDescriptor, typeDeserializer: TypeDeserializer): DeserializationContextWithTypes { fun withTypes(containingDeclaration: DeclarationDescriptor, typeDeserializer: TypeDeserializer): DeserializationContextWithTypes {
return DeserializationContextWithTypes(storageManager, moduleDescriptor, classDataFinder, annotationLoader, return DeserializationContextWithTypes(storageManager, moduleDescriptor, classDataFinder, annotationLoader,
constantLoader, packageFragmentProvider, classDeserializer, constantLoader, packageFragmentProvider, classDeserializer,
nameResolver, containingDeclaration, typeDeserializer) nameResolver, flexibleTypeCapabilitiesDeserializer, containingDeclaration, typeDeserializer)
} }
} }
@@ -88,10 +91,11 @@ class DeserializationContextWithTypes(
packageFragmentProvider: PackageFragmentProvider, packageFragmentProvider: PackageFragmentProvider,
classDeserializer: ClassDeserializer, classDeserializer: ClassDeserializer,
nameResolver: NameResolver, nameResolver: NameResolver,
flexibleTypeCapabilitiesDeserializer: FlexibleTypeCapabilitiesDeserializer,
val containingDeclaration: DeclarationDescriptor, val containingDeclaration: DeclarationDescriptor,
val typeDeserializer: TypeDeserializer val typeDeserializer: TypeDeserializer
) : DeserializationContext(storageManager, moduleDescriptor, classDataFinder, annotationLoader, ) : DeserializationContext(storageManager, moduleDescriptor, classDataFinder, annotationLoader,
constantLoader, packageFragmentProvider, classDeserializer, nameResolver) { constantLoader, packageFragmentProvider, flexibleTypeCapabilitiesDeserializer, classDeserializer, nameResolver) {
val deserializer: MemberDeserializer = MemberDeserializer(this) val deserializer: MemberDeserializer = MemberDeserializer(this)
public fun childContext( public fun childContext(
@@ -145,7 +145,7 @@ public class DeserializerForDecompiler(val packageDirectory: VirtualFile, val di
moduleContainingMissingDependencies.seal() moduleContainingMissingDependencies.seal()
} }
val deserializationContext = DeserializationGlobalContext(storageManager, moduleDescriptor, classDataFinder, annotationLoader, val deserializationContext = DeserializationGlobalContext(storageManager, moduleDescriptor, classDataFinder, annotationLoader,
constantLoader, packageFragmentProvider) constantLoader, packageFragmentProvider, JavaFlexibleTypeCapabilitiesDeserializer)
private fun createDummyPackageFragment(fqName: FqName): MutablePackageFragmentDescriptor { private fun createDummyPackageFragment(fqName: FqName): MutablePackageFragmentDescriptor {
return MutablePackageFragmentDescriptor(moduleDescriptor, fqName) return MutablePackageFragmentDescriptor(moduleDescriptor, fqName)
@@ -2823,6 +2823,12 @@ public class LazyResolveByStubTestGenerated extends AbstractLazyResolveByStubTes
doTest(fileName); doTest(fileName);
} }
@TestMetadata("platform.kt")
public void testPlatform() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/loadJava/compiledKotlin/type/platform.kt");
doTest(fileName);
}
@TestMetadata("String.kt") @TestMetadata("String.kt")
public void testString() throws Exception { public void testString() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/loadJava/compiledKotlin/type/String.kt"); String fileName = JetTestUtils.navigationMetadata("compiler/testData/loadJava/compiledKotlin/type/String.kt");