Skip to content

Commit 5bc19d3

Browse files
committed
2to3
1 parent ec8ee44 commit 5bc19d3

File tree

9 files changed

+54
-53
lines changed

9 files changed

+54
-53
lines changed

bin/j2py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -110,15 +110,15 @@ def runTransform(options):
110110
source = open(filein).read()
111111
else:
112112
source = sys.stdin.read()
113-
except (IOError, ), exc:
113+
except (IOError, ) as exc:
114114
code, msg = exc.args[0:2]
115-
print 'IOError: %s.' % (msg, )
115+
print('IOError: %s.' % (msg, ))
116116
return code
117117

118118
timed['comp']
119119
try:
120120
tree = buildAST(source)
121-
except (Exception, ), exc:
121+
except (Exception, ) as exc:
122122
exception('exception while parsing')
123123
return 1
124124
timed['comp_finish']
@@ -136,35 +136,35 @@ def runTransform(options):
136136
timed['visit_finish']
137137

138138
timed['encode']
139-
source = unicode(module)
139+
source = str(module)
140140
timed['encode_finish']
141141
timed['overall_finish']
142142

143143
if options.lexertokens:
144144
for idx, tok in enumerate(tree.parser.input.tokens):
145-
print >> sys.stderr, '{0} {1}'.format(idx, tok)
146-
print >> sys.stderr
145+
print('{0} {1}'.format(idx, tok), file=sys.stderr)
146+
print(file=sys.stderr)
147147

148148
if options.javaast:
149149
tree.dump(sys.stderr)
150-
print >> sys.stderr
150+
print(file=sys.stderr)
151151

152152
if options.pytree:
153153
module.dumpRepr(sys.stderr)
154-
print >> sys.stderr
154+
print(file=sys.stderr)
155155

156156
if not options.skipsource:
157157
if fileout == filedefault:
158158
output = sys.stdout
159159
else:
160160
output = open(fileout, 'w')
161161
module.name = path.splitext(filein)[0] if filein != '-' else '<stdin>'
162-
print >> output, source
162+
print(source, file=output)
163163

164164
if not options.skipcompile:
165165
try:
166166
compile(source, '<string>', 'exec')
167-
except (SyntaxError, ), ex:
167+
except (SyntaxError, ) as ex:
168168
warning('Generated source has invalid syntax. %s', ex)
169169
else:
170170
info('Generated source has valid syntax.')

java2python/compiler/block.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,15 @@
1616
from java2python.compiler import template, visitor
1717

1818

19-
def addTypeToModule((className, factoryName)):
19+
def addTypeToModule(xxx_todo_changeme):
2020
""" Constructs and adds a new type to this module. """
21+
(className, factoryName) = xxx_todo_changeme
2122
bases = (getattr(template, className), getattr(visitor, className))
2223
newType = type(className, bases, dict(factoryName=factoryName))
2324
setattr(modules[__name__], className, newType)
2425

2526

