DefineParameter() 공개 메소드

public DefineParameter ( int position, System attributes, string strParamName ) : System.Reflection.Emit.ParameterBuilder
position int
attributes System
strParamName string
리턴 System.Reflection.Emit.ParameterBuilder
예제 #1
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);
        }
예제 #2
0
 public ILDynamicMethodDebugImpl(string name, Type delegateType, Type thisType)
 {
     _delegateType = delegateType;
     _expectedLength = 64;
     var mi = delegateType.GetMethod("Invoke");
     var uniqueName = ILDynamicTypeDebugImpl.UniqueName(name);
     _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(uniqueName), AssemblyBuilderAccess.RunAndSave, DynamicILDirectoryPath.DynamicIL);
     _moduleBuilder = _assemblyBuilder.DefineDynamicModule(uniqueName + ".dll", true);
     var sourceCodeFileName = Path.Combine(DynamicILDirectoryPath.DynamicIL, uniqueName + ".il");
     _symbolDocumentWriter = _moduleBuilder.DefineDocument(sourceCodeFileName, SymDocumentType.Text, SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
     _sourceCodeWriter = new SourceCodeWriter(sourceCodeFileName, _symbolDocumentWriter);
     Type[] parameterTypes;
     if (thisType != null)
     {
         parameterTypes = new[] { thisType }.Concat(mi.GetParameters().Select(pi => pi.ParameterType)).ToArray();
     }
     else
     {
         parameterTypes = mi.GetParameters().Select(pi => pi.ParameterType).ToArray();
     }
     _sourceCodeWriter.StartMethod(name, mi.ReturnType, parameterTypes, MethodAttributes.Static);
     _typeBuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, typeof(object), Type.EmptyTypes);
     _forbidenInstructions = new ILGenForbidenInstructionsCheating(_typeBuilder);
     _dynamicMethod = _typeBuilder.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Static, mi.ReturnType, parameterTypes);
     for (int i = 0; i < parameterTypes.Length; i++)
     {
         _dynamicMethod.DefineParameter(i + 1, ParameterAttributes.In, string.Format("arg{0}", i));
     }
 }
 internal void Compile(MethodBuilder m)
 {
     if (Builder == null)
     {
         int ofs = (m.IsStatic ? 0 : 1);
         Builder = m.DefineParameter(this.Index + ofs, this.Attributes, this.Name);
     }
 }
예제 #4
0
		public ReturnParameter (MethodBuilder mb, Location location)
		{
			try {
				builder = mb.DefineParameter (0, ParameterAttributes.None, "");			
			}
			catch (ArgumentOutOfRangeException) {
				RootContext.ToplevelTypes.Compiler.Report.RuntimeMissingSupport (location, "custom attributes on the return type");
			}
		}
예제 #5
0
		// TODO: merge method and mb
		public ReturnParameter (MemberCore method, MethodBuilder mb, Location location)
		{
			this.method = method;
			try {
				builder = mb.DefineParameter (0, ParameterAttributes.None, "");			
			}
			catch (ArgumentOutOfRangeException) {
				method.Compiler.Report.RuntimeMissingSupport (location, "custom attributes on the return type");
			}
		}
예제 #6
0
		public ReturnParameter (MethodBuilder mb, Location location):
			base (null)
		{
			try {
				builder = mb.DefineParameter (0, ParameterAttributes.None, "");			
			}
			catch (ArgumentOutOfRangeException) {
				Report.RuntimeMissingSupport (location, "custom attributes on the return type");
			}
		}
예제 #7
0
        public static void DefineParameters(MethodBuilder method, RppParameterInfo[] rppParams)
        {
            Type[] paramTypes = ParametersTypes(rppParams);
            method.SetParameters(paramTypes);

            int index = 1;
            foreach (var param in rppParams)
            {
                param.Index = index; // In static args should start from 1
                method.DefineParameter(index, ParameterAttributes.None, param.Name);
                index++;
            }
        }
