Generating a method call in code with PSI

Answered

I am working on a plug-in, that should add code to existing code.

How can it be achieved that a method call is added to a Psielement, for example:
Adding the text ".myMethodCall()" to the PsiElement "MyClass", so it becomes : "Myclass.myMethodCall()" ?


I tried adding it as a PsiExpression with addAfter, but that puts it in a new line and deletes the dot-operator.

Ideally, i would like to do this for Groovy-Code, so i will use the Groovy equivalent like for instance GrExpression.

2 comments
Comment actions Permalink

Please see org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory

0
Comment actions Permalink

Thanks Yann,

 

i found a clue in there. Now i must find out what anchor to add this after, currently trying the element at caret (LeafPsiElement), which represents the name of the class the method is supposed to be called in. This still has no dot-operator like this.

PsiElement elementAtCaret = file.findElementAt(editor.getCaretModel().getOffset());
GrMethodCallExpression methodCall = (GrMethodCallExpression) groovyFactory.createExpressionFromText(methodCallText, null);
Runnable r = () -> elementAtCaret.getParent().addAfter(methodCall, elementAtCaret);



It seems like it is required to also include the calling class into the MethodCallExpression, like "MyClass.myCall()". Like that i get the right output, but it makes it difficult, if what i want to chain the method call to is a complex expression by itself, like builder.build().someMethod().myCall(). I was assuming the MethodCallExpression just consists of the actual calling-part(name of the method plus args) that i can hook to whatever was there (under caret)

0

Please sign in to leave a comment.