Apply library models to functional interface checks

Assisted-by: Codex (gpt-6)
diff --git a/nullaway/src/main/java/com/uber/nullaway/NullAway.java b/nullaway/src/main/java/com/uber/nullaway/NullAway.java
index bd8f769..22058e8 100644
--- a/nullaway/src/main/java/com/uber/nullaway/NullAway.java
+++ b/nullaway/src/main/java/com/uber/nullaway/NullAway.java
@@ -966,7 +966,7 @@
    * @param resolvedReference the shared method-reference resolution, or {@code null} for an
    *     ordinary override, lambda, or unsupported reference
    * @param modeledOverriddenMethodType overridden method type after substitution and application of
-   *     library models, for a regular override in JSpecify mode; otherwise {@code null}
+   *     library models in JSpecify mode; otherwise {@code null}
    * @param state visitor state
    * @param overridingMethod if available, the symbol for the overriding method
    * @return discovered error, or {@link Description#NO_MATCH} if no error
@@ -1512,10 +1512,13 @@
     // we update the environment mapping before running any handlers, as some handlers
     // (like Rx nullability) run dataflow analysis
     updateEnvironmentMapping(state.getPath(), state);
+    Type.MethodType modeledFunctionalInterfaceMethodType = null;
     if (config.isJSpecifyMode()) {
       genericsChecks.maybeStoreLibraryModeledPolyExpressionType(tree, state);
+      modeledFunctionalInterfaceMethodType =
+          genericsChecks.getModeledFunctionalInterfaceMethodType(tree, state);
       genericsChecks.checkTypeParameterNullnessForExplicitLambdaParameters(
-          tree, funcInterfaceMethod, state);
+          tree, funcInterfaceMethod, modeledFunctionalInterfaceMethodType, state);
     }
     handler.onMatchLambdaExpression(
         tree, new MethodAnalysisContext(this, state, funcInterfaceMethod));
@@ -1529,7 +1532,7 @@
             tree,
             /* memberReferenceTree= */ null,
             /* resolvedReference= */ null,
