GetILGenerator() публичный Метод

public GetILGenerator ( ) : System.Reflection.Emit.ILGenerator
Результат System.Reflection.Emit.ILGenerator
Пример #1
0
 public override void Gen(TypeBuilder program, MethodBuilder method)
 {
     AstNode left = this.child;
     AstNode right = left.sibling;
     left.Gen(program, method);
     right.Gen(program, method);
     if (this.symbol == "+") {
         method.GetILGenerator().EmitCall(OpCodes.Callvirt, typeof(TypeBase).GetMethod("Add"), new Type[] { typeof(TypeBase) });
     } else if (this.symbol == "-") {
         method.GetILGenerator().EmitCall(OpCodes.Callvirt,typeof(TypeBase).GetMethod("Minus"), new Type[] { typeof(TypeBase) });
     }
 }
Пример #2
0
 public override void Gen(TypeBuilder program, MethodBuilder method)
 {
     EnviromentNode envNode = EnviromentList.Instance.LoopupSymbol(this.symbol);
     AstNode right = this.child;
     right.Gen(program, method);
     if (envNode.IsGlobal) {
         envNode.field = program.DefineField(this.symbol, typeof(TypeBase), System.Reflection.FieldAttributes.Private | System.Reflection.FieldAttributes.Static);
         method.GetILGenerator().Emit(OpCodes.Stsfld, envNode.field);
     } else {
         envNode.local = method.GetILGenerator().DeclareLocal(typeof(TypeBase));
         method.GetILGenerator().Emit(OpCodes.Stloc, envNode.local);
     }
 }
Пример #3
0
 public override void Gen(TypeBuilder program, MethodBuilder method)
 {
     DoGen(program, method);
     // then push a FunctionType value
     EnviromentNode envNode = this.localenv == null ?
         EnviromentList.Instance.LookupLocal(this.symbol) :
         this.localenv.LookupLocal(this.symbol);
     var tmp = method.GetILGenerator().DeclareLocal(typeof(TypeBase));
     method.GetILGenerator().Emit(OpCodes.Ldstr, this.symbol);
     method.GetILGenerator().Emit(OpCodes.Newobj, typeof(FunctionType).GetConstructor(new Type[] { typeof(string) }));
     method.GetILGenerator().Emit(OpCodes.Stloc, tmp);
     SetupClosure(method, envNode.method, envNode.ParamCount, tmp);
     method.GetILGenerator().Emit(OpCodes.Ldloc, tmp);
 }
