Dot-Net

將文本字元串解析為 F# 程式碼

  • April 1, 2012

如何獲取應該是 F#-code 的文本字元串,並將其解析為 F#-code,以在螢幕上列印結果?

我猜它會通過.NET 中的一個特性來解決,所以它可以通過 F# 本身或 C# 來完成。

這可能在tryfsharp.org上以什麼方式解決?

可以使用F# CodeDom provider來實現期望。下面的最小可執行片段展示了所需的步驟。它從字元串中獲取任意可能正確的 F# 程式碼,並嘗試將其編譯為程序集文件。如果成功,那麼它會從文件中載入這個剛剛合成的程序集dll並從那裡呼叫一個已知函式,否則它會顯示編譯程式碼的問題。

open System 
open System.CodeDom.Compiler 
open Microsoft.FSharp.Compiler.CodeDom 

// Our (very simple) code string consisting of just one function: unit -> string 
let codeString =
   "module Synthetic.Code\n    let syntheticFunction() = \"I've been compiled on the fly!\""

// Assembly path to keep compiled code
let synthAssemblyPath = "synthetic.dll"

let CompileFSharpCode(codeString, synthAssemblyPath) =
       use provider = new FSharpCodeProvider() 
       let options = CompilerParameters([||], synthAssemblyPath) 
       let result = provider.CompileAssemblyFromSource( options, [|codeString|] ) 
       // If we missed anything, let compiler show us what's the problem
       if result.Errors.Count <> 0 then  
           for i = 0 to result.Errors.Count - 1 do
               printfn "%A" (result.Errors.Item(i).ErrorText)
       result.Errors.Count = 0

if CompileFSharpCode(codeString, synthAssemblyPath) then
   let synthAssembly = Reflection.Assembly.LoadFrom(synthAssemblyPath) 
   let synthMethod  = synthAssembly.GetType("Synthetic.Code").GetMethod("syntheticFunction") 
   printfn "Success: %A" (synthMethod.Invoke(null, null))
else
   failwith "Compilation failed"

被點燃它會產生預期的輸出

Success: "I've been compiled on the fly!"

如果你要玩這個片段,它需要引用FSharp.Compiler.dllFSharp.Compiler.CodeDom.dll. 享受!

引用自:https://stackoverflow.com/questions/9945382