我正在使用支持node.js的antlr4(4.13)JS解析器,当我运行代码时,我收到如下错误:
const tree = parser.MyStartRule();
^
TypeError: parser.MyStartRule is not a function
我不知道如何解决它。这是我的代码:
语法: https://github.com/antlr/grammars-v4/blob/master/angelscript/angelscript.g4 仅用于测试(不要更改任何内容,只需将“grammarangelscript;”替换为“grammarfns;”)
要运行的代码:(parse.js)
import antlr4 from 'antlr4';
import fnsLexer from './fnsLexer.js';
import fnsParser from './fnsParser.js';
import MyGrammarListener from './fnsListener.js';
const input = "func name(x) { say(x); } name("Hello world");";
const chars = new antlr4.InputStream(input);
const lexer = new fnsLexer(chars);
const tokens = new antlr4.CommonTokenStream(lexer);
const parser = new fnsParser(tokens);
const tree = parser.MyStartRule();
运行命令:node parse.js
还有我的package.json:
{
"name": "fns",
"version": "1.0.0",
"description": "",
"main": "babel.config.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"antlr4": "^4.13.1-patch-1"
}
}
出现此错误后,我尝试使用chat-gpt来解决这个问题,甚至下载了4.9.0版本(这是chat捕获的最新版本),但没有任何帮助。
正如 kaby 在评论中提到的:
MyStartRule()
不是语法的解析器规则。是script
:
grammar angelscript;
script
: (
import_
| enum_
| typdef
| class_
| mixin_
| interface_
| funcdef
| virtprop
| var_
| func_
| namespace
| ';'
)+ EOF
;
用它代替:
const tree = parser.script();