File size: 1,152 Bytes
b19c92c |
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 |
import ast, astor, javalang
class CodeConverter:
def python_to_java(self,code):
try: t=ast.parse(code)
except: return "// parse error\n"+code
out=["public class Converted {"," public static void main(String[] args) {"]
for n in t.body:
if isinstance(n,ast.Expr) and isinstance(n.value,ast.Call) and getattr(n.value.func,'id','')=='print':
args=", ".join(astor.to_source(a).strip() for a in n.value.args)
out.append(f" System.out.println({args});")
out.append(" }"); out.append("}")
return "\n".join(out)
def java_to_python(self,code):
out=["# Converted from Java"]
try: tree=javalang.parse.parse(code)
except: return "# parse error\n"+code
for _,m in tree.filter(javalang.tree.MethodDeclaration):
out.append(f"def {m.name}():\n pass")
return "\n".join(out)
def convert(self,code,src,tgt):
s,t=src.lower(),tgt.lower()
if s=='python' and t=='java': return self.python_to_java(code)
if s=='java' and t=='python': return self.java_to_python(code)
return code
|