예제 #8
0
        private static void AdjustParameterTypes(ParameterInfo[] parameters,
                                                 Func <Type, Type> typeReplacer,
                                                 MethodDefinition method)
        {
            var fixedParams = new Type[parameters.Length];

            foreach (var parameter in parameters)
            {
                var paramType = typeReplacer(parameter.ParameterType);
                fixedParams[parameter.Position] = paramType;
                method.DefineParameter(parameter.Position, parameter.Attributes, parameter.Name);
            }
            // Set fixed parameters having correct generic parameters.
            method.SetParameters(fixedParams);

            // Set fixed return type with correct generic parameter.
            method.SetReturnType(typeReplacer(method.ReturnType));
        }
예제 #9
0
        /// <summary>
        /// Copies the method signature from one method to another.
        /// This includes generic parameters, constraints and parameters.
        /// </summary>
        /// <param name="sourceMethod">The source method.</param>
        /// <param name="targetMethod">The target method.</param>
        internal static void CopyMethodSignature(MethodInfo sourceMethod, MethodBuilder targetMethod)
        {
            CopyGenericSignature(sourceMethod, targetMethod);

            targetMethod.SetReturnType(sourceMethod.ReturnType);

            // copy the parameters and attributes
            // it seems that we can use the source parameters directly because the target method is derived
            // from the source method
            var parameters = sourceMethod.GetParameters();
            targetMethod.SetParameters(parameters.Select(p => p.ParameterType).ToArray());

            for (int i = 0; i < parameters.Length; i++)
            {
                var parameter = parameters[i];
                targetMethod.DefineParameter(i + 1, parameter.Attributes, parameter.Name);
            }
        }
예제 #10
0
        public void Execute()
        {
            var methodAttributes = MethodAttributes.Public;
            if (isOverride) methodAttributes |= MethodAttributes.Virtual;

            methodBuilder = builderBundle().TypeBuilder.DefineMethod(
                methodName()(),
                methodAttributes,
                returnType()(), parameterTypes());

            int counter = 1;
            foreach (Type type in this.parameterTypes())
            {
                methodBuilder.DefineParameter(counter, ParameterAttributes.None, type.Name + "_" + counter);
                counter++;
            }

            this.MethodBuilder = new MethodBuilderBundle(builderBundle(), methodBuilder)
                                     {TypeBuilder = builderBundle().TypeBuilder};
        }
예제 #11
0
 public override void DefineMembers(DefinitionContext c)
 {
     if (method != null)
         throw new InvalidOperationException();
     if (!c.Types.TryGetValue(returntype,out realreturntype))
     {
         throw new ApplicationException();
     }
     realparametertypes = new Type [parametertypes.Length + 1];
     realparametertypes[0] = typeof(ScriptEnvironment);
     for (int i = 0;i < parametertypes.Length;i++)
     {
         if (!c.Types.TryGetValue(parametertypes[i],out realparametertypes[i + 1]))
         {
             throw new ApplicationException();
         }
     }
     method = c.Module.DefineGlobalMethod(name,MethodAttributes.Static | MethodAttributes.Public,realreturntype,realparametertypes);
     for (int i = 0;i < parameternames.Length;i++)
     {
         method.DefineParameter(i + 1,ParameterAttributes.None,parameternames[i]);
     }
     c.DefineMethod(name,method);
 }
