解析文本字符串F# - code字符串、文本、code

2023-09-03 12:28:00 作者:别在爱里死去活来

我如何采取文本串,这应该是F# - code和解析成F# - code,打印出屏幕

How do I take text-string, that is supposed to be F#-code, and parse it into F#-code, to print out the results on the screen?

我猜它会通过在.NET中的功能来解决,因此它可以通过F#本身或完成C#。

I'm guessing it would be solved through a feature in .NET, so it can be done through F# itself or C#.

在什么样的方式是这样可能解决的 tryfsharp.org ?

In what way is this probably solved on tryfsharp.org?

推荐答案

所需的可使用 F#codeDOM提供商来实现。下面一个最小的可运行的代码演示了所需的步骤。这需要一个任意presumably正确的F#code从字符串,并试图将其编译成汇编文件。如果成功的话,那么它加载从 DLL 文件这只是合成组件,并调用来自有一个已知的功能,否则就说明有什么用编译code中的问题。

The desired can be achieved using F# CodeDom provider. A minimal runnable snippet below demonstrates the required steps. It takes an arbitrary presumably correct F# code from a string and tries to compile it into an assembly file. If successful, then it loads this just synthesized assembly from the dll file and invokes a known function from there, otherwise it shows what's the problem with compiling the code.

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"

被解雇行动它产生预期的输出

Being fired-up it produces the expected output

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

如果你要它需要引用片段播放 FSharp.Compiler.dll FSharp.Compiler。codeDom.dll 。尽情享受吧!

If you gonna play with the snippet it requires referencing FSharp.Compiler.dll and FSharp.Compiler.CodeDom.dll. Enjoy!