source: java2python/src/main/java/tudelft/utilities/j2p/PyModule.java@ 380

Last change on this file since 380 was 380, checked in by wouter, 2 years ago

#115 work in progress to move zip code to PyProgram and PyModule

File size: 2.6 KB
Line 
1package tudelft.utilities.j2p;
2
3import java.io.File;
4import java.io.FileNotFoundException;
5import java.nio.file.Path;
6
7import com.github.javaparser.JavaParser;
8import com.github.javaparser.ParseResult;
9import com.github.javaparser.ParserConfiguration;
10import com.github.javaparser.ast.CompilationUnit;
11import com.github.javaparser.symbolsolver.JavaSymbolSolver;
12import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver;
13import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;
14
15import tudelft.utilities.j2p.formatting.Block;
16import tudelft.utilities.j2p.t.Translator;
17
18/**
19 * A PyModule contains a python "file". This is the python equivalent to a java
20 * class "file".
21 */
22public class PyModule {
23 private final Block code;
24 private final String modulename;
25
26 /**
27 *
28 * @param pycode the python code to be zipped as pip-installable zip. It
29 * is assumed that the code is just 1 file.
30 * @param modulename The name of the module. Eg "a.b.c" if there is a file
31 * a.b.c.py. The module name is equivalent to the java
32 * package name. Note that you still need the java BASE
33 * directory (typically src/main/java) to find the
34 * original java file.
35 */
36 public PyModule(Block code, String modulename) {
37 this.code = code;
38 this.modulename = modulename;
39 }
40
41 public Block getCode() {
42 return code;
43 }
44
45 public String getModuleName() {
46 return modulename;
47 }
48
49 /**
50 *
51 * @param javaBaseDir the java base dir from where packages are found,
52 * typically src/main/java
53 * @param modulename the full.qualified.path.to.Class of the java module
54 * @return PyModule containing the translated java file
55 * @throws FileNotFoundException
56 */
57 public static PyModule fromJavaFile(Path javaBaseDir, String modulename)
58 throws FileNotFoundException {
59 String modulepath = modulename.replace(".", "/");
60 File javaFile = javaBaseDir.resolve(modulepath + ".java").toFile();
61 if (!javaFile.exists())
62 throw new FileNotFoundException("There is no file " + modulename
63 + ".java in the directory " + javaBaseDir);
64
65 ParserConfiguration conf = new ParserConfiguration();
66 CombinedTypeSolver typeSolver = new CombinedTypeSolver();
67 typeSolver.add(new ReflectionTypeSolver(false));
68 JavaSymbolSolver symbolSolver = new JavaSymbolSolver(typeSolver);
69 conf.setSymbolResolver(symbolSolver);
70 JavaParser parser = new JavaParser(conf);
71
72 ParseResult<CompilationUnit> res = parser.parse(javaFile);
73
74 Block translation = Translator.translate(res.getResult().get());
75 return new PyModule(translation, modulename);
76 }
77}
Note: See TracBrowser for help on using the repository browser.