Skip to content

Add support for @PolyUI Java 8 lambdas to guichecker - #1481

Merged
wmdietl merged 10 commits into
typetools:masterfrom
lazaroclapp:guieffect_lambdas
Dec 20, 2017
Merged

wmdietl merged 10 commits into
typetools:masterfrom
lazaroclapp:guieffect_lambdas

Conversation

@lazaroclapp

@lazaroclapp lazaroclapp commented Aug 29, 2017 •

Copy link
Copy Markdown
Contributor

(with limited inference)

Summary:

We had some Java 7 code annotated with the guieffect checker's type system, and we are in the process of porting said codebase to Java 8. As part of that process, we are converting multiple anonymous classes into lambdas. It is not clear to us whether is possible to annotate lambdas as being @UI when the functional interface is polymorphic on the UI effect types (@PolyUIType class and @PolyUIEffect method). Assuming we are correct on this, we would like to add support for UI-polymorphic lambda arguments, ideally with some degree of inference that doesn't require us to cast to an @UI version of their functional interface at use (e.g. o.m((@UI Action) () -> { ... }) would not be preferred, instead o.m(()->{ do_some_ui_effect() }) should be alright as long as o is @UI).

The test cases of checker/tests/guieffect/Java8Lambdas.java serve as a reasonable documentation of the cases we would like to handle. This patch works for those.

Apologies for the large PR, specially since I wouldn't be surprised to learn this can all be done in a better way, but I thought it better to discuss this over a PoC implementation than just submitting a feature request :) Will be happy to rewrite part or all of this based on feedback. There is a good chance I missed a much easier/cleaner way to do all this, in which case I'd love to hear it!

Inference:

Since GuiEffectVisitor.java visits method invocations before the body of any lambda expression passed as an argument, we actually infer @UI at use and then allow @UIEffect calls in the body of the lambda only if we previously marked the lambda expression as "inferred @UI".

As such, we mark lambdas as being @UI only when:

  1. The corresponding functional interface is an @UIType with an @UIEffect method.

Or:

  1. The corresponding functional interface is an @PolyUIType with an @PolyUIEffect method.
  2. And either:
    2.1. The lambda is being passed as an argument to a method and the formal parameter is annotated @UI.
    2.2. The lambda is being passed as an argument to a method and the formal parameter is annotated @PolyUI and the receiver is already instantiated @UI.
    2.3. Analogous cases to the two above for returning lambdas.
    2.4. The lambda is being assigned to an @UI local.
    2.5. Some client analysis explicitly calls constrainLambdaToUI()

Known bugs in this PR:

Again, this is a work in progress. There are a few important issues with the behavior of the code below, in particular:

  1. It seems this code won't actually read @PolyUI annotations from methods annotated in stubs, no matter what I try. The code in lines 247-277 of GuiEffectVisitor is already way too redundant and it still doesn't handle that case. The call to atypeFactory.methodFromUse(node) finds @UI annotations on stub arguments, but not @PolyUI annotations in actual source files, atypeFactory.getAnnotatedType(formalArgElement) gets either annotation from source but ignores stubs. Neither finds @PolyUI in stubs. I am sure I am doing something wrong there, but not sure what the recommended way of getting that info is.

  2. We are missing some inference for the case in which lambdas are being passed through @PolyUI -> @PolyUI methods. E.g. Assume we have a method @PolyUI Action id(@PolyUI Action), then we have void m(@UI Action). Ideally we would like m(id(id(id(() -> { do_some_ui_effect() }))))to be understood as valid. The simplest solution I can think of here is a traversal on arguments, return expressions and assignment left hand sides, going inside method invocations only when they are (..., @PolyUI,...) -> @PolyUI and marking all the lambdas found in those argument positions as being inferred-@UI. Is there a better way?

@mernst

mernst commented Aug 29, 2017

Copy link
Copy Markdown
Member

