Compare commits

...

28 Commits

Author SHA1 Message Date
Georgy Bronnikov
0aef5659c2 Kludgy workaraound for bad annotations on imported declarations 2019-07-18 17:48:30 +03:00
Alexander Udalov
3ee9b821e5 Psi2ir: ignore unresolved annotations
Note that the test is an exact copy of an existing test
missingDependencyNestedAnnotation, but with -Xuse-ir
2019-07-18 17:48:29 +03:00
Georgy Bronnikov
ec44269921 ExternalReference.kt 2019-07-18 17:48:28 +03:00
Georgy Bronnikov
3ca5a81f3b React to review, stupid mistakes 2019-07-02 19:47:31 +03:00
Georgy Bronnikov
7a072e4c13 Remove unneeded special case check in deserialization 2019-07-02 13:13:36 +03:00
Georgy Bronnikov
102a21b682 Add a comment 2019-07-02 12:01:57 +03:00
Georgy Bronnikov
41b3ac755a Revert "JVM_IR: repair bytecode tests"
This reverts commit e1317003da.
2019-07-01 18:53:14 +03:00
Georgy Bronnikov
ae38ba3f23 Cut out serialized IR from bytecode test output 2019-07-01 18:52:06 +03:00
Georgy Bronnikov
5af75b628c JVM_IR: do serialize fake overrides after all 2019-07-01 16:51:55 +03:00
Georgy Bronnikov
e139349ef6 React to review 2019-07-01 16:51:43 +03:00
Georgy Bronnikov
89cf6328a9 Serialzie IR as a single array-of-strings field 2019-06-25 19:31:26 +03:00
Georgy Bronnikov
5baaf7ae2a React to review: move files between packages 2019-06-25 15:24:54 +03:00
Georgy Bronnikov
d3ede8f094 React to review comments 2019-06-25 11:25:11 +03:00
Georgy Bronnikov
439c6b38d4 JVM_IR: no wrapping for int64 uniqIds in serialized IR 2019-06-24 18:11:42 +03:00
Georgy Bronnikov
a0a325e66b Remove generated file 2019-06-24 15:29:12 +03:00
Georgy Bronnikov
859377abef Remove dependency of serialization.common on jvm 2019-06-21 21:51:26 +03:00
Georgy Bronnikov
dfc5e0debb JVM_IR: don not serialize fake overrides 2019-06-21 21:30:49 +03:00
Georgy Bronnikov
f6f96e7694 React to review comments 2019-06-21 14:48:19 +03:00
Georgy Bronnikov
a9590fa5d2 Reat to review comments 2019-06-19 15:59:13 +03:00
Georgy Bronnikov
0576bd92a9 JVM_IR: deal with type parameters in IR serialization 2019-06-17 14:30:01 +03:00
Georgy Bronnikov
b0d593f10f JVM_IR: don't attempt to serialize IR to metadata when dealing with FIR 2019-06-17 14:30:00 +03:00
Georgy Bronnikov
e1317003da JVM_IR: repair bytecode tests 2019-06-17 14:29:59 +03:00
Georgy Bronnikov
b7f88a65d0 JVM_IR: make deserializer call stub generator, not the other way around 2019-06-17 14:29:58 +03:00
Georgy Bronnikov
217986d858 JVM_IR: put toplevelFqNames into string table to save space 2019-06-17 14:29:58 +03:00
Georgy Bronnikov
4bfc97c67d JVM_IR: make deserializer argument obligatory 2019-06-17 14:29:57 +03:00
Georgy Bronnikov
84d825aebd TMP: Correct compilation 2019-06-17 14:29:56 +03:00
Georgy Bronnikov
2588b737c7 JVM_IR: IR serialization and deserialization 2019-06-17 14:29:55 +03:00
Georgy Bronnikov
bb03dce309 JVM_IR: tweaks for smooth serialization 2019-06-16 13:12:42 +03:00
72 changed files with 4865 additions and 352 deletions

View File

@@ -203,6 +203,11 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (!checkStringEquals(old.getExtension(JvmProtoBuf.anonymousObjectOriginName), new.getExtension(JvmProtoBuf.anonymousObjectOriginName))) return false
}
if (old.hasExtension(JvmProtoBuf.classUniqId) != new.hasExtension(JvmProtoBuf.classUniqId)) return false
if (old.hasExtension(JvmProtoBuf.classUniqId)) {
if (old.getExtension(JvmProtoBuf.classUniqId) != new.getExtension(JvmProtoBuf.classUniqId)) return false
}
if (old.getExtensionCount(JsProtoBuf.classAnnotation) != new.getExtensionCount(JsProtoBuf.classAnnotation)) {
return false
}
@@ -253,6 +258,7 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
JVM_EXT_CLASS_MODULE_NAME,
JVM_EXT_CLASS_LOCAL_VARIABLE_LIST,
JVM_EXT_ANONYMOUS_OBJECT_ORIGIN_NAME,
JVM_EXT_CLASS_UNIQ_ID,
JS_EXT_CLASS_ANNOTATION_LIST,
JS_EXT_CLASS_CONTAINING_FILE_ID,
JAVA_EXT_IS_PACKAGE_PRIVATE_CLASS,
@@ -325,6 +331,11 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (!checkStringEquals(old.getExtension(JvmProtoBuf.anonymousObjectOriginName), new.getExtension(JvmProtoBuf.anonymousObjectOriginName))) result.add(ProtoBufClassKind.JVM_EXT_ANONYMOUS_OBJECT_ORIGIN_NAME)
}
if (old.hasExtension(JvmProtoBuf.classUniqId) != new.hasExtension(JvmProtoBuf.classUniqId)) result.add(ProtoBufClassKind.JVM_EXT_CLASS_UNIQ_ID)
if (old.hasExtension(JvmProtoBuf.classUniqId)) {
if (old.getExtension(JvmProtoBuf.classUniqId) != new.getExtension(JvmProtoBuf.classUniqId)) result.add(ProtoBufClassKind.JVM_EXT_CLASS_UNIQ_ID)
}
if (old.getExtensionCount(JsProtoBuf.classAnnotation) != new.getExtensionCount(JsProtoBuf.classAnnotation)) {
result.add(ProtoBufClassKind.JS_EXT_CLASS_ANNOTATION_LIST)
}
@@ -415,6 +426,11 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (!checkStringEquals(old.getExtension(JvmProtoBuf.lambdaClassOriginName), new.getExtension(JvmProtoBuf.lambdaClassOriginName))) return false
}
if (old.hasExtension(JvmProtoBuf.functionUniqId) != new.hasExtension(JvmProtoBuf.functionUniqId)) return false
if (old.hasExtension(JvmProtoBuf.functionUniqId)) {
if (old.getExtension(JvmProtoBuf.functionUniqId) != new.getExtension(JvmProtoBuf.functionUniqId)) return false
}
if (old.getExtensionCount(JsProtoBuf.functionAnnotation) != new.getExtensionCount(JsProtoBuf.functionAnnotation)) {
return false
}
@@ -513,6 +529,11 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (old.getExtension(JvmProtoBuf.flags) != new.getExtension(JvmProtoBuf.flags)) return false
}
if (old.hasExtension(JvmProtoBuf.propertyUniqId) != new.hasExtension(JvmProtoBuf.propertyUniqId)) return false
if (old.hasExtension(JvmProtoBuf.propertyUniqId)) {
if (old.getExtension(JvmProtoBuf.propertyUniqId) != new.getExtension(JvmProtoBuf.propertyUniqId)) return false
}
if (old.getExtensionCount(JsProtoBuf.propertyAnnotation) != new.getExtensionCount(JsProtoBuf.propertyAnnotation)) {
return false
}
@@ -677,6 +698,11 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
}
}
if (old.hasExtension(JvmProtoBuf.typeParamUniqId) != new.hasExtension(JvmProtoBuf.typeParamUniqId)) return false
if (old.hasExtension(JvmProtoBuf.typeParamUniqId)) {
if (old.getExtension(JvmProtoBuf.typeParamUniqId) != new.getExtension(JvmProtoBuf.typeParamUniqId)) return false
}
if (old.getExtensionCount(JsProtoBuf.typeParameterAnnotation) != new.getExtensionCount(JsProtoBuf.typeParameterAnnotation)) {
return false
}
@@ -816,6 +842,11 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (!checkEquals(old.getExtension(JvmProtoBuf.constructorSignature), new.getExtension(JvmProtoBuf.constructorSignature))) return false
}
if (old.hasExtension(JvmProtoBuf.constructorUniqId) != new.hasExtension(JvmProtoBuf.constructorUniqId)) return false
if (old.hasExtension(JvmProtoBuf.constructorUniqId)) {
if (old.getExtension(JvmProtoBuf.constructorUniqId) != new.getExtension(JvmProtoBuf.constructorUniqId)) return false
}
if (old.getExtensionCount(JsProtoBuf.constructorAnnotation) != new.getExtensionCount(JsProtoBuf.constructorAnnotation)) {
return false
}
@@ -848,6 +879,11 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (!checkStringEquals(old.name, new.name)) return false
}
if (old.hasExtension(JvmProtoBuf.enumEntryUniqId) != new.hasExtension(JvmProtoBuf.enumEntryUniqId)) return false
if (old.hasExtension(JvmProtoBuf.enumEntryUniqId)) {
if (old.getExtension(JvmProtoBuf.enumEntryUniqId) != new.getExtension(JvmProtoBuf.enumEntryUniqId)) return false
}
if (old.getExtensionCount(JsProtoBuf.enumEntryAnnotation) != new.getExtensionCount(JsProtoBuf.enumEntryAnnotation)) {
return false
}
@@ -905,6 +941,11 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (old.varargElementTypeId != new.varargElementTypeId) return false
}
if (old.hasExtension(JvmProtoBuf.valueParamUniqId) != new.hasExtension(JvmProtoBuf.valueParamUniqId)) return false
if (old.hasExtension(JvmProtoBuf.valueParamUniqId)) {
if (old.getExtension(JvmProtoBuf.valueParamUniqId) != new.getExtension(JvmProtoBuf.valueParamUniqId)) return false
}
if (old.getExtensionCount(JsProtoBuf.parameterAnnotation) != new.getExtensionCount(JsProtoBuf.parameterAnnotation)) {
return false
}
@@ -1655,6 +1696,10 @@ fun ProtoBuf.Class.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) ->
hashCode = 31 * hashCode + stringIndexes(getExtension(JvmProtoBuf.anonymousObjectOriginName))
}
if (hasExtension(JvmProtoBuf.classUniqId)) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.classUniqId).hashCode()
}
for(i in 0..getExtensionCount(JsProtoBuf.classAnnotation) - 1) {
hashCode = 31 * hashCode + getExtension(JsProtoBuf.classAnnotation, i).hashCode(stringIndexes, fqNameIndexes)
}
@@ -1731,6 +1776,10 @@ fun ProtoBuf.Function.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int)
hashCode = 31 * hashCode + stringIndexes(getExtension(JvmProtoBuf.lambdaClassOriginName))
}
if (hasExtension(JvmProtoBuf.functionUniqId)) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.functionUniqId).hashCode()
}
for(i in 0..getExtensionCount(JsProtoBuf.functionAnnotation) - 1) {
hashCode = 31 * hashCode + getExtension(JsProtoBuf.functionAnnotation, i).hashCode(stringIndexes, fqNameIndexes)
}
@@ -1811,6 +1860,10 @@ fun ProtoBuf.Property.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int)
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.flags)
}
if (hasExtension(JvmProtoBuf.propertyUniqId)) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.propertyUniqId).hashCode()
}
for(i in 0..getExtensionCount(JsProtoBuf.propertyAnnotation) - 1) {
hashCode = 31 * hashCode + getExtension(JsProtoBuf.propertyAnnotation, i).hashCode(stringIndexes, fqNameIndexes)
}
@@ -1949,6 +2002,10 @@ fun ProtoBuf.TypeParameter.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes:
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.typeParameterAnnotation, i).hashCode(stringIndexes, fqNameIndexes)
}
if (hasExtension(JvmProtoBuf.typeParamUniqId)) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.typeParamUniqId).hashCode()
}
for(i in 0..getExtensionCount(JsProtoBuf.typeParameterAnnotation) - 1) {
hashCode = 31 * hashCode + getExtension(JsProtoBuf.typeParameterAnnotation, i).hashCode(stringIndexes, fqNameIndexes)
}
@@ -2057,6 +2114,10 @@ fun ProtoBuf.Constructor.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (I
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.constructorSignature).hashCode(stringIndexes, fqNameIndexes)
}
if (hasExtension(JvmProtoBuf.constructorUniqId)) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.constructorUniqId).hashCode()
}
for(i in 0..getExtensionCount(JsProtoBuf.constructorAnnotation) - 1) {
hashCode = 31 * hashCode + getExtension(JsProtoBuf.constructorAnnotation, i).hashCode(stringIndexes, fqNameIndexes)
}
@@ -2079,6 +2140,10 @@ fun ProtoBuf.EnumEntry.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int
hashCode = 31 * hashCode + stringIndexes(name)
}
if (hasExtension(JvmProtoBuf.enumEntryUniqId)) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.enumEntryUniqId).hashCode()
}
for(i in 0..getExtensionCount(JsProtoBuf.enumEntryAnnotation) - 1) {
hashCode = 31 * hashCode + getExtension(JsProtoBuf.enumEntryAnnotation, i).hashCode(stringIndexes, fqNameIndexes)
}
@@ -2127,6 +2192,10 @@ fun ProtoBuf.ValueParameter.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes:
hashCode = 31 * hashCode + varargElementTypeId
}
if (hasExtension(JvmProtoBuf.valueParamUniqId)) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.valueParamUniqId).hashCode()
}
for(i in 0..getExtensionCount(JsProtoBuf.parameterAnnotation) - 1) {
hashCode = 31 * hashCode + getExtension(JsProtoBuf.parameterAnnotation, i).hashCode(stringIndexes, fqNameIndexes)
}

View File

@@ -253,6 +253,10 @@ class DifferenceCalculatorForClass(
ProtoCompareGenerated.ProtoBufClassKind.JVM_EXT_ANONYMOUS_OBJECT_ORIGIN_NAME -> {
// Not affected, this extension is not used in the compiler
}
ProtoBufClassKind.JVM_EXT_CLASS_UNIQ_ID -> {
// When uniqId is affected, this means something else in the class signature has changed.
// Those changes will be caught separately.
}
}
}

View File