예제 #12
0
파일: parameter.cs 프로젝트: afaerber/mono
		public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
		{
			if (mb == null)
				builder = cb.DefineParameter (index, Attributes, Name);
			else
				builder = mb.DefineParameter (index, Attributes, Name);

			if (OptAttributes != null)
				OptAttributes.Emit ();

			if (HasDefaultValue) {
				//
				// Emit constant values for true constants only, the other
				// constant-like expressions will rely on default value expression
				//
				Constant c = default_expr as Constant;
				if (c != null) {
					if (default_expr.Type == TypeManager.decimal_type) {
						builder.SetCustomAttribute (Const.CreateDecimalConstantAttribute (c));
					} else {
						builder.SetConstant (c.GetTypedValue ());
					}
				}
			}

			if (parameter_type == InternalType.Dynamic) {
				PredefinedAttributes.Get.Dynamic.EmitAttribute (builder);
			} else {
				var trans_flags = TypeManager.HasDynamicTypeUsed (parameter_type);
				if (trans_flags != null) {
					var pa = PredefinedAttributes.Get.DynamicTransform;
					if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
						builder.SetCustomAttribute (
							new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
					}
				}
			}
		}
 /// <summary>
 /// Applies attributes to proxied method's parameters.
 /// </summary>
 /// <param name="methodBuilder">The method builder to use.</param>
 /// <param name="targetMethod">The proxied method.</param>
 /// <see cref="IProxyTypeBuilder.ProxyTargetAttributes"/>
 protected virtual void ApplyMethodParameterAttributes(MethodBuilder methodBuilder, MethodInfo targetMethod)
 {
     foreach (ParameterInfo paramInfo in targetMethod.GetParameters())
     {
         ParameterBuilder parameterBuilder = methodBuilder.DefineParameter(
             (paramInfo.Position + 1), paramInfo.Attributes, paramInfo.Name);
         foreach (object attr in GetMethodParameterAttributes(targetMethod, paramInfo))
         {
             if (attr is CustomAttributeBuilder)
             {
                 parameterBuilder.SetCustomAttribute((CustomAttributeBuilder)attr);
             }
             else if (attr is CustomAttributeData)
             {
                 parameterBuilder.SetCustomAttribute(
                     ReflectionUtils.CreateCustomAttribute((CustomAttributeData)attr));
             }
             else if (attr is Attribute)
             {
                 parameterBuilder.SetCustomAttribute(
                     ReflectionUtils.CreateCustomAttribute((Attribute)attr));
             }
         }
     }
 }
 /// <summary>
 /// Applies attributes to the proxied method's return type.
 /// </summary>
 /// <param name="methodBuilder">The method builder to use.</param>
 /// <param name="targetMethod">The proxied method.</param>
 /// <see cref="IProxyTypeBuilder.ProxyTargetAttributes"/>
 protected virtual void ApplyMethodReturnTypeAttributes(MethodBuilder methodBuilder, MethodInfo targetMethod)
 {
     ParameterBuilder parameterBuilder = methodBuilder.DefineParameter(0, ParameterAttributes.Retval, null);
     foreach (object attr in GetMethodReturnTypeAttributes(targetMethod))
     {
         if (attr is CustomAttributeBuilder)
         {
             parameterBuilder.SetCustomAttribute((CustomAttributeBuilder)attr);
         }
         else if (attr is CustomAttributeData)
         {
             parameterBuilder.SetCustomAttribute(
                 ReflectionUtils.CreateCustomAttribute((CustomAttributeData)attr));
         }
         else if (attr is Attribute)
         {
             parameterBuilder.SetCustomAttribute(
                 ReflectionUtils.CreateCustomAttribute((Attribute)attr));
         }
     }
 }
예제 #15
0
파일: class.cs 프로젝트: emtees/old-code
		public override bool Define (TypeContainer parent)
		{
			EventAttributes e_attr = EventAttributes.RTSpecialName | EventAttributes.SpecialName;

			if (!DoDefine (parent))
				return false;

			if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
				Report.Error (74, Location, "'" + parent.Name + "." + Name +
					      "': abstract event can not have an initializer");
				return false;
			}
			
			if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
				Report.Error (66, Location, "'" + parent.Name + "." + Name +
					      "' : event must be of a delegate type");
				return false;
			}

			Type [] parameter_types = new Type [1];
			parameter_types [0] = MemberType;

			Parameter [] parms = new Parameter [1];
			parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
			InternalParameters ip = new InternalParameters (
				parent, new Parameters (parms, null, Location)); 

			if (!CheckBase (parent))
				return false;

			//
			// Now define the accessors
			//
			AddData = new MethodData (this, "add", TypeManager.void_type,
						  parameter_types, ip, CallingConventions.Standard,
						  (Add != null) ? Add.OptAttributes : null,
						  ModFlags, flags, false);

			if (!AddData.Define (parent))
				return false;

			AddBuilder = AddData.MethodBuilder;
			AddBuilder.DefineParameter (1, ParameterAttributes.None, "value");

			RemoveData = new MethodData (this, "remove", TypeManager.void_type,
						     parameter_types, ip, CallingConventions.Standard,
						     (Remove != null) ? Remove.OptAttributes : null,
						     ModFlags, flags, false);

			if (!RemoveData.Define (parent))
				return false;

			RemoveBuilder = RemoveData.MethodBuilder;
			RemoveBuilder.DefineParameter (1, ParameterAttributes.None, "value");

			if (!IsExplicitImpl){
				EventBuilder = new MyEventBuilder (this,
					parent.TypeBuilder, Name, e_attr, MemberType);
					
				if (Add == null && Remove == null) {
					FieldBuilder = parent.TypeBuilder.DefineField (
						Name, MemberType,
						FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
					TypeManager.RegisterPrivateFieldOfEvent (
						(EventInfo) EventBuilder, FieldBuilder);
					TypeManager.RegisterFieldBase (FieldBuilder, this);
				}
			
				EventBuilder.SetAddOnMethod (AddBuilder);
				EventBuilder.SetRemoveOnMethod (RemoveBuilder);

				if (!TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder)) {
					Report.Error (111, Location,
						      "Class `" + parent.Name +
						      "' already contains a definition for the event `" +
						      Name + "'");
					return false;
				}
			}
			
			return true;
		}
 /// <summary>
 /// Defines method parameters based on proxied method metadata.
 /// </summary>
 /// <param name="methodBuilder">
 /// The <see cref="System.Reflection.Emit.MethodBuilder"/> to use.
 /// </param>
 /// <param name="method">The method to proxy.</param>
 protected void DefineParameters(MethodBuilder methodBuilder, MethodInfo method)
 {
     int n = 1;
     foreach (ParameterInfo param in method.GetParameters())
     {
         ParameterBuilder pb = methodBuilder.DefineParameter(n, param.Attributes, param.Name);
         n++;
     }
 }
