IL generation for recursive methods

I tried to generate an IL for the recursive method using the following strategy. First I defined the type using the following code snippet

private void InitializeAssembly(string outputFileName) { AppDomain appDomain = AppDomain.CurrentDomain; AssemblyName assemblyName = new AssemblyName(outputFileName); assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save); moduleBuilder = assemblyBuilder.DefineDynamicModule(outputFileName, outputFileName + ".exe"); typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public); methodBuilder = typeBuilder.DefineMethod("Main", MethodAttributes.Static | MethodAttributes.Public, typeof(void), System.Type.EmptyTypes); ilGen = methodBuilder.GetILGenerator(); } 

Next, I started generating IL for the recursive method, as shown below.

 MethodBuilder method = typeBuilder.DefineMethod( "MethodName", MethodAttributes.Static | MethodAttributes.Public, NodeTypeToDotNetType(func.RetType), parameters); ILGenerator ilOfMethod = method.GetILGenerator(); method.DefineParameter(); 

To call the method itself inside the method body, I used the following construction,

 ilOfMethod.Emit(OpCodes.Call, typeBuilder.GetMethod("MethodName", new System.Type[] {typeof(arg1),typeof(arg2),etc})); 

Finally, save the generated assembly using the following method.

 private void SaveAssembly(string outputFileName) { ilGen.Emit(OpCodes.Ret); typeBuilder.CreateType(); moduleBuilder.CreateGlobalFunctions(); assemblyBuilder.SetEntryPoint(methodBuilder); assemblyBuilder.Save(outputFileName + ".exe"); } 

Unfortunately, this does not work with the recursive construction of a method call; inside the method returns null. The problem here is that the recursive call is inside the method (ie ilOfMethod.Emit(OpCodes.Call, typeBuilder.GetMethod("MethodName", new System.Type[] {typeof(arg1),typeof(arg2),etc})); ) returns null. Since we are actually creating a type inside the SaveAssembly() method, this is acceptable. So my question is this: is it possible to generate IL for recursive methods using the above construct? If this is not possible, let me know what alternative constructs are for generating IL for recursive methods.

+7
source share
1 answer

I have not tested it, but if I remember correctly, you should simply use the DefineMethod result to fix the Call statement:

 MethodBuilder method = typeBuilder.DefineMethod("MethodName", ...); ... ILGenerator ilOfMethod = method.GetILGenerator(); ... ilOfMethod.Emit(OpCodes.Call, method); 
+7
source

All Articles