F#如何将代码报价编译到程序集

时间:2011-08-06 13:39:31

标签: f# metaprogramming

我想知道是否有办法将代码报价编译成程序集?

我了解可以在CompileUntyped()对象上调用Compile()Exp<_>,例如:

let x = <@ 1 * 2 @>
let com = x.Compile()

但是,如何将com作为程序集保存到磁盘?

感谢。

1 个答案:

答案 0 :(得分:12)

您可以使用模式匹配评估F#代码报价:

open Microsoft.FSharp.Quotations.Patterns

let rec eval  = function
    | Value(v,t) -> v
    | Call(None,mi,args) -> mi.Invoke(null, evalAll args)
    | arg -> raise <| System.NotSupportedException(arg.ToString())
and evalAll args = [|for arg in args -> eval arg|]

let x = eval <@ 1 * 3 @>

有关更完整的实施,请参阅F# PowerPackUnquoteFoq OSS项目或此snippet

要编译F#代码报价,您可以define a dynamic method使用Reflection.Emit

open System.Reflection.Emit

let rec generate (il:ILGenerator) = function
    | Value(v,t) when t = typeof<int> ->
        il.Emit(OpCodes.Ldc_I4, v :?> int)
    | Call(None,mi,args) -> 
        generateAll il args
        il.EmitCall(OpCodes.Call, mi, null)
    | arg -> raise <| System.NotSupportedException(arg.ToString())
and generateAll il args = for arg in args do generate il arg

type Marker = interface end

let compile quotation =
    let f = DynamicMethod("f", typeof<int>, [||], typeof<Marker>.Module)
    let il = f.GetILGenerator()
    quotation |> generate il
    il.Emit(OpCodes.Ret)
    fun () -> f.Invoke(null,[||]) :?> int

let f = compile <@ 1 + 3 @>
let x = f ()

要再次编译到程序集,请使用Reflection.Emit生成带有方法的类型:

open System
open System.Reflection

let createAssembly quotation =
    let name = "GeneratedAssembly"
    let domain = AppDomain.CurrentDomain
    let assembly = domain.DefineDynamicAssembly(AssemblyName(name), AssemblyBuilderAccess.RunAndSave)
    let dm = assembly.DefineDynamicModule(name+".dll")
    let t = dm.DefineType("Type", TypeAttributes.Public ||| TypeAttributes.Class)
    let mb = t.DefineMethod("f", MethodAttributes.Public, typeof<int>, [||])
    let il = mb.GetILGenerator()
    quotation |> generate il
    il.Emit(OpCodes.Ret)
    assembly.Save("GeneratedAssembly.dll")

createAssembly <@ 1 + 1 @>

请参阅Fil项目(F#到IL)以获得更完整的实施。