Пример #4
0
        public void Emit(CompilerErrorCollection errors, MethodBuilder m)
        {
            //Set the parameters
            //ParameterBuilder[] parms = new ParameterInfo[args.Length];
            for(int i = 0; i < args.Length; i++)
                m.DefineParameter(i + 1, ParameterAttributes.None, args[i].Name);

            ILGenerator gen = m.GetILGenerator();

            //Define the IT variable
            LocalRef it = locals["IT"] as LocalRef;
            DefineLocal(gen, it);

            statements.Process(this, errors, gen);

            statements.Emit(this, gen);

            //Cast the IT variable to our return type and return it
            if (m.ReturnType != typeof(void))
            {
                gen.Emit(OpCodes.Ldloc, it.Local);
                Expression.EmitCast(gen, it.Type, m.ReturnType);
            }
            gen.Emit(OpCodes.Ret);
        }
 private void CreateMethodBuilder()
 {
     methodBuilder = typeBuilder.DefineMethod(
         "DynamicMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(object), new Type[] { typeof(object), typeof(object[]) });
     methodBuilder.InitLocals = true;
     ilGenerator = methodBuilder.GetILGenerator();
 }
Пример #6
0
        private void CreateContinueMethod(MethodInfo method, MethodBuilder continueMethod, int position, Type[] parameters, int count)
        {
            var generator = continueMethod.GetILGenerator();

            // Store array in temp0
            generator.DeclareLocal(typeof (object[]));
            generator.LoadArgument(1);
            generator.StashTemporaryVariable(0);

            // Push backing object onto the stack
            generator.LoadField(backingObject);

            // Push each of the arguments passed in onto the stack
            for (int i = 0; i < count; i++)
            {
                generator.LoadTemporaryVariable(0);
                generator.LoadInteger(i);
                generator.Emit(OpCodes.Ldelem_Ref);
                generator.MaybeUnBox(parameters[i]);
            }

            // Delegate to backing object
            generator.Execute(method);

            // Convert the returned value to an object
            if (method.ReturnType == typeof(void))
                generator.LoadNull();
            else
                generator.MaybeBox(method.ReturnType);

            // Return
            generator.Emit(OpCodes.Ret);
        }
 private void CreateMethodBuilder(Type returnType, Type[] parameterTypes)
 {
     methodBuilder = typeBuilder.DefineMethod(
         "DynamicMethod", MethodAttributes.Public | MethodAttributes.Static, returnType, parameterTypes);
     methodBuilder.InitLocals = true;
     emitter = new Emitter(methodBuilder.GetILGenerator(), parameterTypes);
 }
		private static void EmitMethodBody (MethodBuilder methodBuilder, MethodInfo methodInfo, String message)
		{
			Type returnType = methodInfo.ReturnType;
			ILGenerator generator = methodBuilder.GetILGenerator ();
			ParameterInfo[] parameterInfos = methodInfo.GetParameters ();

			if (returnType == typeof(void)) {
				MethodInfo sendMessageInvoker = EmitInfos.OBJECTIVECRUNTIME_SENDMESSAGE_VOID_ARGS;

				// Makes the actual call
				generator.Emit (OpCodes.Ldarg_0);
				generator.Emit (OpCodes.Ldstr, message);
				EmitParametersAsArrayOnStack (generator, parameterInfos);
				generator.Emit (OpCodes.Call, sendMessageInvoker);

				generator.Emit (OpCodes.Ret);
			} else {
				MethodInfo sendMessageInvoker = EmitInfos.OBJECTIVECRUNTIME_SENDMESSAGE_ARGS_GENERIC.MakeGenericMethod (returnType);

				// Makes the actual call
				generator.Emit (OpCodes.Ldarg_0);
				generator.Emit (OpCodes.Ldstr, message);
				EmitParametersAsArrayOnStack (generator, parameterInfos);
				generator.Emit (OpCodes.Call, sendMessageInvoker);

				generator.Emit (OpCodes.Ret);
			}
		}
Пример #9
0
		public PropertyEmitter(TypeBuilder owner, string name, Type propertyType, FieldBuilder propertyChangedField) {
			this.owner = owner;
			this.propertyChangedField = propertyChangedField;
			fieldBuilder = owner.DefineField(String.Format("<{0}>", name), propertyType, FieldAttributes.Private);
			getterBuilder = owner.DefineMethod(String.Format("get_{0}", name), MethodAttributes.Public|MethodAttributes.Virtual|MethodAttributes.HideBySig|MethodAttributes.SpecialName, propertyType, Type.EmptyTypes);
			ILGenerator getterIl = getterBuilder.GetILGenerator();
			getterIl.Emit(OpCodes.Ldarg_0);
			getterIl.Emit(OpCodes.Ldfld, fieldBuilder);
			getterIl.Emit(OpCodes.Ret);
			setterBuilder = owner.DefineMethod(String.Format("set_{0}", name), MethodAttributes.Public|MethodAttributes.Virtual|MethodAttributes.HideBySig|MethodAttributes.SpecialName, typeof(void), new[] {propertyType});
			ILGenerator setterIl = setterBuilder.GetILGenerator();
			setterIl.Emit(OpCodes.Ldarg_0);
			setterIl.Emit(OpCodes.Ldarg_1);
			setterIl.Emit(OpCodes.Stfld, fieldBuilder);
			if (propertyChangedField != null) {
				setterIl.Emit(OpCodes.Ldarg_0);
				setterIl.Emit(OpCodes.Dup);
				setterIl.Emit(OpCodes.Ldfld, propertyChangedField);
				setterIl.Emit(OpCodes.Ldstr, name);
				setterIl.Emit(OpCodes.Call, proxyBase_NotifyPropertyChanged);
			}
			setterIl.Emit(OpCodes.Ret);
			propertyBuilder = owner.DefineProperty(name, PropertyAttributes.None, propertyType, null);
			propertyBuilder.SetGetMethod(getterBuilder);
			propertyBuilder.SetSetMethod(setterBuilder);
		}
Пример #10
0
 private static void EmitEmptyImplementation( MethodBuilder vM, Type returnType, ParameterInfo[] parameters )
 {
     ILGenerator gVM = vM.GetILGenerator();
     for( int i = 0; i < parameters.Length; ++i )
     {
         // DefineParameter use 0 for the return parameter.
         ParameterInfo param = parameters[i];
         vM.DefineParameter( i + 1, param.Attributes, param.Name );
         if( param.IsOut )
         {
             Debug.Assert( param.ParameterType.IsByRef, "'Out' is just an attribute on 'by ref' parameters (unfortunate for covariance support)." );
             gVM.StoreDefaultValueForOutParameter( param );
         }
     }
     if( returnType != typeof( void ) )
     {
         if( returnType.GetTypeInfo().IsValueType )
         {
             LocalBuilder retValue = gVM.DeclareLocal( returnType );
             gVM.Emit( OpCodes.Ldloca_S, retValue.LocalIndex );
             gVM.Emit( OpCodes.Initobj, returnType );
             gVM.LdLoc( retValue );
         }
         else
         {
             gVM.Emit( OpCodes.Ldnull );
         }
     }
     gVM.Emit( OpCodes.Ret );
 }
	protected void SetUp () {
		AssemblyName assemblyName = new AssemblyName();
		assemblyName.Name = GetType().FullName;

		AssemblyBuilder assembly 
			= Thread.GetDomain().DefineDynamicAssembly(
				assemblyName, AssemblyBuilderAccess.Run);

		module = assembly.DefineDynamicModule("module1");
		
	    tb = module.DefineType("class1", 
							   TypeAttributes.Public);

		eb = tb.DefineEvent ("event1", EventAttributes.None, typeof (AnEvent));
		mb = 
			tb.DefineMethod ("OnAnEvent",
							 MethodAttributes.Public, typeof (void),
							 new Type [] { typeof (AnEvent) });
		ILGenerator ilgen = mb.GetILGenerator();
		ilgen.Emit (OpCodes.Ret);

		// These two are required
		eb.SetAddOnMethod (mb);
		eb.SetRemoveOnMethod (mb);
	}
Пример #12
0
		public void CreateDynamicMethod()
		{
#if SAVE_ASSEMBLY
			if (_assemblyBuilder == null)
			{
				AssemblyName assemblyName = new AssemblyName("ExpressionAssembly");
				_assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, "I:\\Trash");
				_moduleBuilder = _assemblyBuilder.DefineDynamicModule("ExpressionModule", "ExpressionModule.module");
			}

			string typeName = String.Format("Expression{0}", _typeCount);
			_typeCount++;

			_typeBuilder = _moduleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public);
			
			FieldBuilder filedBuilder = _typeBuilder.DefineField("Source", typeof(string), FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);
			filedBuilder.SetConstant(_source);

			_methodBuilder = _typeBuilder.DefineMethod("Evaluate", MethodAttributes.Public | MethodAttributes.Static, typeof(object), new Type[] { typeof(object[]) });
			_ilGenerator = _methodBuilder.GetILGenerator();
