Skip to content

Commit e7196ea

Browse files
jbretteclaude
andcommitted
Add the j2p Claude Code plugin
A grammar-driven translator and a model are each wrong in different places: j2py never hallucinates structure but tracks no types, so everything type-dependent comes out broken in predictable ways. The plugin pairs them -- run the parser, then repair the known gaps. plugin/ holds the plugin (skill java2python, command /j2p:translate), and the repository root doubles as a marketplace so it installs with `claude plugin install j2p@java2python`. scripts/j2py.sh resolves the translator from $J2PY_HOME, else the checkout it ships in, else a j2py on PATH, preferring a checkout so local edits are what run. It looks for uv at ~/.local/bin as well as on PATH, which a non-interactive shell often lacks. The skill's substance is the list of what j2py cannot get right without types, each item verified against real output: string concatenation, dropped imports and unmapped library types, Java's truncating %, fields that become shared class attributes, and collapsed overloads. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FfdD42ztfjZth9nXpRduKE
1 parent 19c5cdf commit e7196ea

8 files changed

Lines changed: 303 additions & 26 deletions

File tree

‎.claude-plugin/marketplace.json‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
3+
"name": "java2python",
4+
"description": "The java2python Claude Code plugin: translate Java source to Python with the j2py compiler.",
5+
"owner": {
6+
"name": "jbrette",
7+
"url": "https://github.com/jbrette/java2python"
8+
},
9+
"plugins": [
10+
{
11+
"name": "j2p",
12+
"description": "Translate Java source to Python with the java2python (j2py) compiler, then repair what a grammar-driven translator cannot get right on its own. The parser handles structure, control flow and operators; the model fixes what needs type knowledge, such as string concatenation, the Java standard library and integer remainder.",
13+
"author": {
14+
"name": "java2python contributors",
15+
"url": "https://github.com/jbrette/java2python"
16+
},
17+
"category": "development",
18+
"homepage": "https://github.com/jbrette/java2python",
19+
"license": "MIT",
20+
"keywords": ["java", "python", "translation", "transpiler", "migration", "j2py"],
21+
"source": "./plugin"
22+
}
23+
]
24+
}

‎CLAUDE.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,18 @@ Configuration (`config/__init__.py`): `Config` wraps an ordered list of config m
5353

5454
Runtime helpers: when the visitor sees certain constructs it sets a flag on the module (`needsBsrFunc` for `>>>`, `needsJavaDivFunc` for `/` and `/=`, `needsSyncHelpers`, `needsAbstractHelpers`), and a module prologue handler in `mod/basic.py` inlines the source of the matching function from `mod/include/` into the output. Java `/` becomes `jdiv(a, b)`, which truncates toward zero for ints, because types aren't tracked. Interfaces become `ABC` subclasses with `@abstractmethod`.
5555

56-
Output post-processing: `moduleOutputHandlers` includes `basic.outputSubs`, which applies the regex pairs in `<typeName>OutputSubs` (e.g. `moduleOutputSubs` in `config/default.py`, which maps `System.out.println` to `print`) to the generated text.
56+
## Claude Code plugin
57+
58+
`plugin/` is a Claude Code plugin named `j2p` (manifest in
59+
`plugin/.claude-plugin/plugin.json`; the repository root is also a marketplace
60+
via `.claude-plugin/marketplace.json`). It ships the `java2python` skill and
61+
the `/j2p:translate` command, both of which shell out to
62+
`plugin/scripts/j2py.sh`. That script resolves the translator from
63+
`$J2PY_HOME`, else this checkout (preferring `uv run`, falling back to
64+
`python3 bin/j2py`), else a `j2py` on `PATH`. `claude plugin validate .`
65+
checks both manifests. The skill's value is the list of things j2py cannot
66+
get right without types -- keep it in sync with the real behavior.
67+
68+
## Output post-processing
69+
70+
`moduleOutputHandlers` includes `basic.outputSubs`, which applies the regex pairs in `<typeName>OutputSubs` (e.g. `moduleOutputSubs` in `config/default.py`, which maps `System.out.println` to `print`) to the generated text.

