Introduce new string table optimized for JVM class files

This format of the string table allows to reduce the size of the Kotlin
metadata in JVM class files by reusing constants already present in the
constant pool. Currently the string table produced by JvmStringTable is not
fully optimized in serialization (in particular, the 'substring' operation
which will be used to extract type names out of generic signature, is not used
at all), but the format and its complete support in the deserialization
(JvmNameResolver) allows future improvement without changing the binary version
This commit is contained in:
Alexander Udalov
2015-09-21 20:35:27 +03:00
parent 542bfab96f
commit 1036506b25
19 changed files with 4719 additions and 67 deletions
@@ -46,6 +46,8 @@ import org.jetbrains.kotlin.resolve.jvm.JvmClassName;
import org.jetbrains.kotlin.resolve.jvm.JvmPackage;
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin;
import org.jetbrains.kotlin.serialization.DescriptorSerializer;
import org.jetbrains.kotlin.codegen.serialization.JvmStringTable;
import org.jetbrains.kotlin.serialization.jvm.BitEncoding;
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor;
import org.jetbrains.kotlin.types.JetType;
@@ -842,7 +844,7 @@ public class AsmUtil {
av.visitEnd();
}
public static void writeAnnotationData(@NotNull AnnotationVisitor av, @NotNull byte[] bytes) {
public static void writeAnnotationData(@NotNull AnnotationVisitor av, @NotNull DescriptorSerializer serializer, @NotNull byte[] bytes) {
JvmCodegenUtil.writeAbiVersion(av);
AnnotationVisitor data = av.visitArray(JvmAnnotationNames.DATA_FIELD_NAME);
for (String string : BitEncoding.encodeBytes(bytes)) {
@@ -850,7 +852,9 @@ public class AsmUtil {
}
data.visitEnd();
AnnotationVisitor strings = av.visitArray(JvmAnnotationNames.STRINGS_FIELD_NAME);
// TODO: write the actual string table
for (String string : ((JvmStringTable) serializer.getStringTable()).getStrings()) {
strings.visit(null, string);
}
strings.visitEnd();
}
@@ -230,7 +230,7 @@ public class ClosureCodegen extends MemberCodegen<JetElement> {
ProtoBuf.Callable callableProto = serializer.callableProto(funDescriptor).build();
AnnotationVisitor av = v.getVisitor().visitAnnotation(asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_CALLABLE), true);
writeAnnotationData(av, serializer.serialize(callableProto));
writeAnnotationData(av, serializer, serializer.serialize(callableProto));
av.visitEnd();
}
@@ -253,7 +253,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
ProtoBuf.Class classProto = serializer.classProto(descriptor).build();
AnnotationVisitor av = v.getVisitor().visitAnnotation(asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_CLASS), true);
writeAnnotationData(av, serializer.serialize(classProto));
writeAnnotationData(av, serializer, serializer.serialize(classProto));
if (kind != null) {
av.visitEnum(
JvmAnnotationNames.KIND_FIELD_NAME,
@@ -20,6 +20,7 @@ import com.intellij.openapi.util.Pair;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.codegen.serialization.JvmStringTable;
import org.jetbrains.kotlin.codegen.state.JetTypeMapper;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor;
@@ -39,7 +40,7 @@ import static org.jetbrains.kotlin.codegen.JvmSerializationBindings.*;
public class JvmSerializerExtension extends SerializerExtension {
private final JvmSerializationBindings bindings;
private final JetTypeMapper typeMapper;
private final StringTableImpl stringTable = new StringTableImpl(this);
private final StringTable stringTable = new JvmStringTable(this);
private final AnnotationSerializer annotationSerializer = new AnnotationSerializer(stringTable);
public JvmSerializerExtension(@NotNull JvmSerializationBindings bindings, @NotNull JetTypeMapper typeMapper) {
@@ -95,7 +95,7 @@ public class MultifileClassPartCodegen(
if (packageProto.memberCount == 0) return
val av = v.newAnnotation(AsmUtil.asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_MULTIFILE_CLASS_PART), true)
AsmUtil.writeAnnotationData(av, serializer.serialize(packageProto))
AsmUtil.writeAnnotationData(av, serializer, serializer.serialize(packageProto))
av.visit(JvmAnnotationNames.MULTIFILE_CLASS_NAME_FIELD_NAME, multifileClassFqName.shortName().asString())
av.visitEnd()
}
@@ -290,7 +290,7 @@ public class PackageCodegen {
ProtoBuf.Package packageProto = serializer.packageProtoWithoutDescriptors().build();
AnnotationVisitor av = v.newAnnotation(asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_PACKAGE), true);
AsmUtil.writeAnnotationData(av, serializer.serialize(packageProto));
AsmUtil.writeAnnotationData(av, serializer, serializer.serialize(packageProto));
av.visitEnd();
}
@@ -128,7 +128,7 @@ public class PackagePartCodegen extends MemberCodegen<JetFile> {
if (packageProto.getMemberCount() == 0) return;
AnnotationVisitor av = v.newAnnotation(asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_FILE_FACADE), true);
writeAnnotationData(av, serializer.serialize(packageProto));
writeAnnotationData(av, serializer, serializer.serialize(packageProto));
av.visitEnd();
}
}
@@ -0,0 +1,132 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.codegen.serialization
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassOrPackageFragmentDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.load.kotlin.JvmNameResolver
import org.jetbrains.kotlin.resolve.descriptorUtil.classId
import org.jetbrains.kotlin.serialization.SerializerExtension
import org.jetbrains.kotlin.serialization.StringTable
import org.jetbrains.kotlin.serialization.jvm.JvmProtoBuf
import org.jetbrains.kotlin.serialization.jvm.JvmProtoBuf.StringTableTypes.Record
import org.jetbrains.kotlin.types.ErrorUtils
import java.io.OutputStream
import java.util.*
class JvmStringTable(private val extension: SerializerExtension) : StringTable {
public val strings = ArrayList<String>()
private val records = ArrayList<Record>()
private val map = HashMap<String, Int>()
private val localNames = HashSet<Int>()
override fun getStringIndex(string: String): Int =
map.getOrPut(string) {
strings.size().apply {
strings.add(string)
records.add(Record.newBuilder().apply {
// TODO: optimize, don't always store the operation
setOperation(Record.Operation.NONE)
}.build())
}
}
override fun getFqNameIndex(descriptor: ClassDescriptor): Int {
if (ErrorUtils.isError(descriptor)) {
throw IllegalStateException("Cannot get FQ name of error class: " + descriptor)
}
val string: String
val storeAsLiteral: Boolean
val parent = sequence(descriptor, DeclarationDescriptor::getContainingDeclaration).first { it !is ClassDescriptor }
if (parent is PackageFragmentDescriptor) {
val classId = descriptor.classId
val packageName = classId.packageFqName
val className = classId.relativeClassName.asString()
string =
if (packageName.isRoot) className
else packageName.asString().replace('.', '/') + "/" + className
// If any of the class names contains '$', we can't simply replace all '$' with '.' upon deserialization.
// This case is rather rare, so we're storing a literal string
storeAsLiteral = '$' in string && classId.relativeClassName.pathSegments().any { '$' in it.asString() }
}
else {
storeAsLiteral = true
string = descriptor.localClassName()
}
val isLocal = descriptor.containingDeclaration !is ClassOrPackageFragmentDescriptor
map[string]?.let { recordedIndex ->
if (isLocal == (recordedIndex in localNames)) {
return recordedIndex
}
}
val index = strings.size()
if (isLocal) {
localNames.add(index)
}
val record = Record.newBuilder()
if (storeAsLiteral) {
strings.add(string)
// TODO: optimize, don't always store the operation
record.setOperation(Record.Operation.NONE)
}
else {
val predefinedIndex = JvmNameResolver.getPredefinedStringIndex(string)
if (predefinedIndex != null) {
record.setPredefinedIndex(predefinedIndex)
record.setOperation(Record.Operation.NONE)
// TODO: move all records with predefined names to the end and do not write associated strings for them (since they are ignored)
strings.add("")
}
else {
record.setOperation(Record.Operation.DESC_TO_CLASS_ID)
strings.add("L$string;")
}
}
records.add(record.build())
map[string] = index
return index
}
private fun ClassDescriptor.localClassName(): String {
val container = containingDeclaration
return when (container) {
is ClassDescriptor -> container.localClassName() + "." + name.asString()
else -> extension.getLocalClassName(this)
}
}
override fun serializeTo(output: OutputStream) {
with(JvmProtoBuf.StringTableTypes.newBuilder()) {
addAllRecord(records)
addAllLocalName(localNames)
build().writeDelimitedTo(output)
}
}
}