#else
			_dynamicMethod = new DynamicMethod("Expression", typeof(object), new Type[] { typeof(object[]) }, GetType().Module);
			_ilGenerator = _dynamicMethod.GetILGenerator();
#endif
		}
Пример #13
0
 public override void Gen(TypeBuilder program, MethodBuilder method)
 {
     AstNode left = this.child;
     AstNode right = left.sibling;
     left.Gen(program, method);
     right.Gen(program, method);
     method.GetILGenerator().EmitCall(OpCodes.Callvirt, typeof(TypeBase).GetMethod("Equal"), new Type[] { typeof(TypeBase) });
 }
Пример #14
0
        internal void BeginMethod(Type returnType, MethodBuilderInfo methodBuilderInfo, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes)
        {
#if DEBUG
            methodBuilderInfo.Validate(returnType, argTypes, methodAttributes);
#endif
            _methodBuilder = methodBuilderInfo.MethodBuilder;
            _ilGen = _methodBuilder.GetILGenerator();
            InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static);
        }
 private void EmitEqualsObj(TypeBuilder typeBuilder, MethodBuilder method, MethodBuilder typedEqualsMethoed)
 {
     ILGenerator iLGenerator = method.GetILGenerator();
     iLGenerator.Emit(OpCodes.Ldarg_0);
     iLGenerator.Emit(OpCodes.Ldarg_1);
     iLGenerator.Emit(OpCodes.Isinst, typeBuilder);
     iLGenerator.EmitCall(OpCodes.Call, typedEqualsMethoed, null);
     iLGenerator.Emit(OpCodes.Ret);
 }
