Question

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.

Was it helpful?

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.

OTHER TIPS

Assuming you already have written C# parser and IL code emitter (which by itself is no small task, look at how long the C# specification is), the normal way to execute the code would be to create an assembly: an .exe or .dll file that contains the IL code along with the necessary metadata. You could then use that the same way as any other .Net assembly.

To create the assembly in C#, you can use System.Reflection.Emit. Specifically, start with AppDomain.DefineDynamicAssembly().

Another option, if you don't want to create whole assembly, just a single method, is to use DynamicMethod.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top