diff --git a/translator/src/main/java/com/google/devtools/j2objc/translate/KmpAdapterEmitter.java b/translator/src/main/java/com/google/devtools/j2objc/translate/KmpAdapterEmitter.java index 77e1ef094f..389a4a26dc 100644 --- a/translator/src/main/java/com/google/devtools/j2objc/translate/KmpAdapterEmitter.java +++ b/translator/src/main/java/com/google/devtools/j2objc/translate/KmpAdapterEmitter.java @@ -31,14 +31,17 @@ import com.google.devtools.j2objc.ast.IfStatement; import com.google.devtools.j2objc.ast.MethodDeclaration; import com.google.devtools.j2objc.ast.MethodInvocation; +import com.google.devtools.j2objc.ast.NativeDeclaration; import com.google.devtools.j2objc.ast.NativeExpression; import com.google.devtools.j2objc.ast.NativeStatement; import com.google.devtools.j2objc.ast.ReturnStatement; import com.google.devtools.j2objc.ast.SimpleName; import com.google.devtools.j2objc.ast.SingleVariableDeclaration; import com.google.devtools.j2objc.ast.Statement; +import com.google.devtools.j2objc.ast.SuperMethodInvocation; import com.google.devtools.j2objc.ast.ThisExpression; import com.google.devtools.j2objc.ast.TreeUtil; +import com.google.devtools.j2objc.translate.KmpMethodHierarchy.ConcreteKmpOwner; import com.google.devtools.j2objc.translate.KmpTypeConverter.MappingStrategy; import com.google.devtools.j2objc.translate.KmpTypeConverter.ParameterMapping; import com.google.devtools.j2objc.types.ExecutablePair; @@ -52,9 +55,12 @@ import com.google.devtools.j2objc.util.TypeUtil; import com.google.j2objc.annotations.ObjectiveCKmpMethod; import com.google.j2objc.annotations.SwiftName; +import java.util.HashSet; import java.util.List; +import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.PackageElement; @@ -74,6 +80,7 @@ final class KmpAdapterEmitter { private final NameTable nameTable; private final Options options; private final KmpTypeConverter typeConverter; + private final Set emittedOverrideCheckTypes = new HashSet<>(); KmpAdapterEmitter( TypeUtil typeUtil, NameTable nameTable, Options options, KmpTypeConverter typeConverter) { @@ -93,6 +100,56 @@ void emit( new AdapterContext(typeNode, originalMethod, annotation, isInterface, strategy).processMethod(); } + /** + * Prepends a native-override check to an overriding or default-shim method on a subclass so Java + * callers delegate to {@code baseOwner}'s adapted Objective-C selector when overridden natively. + */ + void prependSubclassOverrideCheck( + AbstractTypeDeclaration typeNode, ExecutablePair method, ConcreteKmpOwner baseOwner) { + if (!canPrependSubclassOverrideCheck(typeNode, method, baseOwner, typeConverter)) { + return; + } + MethodDeclaration concreteDecl = findConcreteMethodDeclaration(typeNode, method.element()); + if (concreteDecl == null) { + return; + } + new AdapterContext( + typeNode, + method, + baseOwner.annotation(), + /* isInterface= */ false, + MappingStrategy.JAVA_TO_NATIVE) + .prependOverrideCheck(concreteDecl, baseOwner.ownerType(), baseOwner.method()); + } + + private static boolean canPrependSubclassOverrideCheck( + AbstractTypeDeclaration typeNode, + ExecutablePair method, + ConcreteKmpOwner baseOwner, + KmpTypeConverter typeConverter) { + TypeMirror adapter = + (TypeMirror) ElementUtil.getAnnotationValue(baseOwner.annotation(), "adapter"); + // A subclass override can dispatch to a native override only when: + // 1. The subclass is exposed in the ObjC header and both the subclass and base methods can be + // overridden natively (non-final/non-local class, non-final/non-private method). + // 2. The base method's signature can be reverse-adapted between Java and native types. + // 3. Any covariant subclass return type can be converted back from the base native return type. + return !typeNode.hasPrivateDeclaration() + && canOverrideInNative(typeNode.getTypeElement(), method.element()) + && canOverrideInNative(baseOwner.ownerType(), baseOwner.method().element()) + && typeConverter.canReverseAdapt(baseOwner.method(), adapter) + && typeConverter.canReverseAdaptSubclassReturn( + baseOwner.method().type().getReturnType(), method.type().getReturnType(), adapter); + } + + private static boolean canOverrideInNative(TypeElement type, ExecutableElement method) { + return type.getKind() == ElementKind.CLASS + && !ElementUtil.isFinal(type) + && !ElementUtil.isLocal(type) + && !ElementUtil.isFinal(method) + && !ElementUtil.isPrivate(method); + } + static @Nullable MethodDeclaration findMethodDeclaration( @Nullable AbstractTypeDeclaration typeNode, ExecutableElement element) { if (typeNode == null) { @@ -132,6 +189,74 @@ static boolean isDefaultRenamingShim(MethodDeclaration decl) { return expr instanceof MethodInvocation call && call.getExpression() == null; } + /** + * Finds the primary concrete declaration or {@code default}-method shim implementing {@code + * element} on {@code typeNode}, excluding {@code [self ...]} renaming shims. + */ + private static @Nullable MethodDeclaration findConcreteMethodDeclaration( + AbstractTypeDeclaration typeNode, ExecutableElement element) { + for (MethodDeclaration methodDecl : TreeUtil.getMethodDeclarations(typeNode)) { + if (methodDecl.getBody() == null) { + continue; + } + ExecutableElement declElem = methodDecl.getExecutableElement(); + if (declElem.equals(element) + || (isConcreteGeneratedShim(methodDecl) + && element.equals(((GeneratedExecutableElement) declElem).getOriginalElement()) + && !isDefaultRenamingShim(methodDecl))) { + return methodDecl; + } + } + return null; + } + + /** + * Emits a class-level helper {@code bool _isOverride( *self, SEL selector)} at most + * once per class, returning true when {@code selector}'s implementation differs from the class's. + * + *

Inspects {@code [self class]} rather than {@code object_getClass(self)} so ISA-swizzled + * dynamic subclasses (such as {@code OCMPartialMock} or KVO {@code NSKVONotifying_*}) do not + * falsely trigger adapted override dispatch and cause infinite recursion on unstubbed calls. + * + *

Java subclasses override the unadapted method directly (prepending their own check against + * the owner class), so only native subclass overrides take the adapted branch. Calling {@code + * [super ...]} from a native override—and cross-file Java {@code super} calls on a native + * subclass instance—are unsupported because {@code super} dispatch preserves {@code self}. + */ + private void ensureOverrideCheckHelper(AbstractTypeDeclaration typeNode) { + TypeElement ownerType = typeNode.getTypeElement(); + if (!emittedOverrideCheckTypes.add(ownerType)) { + return; + } + String className = nameTable.getFullName(ownerType); + String signature = + String.format("bool %s(%s *self, SEL selector)", getOverrideCheckName(ownerType), className); + String body = + String.format( + """ + %s { + if (self == nil) { + return false; + } + Class cls = [self class]; + Class owner = [%s class]; + if (cls == owner || ![cls isSubclassOfClass:owner]) { + return false; + } + IMP clsImp = [cls instanceMethodForSelector:selector]; + IMP ownerImp = [owner instanceMethodForSelector:selector]; + return clsImp != ownerImp; + }\ + """, + signature, className); + typeNode.addBodyDeclaration( + NativeDeclaration.newOuterDeclaration("FOUNDATION_EXPORT " + signature + ";", body)); + } + + private String getOverrideCheckName(TypeElement ownerType) { + return nameTable.getFullName(ownerType) + "_isOverride"; + } + /** * Returns true if {@code decl} is an abstract return-type-narrowing stub added by {@link * AbstractMethodRewriter} for {@code targetSelector}. @@ -371,6 +496,98 @@ private void generateInstanceMethodDeclaration(TypeMirror adapterReturnType) { addMethodDeclaration( adapterMethodExecutable, adaptingMethodInvocation, adapterReturnType, adapterParameters); + emitConcreteNativeOverrideSupport(); + } + + // Enables native ObjC/Swift subclasses to override this concrete @ObjectiveCKmpMethod via its + // adapted selector: ensures the class-level `_isOverride` helper is emitted and prepends + // an override check to the unadapted Java method body so Java callers dispatch to the native + // override when present. + private void emitConcreteNativeOverrideSupport() { + TypeElement ownerType = typeNode.getTypeElement(); + if (typeNode.hasPrivateDeclaration() + || !canOverrideInNative(ownerType, originalMethodExecutable) + || !typeConverter.canReverseAdapt(originalMethod, adapter)) { + return; + } + MethodDeclaration concreteDecl = + findConcreteMethodDeclaration(typeNode, originalMethodExecutable); + // When this class inherits an unannotated superclass implementation that satisfies a KMP + // interface method, there is no local body yet; synthesize a [super ...] bridge to attach + // the override check to. + if (concreteDecl == null + && !ElementUtil.isDefault(originalMethodExecutable) + && !ElementUtil.getDeclaringClass(originalMethodExecutable).equals(ownerType)) { + concreteDecl = synthesizeSuperBridgeDeclaration(); + typeNode.addBodyDeclaration(concreteDecl); + } + // Emit the helper even when DeadCodeEliminator stripped the owner's concrete body so live + // subclass overrides referencing `_isOverride` still compile and link. + ensureOverrideCheckHelper(typeNode); + if (concreteDecl != null) { + prependOverrideCheck(concreteDecl, ownerType, originalMethod); + } + } + + // Synthesizes a local bridge forwarding to an unannotated superclass implementation so the + // override check can be prepended on this KMP owner class. Example: + // - (SubFoo *)getItemWithImmutableList:(ImmutableList *)items { + // // (override check prepended here) + // return (SubFoo *) [super getItemWithImmutableList:items]; + // } + private MethodDeclaration synthesizeSuperBridgeDeclaration() { + SuperMethodInvocation superCall = + new SuperMethodInvocation(new ExecutablePair(originalMethodExecutable)); + for (VariableElement param : originalMethodParameters) { + superCall.addArgument(new SimpleName(param)); + } + Expression superExpr = + typeConverter.maybeCast(typeUtil.erasure(originalMethodReturnType), superCall); + MethodDeclaration bridgeDecl = + createBridgeMethodDeclaration(createReturnOrExpressionBlock(superExpr)); + bridgeDecl.setHasDeclaration(false); + return bridgeDecl; + } + + // Prepends a runtime override guard to `concreteDecl`'s body so Java callers dispatch to a + // native ObjC/Swift override when present. Example: + // if (Owner_isOverride(self, @selector(getItemsAsNsArray))) { + // return [Adapter toImmutableListWithId:[self getItemsAsNsArray]]; + // } + // (or `[self setItems:[Adapter fromImmutableList:...]]; return;` for void methods). + private void prependOverrideCheck( + MethodDeclaration concreteDecl, TypeElement ownerType, ExecutablePair contractMethod) { + ImmutableList contractParams = + resolveParameters(contractMethod, getParameterElements(concreteDecl)); + ParameterMapping reverseMapping = + typeConverter.processParameters( + adapter, MappingStrategy.JAVA_TO_NATIVE, contractMethod.element(), contractParams); + GeneratedExecutableElement adapterMethodExecutable = + GeneratedExecutableElement.newAdapterMethod( + selector, + getAdapterReturnType(contractMethod), + reverseMapping.adapterParameters(), + contractMethod.element()); + Block thenBlock = + createAdaptedInvocationBlock( + adapterMethodExecutable, /* receiver= */ null, reverseMapping.adaptingArguments()); + if (TypeUtil.isVoid(originalMethodReturnType)) { + thenBlock.addStatement(new ReturnStatement()); + } + Expression checkExpression = + new NativeExpression( + String.format("%s(self, @selector(%s))", getOverrideCheckName(ownerType), selector), + typeUtil.getBoolean()); + concreteDecl + .getBody() + .getStatements() + .add(0, new IfStatement().setExpression(checkExpression).setThenStatement(thenBlock)); + } + + private static ImmutableList getParameterElements(MethodDeclaration decl) { + return decl.getParameters().stream() + .map(SingleVariableDeclaration::getVariableElement) + .collect(toImmutableList()); } private boolean isInSwiftNameContext() { @@ -647,7 +864,10 @@ private Block createReturnOrExpressionBlock(Expression expression) { : new ReturnStatement(expression)); } - /** Creates a concrete Java bridge method that delegates to the abstract KMP adapter stub. */ + /** + * Synthesizes a concrete unadapted bridge method (for abstract-class or {@code [super ...]} + * delegation) with {@code bodyBlock}. + */ private MethodDeclaration createBridgeMethodDeclaration(Block bodyBlock) { String originalSelector = nameTable.getMethodSelector(originalMethodExecutable); GeneratedExecutableElement bridgeExecutable = diff --git a/translator/src/main/java/com/google/devtools/j2objc/translate/KmpTypeConverter.java b/translator/src/main/java/com/google/devtools/j2objc/translate/KmpTypeConverter.java index 37eb644d0a..b2880e8fbf 100644 --- a/translator/src/main/java/com/google/devtools/j2objc/translate/KmpTypeConverter.java +++ b/translator/src/main/java/com/google/devtools/j2objc/translate/KmpTypeConverter.java @@ -15,6 +15,7 @@ package com.google.devtools.j2objc.translate; import com.google.common.base.Joiner; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.devtools.j2objc.Options; @@ -127,6 +128,105 @@ boolean canReverseAdaptReturnType(TypeMirror returnType, @Nullable TypeMirror ad && canReverseConvertType(adapterElement, returnType, /* isParam= */ false); } + /** + * Returns whether {@code subReturnType} can be reverse-adapted using the same native Objective-C + * return contract as {@code baseReturnType}. + */ + boolean canReverseAdaptSubclassReturn( + TypeMirror baseReturnType, TypeMirror subReturnType, @Nullable TypeMirror adapter) { + if (TypeUtil.isVoid(baseReturnType) || TypeUtil.isVoid(subReturnType)) { + return TypeUtil.isVoid(baseReturnType) && TypeUtil.isVoid(subReturnType); + } + TypeElement adapterElement = adapter != null ? TypeUtil.asTypeElement(adapter) : null; + if (adapterElement == null + || !typeUtil.isSubtype(typeUtil.erasure(subReturnType), typeUtil.erasure(baseReturnType)) + || !canReverseConvertType(adapterElement, baseReturnType, /* isParam= */ false) + || !canReverseConvertType(adapterElement, subReturnType, /* isParam= */ false)) { + return false; + } + for (MappingStrategy strategy : MappingStrategy.values()) { + if (!describeConversion(strategy, adapterElement, baseReturnType, null, true) + .equals(describeConversion(strategy, adapterElement, subReturnType, null, true))) { + return false; + } + } + return true; + } + + /** + * Native conversion applied to a Java type: {@code typeName} is the mapped native type name or the + * erased Java type name, {@code converter} is the adapter method for unmapped type lookups, and + * {@code args} describe each type argument. + */ + private record Conversion( + @Nullable String typeName, @Nullable ExecutableElement converter, List args) { + static final Conversion NONE = new Conversion(null, null, ImmutableList.of()); + + /** A type in {@link #JAVA_TO_NATIVE_TYPE_MAP}, compared by native type name only. */ + static Conversion mapped(String nativeName, List args) { + return new Conversion(nativeName, null, args); + } + + /** An unmapped type converted by {@code converter}. */ + static Conversion converted( + String typeName, ExecutableElement converter, List args) { + return new Conversion(typeName, converter, args); + } + + /** An unmapped type whose conversion is specialized by the enclosing converter's signature. */ + static Conversion specialized(String typeName, List args) { + return new Conversion(typeName, null, args); + } + } + + /** + * Describes how {@code type} is converted under {@code strategy}. A declared {@code pattern} from + * the enclosing converter's signature specializes the conversion; otherwise a composing parent + * looks up a converter and a direct parent passes the type through unconverted. + */ + private Conversion describeConversion( + MappingStrategy strategy, + TypeElement adapterElement, + TypeMirror type, + @Nullable TypeMirror pattern, + boolean parentComposing) { + ExecutableElement converter = null; + boolean composing = false; + if (pattern == null || !TypeUtil.isDeclaredType(pattern)) { + if (!parentComposing) { + return Conversion.NONE; + } + AdapterLookup.ConverterMatch match = + strategy.findReturnConverter(adapterLookup, adapterElement, type); + converter = match.converter(); + if (converter == null) { + return Conversion.NONE; + } + composing = match.matchType().isComposing(); + pattern = + strategy == MappingStrategy.JAVA_TO_NATIVE + ? converter.getReturnType() + : converter.getParameters().get(0).asType(); + } + String erasedName = TypeUtil.getQualifiedName(typeUtil.erasure(type)); + String nativeName = JAVA_TO_NATIVE_TYPE_MAP.get(erasedName); + List typeArgs = TypeUtil.getTypeArguments(type); + List patternArgs = TypeUtil.getTypeArguments(pattern); + List args = new ArrayList<>(); + for (int i = 0; i < typeArgs.size(); i++) { + TypeMirror typeArg = typeArgs.get(i); + TypeMirror patternArg = i < patternArgs.size() ? patternArgs.get(i) : null; + args.add(describeConversion(strategy, adapterElement, typeArg, patternArg, composing)); + } + if (nativeName != null) { + return Conversion.mapped(nativeName, args); + } else if (converter != null) { + return Conversion.converted(erasedName, converter, args); + } else { + return Conversion.specialized(erasedName, args); + } + } + private boolean canReverseConvertType( TypeElement adapterElement, TypeMirror type, boolean isParam) { var reverse = 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 e0673c003f..21b2445719 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 @@ -198,6 +198,9 @@ private void processType(AbstractTypeDeclaration typeNode) { // Only generate if this class owns the KMP config; when a superclass already owns it, // subclasses inherit its Objective-C adapter (which dynamically dispatches via `self`). ConcreteKmpOwner owner = methodHierarchy.findConcreteKmpOwner(typeElem, signature); + if (owner != null && !owner.ownerType().equals(typeElem)) { + adapterEmitter.prependSubclassOverrideCheck(typeNode, method, owner); + } shouldGenerate = owner != null && owner.ownerType().equals(typeElem); } diff --git a/translator/src/test/java/com/google/devtools/j2objc/SmallTests.java b/translator/src/test/java/com/google/devtools/j2objc/SmallTests.java index 5d02730ad2..6adf1060aa 100644 --- a/translator/src/test/java/com/google/devtools/j2objc/SmallTests.java +++ b/translator/src/test/java/com/google/devtools/j2objc/SmallTests.java @@ -74,6 +74,7 @@ import com.google.devtools.j2objc.translate.NumberMethodRewriterTest; import com.google.devtools.j2objc.translate.ObjectiveCAdapterMethodAnnotationTest; import com.google.devtools.j2objc.translate.ObjectiveCKmpMethodTranslatorTest; +import com.google.devtools.j2objc.translate.ObjectiveCKmpNativeOverrideTest; import com.google.devtools.j2objc.translate.ObjectiveCNativeEnumNameTest; import com.google.devtools.j2objc.translate.ObjectiveCNativeProtocolAnnotationTest; import com.google.devtools.j2objc.translate.OcniExtractorTest; @@ -177,6 +178,7 @@ public class SmallTests { ObjectiveCImplementationGeneratorTest.class, ObjectiveCNativeEnumNameTest.class, ObjectiveCKmpMethodTranslatorTest.class, + ObjectiveCKmpNativeOverrideTest.class, ObjectiveCNativeProtocolAnnotationTest.class, ObjectiveCSegmentedHeaderGeneratorTest.class, ObjectiveCSourceFileGeneratorTest.class, diff --git a/translator/src/test/java/com/google/devtools/j2objc/translate/KmpTypeConverterTest.java b/translator/src/test/java/com/google/devtools/j2objc/translate/KmpTypeConverterTest.java index 085aaa4bf4..0e3ff162e4 100644 --- a/translator/src/test/java/com/google/devtools/j2objc/translate/KmpTypeConverterTest.java +++ b/translator/src/test/java/com/google/devtools/j2objc/translate/KmpTypeConverterTest.java @@ -80,15 +80,86 @@ public class WildcardAdapter { } """; + private static final String INTEROP_ADAPTER_SOURCE = + """ + import com.google.common.collect.ImmutableList; + import com.google.common.collect.ImmutableMap; + import java.util.List; + import java.util.Map; + import java.util.function.Function; + + public class InteropAdapter { + public static native List toList(Object list) /*-[ return nil; ]-*/; + public static native Object fromList(List list) /*-[ return nil; ]-*/; + public static native List toList( + Object list, Function conv) /*-[ return nil; ]-*/; + public static native Object fromList( + List list, Function conv) /*-[ return nil; ]-*/; + public static native ImmutableList toImmutableList( + Object list) /*-[ return nil; ]-*/; + public static native Object fromImmutableList( + ImmutableList list) /*-[ return nil; ]-*/; + public static native ImmutableList toImmutableListInteger( + Object list) /*-[ return nil; ]-*/; + public static native Object fromImmutableListInteger( + ImmutableList list) /*-[ return nil; ]-*/; + public static native Map toMap( + Object map, Function kConv, Function vConv) /*-[ return nil; ]-*/; + public static native Object fromMap( + Map map, Function kConv, Function vConv) /*-[ + return nil; + ]-*/; + public static native ImmutableMap> + toImmutableMapTImmutableList(Object map) /*-[ return nil; ]-*/; + public static native Object fromImmutableMapTImmutableList( + ImmutableMap> map) /*-[ return nil; ]-*/; + public static native FutureBox toFuture(FutureBox box) /*-[ return nil; ]-*/; + public static native FutureBox fromFuture( + FutureBox box) /*-[ return nil; ]-*/; + public static native FutureBox toBooleanFuture( + FutureBox box) /*-[ return nil; ]-*/; + public static native FutureBox fromBooleanFuture( + FutureBox box) /*-[ return nil; ]-*/; + public static native Boolean toBoolean(Object b) /*-[ return nil; ]-*/; + public static native Object fromBoolean(Boolean b) /*-[ return nil; ]-*/; + public static native Integer toInteger(Object i) /*-[ return nil; ]-*/; + public static native Object fromInteger(Integer i) /*-[ return nil; ]-*/; + public static native PlainObj toPlainObj(Object obj) /*-[ return nil; ]-*/; + public static native Object fromPlainObj(PlainObj obj) /*-[ return nil; ]-*/; + public static native SubPlainObj toSubPlainObj(Object obj) /*-[ return nil; ]-*/; + public static native Object fromSubPlainObj(SubPlainObj obj) /*-[ return nil; ]-*/; + } + """; + + private static final String ASYMMETRIC_ADAPTER_SOURCE = + """ + import java.util.List; + import java.util.function.Function; + + public class AsymmetricAdapter { + public static native PlainObj toPlainObj(Object obj) /*-[ return nil; ]-*/; + public static native Object fromSubPlainObj(SubPlainObj obj) /*-[ return nil; ]-*/; + public static native Object fromString(String s) /*-[ return nil; ]-*/; + public static native Object fromBoolean(Boolean b) /*-[ return nil; ]-*/; + public static native List toJavaUtilList( + Object list, Function conv) /*-[ return nil; ]-*/; + public static native Object fromJavaUtilList( + List list, Function conv) /*-[ return nil; ]-*/; + } + """; + @Override public void setUp() throws IOException { super.setUp(); options.load(new String[] {"--objc-generics"}); addSourceFile(ADAPTER_SOURCE, "Adapter.java"); addSourceFile(WILDCARD_ADAPTER_SOURCE, "WildcardAdapter.java"); + addSourceFile(INTEROP_ADAPTER_SOURCE, "InteropAdapter.java"); + addSourceFile(ASYMMETRIC_ADAPTER_SOURCE, "AsymmetricAdapter.java"); addSourceFile("public interface MyProto {}", "MyProto.java"); addSourceFile("public class PlainObj {}", "PlainObj.java"); addSourceFile("public class SubPlainObj extends PlainObj {}", "SubPlainObj.java"); + addSourceFile("public class FutureBox {}", "FutureBox.java"); } private static KmpTypeConverter createConverter(CompilationUnit unit) { @@ -831,17 +902,7 @@ public void acceptVoid(String tag, int count) {} assertThat(converter.canReverseAdaptReturnType(echo.getReturnType(), adapter)).isTrue(); } - public void testCanReverseAdapt_asymmetricCustomAndStringConvertersReturnFalse() - throws IOException { - addSourceFile( - """ - public class AsymmetricAdapter { - public static native PlainObj toPlainObj(Object obj) /*-[ return nil; ]-*/; - public static native Object fromSubPlainObj(SubPlainObj obj) /*-[ return nil; ]-*/; - public static native Object fromString(String s) /*-[ return nil; ]-*/; - } - """, - "AsymmetricAdapter.java"); + public void testCanReverseAdapt_asymmetricCustomAndStringConvertersReturnFalse() { CompilationUnit unit = compileType( "Sample", @@ -886,20 +947,7 @@ public void takeBoolList(List flags) {} assertThat(canReverseAdapt(unit, converter, "getBoolList", wildcardAdapter)).isFalse(); } - public void testCanReverseAdapt_composingConvertersRecurseIntoTypeArguments() throws IOException { - addSourceFile( - """ - import java.util.List; - import java.util.function.Function; - public class ComposingPartialBoolAdapter { - public static native List toJavaUtilList( - Object list, Function conv) /*-[ return nil; ]-*/; - public static native Object fromJavaUtilList( - List list, Function conv) /*-[ return nil; ]-*/; - public static native Object fromBoolean(Boolean b) /*-[ return nil; ]-*/; - } - """, - "ComposingPartialBoolAdapter.java"); + public void testCanReverseAdapt_composingConvertersRecurseIntoTypeArguments() { CompilationUnit unit = compileType( "Sample", @@ -907,7 +955,7 @@ public static native Object fromJavaUtilList( import java.util.List; public class Sample { private Adapter adapterRef; - private ComposingPartialBoolAdapter partialBoolRef; + private AsymmetricAdapter partialBoolRef; public List> nested(List> items) { return items; } public List boolList(List flags) { return flags; } } @@ -915,9 +963,202 @@ public class Sample { KmpTypeConverter converter = createConverter(unit); assertThat(canReverseAdapt(unit, converter, "nested", resolveType(unit, "Adapter"))).isTrue(); + assertThat(canReverseAdapt(unit, converter, "boolList", resolveType(unit, "AsymmetricAdapter"))) + .isFalse(); + } + + private static boolean canReverseAdaptSubclassReturn( + CompilationUnit unit, + KmpTypeConverter converter, + String baseMethod, + String subMethod, + TypeMirror adapter) { + return converter.canReverseAdaptSubclassReturn( + findMethod(unit, baseMethod).getReturnType(), + findMethod(unit, subMethod).getReturnType(), + adapter); + } + + public void testCanReverseAdaptSubclassReturn_voidPassThroughAndFoundationCollections() { + CompilationUnit unit = + compileType( + "Sample", + """ + import com.google.common.collect.ImmutableList; + import java.util.List; + import java.util.Map; + public class Sample { + private Adapter unmappedAdapterRef; + private InteropAdapter adapterRef; + public void voidBase() {} + public void voidSub() {} + public PlainObj plainBase() { return null; } + public SubPlainObj subPlain() { return null; } + public Object objectBase() { return null; } + public String stringVal() { return ""; } + public List stringList() { return null; } + public ImmutableList immutableStringList() { return null; } + public Map stringMap() { return null; } + } + """); + KmpTypeConverter converter = createConverter(unit); + TypeMirror adapter = resolveType(unit, "InteropAdapter"); + TypeMirror unmappedAdapter = resolveType(unit, "Adapter"); + + assertThat(canReverseAdaptSubclassReturn(unit, converter, "voidBase", "voidSub", adapter)) + .isTrue(); + assertThat(canReverseAdaptSubclassReturn(unit, converter, "voidBase", "stringVal", adapter)) + .isFalse(); + assertThat(canReverseAdaptSubclassReturn(unit, converter, "stringVal", "voidSub", adapter)) + .isFalse(); + assertThat(canReverseAdaptSubclassReturn(unit, converter, "plainBase", "subPlain", null)) + .isFalse(); + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "plainBase", "subPlain", unmappedAdapter)) + .isTrue(); + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "plainBase", "stringVal", unmappedAdapter)) + .isFalse(); + assertThat(canReverseAdaptSubclassReturn(unit, converter, "objectBase", "stringList", adapter)) + .isFalse(); + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "stringList", "immutableStringList", adapter)) + .isTrue(); + assertThat(canReverseAdaptSubclassReturn(unit, converter, "stringList", "stringMap", adapter)) + .isFalse(); + } + + public void testCanReverseAdaptSubclassReturn_rejectsMismatchedElementConversions() { + CompilationUnit unit = + compileType( + "Sample", + """ + import java.util.List; + public class Sample { + private InteropAdapter interopAdapterRef; + private Adapter specializedAdapterRef; + public List wildcardList() { return null; } + public List objectList() { return null; } + @SuppressWarnings("rawtypes") + public List rawList() { return null; } + public List boolList() { return null; } + public List> nestedStringList() { return null; } + public List plainList() { return null; } + public List stringList() { return null; } + } + """); + KmpTypeConverter converter = createConverter(unit); + TypeMirror interopAdapter = resolveType(unit, "InteropAdapter"); + TypeMirror specializedAdapter = resolveType(unit, "Adapter"); + + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "wildcardList", "boolList", interopAdapter)) + .isFalse(); + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "objectList", "boolList", interopAdapter)) + .isFalse(); + assertThat( + canReverseAdaptSubclassReturn(unit, converter, "rawList", "boolList", interopAdapter)) + .isFalse(); + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "wildcardList", "nestedStringList", interopAdapter)) + .isFalse(); + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "wildcardList", "plainList", interopAdapter)) + .isTrue(); + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "wildcardList", "stringList", specializedAdapter)) + .isFalse(); + } + + public void testCanReverseAdaptSubclassReturn_rejectsComposingOrSpecializedVsDirectMismatch() { + CompilationUnit unit = + compileType( + "Sample", + """ + import com.google.common.collect.ImmutableList; + import com.google.common.collect.ImmutableMap; + import java.util.List; + import java.util.Map; + public class Sample { + private InteropAdapter adapterRef; + public Map> intMap() { return null; } + public ImmutableMap> immutableIntMap() { + return null; + } + public Map> stringToIntListMap() { return null; } + public ImmutableMap> immutableStringToIntListMap() { + return null; + } + public Map> stringMap() { return null; } + public ImmutableMap> immutableStringMap() { + return null; + } + public List intList() { return null; } + public ImmutableList immutableIntList() { return null; } + } + """); + KmpTypeConverter converter = createConverter(unit); + TypeMirror adapter = resolveType(unit, "InteropAdapter"); + + // Composing Map converts Integer keys via toInteger/fromInteger, whereas + // direct ImmutableMap> passes keys through unconverted. + assertThat(canReverseAdaptSubclassReturn(unit, converter, "intMap", "immutableIntMap", adapter)) + .isFalse(); + // Composing Map> converts inner Integer elements via + // toImmutableListInteger, whereas direct ImmutableMap> leaves U + // unconverted. + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "stringToIntListMap", "immutableStringToIntListMap", adapter)) + .isFalse(); + // Direct List skips Integer conversion, whereas specialized ImmutableList + // converts elements. + assertThat( + canReverseAdaptSubclassReturn(unit, converter, "intList", "immutableIntList", adapter)) + .isFalse(); + // Composing Map passes String through unconverted (no String converter), matching + // direct ImmutableMap>. assertThat( - canReverseAdapt( - unit, converter, "boolList", resolveType(unit, "ComposingPartialBoolAdapter"))) + canReverseAdaptSubclassReturn( + unit, converter, "stringMap", "immutableStringMap", adapter)) + .isTrue(); + } + + public void testCanReverseAdaptSubclassReturn_nonFoundationConvertersRequireCompatibleContract() { + CompilationUnit unit = + compileType( + "Sample", + """ + public class Sample { + private InteropAdapter adapterRef; + public FutureBox wildcardFuture() { return null; } + public FutureBox boolFuture() { return null; } + public FutureBox stringFuture() { return null; } + public PlainObj plainBase() { return null; } + public SubPlainObj subPlain() { return null; } + } + """); + KmpTypeConverter converter = createConverter(unit); + TypeMirror adapter = resolveType(unit, "InteropAdapter"); + + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "wildcardFuture", "boolFuture", adapter)) + .isFalse(); + assertThat( + canReverseAdaptSubclassReturn( + unit, converter, "wildcardFuture", "stringFuture", adapter)) + .isTrue(); + assertThat(canReverseAdaptSubclassReturn(unit, converter, "plainBase", "subPlain", adapter)) .isFalse(); } 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 64c95f3735..b78c0d1e66 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 @@ -1327,17 +1327,25 @@ public ImmutableList getItems() { return (NSArray *) [ImmutableListAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:[self getItems]]; } """); - // Original methods should be generated normally + // Original methods should include the override check for non-final concrete classes assertInTranslation( concreteImpl, """ - (void)setItemsWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items { + if (ConcreteClass_isOverride(self, @selector(setItems:))) { + [self setItems:(NSArray *) [ImmutableListAdapter \ + fromImmutableListWithComGoogleCommonCollectImmutableList:items]]; + return; + } } """); assertInTranslation( concreteImpl, """ - (ComGoogleCommonCollectImmutableList *)getItems { + if (ConcreteClass_isOverride(self, @selector(getItemsAsNSArray))) { + return [ImmutableListAdapter toImmutableListWithId:[self getItemsAsNSArray]]; + } return ComGoogleCommonCollectImmutableList_of(); } """); @@ -1466,17 +1474,27 @@ public ImmutableList getItems() { return (NSArray *) [ImmutableListAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *) [self getItems]]; } """); - // Original methods should be generated normally + // Original methods should include the override check for non-final concrete classes assertInTranslation( concreteImpl, """ - (void)setItemsWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items { + if (ConcreteClass_isOverride(self, @selector(setItems:))) { + [self setItems:(NSArray *) [ImmutableListAdapter \ + fromImmutableListWithComGoogleCommonCollectImmutableList:\ + (ComGoogleCommonCollectImmutableList *) items]]; + return; + } } """); assertInTranslation( concreteImpl, """ - (ComGoogleCommonCollectImmutableList *)getItems { + if (ConcreteClass_isOverride(self, @selector(getItemsAsNSArray))) { + return (ComGoogleCommonCollectImmutableList *) [ImmutableListAdapter \ + toImmutableListWithId:[self getItemsAsNSArray]]; + } return ComGoogleCommonCollectImmutableList_of(); } """); @@ -1869,7 +1887,8 @@ public void setBooleanSet(Set set) {} impl, """ - (void)setBooleanSet:(NSSet *)set { - [self setBooleanSetWithJavaUtilSet:(id) [Adapter toJavaUtilSetWithId:set withJavaUtilFunctionFunction:JreLoadStatic(TestSetOfBoolean_$KmpLambda$1, instance)]]; + [self setBooleanSetWithJavaUtilSet:(id) [Adapter toJavaUtilSetWithId:set \ + withJavaUtilFunctionFunction:JreLoadStatic(TestSetOfBoolean_$KmpLambda$2, instance)]]; } """); assertInTranslation( @@ -1936,7 +1955,8 @@ public void setBooleanSet(Set set) {} impl, """ - (void)setBooleanSet:(NSSet *)set { - [self setBooleanSetWithJavaUtilSet:(id) [Adapter toJavaUtilSetWithId:set withJavaUtilFunctionFunction:JreLoadStatic(TestSetLeaf_$KmpLambda$1, instance)]]; + [self setBooleanSetWithJavaUtilSet:(id) [Adapter toJavaUtilSetWithId:set \ + withJavaUtilFunctionFunction:JreLoadStatic(TestSetLeaf_$KmpLambda$2, instance)]]; } """); assertInTranslation( @@ -1967,7 +1987,9 @@ public void setBooleanList(List list) {} impl, """ - (void)setBooleanList:(NSArray *)list { - [self setBooleanListWithJavaUtilList:(id) [Adapter toJavaUtilListWithId:list withJavaUtilFunctionFunction:JreLoadStatic(TestListParam_$KmpLambda$1, instance)]]; + [self setBooleanListWithJavaUtilList:(id) [Adapter \ + toJavaUtilListWithId:list \ + withJavaUtilFunctionFunction:JreLoadStatic(TestListParam_$KmpLambda$2, instance)]]; } """); assertInTranslation( @@ -1999,7 +2021,8 @@ public void setListSet(Set> set) {} impl, """ - (void)setListSet:(NSSet *> *)set { - [self setListSetWithJavaUtilSet:(id) [Adapter toJavaUtilSetWithId:set withJavaUtilFunctionFunction:JreLoadStatic(TestSetOfList_$KmpLambda$1, instance)]]; + [self setListSetWithJavaUtilSet:(id) [Adapter toJavaUtilSetWithId:set \ + withJavaUtilFunctionFunction:JreLoadStatic(TestSetOfList_$KmpLambda$2, instance)]]; } """); assertInTranslation( @@ -2264,7 +2287,7 @@ public void verifyList(List>> list) {} """ - (void)verifyList:(NSArray *> *> *)list { [self verifyListWithJavaUtilList:(id) [Adapter toJavaUtilListWithId:list \ - withJavaUtilFunctionFunction:JreLoadStatic(TestClass_$KmpLambda$1, instance)]]; + withJavaUtilFunctionFunction:JreLoadStatic(TestClass_$KmpLambda$2, instance)]]; } """); assertInTranslation( @@ -2299,7 +2322,8 @@ public class TestClass { """ - (Container *)getNsNumberContainer { return (Container *) [Adapter fromContainerWithContainer:(Container *) \ - [self getFloatContainer] withJavaUtilFunctionFunction:JreLoadStatic(TestClass_$KmpLambda$1, instance)]; + [self getFloatContainer] \ + withJavaUtilFunctionFunction:JreLoadStatic(TestClass_$KmpLambda$2, instance)]; } """); } @@ -2326,7 +2350,7 @@ public void setFloatContainer(Container<@Nullable Float> c) {} - (void)setNsNumberContainer:(Container *)c { [self setFloatContainerWithContainer:(Container *) [Adapter \ toContainerWithContainer:(Container *) c \ - withJavaUtilFunctionFunction:JreLoadStatic(TestClass_$KmpLambda$1, instance)]]; + withJavaUtilFunctionFunction:JreLoadStatic(TestClass_$KmpLambda$2, instance)]]; } """); } @@ -2352,7 +2376,7 @@ public void setBooleanContainer(Container c) {} - (void)setBooleanContainer:(Container *)c { [self setBooleanContainerWithContainer:(Container *) [Adapter \ toContainerWithContainer:(Container *) c \ - withJavaUtilFunctionFunction:JreLoadStatic(TestClass_$KmpLambda$1, instance)]]; + withJavaUtilFunctionFunction:JreLoadStatic(TestClass_$KmpLambda$2, instance)]]; } """); } @@ -2484,9 +2508,16 @@ public Integer getCount() { concreteImpl, """ - (void)setCountWithJavaLangInteger:(JavaLangInteger *)count { + if (ConcreteCountService_isOverride(self, @selector(updateCount:))) { + [self updateCount:(NSNumber *) [Adapter fromIntegerWithJavaLangInteger:count]]; + return; + } } - (JavaLangInteger *)getCount { + if (ConcreteCountService_isOverride(self, @selector(fetchCount))) { + return [Adapter toIntegerWithId:[self fetchCount]]; + } return JavaLangInteger_valueOfWithInt_(0); } """); @@ -2800,6 +2831,8 @@ public static ActionCallback create() { [self onRenderWithComGoogleCommonCollectImmutableList:[ImmutableListAdapter toImmutableListWithId:actions]]; } """); + assertNotInTranslation(impl, "CallbackFactory_$Lambda$1_isOverride"); + assertNotInTranslation(impl, "_dispatch"); } public void testComposableConverter_withPreexistingLambdasInClass() throws IOException { diff --git a/translator/src/test/java/com/google/devtools/j2objc/translate/ObjectiveCKmpNativeOverrideTest.java b/translator/src/test/java/com/google/devtools/j2objc/translate/ObjectiveCKmpNativeOverrideTest.java new file mode 100644 index 0000000000..5a79c4ecc1 --- /dev/null +++ b/translator/src/test/java/com/google/devtools/j2objc/translate/ObjectiveCKmpNativeOverrideTest.java @@ -0,0 +1,1143 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.devtools.j2objc.translate; + +import com.google.devtools.j2objc.GenerationTest; +import com.google.devtools.j2objc.util.CodeReferenceMap; +import java.io.IOException; + +/** + * Tests native subclass override dispatch generation for concrete {@code @ObjectiveCKmpMethod} + * declarations in {@link ObjectiveCKmpMethodTranslator}. + */ +public class ObjectiveCKmpNativeOverrideTest extends GenerationTest { + + @Override + public void setUp() throws IOException { + super.setUp(); + options.load(new String[] {"--objc-generics"}); + addSourceFile("public class Foo {}", "Foo.java"); + addSourceFile("public class SubFoo extends Foo {}", "SubFoo.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import java.util.List; + import java.util.function.Function; + + public class TestAdapter { + public static native Object fromJavaUtilList(List list) /*-[ return nil; ]-*/; + public static native List toJavaUtilList(Object list) /*-[ return nil; ]-*/; + public static native Object fromJavaUtilList( + List list, Function converter) /*-[ return nil; ]-*/; + public static native List toJavaUtilList( + Object list, Function converter) /*-[ return nil; ]-*/; + public static native Object fromImmutableList( + ImmutableList list) /*-[ return nil; ]-*/; + public static native ImmutableList toImmutableList( + Object list) /*-[ return nil; ]-*/; + public static native Object fromBoolean(Boolean b) /*-[ return nil; ]-*/; + public static native Boolean toBoolean(Object b) /*-[ return nil; ]-*/; + } + """, + "TestAdapter.java"); + } + + private void addOpenService() throws IOException { + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public class OpenService { + @ObjectiveCKmpMethod(selector = "getItemsAsNsArray", adapter = TestAdapter.class) + public ImmutableList getItems() { + return ImmutableList.of(); + } + + @ObjectiveCKmpMethod(selector = "setItems:", adapter = TestAdapter.class) + public void setItems(ImmutableList items) {} + } + """, + "OpenService.java"); + } + + private void addInterfaceWithDefault() throws IOException { + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public interface InterfaceWithDefault { + @ObjectiveCKmpMethod(selector = "getItemsAsNsArray", adapter = TestAdapter.class) + default ImmutableList getItems() { + return ImmutableList.of(); + } + + @ObjectiveCKmpMethod(selector = "setItems:", adapter = TestAdapter.class) + default void setItems(ImmutableList items) {} + } + """, + "InterfaceWithDefault.java"); + } + + public void testOpenConcreteClass_emitsOverrideCheckAndInlinesAdaptedCall() throws IOException { + addOpenService(); + + String header = translateSourceFile("OpenService", "OpenService.h"); + assertOccurrences( + header, + "FOUNDATION_EXPORT bool OpenService_isOverride(OpenService *self, SEL selector);", + 1); + assertNotInTranslation(header, "_dispatch"); + + String impl = translateSourceFile("OpenService", "OpenService.m"); + assertOccurrences( + impl, + """ + bool OpenService_isOverride(OpenService *self, SEL selector) { + if (self == nil) { + return false; + } + Class cls = [self class]; + Class owner = [OpenService class]; + if (cls == owner || ![cls isSubclassOfClass:owner]) { + return false; + } + IMP clsImp = [cls instanceMethodForSelector:selector]; + IMP ownerImp = [owner instanceMethodForSelector:selector]; + return clsImp != ownerImp; + } + """, + 1); + assertInTranslation( + impl, + """ + - (ComGoogleCommonCollectImmutableList *)getItems { + if (OpenService_isOverride(self, @selector(getItemsAsNsArray))) { + return [TestAdapter toImmutableListWithId:[self getItemsAsNsArray]]; + } + return ComGoogleCommonCollectImmutableList_of(); + } + """); + assertInTranslation( + impl, + """ + - (void)setItemsWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items { + if (OpenService_isOverride(self, @selector(setItems:))) { + [self setItems:(NSArray *) [TestAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:items]]; + return; + } + } + """); + assertNotInTranslation(impl, "_dispatch"); + } + + public void testNonOverridableDeclarations_skipOverrideChecks() throws IOException { + addInterfaceWithDefault(); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public class ServiceWithFinalMethod { + @ObjectiveCKmpMethod(selector = "getItemsAsNsArray", adapter = TestAdapter.class) + public final ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "ServiceWithFinalMethod.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public final class FinalService { + @ObjectiveCKmpMethod(selector = "getItemsAsNsArray", adapter = TestAdapter.class) + public ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "FinalService.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public enum ServiceEnum { + INSTANCE; + + @ObjectiveCKmpMethod(selector = "getItemsAsNsArray", adapter = TestAdapter.class) + public ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "ServiceEnum.java"); + addSourceFile( + """ + public class AnonAndPrivateFactory { + private static class PrivateImpl implements InterfaceWithDefault {} + + public static InterfaceWithDefault createAnon() { + return new InterfaceWithDefault() {}; + } + + public static InterfaceWithDefault createPrivate() { + return new PrivateImpl(); + } + } + """, + "AnonAndPrivateFactory.java"); + + for (String className : + new String[] { + "ServiceWithFinalMethod", "FinalService", "ServiceEnum", "AnonAndPrivateFactory" + }) { + String impl = translateSourceFile(className, className + ".m"); + assertInTranslation(impl, "- (NSArray *)getItemsAsNsArray"); + assertNotInTranslation(impl, "_isOverride"); + assertNotInTranslation(impl, "_dispatch"); + } + } + + public void testMultiLevelJavaSubclass_delegatesToBaseOverrideCheck() throws IOException { + addOpenService(); + addSourceFile("public class SilentMidService extends OpenService {}", "SilentMidService.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class JavaSubService extends SilentMidService { + @Override + public ImmutableList getItems() { + return super.getItems(); + } + + @Override + public void setItems(ImmutableList items) { + super.setItems(items); + } + } + """, + "JavaSubService.java"); + + String midImpl = translateSourceFile("SilentMidService", "SilentMidService.m"); + assertNotInTranslation(midImpl, "getItemsAsNsArray"); + assertNotInTranslation(midImpl, "setItems:"); + assertNotInTranslation(midImpl, "_isOverride"); + assertNotInTranslation(midImpl, "_dispatch"); + + String subImpl = translateSourceFile("JavaSubService", "JavaSubService.m"); + assertInTranslation( + subImpl, + """ + - (ComGoogleCommonCollectImmutableList *)getItems { + if (OpenService_isOverride(self, @selector(getItemsAsNsArray))) { + return [TestAdapter toImmutableListWithId:[self getItemsAsNsArray]]; + } + return [super getItems]; + } + """); + assertInTranslation( + subImpl, + """ + - (void)setItemsWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items { + if (OpenService_isOverride(self, @selector(setItems:))) { + [self setItems:(NSArray *) [TestAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:items]]; + return; + } + [super setItemsWithComGoogleCommonCollectImmutableList:items]; + } + """); + assertNotInTranslation(subImpl, "- (NSArray *)getItemsAsNsArray"); + assertNotInTranslation(subImpl, "- (void)setItems:"); + assertNotInTranslation(subImpl, "JavaSubService_isOverride"); + assertNotInTranslation(subImpl, "_dispatch"); + } + + public void testFinalSubclassAndFinalOverride_skipOverrideChecks() throws IOException { + addOpenService(); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public final class FinalSub extends OpenService { + @Override + public ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "FinalSub.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class NonFinalSub extends OpenService { + @Override + public final ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "NonFinalSub.java"); + + for (String className : new String[] {"FinalSub", "NonFinalSub"}) { + String impl = translateSourceFile(className, className + ".m"); + assertInTranslation(impl, "- (ComGoogleCommonCollectImmutableList *)getItems"); + assertNotInTranslation(impl, "_isOverride"); + assertNotInTranslation(impl, "_dispatch"); + } + } + + public void testPrivateSuperclassKmpMethod_notInheritedBySubclass() throws IOException { + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public class BaseWithPrivate { + @ObjectiveCKmpMethod(selector = "getSecretAsNsArray", adapter = TestAdapter.class) + private ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "BaseWithPrivate.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class SubWithPublic extends BaseWithPrivate { + public ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "SubWithPublic.java"); + + String baseImpl = translateSourceFile("BaseWithPrivate", "BaseWithPrivate.m"); + assertInTranslation(baseImpl, "- (NSArray *)getSecretAsNsArray"); + assertNotInTranslation(baseImpl, "BaseWithPrivate_isOverride"); + assertNotInTranslation(baseImpl, "BaseWithPrivate_getItems_dispatch"); + + String subImpl = translateSourceFile("SubWithPublic", "SubWithPublic.m"); + assertInTranslation(subImpl, "- (ComGoogleCommonCollectImmutableList *)getItems"); + assertNotInTranslation(subImpl, "_isOverride"); + assertNotInTranslation(subImpl, "_dispatch"); + assertNotInTranslation(subImpl, "getSecretAsNsArray"); + } + + public void testOneWayAdapter_skipsOverrideChecksOnBaseAndSubclass() throws IOException { + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class OneWayReturnAdapter { + public static native Object fromImmutableList( + ImmutableList list) /*-[ return nil; ]-*/; + } + """, + "OneWayReturnAdapter.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public class OpenService { + @ObjectiveCKmpMethod(selector = "getItemsAsNsArray", adapter = OneWayReturnAdapter.class) + public ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "OpenService.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class JavaSubService extends OpenService { + @Override + public ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "JavaSubService.java"); + + String openImpl = translateSourceFile("OpenService", "OpenService.m"); + assertInTranslation(openImpl, "- (NSArray *)getItemsAsNsArray"); + assertNotInTranslation(openImpl, "_isOverride"); + assertNotInTranslation(openImpl, "_dispatch"); + + String subImpl = translateSourceFile("JavaSubService", "JavaSubService.m"); + assertNotInTranslation(subImpl, "_isOverride"); + assertNotInTranslation(subImpl, "_dispatch"); + } + + public void testUnannotatedSuperclassImplementingKmpInterface_synthesizesSuperBridge() + throws IOException { + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class UnannotatedBase { + public T getItem(ImmutableList items) { + return null; + } + + public void setItems(ImmutableList items) {} + } + """, + "UnannotatedBase.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public interface KmpSubFooInterface { + @ObjectiveCKmpMethod(selector = "getItem:", adapter = TestAdapter.class) + Foo getItem(ImmutableList items); + + @ObjectiveCKmpMethod(selector = "setItems:", adapter = TestAdapter.class) + void setItems(ImmutableList items); + } + """, + "KmpSubFooInterface.java"); + addSourceFile( + "public class MidService extends UnannotatedBase implements KmpSubFooInterface {}", + "MidService.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class SubService extends MidService { + @Override + public SubFoo getItem(ImmutableList items) { + return null; + } + } + """, + "SubService.java"); + + String midHeader = translateSourceFile("MidService", "MidService.h"); + assertInTranslation( + midHeader, "FOUNDATION_EXPORT bool MidService_isOverride(MidService *self, SEL selector);"); + assertNotInTranslation(midHeader, "_dispatch"); + assertOccurrences( + midHeader, + "- (SubFoo *)getItemWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items;", + 1); + assertNotInTranslation(midHeader, "- (void)setItemsWithComGoogleCommonCollectImmutableList:"); + + String midImpl = translateSourceFile("MidService", "MidService.m"); + assertInTranslation(midImpl, "- (SubFoo *)getItem:(NSArray *)items"); + assertInTranslation(midImpl, "- (void)setItems:(NSArray *)items"); + assertInTranslation( + midImpl, + """ + - (SubFoo *)getItemWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items { + if (MidService_isOverride(self, @selector(getItem:))) { + return (SubFoo *) [self getItem:(NSArray *) [TestAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:items]]; + } + return (SubFoo *) [super getItemWithComGoogleCommonCollectImmutableList:items]; + } + """); + assertInTranslation( + midImpl, + """ + - (void)setItemsWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items { + if (MidService_isOverride(self, @selector(setItems:))) { + [self setItems:(NSArray *) [TestAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:items]]; + return; + } + [super setItemsWithComGoogleCommonCollectImmutableList:items]; + } + """); + + String subImpl = translateSourceFile("SubService", "SubService.m"); + assertInTranslation( + subImpl, + """ + - (SubFoo *)getItemWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items { + if (MidService_isOverride(self, @selector(getItem:))) { + return (SubFoo *) [self getItem:(NSArray *) [TestAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:items]]; + } + return nil; + } + """); + assertNotInTranslation(subImpl, "UnannotatedBase_isOverride"); + assertNotInTranslation(subImpl, "- (SubFoo *)getItem:(NSArray *)items"); + } + + public void testInheritedInterfaceDefaultMethod_prependsCheckAndSharesWithSubclass() + throws IOException { + addInterfaceWithDefault(); + addSourceFile( + "public class ConcreteInherits implements InterfaceWithDefault {}", + "ConcreteInherits.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class SubOverrides extends ConcreteInherits { + @Override + public ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "SubOverrides.java"); + + String inheritsImpl = translateSourceFile("ConcreteInherits", "ConcreteInherits.m"); + assertInTranslation( + inheritsImpl, "bool ConcreteInherits_isOverride(ConcreteInherits *self, SEL selector)"); + assertNotInTranslation(inheritsImpl, "_dispatch"); + assertInTranslation( + inheritsImpl, + """ + - (ComGoogleCommonCollectImmutableList *)getItems { + if (ConcreteInherits_isOverride(self, @selector(getItemsAsNsArray))) { + return [TestAdapter toImmutableListWithId:[self getItemsAsNsArray]]; + } + return InterfaceWithDefault_getItems(self); + } + """); + assertInTranslation( + inheritsImpl, + """ + - (void)setItemsWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)arg0 { + if (ConcreteInherits_isOverride(self, @selector(setItems:))) { + [self setItems:(NSArray *) [TestAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:arg0]]; + return; + } + InterfaceWithDefault_setItemsWithComGoogleCommonCollectImmutableList_(self, arg0); + } + """); + + String subImpl = translateSourceFile("SubOverrides", "SubOverrides.m"); + assertInTranslation( + subImpl, + """ + - (ComGoogleCommonCollectImmutableList *)getItems { + if (ConcreteInherits_isOverride(self, @selector(getItemsAsNsArray))) { + return [TestAdapter toImmutableListWithId:[self getItemsAsNsArray]]; + } + return ComGoogleCommonCollectImmutableList_of(); + } + """); + assertNotInTranslation(subImpl, "- (NSArray *)getItemsAsNsArray"); + assertNotInTranslation(subImpl, "SubOverrides_isOverride"); + assertNotInTranslation(subImpl, "_dispatch"); + } + + public void testSubinterfaceDefaultMethodOverride_reusesBaseConcreteOwnerCheck() + throws IOException { + addInterfaceWithDefault(); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public interface SubInterfaceWithDefault extends InterfaceWithDefault { + @Override + default ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "SubInterfaceWithDefault.java"); + addSourceFile( + "public class ConcreteBase implements InterfaceWithDefault {}", "ConcreteBase.java"); + addSourceFile( + "public class SubConcrete extends ConcreteBase implements SubInterfaceWithDefault {}", + "SubConcrete.java"); + + String subImpl = translateSourceFile("SubConcrete", "SubConcrete.m"); + assertInTranslation( + subImpl, + """ + - (ComGoogleCommonCollectImmutableList *)getItems { + if (ConcreteBase_isOverride(self, @selector(getItemsAsNsArray))) { + return [TestAdapter toImmutableListWithId:[self getItemsAsNsArray]]; + } + return SubInterfaceWithDefault_getItems(self); + } + """); + assertNotInTranslation(subImpl, "SubConcrete_isOverride"); + assertNotInTranslation(subImpl, "_dispatch"); + } + + private void assertMultiSelectorDefaultMethodShims( + String implName, + String subProtoName, + String superInterfaces, + String primarySelectorPart, + String secondarySelectorPart) + throws IOException { + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public interface GenericDefaultProto { + @ObjectiveCKmpMethod(selector = "workWith:items:", adapter = TestAdapter.class) + default void work(T tag, ImmutableList items) {} + } + """, + "GenericDefaultProto.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public interface StringDefaultProto { + void work(String tag, ImmutableList items); + } + """, + "StringDefaultProto.java"); + addSourceFile( + String.format( + """ + import com.google.common.collect.ImmutableList; + + public interface %s extends %s { + @Override + default void work(String tag, ImmutableList items) {} + } + """, + subProtoName, superInterfaces), + subProtoName + ".java"); + + String impl = + translateSourceFile( + "public class " + implName + " implements " + subProtoName + " {}", + implName, + implName + ".m"); + assertOccurrences(impl, "if (" + implName + "_isOverride(", 1); + assertInTranslation( + impl, + String.format( + """ + - (void)workWith%s:(NSString *)arg0 + withComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)arg1 { + if (%s_isOverride(self, @selector(workWith:items:))) { + [self workWith:arg0 items:(NSArray *) [TestAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:arg1]]; + return; + } + %s_workWithNSString_withComGoogleCommonCollectImmutableList_(self, arg0, arg1); + } + + - (void)workWith%s:(NSString *)arg0 + withComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)arg1 { + [self workWith%s:arg0 withComGoogleCommonCollectImmutableList:arg1]; + } + """, + primarySelectorPart, + implName, + subProtoName, + secondarySelectorPart, + primarySelectorPart)); + assertNotInTranslation( + impl, subProtoName + "_workWithNSString_withComGoogleCommonCollectImmutableList__dispatch"); + } + + public void testMultiSelectorDefaultMethodShims_genericFirstForwardsViaPrimaryCheck() + throws IOException { + assertMultiSelectorDefaultMethodShims( + "MultiSelectorDefaultImpl", + "SubDefaultProto", + "GenericDefaultProto, StringDefaultProto", + "Id", + "NSString"); + } + + public void testMultiSelectorDefaultMethodShims_stringFirstForwardsViaPrimaryCheck() + throws IOException { + assertMultiSelectorDefaultMethodShims( + "StringFirstDefaultImpl", + "StringFirstSubProto", + "StringDefaultProto, GenericDefaultProto", + "NSString", + "Id"); + } + + public void testNoWrapperMethodsWithSwiftName_preservesNullabilityWithoutSwiftFunctionWrappers() + throws IOException { + options.load(new String[] {"--nullability", "--no-wrapper-methods"}); + options.setNullMarked(true); + + String header = + translateSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import com.google.j2objc.annotations.SwiftName; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + + @NullMarked + @SwiftName("SwiftOpenService") + public class OpenService { + @ObjectiveCKmpMethod(selector = "getItemsAsNsArray", adapter = TestAdapter.class) + public @Nullable ImmutableList getItems() { + return null; + } + } + """, + "OpenService", + "OpenService.h"); + assertInTranslation( + header, "FOUNDATION_EXPORT bool OpenService_isOverride(OpenService *self, SEL selector);"); + assertInTranslation( + header, "- (NSArray * _Nullable)getItemsAsNsArray NS_SWIFT_NAME(getItemsAsNsArray());"); + assertNotInTranslation(header, "_dispatch"); + assertNotInTranslation(header, "OpenService_isOverride_swiftName"); + } + + public void testCovariantMappedReturnType_inlinesNarrowedReturnConverter() throws IOException { + String subImpl = + translateSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + class ListBase { + @ObjectiveCKmpMethod(selector = "getItemsAsNsArray", adapter = TestAdapter.class) + public List getItems() { + return ImmutableList.of(); + } + } + + public class ImmutableSub extends ListBase { + @Override + public ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "ImmutableSub", + "ImmutableSub.m"); + assertInTranslation( + subImpl, + """ + - (ComGoogleCommonCollectImmutableList *)getItems { + if (ListBase_isOverride(self, @selector(getItemsAsNsArray))) { + return [TestAdapter toImmutableListWithId:[self getItemsAsNsArray]]; + } + return ComGoogleCommonCollectImmutableList_of(); + } + """); + assertNotInTranslation(subImpl, "ListBase_getItems_dispatch"); + } + + public void testCovariantUnadaptedReturnType_skipsOverrideCheck() throws IOException { + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + class ListOnlyAdapter { + public static native Object fromJavaUtilList(List list) /*-[ return nil; ]-*/; + public static native List toJavaUtilList(Object list) /*-[ return nil; ]-*/; + } + + public class ListOnlyBase { + @ObjectiveCKmpMethod(selector = "getItemsAsNsArray", adapter = ListOnlyAdapter.class) + public List getItems() { + return ImmutableList.of(); + } + } + """, + "ListOnlyBase.java"); + + String subImpl = + translateSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class UnadaptedImmutableSub extends ListOnlyBase { + @Override + public ImmutableList getItems() { + return ImmutableList.of(); + } + } + """, + "UnadaptedImmutableSub", + "UnadaptedImmutableSub.m"); + assertInTranslation(subImpl, "- (ComGoogleCommonCollectImmutableList *)getItems"); + assertNotInTranslation(subImpl, "ListOnlyBase_isOverride"); + } + + public void testCovariantUnmappedReturnType_castsAdaptedReturnInSubclass() throws IOException { + String subImpl = + translateSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + class FooBase { + @ObjectiveCKmpMethod(selector = "getItem:", adapter = TestAdapter.class) + public Foo getItem(ImmutableList items) { + return null; + } + } + + public class SubFooService extends FooBase { + @Override + public SubFoo getItem(ImmutableList items) { + return null; + } + } + """, + "SubFooService", + "SubFooService.m"); + assertInTranslation( + subImpl, + """ + - (SubFoo *)getItemWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items { + if (FooBase_isOverride(self, @selector(getItem:))) { + return (SubFoo *) [self getItem:(NSArray *) [TestAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:items]]; + } + return nil; + } + """); + } + + public void testGenericBaseWithBidirectionalConverter_delegatesSubclassToBase() + throws IOException { + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class BidirectionalGenericAdapter { + public static native Object fromImmutableList( + ImmutableList list) /*-[ return nil; ]-*/; + public static native ImmutableList toImmutableList( + Object list) /*-[ return nil; ]-*/; + } + """, + "BidirectionalGenericAdapter.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public class GenericBase { + @ObjectiveCKmpMethod( + selector = "getItemsAsNsArray", + adapter = BidirectionalGenericAdapter.class) + public ImmutableList getItems() { + return ImmutableList.of(); + } + + @ObjectiveCKmpMethod(selector = "setItems:", adapter = BidirectionalGenericAdapter.class) + public void setItems(ImmutableList items) {} + } + """, + "GenericBase.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class StringSub extends GenericBase { + @Override + public ImmutableList getItems() { + return ImmutableList.of(); + } + + @Override + public void setItems(ImmutableList items) {} + } + """, + "StringSub.java"); + + String baseImpl = translateSourceFile("GenericBase", "GenericBase.m"); + assertInTranslation(baseImpl, "bool GenericBase_isOverride(GenericBase *self, SEL selector)"); + assertNotInTranslation(baseImpl, "_dispatch"); + + String subImpl = translateSourceFile("StringSub", "StringSub.m"); + assertInTranslation( + subImpl, + """ + - (ComGoogleCommonCollectImmutableList *)getItems { + if (GenericBase_isOverride(self, @selector(getItemsAsNsArray))) { + return (ComGoogleCommonCollectImmutableList *) [BidirectionalGenericAdapter toImmutableListWithId:[self getItemsAsNsArray]]; + } + return ComGoogleCommonCollectImmutableList_of(); + } + """); + assertInTranslation( + subImpl, + """ + - (void)setItemsWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items { + if (GenericBase_isOverride(self, @selector(setItems:))) { + [self setItems:(NSArray *) [BidirectionalGenericAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *) items]]; + return; + } + } + """); + } + + public void testGenericBaseSpecializedParamWithCovariantReturn_usesBaseParameterContract() + throws IOException { + String subImpl = + translateSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + class GenericBase { + @ObjectiveCKmpMethod(selector = "process:items:", adapter = TestAdapter.class) + public List process(T tag, List items) { + return items; + } + } + + public class BooleanSub extends GenericBase { + @Override + public ImmutableList process(Boolean id, List inputItems) { + return ImmutableList.of(); + } + } + """, + "BooleanSub", + "BooleanSub.m"); + assertInTranslation( + subImpl, + """ + - (ComGoogleCommonCollectImmutableList *)processWithId:(JavaLangBoolean *)id_ + withJavaUtilList:(id)inputItems { + if (GenericBase_isOverride(self, @selector(process:items:))) { + return [TestAdapter toImmutableListWithId:[self process:id_ items:(NSArray *) [TestAdapter fromJavaUtilListWithJavaUtilList:inputItems]]]; + } + return ComGoogleCommonCollectImmutableList_of(); + } + """); + assertNotInTranslation(subImpl, "fromBoolean"); + } + + public void testAbstractGenericClassWithConcreteMethod_castsAdaptedReturnInSubclass() + throws IOException { + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + + public abstract class AbstractGenericBase { + @ObjectiveCKmpMethod(selector = "getItem:", adapter = TestAdapter.class) + public T getItem(ImmutableList items) { + return null; + } + } + """, + "AbstractGenericBase.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + + public class ConcreteSubFoo extends AbstractGenericBase { + @Override + public SubFoo getItem(ImmutableList items) { + return null; + } + } + """, + "ConcreteSubFoo.java"); + + String baseImpl = translateSourceFile("AbstractGenericBase", "AbstractGenericBase.m"); + assertInTranslation( + baseImpl, + """ + - (Foo *)getItem:(NSArray *)items { + return (Foo *) [self getItemWithComGoogleCommonCollectImmutableList:[TestAdapter toImmutableListWithId:items]]; + } + """); + assertNotInTranslation(baseImpl, "_dispatch"); + + String subImpl = translateSourceFile("ConcreteSubFoo", "ConcreteSubFoo.m"); + assertInTranslation( + subImpl, + """ + - (SubFoo *)getItemWithComGoogleCommonCollectImmutableList:(ComGoogleCommonCollectImmutableList *)items { + if (AbstractGenericBase_isOverride(self, @selector(getItem:))) { + return (SubFoo *) [self getItem:(NSArray *) [TestAdapter fromImmutableListWithComGoogleCommonCollectImmutableList:items]]; + } + return nil; + } + """); + } + + public void testComposableConverterOnSubclass_lowersSynthesizedLambda() throws IOException { + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + public class NestedListBase { + @ObjectiveCKmpMethod(selector = "getNestedItems", adapter = TestAdapter.class) + public List> getNestedItems() { + return null; + } + } + """, + "NestedListBase.java"); + addSourceFile( + """ + import com.google.common.collect.ImmutableList; + import java.util.List; + + public class NestedListSub extends NestedListBase { + @Override + public List> getNestedItems() { + return null; + } + } + """, + "NestedListSub.java"); + + String baseImpl = translateSourceFile("NestedListBase", "NestedListBase.m"); + assertInTranslation( + baseImpl, "if (NestedListBase_isOverride(self, @selector(getNestedItems)))"); + assertInTranslation(baseImpl, "NestedListBase_$KmpLambda$"); + + String subImpl = translateSourceFile("NestedListSub", "NestedListSub.m"); + assertInTranslation(subImpl, "if (NestedListBase_isOverride(self, @selector(getNestedItems)))"); + assertInTranslation(subImpl, "NestedListSub_$KmpLambda$"); + assertInTranslation(subImpl, "return TestAdapter_toImmutableListWithId_(elem);"); + } + + public void testSynchronizedConcreteMethod_prependsOverrideCheckOutsideSynchronizedBlock() + throws IOException { + String impl = + translateSourceFile( + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + public class SyncService { + @ObjectiveCKmpMethod(selector = "fetchItems", adapter = TestAdapter.class) + public synchronized List getItems() { + return null; + } + } + """, + "SyncService", + "SyncService.m"); + + assertInTranslation( + impl, + """ + - (id)getItems { + if (SyncService_isOverride(self, @selector(fetchItems))) { + return [TestAdapter toJavaUtilListWithId:[self fetchItems]]; + } + @synchronized(self) { + return JreRetainedLocalValue(nil); + } + } + """); + } + + public void testNativeConcreteMethods_ocniAndJniPrependOverrideCheck() throws IOException { + String impl = + translateSourceFile( + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.List; + + public class NativeService { + @ObjectiveCKmpMethod(selector = "fetchOcniItems", adapter = TestAdapter.class) + public native List getOcniItems() /*-[ + return nil; + ]-*/; + + @ObjectiveCKmpMethod(selector = "fetchJniItems", adapter = TestAdapter.class) + public native List getJniItems(); + } + """, + "NativeService", + "NativeService.m"); + + assertInTranslation( + impl, + """ + - (id)getOcniItems { + if (NativeService_isOverride(self, @selector(fetchOcniItems))) { + return [TestAdapter toJavaUtilListWithId:[self fetchOcniItems]]; + } + return nil; + } + """); + assertInTranslation( + impl, + """ + - (id)getJniItems { + if (NativeService_isOverride(self, @selector(fetchJniItems))) { + return [TestAdapter toJavaUtilListWithId:[self fetchJniItems]]; + } + return NativeService_getJniItems(self); + } + """); + } + + public void testDeadCodeEliminatedOwnerMethod_stillEmitsOverrideHelperForSubclass() + throws IOException { + addSourceFile( + """ + import com.google.j2objc.annotations.ObjectiveCKmpMethod; + import java.util.Collections; + import java.util.List; + + public abstract class OpenBase { + @ObjectiveCKmpMethod(selector = "getItemsAsNsArray", adapter = TestAdapter.class) + public List getItems() { + return Collections.emptyList(); + } + } + """, + "OpenBase.java"); + addSourceFile( + """ + import java.util.Collections; + import java.util.List; + + public class SubService extends OpenBase { + @Override + public List getItems() { + return Collections.singletonList("sub"); + } + } + """, + "SubService.java"); + setDeadCodeMap( + CodeReferenceMap.builder().addMethod("OpenBase", "getItems", "()Ljava/util/List;").build()); + + String baseHeader = translateSourceFile("OpenBase", "OpenBase.h"); + assertInTranslation( + baseHeader, "FOUNDATION_EXPORT bool OpenBase_isOverride(OpenBase *self, SEL selector);"); + + String baseImpl = translateSourceFile("OpenBase", "OpenBase.m"); + assertInTranslation(baseImpl, "bool OpenBase_isOverride(OpenBase *self, SEL selector)"); + assertNotInTranslation(baseImpl, "- (id)getItems"); + + String subImpl = translateSourceFile("SubService", "SubService.m"); + assertInTranslation(subImpl, "if (OpenBase_isOverride(self, @selector(getItemsAsNsArray)))"); + } +}