Search code examples
c#clrabstract-syntax-treecilvm-implementation

create c# parser, AST tree, CIL and run it in virtual machine


description of my problem is to create:

  1. C# parser
  2. compose AST tree from parsed input .cs file
  3. create CIL/bytecode representation of program
  4. create VM
  5. execute code stored as "bytecode" - make the parsed program work

So basically I need to write my own language with all the "stuff" around.

I'll write my sample program which I want to run. I know how to create C# parser to handle this program and compose AST tree.

I've also found CIL reference http://en.csharp-online.net/CIL_Instruction_Set so I can save my AST as CIL code (hopefully there will be no problem). But my question is, how can I test this CIL before I have my virtual machine? Can I use C# CLR? And how?

How can I create virtual machine executing CIL instructions in C#? Can I "force" C# program to run CIL instructions?

Is my idea, the steps, correct? Should I avoid writing AST to bytecode using CIL instructions?

My ideas were inspired by .NET http://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/CLR_diag.svg/400px-CLR_diag.svg.png

Thank you for any replies which will help me to find the correct way of solving this problem.

P.S. I need to implement everything by myself

EDIT

I've found this: http://msdn.microsoft.com/en-us/magazine/cc136756.aspx

http://www.codeproject.com/Articles/3778/Introduction-to-IL-Assembly-Language

http://www.codeguru.com/csharp/.net/net_general/il/article.php/c4635#Array1

It might solve my problem. I'll give it a try.


Solution

  • I would do the tasks from your list out of order: First I'd write the a simple VM (CIL interpreter) in C#. I would test that with little CIL sequences created 'by hand'. Once I had that working I would build a small compiler that emits a tiny subset of CIL corresponding to what the VM supports and test that. Then I would incrementally refine this until I had the support I desired.