I would like to know if there is a way to compile a code quotation into an assembly?
I understand that it is possible to call CompileUntyped()
or Compile()
on the开发者_开发知识库 Exp<_>
object, for example:
let x = <@ 1 * 2 @>
let com = x.Compile()
However, how can I persist com
to disk as an assembly?
Thanks.
You can evaluate an F# Code Quotations with pattern matching:
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 @>
See the F# PowerPack, Unquote, Foq OSS projects or this snippet for more complete implementations.
To compile an F# Code Quotation you can define a dynamic method using 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 ()
To compile to an assembly again use Reflection.Emit to generate a type with a method:
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 @>
See the Fil project (F# to IL) for a more complete implementation.
精彩评论