Skip to main content

pytunia

Jasmin, the assembler for the Java Virtual Machine, in Python.

pytunia is a Python port of Jasmin 2.4. It translates assembly code for the Java Virtual Machine (.j files) into Java class files, and it produces byte-for-byte the same class files as the original jasmin.jar. Its error messages are identical, too.

pytunia is a library written in pure Python, with no dependencies. It needs Python 3.9 or newer.

Installation

pip install pytunia

The latest development version can be installed from GitHub:

pip install git+https://github.com/karlstroetmann/pytunia

Example

HelloWorld.j:

.class public HelloWorld
.super java/lang/Object

.method public static main([Ljava/lang/String;)V
    .limit stack 2
    getstatic java/lang/System/out Ljava/io/PrintStream;
    ldc "Hello, World!"
    invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
    return
.end method
import pytunia

pytunia.assemble("HelloWorld.j")    # writes HelloWorld.class
$ java HelloWorld
Hello, World!

Usage

import pytunia

# assemble a file and write the class file; returns its path
path = pytunia.assemble("Count.j")                       # examples/Count.class
path = pytunia.assemble("Count.j", output_dir="build")   # build/examples/Count.class

# assemble source text in memory; nothing is written to disk
class_name, data = pytunia.assemble_string(source)       # ("examples/Count", b"\xca\xfe...")

(Here Count.j defines the class examples.Count.)

assemble(source_file, output_dir=None, *, line_numbers=False, encoding="utf-8")

  • Places the class file below output_dir (default: the current directory) in subdirectories for its package, as Jasmin does. output_dir can therefore be used directly as a class path: java -cp build examples.Count. Missing directories are created.
  • line_numbers=True generates a line number table that refers to the lines of the assembly source (option -g of Jasmin), so that Java stack traces show the line numbers of the .j file.
  • Returns the path of the class file as a pathlib.Path.

assemble_string(source, name=None, *, line_numbers=False)

  • Returns the class name (in the internal form of the JVM, e.g. "examples/Count") and the class file as bytes.
  • name is the file name used in error messages and for the class file's SourceFile attribute. Without it, error messages show <string> and the attribute is <class name>.j.

Errors

If the source contains errors, both functions raise pytunia.AssemblyError. Its attribute errors is a list of pytunia.Diagnostic objects, each with filename, line, message, source_line and column. str(error) is exactly the error output of jasmin.jar:

try:
    pytunia.assemble("Bad.j")
except pytunia.AssemblyError as e:
    print(e)
Bad.j:4: JAS Error: bipush value exceed size of byte.
  bipush 300 
             ^
Bad.j: Found 1 errors

A file that cannot be read or written raises the usual OSError, for example FileNotFoundError. The functions print nothing, and they can be called from several threads at once.

Command line

For debugging, the command line of the Java version is available. It is not installed as a command:

python3 -m pytunia [-d <outpath>] [-g] [-e <encoding>] <file> [<file> ...]

Low-level interface

pytunia.ClassFile has the methods of the Java class jasmin.ClassFile (read_jasmin, error_count, get_class_name, write). Errors are collected in its list diagnostics.

Compatibility with Jasmin

Why the output is identical

These details of the Java version had to be reproduced exactly:

  • Parsing. Jasmin's parser is an LALR(1) parser generated by Java CUP. pytunia uses the very same parse tables, extracted from the generated parser.java, and a port of the CUP runtime, including its error recovery. It therefore accepts the same language and reports syntax errors at the same places.
  • Constant pool order. Jasmin stores constant pool entries in a java.util.Hashtable keyed by strings and writes them in the table's enumeration order. pytunia reproduces this order (String.hashCode, bucket layout, rehashing).
  • Number formatting. Some of these keys contain numbers formatted with Float.toString and Double.toString. These are not always the shortest representation, so the JDK 8 algorithm (sun.misc.FloatingDecimal) is ported as well.
  • Java strings and number types. Strings are handled as UTF-16 code units, and constants are written in modified UTF-8. Numbers keep their Java type (Integer, Long, Float, Double), since Jasmin's behaviour depends on it. Number parsing follows Java's rules.

Quirks of Jasmin 2.4 are kept on purpose, because changing them would change the output. For example:

  • iinc gets a wide prefix unless the increment is exactly 127 (a typo in Jasmin's jas.IincOperand).
  • Variable substitution with .set name value / $name does not work: the substituted token is taken as .method.
  • ldc2_w 0.1 stores the float value 0.1f as a double. Write 0.1d to get the exact double.
  • After a syntax error, the error recovery drops one token.

Known differences

  • When .stack frames share an offset, Java prints a stack trace (UNEXPECTED JAS ERROR …) before reporting the error. pytunia prints only the first two lines of it. The result (error, no class file) is the same.
  • The default source encoding is always UTF-8. Java up to version 17 uses the platform encoding instead.
  • Java keeps some state of the assembler in static fields. pytunia keeps it in the objects of a single assembly instead, so assemblies can run in parallel.

Development

How the code is organized

The structure follows the Java sources of Jasmin. Class names are kept, and method names are converted to snake_case.

Python module Java original
pytunia/api.py, pytunia/diagnostics.py the library interface (assemble, assemble_string, AssemblyError); new in pytunia
pytunia/main.py jasmin.Main: command line handling
pytunia/classfile.py jasmin.ClassFile: called by the parser to build the class
pytunia/scanner.py jasmin.Scanner, ScannerUtils, ReservedWords
pytunia/parser.py jasmin.parser (the CUP-generated parser) and the CUP runtime java_cup.runtime.lr_parser
pytunia/parser_tables.py, pytunia/sym.py parse tables and symbol numbers (generated, see below)
pytunia/insninfo.py jasmin.InsnInfo: instruction table
pytunia/jas/ the jas package that writes class files (constant pool, instructions, Code attribute, annotations, StackMap frames, ...)
pytunia/javacompat.py emulation of the Java library behaviour that the output depends on

Tests

python3 -m unittest discover -s tests

tests/cases/ contains about 90 Jasmin files. They cover every instruction form, all directives (fields with constant values, annotations, stack maps, inner classes, debug information, ...), character encodings, and many kinds of errors. tests/expected/ holds the results of jasmin.jar for each case: class files, standard output, standard error and exit status.

  • tests/test_api.py assembles every case with assemble() and assemble_string(). The class files must be identical to those of the Java version, and for sources with errors str(AssemblyError) must be identical to its error output.
  • tests/test_cli.py runs the command line (python3 -m pytunia) on every case and compares the class files, standard output, standard error and exit status. It also checks the number formatting against Java for about 10,000 values.

Running the tests needs neither Java nor Jasmin.

Comparing with the Java version

The following tools need the original Jasmin 2.4 (jasmin-2.4.zip from the Jasmin project on SourceForge). By default they look for it in a directory jasmin-2.4 next to the repository.

To regenerate the expected test results (needs java and javac):

python3 tests/make_expected.py ../jasmin-2.4/jasmin.jar

tools/fuzz_compare.py runs randomly mutated Jasmin files through both versions and reports any file where they differ:

python3 tools/fuzz_compare.py --jar ../jasmin-2.4/jasmin.jar -n 20 tests/cases/*.j

If Jasmin's grammar changes, rebuild its parser with CUP first and then regenerate the parse tables from the generated Java sources:

python3 tools/extract_tables.py ../jasmin-2.4/src/jasmin

License

Jasmin is distributed under a BSD-style license, and pytunia keeps it; see LICENSE.txt, which also lists the credits.

Metadata

Release files for pytunia 0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pytunia 0.1
File Size Uploaded Provenance Actions
pytunia-0.1.tar.gz 266.9 kB With provenance Details for pytunia-0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pytunia 0.1
File Interpreter ABI Platform Actions
pytunia-0.1-py3-none-any.whl Python 3 none any Details for pytunia-0.1-py3-none-any.whl

Total release size: 339.2 kB

Release files / pytunia-0.1.tar.gz

Download URL pytunia-0.1.tar.gz
Size 266.9 kB
Tags Source
SHA-256 checksum
How to use checksums
ebef837ed5336fca443f1ce7fd0d35ea55121fb4da150060ef1fcac0f55c6c71
BLAKE2b-256 checksum
How to use checksums
650f6816ffc8e0d6fc4661da7dc2162082940f2b071478fe98b706b1a30be8d0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Release files / pytunia-0.1-py3-none-any.whl

Download URL pytunia-0.1-py3-none-any.whl
Size 72.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
619d2c7ccc5b079edc42bf95a1d327996b8205c85f44e4488bf6a5a1bf610ec2
BLAKE2b-256 checksum
How to use checksums
6bcf33ba262b1d8e7c4f6cbc678be30ca44198f1216f03e6a8d9afb3a61d23c5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Security for pytunia 0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pytunia-0.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page