Convert LifecycleImpl.finalize() method to LifecycleImpl.dealloc() with @Dealloc annotation. There's no need to break retain-cycles in Java & JavaScript, only in ObjC.

PiperOrigin-RevId: 328493634
diff --git a/annotations/src/main/java/com/google/j2objc/annotations/Dealloc.java b/annotations/src/main/java/com/google/j2objc/annotations/Dealloc.java
new file mode 100644
index 0000000..df5e152
--- /dev/null
+++ b/annotations/src/main/java/com/google/j2objc/annotations/Dealloc.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2012 Google Inc. All Rights Reserved.
+ *
+ * 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.j2objc.annotations;
+
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.CLASS;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+/**
+ * Annotates a method which will be called from "- (void)dealloc" method in the transpiled ObjC
+ * code.
+ *
+ * <p>Annotated method must be private, non-static, return void and have no parameters. If there are
+ * multiple annotated methods, they will be called in declaration order, before calling finalize().
+ *
+ * <p>This annotation is designed to be used in combination with @Weak (which translates to
+ * unsafe_unretained) to break retain-cycles and make sure that there are no dangling pointers in
+ * the transpiled ObjC code. It may involve nullifying @Weak references or removing them from
+ * internal data structures.
+ *
+ * @author Michał Pociecha-Łoś
+ */
+@Target(METHOD)
+@Retention(CLASS)
+public @interface Dealloc {}
diff --git a/translator/src/main/java/com/google/devtools/j2objc/translate/DestructorGenerator.java b/translator/src/main/java/com/google/devtools/j2objc/translate/DestructorGenerator.java
index 403e9c0..d98ab46 100644
--- a/translator/src/main/java/com/google/devtools/j2objc/translate/DestructorGenerator.java
+++ b/translator/src/main/java/com/google/devtools/j2objc/translate/DestructorGenerator.java
@@ -16,6 +16,8 @@
 
 package com.google.devtools.j2objc.translate;
 
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.devtools.j2objc.ast.AbstractTypeDeclaration;
 import com.google.devtools.j2objc.ast.AnnotationTypeDeclaration;
@@ -25,6 +27,7 @@
 import com.google.devtools.j2objc.ast.ExpressionStatement;
 import com.google.devtools.j2objc.ast.FunctionInvocation;
 import com.google.devtools.j2objc.ast.MethodDeclaration;
+import com.google.devtools.j2objc.ast.MethodInvocation;
 import com.google.devtools.j2objc.ast.NativeStatement;
 import com.google.devtools.j2objc.ast.PrefixExpression;
 import com.google.devtools.j2objc.ast.SimpleName;
@@ -40,8 +43,10 @@
 import com.google.devtools.j2objc.types.GeneratedExecutableElement;
 import com.google.devtools.j2objc.types.PointerType;
 import com.google.devtools.j2objc.util.ElementUtil;
+import com.google.devtools.j2objc.util.ErrorUtil;
 import com.google.devtools.j2objc.util.NameTable;
 import com.google.devtools.j2objc.util.TypeUtil;
+import com.google.j2objc.annotations.Dealloc;
 import java.util.List;
 import javax.lang.model.element.ExecutableElement;
 import javax.lang.model.element.Modifier;
@@ -84,7 +89,8 @@
     TypeElement type = node.getTypeElement();
     boolean hasFinalize = hasFinalizeMethod(type);
     List<Statement> releaseStatements = createReleaseStatements(node);
