Skip to main content

Ljavalang

PyPI Python GitHub Actions

English | 中文

Enhanced fork of javalang — fixes core AST bugs, adds Java 9-22 syntax support, zero external dependencies.

Installation

pip install ljavalang

The package name is ljavalang on PyPI, but the import name remains javalang — fully compatible with upstream.

Quick Start

>>> import javalang
>>> tree = javalang.parse.parse('package com.example; class Test {}')
>>> tree.package.name
'com.example'
>>> tree.types[0].name
'Test'

New Syntax Examples

Java 14 switch expression:

>>> code = '''
... class T {
...     int m(int x) {
...         return switch(x) {
...             case 1 -> 10;
...             case 2 -> 20;
...             default -> 0;
...         };
...     }
... }'''
>>> tree = javalang.parse.parse(code)
>>> tree.types[0].body[0].body[0].expression
SwitchExpression

Java 16 record:

>>> tree = javalang.parse.parse('record Point(int x, int y) {}')
>>> tree.types[0]
RecordDeclaration

Java 21 record pattern:

>>> code = '''
... class T {
...     record Point(int x, int y) {}
...     void m(Object o) {
...         switch(o) {
...             case Point(int x, int y) -> System.out.println(x + y);
...             default -> {}
...         }
...     }
... }'''
>>> javalang.parse.parse(code)  # parses successfully

Chained method calls (core bug fix):

>>> code = 'class T { void m(String cmd) { Runtime.getRuntime().exec(cmd); } }'
>>> tree = javalang.parse.parse(code)
>>> # Upstream incorrectly places exec in a flat selectors list
>>> # Ljavalang correctly builds nested MethodInvocation qualifier chain

Visitor Pattern

from javalang.visitor import JavaVisitor

class MethodCollector(JavaVisitor):
    def __init__(self):
        self.methods = []

    def visit_MethodDeclaration(self, node):
        self.methods.append(node.name)
        self.generic_visit(node)

collector = MethodCollector()
collector.visit(tree)
print(collector.methods)  # ['foo', 'bar', ...]

Token Position Range

from javalang.tokenizer import tokenize

code = 'int x = 42;'
for token in tokenize(code):
    r = token.position.range
    print(f'{token.value} -> code[{r.start}:{r.stop}] = {code[r]!r}')
# int -> code[0:3] = 'int'
# x -> code[4:5] = 'x'

AST Node end_position

>>> code = 'class T { void m() { try { int x = 1; } catch (Exception e) {} } }'
>>> tree = javalang.parse.parse(code)
>>> tree.types[0].end_position
Position(line=1, column=66, range=slice(65, 66, None))

Supported Java Syntax

Full list (click to expand)

Java 8 (upstream)

  • Lambda expressions
  • Method references
  • Type annotations
  • Interface default/static methods
  • Generic try-with-resources
  • Receiver parameter (Inner.this)

Java 9

  • try-with-resources with effectively final variables
  • module-info.java (module / open module / requires / exports / opens / uses / provides)
  • Interface private methods
  • Anonymous class diamond operator

Java 10-11

  • var local variable type inference
  • var in for-each / try-with-resources
  • var in lambda parameters

Java 14

  • Switch expression (case X -> arrow syntax)
  • Switch expression at expression level (return switch(...))
  • Multi-label case (case 1, 2, 3 ->)
  • yield statement
  • Pattern matching instanceof (obj instanceof String s)

Java 15

  • Text block ("""...""" triple-quoted strings)

Java 16

  • record class declaration
  • Local record / enum (inside method body)
  • Record as class member

Java 17

  • sealed class / interface
  • permits clause
  • non-sealed modifier

Java 21

  • Pattern matching switch (case String s ->)
  • Record pattern deconstruction (case Point(int x, int y) ->)
  • Nested record patterns
  • case null matching

Java 22

  • Unnamed variable _
  • Unnamed lambda parameters

Key Changes from Upstream

Category Details
Core bug fix Chained method calls now produce nested MethodInvocation qualifier chains instead of flat selectors lists
Bug fixes 6 upstream bugs fixed: #90/#117 (DecimalInteger), #145 (Character token), #81/#112 (type annotations), #141 (void return_type)
New features end_position for 6 AST nodes, Visitor class, Position.range, tokenize return_index, ReceiverParameter, prefix/postfix operators
Dependencies Zero external dependencies (removed six)
Packaging Modern pyproject.toml (PEP 621), setuptools ≥64.0
Tests 112 pytest tests (Python 3.9-3.12 CI matrix)

Project Structure

Ljavalang/
├── pyproject.toml    # Packaging (PEP 621)
├── javalang/
│   ├── parse.py      # Entry: parse() / parse_expression()
│   ├── parser.py     # Recursive descent parser (~2800 lines)
│   ├── tokenizer.py  # Lexer (~700 lines)
│   ├── tree.py       # AST node definitions (~340 lines)
│   ├── visitor.py    # Visitor pattern traversal
│   └── test/         # 112 test cases
└── docs/
    ├── changelog.md
    └── architecture.md

Credits

Based on c2nes/javalang by Chris Thunes.

License

MIT License

Metadata

Release files for ljavalang 2.1.4

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

Source distribution (sdist)

Source distribution for ljavalang 2.1.4
File Size Uploaded Provenance Actions
ljavalang-2.1.4.tar.gz 47.4 kB Without provenance Details for ljavalang-2.1.4.tar.gz

Built distribution (wheel)

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

Total release size: 96.4 kB

Release files / ljavalang-2.1.4.tar.gz

Download URL ljavalang-2.1.4.tar.gz
Size 47.4 kB
Tags Source
SHA-256 checksum
How to use checksums
07aa8a6c78e3fe4461685c12c24fbd6ab4e80ba93678197bf9fa5079c7b17e54
BLAKE2b-256 checksum
How to use checksums
f7066ab8ac878c9fe645a205dbdd3c3f27aa0b73726433e87e102c6757377e8f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Release files / ljavalang-2.1.4-py3-none-any.whl

Download URL ljavalang-2.1.4-py3-none-any.whl
Size 48.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2701e5e4b7ce0f59bf4c74f94a5f0c9232e97b7f168a40afcd6d3ea10d59f860
BLAKE2b-256 checksum
How to use checksums
00c5353751b4f0c57839739a63bed1ea62556fee1caeb5b01d216aa273e9f4e2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Security for ljavalang 2.1.4

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

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