예제 #17
0
		public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa)
		{
			if (builder != null)
				throw new InternalErrorException ("builder already exists");

			if (mb == null)
				builder = cb.DefineParameter (index, Attributes, Name);
			else
				builder = mb.DefineParameter (index, Attributes, Name);

			if (OptAttributes != null)
				OptAttributes.Emit ();

			if (HasDefaultValue) {
				//
				// Emit constant values for true constants only, the other
				// constant-like expressions will rely on default value expression
				//
				Constant c = default_expr as Constant;
				if (c != null) {
					if (default_expr.Type == TypeManager.decimal_type) {
						builder.SetCustomAttribute (Const.CreateDecimalConstantAttribute (c, pa));
					} else {
						builder.SetConstant (c.GetTypedValue ());
					}
				}
			}

			if (parameter_type != null) {
				if (parameter_type == InternalType.Dynamic) {
					pa.Dynamic.EmitAttribute (builder);
				} else if (parameter_type.HasDynamicElement) {
					pa.Dynamic.EmitAttribute (builder, parameter_type);
				}
			}
		}
        /// <summary>
        /// Initializes a method.
        /// </summary>
        /// <param name="methodBuilder">The current constructor builder.</param>
        /// <param name="methodInfo">The <see cref="MethodInfo"/> associated with the <paramref name="methodBuilder"/>.</param>
        private static void InitializeMethod(MethodBuilder methodBuilder, MethodInfo methodInfo)
        {
            // Apply method attributes
            foreach (CustomAttributeData cad in CustomAttributeData.GetCustomAttributes(methodInfo))
            {
                CustomAttributeBuilder cab = CreateCustomAttributeBuilder(cad);
                methodBuilder.SetCustomAttribute(cab);
            }

            // Build parameters
            var parameters = methodInfo.GetParameters();
            for (int i = 0; i < parameters.Length; ++i)
            {
                ParameterInfo parameterInfo = parameters[i];

                string parameterName = string.IsNullOrEmpty(parameterInfo.Name) ?
                    "param" + i.ToString(CultureInfo.InvariantCulture) :
                    parameterInfo.Name;

                ParameterBuilder paramBuilder =
                    methodBuilder.DefineParameter(
                        i + 1, // 1-based index!  (0 == return type)
                        parameterInfo.Attributes,
                        parameterName);

                // Apply parameter attributes
                foreach (CustomAttributeData cad in CustomAttributeData.GetCustomAttributes(parameterInfo))
                {
                    CustomAttributeBuilder cab = CreateCustomAttributeBuilder(cad);
                    paramBuilder.SetCustomAttribute(cab);
                }
            }
        }
