Version 2.2.27
Cherry pick: Desugared library: GSON support
CL: https://r8-review.googlesource.com/c/r8/+/54760
Cherry pick: Desugared library: fix test expectation
CL: https://r8-review.googlesource.com/c/r8/+/54924
- cherry picked the GenericSignature* classes from 2.3.3.
- L8 now clears all attributes but the signature by default
- Interface duplication now parses the signature attribute, modifies it,
and writes it back instead of directly editing the DexClass
classSignature field which did not exist in 2.2.
Bug: 167649682
Change-Id: I6ec0b972977e51422cee83f1b2ebbf1be15eca6b
diff --git a/src/main/java/com/android/tools/r8/Version.java b/src/main/java/com/android/tools/r8/Version.java
index 0d8ef44..1031247 100644
--- a/src/main/java/com/android/tools/r8/Version.java
+++ b/src/main/java/com/android/tools/r8/Version.java
@@ -11,7 +11,7 @@
// This field is accessed from release scripts using simple pattern matching.
// Therefore, changing this field could break our release scripts.
- public static final String LABEL = "2.2.26";
+ public static final String LABEL = "2.2.27";
private Version() {
}
diff --git a/src/main/java/com/android/tools/r8/graph/DexClass.java b/src/main/java/com/android/tools/r8/graph/DexClass.java
index dede4e0..558806d 100644
--- a/src/main/java/com/android/tools/r8/graph/DexClass.java
+++ b/src/main/java/com/android/tools/r8/graph/DexClass.java
@@ -6,6 +6,7 @@
import com.android.tools.r8.dex.MixedSectionCollection;
import com.android.tools.r8.errors.CompilationError;
import com.android.tools.r8.errors.Unreachable;
+import com.android.tools.r8.graph.GenericSignature.ClassSignature;
import com.android.tools.r8.kotlin.KotlinClassLevelInfo;
import com.android.tools.r8.origin.Origin;
import com.android.tools.r8.utils.InternalOptions;
@@ -339,6 +340,20 @@
assert verifyNoDuplicateFields();
}
+ public ClassSignature getClassSignature(AppView<?> appView) {
+ for (DexAnnotation annotation : annotations().annotations) {
+ if (DexAnnotation.isSignatureAnnotation(annotation, appView.dexItemFactory())) {
+ return GenericSignature.parseClassSignature(
+ type.getName(),
+ DexAnnotation.getSignature(annotation),
+ origin,
+ appView.dexItemFactory(),
+ appView.options().reporter);
+ }
+ }
+ return ClassSignature.NO_CLASS_SIGNATURE;
+ }
+
private boolean verifyCorrectnessOfFieldHolder(DexEncodedField field) {
assert field.holder() == type
: "Expected field `"
diff --git a/src/main/java/com/android/tools/r8/graph/DexProgramClass.java b/src/main/java/com/android/tools/r8/graph/DexProgramClass.java
index b5fe6b8..13246eb 100644
--- a/src/main/java/com/android/tools/r8/graph/DexProgramClass.java
+++ b/src/main/java/com/android/tools/r8/graph/DexProgramClass.java
@@ -11,12 +11,15 @@
import com.android.tools.r8.dex.IndexedItemCollection;
import com.android.tools.r8.dex.MixedSectionCollection;
import com.android.tools.r8.errors.CompilationError;
+import com.android.tools.r8.graph.GenericSignature.ClassSignature;
+import com.android.tools.r8.graph.GenericSignature.ClassTypeSignature;
import com.android.tools.r8.ir.conversion.LensCodeRewriterUtils;
import com.android.tools.r8.kotlin.KotlinClassLevelInfo;
import com.android.tools.r8.naming.NamingLens;
import com.android.tools.r8.origin.Origin;
import com.android.tools.r8.shaking.AppInfoWithLiveness;
import com.android.tools.r8.utils.TraversalContinuation;
+import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -444,33 +447,71 @@
methodCollection.addDirectMethod(directMethod);
}
- public void addExtraInterfaces(List<DexType> extraInterfaces, DexItemFactory factory) {
+ public void replaceInterfaces(List<ClassTypeSignature> newInterfaces, AppView<?> appView) {
+ if (newInterfaces.isEmpty()) {
+ return;
+ }
+ clearInterfaces(appView);
+ addExtraInterfaces(newInterfaces, appView);
+ }
+
+ private void clearInterfaces(AppView<?> appView) {
+ interfaces = DexTypeList.empty();
+ ClassSignature classSignature = getClassSignature(appView);
+ if (classSignature.hasNoSignature()) {
+ return;
+ }
+ replaceSignatureAnnotation(
+ new ClassSignature(
+ classSignature.formalTypeParameters,
+ classSignature.superClassSignature,
+ ImmutableList.of()),
+ appView.dexItemFactory());
+ }
+
+ public void addExtraInterfaces(List<ClassTypeSignature> extraInterfaces, AppView<?> appView) {
if (extraInterfaces.isEmpty()) {
return;
}
addExtraInterfacesToInterfacesArray(extraInterfaces);
- addExtraInterfacesToSignatureAnnotationIfPresent(extraInterfaces, factory);
+ addExtraInterfacesToSignatureAnnotationIfPresent(extraInterfaces, appView);
}
- private void addExtraInterfacesToInterfacesArray(List<DexType> extraInterfaces) {
+ private void addExtraInterfacesToInterfacesArray(List<ClassTypeSignature> extraInterfaces) {
DexType[] newInterfaces =
Arrays.copyOf(interfaces.values, interfaces.size() + extraInterfaces.size());
for (int i = interfaces.size(); i < newInterfaces.length; i++) {
- newInterfaces[i] = extraInterfaces.get(i - interfaces.size());
+ newInterfaces[i] = extraInterfaces.get(i - interfaces.size()).type();
}
interfaces = new DexTypeList(newInterfaces);
}
private void addExtraInterfacesToSignatureAnnotationIfPresent(
- List<DexType> extraInterfaces, DexItemFactory factory) {
+ List<ClassTypeSignature> extraInterfaces, AppView<?> appView) {
// We need to introduce in the dalvik.annotation.Signature annotation the extra interfaces.
- // At this point we cheat and pretend the extraInterfaces simply don't use any generic types.
+ ClassSignature classSignature = getClassSignature(appView);
+ if (classSignature.hasNoSignature()) {
+ return;
+ }
+ ImmutableList.Builder<ClassTypeSignature> interfacesBuilder =
+ ImmutableList.<ClassTypeSignature>builder().addAll(classSignature.superInterfaceSignatures);
+ interfacesBuilder.addAll(extraInterfaces);
+ replaceSignatureAnnotation(
+ new ClassSignature(
+ classSignature.formalTypeParameters,
+ classSignature.superClassSignature,
+ interfacesBuilder.build()),
+ appView.dexItemFactory());
+ }
+
+ private void replaceSignatureAnnotation(ClassSignature classSignature, DexItemFactory factory) {
DexAnnotation[] annotations = annotations().annotations;
for (int i = 0; i < annotations.length; i++) {
DexAnnotation annotation = annotations[i];
if (DexAnnotation.isSignatureAnnotation(annotation, factory)) {
DexAnnotation[] rewrittenAnnotations = annotations.clone();
- rewrittenAnnotations[i] = rewriteSignatureAnnotation(annotation, extraInterfaces, factory);
+ rewrittenAnnotations[i] =
+ DexAnnotation.createSignatureAnnotation(classSignature.toString(), factory);
setAnnotations(new DexAnnotationSet(rewrittenAnnotations));
// There is at most one signature annotation, so we can return here.
return;
@@ -478,14 +519,16 @@
}
}
- private DexAnnotation rewriteSignatureAnnotation(
- DexAnnotation annotation, List<DexType> extraInterfaces, DexItemFactory factory) {
- String signature = DexAnnotation.getSignature(annotation);
- StringBuilder newSignatureBuilder = new StringBuilder(signature);
- for (DexType extraInterface : extraInterfaces) {
- newSignatureBuilder.append(extraInterface.descriptor.toString());
+ public void clearAnnotationsButSignature(DexItemFactory factory) {
+ DexAnnotation[] annotations = annotations().annotations;
+ for (DexAnnotation annotation : annotations) {
+ if (DexAnnotation.isSignatureAnnotation(annotation, factory)) {
+ setAnnotations(new DexAnnotationSet(new DexAnnotation[] {annotation}));
+ // There is at most one signature annotation, so we can return here.
+ return;
+ }
}
- return DexAnnotation.createSignatureAnnotation(newSignatureBuilder.toString(), factory);
+ clearAnnotations();
}
@Override
diff --git a/src/main/java/com/android/tools/r8/graph/GenericSignature.java b/src/main/java/com/android/tools/r8/graph/GenericSignature.java
index 2427913..9c34474 100644
--- a/src/main/java/com/android/tools/r8/graph/GenericSignature.java
+++ b/src/main/java/com/android/tools/r8/graph/GenericSignature.java
@@ -5,8 +5,10 @@
import static com.android.tools.r8.utils.DescriptorUtils.getClassBinaryNameFromDescriptor;
import static com.android.tools.r8.utils.DescriptorUtils.getDescriptorFromClassBinaryName;
+import static com.google.common.base.Predicates.alwaysTrue;
import com.android.tools.r8.errors.Unreachable;
+import com.android.tools.r8.naming.NamingLens;
import com.android.tools.r8.origin.Origin;
import com.android.tools.r8.utils.DescriptorUtils;
import com.android.tools.r8.utils.Reporter;
@@ -14,6 +16,7 @@
import java.lang.reflect.GenericSignatureFormatError;
import java.nio.CharBuffer;
import java.util.List;
+import java.util.function.Predicate;
/**
* Internal encoding of the generics signature attribute as defined by JVMS 7 $ 4.3.4.
@@ -125,6 +128,12 @@
default MethodTypeSignature asMethodTypeSignature() {
return null;
}
+
+ boolean hasSignature();
+
+ default boolean hasNoSignature() {
+ return !hasSignature();
+ }
}
public static class FormalTypeParameter {
@@ -192,14 +201,11 @@
return superInterfaceSignatures;
}
+ @Override
public boolean hasSignature() {
return this != NO_CLASS_SIGNATURE;
}
- public boolean hasNoSignature() {
- return !hasSignature();
- }
-
@Override
public boolean isClassSignature() {
return true;
@@ -217,6 +223,25 @@
visitor.visitSuperInterface(superInterface);
}
}
+
+ public String toRenamedString(NamingLens namingLens, Predicate<DexType> isTypeMissing) {
+ if (hasNoSignature()) {
+ return null;
+ }
+ GenericSignaturePrinter genericSignaturePrinter =
+ new GenericSignaturePrinter(namingLens, isTypeMissing);
+ genericSignaturePrinter.visitClassSignature(this);
+ return genericSignaturePrinter.toString();
+ }
+
+ @Override
+ public String toString() {
+ return toRenamedString(NamingLens.getIdentityLens(), alwaysTrue());
+ }
+
+ public static ClassSignature noSignature() {
+ return NO_CLASS_SIGNATURE;
+ }
}
public abstract static class TypeSignature {
@@ -300,6 +325,7 @@
return null;
}
+ @Override
public boolean hasSignature() {
return this != GenericSignature.NO_FIELD_TYPE_SIGNATURE;
}
@@ -309,6 +335,25 @@
public boolean isStar() {
return false;
}
+
+ public String toRenamedString(NamingLens namingLens, Predicate<DexType> isTypeMissing) {
+ if (hasNoSignature()) {
+ return null;
+ }
+ GenericSignaturePrinter genericSignaturePrinter =
+ new GenericSignaturePrinter(namingLens, isTypeMissing);
+ genericSignaturePrinter.visitTypeSignature(this);
+ return genericSignaturePrinter.toString();
+ }
+
+ @Override
+ public String toString() {
+ return toRenamedString(NamingLens.getIdentityLens(), alwaysTrue());
+ }
+
+ public static FieldTypeSignature noSignature() {
+ return NO_FIELD_TYPE_SIGNATURE;
+ }
}
static final class StarFieldTypeSignature extends FieldTypeSignature {
@@ -330,7 +375,7 @@
}
}
- public static final ClassTypeSignature NO_FIELD_TYPE_SIGNATURE =
+ private static final ClassTypeSignature NO_FIELD_TYPE_SIGNATURE =
new ClassTypeSignature(DexItemFactory.nullValueType, EMPTY_TYPE_ARGUMENTS);
public static class ClassTypeSignature extends FieldTypeSignature {
@@ -346,7 +391,11 @@
ClassTypeSignature enclosingTypeSignature;
ClassTypeSignature innerTypeSignature;
- ClassTypeSignature(DexType type, List<FieldTypeSignature> typeArguments) {
+ public ClassTypeSignature(DexType type) {
+ this(type, EMPTY_TYPE_ARGUMENTS);
+ }
+
+ public ClassTypeSignature(DexType type, List<FieldTypeSignature> typeArguments) {
this(type, typeArguments, WildcardIndicator.NOT_AN_ARGUMENT);
}
@@ -542,7 +591,7 @@
public static class MethodTypeSignature implements DexDefinitionSignature<DexEncodedMethod> {
- public static final MethodTypeSignature NO_METHOD_TYPE_SIGNATURE =
+ private static final MethodTypeSignature NO_METHOD_TYPE_SIGNATURE =
new MethodTypeSignature(
EMPTY_TYPE_PARAMS, EMPTY_TYPE_SIGNATURES, ReturnType.VOID, EMPTY_TYPE_SIGNATURES);
@@ -551,6 +600,10 @@
final ReturnType returnType;
final List<TypeSignature> throwsSignatures;
+ public static MethodTypeSignature noSignature() {
+ return NO_METHOD_TYPE_SIGNATURE;
+ }
+
MethodTypeSignature(
final List<FormalTypeParameter> formalTypeParameters,
List<TypeSignature> typeSignatures,
@@ -586,6 +639,7 @@
return true;
}
+ @Override
public boolean hasSignature() {
return this != NO_METHOD_TYPE_SIGNATURE;
}
@@ -605,6 +659,21 @@
public List<FormalTypeParameter> getFormalTypeParameters() {
return formalTypeParameters;
}
+
+ public String toRenamedString(NamingLens namingLens, Predicate<DexType> isTypeMissing) {
+ if (hasNoSignature()) {
+ return null;
+ }
+ GenericSignaturePrinter genericSignaturePrinter =
+ new GenericSignaturePrinter(namingLens, isTypeMissing);
+ genericSignaturePrinter.visitMethodSignature(this);
+ return genericSignaturePrinter.toString();
+ }
+
+ @Override
+ public String toString() {
+ return toRenamedString(NamingLens.getIdentityLens(), alwaysTrue());
+ }
}
public static ClassSignature parseClassSignature(
@@ -632,6 +701,9 @@
Origin origin,
DexItemFactory factory,
Reporter reporter) {
+ if (signature == null || signature.isEmpty()) {
+ return NO_FIELD_TYPE_SIGNATURE;
+ }
Parser parser = new Parser(factory);
try {
return parser.parseFieldTypeSignature(signature);
@@ -973,7 +1045,6 @@
if (symbol == '^') {
do {
scanSymbol();
-
// ThrowsSignature ::= ("^" ClassTypeSignature) | ("^" TypeVariableSignature).
if (symbol == 'T') {
throwsSignatureBuilder.add(updateTypeVariableSignature());
diff --git a/src/main/java/com/android/tools/r8/graph/GenericSignaturePrinter.java b/src/main/java/com/android/tools/r8/graph/GenericSignaturePrinter.java
new file mode 100644
index 0000000..f68675f
--- /dev/null
+++ b/src/main/java/com/android/tools/r8/graph/GenericSignaturePrinter.java
@@ -0,0 +1,184 @@
+// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+package com.android.tools.r8.graph;
+
+import com.android.tools.r8.graph.GenericSignature.ClassSignature;
+import com.android.tools.r8.graph.GenericSignature.ClassTypeSignature;
+import com.android.tools.r8.graph.GenericSignature.FieldTypeSignature;
+import com.android.tools.r8.graph.GenericSignature.FormalTypeParameter;
+import com.android.tools.r8.graph.GenericSignature.MethodTypeSignature;
+import com.android.tools.r8.graph.GenericSignature.ReturnType;
+import com.android.tools.r8.graph.GenericSignature.TypeSignature;
+import com.android.tools.r8.graph.GenericSignature.WildcardIndicator;
+import com.android.tools.r8.naming.NamingLens;
+import com.android.tools.r8.utils.DescriptorUtils;
+import java.util.List;
+import java.util.function.Predicate;
+
+public class GenericSignaturePrinter implements GenericSignatureVisitor {
+
+ private final NamingLens namingLens;
+ private final Predicate<DexType> isTypeMissing;
+
+ public GenericSignaturePrinter(NamingLens namingLens, Predicate<DexType> isTypeMissing) {
+ this.namingLens = namingLens;
+ this.isTypeMissing = isTypeMissing;
+ }
+
+ private final StringBuilder sb = new StringBuilder();
+
+ @Override
+ public void visitClassSignature(ClassSignature classSignature) {
+ classSignature.visit(this);
+ }
+
+ @Override
+ public void visitFieldTypeSignature(FieldTypeSignature fieldSignature) {
+ printFieldTypeSignature(fieldSignature, false);
+ }
+
+ @Override
+ public void visitMethodSignature(MethodTypeSignature methodSignature) {
+ methodSignature.visit(this);
+ }
+
+ @Override
+ public void visitMethodTypeSignatures(List<TypeSignature> typeSignatures) {
+ sb.append("(");
+ typeSignatures.forEach(this::visitTypeSignature);
+ sb.append(")");
+ }
+
+ @Override
+ public void visitReturnType(ReturnType returnType) {
+ if (returnType.isVoidDescriptor()) {
+ sb.append("V");
+ } else {
+ visitTypeSignature(returnType.typeSignature);
+ }
+ }
+
+ @Override
+ public void visitThrowsSignatures(List<TypeSignature> typeSignatures) {
+ for (TypeSignature typeSignature : typeSignatures) {
+ sb.append("^");
+ visitTypeSignature(typeSignature);
+ }
+ }
+
+ @Override
+ public void visitFormalTypeParameters(List<FormalTypeParameter> formalTypeParameters) {
+ if (formalTypeParameters.isEmpty()) {
+ return;
+ }
+ sb.append("<");
+ for (FormalTypeParameter formalTypeParameter : formalTypeParameters) {
+ sb.append(formalTypeParameter.name);
+ formalTypeParameter.visit(this);
+ }
+ sb.append(">");
+ }
+
+ @Override
+ public void visitClassBound(FieldTypeSignature fieldSignature) {
+ sb.append(":");
+ printFieldTypeSignature(fieldSignature, false);
+ }
+
+ @Override
+ public void visitInterfaceBound(FieldTypeSignature fieldSignature) {
+ sb.append(":");
+ printFieldTypeSignature(fieldSignature, false);
+ }
+
+ @Override
+ public void visitSuperClass(ClassTypeSignature classTypeSignature) {
+ printFieldTypeSignature(classTypeSignature, false);
+ }
+
+ @Override
+ public void visitSuperInterface(ClassTypeSignature classTypeSignature) {
+ printFieldTypeSignature(classTypeSignature, false);
+ }
+
+ @Override
+ public void visitTypeSignature(TypeSignature typeSignature) {
+ if (typeSignature.isBaseTypeSignature()) {
+ DexType type = typeSignature.asBaseTypeSignature().type;
+ sb.append(type.toDescriptorString());
+ } else {
+ printFieldTypeSignature(typeSignature.asFieldTypeSignature(), false);
+ }
+ }
+
+ @Override
+ public void visitSimpleClass(ClassTypeSignature classTypeSignature) {
+ printFieldTypeSignature(classTypeSignature, true);
+ }
+
+ @Override
+ public void visitTypeArguments(List<FieldTypeSignature> typeArguments) {
+ if (typeArguments.isEmpty()) {
+ return;
+ }
+ sb.append("<");
+ for (FieldTypeSignature typeArgument : typeArguments) {
+ WildcardIndicator wildcardIndicator = typeArgument.getWildcardIndicator();
+ if (wildcardIndicator != WildcardIndicator.NONE) {
+ assert wildcardIndicator != WildcardIndicator.NOT_AN_ARGUMENT;
+ sb.append(wildcardIndicator == WildcardIndicator.POSITIVE ? "+" : "-");
+ }
+ visitTypeSignature(typeArgument);
+ }
+ sb.append(">");
+ }
+
+ private void printFieldTypeSignature(
+ FieldTypeSignature fieldTypeSignature, boolean printingInner) {
+ // For inner member classes we only print the inner name and the type-arguments.
+ if (fieldTypeSignature.isStar()) {
+ sb.append("*");
+ } else if (fieldTypeSignature.isTypeVariableSignature()) {
+ sb.append("T").append(fieldTypeSignature.asTypeVariableSignature().typeVariable).append(";");
+ } else if (fieldTypeSignature.isArrayTypeSignature()) {
+ sb.append("[");
+ fieldTypeSignature.asArrayTypeSignature().visit(this);
+ } else {
+ assert fieldTypeSignature.isClassTypeSignature();
+ ClassTypeSignature classTypeSignature = fieldTypeSignature.asClassTypeSignature();
+ if (classTypeSignature.isNoSignature()) {
+ return;
+ }
+ String renamedString = namingLens.lookupDescriptor(classTypeSignature.type).toString();
+ if (!printingInner) {
+ sb.append("L").append(DescriptorUtils.getBinaryNameFromDescriptor(renamedString));
+ } else {
+ assert classTypeSignature.enclosingTypeSignature != null;
+ DexType enclosingType = classTypeSignature.enclosingTypeSignature.type;
+ String outerDescriptor = namingLens.lookupDescriptor(enclosingType).toString();
+ String innerClassName = DescriptorUtils.getInnerClassName(outerDescriptor, renamedString);
+ if (innerClassName == null && isTypeMissing.test(classTypeSignature.type)) {
+ assert renamedString.equals(classTypeSignature.type.toDescriptorString());
+ innerClassName =
+ DescriptorUtils.getInnerClassName(enclosingType.toDescriptorString(), renamedString);
+ }
+ if (innerClassName == null) {
+ // We can no longer encode the inner name in the generic signature.
+ return;
+ }
+ sb.append(".").append(innerClassName);
+ }
+ classTypeSignature.visit(this);
+ if (!printingInner) {
+ sb.append(";");
+ }
+ }
+ }
+
+ @Override
+ public String toString() {
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/com/android/tools/r8/graph/GenericSignatureVisitor.java b/src/main/java/com/android/tools/r8/graph/GenericSignatureVisitor.java
index 22ddca7..d3840dd 100644
--- a/src/main/java/com/android/tools/r8/graph/GenericSignatureVisitor.java
+++ b/src/main/java/com/android/tools/r8/graph/GenericSignatureVisitor.java
@@ -9,10 +9,9 @@
import com.android.tools.r8.graph.GenericSignature.ClassTypeSignature;
import com.android.tools.r8.graph.GenericSignature.FieldTypeSignature;
import com.android.tools.r8.graph.GenericSignature.FormalTypeParameter;
+import com.android.tools.r8.graph.GenericSignature.MethodTypeSignature;
import com.android.tools.r8.graph.GenericSignature.ReturnType;
import com.android.tools.r8.graph.GenericSignature.TypeSignature;
-import com.android.tools.r8.naming.MemberNaming.FieldSignature;
-import com.android.tools.r8.naming.MemberNaming.MethodSignature;
import java.util.List;
public interface GenericSignatureVisitor {
@@ -21,11 +20,11 @@
throw new Unreachable("Implement if visited");
}
- default void visitMethodSignature(MethodSignature methodSignature) {
+ default void visitMethodSignature(MethodTypeSignature methodSignature) {
throw new Unreachable("Implement if visited");
}
- default void visitFieldSignature(FieldSignature fieldSignature) {
+ default void visitFieldTypeSignature(FieldTypeSignature fieldSignature) {
throw new Unreachable("Implement if visited");
}
diff --git a/src/main/java/com/android/tools/r8/ir/desugar/DesugaredLibraryEmulatedInterfaceDuplicator.java b/src/main/java/com/android/tools/r8/ir/desugar/DesugaredLibraryEmulatedInterfaceDuplicator.java
new file mode 100644
index 0000000..9b5a4c9
--- /dev/null
+++ b/src/main/java/com/android/tools/r8/ir/desugar/DesugaredLibraryEmulatedInterfaceDuplicator.java
@@ -0,0 +1,124 @@
+// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+package com.android.tools.r8.ir.desugar;
+
+import com.android.tools.r8.graph.AppView;
+import com.android.tools.r8.graph.DexClass;
+import com.android.tools.r8.graph.DexProgramClass;
+import com.android.tools.r8.graph.DexType;
+import com.android.tools.r8.graph.GenericSignature;
+import com.android.tools.r8.graph.GenericSignature.ClassTypeSignature;
+import com.android.tools.r8.graph.GenericSignature.FieldTypeSignature;
+import com.google.common.collect.Sets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class DesugaredLibraryEmulatedInterfaceDuplicator {
+
+ final AppView<?> appView;
+ final Map<DexType, DexType> emulatedInterfaces;
+
+ public DesugaredLibraryEmulatedInterfaceDuplicator(AppView<?> appView) {
+ this.appView = appView;
+ emulatedInterfaces =
+ appView.options().desugaredLibraryConfiguration.getEmulateLibraryInterface();
+ }
+
+ public void duplicateEmulatedInterfaces() {
+ // All classes implementing an emulated interface now implements the interface and the
+ // emulated one, as well as hidden overrides, for correct emulated dispatch.
+ // We not that duplicated interfaces won't feature the correct type parameters in the
+ // class signature since such signature is expected to be unused.
+ for (DexProgramClass clazz : appView.appInfo().classes()) {
+ if (clazz.type == appView.dexItemFactory().objectType) {
+ continue;
+ }
+ if (emulatedInterfaces.containsKey(clazz.type)) {
+ transformEmulatedInterfaces(clazz);
+ } else {
+ duplicateEmulatedInterfaces(clazz);
+ }
+ }
+ }
+
+ private void transformEmulatedInterfaces(DexProgramClass clazz) {
+ List<ClassTypeSignature> newInterfaces = new ArrayList<>();
+ GenericSignature.ClassSignature classSignature = clazz.getClassSignature(appView);
+ for (int i = 0; i < clazz.interfaces.size(); i++) {
+ DexType itf = clazz.interfaces.values[i];
+ assert emulatedInterfaces.containsKey(itf);
+ List<FieldTypeSignature> typeArguments;
+ if (classSignature.hasNoSignature()) {
+ typeArguments = Collections.emptyList();
+ } else {
+ ClassTypeSignature classTypeSignature = classSignature.superInterfaceSignatures().get(i);
+ assert itf == classTypeSignature.type();
+ typeArguments = classTypeSignature.typeArguments();
+ }
+ newInterfaces.add(new ClassTypeSignature(emulatedInterfaces.get(itf), typeArguments));
+ }
+ clazz.replaceInterfaces(newInterfaces, appView);
+ }
+
+ private void duplicateEmulatedInterfaces(DexProgramClass clazz) {
+ List<DexType> extraInterfaces = new ArrayList<>();
+ LinkedList<DexClass> workList = new LinkedList<>();
+ Set<DexType> processed = Sets.newIdentityHashSet();
+ workList.add(clazz);
+ while (!workList.isEmpty()) {
+ DexClass dexClass = workList.removeFirst();
+ if (processed.contains(dexClass.type)) {
+ continue;
+ }
+ processed.add(dexClass.type);
+ if (dexClass.superType != appView.dexItemFactory().objectType) {
+ processSuperType(clazz.superType, extraInterfaces, workList);
+ }
+ for (DexType itf : dexClass.interfaces) {
+ processSuperType(itf, extraInterfaces, workList);
+ }
+ }
+ extraInterfaces = removeDuplicates(extraInterfaces);
+ List<ClassTypeSignature> extraInterfaceSignatures = new ArrayList<>();
+ for (DexType extraInterface : extraInterfaces) {
+ extraInterfaceSignatures.add(new ClassTypeSignature(extraInterface));
+ }
+ clazz.addExtraInterfaces(extraInterfaceSignatures, appView);
+ }
+
+ private List<DexType> removeDuplicates(List<DexType> extraInterfaces) {
+ if (extraInterfaces.size() <= 1) {
+ return extraInterfaces;
+ }
+ // TODO(b/161399032): It would be nice to remove duplicate based on inheritance, i.e.,
+ // if there is ConcurrentMap<K,V> and Map<K,V>, Map<K,V> can be removed.
+ return new ArrayList<>(new HashSet<>(extraInterfaces));
+ }
+
+ void processSuperType(
+ DexType superType, List<DexType> extraInterfaces, LinkedList<DexClass> workList) {
+ if (emulatedInterfaces.containsKey(superType)) {
+ extraInterfaces.add(emulatedInterfaces.get(superType));
+ } else {
+ DexClass superClass = appView.definitionFor(superType);
+ if (shouldProcessSuperclass(superClass)) {
+ workList.add(superClass);
+ }
+ }
+ }
+
+ private boolean shouldProcessSuperclass(DexClass superclazz) {
+ if (appView.options().isDesugaredLibraryCompilation()) {
+ return false;
+ }
+ // TODO(b/161399032): Pay-as-you-go design: stop duplication on library boundaries.
+ return superclazz != null && superclazz.isLibraryClass();
+ }
+}
diff --git a/src/main/java/com/android/tools/r8/ir/desugar/DesugaredLibraryRetargeter.java b/src/main/java/com/android/tools/r8/ir/desugar/DesugaredLibraryRetargeter.java
index 5280f61..73e6e4f 100644
--- a/src/main/java/com/android/tools/r8/ir/desugar/DesugaredLibraryRetargeter.java
+++ b/src/main/java/com/android/tools/r8/ir/desugar/DesugaredLibraryRetargeter.java
@@ -22,6 +22,7 @@
import com.android.tools.r8.graph.DexString;
import com.android.tools.r8.graph.DexType;
import com.android.tools.r8.graph.DexTypeList;
+import com.android.tools.r8.graph.GenericSignature.ClassTypeSignature;
import com.android.tools.r8.graph.MethodAccessFlags;
import com.android.tools.r8.graph.ParameterAnnotationsList;
import com.android.tools.r8.graph.ResolutionResult;
@@ -372,7 +373,8 @@
// applies up to 24.
for (DexEncodedMethod method : methods) {
clazz.addExtraInterfaces(
- Collections.singletonList(dispatchInterfaceTypeFor(method)), appView.dexItemFactory());
+ Collections.singletonList(new ClassTypeSignature(dispatchInterfaceTypeFor(method))),
+ appView);
if (clazz.lookupVirtualMethod(method.getReference()) == null) {
DexEncodedMethod newMethod = createForwardingMethod(method, clazz);
clazz.addVirtualMethod(newMethod);
diff --git a/src/main/java/com/android/tools/r8/ir/desugar/InterfaceMethodRewriter.java b/src/main/java/com/android/tools/r8/ir/desugar/InterfaceMethodRewriter.java
index e58eeba..36a1647 100644
--- a/src/main/java/com/android/tools/r8/ir/desugar/InterfaceMethodRewriter.java
+++ b/src/main/java/com/android/tools/r8/ir/desugar/InterfaceMethodRewriter.java
@@ -53,7 +53,6 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.IdentityHashMap;
-import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
@@ -921,63 +920,6 @@
return newMethods;
}
- private void duplicateEmulatedInterfaces() {
- // All classes implementing an emulated interface now implements the interface and the
- // emulated one, as well as hidden overrides, for correct emulated dispatch.
- for (DexProgramClass clazz : appView.appInfo().classes()) {
- if (clazz.type == appView.dexItemFactory().objectType) {
- continue;
- }
- List<DexType> extraInterfaces = new ArrayList<>();
- for (DexType type : clazz.interfaces.values) {
- if (emulatedInterfaces.containsKey(type)) {
- extraInterfaces.add(emulatedInterfaces.get(type));
- }
- }
- if (!appView.options().isDesugaredLibraryCompilation()) {
- assert clazz.superType != null;
- DexClass superClazz = appView.definitionFor(clazz.superType);
- if (superClazz != null && superClazz.isLibraryClass()) {
- List<DexType> itfs = emulatedInterfacesOf(superClazz);
- for (DexType itf : itfs) {
- extraInterfaces.add(emulatedInterfaces.get(itf));
- }
- }
- // Remove duplicates.
- if (extraInterfaces.size() > 1) {
- extraInterfaces = new ArrayList<>(new LinkedHashSet<>(extraInterfaces));
- }
- }
- clazz.addExtraInterfaces(extraInterfaces, appView.dexItemFactory());
- }
- }
-
- private List<DexType> emulatedInterfacesOf(DexClass superClazz) {
- if (superClazz.type == factory.objectType) {
- return Collections.emptyList();
- }
- ArrayList<DexType> itfs = new ArrayList<>();
- LinkedList<DexType> workList = new LinkedList<>();
- workList.add(superClazz.type);
- while (!workList.isEmpty()) {
- DexType dexType = workList.removeFirst();
- DexClass dexClass = appView.definitionFor(dexType);
- if (dexClass != null) {
- if (dexClass.superType != factory.objectType) {
- workList.add(dexClass.superType);
- }
- for (DexType itf : dexClass.interfaces.values) {
- if (emulatedInterfaces.containsKey(itf)) {
- itfs.add(itf);
- } else {
- workList.add(itf);
- }
- }
- }
- }
- return itfs;
- }
-
/**
* Move static and default interface methods to companion classes, add missing methods to forward
* to moved default methods implementation.
@@ -990,7 +932,7 @@
if (appView.options().isDesugaredLibraryCompilation()) {
generateEmulateInterfaceLibrary(builder);
}
- duplicateEmulatedInterfaces();
+ new DesugaredLibraryEmulatedInterfaceDuplicator(appView).duplicateEmulatedInterfaces();
// Process all classes first. Add missing forwarding methods to
// replace desugared default interface methods.
diff --git a/src/main/java/com/android/tools/r8/shaking/AnnotationRemover.java b/src/main/java/com/android/tools/r8/shaking/AnnotationRemover.java
index 1a8d708..92cb0f7 100644
--- a/src/main/java/com/android/tools/r8/shaking/AnnotationRemover.java
+++ b/src/main/java/com/android/tools/r8/shaking/AnnotationRemover.java
@@ -330,7 +330,7 @@
public static void clearAnnotations(AppView<?> appView) {
for (DexProgramClass clazz : appView.appInfo().classes()) {
- clazz.clearAnnotations();
+ clazz.clearAnnotationsButSignature(appView.dexItemFactory());
clazz.members().forEach(DexDefinition::clearAnnotations);
}
}
diff --git a/src/main/java/com/android/tools/r8/utils/DescriptorUtils.java b/src/main/java/com/android/tools/r8/utils/DescriptorUtils.java
index 95b0fde..a4cef91 100644
--- a/src/main/java/com/android/tools/r8/utils/DescriptorUtils.java
+++ b/src/main/java/com/android/tools/r8/utils/DescriptorUtils.java
@@ -552,6 +552,27 @@
binaryName.replace(DESCRIPTOR_PACKAGE_SEPARATOR, JAVA_PACKAGE_SEPARATOR));
}
+ /**
+ * Computes the inner name from the outer- and inner descriptors. If outer is not a prefix of the
+ * inner descriptor null is returned. Do not use this method if the relationship between inner and
+ * outer is not reflected in the name.
+ *
+ * @param outerDescriptor the outer descriptor, such as Lfoo/bar/Baz;
+ * @param innerDescriptor the inner descriptor, such as Lfoo/bar/Baz$Qux;
+ * @return the inner name or null, i.e. Qux in the example above
+ */
+ public static String getInnerClassName(String outerDescriptor, String innerDescriptor) {
+ if (innerDescriptor.length() <= outerDescriptor.length()) {
+ return null;
+ }
+ String prefix =
+ outerDescriptor.substring(0, outerDescriptor.length() - 1) + INNER_CLASS_SEPARATOR;
+ if (innerDescriptor.startsWith(prefix)) {
+ return innerDescriptor.substring(prefix.length(), innerDescriptor.length() - 1);
+ }
+ return null;
+ }
+
public static class ModuleAndDescriptor {
private final String module;
private final String descriptor;
diff --git a/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/LibraryEmptySubclassInterfaceTest.java b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/LibraryEmptySubclassInterfaceTest.java
index 98e1917..ced1c31 100644
--- a/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/LibraryEmptySubclassInterfaceTest.java
+++ b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/LibraryEmptySubclassInterfaceTest.java
@@ -8,7 +8,6 @@
import static org.hamcrest.MatcherAssert.assertThat;
import com.android.tools.r8.TestParameters;
-import com.android.tools.r8.utils.AndroidApiLevel;
import com.android.tools.r8.utils.BooleanUtils;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
@@ -58,9 +57,7 @@
return;
}
String keepRules = keepRuleConsumer.get();
- assertThat(keepRules, containsString("-keep class j$.util.Map"));
assertThat(keepRules, containsString("-keep class j$.util.concurrent.ConcurrentHashMap"));
- assertThat(keepRules, containsString("-keep class j$.util.concurrent.ConcurrentMap"));
}
@Test
diff --git a/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/AllMapsTestClass.java b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/AllMapsTestClass.java
new file mode 100644
index 0000000..4c15672
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/AllMapsTestClass.java
@@ -0,0 +1,347 @@
+// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+package com.android.tools.r8.desugar.desugaredlibrary.gson;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+public class AllMapsTestClass {
+ // Program class extending ConcurrentHashMap.
+ static class NullableConcurrentHashMap<K, V> extends ConcurrentHashMap<K, V> {
+ NullableConcurrentHashMap() {
+ super();
+ }
+
+ @SuppressWarnings("NullableProblems")
+ @Override
+ public V put(K key, V value) {
+ if (key == null || value == null) {
+ return null;
+ }
+ return super.put(key, value);
+ }
+
+ @Override
+ public void putAll(Map<? extends K, ? extends V> m) {
+ for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
+ put(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+ // Program class extending the library class HashMap, implementing Map.
+ static class NullableHashMap<K, V> extends HashMap<K, V> {
+ NullableHashMap() {
+ super();
+ }
+
+ @SuppressWarnings("NullableProblems")
+ @Override
+ public V put(K key, V value) {
+ if (key == null || value == null) {
+ return null;
+ }
+ return super.put(key, value);
+ }
+
+ @Override
+ public void putAll(Map<? extends K, ? extends V> m) {
+ for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
+ put(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+ // Program class implementing Map.
+ static class NullableMap<K, V> implements Map<K, V> {
+ private HashMap<K, V> map = new HashMap<>();
+
+ NullableMap() {
+ super();
+ }
+
+ @Override
+ public int size() {
+ return map.size();
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return map.isEmpty();
+ }
+
+ @Override
+ public boolean containsKey(Object key) {
+ return map.containsKey(key);
+ }
+
+ @Override
+ public boolean containsValue(Object value) {
+ return map.containsValue(value);
+ }
+
+ @Override
+ public V get(Object key) {
+ return map.get(key);
+ }
+
+ @Override
+ public V put(K key, V value) {
+ return map.put(key, value);
+ }
+
+ @Override
+ public V remove(Object key) {
+ return map.remove(key);
+ }
+
+ @Override
+ public void putAll(Map<? extends K, ? extends V> m) {
+ for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
+ put(entry.getKey(), entry.getValue());
+ }
+ }
+
+ @Override
+ public void clear() {
+ map.clear();
+ }
+
+ @Override
+ public Set<K> keySet() {
+ return map.keySet();
+ }
+
+ @Override
+ public Collection<V> values() {
+ return map.values();
+ }
+
+ @Override
+ public Set<Entry<K, V>> entrySet() {
+ return map.entrySet();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof NullableMap)) return false;
+ NullableMap<?, ?> that = (NullableMap<?, ?>) o;
+ return map.equals(that.map);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(map);
+ }
+ }
+ // Program class implementing ConcurrentMap.
+ static class NullableConcurrentMap<K, V> implements ConcurrentMap<K, V> {
+ private HashMap<K, V> map = new HashMap<>();
+
+ NullableConcurrentMap() {
+ super();
+ }
+
+ @Override
+ public int size() {
+ return map.size();
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return map.isEmpty();
+ }
+
+ @Override
+ public boolean containsKey(Object key) {
+ return map.containsKey(key);
+ }
+
+ @Override
+ public boolean containsValue(Object value) {
+ return map.containsValue(value);
+ }
+
+ @Override
+ public V get(Object key) {
+ return map.get(key);
+ }
+
+ @Override
+ public V put(K key, V value) {
+ return map.put(key, value);
+ }
+
+ @Override
+ public V remove(Object key) {
+ return map.remove(key);
+ }
+
+ @Override
+ public void putAll(Map<? extends K, ? extends V> m) {
+ for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
+ put(entry.getKey(), entry.getValue());
+ }
+ }
+
+ @Override
+ public void clear() {
+ map.clear();
+ }
+
+ @Override
+ public Set<K> keySet() {
+ return map.keySet();
+ }
+
+ @Override
+ public Collection<V> values() {
+ return map.values();
+ }
+
+ @Override
+ public Set<Entry<K, V>> entrySet() {
+ return map.entrySet();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof NullableConcurrentMap)) return false;
+ NullableConcurrentMap<?, ?> that = (NullableConcurrentMap<?, ?>) o;
+ return map.equals(that.map);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(map);
+ }
+
+ @Override
+ public V putIfAbsent(K key, V value) {
+ return null;
+ }
+
+ @Override
+ public boolean remove(Object key, Object value) {
+ return false;
+ }
+
+ @Override
+ public boolean replace(K key, V oldValue, V newValue) {
+ return false;
+ }
+
+ @Override
+ public V replace(K key, V value) {
+ return null;
+ }
+ }
+
+ static class Data {
+ final int id;
+ final String name;
+
+ Data(int id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof Data)) return false;
+ Data data = (Data) o;
+ return id == data.id && name.equals(data.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, name);
+ }
+
+ @Override
+ public String toString() {
+ return "Data{" + "id=" + id + ", name='" + name + '\'' + '}';
+ }
+ }
+
+ public static void main(String[] args) {
+ Gson gson = new Gson();
+
+ HashMap<Integer, Data> hashMap = new HashMap<>();
+ NullableHashMap<Integer, Data> nullableHashMap = new NullableHashMap<>();
+ NullableMap<Integer, Data> nullableMap = new NullableMap<>();
+ NullableConcurrentMap<Integer, Data> nullableConcurrentMap = new NullableConcurrentMap<>();
+ ConcurrentHashMap<Integer, Data> concurrentHashMap = new ConcurrentHashMap<>();
+ NullableConcurrentHashMap<Integer, Data> nullableConcurrentHashMap =
+ new NullableConcurrentHashMap<>();
+
+ fillMap(hashMap);
+ fillMap(nullableHashMap);
+ fillMap(nullableMap);
+ fillMap(nullableConcurrentMap);
+ fillMap(concurrentHashMap);
+ fillMap(nullableConcurrentHashMap);
+
+ // Serialization.
+ String hashMapJson = gson.toJson(hashMap);
+ String nullableHashMapJson = gson.toJson(nullableHashMap);
+ String nullableMapJson = gson.toJson(nullableMap);
+ String nullableConcurrentMapJson = gson.toJson(nullableConcurrentMap);
+ String concurrentHashMapJson = gson.toJson(concurrentHashMap);
+ String nullableConcurrentHashMapJson = gson.toJson(nullableConcurrentHashMap);
+
+ // Deserialization.
+ Type hashMapType = new TypeToken<HashMap<Integer, Data>>() {}.getType();
+ HashMap<Integer, Data> hashMapDeserialized = gson.fromJson(hashMapJson, hashMapType);
+ Type nullableHashMapType = new TypeToken<NullableHashMap<Integer, Data>>() {}.getType();
+ NullableHashMap<Integer, Data> nullableHashMapDeserialized =
+ gson.fromJson(nullableHashMapJson, nullableHashMapType);
+ Type nullableMapType = new TypeToken<NullableMap<Integer, Data>>() {}.getType();
+ NullableMap<Integer, Data> nullableMapDeserialized =
+ gson.fromJson(nullableMapJson, nullableMapType);
+ Type nullableConcurrentMapType =
+ new TypeToken<NullableConcurrentMap<Integer, Data>>() {}.getType();
+ NullableConcurrentMap<Integer, Data> nullableConcurrentMapDeserialized =
+ gson.fromJson(nullableConcurrentMapJson, nullableConcurrentMapType);
+ Type concurrentHashMapType = new TypeToken<ConcurrentHashMap<Integer, Data>>() {}.getType();
+ ConcurrentHashMap<Integer, Data> concurrentHashMapDeserialized =
+ gson.fromJson(concurrentHashMapJson, concurrentHashMapType);
+ Type nullableConcurrentHashMapType =
+ new TypeToken<NullableConcurrentHashMap<Integer, Data>>() {}.getType();
+ NullableConcurrentHashMap<Integer, Data> nullableConcurrentHashMapDeserialized =
+ gson.fromJson(nullableConcurrentHashMapJson, nullableConcurrentHashMapType);
+
+ // Printing.
+ System.out.println(hashMap.getClass() == hashMapDeserialized.getClass());
+ System.out.println(hashMap.equals(hashMapDeserialized));
+ System.out.println(nullableHashMap.getClass() == nullableHashMapDeserialized.getClass());
+ System.out.println(nullableHashMap.equals(nullableHashMapDeserialized));
+ System.out.println(nullableMap.getClass() == nullableMapDeserialized.getClass());
+ System.out.println(nullableMap.equals(nullableMapDeserialized));
+ System.out.println(
+ nullableConcurrentMap.getClass() == nullableConcurrentMapDeserialized.getClass());
+ System.out.println(nullableConcurrentMap.equals(nullableConcurrentMapDeserialized));
+ System.out.println(concurrentHashMap.getClass() == concurrentHashMapDeserialized.getClass());
+ System.out.println(concurrentHashMap.equals(concurrentHashMapDeserialized));
+ System.out.println(
+ nullableConcurrentHashMap.getClass() == nullableConcurrentHashMapDeserialized.getClass());
+ System.out.println(nullableConcurrentHashMap.equals(nullableConcurrentHashMapDeserialized));
+ }
+
+ public static void fillMap(Map<Integer, Data> map) {
+ map.put(1, new Data(1, "a"));
+ map.put(2, new Data(2, "b"));
+ map.put(3, new Data(3, "c"));
+ }
+}
diff --git a/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/LibrarySubclassInterfaceTest.java b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GetGenericInterfaceTest.java
similarity index 97%
rename from src/test/java/com/android/tools/r8/desugar/desugaredlibrary/LibrarySubclassInterfaceTest.java
rename to src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GetGenericInterfaceTest.java
index 29bb1cf..249f26f 100644
--- a/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/LibrarySubclassInterfaceTest.java
+++ b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GetGenericInterfaceTest.java
@@ -1,14 +1,14 @@
// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
+// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-package com.android.tools.r8.desugar.desugaredlibrary;
+package com.android.tools.r8.desugar.desugaredlibrary.gson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.android.tools.r8.TestParameters;
-import com.android.tools.r8.utils.AndroidApiLevel;
+import com.android.tools.r8.desugar.desugaredlibrary.DesugaredLibraryTestBase;
import com.android.tools.r8.utils.BooleanUtils;
import dalvik.system.PathClassLoader;
import java.sql.SQLDataException;
@@ -32,7 +32,7 @@
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
-public class LibrarySubclassInterfaceTest extends DesugaredLibraryTestBase {
+public class GetGenericInterfaceTest extends DesugaredLibraryTestBase {
private final TestParameters parameters;
private final boolean shrinkDesugaredLibrary;
@@ -43,7 +43,7 @@
BooleanUtils.values(), getTestParameters().withDexRuntimes().withAllApiLevels().build());
}
- public LibrarySubclassInterfaceTest(boolean shrinkDesugaredLibrary, TestParameters parameters) {
+ public GetGenericInterfaceTest(boolean shrinkDesugaredLibrary, TestParameters parameters) {
this.shrinkDesugaredLibrary = shrinkDesugaredLibrary;
this.parameters = parameters;
}
@@ -53,7 +53,7 @@
KeepRuleConsumer keepRuleConsumer = createKeepRuleConsumer(parameters);
String stdOut =
testForD8()
- .addInnerClasses(LibrarySubclassInterfaceTest.class)
+ .addInnerClasses(GetGenericInterfaceTest.class)
.setMinApi(parameters.getApiLevel())
.enableCoreLibraryDesugaring(parameters.getApiLevel(), keepRuleConsumer)
.compile()
@@ -73,7 +73,7 @@
KeepRuleConsumer keepRuleConsumer = createKeepRuleConsumer(parameters);
String stdOut =
testForR8(Backend.DEX)
- .addInnerClasses(LibrarySubclassInterfaceTest.class)
+ .addInnerClasses(GetGenericInterfaceTest.class)
.addKeepMainRule(Executor.class)
.noMinification()
.setMinApi(parameters.getApiLevel())
diff --git a/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GsonAllMapsTest.java b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GsonAllMapsTest.java
new file mode 100644
index 0000000..7938465
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GsonAllMapsTest.java
@@ -0,0 +1,77 @@
+// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+package com.android.tools.r8.desugar.desugaredlibrary.gson;
+
+import com.android.tools.r8.TestParameters;
+import com.android.tools.r8.utils.BooleanUtils;
+import java.util.List;
+import org.junit.Assume;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+
+@RunWith(Parameterized.class)
+public class GsonAllMapsTest extends GsonDesugaredLibraryTestBase {
+ private final TestParameters parameters;
+ private final boolean shrinkDesugaredLibrary;
+ private static final String[] EXPECTED_RESULT =
+ new String[] {
+ "true", "true", "true", "true", "true", "true", "true", "true", "true", "true", "true",
+ "true"
+ };
+
+ @Parameters(name = "shrinkDesugaredLibrary: {0}, runtime: {1}")
+ public static List<Object[]> data() {
+ return buildParameters(
+ BooleanUtils.values(), getTestParameters().withDexRuntimes().withAllApiLevels().build());
+ }
+
+ public GsonAllMapsTest(boolean shrinkDesugaredLibrary, TestParameters parameters) {
+ this.shrinkDesugaredLibrary = shrinkDesugaredLibrary;
+ this.parameters = parameters;
+ }
+
+ @Test
+ public void testGsonMapD8() throws Exception {
+ Assume.assumeTrue(requiresEmulatedInterfaceCoreLibDesugaring(parameters));
+ KeepRuleConsumer keepRuleConsumer = createKeepRuleConsumer(parameters);
+ testForD8(parameters.getBackend())
+ .addProgramClassesAndInnerClasses(AllMapsTestClass.class)
+ .addProgramFiles(GSON_2_8_1_JAR)
+ .enableCoreLibraryDesugaring(parameters.getApiLevel(), keepRuleConsumer)
+ .setMinApi(parameters.getApiLevel())
+ .compile()
+ .addDesugaredCoreLibraryRunClassPath(
+ this::buildDesugaredLibrary,
+ parameters.getApiLevel(),
+ keepRuleConsumer.get() + GSON_LIBRARY_KEEP_RULES,
+ shrinkDesugaredLibrary)
+ .run(parameters.getRuntime(), AllMapsTestClass.class)
+ .assertSuccessWithOutputLines(EXPECTED_RESULT);
+ }
+
+ @Test
+ public void testGsonMapR8() throws Exception {
+ Assume.assumeTrue(requiresEmulatedInterfaceCoreLibDesugaring(parameters));
+ KeepRuleConsumer keepRuleConsumer = createKeepRuleConsumer(parameters);
+ testForR8(parameters.getBackend())
+ .addProgramClassesAndInnerClasses(AllMapsTestClass.class)
+ .addProgramFiles(GSON_2_8_1_JAR)
+ .addKeepMainRule(AllMapsTestClass.class)
+ .addKeepRuleFiles(GSON_CONFIGURATION)
+ .allowUnusedProguardConfigurationRules()
+ .allowDiagnosticMessages()
+ .enableCoreLibraryDesugaring(parameters.getApiLevel(), keepRuleConsumer)
+ .setMinApi(parameters.getApiLevel())
+ .compile()
+ .addDesugaredCoreLibraryRunClassPath(
+ this::buildDesugaredLibrary,
+ parameters.getApiLevel(),
+ keepRuleConsumer.get() + GSON_LIBRARY_KEEP_RULES,
+ shrinkDesugaredLibrary)
+ .run(parameters.getRuntime(), AllMapsTestClass.class)
+ .assertSuccessWithOutputLines(EXPECTED_RESULT);
+ }
+}
diff --git a/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GsonDesugaredLibraryTestBase.java b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GsonDesugaredLibraryTestBase.java
new file mode 100644
index 0000000..e761248
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GsonDesugaredLibraryTestBase.java
@@ -0,0 +1,20 @@
+// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+package com.android.tools.r8.desugar.desugaredlibrary.gson;
+
+import com.android.tools.r8.desugar.desugaredlibrary.DesugaredLibraryTestBase;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+public abstract class GsonDesugaredLibraryTestBase extends DesugaredLibraryTestBase {
+ protected static final Path GSON_CONFIGURATION =
+ Paths.get("src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/gson.cfg");
+ protected static final Path GSON_2_8_1_JAR = Paths.get("third_party/iosched_2019/gson-2.8.1.jar");
+ // We only need here, for all subclasses of java.util.Collection and java.util.Map,
+ // to keep the signature attribute.
+ protected static final String GSON_LIBRARY_KEEP_RULES =
+ "-keepattributes Signature\n"
+ + "-keepattributes EnclosingMethod\n"
+ + "-keepattributes InnerClasses\n";
+}
diff --git a/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GsonOptionalTest.java b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GsonOptionalTest.java
new file mode 100644
index 0000000..6b75eb9
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/GsonOptionalTest.java
@@ -0,0 +1,73 @@
+// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+package com.android.tools.r8.desugar.desugaredlibrary.gson;
+
+import com.android.tools.r8.TestParameters;
+import com.android.tools.r8.utils.BooleanUtils;
+import java.util.List;
+import org.junit.Assume;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+@RunWith(Parameterized.class)
+public class GsonOptionalTest extends GsonDesugaredLibraryTestBase {
+ private final TestParameters parameters;
+ private final boolean shrinkDesugaredLibrary;
+
+ @Parameterized.Parameters(name = "shrinkDesugaredLibrary: {0}, runtime: {1}")
+ public static List<Object[]> data() {
+ return buildParameters(
+ BooleanUtils.values(), getTestParameters().withDexRuntimes().withAllApiLevels().build());
+ }
+
+ public GsonOptionalTest(boolean shrinkDesugaredLibrary, TestParameters parameters) {
+ this.shrinkDesugaredLibrary = shrinkDesugaredLibrary;
+ this.parameters = parameters;
+ }
+
+ @Test
+ public void testGsonOptionalD8() throws Exception {
+ Assume.assumeTrue(requiresEmulatedInterfaceCoreLibDesugaring(parameters));
+ KeepRuleConsumer keepRuleConsumer = createKeepRuleConsumer(parameters);
+ testForD8(parameters.getBackend())
+ .addProgramClassesAndInnerClasses(OptionalTestClass.class)
+ .addProgramFiles(GSON_2_8_1_JAR)
+ .addOptionsModification(opt -> opt.ignoreMissingClasses = true)
+ .enableCoreLibraryDesugaring(parameters.getApiLevel(), keepRuleConsumer)
+ .setMinApi(parameters.getApiLevel())
+ .compile()
+ .addDesugaredCoreLibraryRunClassPath(
+ this::buildDesugaredLibrary,
+ parameters.getApiLevel(),
+ keepRuleConsumer.get() + GSON_LIBRARY_KEEP_RULES,
+ shrinkDesugaredLibrary)
+ .run(parameters.getRuntime(), OptionalTestClass.class)
+ .assertSuccessWithOutputLines("true", "true");
+ }
+
+ @Test
+ public void testGsonOptionalR8() throws Exception {
+ Assume.assumeTrue(requiresEmulatedInterfaceCoreLibDesugaring(parameters));
+ KeepRuleConsumer keepRuleConsumer = createKeepRuleConsumer(parameters);
+ testForR8(parameters.getBackend())
+ .addProgramClassesAndInnerClasses(OptionalTestClass.class)
+ .addProgramFiles(GSON_2_8_1_JAR)
+ .addKeepMainRule(OptionalTestClass.class)
+ .addKeepRuleFiles(GSON_CONFIGURATION)
+ .allowUnusedProguardConfigurationRules()
+ .addOptionsModification(opt -> opt.ignoreMissingClasses = true)
+ .allowDiagnosticMessages()
+ .enableCoreLibraryDesugaring(parameters.getApiLevel(), keepRuleConsumer)
+ .setMinApi(parameters.getApiLevel())
+ .compile()
+ .addDesugaredCoreLibraryRunClassPath(
+ this::buildDesugaredLibrary,
+ parameters.getApiLevel(),
+ keepRuleConsumer.get() + GSON_LIBRARY_KEEP_RULES,
+ shrinkDesugaredLibrary)
+ .run(parameters.getRuntime(), OptionalTestClass.class)
+ .assertSuccessWithOutputLines("true", "true");
+ }
+}
diff --git a/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/OptionalTestClass.java b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/OptionalTestClass.java
new file mode 100644
index 0000000..fbc2c31
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/OptionalTestClass.java
@@ -0,0 +1,95 @@
+// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+package com.android.tools.r8.desugar.desugaredlibrary.gson;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.TypeAdapter;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.Objects;
+import java.util.Optional;
+
+public class OptionalTestClass {
+ static class Data {
+ final int id;
+ final String name;
+
+ Data(int id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof Data)) return false;
+ Data data = (Data) o;
+ return id == data.id && name.equals(data.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, name);
+ }
+
+ @Override
+ public String toString() {
+ return "Data{" + "id=" + id + ", name='" + name + '\'' + '}';
+ }
+ }
+
+ static class OptionalAdapter<T> extends TypeAdapter<Optional<T>> {
+ private final TypeAdapter<T> delegate;
+
+ public OptionalAdapter(TypeAdapter<T> delegate) {
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void write(JsonWriter out, Optional<T> value) throws IOException {
+ if (!value.isPresent()) {
+ out.nullValue();
+ return;
+ }
+ delegate.write(out, value.get());
+ }
+
+ @Override
+ public Optional<T> read(JsonReader in) throws IOException {
+ if (in.peek() == JsonToken.NULL) {
+ in.nextNull();
+ return Optional.empty();
+ }
+ return Optional.of(delegate.read(in));
+ }
+
+ @SuppressWarnings("unchecked")
+ public static OptionalAdapter getInstance(TypeToken typeToken) {
+ TypeAdapter delegate;
+ Type type = typeToken.getType();
+ assert type instanceof ParameterizedType;
+ Type innerType = ((ParameterizedType) type).getActualTypeArguments()[0];
+ delegate = new Gson().getAdapter(TypeToken.get(innerType));
+ return new OptionalAdapter<>(delegate);
+ }
+ }
+
+ public static void main(String[] args) {
+ GsonBuilder builder = new GsonBuilder();
+ builder.registerTypeAdapter(
+ Optional.class, OptionalAdapter.getInstance(new TypeToken<Optional<Data>>() {}));
+ Gson gson = builder.create();
+ Optional<Data> optionalData = Optional.of(new Data(1, "a"));
+ String optionalDataSerialized = gson.toJson(optionalData);
+ Optional<Data> optionalDataDeserialized = gson.fromJson(optionalDataSerialized, Optional.class);
+ System.out.println(optionalData.getClass() == optionalDataDeserialized.getClass());
+ System.out.println(optionalData.equals(optionalDataDeserialized));
+ }
+}
diff --git a/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/gson.cfg b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/gson.cfg
new file mode 100644
index 0000000..da7bcba
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/desugar/desugaredlibrary/gson/gson.cfg
@@ -0,0 +1,34 @@
+# Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
+# for details. All rights reserved. Use of this source code is governed by a
+# BSD-style license that can be found in the LICENSE file.
+# Gson uses generic type information stored in a class file when working with fields.
+# R8 removes such information by default, so configure it to keep all of it.
+-keepattributes Signature
+-keepattributes EnclosingMethod
+-keepattributes InnerClasses
+
+# For using GSON @Expose annotation
+-keepattributes AnnotationDefault,RuntimeVisibleAnnotations
+
+# Gson specific classes
+-dontwarn sun.misc.Unsafe
+
+# Application classes that will be serialized/deserialized over Gson
+-keep class com.android.tools.r8.desugar.desugaredlibrary.gson.AllMapsTestClasses$Data { <fields>; }
+-keep class com.android.tools.r8.desugar.desugaredlibrary.gson.AllMapsTestClasses$NullableConcurrentHashMap
+-keep class com.android.tools.r8.desugar.desugaredlibrary.gson.AllMapsTestClasses$NullableHashMap
+-keep class com.android.tools.r8.desugar.desugaredlibrary.gson.AllMapsTestClasses$NullableMap
+-keep class com.android.tools.r8.desugar.desugaredlibrary.gson.AllMapsTestClasses$NullableConcurrentMap
+-keep class com.android.tools.r8.desugar.desugaredlibrary.gson.OptionalTestClass$Data { <fields>; }
+
+# Prevent R8 from stripping interface information from TypeAdapter, TypeAdapterFactory,
+# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
+-keep class * extends com.google.gson.TypeAdapter
+-keep class * implements com.google.gson.TypeAdapterFactory
+-keep class * implements com.google.gson.JsonSerializer
+-keep class * implements com.google.gson.JsonDeserializer
+
+# Prevent R8 from leaving Data object members always null
+-keepclassmembers,allowobfuscation class * {
+ @com.google.gson.annotations.SerializedName <fields>;
+}