我试图用C#解析JavaScript(ECMASCript)。C#,ANTLR,ECMAScript语法错误
我发现了如何创建新的项目下列指令: http://www.antlr.org/wiki/pages/viewpage.action?pageId=557075
所以我已经下载ANTLRWorks,ANTLR v3的,解压后ANTLR,创造了一个VS2010项目(.NET4),添加引用,检查并产生语法。
然后,我收到了很多的编译错误:
The type or namespace name 'AstParserRuleReturnScope' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'GrammarRule' could not be found (are you missing a using directive or an assembly reference?)
Stackoverlowed他们,并得到一个解决方案:antlr c# errors when integrating into VS2008
所以我已经下载了新的运行时,覆盖旧的和重新编译该项目,并有
The name 'HIDDEN' does not exist in the current context d:\Workspace.1\ScriptParser\ScriptParser\TestLexer.cs
好,作为推荐我已经改变了隐藏隐藏在下面的对话:[antlr-interest] How viable is the Csharp3 target? (more specific questions)
现在我试图解析输入。我发现了几个例子,写了下面的代码:
using Antlr.Runtime;
namespace ScriptParser
{
class Program
{
static void Main(string[] args)
{
var stream = new ANTLRStringStream("1+2");
var lexer = new TestLexer(stream);
var tokenStream = new CommonTokenStream(lexer);
var parser = new TestParser(tokenStream);
// what exactly should be here???
}
}
}
我的目标是与解析器ANTLR JavaScript文件,但它似乎会像我以为的不容易......
更新:
public expr : mexpr (PLUS^ mexpr)* SEMI!
;
:
正如Why are antlr3 c# parser methods private?建议我已通过添加“公共”使expr规则修改前修改Test.g语法
然后再生该代码,替换HIDDEN为隐藏(再次)和修改的代码如下:
var stream = new ANTLRStringStream("1+2");
var lexer = new TestLexer(stream);
var tokenStream = new CommonTokenStream(lexer);
var parser = new TestParser(tokenStream);
var result = parser.expr();
var tree = (CommonTree)result.Tree;
而不是在下面的生成的代码
崩溃就行root_0 = (object)adaptor.Nil();
try { DebugEnterRule(GrammarFileName, "expr");
DebugLocation(7, 0);
try
{
// d:\\Workspace.1\\ScriptParser\\ScriptParser\\Test.g:7:13: (mexpr (PLUS^mexpr)* SEMI !)
DebugEnterAlt(1);
// d:\\Workspace.1\\ScriptParser\\ScriptParser\\Test.g:7:15: mexpr (PLUS^mexpr)* SEMI !
{
root_0 = (object)adaptor.Nil();
DebugLocation(7, 15);
PushFollow(Follow._mexpr_in_expr31);
带有NullReferenceException消息,因为适配器为空。
我已通过添加
parser.TreeAdaptor = new CommonTreeAdaptor();
更新2解决它:
所以,最后我已经开始与我的主要任务:解析JavaScript的。
ANTLR highlights Chris Lambrou的ECMAScript语法。
所以我已经生成的词法分析器/分析器和用非常简单的JavaScript代码运行:
var f = function() { };
和解析失败,出现以下输出tree.ToStringTree():
<error: var q = function() { };>
结帐此前问题解答:http://stackoverflow.com/questions/4396080/antlr-3-3-c-sharp-tutorials – 2012-02-08 18:08:05
谢谢你的优秀教程。据我所知,语法规则应该转换为方法。我使用http://www.antlr.org/wiki/pages/viewpage.action?pageId=557075的语法和ANTLRWorks生成“expr”,“atom”和其他方法,但它们是私有的。 – 2012-02-08 18:29:46
谢谢亚历克斯。 W.r.t.私有方法(解析器规则),看另一个问答:http://stackoverflow.com/questions/6411520/why-are-antlr3-c-sharp-parser-methods-private – 2012-02-08 18:45:14