Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package com.google.devtools.j2objc.translate;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.j2objc.types.ExecutablePair;
import com.google.devtools.j2objc.types.GeneratedElement;
import com.google.devtools.j2objc.util.ElementUtil;
Expand All @@ -23,9 +24,11 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
Expand All @@ -44,7 +47,8 @@ record TypeMethods(
TypeElement typeElement,
ImmutableMap<String, ExecutablePair> allMethods,
ImmutableMap<String, AnnotationMirror> annotatedSignatures,
ImmutableMap<String, ExecutableElement> annotatedMethods) {}
ImmutableMap<String, ExecutableElement> annotatedMethods,
ImmutableSet<String> conflictedSignatures) {}

/** Concrete class in a type's hierarchy that owns the KMP adapter and helpers for a method. */
record ConcreteKmpOwner(
Expand Down Expand Up @@ -72,7 +76,7 @@ TypeMethods getTypeMethods(TypeElement typeElem) {
*/
private TypeMethods getTypeMethods(TypeElement typeElem, DeclaredType declaredType) {
List<CachedTypeMethods> entries =
typeMethodsCache.computeIfAbsent(typeElem, _ -> new ArrayList<>());
typeMethodsCache.computeIfAbsent(typeElem, k -> new ArrayList<>());
for (CachedTypeMethods entry : entries) {
if (typeUtil.isSameType(entry.declaredType(), declaredType)) {
return entry.typeMethods();
Expand All @@ -86,6 +90,7 @@ private TypeMethods getTypeMethods(TypeElement typeElem, DeclaredType declaredTy
private TypeMethods computeTypeMethods(TypeElement typeElem, DeclaredType declaredType) {
Map<String, ExecutablePair> methods = new LinkedHashMap<>();
Map<String, ExecutableElement> annotatedMethods = new LinkedHashMap<>();
Set<String> conflictedSignatures = new LinkedHashSet<>();

for (TypeMirror supertype : typeUtil.directSupertypes(declaredType)) {
if (!(supertype instanceof DeclaredType superDeclared)) {
Expand All @@ -102,23 +107,39 @@ private TypeMethods computeTypeMethods(TypeElement typeElem, DeclaredType declar
if (!isInheritedBy(inherited.element(), typeElem)) {
continue;
}
if (superMethods.conflictedSignatures().contains(sig)) {
conflictedSignatures.add(sig);
}
ExecutablePair existing = methods.get(sig);
if (existing == null || takesPrecedence(inherited.element(), existing.element())) {
methods.put(sig, inherited);
}
ExecutableElement superAnnotated = superMethods.annotatedMethods().get(sig);
if (superAnnotated != null && takesPrecedence(superAnnotated, annotatedMethods.get(sig))) {
annotatedMethods.put(sig, superAnnotated);
if (superAnnotated != null) {
ExecutableElement existingAnnotated = annotatedMethods.get(sig);
if (conflictsWith(superAnnotated, existingAnnotated)) {
conflictedSignatures.add(sig);
}
if (takesPrecedence(superAnnotated, existingAnnotated)) {
annotatedMethods.put(sig, superAnnotated);
}
}
}
}

for (ExecutableElement methodElem : ElementUtil.getExecutables(typeElem)) {
if (methodElem instanceof GeneratedElement) {
continue;
}
ExecutablePair method =
new ExecutablePair(methodElem, typeUtil.asMemberOf(declaredType, methodElem));
String sig = getOverrideSignature(method);
methods.put(sig, method);
if (ElementUtil.hasAnnotation(methodElem, ObjectiveCKmpMethod.class)) {
if (ElementUtil.isInstanceMethod(methodElem)
&& conflictsWith(methodElem, annotatedMethods.get(sig))) {
conflictedSignatures.add(sig);
}
annotatedMethods.put(sig, methodElem);
}
}
Expand All @@ -132,7 +153,8 @@ private TypeMethods computeTypeMethods(TypeElement typeElem, DeclaredType declar
typeElem,
ImmutableMap.copyOf(methods),
annotations.buildOrThrow(),
ImmutableMap.copyOf(annotatedMethods));
ImmutableMap.copyOf(annotatedMethods),
ImmutableSet.copyOf(conflictedSignatures));
}

/** Returns the JVM-style parameter-erased signature used to match method overrides. */
Expand Down Expand Up @@ -175,16 +197,20 @@ private String getOverrideSignature(ExecutablePair method) {
@Nullable ConcreteKmpOwner findConcreteKmpOwner(TypeElement typeElem, String signature) {
DeclaredType currentType = (DeclaredType) typeElem.asType();
TypeMethods currentMethods = getTypeMethods(typeElem, currentType);
if (!hasConcreteKmpMethod(currentMethods, signature)) {
if (!hasConcreteKmpMethod(currentMethods, signature)
|| currentMethods.conflictedSignatures().contains(signature)) {
return null;
}
// Walk up while the superclass already owns a concrete KMP adapter with the same config.
// Walk up while the superclass already owns a concrete KMP adapter.
DeclaredType superType = typeUtil.getSuperclass(currentType);
while (superType != null) {
TypeMethods superMethods = getTypeMethods(TypeUtil.asTypeElement(superType), superType);
// Stop if the superclass method is absent, abstract, unannotated, or re-configured.
if (!hasConcreteKmpMethod(superMethods, signature)
|| !sameKmpConfig(currentMethods, superMethods, signature)) {
boolean inheritsSuperAdapter =
hasConcreteKmpMethod(superMethods, signature)
&& isInheritedBy(
superMethods.allMethods().get(signature).element(),
currentMethods.typeElement());
if (!inheritsSuperAdapter) {
break;
}
currentType = superType;
Expand Down Expand Up @@ -215,19 +241,18 @@ private static boolean hasConcreteKmpMethod(TypeMethods methods, String signatur
&& ElementUtil.isInstanceMethod(pair.element());
}

private boolean sameKmpConfig(TypeMethods sub, TypeMethods sup, String signature) {
if (Objects.equals(
sub.annotatedMethods().get(signature), sup.annotatedMethods().get(signature))) {
return true;
private boolean conflictsWith(ExecutableElement a, @Nullable ExecutableElement b) {
if (b == null || a.equals(b)) {
return false;
}
AnnotationMirror a = sub.annotatedSignatures().get(signature);
AnnotationMirror b = sup.annotatedSignatures().get(signature);
return Objects.equals(
ElementUtil.getAnnotationValue(a, "selector"),
ElementUtil.getAnnotationValue(b, "selector"))
&& typeUtil.isSameType(
(TypeMirror) ElementUtil.getAnnotationValue(a, "adapter"),
(TypeMirror) ElementUtil.getAnnotationValue(b, "adapter"));
AnnotationMirror annA = ElementUtil.getAnnotation(a, ObjectiveCKmpMethod.class);
AnnotationMirror annB = ElementUtil.getAnnotation(b, ObjectiveCKmpMethod.class);
return !Objects.equals(
ElementUtil.getAnnotationValue(annA, "selector"),
ElementUtil.getAnnotationValue(annB, "selector"))
|| !typeUtil.isSameType(
(TypeMirror) ElementUtil.getAnnotationValue(annA, "adapter"),
(TypeMirror) ElementUtil.getAnnotationValue(annB, "adapter"));
}

private static boolean isInheritedBy(ExecutableElement method, TypeElement subType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.google.devtools.j2objc.ast.EnumDeclaration;
import com.google.devtools.j2objc.ast.RecordDeclaration;
import com.google.devtools.j2objc.ast.Statement;
import com.google.devtools.j2objc.ast.TreeNode;
import com.google.devtools.j2objc.ast.TreeVisitor;
import com.google.devtools.j2objc.ast.TypeDeclaration;
import com.google.devtools.j2objc.ast.UnitTreeVisitor;
Expand All @@ -28,11 +29,13 @@
import com.google.devtools.j2objc.translate.KmpTypeConverter.MappingStrategy;
import com.google.devtools.j2objc.types.ExecutablePair;
import com.google.devtools.j2objc.util.ElementUtil;
import com.google.devtools.j2objc.util.ErrorUtil;
import com.google.j2objc.annotations.ObjectiveCKmpMethod;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;

/**
Expand Down Expand Up @@ -138,15 +141,29 @@ public void endVisit(ClassInstanceCreation node) {
new PrivateDeclarationResolver(unit).run();
}

private static void reportOverrideConflict(
AbstractTypeDeclaration typeNode, ExecutableElement method) {
TreeNode target = KmpAdapterEmitter.findMethodDeclaration(typeNode, method);
ErrorUtil.error(
target != null ? target : typeNode,
"Overriding an @ObjectiveCKmpMethod method with a different selector or adapter is"
+ " not supported: "
+ ElementUtil.getName(method));
}

private void processType(AbstractTypeDeclaration typeNode) {
TypeElement typeElem = typeNode.getTypeElement();
TypeMethods resolved = methodHierarchy.getTypeMethods(typeElem);
boolean isInterface = typeElem.getKind().isInterface();

for (Map.Entry<String, AnnotationMirror> entry : resolved.annotatedSignatures().entrySet()) {
String signature = entry.getKey();
AnnotationMirror annotation = entry.getValue();
ExecutablePair method = resolved.allMethods().get(signature);
if (resolved.conflictedSignatures().contains(signature)) {
reportOverrideConflict(typeNode, method.element());
continue;
}
AnnotationMirror annotation = entry.getValue();

boolean shouldGenerate;
MappingStrategy strategy = MappingStrategy.NATIVE_TO_JAVA;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,10 @@ public void testFindInterfaceMethodRequiringDispatch_resolvesDirectInheritedAndN
import java.util.List;

interface BaseIface {
@ObjectiveCKmpMethod(selector = "baseSend:", adapter = DummyAdapter.class)
@ObjectiveCKmpMethod(
selector = "send:",
adapter = DummyAdapter.class,
swiftName = "baseSend(_:)")
void send(List<String> items);
}

Expand All @@ -294,7 +297,10 @@ interface UnannotatedSubIface extends BaseIface {
}

interface MidIface extends BaseIface {
@ObjectiveCKmpMethod(selector = "midSend:", adapter = DummyAdapter.class)
@ObjectiveCKmpMethod(
selector = "send:",
adapter = DummyAdapter.class,
swiftName = "midSend(_:)")
@Override
void send(List<String> items);
}
Expand All @@ -311,6 +317,8 @@ public interface LeafIface extends MidIface {
ExecutableElement midSend = findMethod(findType(unit, "MidIface"), "send");
ExecutableElement leafSend = findMethod(findType(unit, "LeafIface"), "send");

assertThat(hierarchy.getTypeMethods(findType(unit, "LeafIface")).conflictedSignatures())
.isEmpty();
assertThat(hierarchy.findInterfaceMethodRequiringDispatch(baseSend)).isEqualTo(baseSend);
assertThat(hierarchy.findInterfaceMethodRequiringDispatch(unannotatedSubSend))
.isEqualTo(baseSend);
Expand Down Expand Up @@ -366,11 +374,18 @@ public void testGetTypeMethods_crossPackagePackagePrivateNotInherited() throws I
"pkg2.RedeclaringSub",
"""
package pkg2;
import adapter.DummyAdapter;
import com.google.j2objc.annotations.ObjectiveCKmpMethod;
import java.util.List;
import pkg1.Base;

class EmptySub extends Base {}

class AnnotatedSub extends Base {
@ObjectiveCKmpMethod(selector = "foo:", adapter = DummyAdapter.class)
public void foo(List<String> items) {}
}

public class RedeclaringSub extends Base {
void foo(List<String> items) {}
}
Expand All @@ -382,6 +397,11 @@ void foo(List<String> items) {}
assertThat(emptyResolved.annotatedSignatures()).isEmpty();
assertThat(emptyResolved.allMethods().keySet()).doesNotContain(sig);

TypeElement annotatedSub = findType(unit, "AnnotatedSub");
assertThat(hierarchy.getTypeMethods(annotatedSub).conflictedSignatures()).isEmpty();
assertThat(hierarchy.findConcreteKmpOwner(annotatedSub, sig).ownerType())
.isEqualTo(annotatedSub);

TypeElement redeclaringSub = findType(unit, "RedeclaringSub");
TypeMethods redeclaringResolved = hierarchy.getTypeMethods(redeclaringSub);
assertThat(redeclaringResolved.annotatedSignatures()).isEmpty();
Expand Down Expand Up @@ -479,12 +499,18 @@ public void testGetTypeMethods_subinterfaceAnnotationOverridesSuperinterfaceAnno
import java.util.List;

interface SuperI {
@ObjectiveCKmpMethod(selector = "superHandle:", adapter = DummyAdapter.class)
@ObjectiveCKmpMethod(
selector = "handle:",
adapter = DummyAdapter.class,
swiftName = "superHandle(_:)")
default void handle(List<String> items) {}
}

interface SubI extends SuperI {
@ObjectiveCKmpMethod(selector = "subHandle:", adapter = DummyAdapter.class)
@ObjectiveCKmpMethod(
selector = "handle:",
adapter = DummyAdapter.class,
swiftName = "subHandle(_:)")
@Override
default void handle(List<String> items) {}
}
Expand All @@ -503,8 +529,10 @@ class ReverseDiamond extends UnannotatedBase implements SubI, SuperI {}

for (String className : ImmutableList.of("ForwardDiamond", "ReverseDiamond")) {
TypeMethods resolved = hierarchy.getTypeMethods(findType(unit, className));
assertThat(ElementUtil.getAnnotationValue(resolved.annotatedSignatures().get(sig), "selector"))
.isEqualTo("subHandle:");
assertThat(resolved.conflictedSignatures()).isEmpty();
assertThat(
ElementUtil.getAnnotationValue(resolved.annotatedSignatures().get(sig), "swiftName"))
.isEqualTo("subHandle(_:)");
assertThat(resolved.annotatedMethods().get(sig)).isEqualTo(subHandle);
}
}
Expand Down Expand Up @@ -704,25 +732,50 @@ public void work() {}
ConcreteKmpOwner sameConfigOwner = hierarchy.findConcreteKmpOwner(sameConfigSub, "work()");
assertThat(sameConfigOwner).isNotNull();
assertThat(sameConfigOwner.ownerType()).isEqualTo(openBase);
assertThat(hierarchy.getTypeMethods(sameConfigSub).conflictedSignatures()).isEmpty();
assertThat(hierarchy.findConcreteKmpOwner(sameConfigSub, "<init>(Ljava/util/List;)")).isNull();
assertThat(hierarchy.findConcreteKmpOwner(sameConfigSub, "make(Ljava/util/List;)")).isNull();
assertThat(hierarchy.findConcreteKmpOwner(sameConfigSub, "missing()")).isNull();

assertThat(hierarchy.findConcreteKmpOwner(newSelectorSub, "work()").ownerType())
.isEqualTo(newSelectorSub);
assertThat(hierarchy.findConcreteKmpOwner(newAdapterSub, "work()").ownerType())
.isEqualTo(newAdapterSub);
for (TypeElement conflicted :
ImmutableList.of(newSelectorSub, newAdapterSub, childOfNewAdapter)) {
assertThat(hierarchy.getTypeMethods(conflicted).conflictedSignatures())
.containsExactly("work()");
assertThat(hierarchy.findConcreteKmpOwner(conflicted, "work()")).isNull();
}
}

ConcreteKmpOwner owner = hierarchy.findConcreteKmpOwner(childOfNewAdapter, "work()");
assertThat(owner).isNotNull();
assertThat(owner.ownerType()).isEqualTo(newAdapterSub);
assertThat(
unit.getEnv()
.typeUtil()
.isSameType(
(TypeMirror) ElementUtil.getAnnotationValue(owner.annotation(), "adapter"),
unit.getEnv().typeUtil().resolveJavaType("OtherAdapter").asType()))
.isTrue();
public void testGetTypeMethods_tracksSiblingInterfaceConflicts() {
CompilationUnit unit =
compileType(
"LeafImpl",
"""
import com.google.j2objc.annotations.ObjectiveCKmpMethod;

interface LeftIface {
@ObjectiveCKmpMethod(selector = "leftWork", adapter = DummyAdapter.class)
void work();
}

interface RightIface {
@ObjectiveCKmpMethod(selector = "rightWork", adapter = DummyAdapter.class)
void work();
}

interface CombinedIface extends LeftIface, RightIface {}

public class LeafImpl implements CombinedIface {
@Override
@ObjectiveCKmpMethod(selector = "leftWork", adapter = DummyAdapter.class)
public void work() {}
}
""");
KmpMethodHierarchy hierarchy = createHierarchy(unit);

assertThat(hierarchy.getTypeMethods(findType(unit, "CombinedIface")).conflictedSignatures())
.containsExactly("work()");
assertThat(hierarchy.getTypeMethods(findType(unit, "LeafImpl")).conflictedSignatures())
.containsExactly("work()");
}

public void testFindConcreteKmpOwner_genericBaseReturnsRawOwnerSignature() {
Expand Down
Loading