From d8b11adf01e2f3cffe7fbcf3196e8e66594887a3 Mon Sep 17 00:00:00 2001 From: Wei Jun Kong Date: Tue, 24 Nov 2026 12:21:46 -0800 Subject: [PATCH] Validate @ObjectiveCKmpMethod override consistency in J2ObjC. PiperOrigin-RevId: 1029251172 --- .../j2objc/translate/KmpMethodHierarchy.java | 69 ++- .../ObjectiveCKmpMethodTranslator.java | 19 +- .../translate/KmpMethodHierarchyTest.java | 93 +++- .../ObjectiveCKmpMethodTranslatorTest.java | 417 +++++++++++++++++- 4 files changed, 537 insertions(+), 61 deletions(-) diff --git a/translator/src/main/java/com/google/devtools/j2objc/translate/KmpMethodHierarchy.java b/translator/src/main/java/com/google/devtools/j2objc/translate/KmpMethodHierarchy.java index 746afae740..2f2b9b31b1 100644 --- a/translator/src/main/java/com/google/devtools/j2objc/translate/KmpMethodHierarchy.java +++ b/translator/src/main/java/com/google/devtools/j2objc/translate/KmpMethodHierarchy.java @@ -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; @@ -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; @@ -44,7 +47,8 @@ record TypeMethods( TypeElement typeElement, ImmutableMap allMethods, ImmutableMap annotatedSignatures, - ImmutableMap annotatedMethods) {} + ImmutableMap annotatedMethods, + ImmutableSet conflictedSignatures) {} /** Concrete class in a type's hierarchy that owns the KMP adapter and helpers for a method. */ record ConcreteKmpOwner( @@ -72,7 +76,7 @@ TypeMethods getTypeMethods(TypeElement typeElem) { */ private TypeMethods getTypeMethods(TypeElement typeElem, DeclaredType declaredType) { List 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(); @@ -86,6 +90,7 @@ private TypeMethods getTypeMethods(TypeElement typeElem, DeclaredType declaredTy private TypeMethods computeTypeMethods(TypeElement typeElem, DeclaredType declaredType) { Map methods = new LinkedHashMap<>(); Map annotatedMethods = new LinkedHashMap<>(); + Set conflictedSignatures = new LinkedHashSet<>(); for (TypeMirror supertype : typeUtil.directSupertypes(declaredType)) { if (!(supertype instanceof DeclaredType superDeclared)) { @@ -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); } } @@ -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. */ @@ -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; @@ -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) { diff --git a/translator/src/main/java/com/google/devtools/j2objc/translate/ObjectiveCKmpMethodTranslator.java b/translator/src/main/java/com/google/devtools/j2objc/translate/ObjectiveCKmpMethodTranslator.java index eff056b436..e0673c003f 100644 --- a/translator/src/main/java/com/google/devtools/j2objc/translate/ObjectiveCKmpMethodTranslator.java +++ b/translator/src/main/java/com/google/devtools/j2objc/translate/ObjectiveCKmpMethodTranslator.java @@ -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; @@ -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; /** @@ -138,6 +141,16 @@ 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); @@ -145,8 +158,12 @@ private void processType(AbstractTypeDeclaration typeNode) { for (Map.Entry 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; diff --git a/translator/src/test/java/com/google/devtools/j2objc/translate/KmpMethodHierarchyTest.java b/translator/src/test/java/com/google/devtools/j2objc/translate/KmpMethodHierarchyTest.java index 8a70888725..5c487ce669 100644 --- a/translator/src/test/java/com/google/devtools/j2objc/translate/KmpMethodHierarchyTest.java +++ b/translator/src/test/java/com/google/devtools/j2objc/translate/KmpMethodHierarchyTest.java @@ -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 items); } @@ -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 items); } @@ -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); @@ -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 items) {} + } + public class RedeclaringSub extends Base { void foo(List items) {} } @@ -382,6 +397,11 @@ void foo(List 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(); @@ -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 items) {} } interface SubI extends SuperI { - @ObjectiveCKmpMethod(selector = "subHandle:", adapter = DummyAdapter.class) + @ObjectiveCKmpMethod( + selector = "handle:", + adapter = DummyAdapter.class, + swiftName = "subHandle(_:)") @Override default void handle(List items) {} } @@ -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); } } @@ -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, "(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() { diff --git a/translator/src/test/java/com/google/devtools/j2objc/translate/ObjectiveCKmpMethodTranslatorTest.java b/translator/src/test/java/com/google/devtools/j2objc/translate/ObjectiveCKmpMethodTranslatorTest.java index cad3fab9cd..64c95f3735 100644 --- a/translator/src/test/java/com/google/devtools/j2objc/translate/ObjectiveCKmpMethodTranslatorTest.java +++ b/translator/src/test/java/com/google/devtools/j2objc/translate/ObjectiveCKmpMethodTranslatorTest.java @@ -3160,7 +3160,7 @@ public interface MyProto { assertNotInTranslation(header, "MyProto_getItems_dispatch_swiftName"); } - public void testTranslate_reannotatedConcreteSubclassEmitsAdapterOnlyWhenConfigDiffers() + public void testTranslate_reannotatedConcreteSubclassWithSameConfigInheritsAdapter() throws IOException { addImmutableListAdapter(); addSourceFile( @@ -3190,26 +3190,10 @@ public ImmutableList getItems() { } """, "SameConfigService.java"); - addSourceFile( - """ - import com.google.common.collect.ImmutableList; - import com.google.j2objc.annotations.ObjectiveCKmpMethod; - - public final class RenamedConfigService extends BaseService { - @Override - @ObjectiveCKmpMethod(selector = "getRenamedItems", adapter = ImmutableListAdapter.class) - public ImmutableList getItems() { - return ImmutableList.of(); - } - } - """, - "RenamedConfigService.java"); String sameImpl = translateSourceFile("SameConfigService", "SameConfigService.m"); + assertNoErrors(); assertNotInTranslation(sameImpl, "- (NSArray *)getItemsAsNsArray"); - - String renamedHeader = translateSourceFile("RenamedConfigService", "RenamedConfigService.h"); - assertInTranslation(renamedHeader, "- (NSArray *)getRenamedItems;"); } public void testAbstractClassImplementingGenericInterface_skipsAbstractNarrowingStub() @@ -3490,4 +3474,401 @@ default void work(String tag, ImmutableList items) {} assertNotInTranslation( impl, "SubDefaultProto_workWithNSString_withComGoogleCommonCollectImmutableList__dispatch"); } + + private void assertTranslatesCleanly(String typeName, String source) throws IOException { + @SuppressWarnings("unused") + String unused = translateSourceFile(source, typeName, typeName.replace('.', '/') + ".h"); + assertNoErrors(); + } + + private void assertKmpOverrideError( + String typeName, int line, String methodName, String source) throws IOException { + @SuppressWarnings("unused") + String unused = translateSourceFile(source, typeName, typeName.replace('.', '/') + ".h"); + assertError( + typeNameToSource(typeName) + + ":" + + line + + ": Overriding an @ObjectiveCKmpMethod method with a different selector or adapter is" + + " not supported: " + + methodName); + } + + private void addPkgBaseSources() throws IOException { + addSourceFile( + """ + package p1; + import java.util.List; + + public class PkgAdapter { + public static native List toJavaUtilList(Object list) /*-[ return nil; ]-*/; + public static native Object fromJavaUtilList(List list) /*-[ return nil; ]-*/; + } + """, + "p1/PkgAdapter.java"); + addSourceFile( + """ + package p1; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + public class PkgBase { + @ObjectiveCKmpMethod(selector = "getItems", adapter = PkgAdapter.class) + List getItems() { + return null; + } + } + """, + "p1/PkgBase.java"); + } + + private void addConflictingSiblingProtos() throws IOException { + addSourceFile( + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + public interface LeftProto { + @ObjectiveCKmpMethod(selector = "leftItems", adapter = Adapter.class) + List getItems(); + } + """, + "LeftProto.java"); + addSourceFile( + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + public interface RightProto { + @ObjectiveCKmpMethod(selector = "rightItems", adapter = Adapter.class) + List getItems(); + } + """, + "RightProto.java"); + } + + public void testOverrideWithDifferentSelectorOnClass_reportsError() throws IOException { + assertKmpOverrideError( + "SubService", + 12, + "getItems", + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + class BaseService { + @ObjectiveCKmpMethod(selector = "getItems", adapter = Adapter.class) + public List getItems() { + return null; + } + } + + public class SubService extends BaseService { + @Override + @ObjectiveCKmpMethod(selector = "fetchItems", adapter = Adapter.class) + public List getItems() { + return null; + } + } + """); + } + + public void testOverrideWithDifferentAdapterOnClassImplementingInterface_reportsError() + throws IOException { + assertKmpOverrideError( + "ServiceImpl", + 15, + "getItems", + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + class OtherAdapter { + public static native List toJavaUtilList(Object list) /*-[ return nil; ]-*/; + public static native Object fromJavaUtilList(List list) /*-[ return nil; ]-*/; + } + + interface ServiceProto { + @ObjectiveCKmpMethod(selector = "getItems", adapter = Adapter.class) + List getItems(); + } + + public class ServiceImpl implements ServiceProto { + @Override + @ObjectiveCKmpMethod(selector = "getItems", adapter = OtherAdapter.class) + public List getItems() { + return null; + } + } + """); + } + + public void testOverrideWithDifferentSelectorOnSubinterface_reportsError() throws IOException { + assertKmpOverrideError( + "SubProto", + 10, + "getItems", + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + interface BaseProto { + @ObjectiveCKmpMethod(selector = "getItems", adapter = Adapter.class) + List getItems(); + } + + public interface SubProto extends BaseProto { + @Override + @ObjectiveCKmpMethod(selector = "fetchItems", adapter = Adapter.class) + List getItems(); + } + """); + } + + public void testOverrideWithMatchingSelectorAndAdapter_succeedsWithoutError() throws IOException { + assertTranslatesCleanly( + "MatchingImpl", + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + interface MatchingProto { + @ObjectiveCKmpMethod(selector = "getItems", adapter = Adapter.class) + List getItems(); + } + + public class MatchingImpl implements MatchingProto { + @Override + @ObjectiveCKmpMethod(selector = "getItems", adapter = Adapter.class) + public List getItems() { + return null; + } + } + """); + } + + public void testOverrideWithDifferentSelectorMultiHop_reportsError() throws IOException { + assertKmpOverrideError( + "LeafService", + 19, + "getItems", + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + class RootService { + @ObjectiveCKmpMethod(selector = "getItems", adapter = Adapter.class) + public List getItems() { + return null; + } + } + + class MidService extends RootService { + @Override + public List getItems() { + return null; + } + } + + public class LeafService extends MidService { + @Override + @ObjectiveCKmpMethod(selector = "fetchItems", adapter = Adapter.class) + public List getItems() { + return null; + } + } + """); + } + + public void testOverrideWithDifferentSelectorParameterizedSupertype_reportsError() + throws IOException { + assertKmpOverrideError( + "StringProtoImpl", + 10, + "accept", + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + interface GenericProto { + @ObjectiveCKmpMethod(selector = "acceptWith:items:", adapter = Adapter.class) + void accept(T value, List items); + } + + public class StringProtoImpl implements GenericProto { + @Override + @ObjectiveCKmpMethod(selector = "handleWith:items:", adapter = Adapter.class) + public void accept(String value, List items) {} + } + """); + } + + public void testCrossPackagePackagePrivateSameSignature_succeedsWithoutError() + throws IOException { + addPkgBaseSources(); + assertTranslatesCleanly( + "p2.PkgSub", + """ + package p2; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + import p1.PkgAdapter; + import p1.PkgBase; + + public class PkgSub extends PkgBase { + @ObjectiveCKmpMethod(selector = "fetchItems", adapter = PkgAdapter.class) + List getItems() { + return null; + } + } + """); + } + + public void testStaticMethodSameNameInSubclass_succeedsWithoutError() throws IOException { + assertTranslatesCleanly( + "StaticSub", + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + class StaticBase { + @ObjectiveCKmpMethod(selector = "makeItems", adapter = Adapter.class) + public static List make() { + return null; + } + } + + public class StaticSub extends StaticBase { + @ObjectiveCKmpMethod(selector = "buildItems", adapter = Adapter.class) + public static List make() { + return null; + } + } + """); + } + + public void testKmpMethodCombinedWithThrowsOnClassAndInterface_succeedsWithoutError() + throws IOException { + assertTranslatesCleanly( + "ThrowingKmpImpl", + """ + import com.google.j2kt.annotations.Throws; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + interface ThrowingKmpProto { + @Throws + @ObjectiveCKmpMethod(selector = "loadItems", adapter = Adapter.class) + List load(); + } + + public class ThrowingKmpImpl implements ThrowingKmpProto { + @Override + public List load() { + return null; + } + + @Throws + @ObjectiveCKmpMethod(selector = "saveItems:", adapter = Adapter.class) + public void save(List items) {} + } + """); + } + + public void + testWidenedPackagePrivateMethodOverriddenInForeignPackageWithDifferentSelector_reportsError() + throws IOException { + addPkgBaseSources(); + addSourceFile( + """ + package p1; + import java.util.List; + + public class WideningMid extends PkgBase { + @Override + protected List getItems() { + return null; + } + } + """, + "p1/WideningMid.java"); + assertKmpOverrideError( + "p2.ForeignSub", + 8, + "getItems", + """ + package p2; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + import p1.PkgAdapter; + import p1.WideningMid; + + public class ForeignSub extends WideningMid { + @Override + @ObjectiveCKmpMethod(selector = "fetchItems", adapter = PkgAdapter.class) + public List getItems() { + return null; + } + } + """); + } + + public void testConflictingSiblingInterfacesWithoutOverride_reportsError() throws IOException { + addConflictingSiblingProtos(); + assertKmpOverrideError( + "CombinedProto", + 1, + "getItems", + "public interface CombinedProto extends LeftProto, RightProto {}"); + } + + public void testAnnotatedOverrideOfConflictingMergedSubinterface_reportsError() + throws IOException { + addConflictingSiblingProtos(); + addSourceFile( + "public interface CombinedProto extends LeftProto, RightProto {}", + "CombinedProto.java"); + assertKmpOverrideError( + "LeafConflictImpl", + 5, + "getItems", + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + public class LeafConflictImpl implements CombinedProto { + @Override + @ObjectiveCKmpMethod(selector = "leftItems", adapter = Adapter.class) + public List getItems() { + return null; + } + } + """); + } + + public void testOverrideChangingOnlySwiftName_succeedsWithoutError() throws IOException { + assertTranslatesCleanly( + "SwiftSub", + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + class SwiftBase { + @ObjectiveCKmpMethod( + selector = "getItems", adapter = Adapter.class, swiftName = "baseItems()") + public List getItems() { + return null; + } + } + + public class SwiftSub extends SwiftBase { + @Override + @ObjectiveCKmpMethod( + selector = "getItems", adapter = Adapter.class, swiftName = "subItems()") + public List getItems() { + return null; + } + } + """); + } }