[英]ANTLR: What is the fastest way to get grammar tree?
What is the fastest (smaller code) way to get grammar tree ? 什么是最快的(较小代码)获取语法树的方法?
I am trying to get grammar tree. 我正在尝试获取语法树。 I've generated C# code based on my simple grammar: 我已经基于简单的语法生成了C#代码:
grammar MyPascal;
options
{
language=CSharp3;
output=AST;
}
operator: (block | ID);
block : BEGIN operator* END;
BEGIN :'begin';
END :'end';
ID :('a'..'z')+;
WS :( ' '
| '\t'
| '\r'
| '\n'
) {$channel=HIDDEN;};
When i'am using ANTLR works for simple input text like: 当我使用ANTLR时,适用于简单的输入文本,例如:
input.txt:
begin
abs
qwe
begin
begin
end
end
end
i get nice picture of grammar tree. 我得到了语法树的漂亮图片。
Now i'am wonder if there any simple way to get tree structure of my "program" from C# without writing 1000s lines of code. 现在,我想知道是否有任何简单的方法可以从C#中获取我的“程序”的树形结构,而无需编写1000s的代码行。
Here i'am trying to get grammar tree: 在这里我试图得到语法树:
class Program
{
static void Main(string[] args)
{
MyPascalLexer lex = new MyPascalLexer(new ANTLRFileStream(@"M:\input.txt"));
CommonTokenStream tokens = new CommonTokenStream(lex);
MyPascalParser g = new MyMyPascalParser(tokens);
MyPascalParser.myprogram_return X = g.myprogram();
Console.WriteLine(X.Tree); // Writes: nill
Console.WriteLine(X.Start); // Writes: [@0,0:4='begin',<4>,1:0]
Console.WriteLine(X.Stop); // Writes: [@35,57:57='end',<19>,12:2]
}
}
You'll have to "tell" ANTLR to build an AST, opposed to just a flat stream of tokens (simple parse tree). 您将不得不“告诉” ANTLR来构建AST,而不是简单的令牌流(简单的分析树)。
See this SO Q&A that shows how to do this in C#. 请参阅此SO Q&A ,其中展示了如何在C#中执行此操作。
Also, you should not use: 另外,您不应使用:
ID : ('a'..'z')*;
ie: let a lexer rule match an empty string, this might (or even will?) get you in trouble (it always matches!). 即:让词法分析器规则匹配一个空字符串,这可能(甚至会导致?)惹上麻烦(它总是匹配!)。 You'll want to let it match at least one character: 您需要让它至少匹配一个字符:
ID : ('a'..'z')+;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.