@csgordon Could you take a first pass at this, and then call on others for advice/help wherever you need it? Thanks!

@csgordon

Copy link
Copy Markdown
Contributor

First off, thanks for working on this!

Here are some quick thoughts at the end of my evening:

  • At a quick glance the overall approach is reasonable, and you're definitely right that some inference is necessary for lambdas beyond the "well-chosen defaults" approach used up to now.
  • I need to think through the behavior of the inference described above. In particular, I'm wondering about the behavior on lambdas with more non-trivial data flow: fields aren't mentioned above, or appearing nested inside other expressions (e.g., as a result of a ternary operator). I'd rather not merge this until we can predict what the inference will do in any use context (and can document it clearly), even if the fallback of switching to an anonymous inner class is always available.
  • jdk.astub should be updated to mark the java.util.function interfaces as polymorphic (at at least a couple instances of this should be in tests).

I'll spend some more time with this tomorrow morning, going through the code in detail, and looking at the first bug you mention. For the second issue mentioned, I'm trying to think whether in general this can simply be done "outside-in" by always assigning the most permissive effect, but I'll think through it more carefully in the morning.

@lazaroclapp

Copy link
Copy Markdown
Contributor Author

Thanks so much for the quick response! Looking forward to your comments on the code tomorrow. Won't be too surprised if I have to rewrite it entirely, but glad to hear the general approach makes sense to you guys :)

  • I agree that there are some cases this patch doesn't handle yet, such as: fields (did think about them, can be done analogously to local vars, requiring a type use annotation and using that one for inference), lambdas in ternary expressions (honestly hadn't considered them), and lambdas with @PolyUI return type that return polymorphic lambda expressions (I don't think we want to infer anything there, it is a recursive rabbit hole, my suggestion is that if you are returning a lambda from a lambda then at least the outer one better not be @PolyUI). I think having a solid definition for the inference behavior is absolutely a great idea but, additionally, at least for guieffect there is always the option of failing soundly. Basically, a lambda we can't infer as @UI is assumed @AlwaysSafe going into its body, which at least means the inference itself shouldn't be causing us to swallow an error. Knowing how to fail safely is one of the reasons I wrote this at the guieffect checker layer, rather than as a more general change on polymorphic types, but would be happy to revisit that decision if a general desired behavior is clear.
  • I didn't see any tests in guieffect-tests that load stubs. Would be happy to add some if there is a stub for a @PolyUI functional interface that ships or should ship with jdk.astub. Will take a look at that file tomorrow.

@csgordon csgordon left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've taken a first pass at the review. There are a couple things that should be refactored, minor code hygiene issues, and a question about the inference approach.

There are also a couple questions for @mernst @wmdietl

* @return the functional interface method
*/
public static Symbol.MethodSymbol getFunctionalInterfaceMethod(LambdaExpressionTree tree) {
Type funcInterfaceType = ((JCTree.JCLambda) tree).type;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mernst, @wmdietl, it seems like there ought to be a "proper" way to locate the method of interest in a functional method, since the compiler already needs to do this itself. Is there one, and is it accessible from here? I couldn't find an appropriate means after a bit of searching.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is, actually. We found out recently that this can be done through the com.sun.tools.javac.code.Types.findDescriptorSymbol API, updating this PR accordingly.

}

// For assignments and local variable initialization:
// Check for @UI annotations on the lhs, use them to infer @UI types on lambda expressions in the rhs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The inference functionality added in this change should live in the GuiEffectTypeFactory, in particular inside the GuiEffectTreeAnnotator.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good. I took a look into doing that today, particularly in conjunction with doing bottom-up instead of top-down inference. There are two issues I am having with doing that:

  • This means instantiating the @PolyUI effect of every method invocation (inside a @PolyUI lambda) visited by GuiEffectTreeAnnotator, so that we know which effect to propagate up to the lambda expression. Ideally, I would like to move the code from lines 215-235 of GuiEffectVisitor into a new method for GuiEffectTypeFactory that we can call in both places. An obstacle for this is the call to visitorState.getMethodReceiver() in line 224, which provides info I don't know how to get inside the factory.
  • I am actually not sure how to annotate the lambda expression in the tree. Is there a reasonable way to get the AnnotatedTypeMirror of the lambda given just the LambdaExpressionTree or is the idea to keep track of the AnnotatedTypeMirror passed to visitLambdaExpression on the way down and use that inside visitMethodInvocation?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Your first point sounds like a reasonable refactoring. If there's no equivalent visitorState in the TreeAnnotator, though, that is an issue. (For those not carefully perusing the code, @lazaroclapp is proposing to move the code that performs the instantiation of polymorphic effects based on receiver types to a helper method where it could be used by both checking and the TreeAnnotator. The visitor.getMethodReceiver() call retrieves the this type for implicit self-dispatch.) getMethodReceiver() just retrieves state tracked by the BaseTypeVisitor, which originates on the method type of the current method (
    public Void visitMethod(MethodTree node, Void p) {
    , see call to setMethodReceiver). The refactored method could accept the implicit receiver type as an argument, and call sites could pass the result of visitorState.getMethodReceiver() or a separate lookup on the type of the enclosing method as needed.
  • Shouldn't the second parameter to an override of TreeAnnotator.visitLambdaExpression be the corresponding AnnotatedTypeMirror?

return new Effect(SafeEffect.class);
}

