AST eclipse, adding arguments to a MethodInvocation - java

Im trying to add arguments to the arguments list of a MethodInvocation and it doesnt seem to work, I can remove objects but I cant see to add them.
My end goal is to take 2 MethodInvocation that invoke the same method with different arguments and convert it to 1 MethodInvocation that has a ConditionalExpression as an argument.
Example:
if (A){
System.out.println("hi");
} else {
System.out.println("hey");
}
Will be converted to:
System.out.println((A ? "hi" : "hey"));
So I would also appreciate it if someone knwos how to convert the argument list to 1 big Expression I can place in the ConditionalExpression.
Thanks!
EDIT: sorry forgot to mention is it a code formatting plug-in for ecplise
EDIT2: the code I am trying to run:
final ExpressionStatement thenStmnt=(ExpressionStatement)((Block)node.getThenStatement()).statements().get(0),
elseStmnt=(ExpressionStatement)((Block)node.getElseStatement()).statements().get(0);
MethodInvocation thenMethod=(MethodInvocation)thenStmnt.getExpression(),
elseMethod=(MethodInvocation)elseStmnt.getExpression();
final MethodInvocation method=ast.newMethodInvocation();
method.setName(ast.newSimpleName("add"));
method.arguments().add(0, elseMethod.arguments().get(0));
ast is a given leagal AST and node is a given leagal IfStatement.

Solved, problem was here:
method.arguments().add(0, elseMethod.arguments().get(0));
If you want to take or copy something that is already part of your original code, meaning already exist in the AST you have to use r.createCopyTarget, like so:
method.arguments().add(0, r.createCopyTarget(elseMethod.arguments().get(0)));

Related

Antlr4: Confusing error message (concatenates correct and incorrect lines) for Java grammar

I am trying to build my own parser based on the existing Java grammar.
Even if I use the Java7 grammar from the source repo, generate the parser and use the TestRig from antlr-4.9.3-complete.jar given the code:
1 public class Test {
2 public static void main() {
3 test
4 int b = 1;
5 }
6 }
I get the following error:
line 4:8 no viable alternative at input 'test\n int'
So for some reason it concatenates the incorrect "test" line with correct "int" line.
Also it says "line 4:8" pointing at the "int" line when it should be pointing to "test" (line 3).
(In a regular Java editor I would see a correct error highlighting for the "test" word which would sound like):
"Syntax error, insert "VariableDeclarators" to complete LocalVariableDeclaration"
What do I do to arrive at a similar error with ANTLR so it only picks on the wrong "test" line?
Most likely it's just my misunderstanding how antlr interprets the errors, then how would I get the listener to at least report correctly the starting line?
You can't compare a sophisticated editor/IDE with a parser (generated by ANTLR). A text editor/IDE knows more about the input source and can look up if test is a valid type, and give a meaningful error message if the type cannot be found.
ANTLR's parser rule "sees" test int b as an Identifier, an INT and another Identifier token and cannot match any parser rule for these tokens, resulting in the error starting at the identifier test.
For example, if class test {} was in the classpath, then input without int would be valid:
public class Test {
public static void main() {
test
/*int*/ a = 1;
}
}
It wouldn't compile of course, but the syntax would be correct:

How to allow catchError in Jenkins?

So I fixed one of my organisation's needs by adding a catchError statement in one of their groovy files but in turn this creates a build error with a generic Jenkins test library BasePipelineTest:
[main] ERROR org.apache.maven.plugin.surefire.SurefirePlugin - PipelineTest.testCall_AllFieldsAvailable:71 ? MissingMethod No signature
[main] ERROR org.apache.maven.plugin.surefire.SurefirePlugin - PipelineTest.testCall_FieldsNotAvailable:130 ? MissingMethod No signature
As part of the Jenkins standard BasePipelineTest class the solution for this is typically:
helper.registerAllowedMethod("cleanWs", []) {}
For a method like cleanWs(), or something similar depending on the method and its inputs. However this is for methods with input values, but catchError doesn't have input values, rather it's done like:
catchError {
...
}
So helper.registerAllowedMethod("catchError", []) {} does not work. Does anyone know how to make it work for something like catchError?
I have also attempted:
helper.registerAllowedMethod("catchError", [com.lesfurets.jenkins.unit.catchError]) {}
This creates a MissingProperty error
Turns out the curly brackets themselves register as a class in groovy. I fixed it with:
helper.registerAllowedMethod("catchError", [Closure.class]) {}

Get IMethod from the method name in java