26-
map(addTypeToModule, (
27+
list(map(addTypeToModule, (
2728
('Annotation', 'at'),
2829
('Class', 'klass'),
2930
('Comment', 'comment'),
@@ -35,4 +36,4 @@ def addTypeToModule((className, factoryName)):
3536
('Module', 'module'),
3637
('Statement', 'statement'),
3738
)
38-
)
39+
))

java2python/compiler/template.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,13 @@
1313
# are usually a sign of a bad design and/or language limitations, and
1414
# this case is no exception.
1515

16-
from cStringIO import StringIO
16+
from io import StringIO
1717
from functools import partial
18-
from itertools import chain, ifilter, imap
18+
from itertools import chain
1919

2020
from java2python.lang import tokens
2121
from java2python.lib import FS, colors
22+
from functools import reduce
2223

2324

2425
class Factory(object):
@@ -74,7 +75,7 @@ def __init__(cls, name, bases, namespace):
7475
pass
7576

7677

77-
class Base(object):
78+
class Base(object, metaclass=FactoryTypeDetector):
7879
""" Base -> base class for formatting Python output.
7980
8081
This class defines a large set of attributes and methods for the
@@ -110,7 +111,6 @@ class Base(object):
110111
a the template as tree for debugging.
111112
112113
"""
113-
__metaclass__ = FactoryTypeDetector
114114
isAnnotation = isClass = isComment = isEnum = isExpression = \
115115
isInterface = isMethod = isModule = isStatement = False
116116

@@ -155,7 +155,7 @@ def altIdent(self, name):
155155
for klass in self.parents(lambda v:v.isClass):
156156
if name in klass.variables:
157157
try:
158-
method = self.parents(lambda v:v.isMethod).next()
158+
method = next(self.parents(lambda v:v.isMethod))
159159
except (StopIteration, ):
160160
return name
161161
if name in [p['name'] for p in method.parameters]:
@@ -173,20 +173,20 @@ def configHandler(self, part, suffix='Handler', default=None):
173173
def configHandlers(self, part, suffix='Handlers'):
174174
""" Returns config handlers for this type of template """
175175
name = '{0}{1}{2}'.format(self.typeName, part, suffix)
176-
return imap(self.toIter, chain(*self.config.every(name, [])))
176+
return map(self.toIter, chain(*self.config.every(name, [])))
177177

178178
def dump(self, fd, level=0):
179179
""" Writes the Python source code for this template to the given file. """
180180
indent, isNotNone = level * self.indent, lambda x:x is not None
181181
lineFormat = '{0}{1}\n'.format
182-
for line in ifilter(isNotNone, self.iterPrologue()):
182+
for line in filter(isNotNone, self.iterPrologue()):
183183
line = lineFormat(indent, line)
184184
fd.write(line if line.strip() else '\n')
185-
for item in ifilter(isNotNone, self.iterHead()):
185+
for item in filter(isNotNone, self.iterHead()):
186186
item.dump(fd, level+1)
187187
for item in self.iterBody():
188188
item.dump(fd, level+1)
189-
for line in ifilter(isNotNone, self.iterEpilogue()):
189+
for line in filter(isNotNone, self.iterEpilogue()):
190190
line = lineFormat(indent, line)
191191
fd.write(line if line.strip() else '\n')
192192

@@ -200,7 +200,7 @@ def dumpRepr(self, fd, level=0):
200200
""" Writes a debug string for this template to the given file. """
201201
indent, default = self.indent, lambda x, y:None
202202
fd.write('{0}{1!r}\n'.format(indent*level, self))
203-
for child in ifilter(None, self.children):
203+
for child in filter(None, self.children):
204204
getattr(child, 'dumpRepr', default)(fd, level+1)
205205

206206
@property
@@ -230,7 +230,7 @@ def iterPrologue(self):
230230
def iterHead(self):
231231
""" Yields the items in the head of this template. """
232232
items = chain(*(h(self) for h in self.configHandlers('Head')))
233-
return imap(self.toExpr, items)
233+
return map(self.toExpr, items)
234234

235235
def iterBody(self):
236236
""" Yields the items in the body of this template. """
@@ -304,10 +304,10 @@ def __init__(self, config, left='', right='', fs=FS.lr, parent=None, tail=''):
304304
def __repr__(self):
305305
""" Returns the debug string representation of this template. """
306306
parts, parent, showfs = [colors.blue(self.typeName)], self.parent, True
307-
if isinstance(self.left, (basestring, )) and self.left:
307+
if isinstance(self.left, str) and self.left:
308308
parts.append(colors.white('left:') + colors.yellow(self.left))
309309
showfs = False
310-
if isinstance(self.right, (basestring, )) and self.right:
310+
if isinstance(self.right, str) and self.right:
311311
parts.append(colors.white('right:') + colors.yellow(self.right))
312312
showfs = False
313313
if self.modifiers:

java2python/compiler/visitor.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414

1515
from functools import reduce, partial
16-
from itertools import ifilter, ifilterfalse, izip, tee
16+
from itertools import filterfalse, tee
1717
from logging import debug, warn
1818
from re import compile as recompile, sub as resub
1919

@@ -31,7 +31,7 @@ def __init__(self):
3131
class Base(object):
3232
""" Base -> Parent class for AST visitors. """
3333

34-
commentSubs = map(recompile, ['^\s*/(\*)+', '(\*)+/\s*$', '^\s*//'])
34+
commentSubs = list(map(recompile, ['^\s*/(\*)+', '(\*)+/\s*$', '^\s*//']))
3535

3636
def accept(self, node, memo):
3737
""" Accept a node, possibly creating a child visitor. """
@@ -48,7 +48,7 @@ def insertComments(self, tmpl, tree, index, memo):
4848
cache, parser, comTypes = memo.comments, tree.parser, tokens.commentTypes
4949
comNew = lambda t:t.type in comTypes and (t.index not in cache)
5050

51-
for tok in ifilter(comNew, parser.input.tokens[memo.last:index]):
51+
for tok in filter(comNew, parser.input.tokens[memo.last:index]):
5252
cache.add(tok.index)
5353

5454
# loop over parents until we find the top expression
@@ -70,7 +70,7 @@ def insertComments(self, tmpl, tree, index, memo):
7070
def stripComment(self, text):
7171
""" Regex substitutions for comments; removes comment characters. """
7272
subText = lambda value, regex:resub(regex, '', value)
73-
for text in ifilter(unicode.strip, text.split('\n')):
73+
for text in filter(str.strip, text.split('\n')):
7474
yield reduce(subText, self.commentSubs, text)
7575

7676
def walk(self, tree, memo=None):
@@ -95,7 +95,7 @@ def walk(self, tree, memo=None):
9595

9696
def zipWalk(self, nodes, visitors, memo):
9797
""" Walk the given nodes zipped with the given visitors. """
98-
for node, visitor in izip(nodes, visitors):
98+
for node, visitor in zip(nodes, visitors):
9999
visitor.walk(node, memo)
100100

101101
def nodeTypeToString(self, node):
@@ -132,7 +132,7 @@ def acceptType(self, node, memo):
132132
_acceptInterface = makeAcceptType('interface')
133133

134134
def acceptInterface(self, node, memo):
135-
module = self.parents(lambda x:x.isModule).next()
135+
module = next(self.parents(lambda x:x.isModule))
136136
module.needsAbstractHelpers = True
137137
return self._acceptInterface(node, memo)
138138

@@ -161,9 +161,9 @@ class ModifiersAcceptor(object):
161161
def acceptModifierList(self, node, memo):
162162
""" Accept and process class and method modifiers. """
163163
isAnno = lambda token:token.type==tokens.AT
164-
for ano in ifilter(isAnno, node.children):
164+
for ano in filter(isAnno, node.children):
165165
self.nodesToAnnos(ano, memo)
166-
for mod in ifilterfalse(isAnno, node.children):
166+
for mod in filterfalse(isAnno, node.children):
167167
self.nodesToModifiers(mod, node)
168168
return self
169169

@@ -407,7 +407,7 @@ def acceptCatch(self, node, memo):
407407

408408
def acceptContinue(self, node, memo):
409409
""" Accept and process a continue statement. """
410-
parent = node.parents(lambda x: x.type in {tokens.FOR, tokens.FOR_EACH, tokens.DO, tokens.WHILE}).next()
410+
parent = next(node.parents(lambda x: x.type in {tokens.FOR, tokens.FOR_EACH, tokens.DO, tokens.WHILE}))
411411
if parent.type == tokens.FOR:
412412
updateStat = self.factory.expr(parent=self)
413413
updateStat.walk(parent.firstChildOfType(tokens.FOR_UPDATE), memo)
@@ -561,7 +561,7 @@ def acceptSwitch(self, node, memo):
561561

562562
def acceptSynchronized(self, node, memo):
563563
""" Accept and process a synchronized statement (not a modifier). """
564-
module = self.parents(lambda x:x.isModule).next()
564+
module = next(self.parents(lambda x:x.isModule))
565565
module.needsSyncHelpers = True
566566
if node.parent.type == tokens.MODIFIER_LIST:
567567
# Skip any synchronized modifier
@@ -743,7 +743,7 @@ def acceptPrePost(self, node, memo):
743743
name = node.firstChildOfType(tokens.IDENT).text
744744
handler = self.configHandler('VariableNaming')
745745
rename = handler(name)
746-
block = self.parents(lambda x:x.isMethod).next()
746+
block = next(self.parents(lambda x:x.isMethod))
747747
if pre:
748748
left = name
749749
else:
@@ -768,7 +768,7 @@ def acceptBitShiftRight(self, node, memo):
768768
self.fs = 'bsr(' + FS.l + ', ' + FS.r + ')'
769769
self.left, self.right = visitors = factory(parent=self), factory()
770770
self.zipWalk(node.children, visitors, memo)
771-
module = self.parents(lambda x:x.isModule).next()
771+
module = next(self.parents(lambda x:x.isModule))
772772
module.needsBsrFunc = True
773773

774774
def acceptBitShiftRightAssign(self, node, memo):
@@ -777,7 +777,7 @@ def acceptBitShiftRightAssign(self, node, memo):
777777
self.fs = FS.l + ' = bsr(' + FS.l + ', ' + FS.r + ')'
778778
self.left, self.right = visitors = factory(parent=self), factory()
779779
self.zipWalk(node.children, visitors, memo)
780-
module = self.parents(lambda x:x.isModule).next()
780+
module = next(self.parents(lambda x:x.isModule))
781781
module.needsBsrFunc = True
782782

783783
def acceptClassConstructorCall(self, node, memo):
@@ -853,12 +853,12 @@ def acceptStaticArrayCreator(self, node, memo):
853853

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

859859
def acceptSuperConstructorCall(self, node, memo):
860860
""" Accept and process a super constructor call. """
861-
cls = self.parents(lambda c:c.isClass).next()
861+
cls = next(self.parents(lambda c:c.isClass))
862862
fs = 'super(' + FS.l + ', self).__init__(' + FS.r + ')'
863863
self.right = self.factory.expr(fs=fs, left=cls.name)
864864
return self.right

java2python/lang/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
# instances.
4848
#
4949

50-
from cStringIO import StringIO
50+
from io import StringIO
5151

5252
from antlr3 import ANTLRStringStream as StringStream, CommonTokenStream as TokenStream
5353
from antlr3.tree import CommonTreeAdaptor, CommonTree
@@ -184,13 +184,13 @@ def innerDump(root, offset):
184184
args[2] = ' ' + self.colorText(ttyp, token.text)
185185
for com in self.selectComments(start, seen):
186186
for line in self.colorComments(com):
187-
print >> fd, '{0}{1}'.format(indent, line)
188-
print >> fd, nform.format(*args)
187+
print('{0}{1}'.format(indent, line), file=fd)
188+
print(nform.format(*args), file=fd)
189189
for child in root.getChildren():
190190
innerDump(child, offset+1)
191191
for com in self.selectComments(root.tokenStopIndex, seen):
192192
for line in self.colorComments(com):
193-
print >> fd, '{0}{1}'.format(indent, line)
193+
print('{0}{1}'.format(indent, line), file=fd)
194194
innerDump(self, level)
195195

196196
def dumps(self, level=0):

java2python/lang/selector.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,11 +90,11 @@ def __init__(self, **attrs):
9090
self.attrs = attrs
9191
## we support strings so that the client can refer to the
9292
## token name that way instead of via lookup or worse, integer.
93-
if isinstance(attrs.get('type'), (basestring, )):
93+
if isinstance(attrs.get('type'), str):
9494
self.attrs['type'] = getattr(tokens, attrs.get('type'))
9595

9696
def __call__(self, tree):
97-
items = self.attrs.items()
97+
items = list(self.attrs.items())
9898
token = tree.token
9999

100100
def match_or_call(k, v):
@@ -106,7 +106,7 @@ def match_or_call(k, v):
106106
yield tree
107107

108108
def __str__(self):
109-
items = self.attrs.items()
109+
items = list(self.attrs.items())
110110
keys = ('{}={}'.format(k, v) for k, v in items if v is not None)
111111
return 'Token({})'.format(', '.join(keys))
112112

@@ -126,7 +126,7 @@ def __call__(self, tree):
126126
matches = tree.children[self.key]
127127
except (IndexError, ):
128128
return
129-
if not isinstance(matches, (list, )):
129+
if not isinstance(matches, list):
130130
matches = [matches]
131131
for child in matches:
132132
yield child

java2python/mod/basic.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def maybeSynchronizedMethod(method):
137137

138138

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

142142

143143
def getBsrSrc():
@@ -237,7 +237,7 @@ def zopeImplementsClassHead(obj):
237237
def moveStaticExpressions(cls):
238238
name = '{}.'.format(cls.name) # notice the dot
239239
exprs = [child for child in cls.children if child.isExpression and name in str(child)]
240-
module = cls.parents(lambda x:x.isModule).next()
240+
module = next(cls.parents(lambda x:x.isModule))
241241
for expr in exprs:
242242
cls.children.remove(expr)
243243
newExpr = module.factory.expr(fs=name + '{right}', right=expr)

java2python/mod/include/overloading.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
if sys.version_info[0] < 3:
4343
# Make the environment more like Python 3.0
4444
__metaclass__ = type
45-
from itertools import izip as zip
45+
4646

4747

4848
class overloaded:

0 commit comments

Comments
 (0)