Steven
Steven

Reputation: 109

C# Best way for Interpreter Executing

I am writing a scripting language, i've done the lexer and parser and i want to dynamically execute in the memory.

Lets say i have something like

function Hello(World)
{
    Print(world);
}
var world = "World";
var boolean = true;
if(boolean == true)
{
    Print("True is True");
}
else
{
    Print("False is True");
}
Hello(world);

what would be the best way to execute this snippet i'ved tried

1) OpCode Il Generation (i couldn't get if statement to work or anything other than Print function) 2) RunSharp, i cannot do the functions cause the way i can do it i have no idea how.

If anyone could point me to the right direction!

Alittle Code will help Link to resource (not something like IronPython) would be also good

Upvotes: 1

Views: 1357

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

your script language like JavaScript,if it dynamic compile in memory.

example:

//csc sample.cs -r:Microsoft.JScript.dll
using System;
using System.CodeDom.Compiler;
using Microsoft.JScript;

class Sample {
    static public void Main(){
        string[] source = new string[] {
@"import System;
class JsProgram {
    function Print(mes){
        Console.WriteLine(mes);
    }
    function Hello(world){
        Print(world);
    }
    function proc(){
        var world = ""World"";
        var bool = true;
        if(bool == true){
            Print(""True is True"");
        }
        else{
            Print(""False is True"");
        }
        Hello(world);
    }
}"
        };
        var compiler = new JScriptCodeProvider();
        var opt      = new CompilerParameters();
        opt.ReferencedAssemblies.Add("System.dll");
        opt.GenerateExecutable = false;
        opt.GenerateInMemory = true;
        var result = compiler.CompileAssemblyFromSource(opt, source);
        if(result.Errors.Count > 0){
            Console.WriteLine("Compile Error");
            return;
        }
        var js = result.CompiledAssembly;
        dynamic jsProg = js.CreateInstance("JsProgram");
        jsProg.proc();
/*
True is True
World
*/
    }
}

Upvotes: 3

Xavjer
Xavjer

Reputation: 9224

If I understand you right, you want to compile and run the code on runtime? then you could try http://www.csscript.net/index.html , its an example on the same page linked.

Upvotes: 0

NickD
NickD

Reputation: 2646

generate c# source and compile it :-) http://support.microsoft.com/kb/304655

Upvotes: 0

Related Questions