public Effect getInferedEffectForLambdaExpression(LambdaExpressionTree lambdaTree) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than keeping a separate set of polymorphic lambdas inferred to be @UI, why not add annotations to the tree? (i.e., add the @UI annotation to the lambda's type). That's what this class (and the TreeAnnotator below) are for. If that's done, then some of the special handling of type checking usage sites of lambdas shouldn't be necessary.

// For assignments and local variable initialization:
// Check for @UI annotations on the lhs, use them to infer @UI types on lambda expressions in the rhs
private void inferLambdaTypeOnAssignment(Tree lhs, ExpressionTree rhs) {
if (rhs instanceof LambdaExpressionTree) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use getKind() instead of instanceof.

// Returning a lambda expression also triggers inference based on the method's return type.
@Override
public Void visitReturn(ReturnTree node, Void p) {
if (node.getExpression() instanceof LambdaExpressionTree) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use getKind() instead of instanceof.

// Field initializers inside anonymous inner classes show up with a null current-method ---
// the traversal goes straight from the class to the initializer.
assert (currentMethods.peek() == null || callerEffect.equals(effStack.peek()));
// Look for lambda arguments and infer them to be @UIEffect for this call

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wary of mixing inference and checking in the same pass (lines 237-280) since we're not doing full effect inference. As I've mentioned elsewhere, the inference work should live in the TypeFactory and TreeAnnotator, updating the tree itself. The separation makes it easier to debug later.

}); // This lambda will be inferred to be safe and thus calling dangerous() is an
// error.
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test cases look good.

// ToDo: Figure out a better way to works in both cases
AnnotatedTypeMirror argTypeFromArgElement =
atypeFactory.getAnnotatedType(formalArgElement);
AnnotatedTypeMirror argTypeFromMFU = typeargs.get(i);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mernst @wmdietl Is this discrepancy @lazaroclapp observed normal? Is there a single way to retrieve the annotations from either the source or stub, or is this a quirk/bug of the CF w.r.t. lambdas?

+ " UI_from_mfu=" + argTypeFromMFU.hasAnnotation(UI.class)
+ " PolyUI_from_mfu=" + argTypeFromMFU.hasAnnotation(PolyUI.class)
+ " UI_from_argElem=" + argTypeFromArgElement.hasAnnotation(UI.class)
+ " PolyUI_from_argElem=" + argTypeFromArgElement.hasAnnotation(PolyUI.class));*/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This top-down inference approach will always be a bit fragile (regarding your comment about many nested applications of the polymorphic identity function). Some depth of nested arguments will remain unannotated when you first visit the outer lambda applications, leading to calling some lambda applications safe when they should be UI. (This is sound, just a little brittle and less expressive than it might be.)