@@ -8,16 +8,23 @@ public final class DebugJvmProtoBuf {
public static void registerAllExtensions(
org.jetbrains.kotlin.protobuf.ExtensionRegistry registry) {
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.constructorSignature);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.constructorUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.methodSignature);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.lambdaClassOriginName);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.functionUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.propertySignature);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.flags);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.propertyUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.enumEntryUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.valueParamUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.typeAnnotation);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.isRaw);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.typeParameterAnnotation);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.typeParamUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.classModuleName);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.classLocalVariable);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.anonymousObjectOriginName);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.classUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.packageModuleName);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.packageLocalVariable);
}
@@ -4521,6 +4528,17 @@ public final class DebugJvmProtoBuf {
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.class,
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.getDefaultInstance());
public static final int CONSTRUCTOR_UNIQ_ID_FIELD_NUMBER = 101;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Constructor { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Constructor,
java.lang.Long> constructorUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Long.class,
null);
public static final int METHOD_SIGNATURE_FIELD_NUMBER = 100;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Function { ... }</code>
@@ -4548,6 +4566,17 @@ public final class DebugJvmProtoBuf {
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int FUNCTION_UNIQ_ID_FIELD_NUMBER = 102;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Function { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Function,
java.lang.Long> functionUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Long.class,
null);
public static final int PROPERTY_SIGNATURE_FIELD_NUMBER = 100;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
@@ -4575,6 +4604,39 @@ public final class DebugJvmProtoBuf {
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int PROPERTY_UNIQ_ID_FIELD_NUMBER = 102;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Property,
java.lang.Long> propertyUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Long.class,
null);
public static final int ENUM_ENTRY_UNIQ_ID_FIELD_NUMBER = 100;
/**
* <code>extend .org.jetbrains.kotlin.metadata.EnumEntry { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.EnumEntry,
java.lang.Long> enumEntryUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Long.class,
null);
public static final int VALUE_PARAM_UNIQ_ID_FIELD_NUMBER = 100;
/**
* <code>extend .org.jetbrains.kotlin.metadata.ValueParameter { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.ValueParameter,
java.lang.Long> valueParamUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Long.class,
null);
public static final int TYPE_ANNOTATION_FIELD_NUMBER = 100;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Type { ... }</code>
@@ -4608,6 +4670,17 @@ public final class DebugJvmProtoBuf {
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int TYPE_PARAM_UNIQ_ID_FIELD_NUMBER = 101;
/**
* <code>extend .org.jetbrains.kotlin.metadata.TypeParameter { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.TypeParameter,
java.lang.Long> typeParamUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Long.class,
null);
public static final int CLASS_MODULE_NAME_FIELD_NUMBER = 101;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
@@ -4650,6 +4723,17 @@ public final class DebugJvmProtoBuf {
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int CLASS_UNIQ_ID_FIELD_NUMBER = 104;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class,
java.lang.Long> classUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Long.class,
null);
public static final int PACKAGE_MODULE_NAME_FIELD_NUMBER = 101;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Package { ... }</code>
@@ -4734,36 +4818,48 @@ public final class DebugJvmProtoBuf {
".JvmMethodSignature:\200\001\n\025constructor_sign" +
"ature\022*.org.jetbrains.kotlin.metadata.Co" +
"nstructor\030d \001(\01325.org.jetbrains.kotlin.m" +
"etadata.jvm.JvmMethodSignature:x\n\020method" +
"_signature\022\'.org.jetbrains.kotlin.metada",
"ta.Function\030d \001(\01325.org.jetbrains.kotlin" +
".metadata.jvm.JvmMethodSignature:O\n\030lamb" +
"da_class_origin_name\022\'.org.jetbrains.kot" +
"lin.metadata.Function\030e \001(\005B\004\230\265\030\001:|\n\022pro" +
"perty_signature\022\'.org.jetbrains.kotlin.m" +
"etadata.Property\030d \001(\01327.org.jetbrains.k" +
"otlin.metadata.jvm.JvmPropertySignature:" +
"9\n\005flags\022\'.org.jetbrains.kotlin.metadata" +
".Property\030e \001(\005:\0010:g\n\017type_annotation\022#." +
"org.jetbrains.kotlin.metadata.Type\030d \003(\013",
"2).org.jetbrains.kotlin.metadata.Annotat" +
"ion:3\n\006is_raw\022#.org.jetbrains.kotlin.met" +
"adata.Type\030e \001(\010:z\n\031type_parameter_annot" +
"ation\022,.org.jetbrains.kotlin.metadata.Ty" +
"peParameter\030d \003(\0132).org.jetbrains.kotlin" +
".metadata.Annotation:E\n\021class_module_nam" +
"e\022$.org.jetbrains.kotlin.metadata.Class\030" +
"e \001(\005B\004\230\265\030\001:k\n\024class_local_variable\022$.or" +
"g.jetbrains.kotlin.metadata.Class\030f \003(\0132" +
"\'.org.jetbrains.kotlin.metadata.Property",
":P\n\034anonymous_object_origin_name\022$.org.j" +
"etbrains.kotlin.metadata.Class\030g \001(\005B\004\230\265" +
"\030\001:I\n\023package_module_name\022&.org.jetbrain" +
"s.kotlin.metadata.Package\030e \001(\005B\004\230\265\030\001:o\n" +
"\026package_local_variable\022&.org.jetbrains." +
"kotlin.metadata.Package\030f \003(\0132\'.org.jetb" +
"rains.kotlin.metadata.PropertyB\022B\020DebugJ" +
"vmProtoBuf"
"etadata.jvm.JvmMethodSignature:G\n\023constr" +
"uctor_uniq_id\022*.org.jetbrains.kotlin.met",
"adata.Constructor\030e \001(\003:x\n\020method_signat" +
"ure\022\'.org.jetbrains.kotlin.metadata.Func" +
"tion\030d \001(\01325.org.jetbrains.kotlin.metada" +
"ta.jvm.JvmMethodSignature:O\n\030lambda_clas" +
"s_origin_name\022\'.org.jetbrains.kotlin.met" +
"adata.Function\030e \001(\005B\004\230\265\030\001:A\n\020function_u" +
"niq_id\022\'.org.jetbrains.kotlin.metadata.F" +
"unction\030f \001(\003:|\n\022property_signature\022\'.or" +
"g.jetbrains.kotlin.metadata.Property\030d \001" +
"(\01327.org.jetbrains.kotlin.metadata.jvm.J",
"vmPropertySignature:9\n\005flags\022\'.org.jetbr" +
"ains.kotlin.metadata.Property\030e \001(\005:\0010:A" +
"\n\020property_uniq_id\022\'.org.jetbrains.kotli" +
"n.metadata.Property\030f \001(\003:D\n\022enum_entry_" +
"uniq_id\022(.org.jetbrains.kotlin.metadata." +
"EnumEntry\030d \001(\003:J\n\023value_param_uniq_id\022-" +
".org.jetbrains.kotlin.metadata.ValuePara" +
"meter\030d \001(\003:g\n\017type_annotation\022#.org.jet" +
"brains.kotlin.metadata.Type\030d \003(\0132).org." +
"jetbrains.kotlin.metadata.Annotation:3\n\006",
"is_raw\022#.org.jetbrains.kotlin.metadata.T" +
"ype\030e \001(\010:z\n\031type_parameter_annotation\022," +
".org.jetbrains.kotlin.metadata.TypeParam" +
"eter\030d \003(\0132).org.jetbrains.kotlin.metada" +
"ta.Annotation:H\n\022type_param_uniq_id\022,.or" +
"g.jetbrains.kotlin.metadata.TypeParamete" +
"r\030e \001(\003:E\n\021class_module_name\022$.org.jetbr" +
"ains.kotlin.metadata.Class\030e \001(\005B\004\230\265\030\001:k" +
"\n\024class_local_variable\022$.org.jetbrains.k" +
"otlin.metadata.Class\030f \003(\0132\'.org.jetbrai",
"ns.kotlin.metadata.Property:P\n\034anonymous" +
"_object_origin_name\022$.org.jetbrains.kotl" +
"in.metadata.Class\030g \001(\005B\004\230\265\030\001:;\n\rclass_u" +
"niq_id\022$.org.jetbrains.kotlin.metadata.C" +
"lass\030h \001(\003:I\n\023package_module_name\022&.org." +
"jetbrains.kotlin.metadata.Package\030e \001(\005B" +
"\004\230\265\030\001:o\n\026package_local_variable\022&.org.je" +
"tbrains.kotlin.metadata.Package\030f \003(\0132\'." +
"org.jetbrains.kotlin.metadata.PropertyB\022" +
"B\020DebugJvmProtoBuf"
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
@@ -4810,18 +4906,25 @@ public final class DebugJvmProtoBuf {
internal_static_org_jetbrains_kotlin_metadata_jvm_JvmPropertySignature_descriptor,
new java.lang.String[] { "Field", "SyntheticMethod", "Getter", "Setter", });
constructorSignature.internalInit(descriptor.getExtensions().get(0));
methodSignature.internalInit(descriptor.getExtensions().get(1));
lambdaClassOriginName.internalInit(descriptor.getExtensions().get(2));
propertySignature.internalInit(descriptor.getExtensions().get(3));
flags.internalInit(descriptor.getExtensions().get(4));
typeAnnotation.internalInit(descriptor.getExtensions().get(5));
isRaw.internalInit(descriptor.getExtensions().get(6));
typeParameterAnnotation.internalInit(descriptor.getExtensions().get(7));
classModuleName.internalInit(descriptor.getExtensions().get(8));
classLocalVariable.internalInit(descriptor.getExtensions().get(9));
anonymousObjectOriginName.internalInit(descriptor.getExtensions().get(10));
packageModuleName.internalInit(descriptor.getExtensions().get(11));
packageLocalVariable.internalInit(descriptor.getExtensions().get(12));
constructorUniqId.internalInit(descriptor.getExtensions().get(1));
methodSignature.internalInit(descriptor.getExtensions().get(2));
lambdaClassOriginName.internalInit(descriptor.getExtensions().get(3));
functionUniqId.internalInit(descriptor.getExtensions().get(4));
propertySignature.internalInit(descriptor.getExtensions().get(5));
flags.internalInit(descriptor.getExtensions().get(6));
propertyUniqId.internalInit(descriptor.getExtensions().get(7));
enumEntryUniqId.internalInit(descriptor.getExtensions().get(8));
valueParamUniqId.internalInit(descriptor.getExtensions().get(9));
typeAnnotation.internalInit(descriptor.getExtensions().get(10));
isRaw.internalInit(descriptor.getExtensions().get(11));
typeParameterAnnotation.internalInit(descriptor.getExtensions().get(12));
typeParamUniqId.internalInit(descriptor.getExtensions().get(13));
classModuleName.internalInit(descriptor.getExtensions().get(14));
classLocalVariable.internalInit(descriptor.getExtensions().get(15));
anonymousObjectOriginName.internalInit(descriptor.getExtensions().get(16));
classUniqId.internalInit(descriptor.getExtensions().get(17));
packageModuleName.internalInit(descriptor.getExtensions().get(18));
packageLocalVariable.internalInit(descriptor.getExtensions().get(19));
org.jetbrains.kotlin.protobuf.ExtensionRegistry registry =
org.jetbrains.kotlin.protobuf.ExtensionRegistry.newInstance();
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.stringIdInTable);

View File

@@ -224,6 +224,7 @@ extra["compilerModules"] = arrayOf(
":compiler:backend.jvm",
":compiler:backend.js",
":compiler:ir.serialization.common",
":compiler:ir.serialization.jvm",
":compiler:ir.serialization.js",
":kotlin-util-io",
":kotlin-util-klib",

View File

@@ -244,7 +244,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
v.getSerializationBindings().put(METHOD_FOR_FUNCTION, freeLambdaDescriptor, method);
DescriptorSerializer serializer =
DescriptorSerializer.createForLambda(new JvmSerializerExtension(v.getSerializationBindings(), state));
DescriptorSerializer.createForLambda(new JvmSerializerExtension(v.getSerializationBindings(), state, (descriptor) -> null));
ProtoBuf.Function.Builder builder = serializer.functionProto(freeLambdaDescriptor);
if (builder == null) return;

View File

@@ -116,7 +116,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
new DelegationFieldsInfo(classAsmType, descriptor, state, bindingContext)
.getDelegationFieldsInfo(myClass.getSuperTypeListEntries());
JvmSerializerExtension extension = new JvmSerializerExtension(v.getSerializationBindings(), state);
JvmSerializerExtension extension = new JvmSerializerExtension(v.getSerializationBindings(), state, (descriptor) -> null);
this.serializer = DescriptorSerializer.create(
descriptor, extension,
parentCodegen instanceof ImplementationBodyCodegen

View File

@@ -123,7 +123,9 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
) {
List<MemberDescriptor> members = CodegenUtil.getMemberDescriptorsToGenerate(codegen.element, codegen.bindingContext);
JvmSerializerExtension extension = new JvmSerializerExtension(codegen.v.getSerializationBindings(), codegen.state);
JvmSerializerExtension extension = new JvmSerializerExtension(
codegen.v.getSerializationBindings(), codegen.state, (descriptor) -> null
);
DescriptorSerializer serializer = DescriptorSerializer.createTopLevel(extension);
ProtoBuf.Package.Builder builder = serializer.packagePartProto(codegen.element.getPackageFqName(), members);
extension.serializeJvmPackage(builder, packagePartType);

View File

@@ -37,7 +37,11 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.Method
class JvmSerializerExtension(private val bindings: JvmSerializationBindings, state: GenerationState) : SerializerExtension() {
class JvmSerializerExtension(
private val bindings: JvmSerializationBindings,
state: GenerationState,
private val uniqIdProvider: ((DeclarationDescriptor) -> Long?) = { null }
) : SerializerExtension() {
private val codegenBinding = state.bindingContext
private val typeMapper = state.typeMapper
override val stringTable = JvmCodegenStringTable(typeMapper)
@@ -73,6 +77,9 @@ class JvmSerializerExtension(private val bindings: JvmSerializationBindings, sta
if (moduleName != JvmProtoBufUtil.DEFAULT_MODULE_NAME) {
proto.setExtension(JvmProtoBuf.classModuleName, stringTable.getStringIndex(moduleName))
}
uniqIdProvider(descriptor)?.let {
proto.setExtension(JvmProtoBuf.classUniqId, it)
}
val containerAsmType =
if (DescriptorUtils.isInterface(descriptor)) typeMapper.mapDefaultImpls(descriptor) else typeMapper.mapClass(descriptor)
@@ -149,6 +156,9 @@ class JvmSerializerExtension(private val bindings: JvmSerializationBindings, sta
for (annotation in typeParameter.nonSourceAnnotations) {
proto.addExtension(JvmProtoBuf.typeParameterAnnotation, annotationSerializer.serializeAnnotation(annotation))
}
uniqIdProvider(typeParameter)?.let {
proto.setExtension(JvmProtoBuf.typeParamUniqId, it)
}
}
override fun serializeConstructor(descriptor: ConstructorDescriptor,
@@ -161,6 +171,9 @@ class JvmSerializerExtension(private val bindings: JvmSerializationBindings, sta
proto.setExtension(JvmProtoBuf.constructorSignature, signature)
}
}
uniqIdProvider(descriptor)?.let {
proto.setExtension(JvmProtoBuf.constructorUniqId, it)
}
}
override fun serializeFunction(descriptor: FunctionDescriptor,
@@ -173,6 +186,9 @@ class JvmSerializerExtension(private val bindings: JvmSerializationBindings, sta
proto.setExtension(JvmProtoBuf.methodSignature, signature)
}
}
uniqIdProvider(descriptor)?.let {
proto.setExtension(JvmProtoBuf.functionUniqId, it)
}
}
override fun serializeProperty(
@@ -211,6 +227,10 @@ class JvmSerializerExtension(private val bindings: JvmSerializationBindings, sta
writeVersionRequirement(1, 2, 70, ProtoBuf.VersionRequirement.VersionKind.COMPILER_VERSION, versionRequirementTable)
)
}
uniqIdProvider(descriptor)?.let {
proto.setExtension(JvmProtoBuf.propertyUniqId, it)
}
}
private fun PropertyDescriptor.isJvmFieldPropertyInInterfaceCompanion(): Boolean {

View File

@@ -13,10 +13,7 @@ import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.declarations.impl.IrModuleFragmentImpl
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.util.ConstantValueGenerator
import org.jetbrains.kotlin.ir.util.ExternalDependenciesGenerator
import org.jetbrains.kotlin.ir.util.SymbolTable
import org.jetbrains.kotlin.ir.util.TypeTranslator
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi2ir.PsiSourceManager
@@ -55,6 +52,6 @@ object Fir2IrConverter {
symbolTable: SymbolTable,
builtIns: IrBuiltIns
) {
ExternalDependenciesGenerator(irModule.descriptor, symbolTable, builtIns).generateUnboundSymbolsAsDependencies()
ExternalDependenciesGenerator(irModule.descriptor, symbolTable, builtIns, deserializer = EmptyDeserializer).generateUnboundSymbolsAsDependencies()
}
}

View File

@@ -33,3 +33,10 @@ fun <T: Any> T.onlyIf(condition: T.()->Boolean, then: (T)->Unit): T {
if (this.condition()) then(this)
return this
}
object EmptyLoggingContext : LoggingContext {
override var inVerbosePhase = false
override fun log(message: () -> String) {}
}

View File

@@ -11,6 +11,7 @@ import org.jetbrains.kotlin.backend.common.phaser.invokeToplevel
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.ir.backend.js.transformers.irToJs.IrModuleToJsTransformer
import org.jetbrains.kotlin.ir.backend.js.utils.JsMainFunctionDetector
import org.jetbrains.kotlin.ir.util.EmptyDeserializer
import org.jetbrains.kotlin.ir.util.ExternalDependenciesGenerator
import org.jetbrains.kotlin.ir.util.patchDeclarationParents
import org.jetbrains.kotlin.library.KotlinLibrary
@@ -54,7 +55,8 @@ fun compile(
ExternalDependenciesGenerator(
moduleDescriptor = moduleDescriptor,
symbolTable = symbolTable,
irBuiltIns = irBuiltIns
irBuiltIns = irBuiltIns,
deserializer = EmptyDeserializer
).generateUnboundSymbolsAsDependencies()
moduleFragment.patchDeclarationParents()

View File

@@ -9,6 +9,7 @@ dependencies {
compile(project(":compiler:ir.tree"))
compile(project(":compiler:ir.psi2ir"))
compile(project(":compiler:ir.backend.common"))
compile(project(":compiler:ir.serialization.jvm"))
compileOnly(intellijCoreDep()) { includeJars("intellij-core", "asm-all", "guava", rootProject = rootProject) }
compileOnly(intellijDep()) { includeJars("trove4j", rootProject = rootProject) }
}

View File

@@ -8,9 +8,12 @@ package org.jetbrains.kotlin.backend.jvm
import org.jetbrains.kotlin.backend.common.CommonBackendContext
import org.jetbrains.kotlin.backend.common.ir.Ir
import org.jetbrains.kotlin.backend.common.phaser.PhaseConfig
import org.jetbrains.kotlin.backend.common.serialization.DeclarationTable
import org.jetbrains.kotlin.backend.common.serialization.DescriptorTable
import org.jetbrains.kotlin.backend.jvm.descriptors.JvmDeclarationFactory
import org.jetbrains.kotlin.backend.jvm.descriptors.JvmSharedVariablesManager
import org.jetbrains.kotlin.backend.jvm.intrinsics.IrIntrinsicMethods
import org.jetbrains.kotlin.backend.jvm.serialization.JvmDeclarationTable
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
@@ -75,4 +78,6 @@ class JvmBackendContext(
override fun shouldGenerateHandlerParameterForDefaultBodyFun() = true
}
val declarationTable: DeclarationTable = JvmDeclarationTable(irBuiltIns, DescriptorTable())
}

View File

@@ -5,12 +5,17 @@
package org.jetbrains.kotlin.backend.jvm
import org.jetbrains.kotlin.backend.common.EmptyLoggingContext
import org.jetbrains.kotlin.backend.common.phaser.PhaseConfig
import org.jetbrains.kotlin.backend.jvm.serialization.JvmIrDeserializer
import org.jetbrains.kotlin.codegen.CompilationErrorHandler
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.declarations.MetadataSource
import org.jetbrains.kotlin.ir.util.ExternalDependenciesGenerator
import org.jetbrains.kotlin.ir.util.SymbolTable
import org.jetbrains.kotlin.ir.util.IrDeserializer
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi2ir.Psi2IrTranslator
import org.jetbrains.kotlin.psi2ir.PsiSourceManager
@@ -25,9 +30,10 @@ object JvmBackendFacade {
) {
val psi2ir = Psi2IrTranslator(state.languageVersionSettings)
val psi2irContext = psi2ir.createGeneratorContext(state.module, state.bindingContext, extensions = JvmGeneratorExtensions)
val irModuleFragment = psi2ir.generateModuleFragment(psi2irContext, files)
val deserializer = JvmIrDeserializer(state.module, EmptyLoggingContext, psi2irContext.irBuiltIns, psi2irContext.symbolTable, state.languageVersionSettings)
val irModuleFragment = psi2ir.generateModuleFragment(psi2irContext, files, deserializer)
doGenerateFilesInternal(state, errorHandler, irModuleFragment, psi2irContext, phaseConfig)
doGenerateFilesInternal(state, errorHandler, irModuleFragment, psi2irContext, phaseConfig, deserializer)
}
internal fun doGenerateFilesInternal(
@@ -35,10 +41,11 @@ object JvmBackendFacade {
errorHandler: CompilationErrorHandler,
irModuleFragment: IrModuleFragment,
psi2irContext: GeneratorContext,
phaseConfig: PhaseConfig
phaseConfig: PhaseConfig,
deserializer: IrDeserializer
) {
doGenerateFilesInternal(
state, errorHandler, irModuleFragment, psi2irContext.symbolTable, psi2irContext.sourceManager, phaseConfig
state, errorHandler, irModuleFragment, psi2irContext.symbolTable, psi2irContext.sourceManager, phaseConfig, deserializer
)
}
@@ -49,6 +56,7 @@ object JvmBackendFacade {
symbolTable: SymbolTable,
sourceManager: PsiSourceManager,
phaseConfig: PhaseConfig,
deserializer: IrDeserializer,
firMode: Boolean = false
) {
val jvmBackendContext = JvmBackendContext(
@@ -59,9 +67,17 @@ object JvmBackendFacade {
irModuleFragment.descriptor,
symbolTable,
irModuleFragment.irBuiltins,
JvmGeneratorExtensions.externalDeclarationOrigin
JvmGeneratorExtensions.externalDeclarationOrigin,
deserializer
).generateUnboundSymbolsAsDependencies()
for (irFile in irModuleFragment.files) {
irFile.metadata?.serializedIr = serializeIrFile(jvmBackendContext, irFile)
for (irClass in irFile.declarations.filterIsInstance<IrClass>()) {
(irClass.metadata as? MetadataSource.Class)?.serializedIr = serializeToplevelIrClass(jvmBackendContext, irClass)
}
}
val jvmBackend = JvmBackend(jvmBackendContext)
for (irFile in irModuleFragment.files) {

View File

@@ -16,7 +16,9 @@
package org.jetbrains.kotlin.backend.jvm
import org.jetbrains.kotlin.backend.common.EmptyLoggingContext
import org.jetbrains.kotlin.backend.common.phaser.PhaseConfig
import org.jetbrains.kotlin.backend.jvm.serialization.JvmIrDeserializer
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
@@ -24,16 +26,12 @@ import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.util.SymbolTable
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi2ir.Psi2IrTranslator
import org.jetbrains.kotlin.psi2ir.PsiSourceManager
class JvmIrCodegenFactory(private val phaseConfig: PhaseConfig) : CodegenFactory {
override fun generateModule(state: GenerationState, files: Collection<KtFile>, errorHandler: CompilationErrorHandler) {
val psi2ir = Psi2IrTranslator(state.languageVersionSettings)
val psi2irContext = psi2ir.createGeneratorContext(state.module, state.bindingContext, extensions = JvmGeneratorExtensions)
val irModuleFragment = psi2ir.generateModuleFragment(psi2irContext, files)
JvmBackendFacade.doGenerateFilesInternal(state, errorHandler, irModuleFragment, psi2irContext, phaseConfig)
JvmBackendFacade.doGenerateFiles(files, state, errorHandler, phaseConfig)
}
fun generateModuleInFrontendIRMode(
@@ -43,8 +41,10 @@ class JvmIrCodegenFactory(private val phaseConfig: PhaseConfig) : CodegenFactory
symbolTable: SymbolTable,
sourceManager: PsiSourceManager
) {
val deserializer =
JvmIrDeserializer(state.module, EmptyLoggingContext, irModuleFragment.irBuiltins, symbolTable, state.languageVersionSettings)
JvmBackendFacade.doGenerateFilesInternal(
state, errorHandler, irModuleFragment, symbolTable, sourceManager, phaseConfig, firMode = true
state, errorHandler, irModuleFragment, symbolTable, sourceManager, phaseConfig, deserializer, firMode = true
)
}

View File

@@ -26,6 +26,7 @@ import org.jetbrains.kotlin.codegen.inline.SourceMapper
import org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings
import org.jetbrains.kotlin.codegen.serialization.JvmSerializerExtension
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.ir.declarations.*
@@ -33,7 +34,9 @@ import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.types.IrSimpleType
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.metadata.jvm.deserialization.BitEncoding
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
@@ -44,6 +47,7 @@ import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.diagnostics.OtherOrigin
import org.jetbrains.kotlin.serialization.DescriptorSerializer
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.org.objectweb.asm.AnnotationVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import java.io.File
@@ -84,7 +88,12 @@ open class ClassCodegen protected constructor(
private var sourceMapper: DefaultSourceMapper? = null
private val serializerExtension = JvmSerializerExtension(visitor.serializationBindings, state)
private fun uniqIdProvider(descriptor: DeclarationDescriptor): Long? {
val index = context.declarationTable.descriptorTable.get(descriptor)
return index
}
private val serializerExtension = JvmSerializerExtension(visitor.serializationBindings, state, ::uniqIdProvider)
private val serializer: DescriptorSerializer? =
when (val metadata = irClass.metadata) {
is MetadataSource.Class -> DescriptorSerializer.create(metadata.descriptor, serializerExtension, parentClassCodegen?.serializer)
@@ -137,8 +146,9 @@ open class ClassCodegen protected constructor(
when (val metadata = irClass.metadata) {
is MetadataSource.Class -> {
val classProto = serializer!!.classProto(metadata.descriptor).build()
writeKotlinMetadata(visitor, state, KotlinClassHeader.Kind.CLASS, 0) {
AsmUtil.writeAnnotationData(it, serializer, classProto)
writeKotlinMetadata(visitor, state, KotlinClassHeader.Kind.CLASS, 0) { av ->
AsmUtil.writeAnnotationData(av, serializer, classProto)
metadata.serializedIr?.let { storeSerializedIr(av, it) }
}
}
is MetadataSource.File -> {
@@ -149,6 +159,8 @@ open class ClassCodegen protected constructor(
writeKotlinMetadata(visitor, state, KotlinClassHeader.Kind.FILE_FACADE, 0) {
AsmUtil.writeAnnotationData(it, serializer, packageProto.build())
val serializedIr = metadata.serializedIr ?: error("File facade should have serialized IR")
storeSerializedIr(it, serializedIr)
// TODO: JvmPackageName
}
}
@@ -382,3 +394,13 @@ private fun IrClass.getSuperClassInfo(typeMapper: IrTypeMapper): IrSuperClassInf
return IrSuperClassInfo(AsmTypes.OBJECT_TYPE, null)
}
private fun storeSerializedIr(av: AnnotationVisitor, serializedIr: ByteArray) {
val serializedIrParts = BitEncoding.encodeBytes(serializedIr)
val partsVisitor = av.visitArray(JvmAnnotationNames.METADATA_SERIALIZED_IR_FIELD_NAME)
for (part in serializedIrParts) {
partsVisitor.visit(null, part)
}
partsVisitor.visitEnd()
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.jvm
import org.jetbrains.kotlin.backend.jvm.serialization.JvmIrSerializer
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrFile
fun serializeIrFile(context: JvmBackendContext, irFile: IrFile): ByteArray {
return JvmIrSerializer(
context,
context.declarationTable,
context.psiSourceManager,
externallyVisibleOnly = true
).serializeJvmIrFile(irFile).toByteArray()
}
fun serializeToplevelIrClass(context: JvmBackendContext, irClass: IrClass): ByteArray {
assert(irClass.parent is IrFile)
return JvmIrSerializer(
context,
context.declarationTable,
context.psiSourceManager,
externallyVisibleOnly = true
).serializeJvmToplevelClass(irClass)
.toByteArray()
}

View File

@@ -20,6 +20,7 @@ import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.util.EmptyDeserializer
import org.jetbrains.kotlin.ir.util.IrDeserializer
import org.jetbrains.kotlin.ir.util.SymbolTable
import org.jetbrains.kotlin.ir.util.patchDeclarationParents
@@ -65,7 +66,7 @@ class Psi2IrTranslator(
): GeneratorContext =
GeneratorContext(configuration, moduleDescriptor, bindingContext, languageVersionSettings, symbolTable, extensions)
fun generateModuleFragment(context: GeneratorContext, ktFiles: Collection<KtFile>, deserializer: IrDeserializer? = null): IrModuleFragment {
fun generateModuleFragment(context: GeneratorContext, ktFiles: Collection<KtFile>, deserializer: IrDeserializer = EmptyDeserializer): IrModuleFragment {
val moduleGenerator = ModuleGenerator(context)
val irModule = moduleGenerator.generateModuleFragmentWithoutDependencies(ktFiles)
postprocess(context, irModule)

View File

@@ -40,7 +40,7 @@ class AnnotationGenerator(context: GeneratorContext) : IrElementVisitorVoid {
declaration.descriptor.backingField
else declaration.descriptor
annotatedDescriptor?.annotations?.mapTo(declaration.annotations) {
annotatedDescriptor?.annotations?.mapNotNullTo(declaration.annotations) {
constantValueGenerator.generateAnnotationConstructorCall(it)
}
}

View File

@@ -33,6 +33,8 @@ import org.jetbrains.kotlin.ir.expressions.impl.IrGetValueImpl
import org.jetbrains.kotlin.ir.symbols.IrFieldSymbol
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.symbols.IrVariableSymbol
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.defaultType
import org.jetbrains.kotlin.ir.util.declareSimpleFunctionWithOverrides
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtProperty
@@ -68,20 +70,22 @@ class DelegatedPropertyGenerator(declarationGenerator: DeclarationGenerator) : D
val delegateReceiverValue = createBackingFieldValueForDelegate(irDelegate.symbol, thisClass, ktDelegate)
val getterDescriptor = propertyDescriptor.getter!!
irProperty.getter = generateDelegatedPropertyAccessor(ktProperty, ktDelegate, getterDescriptor) { irGetter ->
val typeArguments = irGetter.typeParameters.map { it.defaultType }
generateDelegatedPropertyGetterBody(
irGetter,
ktDelegate, getterDescriptor, delegateReceiverValue,
createCallableReference(ktDelegate, kPropertyType, propertyDescriptor, irGetter.symbol)
createCallableReference(ktDelegate, kPropertyType, propertyDescriptor, irGetter.symbol, typeArguments)
)
}
if (propertyDescriptor.isVar) {
val setterDescriptor = propertyDescriptor.setter!!
irProperty.setter = generateDelegatedPropertyAccessor(ktProperty, ktDelegate, setterDescriptor) { irSetter ->
val typeArguments = irSetter.typeParameters.map { it.defaultType }
generateDelegatedPropertySetterBody(
irSetter,
ktDelegate, setterDescriptor, delegateReceiverValue,
createCallableReference(ktDelegate, kPropertyType, propertyDescriptor, irSetter.symbol)
createCallableReference(ktDelegate, kPropertyType, propertyDescriptor, irSetter.symbol, typeArguments)
)
}
}
@@ -156,7 +160,8 @@ class DelegatedPropertyGenerator(declarationGenerator: DeclarationGenerator) : D
val statementGenerator = createBodyGenerator(scopeOwner).createStatementGenerator()
val provideDelegateCall = statementGenerator.pregenerateCall(provideDelegateResolvedCall)
provideDelegateCall.setExplicitReceiverValue(OnceExpressionValue(irDelegateInitializer.expression))
provideDelegateCall.irValueArgumentsByIndex[1] = createCallableReference(ktDelegate, kPropertyType, property, scopeOwner)
provideDelegateCall.irValueArgumentsByIndex[1] =
createCallableReference(ktDelegate, kPropertyType, property, scopeOwner, emptyList())
val irProvideDelegate = CallGenerator(statementGenerator).generateCall(
ktDelegate.startOffsetSkippingComments, ktDelegate.endOffset, provideDelegateCall
)
@@ -207,12 +212,17 @@ class DelegatedPropertyGenerator(declarationGenerator: DeclarationGenerator) : D
ktElement: KtElement,
type: KotlinType,
referencedDescriptor: VariableDescriptorWithAccessors,
scopeOwner: IrSymbol
scopeOwner: IrSymbol,
typeArguments: List<IrType>
): IrCallableReference =
createCallableReference(
ktElement, type, referencedDescriptor,
createBodyGenerator(scopeOwner).createStatementGenerator()
)
).apply {
typeArguments.forEachIndexed { i, typeArgument ->
putTypeArgument(i, typeArgument)
}
}
private fun createLocalDelegatedPropertyReference(
ktElement: KtElement,

View File

@@ -33,9 +33,9 @@ class ModuleGenerator(override val context: GeneratorContext) : Generator {
private val constantValueGenerator = context.constantValueGenerator
fun generateModuleFragment(ktFiles: Collection<KtFile>): IrModuleFragment =
fun generateModuleFragment(ktFiles: Collection<KtFile>, deserializer: IrDeserializer): IrModuleFragment =
generateModuleFragmentWithoutDependencies(ktFiles).also { irModule ->
generateUnboundSymbolsAsDependencies(irModule)
generateUnboundSymbolsAsDependencies(irModule, deserializer)
}
fun generateModuleFragmentWithoutDependencies(ktFiles: Collection<KtFile>): IrModuleFragment =
@@ -43,7 +43,7 @@ class ModuleGenerator(override val context: GeneratorContext) : Generator {
irModule.files.addAll(generateFiles(ktFiles))
}
fun generateUnboundSymbolsAsDependencies(irModule: IrModuleFragment, deserializer: IrDeserializer? = null) {
fun generateUnboundSymbolsAsDependencies(irModule: IrModuleFragment, deserializer: IrDeserializer) {
ExternalDependenciesGenerator(
irModule.descriptor, context.symbolTable, context.irBuiltIns, context.extensions.externalDeclarationOrigin, deserializer
).generateUnboundSymbolsAsDependencies()
@@ -62,7 +62,7 @@ class ModuleGenerator(override val context: GeneratorContext) : Generator {
for (ktAnnotationEntry in ktFile.annotationEntries) {
val annotationDescriptor = getOrFail(BindingContext.ANNOTATION, ktAnnotationEntry)
irFile.annotations.add(constantValueGenerator.generateAnnotationConstructorCall(annotationDescriptor))
irFile.annotations.addIfNotNull(constantValueGenerator.generateAnnotationConstructorCall(annotationDescriptor))
}
for (ktDeclaration in ktFile.declarations) {

View File

@@ -11,9 +11,13 @@ import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
interface MetadataSource {
class Class(val descriptor: ClassDescriptor) : MetadataSource
class Class(val descriptor: ClassDescriptor) : MetadataSource {
var serializedIr: ByteArray? = null
}
class File(val descriptors: List<DeclarationDescriptor>) : MetadataSource
class File(val descriptors: List<DeclarationDescriptor>) : MetadataSource {
var serializedIr: ByteArray? = null
}
class Function(val descriptor: FunctionDescriptor) : MetadataSource

View File

@@ -52,9 +52,7 @@ abstract class IrLazyDeclarationBase(
}
override val annotations: MutableList<IrConstructorCall> by lazy {
descriptor.annotations.map {
typeTranslator.constantValueGenerator.generateAnnotationConstructorCall(it)
}.toMutableList()
descriptor.annotations.mapNotNull(typeTranslator.constantValueGenerator::generateAnnotationConstructorCall).toMutableList()
}
override var metadata: Nothing?

View File

@@ -11,7 +11,6 @@ import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
import org.jetbrains.kotlin.ir.declarations.IrField
import org.jetbrains.kotlin.ir.declarations.IrProperty
import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.expressions.IrConstructorCall
import org.jetbrains.kotlin.ir.expressions.IrExpressionBody
import org.jetbrains.kotlin.ir.expressions.impl.IrExpressionBodyImpl
@@ -66,7 +65,11 @@ class IrLazyField(
override val descriptor: PropertyDescriptor = symbol.descriptor
override val overriddenSymbols: MutableList<IrFieldSymbol> = mutableListOf()
override val overriddenSymbols: MutableList<IrFieldSymbol> by lazyVar {
descriptor.overriddenDescriptors.mapTo(arrayListOf()) {
stubGenerator.generateFieldStub(it.original).symbol
}
}
override var type: IrType by lazyVar {
descriptor.type.toIrType()

View File

@@ -179,6 +179,13 @@ class IrBuiltIns(
else -> error("No KProperty for n=$n mutable=$mutable")
}
val classes = listOf(
anyClass, booleanClass, charClass, numberClass, byteClass, shortClass, intClass, longClass, floatClass, doubleClass,
nothingClass, unitClass, stringClass, collectionClass, arrayClass, throwableClass,
kCallableClass, kPropertyClass, kDeclarationContainerClass, kClassClass,
kProperty0Class, kProperty1Class, kProperty2Class, kMutableProperty0Class, kMutableProperty1Class, kMutableProperty2Class
)
// TODO switch to IrType
val primitiveTypes = listOf(bool, char, byte, short, int, long, float, double)
val primitiveTypesWithComparisons = listOf(char, byte, short, int, long, float, double)

View File

@@ -7,10 +7,10 @@ package org.jetbrains.kotlin.ir.util
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.NotFoundClasses
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.expressions.IrConstructorCall
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.impl.*
@@ -38,7 +38,19 @@ class ConstantValueGenerator(
endOffset: Int,
constantValue: ConstantValue<*>,
varargElementType: KotlinType? = null
): IrExpression {
): IrExpression =
// Assertion is safe here because annotation calls are not allowed in constant initializers
generateConstantOrAnnotationValueAsExpression(startOffset, endOffset, constantValue, varargElementType)!!
/**
* @return null if the constant value is an unresolved annotation
*/
private fun generateConstantOrAnnotationValueAsExpression(
startOffset: Int,
endOffset: Int,
constantValue: ConstantValue<*>,
varargElementType: KotlinType? = null
): IrExpression? {
val constantKtType = constantValue.getType(moduleDescriptor)
val constantType = constantKtType.toIrType()
@@ -103,10 +115,11 @@ class ConstantValueGenerator(
}
}
fun generateAnnotationConstructorCall(annotationDescriptor: AnnotationDescriptor): IrConstructorCall {
fun generateAnnotationConstructorCall(annotationDescriptor: AnnotationDescriptor): IrConstructorCall? {
val annotationType = annotationDescriptor.type
val annotationClassDescriptor = annotationType.constructor.declarationDescriptor as? ClassDescriptor
?: throw AssertionError("No declaration descriptor for annotation $annotationDescriptor")
val annotationClassDescriptor = annotationType.constructor.declarationDescriptor
if (annotationClassDescriptor !is ClassDescriptor) return null
if (annotationClassDescriptor is NotFoundClasses.MockClassDescriptor) return null
assert(DescriptorUtils.isAnnotationClass(annotationClassDescriptor)) {
"Annotation class expected: $annotationClassDescriptor"
@@ -143,4 +156,4 @@ class ConstantValueGenerator(
}
private fun KotlinType.getArrayElementType() = builtIns.getArrayElementType(this)
}
}

View File

@@ -20,11 +20,13 @@ import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFieldImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl
import org.jetbrains.kotlin.ir.declarations.lazy.*
import org.jetbrains.kotlin.ir.expressions.impl.IrErrorExpressionImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrExpressionBodyImpl
import org.jetbrains.kotlin.ir.symbols.IrFieldSymbol
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.symbols.IrTypeParameterSymbol
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.types.KotlinType
@@ -34,7 +36,7 @@ class DeclarationStubGenerator(
val symbolTable: SymbolTable,
languageVersionSettings: LanguageVersionSettings,
private val externalDeclarationOrigin: ((DeclarationDescriptor) -> IrDeclarationOrigin)? = null,
private val deserializer: IrDeserializer? = null
private val deserializer: IrDeserializer
) {
private val lazyTable = symbolTable.lazyWrapper
@@ -45,7 +47,8 @@ class DeclarationStubGenerator(
}
private val typeTranslator = TypeTranslator(lazyTable, languageVersionSettings, moduleDescriptor.builtIns, LazyScopedTypeParametersResolver(lazyTable), true)
private val typeTranslator =
TypeTranslator(lazyTable, languageVersionSettings, moduleDescriptor.builtIns, LazyScopedTypeParametersResolver(lazyTable), true)
private val constantValueGenerator = ConstantValueGenerator(moduleDescriptor, lazyTable)
init {
@@ -61,22 +64,30 @@ class DeclarationStubGenerator(
return symbolTable.declareExternalPackageFragment(descriptor)
}
fun generateMemberStub(descriptor: DeclarationDescriptor): IrDeclaration =
when (descriptor) {
is ClassDescriptor ->
if (DescriptorUtils.isEnumEntry(descriptor))
generateEnumEntryStub(descriptor)
else
generateClassStub(descriptor)
is ClassConstructorDescriptor ->
generateConstructorStub(descriptor)
is FunctionDescriptor ->
generateFunctionStub(descriptor)
is PropertyDescriptor ->
generatePropertyStub(descriptor)
else ->
throw AssertionError("Unexpected member descriptor: $descriptor")
}
fun generateMemberStub(descriptor: DeclarationDescriptor): IrDeclaration = when (descriptor) {
is ClassDescriptor ->
if (DescriptorUtils.isEnumEntry(descriptor))
generateEnumEntryStub(descriptor)
else
generateClassStub(descriptor)
is ClassConstructorDescriptor ->
generateConstructorStub(descriptor)
is FunctionDescriptor ->
generateFunctionStub(descriptor)
is PropertyDescriptor ->
generatePropertyStub(descriptor)
else ->
throw AssertionError("Unexpected member descriptor: $descriptor")
}
fun generateStubBySymbol(symbol: IrSymbol): IrDeclaration = when (symbol) {
is IrFieldSymbol ->
generateFieldStub(symbol.descriptor)
is IrTypeParameterSymbol ->
generateOrGetTypeParameterStub(symbol.descriptor)
else ->
generateMemberStub(symbol.descriptor)
}
private fun computeOrigin(descriptor: DeclarationDescriptor): IrDeclarationOrigin =
externalDeclarationOrigin?.invoke(descriptor) ?: IrDeclarationOrigin.IR_EXTERNAL_DECLARATION_STUB
@@ -95,8 +106,7 @@ class DeclarationStubGenerator(
UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, descriptor.original,
isDelegated = @Suppress("DEPRECATION") descriptor.isDelegated
) {
deserializer?.findDeserializedDeclaration(referenced) as? IrProperty
?: IrLazyProperty(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator, bindingContext)
IrLazyProperty(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator, bindingContext)
}
}
@@ -112,8 +122,7 @@ class DeclarationStubGenerator(
else computeOrigin(descriptor)
return symbolTable.declareField(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, descriptor.original, descriptor.type.toIrType()) {
deserializer?.findDeserializedDeclaration(referenced) as? IrField
?: IrLazyField(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
IrLazyField(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
}
}
@@ -124,10 +133,14 @@ class DeclarationStubGenerator(
}
if (createPropertyIfNeeded && descriptor is PropertyGetterDescriptor) {
return generatePropertyStub(descriptor.correspondingProperty).getter!!
val propertySymbol = symbolTable.referenceProperty(descriptor.correspondingProperty)
val property = deserializer.findDeserializedDeclaration(propertySymbol, ::generateStubBySymbol) as IrProperty
return property.getter!!
}
if (createPropertyIfNeeded && descriptor is PropertySetterDescriptor) {
return generatePropertyStub(descriptor.correspondingProperty).setter!!
val propertySymbol = symbolTable.referenceProperty(descriptor.correspondingProperty)
val property = deserializer.findDeserializedDeclaration(propertySymbol, ::generateStubBySymbol) as IrProperty
return property.setter!!
}
val origin =
@@ -139,8 +152,7 @@ class DeclarationStubGenerator(
origin,
descriptor.original
) {
deserializer?.findDeserializedDeclaration(referenced) as? IrSimpleFunction
?: IrLazyFunction(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
IrLazyFunction(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
}
}
@@ -154,8 +166,7 @@ class DeclarationStubGenerator(
return symbolTable.declareConstructor(
UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, descriptor.original
) {
deserializer?.findDeserializedDeclaration(referenced) as? IrConstructor
?: IrLazyConstructor(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
IrLazyConstructor(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
}
}
@@ -185,8 +196,7 @@ class DeclarationStubGenerator(
}
val origin = computeOrigin(descriptor)
return symbolTable.declareClass(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, descriptor) {
deserializer?.findDeserializedDeclaration(referenceClass) as? IrClass
?: IrLazyClass(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
IrLazyClass(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
}
}
@@ -197,8 +207,7 @@ class DeclarationStubGenerator(
}
val origin = computeOrigin(descriptor)
return symbolTable.declareEnumEntry(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, descriptor) {
deserializer?.findDeserializedDeclaration(referenced) as? IrEnumEntry
?: IrLazyEnumEntryImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
IrLazyEnumEntryImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
}
}
@@ -209,8 +218,7 @@ class DeclarationStubGenerator(
}
val origin = computeOrigin(descriptor)
return symbolTable.declareGlobalTypeParameter(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, descriptor) {
deserializer?.findDeserializedDeclaration(referenced) as? IrTypeParameter
?: IrLazyTypeParameter(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
IrLazyTypeParameter(UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, it, this, typeTranslator)
}
}

View File

@@ -18,17 +18,17 @@ package org.jetbrains.kotlin.ir.util
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import kotlin.math.min
class ExternalDependenciesGenerator(
moduleDescriptor: ModuleDescriptor,
val symbolTable: SymbolTable,
val irBuiltIns: IrBuiltIns,
externalDeclarationOrigin: ((DeclarationDescriptor) -> IrDeclarationOrigin)? = null,
private val deserializer: IrDeserializer? = null
private val deserializer: IrDeserializer = EmptyDeserializer
) {
private val stubGenerator = DeclarationStubGenerator(
moduleDescriptor, symbolTable, irBuiltIns.languageVersionSettings, externalDeclarationOrigin, deserializer
@@ -36,43 +36,31 @@ class ExternalDependenciesGenerator(
fun generateUnboundSymbolsAsDependencies() {
stubGenerator.unboundSymbolGeneration = true
ArrayList(symbolTable.unboundClasses).forEach {
stubGenerator.generateClassStub(it.descriptor)
}
ArrayList(symbolTable.unboundConstructors).forEach {
stubGenerator.generateConstructorStub(it.descriptor)
}
ArrayList(symbolTable.unboundEnumEntries).forEach {
stubGenerator.generateEnumEntryStub(it.descriptor)
}
ArrayList(symbolTable.unboundFields).forEach {
stubGenerator.generateFieldStub(it.descriptor)
}
ArrayList(symbolTable.unboundSimpleFunctions).forEach {
stubGenerator.generateFunctionStub(it.descriptor)
}
ArrayList(symbolTable.unboundProperties).forEach {
stubGenerator.generatePropertyStub(it.descriptor)
}
ArrayList(symbolTable.unboundTypeParameters).forEach {
stubGenerator.generateOrGetTypeParameterStub(it.descriptor)
/*
Deserializing a reference may lead to new unbound references, so we loop until none are left.
*/
var unbound = symbolTable.allUnbound
while (unbound.isNotEmpty()) {
for (symbol in unbound) {
deserializer.findDeserializedDeclaration(symbol, stubGenerator::generateStubBySymbol)
assert(symbol.isBound) { "$symbol unbound even after deserialization attempt" }
}
unbound = symbolTable.allUnbound
}
deserializer?.declareForwardDeclarations()
assertEmpty(symbolTable.unboundClasses, "classes")
assertEmpty(symbolTable.unboundConstructors, "constructors")
assertEmpty(symbolTable.unboundEnumEntries, "enum entries")
assertEmpty(symbolTable.unboundFields, "fields")
assertEmpty(symbolTable.unboundSimpleFunctions, "simple functions")
assertEmpty(symbolTable.unboundProperties, "properties")
assertEmpty(symbolTable.unboundTypeParameters, "type parameters")
deserializer.declareForwardDeclarations()
}
}
private fun assertEmpty(s: Set<IrSymbol>, marker: String) {
assert(s.isEmpty()) {
"$marker: ${s.size} unbound:\n" +
s.toList().subList(0, min(10, s.size)).joinToString(separator = "\n") { it.descriptor.toString() }
}
}
private val SymbolTable.allUnbound
get() =
unboundClasses + unboundConstructors + unboundEnumEntries + unboundFields +
unboundSimpleFunctions + unboundProperties + unboundTypeParameters
object EmptyDeserializer : IrDeserializer {
override fun findDeserializedDeclaration(symbol: IrSymbol, backoff: (IrSymbol) -> IrDeclaration): IrDeclaration? = backoff(symbol)
override fun declareForwardDeclarations() {}
}

View File

@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.source.PsiSourceElement
import org.jetbrains.kotlin.types.KotlinType
@@ -508,3 +509,29 @@ val IrDeclaration.file: IrFile get() = parent.let {
else -> TODO("Unexpected declaration parent")
}
}
fun SymbolTable.referenceMember(descriptor: DeclarationDescriptor): IrSymbol = when (descriptor) {
is ClassDescriptor ->
if (DescriptorUtils.isEnumEntry(descriptor))
referenceEnumEntry(descriptor)
else
referenceClass(descriptor)
is ClassConstructorDescriptor ->
referenceConstructor(descriptor)
is FunctionDescriptor ->
referenceSimpleFunction(descriptor)
is PropertyDescriptor ->
referenceProperty(descriptor)
is TypeParameterDescriptor ->
referenceTypeParameter(descriptor)
else ->
throw AssertionError("Unexpected member descriptor: $descriptor")
}
fun SymbolTable.findOrDeclareExternalPackageFragment(descriptor: PackageFragmentDescriptor) =
referenceExternalPackageFragment(descriptor).also {
if (!it.isBound) {
declareExternalPackageFragment(descriptor)
}
}.owner

View File

@@ -28,7 +28,7 @@ import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.impl.IrUninitializedType
interface IrDeserializer {
fun findDeserializedDeclaration(symbol: IrSymbol): IrDeclaration?
fun findDeserializedDeclaration(symbol: IrSymbol, backoff: (IrSymbol) -> IrDeclaration): IrDeclaration?
fun declareForwardDeclarations()
}

View File

@@ -131,9 +131,8 @@ class TypeTranslator(
}
private fun translateTypeAnnotations(annotations: Annotations): List<IrConstructorCall> =
annotations.map(constantValueGenerator::generateAnnotationConstructorCall)
annotations.mapNotNull(constantValueGenerator::generateAnnotationConstructorCall)
private fun translateTypeArguments(arguments: List<TypeProjection>) =
arguments.map {

View File

@@ -5,11 +5,8 @@
package org.jetbrains.kotlin.backend.common.serialization
import org.jetbrains.kotlin.backend.common.descriptors.WrappedClassConstructorDescriptor
import org.jetbrains.kotlin.backend.common.descriptors.WrappedSimpleFunctionDescriptor
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
@@ -134,7 +131,6 @@ abstract class DescriptorReferenceDeserializer(
}
if (isTypeParameter) {
for (m in (listOfNotNull(clazz) + members)) {
val typeParameters = when (m) {
is PropertyDescriptor -> m.typeParameters

View File

@@ -9,6 +9,7 @@ import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.util.isReal
import org.jetbrains.kotlin.ir.util.original
import org.jetbrains.kotlin.ir.util.resolveFakeOverride
/**
@@ -61,12 +62,12 @@ fun IrSimpleFunction.resolveFakeOverride(allowAbstract: Boolean = false): IrSimp
*/
internal fun IrSimpleFunction.resolveFakeOverrideMaybeAbstract() = this.resolveFakeOverride(allowAbstract = true)
internal fun IrProperty.resolveFakeOverrideMaybeAbstract() = this.getter!!.resolveFakeOverrideMaybeAbstract().correspondingProperty!!
internal fun IrField.resolveFakeOverrideMaybeAbstract() = this.correspondingProperty!!.getter!!.resolveFakeOverrideMaybeAbstract().correspondingProperty!!.backingField
internal fun IrProperty.resolveFakeOverrideMaybeAbstract() =
this.getter?.resolveFakeOverrideMaybeAbstract()?.correspondingPropertySymbol?.owner ?:
this.backingField!!.resolveFakeOverride()!!.correspondingPropertySymbol!!.owner
val IrSimpleFunction.target: IrSimpleFunction
get() = (if (modality == Modality.ABSTRACT) this else resolveFakeOverride()).original
get() = (if (modality == Modality.ABSTRACT) this else resolveFakeOverride(allowAbstract = false)).original
val IrFunction.target: IrFunction get() = when (this) {
is IrSimpleFunction -> this.target

View File

@@ -109,7 +109,7 @@ abstract class IrModuleDeserializer(
annotations
)
}
logger.log { "ir_type = $result; render = ${result.render()}" }
// logger.log { "ir_type = $result; render = ${result.render()}" }
return result
}
@@ -812,7 +812,7 @@ abstract class IrModuleDeserializer(
val operation = proto.operation
val expression = deserializeOperation(operation, start, end, type)
logger.log { "### Deserialized expression: ${ir2string(expression)} ir_type=$type" }
// logger.log { "### Deserialized expression: ${ir2string(expression)} ir_type=$type" } // parent may not be set, so logging fails
return expression
}
@@ -892,7 +892,7 @@ abstract class IrModuleDeserializer(
return parameter
}
private fun deserializeIrClass(
fun deserializeIrClass(
proto: KotlinIr.IrClass,
start: Int,
end: Int,
@@ -1059,7 +1059,7 @@ abstract class IrModuleDeserializer(
return initializer
}
private fun deserializeVisibility(value: KotlinIr.Visibility): Visibility { // TODO: switch to enum
protected open fun deserializeVisibility(value: KotlinIr.Visibility): Visibility { // TODO: switch to enum
return when (deserializeString(value.name)) {
"public" -> Visibilities.PUBLIC
"private" -> Visibilities.PRIVATE
@@ -1068,7 +1068,7 @@ abstract class IrModuleDeserializer(
"internal" -> Visibilities.INTERNAL
"invisible_fake" -> Visibilities.INVISIBLE_FAKE // TODO: eventually we should not serialize fake overrides, so this will be gone.
"local" -> Visibilities.LOCAL
else -> error("Unexpected visibility value: $value")
else -> error("Unexpected visibility value: ${deserializeString(value.name)}")
}
}

View File

@@ -7,6 +7,7 @@ package org.jetbrains.kotlin.backend.common.serialization
import org.jetbrains.kotlin.backend.common.LoggingContext
import org.jetbrains.kotlin.backend.common.ir.ir2string
import org.jetbrains.kotlin.backend.common.lower.parents
import org.jetbrains.kotlin.library.SerializedIr
import org.jetbrains.kotlin.library.impl.CombinedIrFileWriter
import org.jetbrains.kotlin.library.impl.DeclarationId
@@ -15,6 +16,7 @@ import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.ClassKind.*
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.descriptors.Visibilities.isPrivate
import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.SourceManager
@@ -36,7 +38,7 @@ open class IrModuleSerializer(
val logger: LoggingContext,
val declarationTable: DeclarationTable,
val mangler: KotlinMangler,
val bodiesOnlyForInlines: Boolean = false
val externallyVisibleOnly: Boolean = false
) {
private val loopIndex = mutableMapOf<IrLoop, Int>()
@@ -342,7 +344,7 @@ open class IrModuleSerializer(
private fun serializeCatch(catch: IrCatch): KotlinIr.IrCatch {
val proto = KotlinIr.IrCatch.newBuilder()
.setCatchParameter(serializeDeclaration(catch.catchParameter))
.setCatchParameter(serializeIrDeclaration(catch.catchParameter))
.setResult(serializeExpression(catch.result))
return proto.build()
}
@@ -852,7 +854,7 @@ open class IrModuleSerializer(
when (statement) {
is IrDeclaration -> {
logger.log { " ###Declaration " }; proto.declaration = serializeDeclaration(statement)
logger.log { " ###Declaration " }; proto.declaration = serializeIrDeclaration(statement)
}
is IrExpression -> {
logger.log { " ###Expression " }; proto.expression = serializeExpression(statement)
@@ -907,7 +909,7 @@ open class IrModuleSerializer(
private fun serializeIrTypeParameterContainer(typeParameters: List<IrTypeParameter>): KotlinIr.IrTypeParameterContainer {
val proto = KotlinIr.IrTypeParameterContainer.newBuilder()
typeParameters.forEach {
proto.addTypeParameter(serializeDeclaration(it))
proto.addTypeParameter(serializeIrDeclaration(it))
}
return proto.build()
}
@@ -921,13 +923,13 @@ open class IrModuleSerializer(
.setReturnType(serializeIrType(function.returnType))
.setTypeParameters(serializeIrTypeParameterContainer(function.typeParameters))
function.dispatchReceiverParameter?.let { proto.setDispatchReceiver(serializeDeclaration(it)) }
function.extensionReceiverParameter?.let { proto.setExtensionReceiver(serializeDeclaration(it)) }
function.dispatchReceiverParameter?.let { proto.setDispatchReceiver(serializeIrDeclaration(it)) }
function.extensionReceiverParameter?.let { proto.setExtensionReceiver(serializeIrDeclaration(it)) }
function.valueParameters.forEach {
//proto.addValueParameter(serializeIrValueParameter(it))
proto.addValueParameter(serializeDeclaration(it))
proto.addValueParameter(serializeIrDeclaration(it))
}
if (!bodiesOnlyForInlines || function.isInline) {
if (!externallyVisibleOnly || function.isInline) {
function.body?.let { proto.body = serializeStatement(it) }
}
return proto.build()
@@ -1027,8 +1029,13 @@ open class IrModuleSerializer(
.setIsExternal(field.isExternal)
.setIsStatic(field.isStatic)
.setType(serializeIrType(field.type))
val inLocalClass = field.parents.any { it is IrFunction }
val initializer = field.initializer?.expression
if (initializer != null) {
if (initializer != null && (
!externallyVisibleOnly ||
inLocalClass ||
field.correspondingPropertySymbol?.owner?.isConst == true)
) {
proto.initializer = serializeExpression(initializer)
}
return proto.build()
@@ -1046,11 +1053,14 @@ open class IrModuleSerializer(
return proto.build()
}
private fun serializeIrDeclarationContainer(declarations: List<IrDeclaration>): KotlinIr.IrDeclarationContainer {
protected fun serializeIrDeclarationContainer(declarations: List<IrDeclaration>): KotlinIr.IrDeclarationContainer {
val proto = KotlinIr.IrDeclarationContainer.newBuilder()
declarations.forEach {
//if (it is IrDeclarationWithVisibility && it.visibility == Visibilities.INVISIBLE_FAKE) return@forEach
proto.addDeclaration(serializeDeclaration(it))
if (externallyVisibleOnly && it is IrDeclarationWithVisibility && isPrivate(it.visibility)) {
return@forEach
}
proto.addDeclaration(serializeIrDeclaration(it))
}
return proto.build()
}
@@ -1064,7 +1074,7 @@ open class IrModuleSerializer(
OBJECT -> KotlinIr.ClassKind.OBJECT
}
private fun serializeIrClass(clazz: IrClass): KotlinIr.IrClass {
protected fun serializeIrClass(clazz: IrClass): KotlinIr.IrClass {
val proto = KotlinIr.IrClass.newBuilder()
.setName(serializeName(clazz.name))
.setSymbol(serializeIrSymbol(clazz.symbol))
@@ -1081,7 +1091,7 @@ open class IrModuleSerializer(
clazz.superTypes.forEach {
proto.addSuperType(serializeIrType(it))
}
clazz.thisReceiver?.let { proto.thisReceiver = serializeDeclaration(it) }
clazz.thisReceiver?.let { proto.thisReceiver = serializeIrDeclaration(it) }
return proto.build()
}
@@ -1091,16 +1101,18 @@ open class IrModuleSerializer(
.setName(serializeName(enumEntry.name))
.setSymbol(serializeIrSymbol(enumEntry.symbol))
enumEntry.initializerExpression?.let {
proto.initializer = serializeExpression(it)
if (!externallyVisibleOnly) {
enumEntry.initializerExpression?.let {
proto.initializer = serializeExpression(it)
}
}
enumEntry.correspondingClass?.let {
proto.correspondingClass = serializeDeclaration(it)
proto.correspondingClass = serializeIrDeclaration(it)
}
return proto.build()
}
private fun serializeDeclaration(declaration: IrDeclaration): KotlinIr.IrDeclaration {
fun serializeIrDeclaration(declaration: IrDeclaration): KotlinIr.IrDeclaration {
logger.log { "### serializing Declaration: ${ir2string(declaration)}" }
val declarator = KotlinIr.IrDeclarator.newBuilder()
@@ -1168,20 +1180,21 @@ open class IrModuleSerializer(
return@forEach
}
val byteArray = serializeDeclaration(it).toByteArray()
val byteArray = serializeIrDeclaration(it).toByteArray()
val uniqId = declarationTable.uniqIdByDeclaration(it)
writer.addDeclaration(DeclarationId(uniqId.index, uniqId.isLocal), byteArray)
proto.addDeclarationId(protoUniqId(uniqId))
}
// TODO: is it Konan specific?
// TODO: is it Konan specific? -- definitely not applicable to JVM
// Make sure that all top level properties are initialized on library's load.
file.declarations
if (!externallyVisibleOnly) {
// Make sure that all top level properties are initialized on library's load.
file.declarations
.filterIsInstance<IrProperty>()
.filter { it.backingField?.initializer != null && !it.isConst }
.forEach { proto.addExplicitlyExportedToCompiler(serializeIrSymbol(it.backingField!!.symbol)) }
}
// TODO: Konan specific
file.acceptVoid(object: IrElementVisitorVoid {

View File

@@ -6728,33 +6728,15 @@ public final class KotlinIr {
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
java.util.List<org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile>
getFileList();
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile getFile(int index);
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
int getFileCount();
}
@@ -6885,24 +6867,12 @@ public final class KotlinIr {
private java.util.List<org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile> file_;
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public java.util.List<org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile> getFileList() {
return file_;
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public java.util.List<? extends org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFileOrBuilder>
getFileOrBuilderList() {
@@ -6910,36 +6880,18 @@ public final class KotlinIr {
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public int getFileCount() {
return file_.size();
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile getFile(int index) {
return file_.get(index);
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFileOrBuilder getFileOrBuilder(
int index) {
@@ -7262,48 +7214,24 @@ public final class KotlinIr {
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public java.util.List<org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile> getFileList() {
return java.util.Collections.unmodifiableList(file_);
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public int getFileCount() {
return file_.size();
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile getFile(int index) {
return file_.get(index);
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public Builder setFile(
int index, org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile value) {
@@ -7317,12 +7245,6 @@ public final class KotlinIr {
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public Builder setFile(
int index, org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile.Builder builderForValue) {
@@ -7333,12 +7255,6 @@ public final class KotlinIr {
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public Builder addFile(org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile value) {
if (value == null) {
@@ -7351,12 +7267,6 @@ public final class KotlinIr {
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public Builder addFile(
int index, org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile value) {
@@ -7370,12 +7280,6 @@ public final class KotlinIr {
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public Builder addFile(
org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile.Builder builderForValue) {
@@ -7386,12 +7290,6 @@ public final class KotlinIr {
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public Builder addFile(
int index, org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile.Builder builderForValue) {
@@ -7402,12 +7300,6 @@ public final class KotlinIr {
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public Builder addAllFile(
java.lang.Iterable<? extends org.jetbrains.kotlin.backend.common.serialization.KotlinIr.IrFile> values) {
@@ -7419,12 +7311,6 @@ public final class KotlinIr {
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public Builder clearFile() {
file_ = java.util.Collections.emptyList();
@@ -7434,12 +7320,6 @@ public final class KotlinIr {
}
/**
* <code>repeated .org.jetbrains.kotlin.backend.common.serialization.IrFile file = 2;</code>
*
* <pre>
*required IrSymbolTable symbol_table = 3;
*required IrTypeTable type_table = 4;
*required StringTable string_table = 5;
* </pre>
*/
public Builder removeFile(int index) {
ensureFileIsMutable();

View File

@@ -394,10 +394,10 @@ abstract class KotlinIrLinker(
return topLevelDescriptor
}
override fun findDeserializedDeclaration(symbol: IrSymbol): IrDeclaration? {
override fun findDeserializedDeclaration(symbol: IrSymbol, backoff: (IrSymbol) -> IrDeclaration): IrDeclaration? {
if (!symbol.isBound) {
findDeserializedDeclarationForDescriptor(symbol.descriptor) ?: return null
findDeserializedDeclarationForDescriptor(symbol.descriptor) ?: return backoff(symbol)
}
assert(symbol.isBound) {

View File

@@ -244,7 +244,7 @@ abstract class KotlinManglerImpl: KotlinMangler {
private val IrProperty.symbolName: String
get() {
val extensionReceiver: String = getter!!.extensionReceiverParameter?.extensionReceiverNamePart ?: ""
val extensionReceiver: String = (getter ?: setter)?.extensionReceiverParameter?.extensionReceiverNamePart ?: ""
val containingDeclarationPart = parent.fqNameForIrSerialization.let {
if (it.isRoot) "" else "$it."

View File

@@ -5,13 +5,10 @@
package org.jetbrains.kotlin.backend.common.serialization
import org.jetbrains.kotlin.backend.common.serialization.resolveFakeOverride
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.util.isAccessor
import org.jetbrains.kotlin.ir.util.isGetter
import org.jetbrains.kotlin.ir.util.isSetter
import org.jetbrains.kotlin.ir.util.nameForIrSerialization
import org.jetbrains.kotlin.ir.util.nameForIrSerialization
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.resolve.DescriptorFactory
import org.jetbrains.kotlin.resolve.descriptorUtil.classId
@@ -77,7 +74,7 @@ open class DescriptorReferenceSerializer(
val realDeclaration = if (isFakeOverride) {
when (declaration) {
is IrSimpleFunction -> declaration.resolveFakeOverrideMaybeAbstract()
is IrField -> declaration.resolveFakeOverrideMaybeAbstract()
is IrField -> declaration.resolveFakeOverride()!!
is IrProperty -> declaration.resolveFakeOverrideMaybeAbstract()
else -> error("Unexpected fake override declaration")
}

View File

@@ -6,7 +6,7 @@
package org.jetbrains.kotlin.ir.backend.js
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.backend.common.LoggingContext
import org.jetbrains.kotlin.backend.common.EmptyLoggingContext
import org.jetbrains.kotlin.backend.common.serialization.DescriptorTable
import org.jetbrains.kotlin.library.impl.buildKoltinLibrary
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
@@ -27,6 +27,8 @@ import org.jetbrains.kotlin.ir.backend.js.lower.serialization.metadata.*
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.util.ExpectDeclarationRemover
import org.jetbrains.kotlin.ir.util.EmptyDeserializer
import org.jetbrains.kotlin.ir.util.IrDeserializer
import org.jetbrains.kotlin.ir.util.SymbolTable
import org.jetbrains.kotlin.ir.visitors.acceptVoid
import org.jetbrains.kotlin.js.analyze.TopDownAnalyzerFacadeForJS
@@ -64,12 +66,6 @@ fun loadKlib(klibPath: String) =
internal val JS_KLIBRARY_CAPABILITY = ModuleDescriptor.Capability<KotlinLibrary>("JS KLIBRARY")
private val emptyLoggingContext = object : LoggingContext {
override var inVerbosePhase = false
override fun log(message: () -> String) {}
}
private val CompilerConfiguration.metadataVersion
get() = get(CommonConfigurationKeys.METADATA_VERSION) as? JsKlibMetadataVersion ?: JsKlibMetadataVersion.INSTANCE
@@ -127,7 +123,7 @@ fun loadIr(
val symbolTable = psi2IrContext.symbolTable
val moduleDescriptor = psi2IrContext.moduleDescriptor
val deserializer = JsIrLinker(moduleDescriptor, emptyLoggingContext, irBuiltIns, symbolTable)
val deserializer = JsIrLinker(moduleDescriptor, EmptyLoggingContext, irBuiltIns, symbolTable)
val deserializedModuleFragments = allDependencies.map {
deserializer.deserializeIrModuleHeader(depsDescriptors.getModuleDescriptor(it))!!
@@ -151,7 +147,7 @@ private fun runAnalysisAndPreparePsi2Ir(depsDescriptors: ModulesStructure): Gene
)
}
private fun GeneratorContext.generateModuleFragment(files: List<KtFile>, deserializer: JsIrLinker? = null) =
private fun GeneratorContext.generateModuleFragment(files: List<KtFile>, deserializer: IrDeserializer = EmptyDeserializer) =
Psi2IrTranslator(languageVersionSettings, configuration).generateModuleFragment(this, files, deserializer)
@@ -285,7 +281,7 @@ fun serializeModuleIntoKlib(
) {
val declarationTable = JsDeclarationTable(moduleFragment.irBuiltins, DescriptorTable())
val serializedIr = JsIrModuleSerializer(emptyLoggingContext, declarationTable).serializedIrModule(moduleFragment)
val serializedIr = JsIrModuleSerializer(EmptyLoggingContext, declarationTable).serializedIrModule(moduleFragment)
val serializer = JsKlibMetadataSerializationUtil
val moduleDescription =

View File

@@ -12,5 +12,5 @@ import org.jetbrains.kotlin.backend.common.serialization.DeclarationTable
class JsIrModuleSerializer(
logger: LoggingContext,
declarationTable: DeclarationTable,
bodiesOnlyForInlines: Boolean = false
) : IrModuleSerializer(logger, declarationTable, JsMangler, bodiesOnlyForInlines)
externallyVisbileOnly: Boolean = false
) : IrModuleSerializer(logger, declarationTable, JsMangler, externallyVisbileOnly)

View File

@@ -0,0 +1,20 @@
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compile(project(":compiler:ir.tree"))
compile(project(":compiler:ir.serialization.common"))
compile(project(":compiler:ir.psi2ir"))
compile(project(":core:descriptors.jvm"))
compile(project(":core:metadata.jvm"))
compile(project(":compiler:frontend.java"))
}
sourceSets {
"main" {
projectDefault()
}
"test" {}
}

View File

@@ -0,0 +1,36 @@
syntax = "proto2";
package org.jetbrains.kotlin.backend.jvm.serialization;
import "compiler/ir/serialization.common/src/KotlinIr.proto";
option java_outer_classname = "JvmIr";
option optimize_for = LITE_RUNTIME;
/* Stored in JVM .class annotations */
message UniqIdInfo {
required int64 id = 1;
required common.serialization.String toplevel_fq_name = 2;
}
message UniqIdTable {
repeated UniqIdInfo infos = 1;
}
message AuxTables {
required common.serialization.IrSymbolTable symbol_table = 1;
required common.serialization.IrTypeTable type_table = 2;
required common.serialization.StringTable string_table = 3;
repeated common.serialization.IrDeclaration external_refs = 4;
required UniqIdTable uniq_id_table = 5;
}
message JvmIrFile {
required common.serialization.IrDeclarationContainer declaration_container = 1;
required common.serialization.Annotations annotations = 2;
required AuxTables aux_tables = 3;
}
message JvmIrClass {
required common.serialization.IrClass ir_class = 1;
required AuxTables aux_tables = 2;
}

View File

@@ -0,0 +1,268 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.jvm.serialization
import org.jetbrains.kotlin.backend.common.descriptors.*
import org.jetbrains.kotlin.backend.common.ir.copyParameterDeclarationsFrom
import org.jetbrains.kotlin.backend.common.ir.copyTypeParametersFrom
import org.jetbrains.kotlin.backend.common.ir.isTopLevel
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.*
import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression
import org.jetbrains.kotlin.ir.expressions.IrPropertyReference
import org.jetbrains.kotlin.ir.symbols.*
import org.jetbrains.kotlin.ir.symbols.impl.*
import org.jetbrains.kotlin.ir.types.IrErrorType
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun collectExternalReferences(toplevel: IrDeclarationContainer): List<IrDeclaration> {
val collection = ExternalReferenceCollection(toplevel)
toplevel.declarations.forEach {
it.accept(
object : IrElementVisitorVoid {
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
}
override fun visitFunctionAccess(expression: IrFunctionAccessExpression) {
// Copy is stored in collection.references.
collection.getCopy(expression.symbol.owner)
super.visitFunctionAccess(expression)
}
override fun visitPropertyReference(expression: IrPropertyReference, data: Nothing?) {
// Copying a getter or setter will store the whole property in collection.references.
collection.getCopy((expression.getter ?: expression.setter ?: expression.field)!!.owner)
super.visitPropertyReference(expression, data)
}
},
null
)
}
return collection.getToplevels()
}
class ExternalReferenceCollection(
val toplevel: IrDeclarationParent
) {
val references = mutableMapOf<IrSymbol, IrSymbolOwner>()
fun getToplevels(): List<IrDeclaration> =
references.mapNotNull {
it.safeAs<IrDeclaration>()?.takeIf { it.isTopLevel }
}
// Make a copy, preserving only the information needed to reference the object from a different serialization unit.
fun <T: IrSymbolOwner> getCopy(symbolOwner: T): T {
if (symbolOwner == toplevel) return symbolOwner
symbolOwner.safeAs<IrDeclaration>()?.findTopLevelDeclaration()?.let {
// we are either in a toplevel class or in a toplevel function or property.
if (it == toplevel || it.parent == toplevel) return symbolOwner
}
references[symbolOwner.symbol]?.let { return it as T }
when {
symbolOwner is IrPackageFragment ->
return IrExternalPackageFragmentImpl(
DescriptorlessExternalPackageFragmentSymbol(),
symbolOwner.fqName
).apply {
symbol.bind(this)
references[symbolOwner.symbol] = this
} as T
symbolOwner is IrDeclaration -> {
val parentCopy = getCopy(symbolOwner.parent as IrSymbolOwner) as IrDeclarationContainer
val newDeclaration = symbolOwner.bodilessCopyTo(parentCopy).apply {
require(this is IrSymbolOwner)
references[symbolOwner.symbol] = this
// Special case: we need to handle relations between properties and their accessors and fields.
// This should be done after putting the created declaration into `references`.
when (symbolOwner) {
is IrProperty -> {
require(this is IrProperty)
getter = symbolOwner.getter?.bodilessCopyTo(parentCopy) as IrSimpleFunction?
setter = symbolOwner.setter?.bodilessCopyTo(parentCopy) as IrSimpleFunction?
backingField = symbolOwner.backingField?.bodilessCopyTo(parentCopy) as IrField?
parentCopy.declarations.add(this)
}
is IrSimpleFunction -> {
require(this is IrSimpleFunction)
// Here and in the next clause, we use the fact that _in unlowered IR_
// property accessors and fields are not in their parent's declaration list.
if (symbolOwner.correspondingPropertySymbol != null) {
correspondingPropertySymbol = symbolOwner.correspondingPropertySymbol!!.owner.bodilessCopyTo(parentCopy)
.safeAs<IrProperty>()!!.symbol
} else {
parentCopy.declarations.add(this)
}
}
is IrField -> {
require(this is IrField)
if (symbolOwner.correspondingPropertySymbol != null) {
correspondingPropertySymbol = symbolOwner.correspondingPropertySymbol!!.owner.bodilessCopyTo(parentCopy)
.safeAs<IrProperty>()!!.symbol
} else {
parentCopy.declarations.add(this)
}
}
else -> parentCopy.declarations.add(this)
}
}
/* Kludge to work around annotations that are not correctly generated by Psi2Ir */
val annotations = symbolOwner.annotations.filter { annotation ->
(0 until annotation.valueArgumentsCount).all { i ->
annotation.getValueArgument(i)?.type !is IrErrorType
}
}
annotations.mapTo(newDeclaration.annotations) {
it.deepCopyWithExternalReferences(this)
}
return newDeclaration as T
}
else -> error("should never be reached")
}
}
// Type parameters in return/field types are not remapped, but this should not matter for serialization.
private fun IrDeclaration.bodilessCopyTo(newParent: IrDeclarationParent): IrDeclaration = when (this) {
is IrEnumEntry -> run {
val descriptor = WrappedEnumEntryDescriptor()
IrEnumEntryImpl(
startOffset, endOffset, origin, IrEnumEntrySymbolImpl(descriptor), name
).apply {
descriptor.bind(this)
parent = newParent
}
}
is IrClass -> {
val descriptor = WrappedClassDescriptor()
IrClassImpl(
startOffset, endOffset, origin,
IrClassSymbolImpl(descriptor),
name, kind, visibility, modality, isCompanion, isInner, isData, isExternal, isInline
).apply {
descriptor.bind(this)
parent = newParent
copyTypeParametersFrom(this@bodilessCopyTo)
}
}
is IrConstructor -> {
val descriptor = WrappedClassConstructorDescriptor()
IrConstructorImpl(
startOffset, endOffset, origin,
IrConstructorSymbolImpl(descriptor),
name, visibility, returnType, isInline, isExternal, isPrimary
).apply {
descriptor.bind(this)
parent = newParent
copyParameterDeclarationsFrom(this@bodilessCopyTo)
}
}
is IrSimpleFunction -> {
val descriptor = WrappedSimpleFunctionDescriptor()
IrFunctionImpl(
startOffset, endOffset, origin,
IrSimpleFunctionSymbolImpl(descriptor),
name, visibility, modality, returnType, isInline, isExternal, isTailrec, isSuspend
).apply {
descriptor.bind(this)
parent = newParent
copyParameterDeclarationsFrom(this@bodilessCopyTo)
}
}
is IrProperty -> {
val descriptor = WrappedPropertyDescriptor()
IrPropertyImpl(
startOffset, endOffset, origin,
IrPropertySymbolImpl(descriptor),
name, visibility, modality, isVar, isConst, isLateinit, isDelegated, isExternal
).apply {
descriptor.bind(this)
parent = newParent
}
}
is IrField -> {
val descriptor = WrappedFieldDescriptor()
IrFieldImpl(
startOffset, endOffset, origin,
IrFieldSymbolImpl(descriptor),
name, type, visibility, isFinal, isExternal, isStatic
).apply {
descriptor.bind(this)
parent = newParent
}
}
else -> error("Unsupported declaration type $this")
}
}
// This symbol remapper is only applied to annotations, so many types of entities should never occur.
private class ExternalReferenceSymbolRemapper(val referenceCollection: ExternalReferenceCollection) : SymbolRemapper {
override fun getDeclaredClass(symbol: IrClassSymbol) = error("should never be called")
override fun getDeclaredFunction(symbol: IrSimpleFunctionSymbol) = error("should never be called")
override fun getDeclaredProperty(symbol: IrPropertySymbol) = error("should never be called")
override fun getDeclaredField(symbol: IrFieldSymbol) = error("should never be called")
override fun getDeclaredFile(symbol: IrFileSymbol) = error("should never be called")
override fun getDeclaredConstructor(symbol: IrConstructorSymbol) = error("should never be called")
override fun getDeclaredEnumEntry(symbol: IrEnumEntrySymbol) = error("should never be called")
override fun getDeclaredExternalPackageFragment(symbol: IrExternalPackageFragmentSymbol) = error("should never be called")
override fun getDeclaredVariable(symbol: IrVariableSymbol) = error("should never be called")
override fun getDeclaredLocalDelegatedProperty(symbol: IrLocalDelegatedPropertySymbol) = error("should never be called")
override fun getDeclaredTypeParameter(symbol: IrTypeParameterSymbol) = error("should never be called")
override fun getDeclaredValueParameter(symbol: IrValueParameterSymbol) = error("should never be called")
override fun getReferencedClass(symbol: IrClassSymbol) = referenceCollection.getCopy(symbol.owner).symbol
override fun getReferencedClassOrNull(symbol: IrClassSymbol?) = symbol?.let { getReferencedClass(it) }
override fun getReferencedEnumEntry(symbol: IrEnumEntrySymbol) = referenceCollection.getCopy(symbol.owner).symbol
override fun getReferencedVariable(symbol: IrVariableSymbol) = error("should never be called")
override fun getReferencedLocalDelegatedProperty(symbol: IrLocalDelegatedPropertySymbol) = error("should never be called")
override fun getReferencedField(symbol: IrFieldSymbol) = referenceCollection.getCopy(symbol.owner).symbol
override fun getReferencedConstructor(symbol: IrConstructorSymbol) = referenceCollection.getCopy(symbol.owner).symbol
override fun getReferencedValue(symbol: IrValueSymbol) = referenceCollection.getCopy(symbol.owner).symbol
override fun getReferencedFunction(symbol: IrFunctionSymbol) = referenceCollection.getCopy(symbol.owner).symbol
override fun getReferencedProperty(symbol: IrPropertySymbol) = referenceCollection.getCopy(symbol.owner).symbol
override fun getReferencedSimpleFunction(symbol: IrSimpleFunctionSymbol) = referenceCollection.getCopy(symbol.owner).symbol
override fun getReferencedReturnableBlock(symbol: IrReturnableBlockSymbol) = error("should never be called")
override fun getReferencedClassifier(symbol: IrClassifierSymbol) = referenceCollection.getCopy(symbol.owner).symbol as IrClassifierSymbol
}
// Copied with modifications from `deepCopyWithSymbols`
private fun <T : IrElement> T.deepCopyWithExternalReferences(
referenceCollection: ExternalReferenceCollection,
initialParent: IrDeclarationParent? = null
): T {
val symbolRemapper = ExternalReferenceSymbolRemapper(referenceCollection)
val typeRemapper = DeepCopyTypeRemapper(symbolRemapper)
return transform(DeepCopyIrTreeWithSymbols(symbolRemapper, typeRemapper), null).patchDeclarationParents(initialParent) as T
}
// Copied from MoveBodilessDeclarationsToSeparatePlace.kt
private class DescriptorlessExternalPackageFragmentSymbol : IrExternalPackageFragmentSymbol {
override val descriptor: PackageFragmentDescriptor
get() = error("Operation is unsupported")
private var _owner: IrExternalPackageFragment? = null
override val owner get() = _owner!!
override val isBound get() = _owner != null
override fun bind(owner: IrExternalPackageFragment) {
_owner = owner
}
}

View File

@@ -0,0 +1,15 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.jvm.serialization
import org.jetbrains.kotlin.backend.common.serialization.DeclarationTable
import org.jetbrains.kotlin.backend.common.serialization.DescriptorTable
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
class JvmDeclarationTable(builtIns: IrBuiltIns, descriptorTable: DescriptorTable) :
DeclarationTable(builtIns, descriptorTable, JvmMangler) {
override var currentIndex = 0x1_0000_0000L
}

View File

@@ -0,0 +1,29 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.jvm.serialization
import org.jetbrains.kotlin.backend.common.serialization.DescriptorReferenceDeserializer
import org.jetbrains.kotlin.backend.common.serialization.DescriptorUniqIdAware
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.name.FqName
class JvmDescriptorReferenceDeserializer(currentModule: ModuleDescriptor, private val uniqIdAware: DescriptorUniqIdAware) :
DescriptorReferenceDeserializer(
currentModule,
mutableMapOf()
),
DescriptorUniqIdAware by uniqIdAware {
override fun resolveSpecialDescriptor(fqn: FqName): ClassDescriptor {
error("Should never be called")
}
override fun checkIfSpecialDescriptorId(id: Long) = false
override fun getDescriptorIdOrNull(descriptor: DeclarationDescriptor): Long? = null
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.jvm.serialization
import org.jetbrains.kotlin.backend.common.serialization.DescriptorUniqIdAware
import org.jetbrains.kotlin.backend.common.serialization.tryGetExtension
import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.declarations.IrDeclarationParent
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.load.java.descriptors.JavaClassConstructorDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaPropertyDescriptor
import org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf
import org.jetbrains.kotlin.serialization.deserialization.descriptors.*
class JvmDescriptorUniqIdAware(val symbolTable: SymbolTable, val fallback: (IrSymbol) -> IrDeclaration) : DescriptorUniqIdAware {
override fun DeclarationDescriptor.getUniqId(): Long? =
when (this) {
is DeserializedClassDescriptor -> this.classProto.tryGetExtension(JvmProtoBuf.classUniqId)
?: referenceAndHash(this)
is DeserializedSimpleFunctionDescriptor -> this.proto.tryGetExtension(JvmProtoBuf.functionUniqId)
?: referenceAndHash(this)
is DeserializedPropertyDescriptor -> this.proto.tryGetExtension(JvmProtoBuf.propertyUniqId)
?: referenceAndHash(this)
is DeserializedClassConstructorDescriptor -> this.proto.tryGetExtension(JvmProtoBuf.constructorUniqId)
?: referenceAndHash(this)
is DeserializedTypeParameterDescriptor -> this.proto.tryGetExtension(JvmProtoBuf.typeParamUniqId)
?: referenceAndHash(this)
is JavaClassDescriptor,
is JavaClassConstructorDescriptor,
is JavaMethodDescriptor,
is JavaPropertyDescriptor,
is FunctionClassDescriptor -> referenceAndHash(this)
else -> null
}
private fun referenceAndHash(descriptor: DeclarationDescriptor): Long? =
if (descriptor is CallableMemberDescriptor && descriptor.kind === CallableMemberDescriptor.Kind.FAKE_OVERRIDE)
null
else with(JvmMangler) {
referenceWithParents(descriptor).hashedMangle
}
private fun referenceWithParents(descriptor: DeclarationDescriptor): IrDeclaration {
val original = descriptor.original
val result = referenceOrDeclare(original)
var currentDescriptor = original
var current = result
while (true) {
val nextDescriptor = currentDescriptor.containingDeclaration!!
if (nextDescriptor is PackageFragmentDescriptor) {
current.parent = symbolTable.findOrDeclareExternalPackageFragment(nextDescriptor)
break
} else {
val next = referenceOrDeclare(nextDescriptor)
current.parent = next as IrDeclarationParent
currentDescriptor = nextDescriptor
current = next
}
}
return result
}
private fun referenceOrDeclare(descriptor: DeclarationDescriptor): IrDeclaration =
symbolTable.referenceMember(descriptor).also {
if (!it.isBound) {
fallback(it)
}
}.owner as IrDeclaration
}
// May be needed in the future
//
//fun DeclarationDescriptor.willBeEliminatedInLowerings(): Boolean =
// isAnnotationConstructor() ||
// (this is PropertyAccessorDescriptor &&
// correspondingProperty.hasJvmFieldAnnotation())

View File

@@ -0,0 +1,239 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.jvm.serialization
import org.jetbrains.kotlin.backend.common.LoggingContext
import org.jetbrains.kotlin.backend.common.descriptors.*
import org.jetbrains.kotlin.backend.common.serialization.*
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.expressions.impl.IrLoopBase
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrAnonymousInitializerSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrVariableSymbolImpl
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.ir.visitors.acceptVoid
import org.jetbrains.kotlin.load.java.JavaVisibilities
import org.jetbrains.kotlin.load.kotlin.JvmPackagePartSource
import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinarySourceElement
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor
class JvmIrDeserializer(
val module: ModuleDescriptor,
val logger: LoggingContext,
val builtIns: IrBuiltIns,
val symbolTable: SymbolTable,
val languageVersionSettings: LanguageVersionSettings
) : IrDeserializer {
val knownToplevelFqNames = mutableMapOf<Long, FqName>()
private val deserializedSymbols = mutableMapOf<UniqIdKey, IrSymbol>()
override fun findDeserializedDeclaration(symbol: IrSymbol, backoff: (IrSymbol) -> IrDeclaration): IrDeclaration? {
if (symbol.isBound) return symbol.owner as IrDeclaration
val descriptor =
symbol.descriptor as? DeserializedMemberDescriptor ?: symbol.descriptor as? DeserializedClassDescriptor
?: return backoff(symbol)
val moduleDescriptor = descriptor.module
val toplevelDescriptor = descriptor.toToplevel()
val packageFragment = symbolTable.findOrDeclareExternalPackageFragment(toplevelDescriptor.containingDeclaration as PackageFragmentDescriptor)
if (toplevelDescriptor is ClassDescriptor) {
val classHeader = (toplevelDescriptor.source as? KotlinJvmBinarySourceElement)?.binaryClass?.classHeader ?: return backoff(symbol)
if (classHeader.serializedIr == null || classHeader.serializedIr!!.size == 0) return backoff(symbol)
val irProto = JvmIr.JvmIrClass.parseFrom(classHeader.serializedIr)
val moduleDeserializer = ModuleDeserializer(moduleDescriptor, irProto.auxTables, backoff)
consumeUniqIdTable(irProto.auxTables.uniqIdTable, moduleDeserializer)
val deserializedToplevel = moduleDeserializer.deserializeIrClass(
irProto.irClass,
UNDEFINED_OFFSET, UNDEFINED_OFFSET,
IrDeclarationOrigin.IR_EXTERNAL_DECLARATION_STUB
)
deserializedToplevel.patchDeclarationParents(packageFragment) // TODO: toplevel's parent should be the module
assert(symbol.isBound)
return symbol.owner as IrDeclaration
} else {
val jvmPackagePartSource = (descriptor as DeserializedMemberDescriptor).containerSource as? JvmPackagePartSource ?: return backoff(symbol)
val classHeader = jvmPackagePartSource.knownJvmBinaryClass?.classHeader ?: return backoff(symbol)
if (classHeader.serializedIr == null || classHeader.serializedIr!!.size == 0) return backoff(symbol)
val irProto = JvmIr.JvmIrFile.parseFrom(classHeader.serializedIr)
val moduleDeserializer = ModuleDeserializer(moduleDescriptor, irProto.auxTables, backoff)
consumeUniqIdTable(irProto.auxTables.uniqIdTable, moduleDeserializer)
for (declaration in irProto.declarationContainer.declarationList) {
val member = moduleDeserializer.deserializeDeclaration(declaration, packageFragment)
packageFragment.declarations.add(member)
}
packageFragment.patchDeclarationParents(packageFragment)
assert(symbol.isBound)
return symbol.owner as IrDeclaration
}
}
override fun declareForwardDeclarations() {}
private fun consumeUniqIdTable(table: JvmIr.UniqIdTable, moduleDeserializer: ModuleDeserializer) {
for (entry in table.infosList) {
val id = entry.id
val toplevelFqName = FqName(moduleDeserializer.deserializeString(entry.toplevelFqName))
val oldFqName = knownToplevelFqNames[id]
assert(oldFqName == null || oldFqName == toplevelFqName) { "FqName table clash: $oldFqName vs $toplevelFqName" }
knownToplevelFqNames[id] = toplevelFqName
}
}
private tailrec fun DeclarationDescriptor.toToplevel(): DeclarationDescriptor =
if (containingDeclaration is PackageFragmentDescriptor) this else containingDeclaration!!.toToplevel()
inner class ModuleDeserializer(
val moduleDescriptor: ModuleDescriptor,
val auxTables: JvmIr.AuxTables,
backoff: (IrSymbol) -> IrDeclaration
) :
IrModuleDeserializer(logger, builtIns, symbolTable) {
val uniqIdAware = JvmDescriptorUniqIdAware(symbolTable, backoff)
val descriptorReferenceDeserializer = JvmDescriptorReferenceDeserializer(moduleDescriptor, uniqIdAware)
private var moduleLoops = mutableMapOf<Int, IrLoopBase>()
private fun referenceDeserializedSymbol(
proto: KotlinIr.IrSymbolData,
descriptor: DeclarationDescriptor?
): IrSymbol = when (proto.kind) {
KotlinIr.IrSymbolKind.ANONYMOUS_INIT_SYMBOL ->
IrAnonymousInitializerSymbolImpl(
descriptor as ClassDescriptor?
?: WrappedClassDescriptor()
)
KotlinIr.IrSymbolKind.CLASS_SYMBOL ->
symbolTable.referenceClass(
descriptor as ClassDescriptor?
?: WrappedClassDescriptor()
)
KotlinIr.IrSymbolKind.CONSTRUCTOR_SYMBOL ->
symbolTable.referenceConstructor(
descriptor as ClassConstructorDescriptor?
?: WrappedClassConstructorDescriptor()
)
KotlinIr.IrSymbolKind.TYPE_PARAMETER_SYMBOL ->
symbolTable.referenceTypeParameter(
descriptor as TypeParameterDescriptor?
?: WrappedTypeParameterDescriptor()
)
KotlinIr.IrSymbolKind.ENUM_ENTRY_SYMBOL ->
symbolTable.referenceEnumEntry(
descriptor as ClassDescriptor?
?: WrappedEnumEntryDescriptor()
)
KotlinIr.IrSymbolKind.STANDALONE_FIELD_SYMBOL ->
symbolTable.referenceField(WrappedFieldDescriptor())
KotlinIr.IrSymbolKind.FIELD_SYMBOL ->
symbolTable.referenceField(
descriptor as PropertyDescriptor?
?: WrappedPropertyDescriptor()
)
KotlinIr.IrSymbolKind.FUNCTION_SYMBOL ->
symbolTable.referenceSimpleFunction(
descriptor as FunctionDescriptor?
?: WrappedSimpleFunctionDescriptor()
)
KotlinIr.IrSymbolKind.VARIABLE_SYMBOL ->
IrVariableSymbolImpl(
descriptor as VariableDescriptor?
?: WrappedVariableDescriptor()
)
KotlinIr.IrSymbolKind.VALUE_PARAMETER_SYMBOL ->
IrValueParameterSymbolImpl(
descriptor as ParameterDescriptor?
?: WrappedValueParameterDescriptor()
)
KotlinIr.IrSymbolKind.RECEIVER_PARAMETER_SYMBOL ->
IrValueParameterSymbolImpl(
descriptor as ParameterDescriptor? ?: WrappedReceiverParameterDescriptor()
)
KotlinIr.IrSymbolKind.PROPERTY_SYMBOL ->
symbolTable.referenceProperty(
descriptor as PropertyDescriptor? ?: WrappedPropertyDescriptor()
)
else -> TODO("Unexpected classifier symbol kind: ${proto.kind}")
}
override fun deserializeString(proto: KotlinIr.String): String {
return auxTables.stringTable.getStrings(proto.index)
}
override fun deserializeIrType(proto: KotlinIr.IrTypeIndex): IrType {
val typeData = auxTables.typeTable.getTypes(proto.index)
return deserializeIrTypeData(typeData)
}
override fun deserializeIrSymbol(proto: KotlinIr.IrSymbol): IrSymbol {
val symbolData = auxTables.symbolTable.getSymbols(proto.index)
return deserializeIrSymbolData(symbolData)
}
private fun deserializeIrSymbolData(proto: KotlinIr.IrSymbolData): IrSymbol {
val key = proto.uniqId.uniqIdKey(moduleDescriptor)
val symbol = deserializedSymbols.getOrPut(key) {
val descriptor = if (proto.hasDescriptorReference()) {
deserializeDescriptorReference(proto.descriptorReference)
} else {
null
}
referenceDeserializedSymbol(proto, descriptor)
}
return symbol
}
override fun deserializeDescriptorReference(proto: KotlinIr.DescriptorReference) =
descriptorReferenceDeserializer.deserializeDescriptorReference(
deserializeString(proto.packageFqName),
deserializeString(proto.classFqName),
deserializeString(proto.name),
if (proto.hasUniqId()) proto.uniqId.index else null,
isEnumEntry = proto.isEnumEntry,
isEnumSpecial = proto.isEnumSpecial,
isDefaultConstructor = proto.isDefaultConstructor,
isFakeOverride = proto.isFakeOverride,
isGetter = proto.isGetter,
isSetter = proto.isSetter,
isTypeParameter = proto.isTypeParameter
)
override fun deserializeLoopHeader(loopIndex: Int, loopBuilder: () -> IrLoopBase) =
moduleLoops.getOrPut(loopIndex, loopBuilder)
override fun deserializeVisibility(value: KotlinIr.Visibility): Visibility = when (deserializeString(value.name)) {
"package" -> JavaVisibilities.PACKAGE_VISIBILITY
"protected_static" -> JavaVisibilities.PROTECTED_STATIC_VISIBILITY
"protected_and_package" -> JavaVisibilities.PROTECTED_AND_PACKAGE
else -> super.deserializeVisibility(value)
}
}
}

View File

@@ -0,0 +1,133 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.jvm.serialization
import org.jetbrains.kotlin.backend.common.LoggingContext
import org.jetbrains.kotlin.backend.common.ir.ir2string
import org.jetbrains.kotlin.backend.common.serialization.*
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression
import org.jetbrains.kotlin.ir.util.fqNameWhenAvailable
import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.load.java.descriptors.getImplClassNameForDeserialized
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi2ir.PsiSourceManager
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor
class JvmIrSerializer(
logger: LoggingContext,
declarationTable: DeclarationTable,
val psiSourceManager: PsiSourceManager,
externallyVisibleOnly: Boolean = true
) : IrModuleSerializer(logger, declarationTable, JvmMangler, externallyVisibleOnly) {
// Usage protocol: construct an instance, call only one of `serializeIrFile()` and `serializeTopLevelClass()` only once.
fun serializeJvmIrFile(irFile: IrFile): JvmIr.JvmIrFile {
val proto = JvmIr.JvmIrFile.newBuilder()
proto.declarationContainer = serializeIrDeclarationContainer(irFile.declarations.filter { it !is IrClass })
proto.annotations = serializeAnnotations(irFile.annotations)
val idCollector = UniqIdCollector(irFile.facadeFqName())
for (declaration in irFile.declarations) {
if (declaration !is IrClass) {
idCollector.collectUniqIds(declaration)
}
}
proto.auxTables = serializeAuxTables(idCollector.map, collectExternalReferences(irFile))
return proto.build()
}
fun serializeJvmToplevelClass(irClass: IrClass): JvmIr.JvmIrClass {
val proto = JvmIr.JvmIrClass.newBuilder()
proto.irClass = serializeIrClass(irClass)
val idMap = UniqIdCollector(irClass.fqNameWhenAvailable!!)
.apply { collectUniqIds(irClass) }
.map
proto.auxTables = serializeAuxTables(idMap, collectExternalReferences(irClass))
return proto.build()
}
private fun serializeAuxTables(idMap: Map<Long, FqName>, copiedExternalReferences: List<IrDeclaration>): JvmIr.AuxTables {
val proto = JvmIr.AuxTables.newBuilder()
proto.uniqIdTable = JvmIr.UniqIdTable.newBuilder() // This should come before serializing stringTable.
.addAllInfos(idMap.toList().map { (id, fqName) ->
JvmIr.UniqIdInfo.newBuilder()
.setId(id)
.setToplevelFqName(serializeString(fqName.asString()))
.build()
})
.build()
for (ref in copiedExternalReferences) {
proto.addExternalRefs(serializeIrDeclaration(ref))
}
proto.symbolTable = KotlinIr.IrSymbolTable.newBuilder()
.addAllSymbols(protoSymbolArray)
.build()
proto.typeTable = KotlinIr.IrTypeTable.newBuilder()
.addAllTypes(protoTypeArray)
.build()
proto.stringTable = KotlinIr.StringTable.newBuilder()
.addAllStrings(protoStringArray)
.build()
return proto.build()
}
private inner class UniqIdCollector(val ourToplevelFqName: FqName) : IrElementVisitorVoid {
val map = mutableMapOf<Long, FqName>()
fun collectUniqIds(declaration: IrDeclaration) {
declaration.acceptChildrenVoid(this)
}
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
}
override fun visitFunctionAccess(expression: IrFunctionAccessExpression) {
handleReference(expression.symbol.owner)
super.visitFunctionAccess(expression)
}
private fun handleReference(target: IrDeclaration) {
val targetToplevelFqName = target.getToplevelFqName()
if (targetToplevelFqName != ourToplevelFqName) {
val uniqId = with(JvmMangler) {
target.hashedMangle
}
map[uniqId] = targetToplevelFqName
}
}
}
private tailrec fun IrDeclaration.getToplevelFqName(): FqName =
when {
parent is IrDeclaration -> (parent as IrDeclaration).getToplevelFqName() // not toplevel
this is IrClass -> fqNameWhenAvailable!!
parent is IrFile -> (parent as IrFile).facadeFqName()
parent is IrExternalPackageFragment -> (parent as IrExternalPackageFragment).fqName
parent is IrModuleFragment -> (descriptor as DeserializedMemberDescriptor).getImplClassNameForDeserialized()?.fqNameForTopLevelClassMaybeWithDollars
?: error("Unknown impl class name for $descriptor")
else -> error("Unknown element in Ir tree: ${ir2string(this)}")
}
fun IrFile.facadeFqName(): FqName {
val fileEntry = fileEntry
val ktFile = psiSourceManager.getKtFile(fileEntry as PsiSourceManager.PsiFileEntry)
?: throw AssertionError("Unexpected file entry: $fileEntry")
val fileClassInfo = JvmFileClassUtil.getFileClassInfoNoResolve(ktFile)
return fileClassInfo.facadeClassFqName
}
}

View File

@@ -0,0 +1,20 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.jvm.serialization
import org.jetbrains.kotlin.backend.common.serialization.KotlinManglerImpl
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.util.isInlined
object JvmMangler : KotlinManglerImpl() {
// TODO: think about this
override val String.hashMangle: Long
get() =
this.hashCode().toLong()
override val IrType.isInlined: Boolean
get() = this.isInlined()
}

View File

@@ -1,4 +1,3 @@
// IGNORE_BACKEND: JVM_IR
// IGNORE_BACKEND: JS_IR
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE

View File

@@ -1,4 +1,3 @@
// IGNORE_BACKEND: JVM_IR
// TARGET_BACKEND: JVM
public object SomeObject {

View File

@@ -0,0 +1,6 @@
package a
interface A {
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.TYPE_PARAMETER)
annotation class Anno(val value: String)
}

View File

@@ -0,0 +1,9 @@
package b
import a.A
@A.Anno("B")
interface B {
@A.Anno("foo")
fun <@A.Anno("T") T> foo(t: T) = t
}

View File

@@ -0,0 +1,8 @@
package c
import b.B
// There should be _no_ error despite the fact that B and B#foo are annotated with an annotation which cannot be resolved
fun bar(b: B) {
b.foo("")
}

View File

@@ -0,0 +1,13 @@
// FILE: 1.kt
open class Base {
fun ok() = "OK"
}
inline fun inlineWithLocalClass(): String {
return (object : Base() {}).ok()
}
// FILE: 2.kt
fun box(): String = inlineWithLocalClass()

View File

@@ -0,0 +1,14 @@
// FILE: A.kt
open class A {
val ok: String = "OK"
}
class B : A()
// FILE: B.kt
fun box(): String {
return B().ok
}

View File

@@ -79,7 +79,7 @@ FILE fqName:<root> fileName:/genericPropertyRef.kt
$this: GET_FIELD 'FIELD DELEGATE name:additionalText$delegate type:<root>.DVal visibility:private [final,static] ' type=<root>.DVal origin=null
t: GET_VAR '<this>: <root>.Value<T of <root>.<get-additionalText>> declared in <root>.<get-additionalText>' type=<root>.Value<T of <root>.<get-additionalText>> origin=null
p: PROPERTY_REFERENCE 'public final additionalText: kotlin.Int [delegated,val]' field=null getter='public final fun <get-additionalText> <T> (): kotlin.Int declared in <root>' setter=null type=kotlin.reflect.KProperty1<<root>.Value<T of <root>.<get-additionalText>>, kotlin.Int> origin=PROPERTY_REFERENCE_FOR_DELEGATE
<1>: <none>
<1>: T of <root>.<get-additionalText>
PROPERTY name:additionalValue visibility:public modality:FINAL [delegated,val]
FIELD DELEGATE name:additionalValue$delegate type:<root>.DVal visibility:private [final,static]
EXPRESSION_BODY
@@ -95,7 +95,7 @@ FILE fqName:<root> fileName:/genericPropertyRef.kt
$this: GET_FIELD 'FIELD DELEGATE name:additionalValue$delegate type:<root>.DVal visibility:private [final,static] ' type=<root>.DVal origin=null
t: GET_VAR '<this>: <root>.Value<T of <root>.<get-additionalValue>> declared in <root>.<get-additionalValue>' type=<root>.Value<T of <root>.<get-additionalValue>> origin=null
p: PROPERTY_REFERENCE 'public final additionalValue: kotlin.Int [delegated,val]' field=null getter='public final fun <get-additionalValue> <T> (): kotlin.Int declared in <root>' setter=null type=kotlin.reflect.KProperty1<<root>.Value<T of <root>.<get-additionalValue>>, kotlin.Int> origin=PROPERTY_REFERENCE_FOR_DELEGATE
<1>: <none>
<1>: T of <root>.<get-additionalValue>
CLASS CLASS name:DVal modality:FINAL visibility:public superTypes:[kotlin.Any]
$this: VALUE_PARAMETER INSTANCE_RECEIVER name:<this> type:<root>.DVal
CONSTRUCTOR visibility:public <> (kmember:kotlin.Any) returnType:<root>.DVal [primary]

View File

@@ -88,13 +88,18 @@ abstract class AbstractBytecodeTextTest : CodegenTestCase() {
return kotlinFiles > 1
}
private val SERIALIZED_IR_FIELD_REGEX = Regex(""", si=\{".*?[^\\]"\}""")
fun checkGeneratedTextAgainstExpectedOccurrences(text: String, expectedOccurrences: List<OccurrenceInfo>) {
val expected = StringBuilder()
val actual = StringBuilder()
/* Remove serialized IR metadata */
val sanitizedText = SERIALIZED_IR_FIELD_REGEX.replace(text, "")
for (info in expectedOccurrences) {
expected.append(info).append("\n")
actual.append(info.getActualOccurrence(text)).append("\n")
actual.append(info.getActualOccurrence(sanitizedText)).append("\n")
}
try {

View File

@@ -62,7 +62,8 @@ abstract class AbstractIrTextTestCase : AbstractIrGeneratorTestCase() {
val stubGenerator = DeclarationStubGenerator(
irModule.descriptor,
SymbolTable(), // TODO
myEnvironment.configuration.languageVersionSettings
myEnvironment.configuration.languageVersionSettings,
deserializer = EmptyDeserializer
)
val path = wholeFile.path

View File

@@ -128,6 +128,11 @@ public class CompileKotlinAgainstKotlinTestGenerated extends AbstractCompileKotl
runTest("compiler/testData/compileKotlinAgainstKotlin/enum.kt");
}
@TestMetadata("fakeOverrideInLocalClass.kt")
public void testFakeOverrideInLocalClass() throws Exception {
runTest("compiler/testData/compileKotlinAgainstKotlin/fakeOverrideInLocalClass.kt");
}
@TestMetadata("inlineClassFromBinaryDependencies.kt")
public void testInlineClassFromBinaryDependencies() throws Exception {
runTest("compiler/testData/compileKotlinAgainstKotlin/inlineClassFromBinaryDependencies.kt");
@@ -268,6 +273,11 @@ public class CompileKotlinAgainstKotlinTestGenerated extends AbstractCompileKotl
runTest("compiler/testData/compileKotlinAgainstKotlin/platformTypes.kt");
}
@TestMetadata("propertyFakeOverride.kt")
public void testPropertyFakeOverride() throws Exception {
runTest("compiler/testData/compileKotlinAgainstKotlin/propertyFakeOverride.kt");
}
@TestMetadata("propertyReference.kt")
public void testPropertyReference() throws Exception {
runTest("compiler/testData/compileKotlinAgainstKotlin/propertyReference.kt");

View File

@@ -128,6 +128,11 @@ public class IrCompileKotlinAgainstKotlinTestGenerated extends AbstractIrCompile
runTest("compiler/testData/compileKotlinAgainstKotlin/enum.kt");
}
@TestMetadata("fakeOverrideInLocalClass.kt")
public void testFakeOverrideInLocalClass() throws Exception {
runTest("compiler/testData/compileKotlinAgainstKotlin/fakeOverrideInLocalClass.kt");
}
@TestMetadata("inlineClassFromBinaryDependencies.kt")
public void testInlineClassFromBinaryDependencies() throws Exception {
runTest("compiler/testData/compileKotlinAgainstKotlin/inlineClassFromBinaryDependencies.kt");
@@ -268,6 +273,11 @@ public class IrCompileKotlinAgainstKotlinTestGenerated extends AbstractIrCompile
runTest("compiler/testData/compileKotlinAgainstKotlin/platformTypes.kt");
}
@TestMetadata("propertyFakeOverride.kt")
public void testPropertyFakeOverride() throws Exception {
runTest("compiler/testData/compileKotlinAgainstKotlin/propertyFakeOverride.kt");
}
@TestMetadata("propertyReference.kt")
public void testPropertyReference() throws Exception {
runTest("compiler/testData/compileKotlinAgainstKotlin/propertyReference.kt");

View File

@@ -77,11 +77,11 @@ class CompileKotlinAgainstCustomBinariesTest : AbstractKotlinCompilerIntegration
private fun analyzeAndGetAllDescriptors(vararg extraClassPath: File): Collection<DeclarationDescriptor> =
DescriptorUtils.getAllDescriptors(analyzeFileToPackageView(*extraClassPath).memberScope)
private fun doTestBrokenLibrary(libraryName: String, vararg pathsToDelete: String) {
private fun doTestBrokenLibrary(libraryName: String, vararg pathsToDelete: String, additionalOptions: List<String> = emptyList()) {
// This function compiles a library, then deletes one class file and attempts to compile a Kotlin source against
// this broken library. The expected result is an error message from the compiler
val library = copyJarFileWithoutEntry(compileLibrary(libraryName), *pathsToDelete)
compileKotlin("source.kt", tmpdir, listOf(library))
compileKotlin("source.kt", tmpdir, listOf(library), additionalOptions = additionalOptions)
}
private fun doTestKotlinLibraryWithWrongMetadataVersion(
@@ -215,6 +215,10 @@ class CompileKotlinAgainstCustomBinariesTest : AbstractKotlinCompilerIntegration
doTestBrokenLibrary("library", "a/A\$Anno.class")
}
fun testMissingDependencyNestedAnnotationIr() {
doTestBrokenLibrary("library", "a/A\$Anno.class", additionalOptions = listOf("-Xuse-ir"))
}
fun testMissingDependencyConflictingLibraries() {
val library1 = copyJarFileWithoutEntry(
compileLibrary("library1"),

View File

@@ -34,6 +34,7 @@ public final class JvmAnnotationNames {
public static final String METADATA_PACKAGE_NAME_FIELD_NAME = "pn";
public static final String METADATA_MULTIFILE_CLASS_NAME_FIELD_NAME = METADATA_EXTRA_STRING_FIELD_NAME;
public static final String METADATA_EXTRA_INT_FIELD_NAME = "xi";
public static final String METADATA_SERIALIZED_IR_FIELD_NAME = "si";
public static final int METADATA_MULTIFILE_PARTS_INHERIT_FLAG = 1 << 0;
public static final int METADATA_PRE_RELEASE_FLAG = 1 << 1;

View File

@@ -31,7 +31,8 @@ class KotlinClassHeader(
val strings: Array<String>?,
private val extraString: String?,
val extraInt: Int,
val packageName: String?
val packageName: String?,
val serializedIr: ByteArray?
) {
// See kotlin.Metadata
enum class Kind(val id: Int) {

View File

@@ -20,6 +20,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.SourceElement;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.metadata.jvm.deserialization.BitEncoding;
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmBytecodeBinaryVersion;
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion;
import org.jetbrains.kotlin.name.ClassId;
@@ -59,6 +60,7 @@ public class ReadKotlinClassHeaderAnnotationVisitor implements AnnotationVisitor
private String[] strings = null;
private String[] incompatibleData = null;
private KotlinClassHeader.Kind headerKind = null;
private String[] serializedIrFields = null;
@Nullable
public KotlinClassHeader createHeader() {
@@ -79,6 +81,12 @@ public class ReadKotlinClassHeaderAnnotationVisitor implements AnnotationVisitor
return null;
}
byte[] serializedIr = null;
if (serializedIrFields != null) {
serializedIr = BitEncoding.decodeBytes(serializedIrFields);
}
return new KotlinClassHeader(
headerKind,
metadataVersion,
@@ -88,7 +96,8 @@ public class ReadKotlinClassHeaderAnnotationVisitor implements AnnotationVisitor
strings,
extraString,
extraInt,
packageName
packageName,
serializedIr
);
}
@@ -178,6 +187,9 @@ public class ReadKotlinClassHeaderAnnotationVisitor implements AnnotationVisitor
else if (METADATA_STRINGS_FIELD_NAME.equals(string)) {
return stringsArrayVisitor();
}
else if (METADATA_SERIALIZED_IR_FIELD_NAME.equals(string)) {
return serializedIrArrayVisitor();
}
else {
return null;
}
@@ -203,6 +215,16 @@ public class ReadKotlinClassHeaderAnnotationVisitor implements AnnotationVisitor
};
}
@NotNull
private AnnotationArrayArgumentVisitor serializedIrArrayVisitor() {
return new CollectStringArrayAnnotationVisitor() {
@Override
protected void visitEnd(@NotNull String[] result) {
serializedIrFields = result;
}
};
}
@Override
public void visitEnum(@NotNull Name name, @NotNull ClassId enumClassId, @NotNull Name enumEntryName) {
}

View File

@@ -90,6 +90,8 @@ message JvmPropertySignature {
extend Constructor {
optional JvmMethodSignature constructor_signature = 100;
optional int64 constructor_uniq_id = 101;
}
extend Function {
@@ -98,6 +100,8 @@ extend Function {
// For lambdas from bodies of inline functions copied to the use site, the JVM internal name of the original
// lambda class this class is copied from
optional int32 lambda_class_origin_name = 101 [(string_id_in_table) = true];
optional int64 function_uniq_id = 102;
}
extend Property {
@@ -107,6 +111,16 @@ extend Property {
isMovedFromInterfaceCompanion true if this property is declared in an interface companion, and the field is stored in the interface
*/
optional int32 flags = 101 [default = 0];
optional int64 property_uniq_id = 102;
}
extend EnumEntry {
optional int64 enum_entry_uniq_id = 100;
}
extend ValueParameter {
optional int64 value_param_uniq_id = 100;
}
extend Type {
@@ -116,6 +130,8 @@ extend Type {
extend TypeParameter {
repeated Annotation type_parameter_annotation = 100;
optional int64 type_param_uniq_id = 101;
}
extend Class {
@@ -127,6 +143,8 @@ extend Class {
// For anonymous objects from bodies of inline functions copied to the use site, the JVM internal name of the original
// anonymous object this class is copied from
optional int32 anonymous_object_origin_name = 103 [(string_id_in_table) = true];
optional int64 class_uniq_id = 104;
}
extend Package {

View File

@@ -8,16 +8,23 @@ public final class JvmProtoBuf {
public static void registerAllExtensions(
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite registry) {
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.constructorSignature);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.constructorUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.methodSignature);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.lambdaClassOriginName);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.functionUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.propertySignature);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.flags);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.propertyUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.enumEntryUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.valueParamUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.typeAnnotation);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.isRaw);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.typeParameterAnnotation);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.typeParamUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.classModuleName);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.classLocalVariable);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.anonymousObjectOriginName);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.classUniqId);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.packageModuleName);
registry.add(org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.packageLocalVariable);
}
@@ -3806,6 +3813,22 @@ public final class JvmProtoBuf {
100,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.MESSAGE,
org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf.JvmMethodSignature.class);
public static final int CONSTRUCTOR_UNIQ_ID_FIELD_NUMBER = 101;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Constructor { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessageLite.GeneratedExtension<
org.jetbrains.kotlin.metadata.ProtoBuf.Constructor,
java.lang.Long> constructorUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessageLite
.newSingularGeneratedExtension(
org.jetbrains.kotlin.metadata.ProtoBuf.Constructor.getDefaultInstance(),
0L,
null,
null,
101,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.INT64,
java.lang.Long.class);
public static final int METHOD_SIGNATURE_FIELD_NUMBER = 100;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Function { ... }</code>
@@ -3843,6 +3866,22 @@ public final class JvmProtoBuf {
101,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.INT32,
java.lang.Integer.class);
public static final int FUNCTION_UNIQ_ID_FIELD_NUMBER = 102;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Function { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessageLite.GeneratedExtension<
org.jetbrains.kotlin.metadata.ProtoBuf.Function,
java.lang.Long> functionUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessageLite
.newSingularGeneratedExtension(
org.jetbrains.kotlin.metadata.ProtoBuf.Function.getDefaultInstance(),
0L,
null,
null,
102,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.INT64,
java.lang.Long.class);
public static final int PROPERTY_SIGNATURE_FIELD_NUMBER = 100;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
@@ -3880,6 +3919,54 @@ public final class JvmProtoBuf {
101,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.INT32,
java.lang.Integer.class);
public static final int PROPERTY_UNIQ_ID_FIELD_NUMBER = 102;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessageLite.GeneratedExtension<
org.jetbrains.kotlin.metadata.ProtoBuf.Property,
java.lang.Long> propertyUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessageLite
.newSingularGeneratedExtension(
org.jetbrains.kotlin.metadata.ProtoBuf.Property.getDefaultInstance(),
0L,
null,
null,
102,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.INT64,
java.lang.Long.class);
public static final int ENUM_ENTRY_UNIQ_ID_FIELD_NUMBER = 100;
/**
* <code>extend .org.jetbrains.kotlin.metadata.EnumEntry { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessageLite.GeneratedExtension<
org.jetbrains.kotlin.metadata.ProtoBuf.EnumEntry,
java.lang.Long> enumEntryUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessageLite
.newSingularGeneratedExtension(
org.jetbrains.kotlin.metadata.ProtoBuf.EnumEntry.getDefaultInstance(),
0L,
null,
null,
100,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.INT64,
java.lang.Long.class);
public static final int VALUE_PARAM_UNIQ_ID_FIELD_NUMBER = 100;
/**
* <code>extend .org.jetbrains.kotlin.metadata.ValueParameter { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessageLite.GeneratedExtension<
org.jetbrains.kotlin.metadata.ProtoBuf.ValueParameter,
java.lang.Long> valueParamUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessageLite
.newSingularGeneratedExtension(
org.jetbrains.kotlin.metadata.ProtoBuf.ValueParameter.getDefaultInstance(),
0L,
null,
null,
100,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.INT64,
java.lang.Long.class);
public static final int TYPE_ANNOTATION_FIELD_NUMBER = 100;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Type { ... }</code>
@@ -3928,6 +4015,22 @@ public final class JvmProtoBuf {
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.MESSAGE,
false,
org.jetbrains.kotlin.metadata.ProtoBuf.Annotation.class);
public static final int TYPE_PARAM_UNIQ_ID_FIELD_NUMBER = 101;
/**
* <code>extend .org.jetbrains.kotlin.metadata.TypeParameter { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessageLite.GeneratedExtension<
org.jetbrains.kotlin.metadata.ProtoBuf.TypeParameter,
java.lang.Long> typeParamUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessageLite
.newSingularGeneratedExtension(
org.jetbrains.kotlin.metadata.ProtoBuf.TypeParameter.getDefaultInstance(),
0L,
null,
null,
101,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.INT64,
java.lang.Long.class);
public static final int CLASS_MODULE_NAME_FIELD_NUMBER = 101;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
@@ -3985,6 +4088,22 @@ public final class JvmProtoBuf {
103,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.INT32,
java.lang.Integer.class);
public static final int CLASS_UNIQ_ID_FIELD_NUMBER = 104;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessageLite.GeneratedExtension<
org.jetbrains.kotlin.metadata.ProtoBuf.Class,
java.lang.Long> classUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessageLite
.newSingularGeneratedExtension(
org.jetbrains.kotlin.metadata.ProtoBuf.Class.getDefaultInstance(),
0L,
null,
null,
104,
org.jetbrains.kotlin.protobuf.WireFormat.FieldType.INT64,
java.lang.Long.class);
public static final int PACKAGE_MODULE_NAME_FIELD_NUMBER = 101;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Package { ... }</code>

View File

@@ -60,7 +60,8 @@ val PROTO_PATHS: List<ProtoPath> = listOf(
ProtoPath("core/metadata.jvm/src/jvm_module.proto"),
ProtoPath("build-common/src/java_descriptors.proto"),
ProtoPath("compiler/ir/backend.js/src/js.proto", false),
ProtoPath("compiler/ir/serialization.common/src/KotlinIr.proto", false)
ProtoPath("compiler/ir/serialization.common/src/KotlinIr.proto", false),
ProtoPath("compiler/ir/serialization.jvm/src/JvmIr.proto", false)
)
private val EXT_OPTIONS_PROTO_PATH = ProtoPath("core/metadata/src/ext_options.proto")

View File

@@ -54,6 +54,7 @@ include ":kotlin-build-common",
":compiler:ir.ir2cfg",
":compiler:ir.backend.common",
":compiler:ir.serialization.common",
":compiler:ir.serialization.jvm",
":compiler:ir.serialization.js",
":compiler:backend.js",
":compiler:backend.jvm",
@@ -323,6 +324,7 @@ project(':compiler:ir.backend.common').projectDir = "$rootDir/compiler/ir/backen
project(':compiler:backend.js').projectDir = "$rootDir/compiler/ir/backend.js" as File
project(':compiler:backend.jvm').projectDir = "$rootDir/compiler/ir/backend.jvm" as File
project(':compiler:ir.serialization.common').projectDir = "$rootDir/compiler/ir/serialization.common" as File
project(':compiler:ir.serialization.jvm').projectDir = "$rootDir/compiler/ir/serialization.jvm" as File
project(':compiler:ir.serialization.js').projectDir = "$rootDir/compiler/ir/serialization.js" as File
project(':kotlin-util-io').projectDir = "$rootDir/compiler/util-io" as File
project(':kotlin-util-klib').projectDir = "$rootDir/compiler/util-klib" as File