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


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

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

这可能以什么方式解决了 tryfsharp.org


4649
2018-03-30 14:54


起源

值得看看这个 题 - Dave Maff
你也可以使用 f#codedom - Dave Maff


答案:


可以使用实现所需的 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"

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

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

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


11
2018-04-01 20:09





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

不。 F#提供了相对温和的元编程设施。您需要从F#编译器本身中删除相关代码。


4
2018-03-30 17:20



好的,那我知道一半是不可能的。那么C#-part或.NET Framework中的东西呢? - Seb Nilsson
没有;没有框架知道F#存在。产品中没有这方面的API,尽管所有源代码都可用,因此您可以自己构建它。我认为从长远来看,我们想发布展示如何做到这一点的样本,但我们尚未做好准备。 - Brian


F#有一个解释器fsi.exe,它可以做你想要的。我认为它也有一些API。


0
2018-03-30 15:12