C# Compiler – Do You Need to Know CIL to Make a Compiler for .NET?

ccompilermanaged-codenetprogramming-languages

Assume one wants to create a simple .NET language, or slightly more difficult, a compiler for an existing .NET language. Do you absolutely need to be familiar with the CIL (Common Intermediate Language) to implement a compiler? And do you have to translate the syntax of your language to CIL by hand? Or is there another (more preferable) way? If not, what is the best way to learn CIL and especially to learn how to translate High-Level code to CIL?

Best Answer

Of course you can generate C# or any other higher level language code instead of targeting CIL directly.

It is common to implement compilers as eDSLs on top of meta-languages. You can take, say, a decent Scheme implementation for .NET, or a more heavyweight language, like Nemerle, and build up your compiler as a set of macros on top of a host language, with a syntax front-end at the very top of this hierarchy.

As you've mentioned "translating the syntax to CIL", you're likely having a somewhat distorted view on how compilers should work. Normally there are many more steps in between parser and code generation, and it does not make any sense to do everything in a single pass.

And, of course, if your language semantics is significantly different from the host language, for an efficient implementation you'd still be much better off with generating CIL directly (or via a sequence of intermediate languages).

Learning CIL is not a big deal at all: everything you have to know is available on MSDN.

And here is a trivial example of building a compiler on top of a meta-language - you can easily do it with any Lisp.