예제 #19
0
        private void ConvertMethodParameters(ICommonMethodNode value, MethodBuilder methb)
        {
            ParameterBuilder pb = null;
            IParameterNode[] parameters = value.parameters;
            for (int i = 0; i < parameters.Length; i++)
            {
                object default_value = null;
                if (parameters[i].default_value != null)
                    default_value = helper.GetConstantForExpression(parameters[i].default_value);

                ParameterAttributes pa = ParameterAttributes.None;
                //if (value.parameters[i].parameter_type == parameter_type.var)
                //    pa = ParameterAttributes.Retval;
                if (default_value != null)
                    pa |= ParameterAttributes.Optional;
                pb = methb.DefineParameter(i + 1, pa, parameters[i].name);
                if (default_value != null)
                    pb.SetConstant(default_value);
                helper.AddParameter(parameters[i], pb);
                if (parameters[i].is_params)
                    pb.SetCustomAttribute(TypeFactory.ParamArrayAttributeConstructor, new byte[] { 0x1, 0x0, 0x0, 0x0 });
            }
        }
예제 #20
0
		public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
		{
			if (mb == null)
				builder = cb.DefineParameter (index, Attributes, Name);
			else
				builder = mb.DefineParameter (index, Attributes, Name);

			if (OptAttributes != null)
				OptAttributes.Emit ();
		}
예제 #21
0
		public ImplicitParameter (MethodBuilder mb):
			base (null)
		{
			builder = mb.DefineParameter (1, ParameterAttributes.None, "");			
		}
예제 #22
0
        private static void HandleGenericMethodArguments(MethodInfo targetMethod, MethodBuilder method)
        {
            if (targetMethod.ContainsGenericParameters)
            {
                var genericArguments = targetMethod.GetGenericArguments();
                var genericParameters = method.DefineGenericParameters(
                    Array.ConvertAll<Type, string>(genericArguments,
                        new Converter<Type, string>(target => { return target.Name; })));

                for (var i = 0; i < genericParameters.Length; i++)
                {
                    var genericParameter = genericParameters[i];
                    var genericArgument = genericArguments[i];
                    genericParameter.SetGenericParameterAttributes(
                        genericArgument.GenericParameterAttributes);
                    var interfaceConstraints = new List<Type>();
                    Type baseTypeConstraint = null;

                    foreach (Type typeConstraint in genericArgument.GetGenericParameterConstraints())
                    {
                        if (typeConstraint.IsClass)
                        {
                            baseTypeConstraint = typeConstraint;
                        }
                        else
                        {
                            interfaceConstraints.Add(typeConstraint);
                        }
                    }

                    if (baseTypeConstraint != null)
                    {
                        genericParameter.SetBaseTypeConstraint(baseTypeConstraint);
                    }

                    if (interfaceConstraints.Count > 0)
                    {
                        genericParameter.SetInterfaceConstraints(interfaceConstraints.ToArray());
                    }
                }
            }

            for (var i = 0; i < targetMethod.GetParameters().Length; i++)
            {
                var parameterInfo = targetMethod.GetParameters()[i];
                method.DefineParameter(i + 1, parameterInfo.Attributes, parameterInfo.Name);
            }
        }
예제 #23
0
 public static void RegisterBuilders(this IReadOnlyList<ParameterStructure> prm, MethodBuilder builder, bool isInstance)
 {
     for (var i = 0; i < prm.Count; ++i)
     {
         var p = prm[i];
         var pb = builder.DefineParameter(i + 1, p.Attributes, p.Name);
         p.RegisterBuilder(pb, isInstance);
     }
 }
예제 #24
0
		public ImplicitParameter (MethodBuilder mb)
		{
			builder = mb.DefineParameter (1, ParameterAttributes.None, "value");			
		}
예제 #25
0
 public static ParameterBuilder DefineParameterCopy(MethodBuilder builder, int paramIndex, ParameterInfo info) {
     var result = builder.DefineParameter(1 + paramIndex, info.Attributes, info.Name);
     CopyParameterAttributes(info, result);
     return result;
 }
