You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Antlr4与TypeScript:使用特定语法的Lexer和Parser时出现类型错误

TypeScript调用ANTLR生成的PL/SQL词法/解析器时的类型错误问题

语法生成步骤

# 清理并创建目录
rm -rf grammar
mkdir grammar

# 下载PL/SQL语法文件
curl --output grammar/PlSqlLexer.g4 https://raw.githubusercontent.com/antlr/grammars-v4/master/sql/plsql/PlSqlLexer.g4
curl --output grammar/PlSqlParser.g4 https://raw.githubusercontent.com/antlr/grammars-v4/master/sql/plsql/PlSqlParser.g4

# 生成TypeScript版本的词法/解析器
antlr4 -Dlanguage=TypeScript grammar/PlSqlLexer.g4
antlr4 -Dlanguage=TypeScript grammar/PlSqlParser.g4

示例代码

import antlr4 from 'antlr4';
import PlSqlLexer from './grammar/PlSqlLexer';
import PlSqlParser from './grammar/PlSqlParser';

const input = 'select * from dual';
const chars = new antlr4.CharStream(input);
const lexer = new PlSqlLexer(chars);
const tokens = new antlr4.CommonTokenStream(lexer); /* 类型错误1 */
const parser = new PlSqlParser(tokens);
const tree = parser.sql_script();
console.log(tree.toStringTree(null, parser)); /* 类型错误2 */

类型错误详情

  • 错误1:类型为PlSqlLexer的参数无法赋值给类型为Lexer的参数。PlSqlLexer缺少Lexer类型的以下属性:_input、_interp、text、line及另外18个属性。
  • 错误2:类型为PlSqlParser的参数无法赋值给类型为Parser的参数。PlSqlParser缺少Parser类型的以下属性:_input、_ctx、_interp、_errHandler及另外25个属性。

解决方案

1. 替换为官方TypeScript版ANTLR依赖

原antlr4包是JavaScript版本,类型定义存在兼容问题,需改用官方维护的TypeScript版本antlr4ts:

# 卸载旧依赖
npm uninstall antlr4
# 安装antlr4ts及对应的CLI工具
npm install antlr4ts
npm install -g antlr4ts-cli

2. 重新生成词法/解析器代码

使用antlr4ts命令重新生成TypeScript代码:

antlr4ts grammar/PlSqlLexer.g4
antlr4ts grammar/PlSqlParser.g4

3. 修正示例代码的导入与调用

import { CharStream, CommonTokenStream } from 'antlr4ts';
import PlSqlLexer from './grammar/PlSqlLexer';
import PlSqlParser from './grammar/PlSqlParser';

const input = 'select * from dual';
// 使用CharStream.fromString替代new CharStream
const chars = CharStream.fromString(input);
const lexer = new PlSqlLexer(chars);
const tokens = new CommonTokenStream(lexer);
const parser = new PlSqlParser(tokens);
const tree = parser.sql_script();
// toStringTree只需传入parser参数
console.log(tree.toStringTree(parser));

4. 版本一致性检查(可选)

确保全局安装的antlr4ts-cli与项目中antlr4ts包的版本完全一致,避免因版本差异导致的类型问题。

内容的提问来源于stack exchange,提问作者doberkofler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 07:10:10