Пример #16
0
 /// <summary>
 /// Constructs an Emitter using the specified MethodBuilder.
 /// </summary>
 /// <param name="metb">MethodBuilder</param>
 public Emitter(MethodBuilder metb)
 {
     if (metb == null) {
         throw new ArgumentNullException("metb");
     }
     _il = metb.GetILGenerator();
     _temp = new Collection<LocalDescriptor>();
     _code = new Collection<Instruction>();
 }
Пример #17
0
        public static void genDelegateCall(	Type			interfaceType
													,Type[]			parameters
													,MethodBuilder	methodBuilder
													,FieldInfo		invoker
													,FieldInfo		target)
        {
            ILGenerator	IL	=	methodBuilder.GetILGenerator();
            // Declare and initialize the array for passing the parameters.
            IL.DeclareLocal(typeof(object[]));		//loc.0
            IL.DeclareLocal(typeof(MethodInfo));	//loc.1
            IL.DeclareLocal(typeof(object));		//loc.2

            //If there is a return
            if(methodBuilder.ReturnType!=typeof(void))
                IL.DeclareLocal(methodBuilder.ReturnType);	//loc.3
            // Init the args array
            if(parameters==null)
            {
                IL.Emit(OpCodes.Ldnull);
                storeLocal(IL,0);
            }
            else
            {
                loadInt32(IL,parameters.Length);
                IL.Emit(OpCodes.Newarr, typeof(object));
                storeLocal(IL,0);
                // Store the parameters in the new array.
                for(int i = 0; i < parameters.Length; i++)
                {
                    loadLocal(IL,0);//Load the array reference
                    putArgInArray(IL,i, parameters[i]);
                }
            }
            // Store the methodinfo object using the Ldtoken command. Must use the interfaces MethodInfo.
            MethodInfo	mi	=	parameters==null?interfaceType.GetMethod(methodBuilder.Name):interfaceType.GetMethod(methodBuilder.Name,parameters);
            IL.Emit(OpCodes.Ldtoken,mi);
            IL.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle"));
            storeLocal(IL,1);
            IL.Emit(OpCodes.Ldarg_0);		//	Proxy (this)
            IL.Emit(OpCodes.Ldfld, target);	//	The delegate from the proxy
            storeLocal(IL,2);
            // Setup the stack for the delegate call.
            IL.Emit(OpCodes.Ldarg_0);		//	this needed for the load field opcode
            IL.Emit(OpCodes.Ldfld, invoker);//	The delegate from the proxy
            loadLocal(IL,2);
            //IL.Emit(OpCodes.Ldarg_0);		//	1st arg - Proxy (this)
            loadLocal(IL,1);				//	2nd arg - MethodInfo
            loadLocal(IL,0);				//	3rd arg - array of arguments
            IL.Emit(OpCodes.Callvirt,(typeof(Proxy.InvocationDelegate).GetMethod("Invoke")));
            emitReturnFromMethod(IL, methodBuilder.ReturnType);
            if(methodBuilder.ReturnType!=typeof(void))
            {	// Not sure I need to so this but the C# compiler seems to generate this code?
                storeLocal(IL,3);
                loadLocal(IL,3);
            }
            IL.Emit(OpCodes.Ret);
        }