Did you consider moving this after the recursive visitation, so all of the nested subexpressions will already have inference complete? Then the contexts would then have incomplete information instead of the nested parameters, but I'm wondering if this was a choice or the first thing that you tried that worked well on your programs of interest.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am happy to switch to bottom-up. I think it makes a lot of sense. Will rework the code to do that, but see above regarding GuiEffectTreeAnnotator and annotating lambda expressions themselves.

@csgordon

Copy link
Copy Markdown
Contributor

I've also thought some more about this:

Assume we have a method @PolyUI Action id(@PolyUI Action), then we have void m(@UI Action). Ideally we would like m(id(id(id(() -> { do_some_ui_effect() })))) to be understood as valid.

This depends on the receiver qualifier in the calling context. @PolyUI Action id(@PolyUI Action) is really implicitly @PolyUI Action id(@PolyUI Foo this, @PolyUI Action) (see the TreeAnnotator code). So the above example is only valid if the receiver parameter in the calling context is @UI, because the current qualifier instantiation code directly reflects the qualifier into an effect eagerly, without subtyping. Technically an @AlwaysSafe receiver reference should be usable in this way (i.e., implicitly upcast the receiver's qualifier before making the instantiation choice), but isn't because it was not previously required. Making your example work as desired for arbitrary nesting of id calls will require non-trivial, non-local inference. This is actually something I'm planning to do in a generic way (i.e., for arbitrary effect systems) in the next year, but I'm sure you don't want to wait so long (and there's probably something useful we can do in the mean time).

@msridhar

Copy link
Copy Markdown
Contributor

/cc @bennostein who may also be interested / have feedback

@lazaroclapp

Copy link
Copy Markdown
Contributor Author

Regarding the id example. The case we care about the most ourselves is static methods. So, something like:

static <T> @PolyUI Function<T> foo(final @PolyUI Function<T> f);

Which wraps a lambda and performs some checking before/after the lambda runs. Chained calls of these sort of method are indeed a possibility. Would this be simple enough to handle now? We might not need it to work in every case, but at least where the lambda is being passed directly to a chain of invocations, each being the argument to the next.

@csgordon

Copy link
Copy Markdown
Contributor

Interesting. It seems like the static case should already be handled by the Checker Framework's existing support for @PolymorphicQualifier declarations. If it isn't, that's a bug. It's possible that one of the GuiEffectChecker (or Visitor, or ...) overrides masks the default behavior that handles this.

@lazaroclapp

Copy link
Copy Markdown
Contributor Author

So, will take a look at the static @PolyUI->@PolyUI methods case once bottom-up inference is working. However, I seem to be a bit confused about TreeAnnotators. Basically, I am adding the following two methods to GuiEffectTreeAnnotator:

        @Override
        public Void visitMethodInvocation(MethodInvocationTree node, AnnotatedTypeMirror type) {
            System.err.println("Observed call: " + node);
            // [...]
            return super.visitMethodInvocation(node, type);
        }

        @Override
        public Void visitLambdaExpression(LambdaExpressionTree node, AnnotatedTypeMirror type) {
            System.err.println("Observed lambda: " + node + " " + node.getBodyKind());
            // [...]
            return super.visitLambdaExpression(node, type);
        }

Now, in the output I am getting:

   [junit] Observed lambda: (e)->e.repaint() EXPRESSION
    [junit] Observed lambda: (e)->e.repaint() EXPRESSION
    [junit] Observed lambda: (e)->e.repaint() EXPRESSION
    [junit] Observed lambda: (e)->e.dangerous() EXPRESSION
    [junit] Observed lambda: (e)->e.dangerous() EXPRESSION
    [junit] Observed lambda: (e)->e.dangerous() EXPRESSION
    [junit] Observed lambda: (e)->e.repaint() EXPRESSION
    ....