‎doc/todo.md‎

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,52 +11,49 @@ Status of the Python 3.14 / uv modernization and what is still open.
1111
- Generated code targets Python 3.14+: `python3` shebang, no `__future__`
1212
imports, `class X:`, `super()`, `ABC` interfaces, `int` for `long`, `0o` octal
1313
literals, Java integer division via an inlined `jdiv()` helper.
14-
- All 100 `test/*.java` programs translate, compile, and run without errors on
15-
Python 3.14.8. The selector unit tests pass.
16-
- The full `cd test && make` suite has been run against a JDK (Temurin 25):
17-
100/100 `[PASS]`, with the Python output diffing clean against the Java
18-
output. `make selectors` passes (11 tests).
14+
- The full `cd test && make` suite has been run against a JDK: all 107
15+
`test/*.java` programs compile, translate, and run, with the Python output
16+
diffing clean against the Java output. `make selectors` passes (11 tests).
17+
- CLI fixes: a directory walk now writes under the output directory instead
18+
of beside the input (`path.join` discards it for absolute names), each file
19+
of a walk gets its own config list instead of accumulating the previous
20+
files' configs, and unreadable or unparseable input reports an error and an
21+
exit code instead of a traceback (`JavaSyntaxError` from `buildAST`).
22+
- A Claude Code plugin lives in `plugin/`; see CLAUDE.md.
23+
- Labeled `break` and `continue` are translated. A jump a bare keyword can
24+
express still emits one; the rest raise a generated per-label exception
25+
that the labeled statement catches (`java2python/compiler/visitor.py`,
26+
`basic.maybeLabelClasses`). Covered by `test/Break2-4.java`,
27+
`test/Continue3-5.java` and `test/ForEach1.java`.
1928

2029
### To Do
2130