Пример #18
0
 public Function(string name, Type returnType, FuncParam[] parameters, Block body, MethodBuilder info)
 {
     Name = name;
     ReturnType = returnType;
     Params = parameters;
     Body = body;
     Info = info;
     ILGenerator = info.GetILGenerator();
 }
Пример #19
0
 public CodeContext(DefinitionContext next,MethodBuilder method) : base(next)
 {
     if (method == null)
         throw new ArgumentNullException("method");
     this.method = method;
     this.il = method.GetILGenerator();
     this.locals = new Dictionary<string,LocalBuilder>();
     this.parameters = new Dictionary<string,int>();
     this.parametertypes = new List<Type>();
 }
Пример #20
0
		public void EmitMethodBody(MethodBuilder generatedMethod, MethodInfo method, FieldInfo field)
		{
			var IL = generatedMethod.GetILGenerator();

			ParameterInfo[] parameters = method.GetParameters();
			IL.DeclareLocal(typeof (object[]));
			IL.DeclareLocal(typeof (InvocationInfo));
			IL.DeclareLocal(typeof(System.Type[]));

			IL.Emit(OpCodes.Ldarg_0);
			IL.Emit(OpCodes.Callvirt, getInterceptor);

			// if (interceptor == null)
			// 		return base.method(...);

			Label skipBaseCall = IL.DefineLabel();

			IL.Emit(OpCodes.Ldnull);
			IL.Emit(OpCodes.Bne_Un, skipBaseCall);

			IL.Emit(OpCodes.Ldarg_0);

			for (int i = 0; i < method.GetParameters().Length; i++)
				IL.Emit(OpCodes.Ldarg_S, (sbyte)(i + 1));

			IL.Emit(OpCodes.Call, method);
			IL.Emit(OpCodes.Ret);

			IL.MarkLabel(skipBaseCall);

			// Push arguments for InvocationInfo constructor.
			IL.Emit(OpCodes.Ldarg_0);  // 'this' pointer
			PushTargetMethodInfo(IL, generatedMethod, method);
			PushStackTrace(IL);
			PushGenericArguments(method, IL);
			_argumentHandler.PushArguments(parameters, IL, false);

			// InvocationInfo info = new InvocationInfo(...);

			IL.Emit(OpCodes.Newobj, infoConstructor);
			IL.Emit(OpCodes.Stloc_1);

			// this.Interceptor.Intercept(info);
			IL.Emit(OpCodes.Ldarg_0);
			IL.Emit(OpCodes.Callvirt, getInterceptor);
			IL.Emit(OpCodes.Ldloc_1);
			IL.Emit(OpCodes.Callvirt, handlerMethod);

			PackageReturnType(method, IL);
			SaveRefArguments(IL, parameters);

			IL.Emit(OpCodes.Ret);
		}
Пример #21
0
        public override void Gen(TypeBuilder program, MethodBuilder method)
        {
            ILGenerator il = method.GetILGenerator();
            AstNode lowerBound = child;
            AstNode upperBound = child.sibling;

            il.Emit(OpCodes.Newobj, typeof(ArrayBoundType).GetConstructor(new Type[] { }));
            lowerBound.Gen(program, method);
            upperBound.Gen(program, method);
            il.EmitCall(OpCodes.Call, typeof(ArrayBoundType).GetMethod("Append"),
                        new Type[] { typeof(TypeBase), typeof(TypeBase) });
        }
Пример #22
0
 public override MethodInfo BeginMethod(string methodName, Type returnType, Type[] paramTypes, string[] paramNames)
 {
     typeBuilder = _asm.ModuleBuilder.DefineType(methodName, System.Reflection.TypeAttributes.Public);
     methodBuilder = typeBuilder.DefineMethod(
         "R",
         System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Static,
         System.Reflection.CallingConventions.Standard,
         returnType,
         paramTypes
         );
     MsilGen = methodBuilder.GetILGenerator();
     return methodBuilder;
 }