But no sign of the corresponding "Observed call: e.repaint()" or the like. Am I missing something here? Does the visitor not call visitMethodInvocation on callsites inside a lambda expression? As far as I can tell, the traversal is controlled by whatever controls the underlaying TreeVisitor, since there are no calls to visitLambdaExpression other than super.visitLambdaExpression(...) through the checkerframework code.

@csgordon

Copy link
Copy Markdown
Contributor

It seems that I've misunderstood how the TreeAnnotator is actually used by the framework. @wmdietl, @mernst, can you point us to any documentation on how the TreeAnnotator is actually supposed to be used?

You're seeing that behavior because TreeAnnotator does not override the the visitLambdaExpression it inherits from SimpleTreeVisitor. That default implementation simply returns a default value without performing any further visitation. Apparently the "Simple" in the class name is because it's intended to not be recursive, which has me wondering why the Checker Framework is using it as a base class for anything. Subclasses of TreePathScanner (i.e., all the other visitors) do recur. So in the mean time, it seems like the TypeFactory would be the place to put this functionality.

@lazaroclapp

Copy link
Copy Markdown
Contributor Author

So, I can always use the traversal done by GuiEffectVisitor as in the original patch, but move the bulk of the code dealing with annotating and computing the inferred effect of lambdas (going bottom-up rather than top-down) to the GuieEffectTypeFactory. Is this what you mean? (there is also TypeAnnotator but this seems to be doing a traversal over something else).

If the above is roughly correct, then I am still not sure how to persist the type annotations on the lambda expressions themselves, the following code does not suffice:

public void constrainLambdaToUI(LambdaExpressionTree lambdaExpressionTree) {
        System.err.println(this.type(lambdaExpressionTree).getAnnotations()); 
                          // No @UI annotation
        AnnotatedTypeMirror typeMirror = this.type(lambdaExpressionTree);
        typeMirror.addAnnotation(UI.class);
        System.err.println(this.type(lambdaExpressionTree).getAnnotations()); 
                          // Still no @UI annotation
    }

Is there somewhere I need to pass that TypeAnnotationMirror so that it gets picked up the next time someone queries the type of the lambda expression?

@csgordon

csgordon commented Sep 1, 2017

Copy link
Copy Markdown
Contributor

So, I can always use the traversal done by GuiEffectVisitor as in the original patch, but move the bulk of the code dealing with annotating and computing the inferred effect of lambdas (going bottom-up rather than top-down) to the GuieEffectTypeFactory. Is this what you mean?

Yes, that's what I mean.

this.type(lambdaExpressionTree)

