nearley vs antlr4 vs pegjs vs jison
JavaScript 解析器生成器架构选型指南
nearleyantlr4pegjsjison

JavaScript 解析器生成器架构选型指南

antlr4、jison、nearley 和 pegjs 都是用于构建自定义语言解析器的工具,常用于开发配置文件、查询语言、模板引擎或领域特定语言(DSL)。它们将文法定义转换为可执行的 JavaScript 代码,但底层算法、维护状态和适用场景差异巨大。antlr4 是工业级标准,适合复杂语言;jison 是老牌 LALR 生成器,现已停止维护;nearley 基于 Earley 算法,擅长处理模糊文法;pegjs 采用 PEG 语法,上手最快,但社区已转向其分支 peggy。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
nearley11,897,0803,737-1986 年前MIT
antlr42,402,92519,0383.09 MB1,1022 年前BSD-3-Clause
pegjs748,0974,904-11710 年前MIT
jison102,1894,379-1619 年前MIT

JavaScript 解析器生成器:antlr4 vs jison vs nearley vs pegjs

在前端架构中,解析器生成器(Parser Generator)常用于处理自定义配置文件、查询语言或模板引擎。antlr4、jison、nearley 和 pegjs 是四个主流选择,但它们的底层算法和维护状态差异巨大。让我们从工程实战角度对比它们的区别。

📝 文法定义方式:声明式 vs 编程式

antlr4 使用独立的 .g4 文件定义文法,需通过 CLI 工具生成 JS 代码。

  • 文法与代码分离,适合大型团队协作。
  • 支持 Lexer 和 Parser 分层定义。
// antlr4: Expr.g4 文件
grammar Expr;
parse: expr EOF;
expr: expr '*' expr | expr '+' expr | INT;
INT: [0-9]+;

jison 允许在 JS 文件中直接嵌入文法,类似 Yacc。

  • 文法与动作代码混合,适合小型工具。
  • 使用 LALR(1) 算法,文法冲突需手动解决。
// jison: 直接在 JS 中定义
var parser = new Parser({
  lex: { rules: [["\\d+", "return 'INT';"]] },
  bnf: { "expr": [["expr '+' expr", "$$ = $1 + $3;"]] }
});

nearley 使用独立的 .ne 文件或 JS 对象定义文法。

  • 支持正则表达式直接嵌入文法。
  • 基于 Earley 算法,无需担心左递归问题。
// nearley: grammar.ne 编译后
const grammar = nearley.Grammar.fromCompiled({
  rules: [{ name: "expr", symbols: [{ literal: "+" }] }]
});

pegjs 使用专门的 .pegjs 语法,结构最简洁。

  • 文法即代码,无需单独生成步骤(可运行时编译)。
  • 基于 PEG 算法,顺序匹配,无歧义。
// pegjs: 文法字符串
const grammar = `
  start = sum
  sum = left:number '+' right:number { return left + right; }
  number = [0-9]+ { return parseInt(text()); }
`;
const parser = peg.generate(grammar);

⚙️ 解析执行模型:生成代码 vs 运行时编译

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");

⚠️ 错误处理机制:容错 vs 严格

antlr4 提供强大的错误监听器接口。

  • 可自定义错误恢复策略,继续解析后续内容。
  • 适合 IDE 语法高亮等需要容错的场景。
// 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 团队官方维护,更新频繁。

  • 多语言支持(Java, C#, Python, JS 等)。
  • 社区庞大,文档齐全,适合长期项目。

jison 社区已停止维护,最后更新在数年前。

  • 存在未修复的 Bug,不建议新项目使用。
  • 仅适合维护遗留系统。

nearley 维护状态稳定,更新节奏适中。

  • 社区活跃,插件生态丰富(如 nearley-railroad)。
  • 适合中等规模 DSL 项目。

pegjs 官方仓库活跃度下降,社区推荐转向 peggy。

  • peggy 是 pegjs 的分支,API 兼容且修复了已知问题。
  • 新项目建议直接使用 peggy 包。

📊 核心差异对比表

特性antlr4jisonnearleypegjs
算法LL(*)LALR(1)EarleyPEG
文法文件.g4 (独立)JS 对象/文件.ne (独立).pegjs (独立)
左递归✅ 支持❌ 不支持✅ 支持❌ 不支持
错误恢复✅ 强大❌ 基础⚠️ 有限⚠️ 基础
维护状态🟢 活跃🔴 停止🟢 稳定🟡 转向 peggy
学习成本🔴 高🟡 中🟢 低🟢 低

💡 选型建议总结

antlr4 是重型武器 🏗️ — 适合构建编译器、复杂查询语言或需要多语言生成的企业级项目。如果团队有编译原理基础,这是最稳妥的选择。

jison 是历史遗留 🕸️ — 除非维护旧代码,否则不要在新项目中使用。它的功能已被更现代的工具覆盖。

nearley 是灵活中间件 🧩 — 适合需要处理歧义文法或不想受 LALR 限制的场景。它的 JavaScript 原生支持让前端开发者上手更快。

pegjs (或 peggy) 是轻量首选 🪶 — 适合快速构建配置文件解析器、简单 DSL 或原型验证。文法简洁,调试方便,是前端领域最常用的选择。

最终建议:对于大多数前端 DSL 场景,优先考虑 peggy(pegjs 的现代分支);如果文法极其复杂,选择 antlr4;避免使用 jison。

如何选择: nearley vs antlr4 vs pegjs vs jison

  • nearley:

    选择 nearley 如果你的文法存在歧义或需要无限 lookahead 能力。它比 antlr4 轻量,比 pegjs 更灵活,适合中等复杂度的 DSL,且支持 JavaScript 原生编写文法。

  • antlr4:

    选择 antlr4 如果你需要构建企业级复杂语言(如 SQL、Solidity),且可能需要生成多种语言目标(Java、C# 等)。它学习曲线陡峭,但功能最强大,适合长期维护的核心基础设施项目。

  • pegjs:

    选择 pegjs 如果你需要快速构建简单的 DSL 或配置文件解析器,且追求极简的文法 syntax。注意官方维护已放缓,社区推荐转向其活跃分支 peggy,两者 API 基本兼容。

  • jison:

    不建议在新项目中使用 jison。它基于 LALR(1) 算法,适合类 C 语言结构,但社区已停止维护多年。如果维护旧代码库遇到它,建议计划迁移到 nearley 或 peggy。

nearley的README

nearley ↗️

JS.ORG npm version

nearley is a simple, fast and powerful parsing toolkit. It consists of:

  1. A powerful, modular DSL for describing languages
  2. An efficient, lightweight Earley parser
  3. Loads of tools, editor plug-ins, and other goodies!

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.

Documentation

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.

Contributing

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.

Citing nearley

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}
}