Пример #23
0
        public CodeGenContext(List<Instruction> insList)
        {
            AssemblyName assemblyName = new AssemblyName ();
            assemblyName.Name = ASSEMBLY_NAME;

            assembly = Thread.GetDomain ().DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.RunAndSave, ".");
            module = assembly.DefineDynamicModule ("module1", "ps.dll");
            typeBuilder = module.DefineType ("Shader", TypeAttributes.Public);
            method = typeBuilder.DefineMethod ("Exec", MethodAttributes.Public | MethodAttributes.Static, typeof (void), new Type [] { typeof (ShaderData) });
            ilgen = method.GetILGenerator ();

            this.insList = insList;
        }
 public static void CompileToInstanceMethod(this LambdaExpression expression, MethodBuilder method)
 {
     string uniqueId = Guid.NewGuid().ToString("N");
     TypeBuilder typeBuilder = moduleBuilder.DefineType("t" + uniqueId);
     MethodBuilder methodBuilder = typeBuilder.DefineMethod(
         "m" + uniqueId,
         MethodAttributes.Public | MethodAttributes.Static,
         expression.Type,
         expression.Parameters.Select(parameter => parameter.Type).ToArray());
     expression.CompileToMethod(methodBuilder);
     Type type = typeBuilder.CreateType();
     MethodInfo staticMethod = type.GetMethod("m" + uniqueId);
     new ILReader(staticMethod).Accept(new ILTransform(method.GetILGenerator()));
 }
Пример #25
0
 private static void GenerateMainMethod(MethodBuilder mainMethod, BFMemory memory, string sourceCode)
 {
     ILGenerator ilGen = mainMethod.GetILGenerator();
     var charray = sourceCode
                     .Replace(" ", string.Empty)
                     .Replace("\r", string.Empty)
                     .Replace("\n", string.Empty)
                     .Replace("\t", string.Empty)
                     .ToCharArray();
     using (var generator = new BFGenerator(ilGen, memory))
     {
         foreach (var t in charray)
         {
             switch (t)
             {
                 case '>':
                     generator.GenerateMoveRight();
                     break;
                 case '<':
                     generator.GenerateMoveLeft();
                     break;
                 case '+':
                     generator.GenerateIncrement();
                     break;
                 case '-':
                     generator.GenerateDecrement();
                     break;
                 case '.':
                     generator.GenerateWrite();
                     break;
                 case ',':
                     generator.GenerateRead();
                     break;
                 case '[':
                     generator.GenerateOpenLoop();
                     break;
                 case ']':
                     generator.GenerateCloseLoop();
                     break;
             }
         }
     }
 }
Пример #26
0
        private void GeneratePlangCore(AstNode root)
        {
            // generate all global field
            //foreach (var keyvalue in EnviromentList.Global.table) {
            //    EnviromentNode node = keyvalue.Value;
            //    if( node.Type != "__function__" && node.Type != "__lambda__" )
            //        node.field = program.DefineField(keyvalue.Key, typeof(TypeBase), System.Reflection.FieldAttributes.Private | System.Reflection.FieldAttributes.Static);
            //}

            // then generate global sentenses
            main = program.DefineMethod("Main", System.Reflection.MethodAttributes.Static | System.Reflection.MethodAttributes.Public,
                 System.Reflection.CallingConventions.Standard, typeof(void), null);
            _gen.SetEntryPoint(main);
            AstNode sentense = root;
            while (sentense != null) {
                    sentense.Gen(program, main);
                sentense = sentense.sibling;
            }
            main.GetILGenerator().Emit(OpCodes.Ret);
        }