22-
1. **Labeled `break` and `continue`.** Python has no labeled loop control, so
23-
`acceptBreak` and `acceptContinue` drop the label and emit a bare `break` /
24-
`continue` (`java2python/compiler/visitor.py:375` and `:406`), each warning
25-
`Detected unhandled break statement with label; generated code incorrect.`
26-
The statement label itself (`foo:`) is dropped too, so `test/Break0.java`
27-
translates to a plain `break` inside the `while`. That test passes only
28-
because its `break foo;` targets the innermost loop; a label naming an
29-
*outer* loop from a nested one, or a labeled block, generates silently wrong
30-
code. Fixing it needs a real rewrite -- a sentinel flag checked by each
31-
enclosing loop, a label-specific exception raised and caught around the
32-
labeled statement, or hoisting the labeled loop into a function so the jump
33-
becomes a `return`. A test with a nested loop would catch regressions.
34-
2. **Java `%` semantics.** Java `%` truncates toward zero, while Python `%`
31+
1. **Java `%` semantics.** Java `%` truncates toward zero, while Python `%`
3532
floors, so the results differ when an operand is negative. Consider a
3633
`jmod()` helper alongside `jdiv()`
3734
(`java2python/compiler/visitor.py`, `java2python/mod/include/`).
38-
3. **Division readability.** Every `/` becomes `jdiv(a, b)`, even for floats,
35+
2. **Division readability.** Every `/` becomes `jdiv(a, b)`, even for floats,
3936
because types aren't tracked. Possible improvements: emit plain `/` when an
4037
operand is a float literal or a float/double cast, or track declared local
4138
variable types.
42-
4. **Parser regeneration.** The `java2python/lang/Makefile` flow (ANTLR 3.1.3
39+
3. **Parser regeneration.** The `java2python/lang/Makefile` flow (ANTLR 3.1.3
4340
tool, then rewriting the imports to the vendored runtime) is untested.
4441
Regenerating would also bring back the `__main__` blocks that import
4542
`antlr3.main`, which isn't vendored.
46-
5. **`test/configs/defaults.py`.** It defines `outputSubs`, but the code
43+
4. **`test/configs/defaults.py`.** It defines `outputSubs`, but the code
4744
reads `moduleOutputSubs`, so those substitutions probably never apply.
4845
Rename it and check that the tests still pass.
49-
6. **Generated-code style.** Possible cleanups: emit f-strings instead of
46+
5. **Generated-code style.** Possible cleanups: emit f-strings instead of
5047
`.format()` for `String.format` and drop redundant `int()`/`str()` casts on
5148
literals (flagged by `ruff --select UP` on the test output).
5249
`@classmethod` for static methods could become `@staticmethod` when `cls`
5350
isn't used.
54-
7. **Optional dependency on zope.interface.** It is only needed by
51+
6. **Optional dependency on zope.interface.** It is only needed by
5552
`test/configs/defaults.py` and the `zope*` handlers in `mod/basic.py`.
5653
Consider dropping those handlers.
57-
8. **Tooling.** Add ruff configuration and CI (GitHub Actions with
54+
7. **Tooling.** Add ruff configuration and CI (GitHub Actions with
5855
`astral-sh/setup-uv`, a JDK, and `make -C test`). Possibly port the
5956
Makefile harness to pytest.
60-
9. **Docs.** `doc/usage.md`, `doc/translation.md`, and
57+
8. **Docs.** `doc/usage.md`, `doc/translation.md`, and
6158
`doc/customization.md` still show Python 2-era output in places, and the
6259
links still point at the upstream `natural/java2python` repository.

‎plugin/.claude-plugin/plugin.json‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"name": "j2p",
3+
"version": "0.1.0",
4+
"description": "Translate Java source to Python with the java2python (j2py) compiler, then repair what a grammar-driven translator cannot get right on its own. The parser handles structure, control flow and operators; the model fixes what needs type knowledge, such as string concatenation, the Java standard library and integer remainder.",
5+
"author": {
6+
"name": "java2python contributors",
7+
"url": "https://github.com/jbrette/java2python"
8+
},
9+
"homepage": "https://github.com/jbrette/java2python",
10+
"repository": "https://github.com/jbrette/java2python",
11+
"license": "MIT",
12+
"keywords": ["java", "python", "translation", "transpiler", "migration", "j2py"]
13+
}

‎plugin/README.md‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# j2p -- the java2python Claude Code plugin
2+
3+
Translate Java to Python from inside Claude Code, using the
4+
[java2python](https://github.com/jbrette/java2python) compiler for the
5+
structure and the model for the parts that need type knowledge.
6+
7+
## What is in it
8+
9+
| Component | Name | Purpose |
10+
| --- | --- | --- |
11+
| Skill | `java2python` | Loads when a task involves translating Java to Python. Explains how to run j2py and, more importantly, what to check in its output. |
12+
| Command | `/j2p:translate <file>` | Translate a named file, directory or snippet now. |
13+
| Script | `scripts/j2py.sh` | Runs the translator, finding it wherever it lives. |
14+
15+
## Install
16+
17+
```
18+
/plugin install j2p --marketplace jbrette/java2python
19+
```
20+
21+
From a checkout of this repository, where the repository root is itself the
22+
marketplace:
23+
24+
```bash
25+
claude plugin marketplace add .
26+
claude plugin install j2p@java2python
27+
```
28+
29+
`claude plugin validate ./plugin` checks the manifest without installing
30+
anything.
31+
32+
## Finding the translator
33+
34+
`scripts/j2py.sh` resolves j2py in this order:
35+
36+
1. `$J2PY_HOME`, if set, which must be a java2python checkout.
37+
2. The checkout the plugin ships inside (`plugin/` lives at its root).
38+
3. A `j2py` already on `PATH`.
39+
40+
A checkout wins over an installed `j2py` so that local edits to the translator
41+
are what actually run. With a checkout it prefers `uv run`, falling back to
42+
`python3 bin/j2py` when uv is not installed.
43+
44+
## Why the model is still in the loop
45+
46+
j2py parses Java with an ANTLR grammar, so it gets the structure right and
47+
never hallucinates it. It tracks no types, so `"n is " + i` -- fine in Java --
48+
comes out as a Python `TypeError`, `new ArrayList<>()` comes out as an
49+
undefined name, and `%` keeps Python's sign rules instead of Java's. The skill
50+
lists these, and the fix is a reading pass over the generated file, not a
51+
rewrite of it.

‎plugin/commands/translate.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
description: Translate a Java file, directory or snippet to Python with j2py, then fix what the translator cannot infer without types.
3+
argument-hint: <Foo.java | src/ > [output]
4+
allowed-tools: ["Bash(${CLAUDE_PLUGIN_ROOT}/scripts/j2py.sh:*)", "Read", "Write", "Edit", "Glob", "Grep"]
5+
---
6+
7+
Translate `$ARGUMENTS` from Java to Python.
8+
9+
Follow the `java2python` skill. In short:
10+
11+
1. Run the translator rather than hand-writing the Python:
12+
`${CLAUDE_PLUGIN_ROOT}/scripts/j2py.sh $ARGUMENTS`
13+
2. Read the result against the skill's "What you have to fix" list -- string
14+
concatenation, the Java standard library, `%` on negatives, fields that
15+
became class attributes, lost overloads -- and repair each one.
16+
3. Run the Python. If a JDK is on PATH, run the Java too and diff the output.
17+
4. Report what you changed after the translation and anything left uncertain.
18+
19+
If no argument was given, ask which file or directory to translate.

‎plugin/scripts/j2py.sh‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#!/usr/bin/env bash
2+
# Runs the java2python translator, whichever way it happens to be available,
3+
# and forwards every argument to it. Resolution order:
4+
#
5+
# 1. $J2PY_HOME -- an explicit java2python checkout
6+
# 2. the checkout this plugin ships inside
7+
# 3. a j2py already on PATH
8+
#
9+
# A checkout is preferred over an installed j2py so that local edits to the
10+
# translator are what actually run.
11+
set -euo pipefail
12+
13+
here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
14+
15+
findUv() {
16+
if command -v uv >/dev/null 2>&1; then
17+
command -v uv
18+
elif [ -x "$HOME/.local/bin/uv" ]; then
19+
# uv installs here, and a non-interactive shell may not have it on PATH.
20+
echo "$HOME/.local/bin/uv"
21+
fi
22+
}
23+
24+
isCheckout() {
25+
[ -f "$1/java2python/cli.py" ] && [ -f "$1/pyproject.toml" ]
26+
}
27+
28+
home=${J2PY_HOME:-}
29+
if [ -n "$home" ]; then
30+
if ! isCheckout "$home"; then
31+
echo "j2py: J2PY_HOME=$home is not a java2python checkout" >&2
32+
exit 2
33+
fi
34+
elif isCheckout "$here/../.."; then
35+
home=$(cd -- "$here/../.." && pwd)
36+
fi
37+
38+
if [ -n "$home" ]; then
39+
uv=$(findUv)
40+
if [ -n "$uv" ]; then
41+
exec "$uv" run --project "$home" j2py "$@"
42+
fi
43+
# No uv: run from the checkout directly. This needs the dependencies
44+
# of any config the caller passes, but the translator itself has none.
45+
PYTHONPATH="$home${PYTHONPATH:+:$PYTHONPATH}" exec python3 "$home/bin/j2py" "$@"
46+
fi
47+
48+
if command -v j2py >/dev/null 2>&1; then
49+
exec j2py "$@"
50+
fi
51+
52+
cat >&2 <<'MSG'
53+
j2py: no java2python found.
54+
55+
Install it, or point the plugin at a checkout:
56+
57+
uv tool install java2python # or: pip install java2python
58+
J2PY_HOME=/path/to/java2python # a git checkout
59+
MSG
60+
exit 127

‎plugin/skills/java2python/SKILL.md‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
---
2+
name: java2python
3+
description: >-
4+
Translate Java source to Python using the java2python (j2py) compiler, then
5+
repair what a grammar-driven translator cannot get right on its own. Use when
6+
asked to translate or port Java to Python, convert a .java file to .py, run
7+
j2py, or migrate a Java class, package or project to Python. The parser does
8+
the mechanical work -- classes, control flow, labeled jumps, interfaces,
9+
operators, comments -- and the remaining fixes need type knowledge the parser
10+
does not have: string concatenation, the Java standard library, integer
11+
remainder, and instance fields.
12+
version: 0.1.0
13+
---
14+
15+
# Java to Python with j2py
16+
17+
j2py parses real Java with an ANTLR grammar, so it never guesses at
18+
structure. It also tracks no types at all, so everything that depends on
19+
knowing whether a value is an `int`, a `String` or an `ArrayList` comes out
20+
wrong. Translating well means running the parser first and then fixing the
21+
type-dependent parts by hand.
22+
23+
Do not hand-translate a file that j2py can parse. Its output is a correct
24+
skeleton, and starting from it is faster and less error-prone than rewriting
25+
the structure yourself.
26+
27+
## Running it
28+
29+
```bash
30+
${CLAUDE_PLUGIN_ROOT}/scripts/j2py.sh Foo.java # to stdout
31+
${CLAUDE_PLUGIN_ROOT}/scripts/j2py.sh Foo.java Foo.py # to a file
32+
${CLAUDE_PLUGIN_ROOT}/scripts/j2py.sh src/ out/ # whole tree
33+
cat Foo.java | ${CLAUDE_PLUGIN_ROOT}/scripts/j2py.sh - # from stdin
34+
```
35+
36+
Useful flags: `-s -j` dumps the Java AST instead of source (`-p` the Python
37+
block tree, `-t` the lexer tokens) when output looks wrong and you need to see
38+
what the parser saw; `-c MODULE` and `-d DIR` add configuration modules;
39+
`-l info` reports timings. A non-zero exit means the file did not parse or
40+
could not be read -- the message says which, and the parser prints the
41+
offending line and column before it.
42+
43+
The script finds the translator itself: `$J2PY_HOME`, else the checkout it
44+
ships in, else a `j2py` on PATH.
45+
46+
## What it gets right
47+
48+
Classes, interfaces (as `ABC` with `@abstractmethod`), enums, constructors,
49+
fields, static methods (as `@classmethod`), all the loops, `switch` (as an
50+
if/elif chain), `try`/`catch`/`finally`, `synchronized`, labeled `break` and
51+
`continue`, the ternary, casts, `>>>`, Java's truncating integer division (as
52+
an inlined `jdiv()` helper), comments and Javadoc.
53+
54+
## What you have to fix
55+
56+
Check each of these in the output. They are not bugs to report; they are the
57+
known cost of translating without a type checker.
58+
59+
**String concatenation.** `"i is " + i` is valid Java and a `TypeError` in
60+
Python. Every `+` that mixes a string with anything else needs an f-string.
61+
62+
**The Java standard library.** Imports are dropped and the class names survive
63+
as-is, so `new ArrayList<String>()` becomes `ArrayList()` and raises
64+
`NameError`. Map the types and their methods onto Python equivalents: `List`
65+
to `list`, `Map` to `dict`, `StringBuilder` to a list of parts or an f-string,
66+
`.add()` to `.append()`, `.put(k, v)` to `d[k] = v`, `.size()` -- which does
67+
become `len(...)` -- and so on.
68+
69+
**Integer remainder.** Java's `%` truncates toward zero and Python's floors,
70+
so they disagree whenever an operand is negative: `-7 % 3` is `-1` in Java and
71+
`2` in Python. j2py emits a bare `%`. Fix it where a negative operand is
72+
reachable. (`/` is already handled, by `jdiv()`.)
73+
74+
**Instance fields.** A field initialized at its declaration becomes a class
75+
attribute, which every instance then shares. Move mutable ones into
76+
`__init__`.
77+
78+
**Overloads.** Python keeps only the last method of a given name. Merge them
79+
into one with default or variadic arguments.
80+
81+
**Generics** are erased, and inner, anonymous and nested classes, threads and
82+
annotations are best-effort. Read them closely.
83+
84+
## Verify, do not assume
85+
86+
Translate, then actually run the Python. If a JDK is available, run the Java
87+
too and diff the output -- that is what the project's own test suite does:
88+
89+
```bash
90+
javac Foo.java && java Foo > java.txt
91+
python3 Foo.py > py.txt
92+
diff -u java.txt py.txt
93+
```
94+
95+
Without a JDK, at minimum `python3 -c "import ast; ast.parse(open('Foo.py').read())"`
96+
and then read the output against the Java with the list above in hand.
97+
98+
For a tree of files, translate the whole tree in one run, then work through
99+
the failures one file at a time rather than eyeballing all of them.

0 commit comments

Comments
 (0)