groovy-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jochen Theodorou <blackd...@gmx.org>
Subject Re: Get reference to enclosing closure
Date Tue, 21 Nov 2017 23:49:09 GMT
On 21.11.2017 21:43, Leonard Brünings wrote:
> Hi Jochen,
> 
> your first suggestion might do the trick and if closures disappear then 
> there will be much more that doesn't work.
> 
> We currently do something like this:
> 
> 
>    public void replaceImplicitThis(Expression invocation) {
>      if (invocation instanceof MethodCallExpression) {
>        MethodCallExpression methodCallExpression = 
> (MethodCallExpression)invocation;
>        if (methodCallExpression.isImplicitThis()) {
> 
>          Expression target = referenceToCurrentClosure();
>          methodCallExpression.setObjectExpression(target);
>        }
>      }
>    }
> 
>    private MethodCallExpression referenceToCurrentClosure() {
>      return new MethodCallExpression(
>        new VariableExpression("this"),
>        new ConstantExpression("each"),
>        new ArgumentListExpression(
>          new PropertyExpression(
>            new 
> ClassExpression(ClassHelper.makeWithoutCaching(Closure.class)),
>            new ConstantExpression("IDENTITY")
>          )
>        )
>      );
>    }
> 
> This looks a similar to your second suggestion.

similar in that both get the current reference, yes.

> Could you give me a hint on how to write a BytecodeExpersion for "ALOAD 
> 0"? Could I just use this in place of the other MethodCallExpression 
> from referenceToCurrentClosure?

You use it in place of referenceToCurrentClosure,yes. Something like

>                         new BytecodeExpression(ClassHelper.CLOSURE) {
>                             public void visit(MethodVisitor mv) {
>                                 mv.visitVarInsn(ALOAD, 0);
>                             }
>                         });

frankly this is using a feature I do not like so much and that is that 
Groovy handles a call on a closure instance the same way as a call from 
within that closure instance (well, not 100% the same, there are 
differences).But in this case you profit from it. Otherwise you would 
need a way to express the implicit this as parameter... Maybe this is 
actually something we should do..

bye Jochen

Mime
View raw message