예제 #26
0
 protected void SetCustomAttributes(MethodBuilder mb)
 {
     GenInterface.SetCustomAttributes(mb, MethodMeta);
     if (Parms != null)
     {
         for (int i = 0; i < Parms.count(); i++)
         {
             IPersistentMap meta = GenInterface.ExtractAttributes(RT.meta(Parms.nth(i)));
             if (meta != null && meta.count() > 0)
             {
                 ParameterBuilder pb = mb.DefineParameter(i + 1, ParameterAttributes.None, ((Symbol)Parms.nth(i)).Name);
                 GenInterface.SetCustomAttributes(pb, meta);
             }
         }
     }
 }
		private void SetupParameter (MethodBuilder builder, int index, Type t) {
			ParameterBuilder pb = builder.DefineParameter (index, ParameterAttributes.HasFieldMarshal, string.Format ("arg{0}", index));
			ConstructorInfo cinfo = typeof (MarshalAsAttribute).GetConstructor (new Type[] { typeof (UnmanagedType) });
			FieldInfo mtrfld = typeof (MarshalAsAttribute).GetField ("MarshalTypeRef");
			CustomAttributeBuilder cabuilder = new CustomAttributeBuilder (cinfo, new object [] { UnmanagedType.CustomMarshaler }, new FieldInfo [] { mtrfld }, new object [] { MarshalerForType (t) });

			pb.SetCustomAttribute (cabuilder);
		}
예제 #28
0
        public static void CopyMethodSignature(MethodInfo from, MethodBuilder to, bool substituteDeclaringType) {
            ParameterInfo[] paramInfos = from.GetParameters();
            Type[] parameterTypes = new Type[paramInfos.Length];
            Type[][] parameterRequiredModifiers = null, parameterOptionalModifiers = null;
            Type[] returnRequiredModifiers = null, returnOptionalModifiers = null;

#if !SILVERLIGHT
#if CLR2
            bool copyModopts = !from.IsGenericMethodDefinition || ModopsSupported;
#else
            bool copyModopts = true;
#endif
            if (copyModopts) {    
                returnRequiredModifiers = from.ReturnParameter.GetRequiredCustomModifiers();
                returnOptionalModifiers = from.ReturnParameter.GetOptionalCustomModifiers();
            }
#endif

            for (int i = 0; i < paramInfos.Length; i++) {
                if (substituteDeclaringType && paramInfos[i].ParameterType == from.DeclaringType) {
                    parameterTypes[i] = to.DeclaringType;
                } else {
                    parameterTypes[i] = paramInfos[i].ParameterType;
                }

#if !SILVERLIGHT
                if (copyModopts) {
                    var mods = paramInfos[i].GetRequiredCustomModifiers();
                    if (mods.Length > 0) {
                        if (parameterRequiredModifiers == null) {
                            parameterRequiredModifiers = new Type[paramInfos.Length][];
                        }

                        parameterRequiredModifiers[i] = mods;
                    }

                    mods = paramInfos[i].GetOptionalCustomModifiers();
                    if (mods.Length > 0) {
                        if (parameterOptionalModifiers == null) {
                            parameterOptionalModifiers = new Type[paramInfos.Length][];
                        }

                        parameterOptionalModifiers[i] = mods;
                    }
                }
#endif
            }

            to.SetSignature(
                from.ReturnType, returnRequiredModifiers, returnOptionalModifiers,
                parameterTypes, parameterRequiredModifiers, parameterOptionalModifiers
            );

            CopyGenericMethodAttributes(from, to);

            for (int i = 0; i < paramInfos.Length; i++) {
                to.DefineParameter(i + 1, paramInfos[i].Attributes, paramInfos[i].Name);
            }
        }