Пример #27
0
        public BrainfuckApp(string name)
        {
            Name = name;
            _asBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName { Name = "Brainfuck app" }, AssemblyBuilderAccess.Save);
            _modBuilder = _asBuilder.DefineDynamicModule("bf", name + ".exe");
            _typeBuilder = _modBuilder.DefineType("Program", TypeAttributes.Public);
            _methBuilder = _typeBuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static);
            _asBuilder.SetEntryPoint(_methBuilder);
            _il = _methBuilder.GetILGenerator();

            _il.DeclareLocal(typeof(int));
            _il.DeclareLocal(typeof(int[]));

            // Initialize idx to 0
            _il.Emit(OpCodes.Ldc_I4_0);
            _il.Emit(OpCodes.Stloc_0);

            // Initialize cell with 30000 fields of int
            _il.Emit(OpCodes.Ldc_I4, 30000);
            _il.Emit(OpCodes.Newarr, typeof(int));
            _il.Emit(OpCodes.Stloc_1);
        }
        void GenFactoryDelegateMethod()
        {
            // This generates the method that will be wrapped by the delegate in the GetFactory method
            _factoryDelegateMethod = _tb.DefineMethod(
                "FactoryDelegateMethod",
                MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.Static,
                typeof(object),
                _ctorArgTypes.Select(a => typeof(object)).ToArray());

            var gen = _factoryDelegateMethod.GetILGenerator();

            ushort index = 0;
            foreach (var arg in _ctorArgTypes)
            {
                gen.EmitBestLdArg(index);
                gen.Emit(OpCodes.Castclass, arg);
                ++index;
            }

            gen.Emit(OpCodes.Newobj, _ctor);
            gen.Emit(OpCodes.Ret);
        }
Пример #29
0
        public override void Gen(TypeBuilder program, MethodBuilder method)
        {
            AstNode content = child;
            ILGenerator il = method.GetILGenerator();

            var tmp = il.DeclareLocal(typeof(ArrayType));
            il.Emit(OpCodes.Newobj, typeof(ArrayType).GetConstructor(new Type[]{}));
            il.Emit(OpCodes.Stloc, tmp);

            int count = 0;
            while (content != null)
            {
                count++;
                il.Emit(OpCodes.Ldloc, tmp);
                content.Gen(program, method);

                il.EmitCall(OpCodes.Call, typeof(ArrayType).GetMethod("Append"),
                    new Type[] { typeof(TypeBase) });

                content = content.sibling;
            }

            il.Emit(OpCodes.Ldloc, tmp);
        }
Пример #30
0
        public void GenerateIL(stmt Stmt, ILGenerator generator, Context context, Dictionary<string,LocalBuilder> symbolTable, MethodBuilder Method = null, TypeBuilder Class = null)
        {
            ILGenerator ilGenerator;
            if (generator == null)
            {
                if (Method == null)
                {
                    ilGenerator = mainMethod.GetILGenerator();
                }
                else
                {
                    ilGenerator = Method.GetILGenerator();
                }
            }
            else
            {
                ilGenerator = generator;
            }

            if (Class != null)
            {
                if(Stmt is stmt_list)
                {
                    stmt_list list = Stmt as stmt_list; //Cast stmt
                    foreach (stmt s in list.list)
                    {
                        GenerateIL(s, null, context, null, null, Class);
                    }
                }
            }
            else
            {
                if (Stmt is stmt_list)
                {
                    stmt_list list = Stmt as stmt_list; //Cast stmt
                    foreach (stmt s in list.list)
                    {
                        GenerateIL(s, generator, context, symbolTable, Method, null);
                    }
                }
                else if (Stmt is declarevar)
                {
                    declarevar stmt = Stmt as declarevar;
                    mainSymbolTable[stmt.name] = ilGenerator.DeclareLocal(GetILType(stmt.type));

                    GenerateExpr(stmt.value, ilGenerator);
                    StoreLocal(stmt.name, ilGenerator);
                }
                else if (Stmt is setvar)
                {
                    setvar stmt = Stmt as setvar;
                    GenerateExpr(stmt.value, ilGenerator);
                    StoreLocal(stmt.name, ilGenerator);
                }
                else if (Stmt is function_call)
                {
                    function_call stmt = Stmt as function_call;
                    GenerateExpr(stmt.arg, ilGenerator);
                    //ilGenerator.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
                    MethodInfo method = GetMethodInfo(stmt.name, Class, null, GetExprTypes(stmt.arg));
                    MethodInfo rmethod = Type.GetType("System.Console").GetMethod("WriteLine", new Type[] { typeof(string) });
                    if(method == rmethod)
                    {
                        Console.WriteLine("MATCH!");
                    }
                    ilGenerator.Emit(OpCodes.Call, method);
                }
                else if (Stmt is class_definition)
                {
                    class_definition stmt = Stmt as class_definition;
                    GenerateClass(stmt, context);
                }
            }
        }