-    if (releaseStatements.isEmpty() && !hasFinalize) {
+    List<MethodDeclaration> deallocMethodDeclarations = getDeallocMethodDeclarations(node);
+    if (releaseStatements.isEmpty() && !hasFinalize && deallocMethodDeclarations.isEmpty()) {
       return;
     }
 
@@ -96,6 +102,12 @@
     Block block = new Block();
     deallocDecl.setBody(block);
     List<Statement> stmts = block.getStatements();
+    for (MethodDeclaration deallocMethodDeclaration : deallocMethodDeclarations) {
+      stmts.add(
+          new ExpressionStatement(
+              new MethodInvocation(
+                  new ExecutablePair(deallocMethodDeclaration.getExecutableElement()), null)));
+    }
     if (hasFinalize) {
       String clsName = nameTable.getFullName(type);
       stmts.add(new NativeStatement("JreCheckFinalize(self, [" + clsName + " class]);"));
@@ -122,6 +134,48 @@
     return hasFinalizeMethod(ElementUtil.getSuperclass(type));
   }
 
+  private static ImmutableList<MethodDeclaration> getDeallocMethodDeclarations(
+      AbstractTypeDeclaration typeDeclaration) {
+    return ImmutableList.copyOf(
+        Iterables.filter(
+            Iterables.transform(
+                typeDeclaration.getBodyDeclarations(),
+                bodyDeclaration -> {
+                  if (!(bodyDeclaration instanceof MethodDeclaration)) {
+                    return null;
+                  }
+
+                  MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
+                  ExecutableElement executableElement = methodDeclaration.getExecutableElement();
+                  if (!ElementUtil.hasAnnotation(executableElement, Dealloc.class)) {
+                    return null;
+                  }
+
+                  if (!executableElement.getModifiers().contains(Modifier.PRIVATE)) {
+                    ErrorUtil.error(methodDeclaration, "@Dealloc method must be private.");
+                    return null;
+                  }
+
+                  if (executableElement.getModifiers().contains(Modifier.STATIC)) {
+                    ErrorUtil.error(methodDeclaration, "@Dealloc method must not be static.");
+                    return null;
+                  }
+
+                  if (!TypeUtil.isVoid(executableElement.getReturnType())) {
+                    ErrorUtil.error(methodDeclaration, "@Dealloc method must be void.");
+                    return null;
+                  }
+
+                  if (!executableElement.getParameters().isEmpty()) {
+                    ErrorUtil.error(methodDeclaration, "@Dealloc method must have no parameters.");
+                    return null;
+                  }
+
+                  return methodDeclaration;
+                }),
+            methodDeclaration -> methodDeclaration != null));
+  }
+
   private List<Statement> createReleaseStatements(AbstractTypeDeclaration node) {
     List<Statement> statements = Lists.newArrayList();
     for (VariableDeclarationFragment fragment : TreeUtil.getAllFields(node)) {
diff --git a/translator/src/test/java/com/google/devtools/j2objc/translate/DestructorGeneratorTest.java b/translator/src/test/java/com/google/devtools/j2objc/translate/DestructorGeneratorTest.java
index 43832cf..30a5172 100644
--- a/translator/src/test/java/com/google/devtools/j2objc/translate/DestructorGeneratorTest.java
+++ b/translator/src/test/java/com/google/devtools/j2objc/translate/DestructorGeneratorTest.java
@@ -18,7 +18,6 @@
 
 import com.google.devtools.j2objc.GenerationTest;
 import com.google.devtools.j2objc.Options;
-
 import java.io.IOException;
 
 /**
@@ -135,4 +134,37 @@
         "  JreCheckFinalize(self, [Test class]);",
         "}");
   }
+
+  static final String DEALLOC_METHODS_SOURCE =
+      "import com.google.j2objc.annotations.Dealloc;"
+          + "class Test {"
+          + "  @Dealloc private void dealloc1() {}"
+          + "  @Dealloc private void dealloc2() {}"
+          + "  protected void finalize() {}"
+          + "}";
+
+  public void testDeallocMethodsReferenceCounting() throws IOException {
+    options.setMemoryManagementOption(Options.MemoryManagementOption.REFERENCE_COUNTING);
+    String translation = translateSourceFile(DEALLOC_METHODS_SOURCE, "Test", "Test.m");
+    assertTranslatedLines(
+        translation,
+        "- (void)dealloc {",
+        "  Test_dealloc1(self);",
+        "  Test_dealloc2(self);",
+        "  JreCheckFinalize(self, [Test class]);",
+        "  [super dealloc];",
+        "}");
+  }
+
+  public void testDeallocMethodsARC() throws IOException {
+    options.setMemoryManagementOption(Options.MemoryManagementOption.ARC);
+    String translation = translateSourceFile(DEALLOC_METHODS_SOURCE, "Test", "Test.m");
+    assertTranslatedLines(
+        translation,
+        "- (void)dealloc {",
+        "  Test_dealloc1(self);",
+        "  Test_dealloc2(self);",
+        "  JreCheckFinalize(self, [Test class]);",
+        "}");
+  }
 }