예제 #29
0
        private void DefineParameter(MethodBuilder methodBuilder, ConstructorBuilder constructorBuilder, Cci.IParameterDefinition paramDef)
        {
            // No explicit param row is needed if param has no flags (other than optionally IN),
            // no name and no references to the param row, such as CustomAttribute, Constant, or FieldMarshall
            var attributes = paramDef.GetAttributes(_context);
            var defaultValue = paramDef.GetDefaultValue(_context);

            if (defaultValue != null ||
                paramDef.IsOptional ||
                paramDef.IsOut ||
                paramDef.IsMarshalledExplicitly ||
                attributes.Any() ||
                paramDef.Name.Length > 0)
            {
                int index = paramDef is Cci.ReturnValueParameter ? 0 : paramDef.Index + 1;
                ParameterAttributes attrs = (ParameterAttributes)Cci.MetadataWriter.GetParameterFlags(paramDef);

                ParameterBuilder paramBuilder = (methodBuilder != null) ?
                    methodBuilder.DefineParameter(index, attrs, paramDef.Name) :
                    constructorBuilder.DefineParameter(index, attrs, paramDef.Name);

                if (defaultValue != null)
                {
                    object rawValue = defaultValue.Value;
                    if (rawValue == null)
                    {
                        var paramTypeRef = paramDef.GetType(_context);
                        if (paramTypeRef.IsValueType)
                        {
                            SetParameterDefaultStructValue(paramBuilder);
                        }
                        else
                        {
                            paramBuilder.SetConstant(null);
                        }
                    }
                    else
                    {
                        // TODO (tomat): Ref.Emit has too strict checks on the constant type. While it is ok to emit value,
                        // e.g. of type Int16 for parameter of type Int32 to metadata, Ref.Emit checks if these types are Type.IsAssignableFrom.
                        // To make this work we need to convert.
                        //
                        // We also need to support Nullable<T>.
                        if (rawValue.GetType().IsPrimitive)
                        {
                            // parameter type has already been resolved once when defining the method, so just retrive it:
                            Type paramType = ResolveType(paramDef.GetType(_context));

                            if (paramType.IsGenericType && paramType.GetGenericTypeDefinition() == typeof(Nullable<>))
                            {
                                paramType = paramType.GetGenericArguments()[0];
                            }

                            if (paramType.IsEnum)
                            {
                                // If emitting the enum, it isn't "created" as this stage so Enum.GetUnderlyingType() will throw
                                // Otherwise, if the enum is already defined, we should use Enum.GetUnderlyingType() to get the correct type
                                paramType = paramType is TypeBuilder ? paramType.UnderlyingSystemType : Enum.GetUnderlyingType(paramType);
                            }

                            rawValue = Convert.ChangeType(rawValue, paramType, System.Globalization.CultureInfo.InvariantCulture);
                        }

                        paramBuilder.SetConstant(rawValue);
                    }
                }

                if (paramDef.IsMarshalledExplicitly)
                {
                    // FieldMarshal
                    var marshallingInformation = paramDef.MarshallingInformation;

                    if (marshallingInformation != null)
                    {
                        paramBuilder.SetCustomAttribute(GetMarshalAsAttribute(marshallingInformation));
                    }
                    else
                    {
                        Debug.Assert(!paramDef.MarshallingDescriptor.IsDefaultOrEmpty);
                        // TODO:
                        throw new NotImplementedException();
                    }
                }

                EmitCustomAttributes(paramBuilder, attributes);
            }
        }
예제 #30
0
		/// <summary>
		/// Sets attributes of generated override/implement/export stub parameters.
		/// </summary>
		/// <param name="stub">The stub method builder.
		/// </param>
		/// <param name="formalParams">Formal parameters of the implementing PHP method.</param>
		/// <param name="templateParams">Parameters of the overload being overriden/implemented/exported.</param>
		public static void DefineStubParameters(MethodBuilder/*!*/ stub,
			PHP.Core.AST.FormalParam[] formalParams, ParameterInfo[]/*!*/ templateParams)
		{
			for (int i = 0; i < templateParams.Length; i++)
			{
				string name;

				// take the overriding parameter name if available
				if (formalParams != null && i < formalParams.Length) name = formalParams[i].Name.ToString();
				else name = templateParams[i].Name;

				stub.DefineParameter(i + 1, templateParams[i].Attributes, name);
			}
		}
        private void InitializeReturnType(MethodBuilder methodBuilder, MethodReturnType returnType)
        {
            methodBuilder.SetReturnType(ResolveReturnType(returnType));

            ParameterBuilder parameterBuilder = methodBuilder.DefineParameter(0,
                System.Reflection.ParameterAttributes.Retval, null);

            if (returnType.HasConstant)
                parameterBuilder.SetConstant(returnType.Constant);

            metadataPass.Add(delegate
            {
                InitializeCustomAttributes(parameterBuilder.SetCustomAttribute, returnType.CustomAttributes);
            });
        }