Repository navigation
Add support for @PolyUI Java 8 lambdas to guichecker - #1481
Conversation
|
@csgordon Could you take a first pass at this, and then call on others for advice/help wherever you need it? Thanks! |
|
First off, thanks for working on this! Here are some quick thoughts at the end of my evening:
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. |
|
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 :)
|
| * @return the functional interface method | ||
| */ | ||
| public static Symbol.MethodSymbol getFunctionalInterfaceMethod(LambdaExpressionTree tree) { | ||
| Type funcInterfaceType = ((JCTree.JCLambda) tree).type; |
There was a problem hiding this comment.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
The inference functionality added in this change should live in the GuiEffectTypeFactory, in particular inside the GuiEffectTreeAnnotator.
There was a problem hiding this comment.
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
@PolyUIeffect of every method invocation (inside a@PolyUIlambda) visited byGuiEffectTreeAnnotator, 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 ofGuiEffectVisitorinto a new method forGuiEffectTypeFactorythat we can call in both places. An obstacle for this is the call tovisitorState.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
AnnotatedTypeMirrorof the lambda given just theLambdaExpressionTreeor is the idea to keep track of theAnnotatedTypeMirrorpassed tovisitLambdaExpressionon the way down and use that insidevisitMethodInvocation?
There was a problem hiding this comment.
- Your first point sounds like a reasonable refactoring. If there's no equivalent
visitorStatein 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. Thevisitor.getMethodReceiver()call retrieves thethistype for implicit self-dispatch.)getMethodReceiver()just retrieves state tracked by theBaseTypeVisitor, which originates on the method type of the current method (, see call tosetMethodReceiver). The refactored method could accept the implicit receiver type as an argument, and call sites could pass the result ofvisitorState.getMethodReceiver()or a separate lookup on the type of the enclosing method as needed. - Shouldn't the second parameter to an override of
TreeAnnotator.visitLambdaExpressionbe the correspondingAnnotatedTypeMirror?
| return new Effect(SafeEffect.class); | ||
| } | ||
|
|
||
| public Effect getInferedEffectForLambdaExpression(LambdaExpressionTree lambdaTree) { |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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. | ||
| } | ||
| } |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
@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));*/ |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
I've also thought some more about this:
This depends on the receiver qualifier in the calling context. |
|
/cc @bennostein who may also be interested / have feedback |
|
Regarding the
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. |
|
Interesting. It seems like the static case should already be handled by the Checker Framework's existing support for |
|
So, will take a look at the static Now, in the output I am getting: But no sign of the corresponding "Observed call: e.repaint()" or the like. Am I missing something here? Does the visitor not call |
|
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 |
|
So, I can always use the traversal done by 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: Is there somewhere I need to pass that |
Yes, that's what I mean.
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 |
|
I can look at TreeAnnotators and the whole PR this weekend. |
f495666 to
2c23125
Compare
| 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 ? |
There was a problem hiding this comment.
@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)
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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! |
There was a problem hiding this comment.
This test case should be failing, and I don't get why it isn't.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Another test that should be failing.
There was a problem hiding this comment.
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.
|
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 On my end, what I would love to figure out is:
On a more minor note: I haven't figured out how to get if an argument to a method was declared at |
| 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()));*/ |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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) { |
There was a problem hiding this comment.
Is the commented code below not supposed to persist the type for that Tree node?
There was a problem hiding this comment.
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); | ||
| } |
There was a problem hiding this comment.
Ignore this. Not sure why rebasing didn't get rid of it, will fix it before final PR.
2c23125 to
bcba4a5
Compare
c3b5797 to
04f2112
Compare
|
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 :) |
702c88e to
1d7a778
Compare
|
Rebased this by pulling, and switched our custom code to get the functional interface method of a lambda with a better solution which uses 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 :) |
|
@csgordon have your concerns about this PR been addressed sufficiently? |
34a6e65 to
8c9f25b
Compare
|
Hey, @wmdietl, thanks again for looking at this! Modulo the comment above about What do you guys think? Is this now a reasonable patch to make to the guieffect checker until #979 is ready? (cc: @csgordon ?) |
|
@lazaroclapp Can you try after updating from master to see whether your uses of @csgordon Can you do another pass and see whether all your review comments were addressed? |
4d0ea4e to
45f28c3
Compare
|
@wmdietl I just pulled the latest master and the |
|
|
||
| protected final boolean debugSpew; | ||
|
|
||
| protected final Set<LambdaExpressionTree> uiLambdas = new HashSet<LambdaExpressionTree>(); |
| } | ||
|
|
||
| /** | ||
| * Get the effect of a method call at its callsite, acknowledging polimorphic instantiation |
| } | ||
| srcType = callerReceiver; | ||
| } else { | ||
| throw new AssertionError("Unexpected getMethodSelect() kind at callsite " + node); |
There was a problem hiding this comment.
ErrorReporter.errorAbort( would give a nicer error if this ever happened.
| callerEffect = | ||
| atypeFactory.getInferedEffectForLambdaExpression( | ||
| (LambdaExpressionTree) callerTree); | ||
| assert callerEffect.isUI(); |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
Use getKind() like in the other cases.
| } | ||
|
|
||
| /** | ||
| * finds the corresponding functional interface method for a lambda expression |
There was a problem hiding this comment.
What is the difference to findFunction above? The description and implementation look very similar.
…ted inference.
This replaces potentially buggy custom logic.
|
Once the comments from @wmdietl are addressed, I'm onboard with merging. |
45f28c3 to
fea684f
Compare
|
Awesome. I just rebased, and I believe I addressed the final round of comments! |
|
@smillst Is it good to merge this today? |
|
@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.) |
|
@smillst Ok, I've squashed and merged. Travis for the last commit was green, so it shouldn't make master worse. |
(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
@UIwhen the functional interface is polymorphic on the UI effect types (@PolyUITypeclass and@PolyUIEffectmethod). 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@UIversion of their functional interface at use (e.g.o.m((@UI Action) () -> { ... })would not be preferred, insteado.m(()->{ do_some_ui_effect() })should be alright as long as o is@UI).The test cases of
checker/tests/guieffect/Java8Lambdas.javaserve 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.javavisits method invocations before the body of any lambda expression passed as an argument, we actually infer@UIat use and then allow@UIEffectcalls in the body of the lambda only if we previously marked the lambda expression as "inferred@UI".As such, we mark lambdas as being
@UIonly when:@UITypewith an@UIEffectmethod.Or:
@PolyUITypewith an@PolyUIEffectmethod.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
@PolyUIand 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
@UIlocal.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:
It seems this code won't actually read
@PolyUIannotations from methods annotated in stubs, no matter what I try. The code in lines 247-277 ofGuiEffectVisitoris already way too redundant and it still doesn't handle that case. The call toatypeFactory.methodFromUse(node)finds@UIannotations on stub arguments, but not@PolyUIannotations in actual source files,atypeFactory.getAnnotatedType(formalArgElement)gets either annotation from source but ignores stubs. Neither finds@PolyUIin stubs. I am sure I am doing something wrong there, but not sure what the recommended way of getting that info is.We are missing some inference for the case in which lambdas are being passed through
@PolyUI -> @PolyUImethods. E.g. Assume we have a method@PolyUI Action id(@PolyUI Action), then we havevoid m(@UI Action). Ideally we would likem(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,...) -> @PolyUIand marking all the lambdas found in those argument positions as being inferred-@UI. Is there a better way?