Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Update changes to get code running on Python 3 using antlr_python3_runtime-3.1.3. #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 17 additions & 16 deletions bin/j2py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ This is all very ordinary. We import the package bits, open and read
a file, translate it, and write it out.

"""
import io
import sys
from argparse import ArgumentParser, ArgumentTypeError
from collections import defaultdict
from logging import _levelNames as logLevels, exception, warning, info, basicConfig
from logging import _nameToLevel as logLevels, exception, warning, info, basicConfig
from os import path, makedirs
from time import time

Expand Down Expand Up @@ -60,16 +61,16 @@ def runOneOrMany(options):
""" Runs our main transformer with each of the input files. """
infile, outfile = options.inputfile, options.outputfile

if infile and not isinstance(infile, file) and path.isdir(infile):
if outfile and not isinstance(outfile, file) and not path.isdir(outfile):
if infile and not isinstance(infile, io.IOBase) and path.isdir(infile):
if outfile and not isinstance(outfile, io.IOBase) and not path.isdir(outfile):
warning('Must specify output directory or stdout when using input directory.')
return 2
def walker(arg, dirname, files):
for name in [name for name in files if name.endswith('.java')]:
fullname = path.join(dirname, name)
options.inputfile = fullname
info('opening %s', fullname)
if outfile and outfile != '-' and not isinstance(outfile, file):
if outfile and outfile != '-' and not isinstance(outfile, io.IOBase):
full = path.abspath(path.join(outfile, fullname))
head, tail = path.split(full)
tail = path.splitext(tail)[0] + '.py'
Expand All @@ -89,15 +90,15 @@ def runTransform(options):
timed['overall']

filein = fileout = filedefault = '-'
if options.inputfile and not isinstance(options.inputfile, file):
if options.inputfile and not isinstance(options.inputfile, io.IOBase):
filein = options.inputfile
if options.outputfile and not isinstance(options.outputfile, file):
if options.outputfile and not isinstance(options.outputfile, io.IOBase):
fileout = options.outputfile
elif fileout != filedefault:
fileout = '%s.py' % (path.splitext(filein)[0])

configs = options.configs
if options.configdirs and not isinstance(filein, file):
if options.configdirs and not isinstance(filein, io.IOBase):
for configdir in options.configdirs:
dirname = configFromDir(filein, configdir)
if path.exists(dirname):
Expand All @@ -110,15 +111,15 @@ def runTransform(options):
source = open(filein).read()
else:
source = sys.stdin.read()
except (IOError, ), exc:
except (IOError, ) as exc:
code, msg = exc.args[0:2]
print 'IOError: %s.' % (msg, )
print(f'IOError: {msg}.')
return code

timed['comp']
try:
tree = buildAST(source)
except (Exception, ), exc:
except (Exception, ) as exc:
exception('exception while parsing')
return 1
timed['comp_finish']
Expand All @@ -142,29 +143,29 @@ def runTransform(options):

if options.lexertokens:
for idx, tok in enumerate(tree.parser.input.tokens):
print >> sys.stderr, '{0} {1}'.format(idx, tok)
print >> sys.stderr
print(f'{idx} {tok}', file=sys.stderr)
print(file=sys.stderr)

if options.javaast:
tree.dump(sys.stderr)
print >> sys.stderr
print(file=sys.stderr)

if options.pytree:
module.dumpRepr(sys.stderr)
print >> sys.stderr
print(file=sys.stderr)

if not options.skipsource:
if fileout == filedefault:
output = sys.stdout
else:
output = open(fileout, 'w')
module.name = path.splitext(filein)[0] if filein != '-' else '<stdin>'
print >> output, source
print(source, file=output)

if not options.skipcompile:
try:
compile(source, '<string>', 'exec')
except (SyntaxError, ), ex:
except (SyntaxError, ) as ex:
warning('Generated source has invalid syntax. %s', ex)
else:
info('Generated source has valid syntax.')
Expand Down
2 changes: 1 addition & 1 deletion java2python/compiler/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def altIdent(self, name):
for klass in self.parents(lambda v:v.isClass):
if name in klass.variables:
try:
method = self.parents(lambda v:v.isMethod).next()
method = next(self.parents(lambda v:v.isMethod))
except (StopIteration, ):
return name
if name in [p['name'] for p in method.parameters]:
Expand Down
12 changes: 6 additions & 6 deletions java2python/compiler/visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,7 @@ def acceptSwitch(self, node, memo):

def acceptSynchronized(self, node, memo):
""" Accept and process a synchronized statement (not a modifier). """
module = self.parents(lambda x:x.isModule).next()
module = next(self.parents(lambda x:x.isModule))
module.needsSyncHelpers = True
if node.parent.type == tokens.MODIFIER_LIST:
# Skip any synchronized modifier
Expand Down Expand Up @@ -700,7 +700,7 @@ def acceptPrePost(self, node, memo):
name = node.firstChildOfType(tokens.IDENT).text
handler = self.configHandler('VariableNaming')
rename = handler(name)
block = self.parents(lambda x:x.isMethod).next()
block = next(self.parents(lambda x:x.isMethod))
if pre:
left = name
else:
Expand All @@ -725,7 +725,7 @@ def acceptBitShiftRight(self, node, memo):
self.fs = 'bsr(' + FS.l + ', ' + FS.r + ')'
self.left, self.right = visitors = factory(parent=self), factory()
self.zipWalk(node.children, visitors, memo)
module = self.parents(lambda x:x.isModule).next()
module = next(self.parents(lambda x:x.isModule))
module.needsBsrFunc = True

def acceptBitShiftRightAssign(self, node, memo):
Expand All @@ -734,7 +734,7 @@ def acceptBitShiftRightAssign(self, node, memo):
self.fs = FS.l + ' = bsr(' + FS.l + ', ' + FS.r + ')'
self.left, self.right = visitors = factory(parent=self), factory()
self.zipWalk(node.children, visitors, memo)
module = self.parents(lambda x:x.isModule).next()
module = next(self.parents(lambda x:x.isModule))
module.needsBsrFunc = True

def acceptClassConstructorCall(self, node, memo):
Expand Down Expand Up @@ -810,12 +810,12 @@ def acceptStaticArrayCreator(self, node, memo):

def acceptSuper(self, node, memo):
""" Accept and process a super expression. """
cls = self.parents(lambda c:c.isClass).next()
cls = next(self.parents(lambda c:c.isClass))
self.right = self.factory.expr(fs='super({name}, self)'.format(name=cls.name))

def acceptSuperConstructorCall(self, node, memo):
""" Accept and process a super constructor call. """
cls = self.parents(lambda c:c.isClass).next()
cls = next(self.parents(lambda c:c.isClass))
fs = 'super(' + FS.l + ', self).__init__(' + FS.r + ')'
self.right = self.factory.expr(fs=fs, left=cls.name)
return self.right
Expand Down
6 changes: 3 additions & 3 deletions java2python/lang/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,13 @@ def innerDump(root, offset):
args[2] = ' ' + self.colorText(ttyp, token.text)
for com in self.selectComments(start, seen):
for line in self.colorComments(com):
print >> fd, '{0}{1}'.format(indent, line)
print >> fd, nform.format(*args)
print(f'{indent}{line}', file=fd)
print(nform.format(*args), file=fd)
for child in root.getChildren():
innerDump(child, offset+1)
for com in self.selectComments(root.tokenStopIndex, seen):
for line in self.colorComments(com):
print >> fd, '{0}{1}'.format(indent, line)
print(f'{indent}{line}', file=fd)
innerDump(self, level)

def dumps(self, level=0):
Expand Down
4 changes: 2 additions & 2 deletions java2python/mod/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,13 @@ def maybeAbstractMethod(method):

def maybeSynchronizedMethod(method):
if 'synchronized' in method.modifiers:
module = method.parents(lambda x:x.isModule).next()
module = next(method.parents(lambda x:x.isModule))
module.needsSyncHelpers = True
yield '@synchronized'


def globalNameCounter(original, counter=count()):
return '__{0}_{1}'.format(original, counter.next())
return '__{0}_{1}'.format(original, next(counter))


def getBsrSrc():
Expand Down
10 changes: 5 additions & 5 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,8 @@ def doc_files():
author='Troy Melhase',
author_email='[email protected]',

url='https://github.com/natural/java2python/',
download_url='https://github.com/downloads/natural/java2python/java2python-0.5.1.tar.gz',

url='https://github.com/GEGlobalResearch/java2python/',
download_url='https://github.com/GEGlobalResearch/java2python/archive/master.zip',
keywords=['java', 'java2python', 'compiler'],
classifiers=filter(None, classifiers.split('\n')),

Expand Down Expand Up @@ -81,6 +80,7 @@ def doc_files():
('doc', doc_files()),
],

install_requires=['antlr_python_runtime==3.1.3'],

install_requires=[
'antlr_python_runtime@https://github.com/altigee/antlr-python3-runtime-3.1.3/archive/master.zip',
],
)