Skip to content

Commit 19c5cdf

Browse files
jbretteclaude
andcommitted
Fix three CLI bugs found while exercising j2py
Directory mode wrote to the input tree. path.join discards the output directory when the walked name is absolute, so `j2py src/ out/` left out/ empty and scattered .py files through src/. Mirror the tree with a path relative to the input directory instead. A directory walk accumulated configs. One options object is reused for every file and runTransform inserted into the original list, so file N was translated with files 1..N-1's configs as well -- visible as "duplicate argument 'cls' in function definition" from the second file onward. Copy the list. Unparseable input crashed. The lexer and parser report their own errors and then recover, leaving a tree that transformAST cannot walk (AttributeError on a None token). buildAST now checks the error counts and raises JavaSyntaxError; the CLI reports the file and the count and exits 1. An unreadable file reports through logging rather than printing to stdout, where it corrupted piped output. Also drop two dead statements: an elif that can never be true, and a module.name assignment made after the source was already rendered. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FfdD42ztfjZth9nXpRduKE
1 parent f8d18cb commit 19c5cdf

2 files changed

Lines changed: 32 additions & 15 deletions

File tree

‎java2python/cli.py‎

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@
88
from argparse import ArgumentParser, ArgumentTypeError
99
from collections import defaultdict
1010
from importlib.metadata import PackageNotFoundError, version as packageVersion
11-
from logging import getLevelNamesMapping, exception, warning, info, basicConfig
11+
from logging import getLevelNamesMapping, error, exception, warning, info, basicConfig
1212
from os import path, makedirs, walk
1313
from time import time
1414
from io import IOBase
1515

16-
from java2python.compiler import Module, buildAST, transformAST
16+
from java2python.compiler import JavaSyntaxError, Module, buildAST, transformAST
1717
from java2python.config import Config
1818
from java2python.lib import escapes
1919

@@ -74,12 +74,15 @@ def runOneOrMany(options):
7474
options.inputfile = fullname
7575
info('opening %s', fullname)
7676
if outfile and outfile != '-' and not isinstance(outfile, IOBase):
77-
full = path.abspath(path.join(outfile, fullname))
78-
head, tail = path.split(full)
79-
tail = path.splitext(tail)[0] + '.py'
80-
if not path.exists(head):
77+
# path.join discards the output directory when the
78+
# walked name is absolute, so mirror the tree with a
79+
# path relative to the input directory instead.
80+
relname = path.relpath(fullname, infile)
81+
full = path.join(outfile, path.splitext(relname)[0] + '.py')
82+
head = path.dirname(full)
83+
if head and not path.exists(head):
8184
makedirs(head)
82-
options.outputfile = path.join(head, tail)
85+
options.outputfile = full
8386
runTransform(options)
8487
return 0
8588
else:
@@ -96,10 +99,11 @@ def runTransform(options):
9699
filein = options.inputfile
97100
if options.outputfile and not isinstance(options.outputfile, IOBase):
98101
fileout = options.outputfile
99-
elif fileout != filedefault:
100-
fileout = '%s.py' % (path.splitext(filein)[0])
101102

102-
configs = options.configs
103+
# A copy: one options object is reused for every file of a directory
104+
# walk, and inserting into the original accumulates the configs of
105+
# each file that came before.
106+
configs = list(options.configs)
103107
if options.configdirs and not isinstance(filein, IOBase):
104108
for configdir in options.configdirs:
105109
dirname = configFromDir(filein, configdir)
@@ -115,13 +119,15 @@ def runTransform(options):
115119
else:
116120
source = sys.stdin.read()
117121
except OSError as exc:
118-
code, msg = exc.args[0:2]
119-
print('IOError: {}.'.format(msg))
120-
return code
122+
error('could not read %s: %s', filein, exc.strerror or exc)
123+
return exc.errno or 1
121124

122125
timed['comp']
123126
try:
124127
tree = buildAST(source)
128+
except (JavaSyntaxError, ) as exc:
129+
error('could not parse %s: %s', filein, exc)
130+
return 1
125131
except (Exception, ) as exc:
126132
exception('exception while parsing')
127133
return 1
@@ -158,7 +164,6 @@ def runTransform(options):
158164
print(file=sys.stderr)
159165

160166
if not options.skipsource:
161-
module.name = path.splitext(filein)[0] if filein != '-' else '<stdin>'
162167
if fileout == filedefault:
163168
print(source)
164169
else:

‎java2python/compiler/__init__.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,25 @@
99
from java2python.lang import Lexer, Parser, StringStream, TokenStream, TreeAdaptor
1010

1111

12+
class JavaSyntaxError(Exception):
13+
""" Raised when the Java source cannot be parsed. """
14+
15+
1216
def buildAST(source):
13-
""" Returns an AST for the given source. """
17+
""" Returns an AST for the given source.
18+
19+
The lexer and parser report their own errors to stderr and then
20+
recover, which leaves a tree that later stages cannot walk, so the
21+
error count is checked here instead of failing further downstream.
22+
"""
1423
lexer = Lexer(StringStream(source))
1524
parser = Parser(TokenStream(lexer))
1625
adapter = TreeAdaptor(lexer, parser)
1726
parser.setTreeAdaptor(adapter)
1827
scope = parser.javaSource()
28+
errors = lexer.getNumberOfSyntaxErrors() + parser.getNumberOfSyntaxErrors()
29+
if errors:
30+
raise JavaSyntaxError(f'{errors} syntax error(s) in Java source')
1931
return scope.tree
2032

2133

0 commit comments

Comments
 (0)