-            /* modeledOverriddenMethodType= */ null,
+            modeledFunctionalInterfaceMethodType,
             state,
             /* overridingMethod= */ null);
     if (!description.equals(Description.NO_MATCH)) {
@@ -1581,7 +1584,7 @@
    * @param overriddenMethod method being overridden
    * @param overridingMethod overriding method
    * @param modeledOverriddenMethodType overridden method type after substitution and application of
-   *     library models, for a regular override in JSpecify mode; otherwise {@code null}
+   *     library models in JSpecify mode; otherwise {@code null}
    * @param memberReferenceTree if override is via a method reference, the relevant {@link
    *     MemberReferenceTree}; otherwise {@code null}
    * @param state visitor state.
@@ -1600,6 +1603,9 @@
         resolvedReference =
             genericsChecks.resolveMemberReference(
                 memberReferenceTree, overridingMethod, functionalInterfaceType, state);
+        if (config.isJSpecifyMode() && resolvedReference != null) {
+          modeledOverriddenMethodType = resolvedReference.functionalInterfaceMethodType();
+        }
       }
     }
     if (config.isJSpecifyMode()
diff --git a/nullaway/src/main/java/com/uber/nullaway/ResolvedMethodReference.java b/nullaway/src/main/java/com/uber/nullaway/ResolvedMethodReference.java
index 0611ca1..a0b8aeb 100644
--- a/nullaway/src/main/java/com/uber/nullaway/ResolvedMethodReference.java
+++ b/nullaway/src/main/java/com/uber/nullaway/ResolvedMethodReference.java
@@ -16,7 +16,8 @@
  *     references, outside JSpecify mode, or when unavailable
  * @param functionalInterfaceMethod the symbol of the target functional interface's abstract method
  * @param functionalInterfaceMethodType the functional interface method's type as a member of the
- *     ground target type in JSpecify mode, or its declared type otherwise
+ *     ground target type with library models applied in JSpecify mode, or its declared type
+ *     otherwise
  * @param isUnbound whether the first functional interface parameter supplies the instance receiver,
  *     as in {@code String::length}
  * @param returnNullnessHint the return-nullness refinement from handlers or the core {@code
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
index 2ebbab3..fa8f60f 100644
--- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
@@ -40,7 +40,6 @@
 import com.sun.tools.javac.code.Symbol;
 import com.sun.tools.javac.code.Symtab;
 import com.sun.tools.javac.code.Type;
-import com.sun.tools.javac.code.Types;
 import com.sun.tools.javac.tree.JCTree;
 import com.sun.tools.javac.tree.TreeInfo;
 import com.sun.tools.javac.util.Name;
@@ -200,7 +199,7 @@
   }
 
   /**
-   * Returns the substituted functional-interface method type of a lambda or method reference.
+   * Returns the substituted, modeled functional-interface method type for nested return checking.
    *
    * @param polyExpressionTree lambda or method-reference tree
    * @param state visitor state
@@ -210,7 +209,6 @@
   @SuppressWarnings("ReferenceEquality") // locate the existing path to the expression
   public Type.@Nullable MethodType getFunctionalInterfaceMethodType(
       ExpressionTree polyExpressionTree, VisitorState state) {
-    Type functionalInterfaceType = getPolyExpressionType(polyExpressionTree);
     TreePath expressionPath = state.getPath();
     while (expressionPath != null && expressionPath.getLeaf() != polyExpressionTree) {
       expressionPath = expressionPath.getParentPath();
@@ -227,10 +225,23 @@
       // inference solution, but only the outer call's direct arguments have cached poly types.
       return null;
     }
+    return getModeledFunctionalInterfaceMethodType(polyExpressionTree, state);
+  }
+
+  /**
+   * Returns the functional-interface method type after substitution and library modeling.
+   *
+   * @param polyExpressionTree lambda or method reference
+   * @param state visitor state
+   * @return the modeled method type, or {@code null} if the target is unavailable or raw
+   */
+  public Type.@Nullable MethodType getModeledFunctionalInterfaceMethodType(
+      ExpressionTree polyExpressionTree, VisitorState state) {
+    Type functionalInterfaceType = getPolyExpressionType(polyExpressionTree);
     if (functionalInterfaceType == null || functionalInterfaceType.isRaw()) {
       return null;
     }
-    return getFunctionalInterfaceMethodType(
+    return getModeledFunctionalInterfaceMethodType(
         NullabilityUtil.getFunctionalInterfaceMethod(polyExpressionTree, state.getTypes()),
         functionalInterfaceType,
         state);
@@ -1135,15 +1146,11 @@
               VariableTree param = params.get(i);
               Symbol paramSymbol = ASTHelpers.getSymbol(param);
               if (paramSymbol != null && paramSymbol.equals(symbol)) {
-                // get the type of the functional interface method as a member of the inferred type
-                // of the lambda
-                Types types = state.getTypes();
-                var fiMethodType =
-                    TypeSubstitutionUtils.memberType(
-                        types,
+                Type.MethodType fiMethodType =
+                    getModeledFunctionalInterfaceMethodType(
+                        NullabilityUtil.getFunctionalInterfaceMethod(lambdaTree, state.getTypes()),
                         inferredLambdaType,
-                        NullabilityUtil.getFunctionalInterfaceMethod(lambdaTree, types),
-                        config);
+                        state);
                 return fiMethodType.getParameterTypes().get(i);
               }
             }
@@ -2133,7 +2140,7 @@
         NullabilityUtil.getFunctionalInterfaceMethod(memberReferenceTree, state.getTypes());
     Type.MethodType functionalInterfaceMethodType =
         config.isJSpecifyMode()
-            ? getFunctionalInterfaceMethodType(
+            ? getModeledFunctionalInterfaceMethodType(
                 functionalInterfaceMethod,
                 GenericsUtils.groundTargetType(targetType, state, config, handler),
                 state)
@@ -2232,7 +2239,8 @@
 
   /**
    * Gets a functional interface method's type as a member of the ground target type, preserving
-   * nullness when substituting type arguments. Only suitable for use in JSpecify mode.
+   * nullness when substituting type arguments and applying library models. Only suitable for use in
+   * JSpecify mode.
    *
    * @param functionalInterfaceMethod the functional interface method
    * @param targetType the method reference's ground target type from javac attribution, with any
@@ -2240,12 +2248,14 @@
    * @param state the current visitor state
    * @return the functional interface method type as a member of the ground target type
    */
-  private Type.MethodType getFunctionalInterfaceMethodType(
+  private Type.MethodType getModeledFunctionalInterfaceMethodType(
       Symbol.MethodSymbol functionalInterfaceMethod, Type targetType, VisitorState state) {
     verify(config.isJSpecifyMode(), "Method only suitable for use in JSpecify mode");
-    return TypeSubstitutionUtils.memberType(
-            state.getTypes(), targetType, functionalInterfaceMethod, config)
-        .asMethodType();
+    Type.MethodType methodType =
+        TypeSubstitutionUtils.memberType(
+                state.getTypes(), targetType, functionalInterfaceMethod, config)
+            .asMethodType();
+    return handler.onOverrideMethodType(functionalInterfaceMethod, methodType, state, null);
   }
 
   /**
@@ -3188,26 +3198,22 @@
    *
    * @param tree the lambda
    * @param fiMethod the functional interface method the lambda implements
+   * @param fiMethodType its substituted, modeled type, or {@code null} for a raw target
    * @param state the visitor state
    */
   public void checkTypeParameterNullnessForExplicitLambdaParameters(
-      LambdaExpressionTree tree, Symbol.MethodSymbol fiMethod, VisitorState state) {
+      LambdaExpressionTree tree,
+      Symbol.MethodSymbol fiMethod,
+      Type.@Nullable MethodType fiMethodType,
+      VisitorState state) {
     if (((JCTree.JCLambda) tree).paramKind != JCTree.JCLambda.ParameterKind.EXPLICIT
         || CodeAnnotationInfo.instance(state.context)
             .isSymbolUnannotated(fiMethod, config, handler)) {
       return;
     }
-    Type targetType = typeOrNullIfRawNonArray(getPolyExpressionType(tree));
-    if (targetType == null) {
+    if (fiMethodType == null) {
       return;
     }
-    Type.MethodType fiMethodType =
-        handler.onOverrideMethodType(
-            fiMethod,
-            TypeSubstitutionUtils.memberType(state.getTypes(), targetType, fiMethod, config)
-                .asMethodType(),
-            state,
-            null);
     List<? extends VariableTree> parameters = tree.getParameters();
     List<Type> fiParameterTypes = fiMethodType.getParameterTypes();
     for (int i = 0; i < parameters.size(); i++) {
diff --git a/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java
index ea8a80b..9351253 100644
--- a/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java
+++ b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java
@@ -548,6 +548,72 @@
   }
 
   @Test
+  public void invocationHandlerLambdaUsesJSpecifyModel() {
+    makeHelper()
+        .addSourceLines(
+            "Test.java",
+            """
+            import java.lang.reflect.InvocationHandler;
+            import java.lang.reflect.Method;
+            import org.jspecify.annotations.NullMarked;
+            import org.jspecify.annotations.Nullable;
+            @NullMarked
+            class Test {
+              void test() {
+                InvocationHandler topLevelMismatch =
+                    // BUG: Diagnostic contains: parameter args is @NonNull
+                    (Object proxy, Method method, Object[] args) -> null;
+                InvocationHandler handler =
+                    // BUG: Diagnostic contains: mismatched type parameter nullability
+                    (Object proxy, Method method, Object @Nullable [] args) -> null;
+                InvocationHandler safe =
+                    (Object proxy, Method method, @Nullable Object @Nullable [] args) -> null;
+              }
+            }
+            """)
+        .doTest();
+  }
+
+  @Test
+  public void invocationHandlerMethodReferenceUsesJSpecifyModel() {
+    makeHelper()
+        .addSourceLines(
+            "Test.java",
+            """
+            import java.lang.reflect.InvocationHandler;
+            import java.lang.reflect.Method;
+            import org.jspecify.annotations.NullMarked;
+            import org.jspecify.annotations.Nullable;
+            @NullMarked
+            class Test {
+              void test() {
+                // BUG: Diagnostic contains: parameter args of referenced method is @NonNull
+                InvocationHandler topLevelMismatch = Test::handleTopLevelMismatch;
+                // BUG: Diagnostic contains: mismatched type parameter nullability
+                InvocationHandler handler = Test::handle;
+                InvocationHandler safe = Test::handleSafe;
+              }
+
+              static @Nullable Object handleTopLevelMismatch(
+                  Object proxy, Method method, Object[] args) {
+                return null;
+              }
+
+              static @Nullable Object handle(
+                  Object proxy, Method method, Object @Nullable [] args) {
+                return null;
+              }
+
+              static @Nullable Object handleSafe(
+                  Object proxy, Method method, @Nullable Object @Nullable [] args) {
+                return null;
+              }
+            }
+            """)
+        .doTest();
+  }
+
+  @Test
   public void modeledMethodTypeVariableBoundUsedForOverride() {
     makeHelper()
         .addSourceLines(