Compiler compiler in C#

2020-05-21 05:44发布

问题:

I'm looking for a customizable parser and/or lexer that can allow me to build a custom syntax checker in C#. Essentially the user will enter code a line of code (custom), and the syntax checker will be able respond if it is written correctly or not.

回答1:

That's Irony. Be sure to read the discussion, because it's a lot going on there. Use the old release from November or use the latest, but then make sure you understand what is in that release and what not.

For most things, the November release should work well (using it in a pet project).

Irony allows to build an abstract syntax tree (AST) from any grammar you can define directly in C# code. It also supports evaluation (i.e. interpreting the code), and it's even not hard to build code from it. Or, well, convert it into a DLR (Dynamic Language Runtime) AST.



回答2:

Here are few things which you might want to consider using:

  • Irony
  • Oslo / MGrammar
  • C# Flex
  • CocoR
  • ANTLR
  • GPPG


回答3:

I like ANTLR, it supports C# as well as Java, Python, C, etc etc. The pros of using ANTLR arethe very good documentation (examples, books, tutorials, etc) and wide usage.



回答4:

From here:

LINQPad uses a number of third-party components within the UI. The query editor uses Actipro's SyntaxEditor control (a very polished product); the "IntelliSense" features rely on a combination of libraries from Actipro Software and ICSharpCode (from the SharpDevelop project).

I've not used any of the products mentioned in that excerpt (apart from LINQPad - which I highly recommend!) but thought it might start moving you in the right direction perhaps.



回答5:

If what the user is entering is a line of code corresponding to traditional expressions, you can hand-code a recursive descent parser for this in a few hours max and be done with it.

If your input is a fragment of a complex language (e.g., you want to accept a line of C# code) you'll need a much strong parser and a parser generator is recommended.

However, you'll find that most parser generators do not offer you a good way to parse a piece of the language that you define, but you can hack you way around that by defining the root grammar rule to mention the nonterminals that correspond to the "lines" that you are willing to accept.



回答6:

I use a recursive descent parser which combines parsing and lexing that I wrote from scratch in C# in my own language project. I found it made writing grammar rules relatively easy. See here for an example grammar and see here for the unit tests.



回答7:

I've been using QWhale .NET Editor. It's not free, but it's fairly good.