This probably isn't the method you want. Its javadocs suggests it explicitly doesn't add any type annotations (https://checkerframework.org/releases/2.1.9/api/org/checkerframework/framework/type/AnnotatedTypeFactory.html#type-com.sun.source.tree.Tree-). Try getAnnotatedType().

@wmdietl wmdietl self-assigned this Sep 1, 2017
@wmdietl

wmdietl commented Sep 1, 2017

Copy link
Copy Markdown
Member

I can look at TreeAnnotators and the whole PR this weekend.

safePolymorphicLambdaRunner.doEither(e -> e.repaint());
// This next two are ok for this patch since the behavior is the same (no report) for lambdas as for annon
// classes. However, shouldn't this be (argument.type.incompatible) just because safePolymorphicLambdaRunner
// is not an @UI PolymorphicLambdaRunner ? Or, failing that (call.invalid.ui) since doEither is @PolyUIEffect ?

@lazaroclapp lazaroclapp Sep 2, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@csgordon @wmdietl : Am I misunderstanding something about how polymorphic qualifiers work here? This doesn't seem to be specific to the lambda inference stuff, but just in general I seem to be able to pass an @UI argument to a @PolyUI formal when the receiver is @AlwaysSafe (see comment above and lines 108-113 below)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re: your comment in the code: The effect of invoking safePolymorphicLambdaRunner.doEither should be (and seems to be) @SafeEffect.

It ought to be argument.type.incompatible as you suggest, but if that lambda is annotated with both @UI and @AlwaysSafe, that indicates a bug somewhere, as that pairing shouldn't be possible. With that as the stated type, though, it's possible the framework's @PolymorphicQualifier support does something funny with the bad input. @wmdietl do you know what the @PolymorphicQualifier instantiation code would do with an argument that had multiple qualifiers attached to it?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, I wrote this before I figured out the issue with doing bottom-up inference on the tail-end of checking, so this is probably also the same root cause --- the super call on the method invocation occurs before the lambda is inferred to be @UI, so the framework does subtyping check with an assumed @AlwaysSafe on the lambda. As with the others, the ideal fix is to find out the proper way to do inference in a separate pass before checking.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one is still assumed safe. But that seems to be the same behavior as for anonymous classes. Is the lack of error in line 108 expected, for example? (that one is not a lambda and I am adding no annotations there)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The short version is it's wrong, but it's my fault, not yours. I'm working on a clean bug report.

uiPolymorphicLambdaRunner.doEither(e -> e.dangerous());
PolymorphicFunctionalInterface<UIElement> func1 = e -> e.repaint();
// No error, why? //:: error: (assignment.type.incompatible)
PolymorphicFunctionalInterface<UIElement> func2 = e -> e.dangerous(); // Incompatible types!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test case should be failing, and I don't get why it isn't.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect this is related to bottom-up inference, and in hindsight I should have predicted this.

Bottom up inference lets us infer more lambdas' types correctly. But, the checking that would have issued the assignment.type.incompatible occurs in the call to super.visitMethodInvocation(node, p), which is executed before you do the bottom-up inference of that call site. So when the inherited method invocation checks are performed, the Checker Framework is still working only with the default @AlwaysSafe.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doing a separate pass for inference before any checking occurs (which was the intent of my initial suggestion to put inference in the TreeAnnotator) would have the inferred @UI qualifiers in place before the subtyping checks run for passing actual parameters. So when we find out what the proper solution is for separating inference in an earlier pass, that should fix these.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure this is the true issue here.

I built a different version of this PR just now, which uses my own SourceVisitor to recursively annotate the lambdas (called from GuiEffectVisitor.processClassTree for every top level class). The results are exactly the same in terms of the test cases. Note that this version of the PR duplicates a fair amount of the checking code for assignments, method invocations and return after the recursive super.visitX calls.

Moving the inference to its own traversal does indeed make the code cleaner (requiring less duplicated checks), but there is a performance cost that I am not sure we want to pay to do it that way, particularly if the behavior is equivalent. Here is the diff between this PR and that alternative approach, in case it proves useful for the discussion: lazaroclapp@2df0400

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I spent a while poking around the superclasses; as far as I can tell your getAnnotatedType override should be called.

This could still be a consequence of having multiple annotations on the type. If I try to compile the following:

import org.checkerframework.checker.guieffect.qual.*;

public class Blah {


    public @UI @AlwaysSafe Object o;

    public void m(@AlwaysSafe Object o) {
    }

    public void x() {
        m(o);
    }
}

I see the following complaints:

Blah.java:6: error: [type.invalid] [@AlwaysSafe, @UI] may not be applied to the type "@AlwaysSafe @UI Object"
    public @UI @AlwaysSafe Object o;
                                  ^
Blah.java:12: error: [type.invalid] [@AlwaysSafe, @UI] may not be applied to the type "@AlwaysSafe @UI Object"
        m(o);
          ^
2 errors

So blindly tacking on the @UI is probably breaking some sort of invariant --- @wmdietl would know for sure.

Have you tried explicitly removing the @AlwaysSafe from the underlying annotated type mirror in your override's lambda handling?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is absolutely right! Sorry about that. I just replaced the blind addAnnotation call with replaceAnnotation and now I seem to be getting exactly the same behavior as for anonymous classes. Not to say there aren't still a few issues with this patch (namely persisting the set of UI lambdas on the side), but it looks to me that it at least behaves correctly now. Thanks!


// This should be an error without an @UI annotation on the return type. No?
public PolymorphicFunctionalInterface<UIElement> returnLambdasTest2() {
// No error, why? :: error: (return.type.incompatible)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another test that should be failing.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would also be explained by the super.visitX invocation preceding the inference of the lambda inference, because again that's where the subtyping checks to generate that error would occur.

@lazaroclapp

Copy link
Copy Markdown
Contributor Author

Updating this PR in advance of @wmdietl taking a look (thanks so much!). It is now doing bottom-up inference and reusing as much checkerframework code as I could figure out. However, it still uses GuiEffectVisitor for the traversal and keeps track of the @UI lambdas on the side.

On my end, what I would love to figure out is:

  • How to add (and persist) an @UI type annotation on the lambda expressions, with the caveat that we can only determine that type after looking at (visiting) all the method invocations within the lambda.
  • There are three test cases that fail now, compared to the original PR. I am not sure the reason, one of them seems to have the same behavior with anonymous classes as with lambdas, so it might be a misunderstanding on my part.

On a more minor note: I haven't figured out how to get if an argument to a method was declared at @PolyUI. getDeclAnnotations(methodElt.getParameters().get(0)) doesn't do what I want, and every other thing I tried either ignores stubs or gives me the type after it has been instantiated to @AlwaysSafe by the framework, based on knowledge before the lambda inference. That said, I am now using commonAssignmentCheck to check the types, and I am not sure I need to get these annotations directly anymore.

Void result = super.visitReturn(node, p);
/*if (node.getExpression() != null && TreeUtils.enclosingClass(getCurrentPath()).toString().contains("Java8"))
System.err.println(TreeUtils.enclosingMethodOrLambda(getCurrentPath()) + " returns: " + node.getExpression() + " with type " +
atypeFactory.getAnnotatedType(node.getExpression()));*/

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code above, when uncommented, shows that for Java8Lambdas.returnLambdasTest2, the checker indeed knows the type of the formal is @AlwaysSafe and the actual parameter is @AlwaysSafe @UI, but lambdaAssignmentCheck (and, by extension, commonAssignmentCheck) fails to report an error.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AlwaysSafe @UI T isn't a valid type for any T. Something ought to be complaining, unless you're explicitly adding one of those qualifiers.

return new ListTreeAnnotator(super.createTreeAnnotator(), new GuiEffectTreeAnnotator());
}

public void constrainLambdaToUI(LambdaExpressionTree lambdaExpressionTree) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the commented code below not supposed to persist the type for that Tree node?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the same problem with your abuse of AnnotatedExecutableTypes. Adding an annotation to an AET never had any effect. I recently changed this to raise an assertion error, to guard against this misunderstanding.
In b69a425
I commented out dead code in the GUI Checker that also mis-used this.

this.env = env;
if (trees == null) {
trees = Trees.instance(env);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ignore this. Not sure why rebasing didn't get rid of it, will fix it before final PR.

@lazaroclapp

Copy link
Copy Markdown
Contributor Author

Any update on this or #1516 ? We have some working version of these patches internally, but we would still like some feedback on them, and to eventually have them be part of mainline checker-framework :)

@lazaroclapp

Copy link
Copy Markdown
Contributor Author

Rebased this by pulling, and switched our custom code to get the functional interface method of a lambda with a better solution which uses Types.findDescriptorSymbol.

Some of the questions about the code in comments remain, as there should still probably be a better way to do all of this (particularly, some way to persist the inferred types without having a map on the side). We have been using this patch internally for a while, but we would still very much appreciate a careful review of all of this :)

@msridhar

msridhar commented Nov 4, 2017

Copy link
Copy Markdown
Contributor

@csgordon have your concerns about this PR been addressed sufficiently?

@lazaroclapp

Copy link
Copy Markdown
Contributor Author

Hey, @wmdietl, thanks again for looking at this! Modulo the comment above about replaceAnnotation, I think I have incorporated your feedback. Please let me know if I missed something or if there are any further issues.

What do you guys think? Is this now a reasonable patch to make to the guieffect checker until #979 is ready? (cc: @csgordon ?)

@wmdietl

wmdietl commented Dec 8, 2017

Copy link
Copy Markdown
Member

@lazaroclapp Can you try after updating from master to see whether your uses of replaceAnnotation work? They seem unusual to me, as an AnnotatedExecutableType doesn't take any type annotations.

@csgordon Can you do another pass and see whether all your review comments were addressed?

@lazaroclapp

lazaroclapp commented Dec 8, 2017 •

Copy link
Copy Markdown
Contributor Author

@wmdietl I just pulled the latest master and the replaceAnnotation code still works. Like I said before, I don't think it persist the new annotation anywhere permanent, but it does add it to the typeMirror variable being returned, and that's the behavior we are relying on. Let me know if you can think of cleaner or more robust way to do this, though. We are open to suggestions.

@wmdietl wmdietl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some more comments to address. Afterwards I'm fine with merging.
@csgordon are you fine with merging this? Or do you have an ETA on a re-review?


protected final boolean debugSpew;

protected final Set<LambdaExpressionTree> uiLambdas = new HashSet<LambdaExpressionTree>();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some javadoc might be useful.

}

