Coder Social home page Coder Social logo

natural / java2python Goto Github PK

View Code? Open in Web Editor NEW
558.0 558.0 240.0 2.08 MB

Simple but effective library to translate Java source code to Python.

License: GNU Lesser General Public License v2.1

Python 94.20% GAP 2.95% Java 2.73% Shell 0.03% Makefile 0.09%

java2python's People

Contributors

bdkearns avatar iuliux avatar liling avatar natural avatar smsaladi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java2python's Issues

.length() gets applied to the wrong object

Testcase:

class Klass {
    void method() {
        String foo = "asdf";
        dummy(foo.length());
    }
}

Generated output:


#!/usr/bin/env python
""" generated source for module test """
class Klass(object):
    """ generated source for class Klass """
    def method(self):
        """ generated source for method method """
        foo = "asdf"
        len(dummy(foo))

As you can see, the len() should be applied to foo not dummy()

lengthToLen() is called when the selection pattern doesn't fully match

So part of tracking down the length issue (since I'm seeing that currently), I noticed that the
call transforms.lengthToLen() got called repeatedly for transforms that weren't related to the selection definition for that
function.

Breaking in with the python debugger gave me the following:

In compiler/__init__.py(38):transformAST()
-> import pdb; pdb.set_trace()
(Pdb) print selector
Child(Type(DOT:15) > Type(IDENT=length:164))

There should be a METHOD_CALL in front of that according to what's in config/default.py:

(Type('METHOD_CALL') > Type('DOT') > Type('IDENT', 'length'), transform.lengthToLen)

Further tracing shows the problem to be in the Selector.gt() function in lang/selector.py:

def __gt__(self, other):
    """ E > F

    Like CSS: "E > F": an F element child of an E element
    """
    return Child(self, other)

In the case of Type(A) > Type(B) > Type(C), the interpreter is evaluating Type(A) > Type(B) as True first and then returns the
value of Type(B) > Type(C).

wrong translation of x++ operator

Here is another one. I don't know if this comes from ANTLR, or is something that could be solved here.

The Java code:

if (condition):
    myArr[count++] = index;
    # .. more code here
    myArr[count++] = index;

is translated to:

__count_1 = count
count += 1
__count_2 = count
count += 1
if condition:
    myArr[__count_1] = index;
    # .. more code here
    myArr[__count_2] = index;

It should be translated to:

if condition:
    myArr[count] = index;
    count += 1
    # .. more code here
    myArr[count] = index;
    count += 1

Otherwise the result is not the same if the additional code between both assignments do change the count variable.

j2py fails to convert

Hi I tried to use java2python on this library and it fails to do the convertion for some of the files.

For example, <src/model/Dof.java> and <src/model/FeLoadData.java> are converted without problems, but <src/model/FeModelData.java> fails with the following traceback.

I'm on Linux 64bit. and I have Installed j2py 0.5.1.

any ideas?

P.

Traceback (most recent call last):
  File "/usr/bin/j2py", line 259, in <module>
    sys.exit(runMain(configScript(sys.argv[1:])))
  File "/usr/bin/j2py", line 57, in runMain
    return runOneOrMany(options)
  File "/usr/bin/j2py", line 83, in runOneOrMany
    return runTransform(options)
  File "/usr/bin/j2py", line 135, in runTransform
    module.walk(tree)
  File "/usr/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/usr/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/usr/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/usr/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/usr/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/usr/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 83, in walk
    visitor = self.accept(tree, memo)
  File "/usr/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 43, in accept
    return call(node, memo)
  File "/usr/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 443, in acceptFor
    if not node.firstChildOfType(tokens.BLOCK_SCOPE).children:
AttributeError: 'NoneType' object has no attribute 'children'

Cast to non-builtin types

A cast to a class type is turned into a constructor of that type. For example:

obj = (Cast) o;

becomes:

self.obj = Cast(o)

However, with builtin types like String, this works fine.

java2python

after execution of "python setup.py install" , i tried to execute j2py -- version

I am getting j2py is not recognised as internal or external command

Fail with non-ascii char

Running j2py on a java file containing non ascii caracthers is failing:

Traceback (most recent call last):
  File "/usr/local/bin/j2py", line 120, in runTransform
    tree = buildAST(source)
  File "/usr/local/lib/python2.7/dist-packages/java2python/compiler/__init__.py", line 15, in buildAST
    lexer = Lexer(StringStream(source))
  File "/usr/local/lib/python2.7/dist-packages/antlr_python_runtime-3.1.3-py2.7.egg/antlr3/streams.py", line 336, in __init__
    self.strdata = unicode(data)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3345: ordinal not in range(128)

I guess j2py is not properly handling unicode string.

j2py

I think things worked.

However, this might be a silly question to ask as I'm new to Python and converting language content.

What is this code for?

if name == 'main':
import sys
HelloWorld.main(sys.argv)

Minor update on installation of ANTLR Runtime

Please modify
install ANTLR Runtime
wget http://www.antlr3.org/download/antlr-3.1.3.tar.gz

from wget http://www.antlr.org/download/antlr-3.1.3.tar.gz
Antlr no longer hosts the 3.1.3 at the "base" link.

[Comments : I also tried with antlr4-4.0.tar.gz ,surprisingly the ANTLR directory structure for v4 does not have runtime/python folder, so setup doesnot go through . Since java2python explicitly needs the antlr3, so fails, hence recommendation to correct in the installation docs here[for the benefit of other novice programmers like me]

Java wrapper classes handling

The Java wrapper classes (Integer, Boolean, Byte, Char, Short, Long, Float, Double [and String]) should be handled consistently.

At the moment Integer, Boolean and String are translated into primitive types in Python and the rest are treated as common objects.

I think that the same rule should apply to all of them.

A big problem here are the (pretty useful) static methods inside them.

Comments are carried down into all child scopes if there is a for loop

Test case:

// Header Comment

class Klass {
  void method() {
      for (;;) {}
  }
}

Output:

$ j2py test.java
#!/usr/bin/env python
""" generated source for module test """
#  Header Comment
class Klass(object):
    """ generated source for class Klass """
    def method(self):
        """ generated source for method method """
        #  Header Comment
        while True:
            #  Header Comment

The "header comment" is printed in the child scopes.

Operands for "variable < constant" will be reversed in output as "constant < variable"

As in the title, the parser generally swaps the left and right operands of "<", "<=", ">=", ">" if the right operand is a constant.

class ConditionalOperands {
    public static void main(String[] args) {
        String s = "abc";
        if (abc.length() < 10)
            System.out.println("length < 10");
        else
            System.out.println("length >= 10");
    }
}

Python output

""" generated source for module ConditionalOperands """
from __future__ import print_function
#  This is the HelloWorld class with a single method.
class ConditionalOperands(object):
    """ generated source for class ConditionalOperands """
    @classmethod
    def main(cls, args):
        """ generated source for method main """
        s = "abc"
        if 10 < len(abc):  # <---- This is wrong!
            print("length < 10")
        else:
            print("length >= 10")


if __name__ == '__main__':
    import sys
    ConditionalOperands.main(sys.argv)

Use j2py to convert folders

I managed to install j2py and also used it for single files.
Is there a possibility to convert folders (all files with the folder and all subfolders within) like /src/ into Python via j2py?

IndexError: list index out of range

Thanks in advance...

Running java2python in Anaconda on a Mac with following packages:
...$ conda list -n j2p

packages in environment at /Applications/Anaconda/anaconda3/envs/j2p:

Name Version Build Channel

antlr-python-runtime 3.1.3 pypi_0 pypi
ca-certificates 2019.8.28 0
certifi 2019.9.11 py27_0
java2python 0.5.0 pypi_0 pypi
libcxx 4.0.1 hcfea43d_1
libcxxabi 4.0.1 hcfea43d_1
libedit 3.1.20181209 hb402a30_0
libffi 3.2.1 h475c297_4
ncurses 6.1 h0a44026_1
pip 19.2.3 py27_0
python 2.7.16 h97142e2_7
readline 7.0 h1de35cc_5
setuptools 41.4.0 py27_0
sqlite 3.30.0 ha441bb4_0
tk 8.6.8 ha441bb4_0
wheel 0.33.6 py27_0
zlib 1.2.11 h1de35cc_3

Trying to convert this file to python...
https://github.com/smithk/cidre/blob/master/0.1/imagej/src/Cidre_Plugin.java

Get the following error
j2py Cidre_Plugin.java Cidre_Plugin.py
Traceback (most recent call last):
File "/Applications/Anaconda/anaconda3/envs/j2p/bin/j2py", line 258, in
sys.exit(runMain(configScript(sys.argv[1:])))
File "/Applications/Anaconda/anaconda3/envs/j2p/bin/j2py", line 57, in runMain
return runOneOrMany(options)
File "/Applications/Anaconda/anaconda3/envs/j2p/bin/j2py", line 82, in runOneOrMany
return runTransform(options)
File "/Applications/Anaconda/anaconda3/envs/j2p/bin/j2py", line 134, in runTransform
module.walk(tree)
File "/Applications/Anaconda/anaconda3/envs/j2p/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/Applications/Anaconda/anaconda3/envs/j2p/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/Applications/Anaconda/anaconda3/envs/j2p/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/Applications/Anaconda/anaconda3/envs/j2p/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/Applications/Anaconda/anaconda3/envs/j2p/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/Applications/Anaconda/anaconda3/envs/j2p/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 83, in walk
visitor = self.accept(tree, memo)
File "/Applications/Anaconda/anaconda3/envs/j2p/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 43, in accept
return call(node, memo)
File "/Applications/Anaconda/anaconda3/envs/j2p/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 474, in acceptIf
nextNode = nextNode.children[2]
IndexError: list index out of range

Some non-Python Java primitives not converted

Some of the primitive types in Java that don't have a correspondent type in Python are not translated correctly.

For example, short in Java should become int in Python. char should become str, and I see that there is a rule in this direction in the config/default.py but no effect.

Test example:

class Primitives {
    char chr;
    byte byt;
    short shr;
    int in_t;
    long lng;
    float flt;
    double dbl;
}

Generates the output:

class Primitives(object):
    chr = char()  # <- Problem
    byt = byte()  # <- Problem
    shr = short()  # <- Problem
    in_t = int()
    lng = long()  # <- Problem
    flt = float()
    dbl = float()

This is a blocker for Issue #6 I started solving.

Bugs found trying to translate toxiclibs

I thought I'd point java2python at toxiclibs and see what happens, unfortunately it gets stuck:

# hg clone https://bitbucket.org/postspectacular/toxiclibs

ToneMap https://bitbucket.org/postspectacular/toxiclibs/src/689ddcd9bea39d1f8dddad26e971ae4c12b1198e/src.color/toxi/color/ToneMap.java?at=default

Triggers ValueError: list.remove(x): x not in list


# j2py src.color/toxi/color/ToneMap.java
Traceback (most recent call last):
  File "/home/stu/.virtualenvs/tmp/bin/j2py", line 7, in <module>
    execfile(__file__)
  File "/home/stu/.virtualenvs/tmp/src/java2python/bin/j2py", line 259, in <module>
    sys.exit(runMain(configScript(sys.argv[1:])))
  File "/home/stu/.virtualenvs/tmp/src/java2python/bin/j2py", line 57, in runMain
    return runOneOrMany(options)
  File "/home/stu/.virtualenvs/tmp/src/java2python/bin/j2py", line 83, in runOneOrMany
    return runTransform(options)
  File "/home/stu/.virtualenvs/tmp/src/java2python/bin/j2py", line 128, in runTransform
    transformAST(tree, config)
  File "/home/stu/.virtualenvs/tmp/src/java2python/java2python/compiler/__init__.py", line 37, in transformAST
    call(node, config)
  File "/home/stu/.virtualenvs/tmp/src/java2python/java2python/mod/transform.py", line 96, in lengthToLen
    raise e
ValueError: list.remove(x): x not in list


ColorList generates invalid syntax -

ColorList.#      * Creates a deep copy of the given ColorList. Manipulating the new list or

# WARNING runTransform: Generated source has invalid syntax. expected an indented block (<string>, line 117)

ANTLR 3.1.3 not found

When trying to install with

pip install java2python

I get the following error message:

(py27)➜ Downloads pip install java2python
Collecting java2python
Using cached java2python-0.5.0.tar.gz
Collecting antlr-python-runtime==3.1.3 (from java2python)
Could not find a version that satisfies the requirement antlr-python-runtime==3.1.3 (from java2python) (from versions: )
No matching distribution found for antlr-python-runtime==3.1.3 (from java2python)

I think the installation instructions might need updating to reflect that the section Install ANTLR Runtime is necessary regardless of whether pip install java2python is used or not.

translate String.charAt into []

I've seen String.length been translated to len(string)

how about String.charAt into string[]
and String.substring(b, e) into string[b:e] ?

can not install

$ pip install java2python
Collecting java2python
  Downloading https://files.pythonhosted.org/packages/e4/4d/96dd48650ebe9dcdcbef4e61840e9efdf240b34cee6bdb8ea8de6749d1e5/java2python-0.5.0.tar.gz (138kB)
    100% |████████████████████████████████| 143kB 23kB/s 
Collecting antlr_python_runtime==3.1.3 (from java2python)
  Could not find a version that satisfies the requirement antlr_python_runtime==3.1.3 (from java2python) (from versions: )
No matching distribution found for antlr_python_runtime==3.1.3 (from java2python)

pip installation failed, 'long' installation works

Just a mention that might be of use to other users.

I had some problems with installation.
My first try was using the quick 'pip install java2python'

  • When doing this with python 2.7.9, the following error occurred:
Collecting java2python
  Using cached java2python-0.5.0.tar.gz
Collecting antlr-python-runtime==3.1.3 (from java2python)
←[31m  Could not find a version that satisfies the requirement antlr-python-runt
ime==3.1.3 (from java2python) (from versions: )←[0m
←[33m  Some externally hosted files were ignored as access to them may be unreli
able (use --allow-external antlr-python-runtime to allow).←[0m
←[33m  Some insecure and unverifiable files were ignored (use --allow-unverified
 antlr-python-runtime to allow).←[0m
←[31m  No matching distribution found for antlr-python-runtime==3.1.3 (from java
2python)←[0m
  • When doing the 'long install' method, things worked (though some of the links to antler in the java2python
    docs are old). Here are steps that worked (I did this in a 'GitBash shell' under Windows OS):
  • j2py now works as advertised.
  • The above method does not get the tests, but they may be obtained by downloading a zip of this
    Github repository.

Two minor nitpicks on the action of j2py:

  • Empty If-then-else clauses need a 'pass' action, or Python complains
  • Many of the comments are moved from their original location in the Java file. Would be better if they
    were left in at least approximate original locations.

Thanks for making this available. It will save a lot of time in converting a 2000 line Java program.

assignment expressions in while loop

Hello,

I'll put some feed back here to some missing conversions. I hope it can be useful.

A java code like this:

int amountRead;
while((amountRead = is.read(buffer, 0, 1024))!= -1)
{
    decoded.write(buffer, 0, amountRead);
}
decoded.flush();

is converted to this python one:

amountRead = int()
while (amountRead = is_.read(buffer_, 0, 1024)) != -1:
    decoded.write(buffer_, 0, amountRead)
decoded.flush()

The problem is that Python doesn't allow assignment expressions to be used inside the conditional expression of the loop. Check here: expression vs assignments in while loop in python and Java?

mechanism to force j2py to print what it's got?

Often, j2py will exit without printing python up to... wherever it's gotten up to before it errored. Equally often... we will get a chunk of Java code without context. Meaning, the variable declaration is missing (easy enough to fix), or worse... unknown package import, or something else that may not be necessarily be important to whatever we're trying to do.
I'd like a switch where I can say --ignore or --force to be able to see where j2py got up to. And I'll go ahead and fill in the blanks.

Possible?

(I wouldn't normally ask for something like this, but the program never successfully completes because I'm never given a full correct Java source.)

AttributeError: 'NoneType' object has no attribute 'type'

Hello~ run the coomand: python2 j2py CoNLLStreamExtractor.java

Returned the following bug:

line 103:11 no viable alternative at input u'void'
line 103:11 no viable alternative at input u'void'
line 111:45 no viable alternative at input u'>'
line 186:8 no viable alternative at input u'List'
line 186:8 no viable alternative at input u'List'
line 186:43 mismatched input u'(' expecting SEMI
Traceback (most recent call last):
  File "j2py", line 259, in <module>
    sys.exit(runMain(configScript(sys.argv[1:])))
  File "j2py", line 57, in runMain
    return runOneOrMany(options)
  File "j2py", line 83, in runOneOrMany
    return runTransform(options)
  File "j2py", line 128, in runTransform
    transformAST(tree, config)
  File "D:\Python\python27\lib\site-packages\java2python\compiler\__init__.py", line 36, in transformAST
    for node in selector.walk(tree):
  File "D:\Python\python27\lib\site-packages\java2python\lang\selector.py", line 68, in walk
    for item in self.walk(child):
  File "D:\Python\python27\lib\site-packages\java2python\lang\selector.py", line 68, in walk
    for item in self.walk(child):
  File "D:\Python\python27\lib\site-packages\java2python\lang\selector.py", line 65, in walk
    for item in self(tree):
  File "D:\Python\python27\lib\site-packages\java2python\lang\selector.py", line 163, in __call__
    if tree.token.type == self.key:
AttributeError: 'NoneType' object has no attribute 'type'

Best wishes and good luck to you!

empty blocks with comments

Here is another case. Is there anyway we can help to fix them ?

if (a > 1)
{
  # comment from java code (maybe a todo)
}
else
{
   result = 4
}

becomes in Python:

if a > 1:
  # comment from java code (maybe a todo)
else
   result = 4

That construction is not valid in Python, it needs at less a pass sentence besides the comments. This way:

if a > 1:
  # comment from java code (maybe a todo)
  pass
else
  result = 4

Can't find antlr installation

The installation fails to find antlr

[root@localhost j2p]# pip2.7 --proxy http://70.10.15.10:8080 --trusted-host pypi.python.org install ./java2python-0.5.1
Processing ./java2python-0.5.1
Requirement already satisfied (use --upgrade to upgrade): java2python==0.5.1 from file:///root/work/j2p/java2python-0.5.1 in /usr/lib/python2.7/site-packages/java2python-0.5.1-py2.7.egg
Collecting antlr_python_runtime==3.1.3 (from java2python==0.5.1)
Could not find a version that satisfies the requirement antlr_python_runtime==3.1.3 (from java2python==0.5.1) (from versions: )
No matching distribution found for antlr_python_runtime==3.1.3 (from java2python==0.5.1)

AttributeError: 'NoneType' object has no attribute 'children' at line 443 in visitor.py

Hi, when I tried to translate my java code it raised:

Traceback (most recent call last):
File "/opt/bin/j2py", line 259, in
sys.exit(runMain(configScript(sys.argv[1:])))
File "/opt/bin/j2py", line 57, in runMain
return runOneOrMany(options)
File "/opt/bin/j2py", line 83, in runOneOrMany
return runTransform(options)
File "/opt/bin/j2py", line 135, in runTransform
module.walk(tree)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 83, in walk
visitor = self.accept(tree, memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 43, in accept
return call(node, memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 471, in acceptIf
ifBlock.walk(node.children[1], memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
visitor.walk(child, memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 83, in walk
visitor = self.accept(tree, memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 43, in accept
return call(node, memo)
File "/opt/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 443, in acceptFor
if not node.firstChildOfType(tokens.BLOCK_SCOPE).children:
AttributeError: 'NoneType' object has no attribute 'children'

and found a quick walkaround by this patch:

diff --git a/java2python/compiler/visitor.py b/java2python/compiler/visitor.py
index 4109883..374e286 100644
--- a/java2python/compiler/visitor.py
+++ b/java2python/compiler/visitor.py
@@ -440,7 +440,7 @@ class MethodContent(Base):
         else:
             whileStat.expr.walk(cond, memo)
         whileBlock = self.factory.methodContent(parent=self)
-        if not node.firstChildOfType(tokens.BLOCK_SCOPE).children:
+        if node.firstChildOfType(tokens.BLOCK_SCOPE) and not node.firstChildOfType(tokens.BLOCK_SCOPE).children:
             self.factory.expr(left='pass', parent=whileBlock)
         else:
             whileBlock.walk(node.firstChildOfType(tokens.BLOCK_SCOPE), memo)

from java2python.mod.include import sync

c:\python27\lib\site-packages\java2python\mod\basic.py(151):
from java2python.mod.include import sync

This statement fails, because there is no module "include".

grep found a sync in
c:\python27\lib\site-packages\java2python\compiler\visitor.py(559)
is that the one that should be included? comments seem to indicate differently ...

Cannot install on mac

I get this exception while installing on mac via the command: sudo pip install java2python (I see the same problem without sudo)

    byte-compiling /Library/Python/2.7/site-packages/java2python/mod/transform.py to transform.pyc
    running install_data
    creating /System/Library/Frameworks/Python.framework/Versions/2.7/doc
    error: could not create '/System/Library/Frameworks/Python.framework/Versions/2.7/doc': Operation not permitted

    ----------------------------------------
  Rolling back uninstall of java2python
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-BTfKen-build/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-BWjER1-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-BTfKen-build/

Couple of issues

I was trying to convert some old Java class to python using your utility and for the most part it worked awesome!

However, these were a couple of issues:

  1. Conversion lost some lines of code along with most of the comments. For example, see assignment to the 'name' variable in the constructor. This made me go and compare every single line just to make I have not lost anything. This is probably my main issue with tool.
  2. Some of the member functions got the 'self' pointer, while others for some reason got 'cls'. Not sure why, but this was completely unnecessary.
  3. The tool did not prepend the calls to member functions with .self.
  4. For loops got replaced with 'while'.

My Java file

Output Python file

Thanks very much for your efforts!

Maksym

translated constant arrays result in syntax errors

A little problem translating array initializers. This Java code:

public class XParser extends BaseParser
{
    private static final char[] MYCHARARR = new char[] { 'a', 'b', 'c', 'd' };
    # ....
}

results in this invalid syntax:

class COSParser(BaseParser):
    MYCHARARR = [None] * 

it should be:

class COSParser(BaseParser):
    MYCHARARR = ['a', 'b', 'c', 'd']

Instance vars not prepended with `self`

The second operator in a conditional (being instance variable) is mistranslated to a global variable. Example:

boolean b = (v1 == v2);

is turned into:

b = (self.v1 == v2)

AttributeError: 'NoneType' object has no attribute 'token'

The below code compiles and executes correctly via java, but I receive an error when trying to use java2python to convert the code to python:

class helloworld {
public static void main(String[] args) {
String result = String.format("The format method is %s!"
+ " blah ", "great");

    System.out.println(result);
}

}

The statement + " blah" is causing the problem.. These types of statements occur frequently in gwt, and other libraries.

Billy

imports are referenced incorrectly

for example:

import sudoku.SudokuBoardGenerator;
import sudoku.SudokuFile;

public class BTSolverExample {

	public static void main(String[] args)
	{
		SudokuFile sf = SudokuBoardGenerator.generateBoard(9, 3, 3, 12);

will convert to:

import sudoku.SudokuBoardGenerator
import sudoku.SudokuFile


class BTSolverExample(object):
    """ generated source for class BTSolverExample """
    @classmethod
    def main(cls, args):
        """ generated source for method main """
        sf = SudokuBoardGenerator.generateBoard(9, 3, 3, 12)

but it should be:

import sudoku.SudokuBoardGenerator
import sudoku.SudokuFile


class BTSolverExample(object):
    """ generated source for class BTSolverExample """
    @classmethod
    def main(cls, args):
        """ generated source for method main """
        sf = sudoku.SudokuBoardGenerator.generateBoard(9, 3, 3, 12)

to point it out, SudokuBoardGenerator should be sudoku.SudokuBoardGenerator

Suggestions for little improvements

Hello,

I tried your tool and had some problems which you might like to know for future improvement. I tell you every point so you can decide which are useful for you.

  1. The tool coudn't convert sourcecode with German Umlauts, even if the Umlauts where only in comments.
  2. Java import statements where left in which where useless in Python.
  3. The converter inserted cls as self-reference. It added cls. before variables, but not before functions, so the functions wheren't found when running.
  4. Javas functions from librarys are left untouched. It would be possible to exchange "Math.abs(Random().nextInt()) % 6" by Pythons "random.randint(0, 6)"
  5. stdin = BufferedReader(InputStreamReader(System.in_)) is left in and not useful anymore. (Only "BufferedReader" before stdin was thrown out.)
  6. String eing = stdin.readLine(); was completly thrown out by the tool. I would like it to be exchanged by eing = raw_input("")
  7. If a variable is declared as something else as a string and is concatenated with a string, it would be nice to put str() around it. For example:
    int counter = 0;
    System.out.println("The counter is: " + counter);
    should become
    counter = 0
    print "The counter is: " + str(counter)

Thanks for the great work, I like your tool as it is. Please take this points as suggestions, without need to accept.

AttributeError when attempting static access to Class.class

Given the following (simplified as much as possible) class definition:

public class demoClass {
    static Class klass = demoClass.class;
}

I get the following error:

$ j2py demoClass.java 
Traceback (most recent call last):
  File "/pathToPython/bin/j2py", line 258, in <module>
    sys.exit(runMain(configScript(sys.argv[1:])))
  File "/pathToPython/bin/j2py", line 57, in runMain
    return runOneOrMany(options)
  File "/pathToPython/bin/j2py", line 82, in runOneOrMany
    return runTransform(options)
  File "/pathToPython/bin/j2py", line 134, in runTransform
    module.walk(tree)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 86, in walk
    visitor.walk(child, memo)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 83, in walk
    visitor = self.accept(tree, memo)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 43, in accept
    return call(node, memo)
  File "/pathToPython/lib/python2.7/site-packages/java2python/compiler/visitor.py", line 121, in acceptType
    name = node.firstChildOfType(tokens.IDENT).text
AttributeError: 'NoneType' object has no attribute 'text'

The original offending line is actually a call to Logger.getLogger, like so:

private static Logger log = Logger.getLogger( aClassName.class );

In this case I can easily rewrite the Java code via search-and-replace or even comment the code out, but it would be nice to have this handled automatically.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.