It's continuous of my previous question: How to parse a for-loop using Javaparser?. I'm trying to parse this incorrect for-loop: FOR(j, k, 15, >, -);
to the correct form: for (var j = k; j > 15; j--){}
. It means to parse Class.java to the class ClassAltered.java. My code should create the new class ClassAltered.java with the correct loop-for. Now my method to parse the for-loop is commented (I haven't finished it), but anyway I have the same error.
I'm sure that javaparser could parse incorrect statements, but I have problems with the sights ">", "<=", "+", "-". If I delete this sights everything works.
I use javaparser-core-3.1.0.jar
Here is my error:
Here is my Class.java which I want to parse:
public class Class {
public static void main(String[] args) {
method1();
method2();
}
public static void method1() {
FOR(j, k, 15, >, -);
System.out.println("FOR(j, k, 15, >, -) test");
}
public static void method2() {
FOR(j, 0, 10, <=, +);
System.out.println("FOR(j, 0, 10, <=, +) test");
}
}
Here is my Main.class:
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.stmt.ForStmt;
import javax.tools.*;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
final String fileName = "Class.java";
final String alteredFileName = "src\\ClassAltered.java";
CompilationUnit cu;
try(FileInputStream in = new FileInputStream(fileName)){
cu = JavaParser.parse(in);
}
//cu.getChildNodesByType(ForStmt.class)
//.forEach(Main::setForStatement);
cu.getClassByName("Class").get().setName("ClassAltered");
try(FileWriter output = new FileWriter(new File(alteredFileName), false)) {
output.write(cu.toString());
}
File[] files = {new File(alteredFileName)};
String[] options = { "-d", "out//production//Synthesis" };
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
Iterable<? extends JavaFileObject> compilationUnits =
fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files));
compiler.getTask(
null,
fileManager,
diagnostics,
Arrays.asList(options),
null,
compilationUnits).call();
diagnostics.getDiagnostics().forEach(d -> System.out.println(d.getMessage(null)));
}
}
/*private static void setForStatement(ForStmt forStmt) {
MethodCallExpr initializer = (MethodCallExpr) forStmt.getInitialization().get(0);
if (initializer.getArguments().size() == 5
&& initializer.getArgument(1) instanceof IntegerLiteralExpr
&& initializer.getArgument(2) instanceof IntegerLiteralExpr) {
IntegerLiteralExpr a1 = (IntegerLiteralExpr) initializer.getArgument(1);
IntegerLiteralExpr a2 = (IntegerLiteralExpr) initializer.getArgument(2);
}
}*/
}