简体   繁体   中英

Best/fastest way to write a parser in c#

What is the best way to build a parser in c# to parse my own language? Ideally I'd like to provide a grammar, and get Abstract Syntax Trees as an output. Many thanks, Nestor

I've had good experience with ANTLR v3 . By far the biggest benefit is that it lets you write LL(*) parsers with infinite lookahead - these can be quite suboptimal, but the grammar can be written in the most straightforward and natural way with no need to refactor to work around parser limitations, and parser performance is often not a big deal (I hope you aren't writing a C++ compiler), especially in learning projects.

It also provides pretty good means of constructing meaningful ASTs without need to write any code - for every grammar production, you indicate the "crucial" token or sub-production, and that becomes a tree node. Or you can write a tree production.

Have a look at the following ANTLR grammars (listed here in order of increasing complexity) to get a gist of how it looks and feels

I've played wtih Irony . It looks simple and useful.

您可以研究Mono C#编译器的源代码。

虽然它还处于早期测试阶段,但奥斯陆建模语言和微软的MGrammar工具正在展现出一些希望。

I would also take a look at SableCC . Its very easy to create the EBNF grammer. Here is a simple C# calculator example.

有一个简短的文件在这里就在这里构建一个LL(1)语法分析器,当然你也可以使用一个发电机了。

Lex and yacc are still my favorites. Obscure if you're just starting out, but extremely simple, fast, and easy once you've got the lingo down.

You can make it do whatever you want; generate C# code, build other grammars, emulate instructions, whatever.

It's not pretty, it's a text based format and LL1, so your syntax has to accomodate that.

On the plus side, it's everywhere. There are great O'reilly books about it, lots of sample code, lots of premade grammars, and lots of native language libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM