antlr4、jison、nearley 和 pegjs 都是用于构建自定义语言解析器的工具,常用于开发配置文件、查询语言、模板引擎或领域特定语言(DSL)。它们将文法定义转换为可执行的 JavaScript 代码,但底层算法、维护状态和适用场景差异巨大。antlr4 是工业级标准,适合复杂语言;jison 是老牌 LALR 生成器,现已停止维护;nearley 基于 Earley 算法,擅长处理模糊文法;pegjs 采用 PEG 语法,上手最快,但社区已转向其分支 peggy。
在前端架构中,解析器生成器(Parser Generator)常用于处理自定义配置文件、查询语言或模板引擎。antlr4、jison、nearley 和 pegjs 是四个主流选择,但它们的底层算法和维护状态差异巨大。让我们从工程实战角度对比它们的区别。
antlr4 使用独立的 .g4 文件定义文法,需通过 CLI 工具生成 JS 代码。
// antlr4: Expr.g4 文件
grammar Expr;
parse: expr EOF;
expr: expr '*' expr | expr '+' expr | INT;
INT: [0-9]+;
jison 允许在 JS 文件中直接嵌入文法,类似 Yacc。
// jison: 直接在 JS 中定义
var parser = new Parser({
lex: { rules: [["\\d+", "return 'INT';"]] },
bnf: { "expr": [["expr '+' expr", "$$ = $1 + $3;"]] }
});
nearley 使用独立的 .ne 文件或 JS 对象定义文法。
// nearley: grammar.ne 编译后
const grammar = nearley.Grammar.fromCompiled({
rules: [{ name: "expr", symbols: [{ literal: "+" }] }]
});
pegjs 使用专门的 .pegjs 语法,结构最简洁。
// pegjs: 文法字符串
const grammar = `
start = sum
sum = left:number '+' right:number { return left + right; }
number = [0-9]+ { return parseInt(text()); }
`;
const parser = peg.generate(grammar);
antlr4 必须预生成解析器代码。
antlr4 库。// antlr4: 使用生成的类
const chars = new antlr4.InputStream(input);
const lexer = new ExprLexer(chars);
const tokens = new antlr4.CommonTokenStream(lexer);
const parser = new ExprParser(tokens);
const tree = parser.parse();
jison 可预生成也可运行时初始化。
// jison: 初始化后解析
var parser = new Parser(grammar);
const result = parser.parse("1 + 2");
nearley 通常预编译文法为 JS 对象。
Parser 并 feed 数据。// nearley: 流式解析
const parser = new nearley.Parser(grammar);
parser.feed("1 + 2");
const result = parser.results[0];
pegjs 支持运行时动态生成解析器。
// pegjs: 运行时生成
const parser = peg.generate(grammar);
const result = parser.parse("1 + 2");
antlr4 提供强大的错误监听器接口。
// antlr4: 自定义错误监听
class ErrorListener extends antlr4.ErrorListener {
syntaxError(recognizer, offendingSymbol, line, col, msg, e) {
console.log(`错误在第 ${line} 行`);
}
}
jison 遇到错误通常直接抛出异常。
// jison: 捕获异常
try {
parser.parse("1 +");
} catch (e) {
console.log("解析失败", e.message);
}
nearley 解析失败时返回空结果数组。
results.length。// nearley: 检查结果
if (parser.results.length === 0) {
console.log("无匹配结果");
}
pegjs 抛出详细的异常对象,包含位置信息。
// pegjs: 捕获详细错误
try {
parser.parse("1 +");
} catch (e) {
console.log(`错误在 ${e.location.start.line}:${e.location.start.column}`);
}
antlr4 由 ANTLR 团队官方维护,更新频繁。
jison 社区已停止维护,最后更新在数年前。
nearley 维护状态稳定,更新节奏适中。
pegjs 官方仓库活跃度下降,社区推荐转向 peggy。
peggy 是 pegjs 的分支,API 兼容且修复了已知问题。peggy 包。| 特性 | antlr4 | jison | nearley | pegjs |
|---|---|---|---|---|
| 算法 | LL(*) | LALR(1) | Earley | PEG |
| 文法文件 | .g4 (独立) | JS 对象/文件 | .ne (独立) | .pegjs (独立) |
| 左递归 | ✅ 支持 | ❌ 不支持 | ✅ 支持 | ❌ 不支持 |
| 错误恢复 | ✅ 强大 | ❌ 基础 | ⚠️ 有限 | ⚠️ 基础 |
| 维护状态 | 🟢 活跃 | 🔴 停止 | 🟢 稳定 | 🟡 转向 peggy |
| 学习成本 | 🔴 高 | 🟡 中 | 🟢 低 | 🟢 低 |
antlr4 是重型武器 🏗️ — 适合构建编译器、复杂查询语言或需要多语言生成的企业级项目。如果团队有编译原理基础,这是最稳妥的选择。
jison 是历史遗留 🕸️ — 除非维护旧代码,否则不要在新项目中使用。它的功能已被更现代的工具覆盖。
nearley 是灵活中间件 🧩 — 适合需要处理歧义文法或不想受 LALR 限制的场景。它的 JavaScript 原生支持让前端开发者上手更快。
pegjs (或 peggy) 是轻量首选 🪶 — 适合快速构建配置文件解析器、简单 DSL 或原型验证。文法简洁,调试方便,是前端领域最常用的选择。
最终建议:对于大多数前端 DSL 场景,优先考虑 peggy(pegjs 的现代分支);如果文法极其复杂,选择 antlr4;避免使用 jison。
选择 nearley 如果你的文法存在歧义或需要无限 lookahead 能力。它比 antlr4 轻量,比 pegjs 更灵活,适合中等复杂度的 DSL,且支持 JavaScript 原生编写文法。
选择 antlr4 如果你需要构建企业级复杂语言(如 SQL、Solidity),且可能需要生成多种语言目标(Java、C# 等)。它学习曲线陡峭,但功能最强大,适合长期维护的核心基础设施项目。
选择 pegjs 如果你需要快速构建简单的 DSL 或配置文件解析器,且追求极简的文法 syntax。注意官方维护已放缓,社区推荐转向其活跃分支 peggy,两者 API 基本兼容。
不建议在新项目中使用 jison。它基于 LALR(1) 算法,适合类 C 语言结构,但社区已停止维护多年。如果维护旧代码库遇到它,建议计划迁移到 nearley 或 peggy。
nearley is a simple, fast and powerful parsing toolkit. It consists of:
nearley is a streaming parser with support for catching errors gracefully and providing all parsings for ambiguous grammars. It is compatible with a variety of lexers (we recommend moo). It comes with tools for creating tests, railroad diagrams and fuzzers from your grammars, and has support for a variety of editors and platforms. It works in both node and the browser.
Unlike most other parser generators, nearley can handle any grammar you can define in BNF (and more!). In particular, while most existing JS parsers such as PEGjs and Jison choke on certain grammars (e.g. left recursive ones), nearley handles them easily and efficiently by using the Earley parsing algorithm.
nearley is used by a wide variety of projects:
nearley is an npm staff pick.
Please visit our website https://nearley.js.org to get started! You will find a tutorial, detailed reference documents, and links to several real-world examples to get inspired.
Please read this document before working on nearley. If you are interested in contributing but unsure where to start, take a look at the issues labeled "up for grabs" on the issue tracker, or message a maintainer (@kach or @tjvr on Github).
nearley is MIT licensed.
A big thanks to Nathan Dinsmore for teaching me how to Earley, Aria Stewart for helping structure nearley into a mature module, and Robin Windels for bootstrapping the grammar. Additionally, Jacob Edelman wrote an experimental JavaScript parser with nearley and contributed ideas for EBNF support. Joshua T. Corbin refactored the compiler to be much, much prettier. Bojidar Marinov implemented postprocessors-in-other-languages. Shachar Itzhaky fixed a subtle bug with nullables.
If you are citing nearley in academic work, please use the following BibTeX entry.
@misc{nearley,
author = "Kartik Chandra and Tim Radvan",
title = "{nearley}: a parsing toolkit for {JavaScript}",
year = {2014},
doi = {10.5281/zenodo.3897993},
url = {https://github.com/kach/nearley}
}