Skip to main content

Lesprima-python

PyPI version Python 3.11+

Enhanced fork of Kronuz/esprima-python — fixes core AST bugs, supports ES2018–ES2025 syntax.

特性

  • ES2018–ES2025 全覆盖 — async generators、optional chaining、nullish coalescing、private fields/methods、decorators、import attributes、using/await using 等
  • 22 个上游 bug 修复 — 修复 jquery/esprima 仓库中确认的 parser 正确性问题(yield 上下文、cover grammar、scope validation 等)
  • ESTree 兼容 AST — 输出格式遵循 ESTree 标准
  • JSX 支持 — 包含 Fragment <></> 语法
  • 151+ 测试通过 — 覆盖新特性、bug 修复和回归验证
  • Python 3.11+ — 现代化代码,移除 Python 2.x 遗留兼容

安装

pip install lesprima

Note: PyPI 包名为 lesprima,但 import 名称仍为 esprima(保持与上游兼容)。如果之前安装过上游 esprima,请先卸载:

pip uninstall esprima && pip install lesprima

快速开始

解析 JavaScript

import esprima

# 解析脚本
tree = esprima.parseScript('const answer = 42')
print(tree.toDict())

# 解析模块
tree = esprima.parseModule('import { foo } from "bar"; export default foo;')

# 自动检测模式
tree = esprima.parse('const x = 1')

Tokenize

import esprima

tokens = esprima.tokenize('const answer = 42')
for token in tokens:
    print(f'{token.type}: {token.value}')
# Keyword: const
# Identifier: answer
# Punctuator: =
# NumericLiteral: 42

遍历 AST

import esprima

tree = esprima.parseScript('function greet(name) { return "Hello, " + name; }')

# 使用 visitor
from esprima import visitor

class FunctionCollector(visitor.Visitor):
    def __init__(self):
        super().__init__()
        self.functions = []

    def visit_FunctionDeclaration(self, node):
        self.functions.append(node.id.name)
        return self.generic_visit(node)

collector = FunctionCollector()
collector.visit(tree)
print(collector.functions)  # ['greet']

支持的 ECMAScript 特性

版本 特性
ES2018 Async generators, for-await-of, Template literal revision
ES2019 Optional catch binding
ES2020 import.meta, Nullish coalescing ??, Optional chaining ?.
ES2021 Numeric separators 1_000, Logical assignment &&= `
ES2022 Top-level await, Static class fields, Static init block, Private fields #x
ES2023 Hashbang grammar #!
ES2025 Import Attributes with {}, using/await using, Decorators @expr
JSX Fragment <></>, elements, expressions

API

esprima.parse(code, options)

解析 JavaScript 代码,自动判断 script/module 模式。

tree = esprima.parse(code, {
    'sourceType': 'module',   # 'script' | 'module'
    'jsx': True,              # 启用 JSX 解析
    'loc': True,              # 包含位置信息
    'range': True,            # 包含起止索引
    'comment': True,          # 包含注释
    'tolerant': True,         # 容错模式
    'classProperties': True,  # 类属性(默认开启)
})

esprima.parseScript(code, options) / esprima.parseModule(code, options)

显式指定模式解析。

esprima.tokenize(code, options)

返回 token 列表。

与上游的区别

Lesprima-python 基于 Kronuz/esprima-python(ES2017),进行了以下改进:

  1. ES2018–ES2025 语法支持 — 新增 18 个语法特性
  2. 22 个 bug 修复 — 修复来自 jquery/esprima#issues 的确认 bug
  3. Python 3.11+ 兼容 — 移除 Python 2.x 兼容代码,修复 async/await 关键字冲突
  4. CI/CD — GitHub Actions 自动化测试(Python 3.11/3.12/3.13)

开发

# 克隆仓库
git clone https://github.com/LoRexxar/Lesprima-python.git
cd Lesprima-python

# 安装依赖
pip install -e .

# 运行测试
python -m pytest tests/ -v

许可证

BSD — 详见 LICENSE。

致谢

Metadata

Release files for lesprima 2.0.0

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

Source distribution (sdist)

Source distribution for lesprima 2.0.0
File Size Uploaded Provenance Actions
lesprima-2.0.0.tar.gz 65.3 kB Without provenance Details for lesprima-2.0.0.tar.gz

Built distribution (wheel)

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

Total release size: 138.4 kB

Release files / lesprima-2.0.0.tar.gz

Download URL lesprima-2.0.0.tar.gz
Size 65.3 kB
Tags Source
SHA-256 checksum
How to use checksums
38557a1ef2325c95dc9bf2095de8f0a270e75d6de35a3f0ea7522a489999a484
BLAKE2b-256 checksum
How to use checksums
128b0b49e9fe2fd5e8d47675b7c40707743fe2bd6566579ece1d498f99bb4575
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Release files / lesprima-2.0.0-py3-none-any.whl

Download URL lesprima-2.0.0-py3-none-any.whl
Size 73.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8ff9968ac47f6e28db52acd44d79cc34a63b90c3bf2d85b80935791b11113476
BLAKE2b-256 checksum
How to use checksums
87218dcf9c260c4a53931b046893890d13ac2de9e0e7c62a93c8e8f3dda0b731
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Security for lesprima 2.0.0

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.

Release history Release notifications | RSS feed

This release

2.0.0 This release

2 release files No 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