/**
* Get the effect of a method call at its callsite, acknowledging polimorphic instantiation

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

polimorphic -> polymorphic

}
srcType = callerReceiver;
} else {
throw new AssertionError("Unexpected getMethodSelect() kind at callsite " + node);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ErrorReporter.errorAbort( would give a nicer error if this ever happened.

callerEffect =
atypeFactory.getInferedEffectForLambdaExpression(
(LambdaExpressionTree) callerTree);
assert callerEffect.isUI();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why perform the computation if you already know the answer?

List<AnnotatedTypeMirror> argsTypes =
AnnotatedTypes.expandVarArgs(atypeFactory, invokedMethod, node.getArguments());
for (int i = 0; i < args.size(); ++i) {
if (args.get(i) instanceof LambdaExpressionTree) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use getKind() like in the other cases.

}

/**
* finds the corresponding functional interface method for a lambda expression

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the difference to findFunction above? The description and implementation look very similar.

@csgordon

Copy link
Copy Markdown
Contributor

Once the comments from @wmdietl are addressed, I'm onboard with merging.

@lazaroclapp

Copy link
Copy Markdown
Contributor Author

Awesome. I just rebased, and I believe I addressed the final round of comments!

@lazaroclapp lazaroclapp changed the title [WIP] Add support for @PolyUI Java 8 lambdas to guichecker Add support for @PolyUI Java 8 lambdas to guichecker Dec 19, 2017
@wmdietl wmdietl assigned smillst and unassigned lazaroclapp and csgordon Dec 20, 2017
@wmdietl

wmdietl commented Dec 20, 2017

Copy link
Copy Markdown
Member

@smillst Is it good to merge this today?

@smillst

smillst commented Dec 20, 2017

Copy link
Copy Markdown
Member

@wmdietl You can merge when you think it's ready. (FYI Travis is failing on typetools/checker-framework, but it seems to be a Travis issue rather than a problem with our code.)

@wmdietl
wmdietl merged commit cd30fc0 into typetools:master Dec 20, 2017
@wmdietl

wmdietl commented Dec 20, 2017

Copy link
Copy Markdown
Member

@smillst Ok, I've squashed and merged. Travis for the last commit was green, so it shouldn't make master worse.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants