forked from redmouth/java2cpp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathParser.java
More file actions
86 lines (69 loc) · 2.81 KB
/
Parser.java
File metadata and controls
86 lines (69 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package co.deepblue.java2cpp;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;
import java.util.Optional;
import static com.github.javaparser.ast.type.PrimitiveType.intType;
/**
* Created by levin on 17-5-6.
*/
public class Parser {
int a = 0;
class b{
int x = a;
}
public Optional<ClassOrInterfaceDeclaration> parseClass(String classString) {
CompilationUnit compilationUnit = JavaParser.parse(classString);
return compilationUnit.getClassByName("A");
}
public String parseSourceFile(String fileName) throws Exception {
FileInputStream in = new FileInputStream(fileName);
// parse the file
CompilationUnit cu = JavaParser.parse(in);
// prints the resulting compilation unit to default system output
return cu.toString();
}
public CompilationUnit parseToCompilationUnit(String fileName) throws Exception {
FileInputStream in = new FileInputStream(fileName);
// parse the file
CompilationUnit cu = JavaParser.parse(in);
// prints the resulting compilation unit to default system output
return cu;
}
public static class MethodVisitor extends VoidVisitorAdapter<Void> {
@Override
public void visit(MethodDeclaration n, Void arg) {
/* here you can access the attributes of the method.
this method will be called for all methods in this
CompilationUnit, including inner class methods */
System.out.println(n.getName());
super.visit(n, arg);
}
}
public void changeMethods(CompilationUnit cu) {
// Go through all the types in the file
NodeList<TypeDeclaration<?>> types = cu.getTypes();
for (TypeDeclaration<?> type : types) {
// Go through all fields, methods, etc. in this type
NodeList<BodyDeclaration<?>> members = type.getMembers();
for (BodyDeclaration<?> member : members) {
if (member instanceof MethodDeclaration) {
MethodDeclaration method = (MethodDeclaration) member;
changeMethod(method);
}
}
}
}
public void changeMethod(MethodDeclaration n) {
// change the name of the method to upper case
n.setName(n.getNameAsString().toUpperCase());
// create the new parameter
n.addParameter(intType(), "value");
}
}