/// <summary> /// Compiles the lambda into a method definition. /// </summary> /// <param name="lambda">the lambda to compile</param> /// <param name="method">A <see cref="MethodBuilder"/> which will be used to hold the lambda's IL.</param> /// <param name="emitDebugSymbols">A parameter that indicates if debugging information should be emitted to a PDB symbol store.</param> public static void CompileToMethod(this LambdaExpression lambda, MethodBuilder method, bool emitDebugSymbols) { if (emitDebugSymbols) { var module = method.Module as ModuleBuilder; ContractUtils.Requires(module != null, "method", "MethodBuilder does not have a valid ModuleBuilder"); lambda.CompileToMethod(method, DebugInfoGenerator.CreatePdbGenerator()); return; } lambda.CompileToMethod(method); }
/// <summary> /// Emits the IL for this method. Adds a backing static method to which the expression is compiled, /// then calls that method with appropriate arguments /// </summary> /// <param name="il">IL generator for the current method</param> /// <param name="sourceField">Field representing the source component</param> /// <param name="typeBeingBuilt">The type being built</param> internal override void Emit(ILGenerator il, FieldBuilder sourceField, TypeSpecifier typeBeingBuilt) { var pTypes = _expr.Parameters.Select(p => p.Type).ToArray(); var nestedClass = typeBeingBuilt.CreateDisplayClass(); var lambda = nestedClass.TypeBuilder.DefineMethod(nestedClass.GetMethodName(_name), MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.Public, _expr.ReturnType, pTypes); // We'd really like to compile this straight into our method, // but `LambdaExpression.CompileToMethod` only takes static methods, // so the next best thing is to use this attribute to tell the JITter // that it should be inlined. lambda.SetCustomAttribute(new CustomAttributeBuilder( typeof(MethodImplAttribute).GetConstructor(new Type[] { typeof(MethodImplOptions) }), new object[1] { MethodImplOptions.AggressiveInlining })); _expr.CompileToMethod(lambda); foreach (var p in _params) { p.Emit(il, sourceField, typeBeingBuilt.TypeBuilder); } il.Emit(OpCodes.Call, lambda); il.Emit(OpCodes.Ret); }
static void Main(string[] args) { var asmName = new AssemblyName("Foo"); var asmBuilder = AssemblyBuilder.DefineDynamicAssembly (asmName, AssemblyBuilderAccess.RunAndSave); var moduleBuilder = asmBuilder.DefineDynamicModule("Foo", "Foo.exe"); var typeBuilder = moduleBuilder.DefineType("Program", TypeAttributes.Public); var methodBuilder = typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void), new[] { typeof(string) }); var serializer = new Serializer <CompactBinaryWriter <OutputBuffer> >(typeof(AnswerConfig)); var expression = serializer.GetExpressions().First(); var visitor = new MyVisitor(); LambdaExpression exp = (LambdaExpression)visitor.Visit(expression); exp.CompileToMethod(methodBuilder); typeBuilder.CreateType(); asmBuilder.SetEntryPoint(methodBuilder); asmBuilder.Save("Foo.exe"); var output = new OutputBuffer(); var writer = new CompactBinaryWriter <OutputBuffer>(output); //BondExpressionsInterceptor.Serialize.To<CompactBinaryWriter<OutputBuffer>, Record>(writer, src); var input = new InputBuffer(output.Data); var reader = new CompactBinaryReader <InputBuffer>(input); var dst = Deserialize <Record> .From(reader); }
private MethodBuilder GenerateConstants(TypeBuilder fnTB, Type baseType) { try { Var.pushThreadBindings(RT.map(RT.PRINT_DUP, RT.T)); List <Expression> inits = new List <Expression>(); for (int i = 0; i < _constants.count(); i++) { Expression expr = GenerateValue(_constants.nth(i)); Expression init = Expression.Assign( Expression.Field(null, baseType, ConstantName(i)), Expression.Convert(expr, ConstantType(i))); inits.Add(init); } inits.Add(Expression.Default(typeof(void))); Expression block = Expression.Block(inits); LambdaExpression lambda = Expression.Lambda(block); MethodBuilder methodBuilder = fnTB.DefineMethod(STATIC_CTOR_HELPER_NAME, MethodAttributes.Private | MethodAttributes.Static); lambda.CompileToMethod(methodBuilder); return(methodBuilder); } finally { Var.popThreadBindings(); } }
void CreateStaticCtor() { //Console.WriteLine("Creating static ctor for {0}", // _typeBuilder.AssemblyQualifiedName); ConstructorBuilder ctorB = _typeBuilder.DefineConstructor(MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); CljILGen gen = new CljILGen(ctorB.GetILGenerator()); for (int i = 0; i < _fieldBuilders.Count; i++) { FieldBuilder fb = _fieldBuilders[i]; Expression fbInit = _fieldInits[i]; string setterName = String.Format("{0}_setter", fb.Name); MethodBuilder mbSetter = _typeBuilder.DefineMethod( setterName, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, fbInit.Type, Type.EmptyTypes); LambdaExpression initL = Expression.Lambda(Expression.Assign(Expression.Field(null, fb), fbInit)); initL.CompileToMethod(mbSetter); gen.EmitCall(mbSetter); gen.Emit(OpCodes.Pop); } gen.Emit(OpCodes.Ret); }
private MethodBuilder GenerateKeywordCallsiteInit(TypeBuilder fnTB, Type baseType, bool isDebuggable) { if (_keywordCallsites.count() == 0) { return(null); } List <Expression> inits = new List <Expression>(); ParameterExpression parm = Expression.Parameter(typeof(KeywordLookupSite), "temp"); for (int i = 0; i < _keywordCallsites.count(); i++) { Expression kArg = GenerateValue(_keywordCallsites.nth(i)); Expression parmAssign = Expression.Assign( parm, Expression.New(Compiler.Ctor_KeywordLookupSite_1, new Expression[] { kArg })); Expression siteAssign = Expression.Assign(Expression.Field(null, _keywordLookupSiteFields[i]), parm); Expression thunkAssign = Expression.Assign(Expression.Field(null, _thunkFields[i]), Expression.Convert(parm, typeof(ILookupThunk))); inits.Add(parmAssign); inits.Add(siteAssign); inits.Add(thunkAssign); inits.Add(Expression.Default(typeof(void))); } Expression allInits = Expression.Block(new ParameterExpression[] { parm }, inits); LambdaExpression lambda = Expression.Lambda(allInits); MethodBuilder methodBuilder = fnTB.DefineMethod(STATIC_CTOR_HELPER_NAME + "_kwcallsites", MethodAttributes.Private | MethodAttributes.Static, typeof(void), Type.EmptyTypes); lambda.CompileToMethod(methodBuilder, isDebuggable); return(methodBuilder); }
private void CompileWithStaticGlobals(out DlrMainCallTarget target, out IAttributesCollection globals) { // Create typegen TypeGen typeGen = Snippets.Shared.DefineType(MakeDebugName(), typeof(CustomSymbolDictionary), false, SourceUnit.EmitDebugSymbols); typeGen.TypeBuilder.DefineDefaultConstructor(MethodAttributes.Public); // Create rewriter GlobalStaticFieldRewriter rewriter = new GlobalStaticFieldRewriter(typeGen); // Compile lambda LambdaExpression lambda = rewriter.RewriteLambda(Code, "Initialize"); lambda.CompileToMethod(typeGen.TypeBuilder, CompilerHelpers.PublicStatic, SourceUnit.EmitDebugSymbols); // Create globals dictionary, finish type rewriter.EmitDictionary(); Type type = typeGen.FinishType(); globals = (IAttributesCollection)Activator.CreateInstance(type); // Create target target = (DlrMainCallTarget)Delegate.CreateDelegate(typeof(DlrMainCallTarget), type.GetMethod("Initialize")); // TODO: clean this up after clarifying dynamic site initialization logic InitializeFields(type); }
} // func CreateUniqueTypeName LuaChunk ILuaDebug.CreateChunk(Lua lua, LambdaExpression expr) { lock (this) { // create the dynamic assembly if (assembly == null) { assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(GetLuaDynamicName(), AssemblyBuilderAccess.RunAndCollect); module = assembly.DefineDynamicModule("lua", true); } // create a type for the expression var type = module.DefineType(CreateUniqueTypeName(expr.Name), TypeAttributes.NotPublic | TypeAttributes.Sealed); // transform the expression var reduce = new ReduceDynamic(lua, this, type); expr = (LambdaExpression)reduce.Visit(expr); // compile the function var method = type.DefineMethod(expr.Name, MethodAttributes.Static | MethodAttributes.Public); var chunk = new LuaStackTraceChunk(lua, expr.Name); var collectedDebugInfo = new LuaDebugInfoGenerator(chunk); expr.CompileToMethod(method, collectedDebugInfo); // create the type and build the delegate var typeFinished = type.CreateType(); // Initialize fields, create the static callsite's reduce.InitMethods(typeFinished); // return chunk return(chunk.InitChunk(Delegate.CreateDelegate(expr.Type, typeFinished.GetMethod(expr.Name)))); } } // func ILuaDebug.CreateChunk
public CompiledMethod AddMethod(LambdaExpression lambda) { int functionId = Interlocked.Increment(ref functionCounter); TypeBuilder typeBuilder = ModuleBuilder.DefineType("Function" + functionId, TypeAttributes.Public | TypeAttributes.Class); MethodBuilder methodBuilder = typeBuilder.DefineMethod("Call", MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.Public, typeof(void), new Type[] { typeof(int) }); var constantRewriterStage1 = new ConstantRewriterStage1(); constantRewriterStage1.constantFieldStorageType = ModuleBuilder.DefineType("FunctionConst" + functionId, TypeAttributes.Public | TypeAttributes.Class); lambda = (LambdaExpression)constantRewriterStage1.Visit(lambda); var constantRewriterStage2 = new ConstantRewriterStage2(); constantRewriterStage2.constantFieldStorageType = constantRewriterStage1.constantFieldStorageType.CreateType(); constantRewriterStage2.constantFields = constantRewriterStage1.constantFields; lambda = (LambdaExpression)constantRewriterStage2.Visit(lambda); foreach (var p in constantRewriterStage1.constantFields) { constantRewriterStage2.constantFieldStorageType.GetField(p.Value).SetValue(null, p.Key.Value); } lambda.CompileToMethod(methodBuilder, new MyDebugInfoGenerator()); Type typeInstance = typeBuilder.CreateType(); // assemblyBuilder.Save("generated.dll"); return(new CompiledMethod(typeInstance.GetMethod("Call"))); }
private IAfterProperty addMethod(string methodName, LambdaExpression methBody, MethodAttributes methAttrs = MethodAttributes.Public | MethodAttributes.NewSlot | MethodAttributes.Final | MethodAttributes.Static) { MethodBuilder _mb = _tBuilder.DefineMethod(methodName, methAttrs); methBody.CompileToMethod(_mb); return(this); }
private MethodInfo CreateDefaultMethod(LambdaExpression lambda, TypeBuilder dynType) { var dynMethod = dynType.DefineMethod("Dflt", MethodAttributes.Static | MethodAttributes.Private, lambda.ReturnType, new Type[0]); lambda.CompileToMethod(dynMethod); return(dynMethod); }
/// <summary> /// Compiles the lambda into a method definition. /// </summary> /// <param name="lambda">the lambda to compile</param> /// <param name="method">A <see cref="MethodBuilder"/> which will be used to hold the lambda's IL.</param> /// <param name="emitDebugSymbols">A parameter that indicates if debugging information should be emitted to a PDB symbol store.</param> public static void CompileToMethod(this LambdaExpression lambda, MethodBuilder method, bool emitDebugSymbols) { #if FEATURE_PDBEMIT if (emitDebugSymbols) { var module = method.Module as ModuleBuilder; ContractUtils.Requires(module != null, "method", "MethodBuilder does not have a valid ModuleBuilder"); lambda.CompileToMethod(method, DebugInfoGenerator.CreatePdbGenerator()); return; } #endif #if WIN8 // TODO ((dynamic)lambda).CompileToMethod(method); #else lambda.CompileToMethod(method); #endif }
public static Delegate CreateDynamicDelegate(LambdaExpression expression, Type delegateType) { var typeBuilder = _moduleBuilder.DefineType("BatMap_DynamicType" + _typeCounter++, TypeAttributes.Public); var methodBuilder = typeBuilder.DefineMethod("BatMap_DynamicMethod", MethodAttributes.Public | MethodAttributes.Static); expression.CompileToMethod(methodBuilder); var type = typeBuilder.CreateType(); return(Delegate.CreateDelegate(delegateType, type.GetMethod("BatMap_DynamicMethod"))); }
private MethodInfo CreateLambdaMethod(LambdaExpression lambda, TypeBuilder dynType) { var p1 = lambda.Parameters[0]; var counter = ++lambdaMethodCounter; var dynMethod = dynType.DefineMethod($"LM_{counter}", MethodAttributes.Static | MethodAttributes.Private, lambda.ReturnType, new[] { p1.Type }); dynMethod.DefineParameter(1, ParameterAttributes.None, p1.Name); lambda.CompileToMethod(dynMethod); return(dynMethod); }
internal void GenerateLiteralType() { if (this._LiteralsType == null) { return; } // It would have been nice to use the Lambda Compiler, but it can't compile constructors, // ... so we compile a helper method that retunrns an array ... NewArrayExpression array = Expression.NewArrayInit(typeof(object), this.DefinedLiterals.Select(def => def.Initializer)); LambdaExpression lambda = Expression.Lambda(array, true); MethodBuilder methodBuilder = this.LiteralsType.DefineMethod("InitializeLiterals", MethodAttributes.Private | MethodAttributes.Static); if (this.Client.Compiler.NativeGenerator.DebugInfoGenerator == null) { lambda.CompileToMethod(methodBuilder); } else { lambda.CompileToMethod(methodBuilder, this.Client.Compiler.NativeGenerator.DebugInfoGenerator); } // ... and fromt his array we generate the constructor by emitting IL code by hand :/ ConstructorBuilder ctor = this._LiteralsType.DefineConstructor( MethodAttributes.Private | MethodAttributes.Static, CallingConventions.Standard, new Type[0]); ILGenerator ctorIL = ctor.GetILGenerator(); ctorIL.DeclareLocal(typeof(object[])); // Define a temp var for the array ctorIL.Emit(OpCodes.Call, methodBuilder); // Call the InitializeLiterals method. ctorIL.Emit(OpCodes.Stloc_0); // Store the result in the temp var // ... now assign to each literal field for (int i = 0; i < this.DefinedLiterals.Count; i++) { ctorIL.Emit(OpCodes.Ldloc_0); // Load the temp array var ctorIL.PushInt(i); // Index in the array ctorIL.Emit(OpCodes.Ldelem_Ref); // Load elem from the array at the given index ctorIL.Emit(OpCodes.Stsfld, this.DefinedLiterals[i].Field); // Store the value in the static field } ctorIL.Emit(OpCodes.Ret); this.LiteralTypeType = this._LiteralsType.CreateType(); }
private static MethodInfo CompileToStaticMethod(LambdaExpression lambda, string typeName, string methodName) { var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run); var moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); var typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public | TypeAttributes.Class); var methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Static); lambda.CompileToMethod(methodBuilder); var accessorType = typeBuilder.CreateType(); return(accessorType.GetMethod(methodName)); }
protected string CompileMethod(LambdaExpression expr) { var returnType = expr.Type; var parameters = expr.Parameters.Select(p => p.Type).ToArray(); lock (locker) { var name = "Binding_" + (methodCounter++); var method = bindingsClass.DefineMethod(name, MethodAttributes.Public | MethodAttributes.Static, returnType, parameters); expr.CompileToMethod(method); return(bindingsClass.FullName + "." + name); } }
MethodBuilder GenerateStaticMethod(GenContext context) { string methodName = GetStaticMethodName(); FnExpr fn = context.FnExpr; TypeBuilder tb = fn.TypeBuilder; List <ParameterExpression> parms = new List <ParameterExpression>(_argLocals.count() + 1); ParameterExpression thisParm = Expression.Parameter(fn.BaseType, "this"); _thisBinding.ParamExpression = thisParm; fn.ThisParam = thisParm; parms.Add(thisParm); try { LabelTarget loopLabel = Expression.Label("top"); Var.pushThreadBindings(RT.map(Compiler.LOOP_LABEL, loopLabel, Compiler.METHODS, this)); for (int i = 0; i < _argLocals.count(); i++) { LocalBinding lb = (LocalBinding)_argLocals.nth(i); ParameterExpression parm = Expression.Parameter(typeof(object), lb.Name); lb.ParamExpression = parm; parms.Add(parm); } Expression body = Expression.Block( Expression.Label(loopLabel), Compiler.MaybeBox(_body.GenDlr(context))); LambdaExpression lambda = Expression.Lambda(body, parms); // TODO: Figure out why the Java code nulls all the local variables here. // TODO: Cache all the CreateObjectTypeArray values MethodBuilder mb = tb.DefineMethod(methodName, MethodAttributes.Static, typeof(object), Compiler.CreateObjectTypeArray(NumParams)); lambda.CompileToMethod(mb); //lambda.CompileToMethod(mb, true); return(mb); } finally { Var.popThreadBindings(); } }
internal static Delegate CompileLambdaInDynamicAssembly(LambdaExpression lambda, string typeName, string methodName) { TypeBuilder typeBuilder = Container.ModuleBuilder.DefineType(typeName, TypeAttributes.Public); MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Static | MethodAttributes.Public); lambda.CompileToMethod(methodBuilder); Type type = typeBuilder.CreateType(); return(Delegate.CreateDelegate(lambda.Type, type.GetMethod(methodName), true)); }
static F Compile <F>(LambdaExpression lambda, string typeName, string methodName) where F : Delegate { #if COREFX20 return((F)lambda.Compile()); #else var name = Guid.NewGuid().ToString(); var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.Run); var type = asm.DefineDynamicModule("module").DefineType(typeName); var builder = type.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Static); lambda.CompileToMethod(builder); var resultingType = type.CreateType(); return((F)Delegate.CreateDelegate(typeof(F), resultingType.GetMethod(methodName))); #endif }
private static void SaveToAssembly(this LambdaExpression lambdaExpr, string assemblyName, Type returnType, Type[] paramTypes) { AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.RunAndSave); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName, assemblyName + ".dll"); TypeBuilder typeBuilder = moduleBuilder.DefineType(assemblyName + "Class", TypeAttributes.Public); MethodBuilder methodBuilder = typeBuilder.DefineMethod(assemblyName + "Method", MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.Static, returnType, paramTypes); lambdaExpr.CompileToMethod(methodBuilder); typeBuilder.CreateType(); assemblyBuilder.Save(assemblyName + ".dll"); }
protected MethodInfo CompileMethod(LambdaExpression expr) { var returnType = expr.Type; var parameters = expr.Parameters.Select(p => p.Type).ToArray(); lock (locker) { var name = "Binding_" + (methodCounter++); #if NET461 var method = bindingsClass.DefineMethod(name, MethodAttributes.Public | MethodAttributes.Static, returnType, parameters); expr.CompileToMethod(method); return(method); #endif throw new NotImplementedException(); } }
private unsafe void SlowLookup(EVENT_RECORD *eventRecord, EventRecordReader eventRecordReader, RuntimeEventMetadata runtimeMetadata, ref TraceEventKey key) { if (this.CustomParserLookup(eventRecord, ref key)) { return; } bool isSpecialKernelTraceMetaDataEvent = false; var operand = this.BuildOperand(eventRecord, eventRecordReader, this.eventMetadataTableList.Count, ref isSpecialKernelTraceMetaDataEvent); if (operand != null) { this.eventMetadataTableList.Add(operand.Metadata); this.eventMetadataTable = this.eventMetadataTableList.ToArray(); // TODO: Need to improve this var eventRecordReaderParam = Expression.Parameter(ReaderType); var eventWriterParam = Expression.Parameter(WriterType); var eventMetadataTableParam = Expression.Parameter(EventMetadataArrayType); var runtimeMetadataParam = Expression.Parameter(RuntimeMetadataType); var parameters = new[] { eventRecordReaderParam, eventWriterParam, eventMetadataTableParam, runtimeMetadataParam }; var name = Regex.Replace(InvalidCharacters.Replace(operand.Metadata.Name, "_"), @"\s+", "_"); var body = EventTraceOperandExpressionBuilder.Build(operand, eventRecordReaderParam, eventWriterParam, eventMetadataTableParam, runtimeMetadataParam); LambdaExpression expression = Expression.Lambda <Action <EventRecordReader, T, EventMetadata[], RuntimeEventMetadata> >(body, "Read_" + name, parameters); var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.RunAndCollect); var moduleBuilder = assemblyBuilder.DefineDynamicModule(name, name + ".dll"); var typeBuilder = moduleBuilder.DefineType(name, TypeAttributes.Public); var methodBuilder = typeBuilder.DefineMethod("Read", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new[] { ReaderType, WriterType, EventMetadataArrayType, RuntimeMetadataType }); expression.CompileToMethod(methodBuilder); var action = (Action <EventRecordReader, T, EventMetadata[], RuntimeEventMetadata>)Delegate.CreateDelegate(expression.Type, typeBuilder.CreateType().GetMethod("Read")); if (isSpecialKernelTraceMetaDataEvent) { var e = (TRACE_EVENT_INFO *)eventRecord->UserDataFixed; this.actionTable.AddOrUpdate(new TraceEventKey(e->ProviderGuid, e->EventGuid == Guid.Empty ? e->Id : e->Opcode, e->Version), action); } else { this.actionTable.Add(key, action); action(eventRecordReader, this.writer, this.eventMetadataTable, runtimeMetadata); } } }
static public void EmitDynamicCallPreamble(DynamicExpression dyn, IPersistentMap spanMap, string methodName, Type returnType, List <ParameterExpression> paramExprs, Type[] paramTypes, CljILGen ilg, out LambdaExpression lambda, out Type delType, out MethodBuilder mbLambda) { Expression call = dyn; GenContext context = Compiler.CompilerContextVar.deref() as GenContext; if (context != null && context.DynInitHelper != null) { call = context.DynInitHelper.ReduceDyn(dyn); } if (returnType == typeof(void)) { call = Expression.Block(call, Expression.Default(typeof(object))); returnType = typeof(object); } else if (returnType != call.Type) { call = Expression.Convert(call, returnType); } call = GenContext.AddDebugInfo(call, spanMap); delType = Microsoft.Scripting.Generation.Snippets.Shared.DefineDelegate("__interop__", returnType, paramTypes); lambda = Expression.Lambda(delType, call, paramExprs); mbLambda = null; if (context == null) { // light compile Delegate d = lambda.Compile(); int key = RT.nextID(); CacheDelegate(key, d); ilg.EmitInt(key); ilg.Emit(OpCodes.Call, Method_MethodExpr_GetDelegate); ilg.Emit(OpCodes.Castclass, delType); } else { mbLambda = context.TB.DefineMethod(methodName, MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, returnType, paramTypes); lambda.CompileToMethod(mbLambda); } }
public static Delegate CompileToMethod(LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator, bool emitDebugSymbols) { string methodName = String.IsNullOrEmpty(lambda.Name) ? GetUniqueMethodName() : lambda.Name; var type = Snippets.Shared.DefineType(methodName, typeof(object), false, emitDebugSymbols).TypeBuilder; var rewriter = new DebuggableCodeRewriter(type); lambda = (LambdaExpression)rewriter.Visit(lambda); //Create a unique method name when the lambda doesn't have a name or the name is empty. var method = type.DefineMethod(methodName, PublicStatic); lambda.CompileToMethod(method, debugInfoGenerator); var finished = type.CreateType(); rewriter.InitializeFields(finished); return(finished.GetMethod(method.Name).CreateDelegate(lambda.Type)); }
public Delegate Compile(Type delegateType, LambdaExpression expression) { if (delegateType == null) { throw new ArgumentNullException(nameof(delegateType)); } if (expression == null) { throw new ArgumentNullException(nameof(expression)); } if (!typeof(Delegate).IsAssignableFrom(delegateType)) { throw new ArgumentException("Type is not delegate.", nameof(delegateType)); } try { var typeBuilder = moduleBuilder.DefineType("Dynamic.DynamicType_" + Guid.NewGuid().ToString("N"), TypeAttributes.Public); var methodBuilder = typeBuilder.DefineMethod("DynamicMethod_" + Guid.NewGuid().ToString("N"), MethodAttributes.Public | MethodAttributes.Static); expression.CompileToMethod(methodBuilder); var type = typeBuilder.CreateTypeInfo(); var methodInfo = type.GetMethod(methodBuilder.Name); if (methodInfo == null) { throw new InvalidOperationException($"Can't get method {methodBuilder.Name} of type {type.FullName}"); } // Force method JIT compilation for debug purposes, we need fail as soon as possible if something goes wrong System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(methodInfo.MethodHandle); return(Delegate.CreateDelegate(delegateType, methodInfo)); } catch (Exception) { return(FallbackCompiler.Compile(delegateType, expression)); } }
protected override MethodBuilder CompileForSave(TypeGen typeGen, Dictionary <SymbolId, FieldBuilder> symbolDict) { // first, serialize constants and dynamic sites: ToDiskRewriter diskRewriter = new ToDiskRewriter(typeGen); LambdaExpression lambda = diskRewriter.RewriteLambda(Code); // rewrite global variables: var globalRewriter = new GlobalArrayRewriter(symbolDict, typeGen); lambda = globalRewriter.RewriteLambda(lambda); MethodBuilder builder = lambda.CompileToMethod(typeGen.TypeBuilder, CompilerHelpers.PublicStatic | MethodAttributes.SpecialName, false); builder.SetCustomAttribute(new CustomAttributeBuilder( typeof(CachedOptimizedCodeAttribute).GetConstructor(new Type[] { typeof(string[]) }), new object[] { ArrayUtils.ToArray(globalRewriter.Names) } )); return(builder); }
public Delegate Compile(string name, LambdaExpression expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } using (Timer.Step("MethodBuilderCompiler.Compile")) { expression.AssertNoPrivateMethods(); var typeB = _module.DefineType(name, TypeAttributes.Public); var v = new AddFieldsForConstantsVisitor(typeB); expression = v.VisitAndConvert(expression, nameof(Compile)); var methodB = typeB.DefineMethod( MethodName, MethodAttributes.Public | MethodAttributes.Static, expression.ReturnType, expression.Parameters.Select(p => p.Type).ToArray()); expression.CompileToMethod(methodB); var type = typeB.CreateType(); foreach (var f in v.Fields) { var fi = type.GetField(f.Value.Name); fi.SetValue(null, f.Key.Value); } var method = type.GetMethod(MethodName); var del = Delegate.CreateDelegate(expression.Type, method); return(del); } }
private static Delegate CompileLambdaInDynamicAssembly(LambdaExpression lambda) { const string MethodName = "Lambda"; string typeName = "DynamicProducer" + GetNextDynamicClassId(); TypeBuilder typeBuilder; lock (Builder) { typeBuilder = Builder.DefineType(typeName, TypeAttributes.Public); } MethodBuilder methodBuilder = typeBuilder.DefineMethod(MethodName, MethodAttributes.Static | MethodAttributes.Public); lambda.CompileToMethod(methodBuilder); Type type = typeBuilder.CreateType(); return(Delegate.CreateDelegate(lambda.Type, type.GetMethod(MethodName), true)); }
/// <summary> /// Compile lambda expression to an assembly /// </summary> public static Func <S, T> CompileToAssembly <S, T>(this LambdaExpression expression, IEnumerable <PropertyInfo> inputs, string assemblyName, string directoryName) { var domain = AppDomain.CurrentDomain; var assembly = new AssemblyName("Assembly"); var assemblyBuilder = domain.DefineDynamicAssembly(assembly, AssemblyBuilderAccess.RunAndSave, directoryName); var module = assemblyBuilder.DefineDynamicModule("Module", assemblyName); var typeBuilder = module.DefineType("BigML", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed); var methodBuilder = typeBuilder.DefineMethod("Predict", MethodAttributes.Public | MethodAttributes.Static, typeof(T), new[] { typeof(S) }); expression.CompileToMethod(methodBuilder); var type = typeBuilder.CreateType(); assemblyBuilder.Save(assemblyName); var predict = type.GetMethod("Predict"); return(delegate(S s) { var args = inputs.GetValue(s); return (T)Convert.ChangeType(predict.Invoke(null, args.ToArray()), typeof(T)); }); }