将文本字符串解析为F#-code

Seb*_*son 11 .net f# parsing

如何使用文本字符串(应该是F#-code)并将其解析为F#-code,以在屏幕上打印出结果?

我猜它可以通过.NET中的一个功能来解决,所以它可以通过F#本身或C#来完成.

这可能在tryfsharp.org上以什么方式解决?

Gen*_*ski 11

使用F#CodeDom提供程序可以实现所需的功能.下面的最小可运行代码段演示了所需的步骤.它从字符串中获取任意大概正确的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"
Run Code Online (Sandbox Code Playgroud)

被激发它会产生预期的输出

Success: "I've been compiled on the fly!"
Run Code Online (Sandbox Code Playgroud)

如果您要使用片段,则需要参考FSharp.Compiler.dllFSharp.Compiler.CodeDom.dll.请享用!