I'm looking for a way to find the IMethod, given the method name as input for developing my eclipse plugin further.
Couldn't figure out a way to do so.
can someone please direct me in the right path.
There can be two approaches:
You can use the ASTVisitor pattern to visit the MethodDeclaration nodes, do a check for name and arguments, and get IMethod from them by resolving the binding. Refer the below posts:
Eclipse create CompilationUnit from .java file
How to convert AST to JDT Java model
Get the ITypes from the compilation unit and loop through the IMethods, do check for name and arguments to find the required one.
IType [] typeDeclarationList = unit.getTypes();
for (IType typeDeclaration : typeDeclarationList) {
// Get methods under each type declaration.
IMethod [] methodList = typeDeclaration.getMethods();
for (IMethod method : methodList) {
// Logic here.
}
}

How to call String[][] in R using rjava

I am preparing an R wrapper for a java code that I didn't write myself (and in fact I don't know java). I am trying to use rJava for the first time and I am struggling to get the .jcall right.
Here is an extract of the java code for which I write a wrapper:
public class Model4R{
[...cut...]
public String[][] runModel(String dir, String initFileName, String[] variableNames, int numSims) throws Exception {
[...cut...]
dir and initFileName are character strings for the directory and file name with initial conditions, variable names is a list of character strings that I would write like this in R: c("var1", "var2", "var3", ...) and can be of length from one to five. Finally, numSim is an integer.
Here is my tentative R code for a wrapper function:
runmodel <- function(dir, inFile, varNames, numSim){
hjw <- .jnew("Model4R")
out <- .jcall(hjw, "[[Ljava/lang/String", "runModel", as.character(dir), as.character(inFile), as.vector(varNames), as.integer(numSim))
return(out)
}
The error in R is:
Error in .jcall(hjw, "[[Ljava/lang/String", "runModel", as.character(dir),
: method runModel with signature (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)[[Ljava/lang/String not found
I suspect that the JNI type isn't correct for String[][]. Anyhow, any help that could direct me towards a solution would be welcome!
You're missing a semicolon at the end of the JNI for String[][] - it should be "[[Ljava/lang/String;". Also, I think you need to call .jarray instead of as.vector on varNames. The R error is telling you that rJava thinks the class of the third argument is Ljava/lang/String; instead of [Ljava/lang/String;.

Mysterious ANTLR error

All I know is that it's stopping antlr from generating, I apologize. Here's the log file:
(10): internal error: /Bridge/bridge.g : java.lang.IllegalStateException: java.lang.NullPointerException
org.deved.antlride.runtime.AntlrErrorListener$DynamicToken.invokeMethod(AntlrErrorListener.java:59)
org.deved.antlride.runtime.AntlrErrorListener$DynamicToken.getLine(AntlrErrorListener.java:64)
org.deved.antlride.runtime.AntlrErrorListener.report(AntlrErrorListener.java:131)
org.deved.antlride.runtime.AntlrErrorListener.message(AntlrErrorListener.java:115)
org.deved.antlride.runtime.AntlrErrorListener.warning(AntlrErrorListener.java:99)
org.antlr.tool.ErrorManager.grammarWarning(ErrorManager.java:742)
org.antlr.tool.ErrorManager.grammarWarning(ErrorManager.java:757) org.antlr.tool.Grammar.parseAndBuildAST(Grammar.java:655)
org.antlr.Tool.getRootGrammar(Tool.java:626) org.antlr.Tool.process(Tool.java:459)
org.deved.antlride.runtime.Tool2.main(Tool2.java:24)
I got the same error with a simple grammar for logical formulas. For me the problem was, that ANTLR could not find an obvious start rule because I had a recursion on my intended start rule. Adding a new rule pointing to the recursive one did the job (see http://thesoftwarelife.blogspot.com/2008/07/antlr-frustrations.html).
It's a pity that ANTLR IDE does not correctly forward the error message. On the command line i get:
warning(138): Formula.g:0:1: grammar Formula: no start rule (no rule can obviously be followed by EOF)
I had the same problem yesterday. Not sure if my case is identical to yours but it worth a try. I had a rule named annotation like this:
annotation
: AT class declaration?
-> ^(ANNOTATION class declaration?)
;
And I wanted to parse sub annotations in curly braces so I did:
subAnnotation:
: CURLY_START annotation CURLY_END
-> ^(ANNOTATION annotation)
;
This was given me the same error has yours. So, I end up wondering with it is not working. Even if I'm unsure, I think the problem is the recursion of the annotation rule that was causing the error. So, I ended up doing this:
annotationValue:
: CURLY_START subAnnotation CURLY_END
-> ^(ANNOTATION subAnnotation)
;
subAnnotation
: AT class declaration?
-> ^(ANNOTATION class declaration?)
;
This resolved my problem. Like I said, I don't know if this fix can be applied to your problem. Moreover, I thought that ANTLR was able to deal with non-left-recursive rule. Maybe someone with a better knowledge of the tool could confirm it.
I must admit I did not try the suggestion of #BartKiers, maybe it would also solve the problem.
Regards,
Matt

Categories

Resources