2011-10-03 49 views
1

我正在編寫腳本語言,我已經完成了詞法分析器和解析器,並且我想在內存中動態執行。C#解釋器執行的最佳途徑

可以說我有類似

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); 

這將是執行這個片段的最佳方式i'ved試圖

1)操作碼伊爾代(if語句工作,我不能讓或其他任何東西打印功能) 2)RunSharp,我不能做的功能,導致我可以做到這一點,我不知道如何。

如果有人能指出我正確的方向!

小有一點代碼將幫助 鏈接資源(不是像IronPython的),也將是不錯的

+0

1)操作碼生成:通過您的分析器轉換表達式樹來分析你的語言。表達式對象是http://msdn.microsoft.com/library/bb356138.aspx。表達式對象樹編譯:http://msdn.microsoft.com/library/bb345362.aspx。你製作了YourLanguegeProvider。 – BLUEPIXY

+0

thxs我會檢查出來 編輯: 謝謝!看起來它會適合我的需要,也節省瀏覽時間,是否有可能做的功能,然後使他們被稱爲,我不知道如何與操作碼或runharp – Steven

回答

3

您的腳本語言像JavaScript,如果它在內存中動態編譯。

例如:

//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 
*/ 
    } 
}