2004-04-07 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / MethodBuilder.cs
1
2 //
3 // System.Reflection.Emit/MethodBuilder.cs
4 //
5 // Author:
6 //   Paolo Molaro (lupus@ximian.com)
7 //
8 // (C) 2001 Ximian, Inc.  http://www.ximian.com
9 //
10
11 using System;
12 using System.Reflection;
13 using System.Reflection.Emit;
14 using System.Globalization;
15 using System.Security;
16 using System.Security.Permissions;
17 using System.Runtime.CompilerServices;
18 using System.Runtime.InteropServices;
19
20 namespace System.Reflection.Emit {
21
22         public sealed class MethodBuilder : MethodInfo {
23                 private RuntimeMethodHandle mhandle;
24                 private Type rtype;
25                 private Type[] parameters;
26                 private MethodAttributes attrs;
27                 private MethodImplAttributes iattrs;
28                 private string name;
29                 private int table_idx;
30                 private byte[] code;
31                 private ILGenerator ilgen;
32                 private TypeBuilder type;
33                 private ParameterBuilder[] pinfo;
34                 private CustomAttributeBuilder[] cattrs;
35                 private MethodInfo override_method;
36                 private string pi_dll;
37                 private string pi_entry;
38                 private CharSet ncharset;
39                 private CallingConvention native_cc;
40                 private CallingConventions call_conv;
41                 private bool init_locals = true;
42                 private MonoGenericParam[] generic_params;
43                 private Type[] returnModReq;
44                 private Type[] returnModOpt;
45                 private Type[][] paramModReq;
46                 private Type[][] paramModOpt;
47                 private RefEmitPermissionSet[] permissions;
48
49                 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt) {
50                         this.name = name;
51                         this.attrs = attributes;
52                         this.call_conv = callingConvention;
53                         this.rtype = returnType;
54                         this.returnModReq = returnModReq;
55                         this.returnModOpt = returnModOpt;
56                         this.paramModReq = paramModReq;
57                         this.paramModOpt = paramModOpt;
58                         // The MSDN docs does not specify this, but the MS MethodBuilder
59                         // appends a HasThis flag if the method is not static
60                         if ((attributes & MethodAttributes.Static) == 0)
61                                 this.call_conv |= CallingConventions.HasThis;
62                         if (parameterTypes != null) {
63                                 this.parameters = new Type [parameterTypes.Length];
64                                 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
65                         }
66                         type = tb;
67                         table_idx = get_next_table_index (this, 0x06, true);
68                         //Console.WriteLine ("index for "+name+" set to "+table_idx.ToString());
69                 }
70
71                 internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, 
72                                                                 CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt, 
73                         String dllName, String entryName, CallingConvention nativeCConv, CharSet nativeCharset) 
74                         : this (tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt) {
75                         pi_dll = dllName;
76                         pi_entry = entryName;
77                         native_cc = nativeCConv;
78                         ncharset = nativeCharset;
79                 }
80
81                 public bool InitLocals {
82                         get {return init_locals;}
83                         set {init_locals = value;}
84                 }
85
86                 internal TypeBuilder TypeBuilder {
87                         get {return type;}
88                 }
89
90                 public override RuntimeMethodHandle MethodHandle {
91                         get {
92                                 throw NotSupported ();
93                         }
94                 }
95
96                 public override Type ReturnType {get {return rtype;}}
97                 public override Type ReflectedType {get {return type;}}
98                 public override Type DeclaringType {get {return type;}}
99                 public override string Name {get {return name;}}
100                 public override MethodAttributes Attributes {get {return attrs;}}
101                 public override ICustomAttributeProvider ReturnTypeCustomAttributes {
102                         get {return null;}
103                 }
104
105                 public override CallingConventions CallingConvention { 
106                         get { return call_conv; }
107                 }
108
109                 [MonoTODO]
110                 public string Signature {
111                         get {
112                                 throw new NotImplementedException ();
113                         }
114                 }
115
116                 public MethodToken GetToken() {
117                         return new MethodToken(0x06000000 | table_idx);
118                 }
119                 
120                 public override MethodInfo GetBaseDefinition() {
121                         return this;
122                 }
123                 public override MethodImplAttributes GetMethodImplementationFlags() {
124                         return iattrs;
125                 }
126                 public override ParameterInfo[] GetParameters() {
127                         if (parameters == null)
128                                 return null;
129
130                         ParameterInfo[] retval = new ParameterInfo [parameters.Length];
131                         for (int i = 0; i < parameters.Length; i++) {
132                                 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
133                         }
134                         return retval;
135                 }
136                 
137                 internal override int GetParameterCount ()
138                 {
139                         if (parameters == null)
140                                 return 0;
141                         
142                         return parameters.Length;
143                 }
144
145                 public Module GetModule () {
146                         return type.Module;
147                 }
148
149                 public void CreateMethodBody( byte[] il, int count) {
150                         if ((il != null) && ((count < 0) || (count > il.Length)))
151                                 throw new ArgumentException ("Index was out of range.  Must be non-negative and less than the size of the collection.");
152
153                         if ((code != null) || type.is_created)
154                                 throw new InvalidOperationException ("Type definition of the method is complete.");
155
156                         if (il == null)
157                                 code = null;
158                         else {
159                                 code = new byte [count];
160                                 System.Array.Copy(il, code, count);
161                         }
162                 }
163
164                 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
165                         throw NotSupported ();
166                 }
167                 public override bool IsDefined (Type attribute_type, bool inherit) {
168                         throw NotSupported ();
169                 }
170                 public override object[] GetCustomAttributes( bool inherit) {
171                         throw NotSupported ();
172                 }
173                 public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
174                         throw NotSupported ();
175                 }
176                 public ILGenerator GetILGenerator () {
177                         return GetILGenerator (64);
178                 }
179
180                 public ILGenerator GetILGenerator (int size) {
181                         if (((iattrs & MethodImplAttributes.CodeTypeMask) != 
182                                  MethodImplAttributes.IL) ||
183                                 ((iattrs & MethodImplAttributes.ManagedMask) != 
184                                  MethodImplAttributes.Managed))
185                                 throw new InvalidOperationException ("Method body should not exist.");
186                         if (ilgen != null)
187                                 return ilgen;
188                         ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
189                         return ilgen;
190                 }
191                 
192                 public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
193                 {
194                         //
195                         // Extension: Mono allows position == 0 for the return attribute
196                         //
197                         if ((position < 0) || (position > parameters.Length))
198                                 throw new ArgumentOutOfRangeException ("position");
199
200                         RejectIfCreated ();
201
202                         ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
203                         if (pinfo == null)
204                                 pinfo = new ParameterBuilder [parameters.Length + 1];
205                         pinfo [position] = pb;
206                         return pb;
207                 }
208
209                 internal void fixup () {
210                         if (ilgen != null)
211                                 ilgen.label_fixup ();
212                 }
213
214                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
215                         if (customBuilder == null)
216                                 throw new ArgumentNullException ("customBuilder");
217                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
218                         if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
219                                 byte[] data = customBuilder.Data;
220                                 int impla; // the (stupid) ctor takes a short or an int ... 
221                                 impla = (int)data [2];
222                                 impla |= ((int)data [3]) << 8;
223                                 SetImplementationFlags ((MethodImplAttributes)impla);
224                                 return;
225                         }
226                         if (cattrs != null) {
227                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
228                                 cattrs.CopyTo (new_array, 0);
229                                 new_array [cattrs.Length] = customBuilder;
230                                 cattrs = new_array;
231                         } else {
232                                 cattrs = new CustomAttributeBuilder [1];
233                                 cattrs [0] = customBuilder;
234                         }
235                 }
236                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
237                         if (con == null)
238                                 throw new ArgumentNullException ("con");
239                         if (binaryAttribute == null)
240                                 throw new ArgumentNullException ("binaryAttribute");
241                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
242                 }
243                 public void SetImplementationFlags( MethodImplAttributes attributes) {
244                         RejectIfCreated ();
245                         iattrs = attributes;
246                 }
247
248                 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
249                         if (pset == null)
250                                 throw new ArgumentNullException ("pset");
251                         if ((action == SecurityAction.RequestMinimum) ||
252                                 (action == SecurityAction.RequestOptional) ||
253                                 (action == SecurityAction.RequestRefuse))
254                                 throw new ArgumentException ("Request* values are not permitted", "action");
255
256                         RejectIfCreated ();
257
258                         if (permissions != null) {
259                                 /* Check duplicate actions */
260                                 foreach (RefEmitPermissionSet set in permissions)
261                                         if (set.action == action)
262                                                 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
263
264                                 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
265                                 permissions.CopyTo (new_array, 0);
266                                 permissions = new_array;
267                         }
268                         else
269                                 permissions = new RefEmitPermissionSet [1];
270
271                         permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
272                         attrs |= MethodAttributes.HasSecurity;
273                 }
274
275                 [MonoTODO]
276                 public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
277                 {
278                         RejectIfCreated ();
279                         throw new NotImplementedException ();
280                 }
281
282                 [MonoTODO]
283                 public void SetSymCustomAttribute (string name, byte[] data)
284                 {
285                         RejectIfCreated ();
286                         throw new NotImplementedException ();
287                 }
288
289                 internal override int get_next_table_index (object obj, int table, bool inc) {
290                     return type.get_next_table_index (obj, table, inc);
291                 }
292
293                 internal void set_override (MethodInfo mdecl) {
294                         override_method = mdecl;
295                 }
296
297                 private void RejectIfCreated () {
298                         if (type.is_created)
299                                 throw new InvalidOperationException ("Type definition of the method is complete.");
300                 }
301
302                 private Exception NotSupported () {
303                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
304                 }
305
306 #if NET_1_2
307                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
308                 public override extern MethodInfo BindGenericParameters (Type [] types);
309
310                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
311                 private extern MonoGenericParam define_generic_parameter (string name, int index);
312                 
313                 public Type DefineGenericParameter (string name)
314                 {
315                         int index;
316                         if (generic_params != null) {
317                                 MonoGenericParam[] new_generic_params = new MonoGenericParam [generic_params.Length+1];
318                                 System.Array.Copy (generic_params, new_generic_params, generic_params.Length);
319                                 index = generic_params.Length;
320                                 generic_params = new_generic_params;
321                         } else {
322                                 generic_params = new MonoGenericParam [1];
323                                 index = 0;
324                         }
325
326                         generic_params [index] = define_generic_parameter (name, index);
327                         return generic_params [index];
328                 }
329
330                 public void SetGenericParameterConstraints (int index, Type[] constraints, bool has_ctor_constraint)
331                 {
332                         generic_params [index].SetConstraints (constraints, has_ctor_constraint);
333                 }
334
335                 public override bool Mono_IsInflatedMethod {
336                         get {
337                                 return false;
338                         }
339                 }
340
341                 public override bool HasGenericParameters {
342                         get {
343                                 return generic_params != null;
344                         }
345                 }
346
347                 public override Type[] GetGenericArguments ()
348                 {
349                         if (generic_params == null)
350                                 return new Type [0];
351
352                         Type[] result = new Type [generic_params.Length];
353                         for (int i = 0; i < generic_params.Length; i++)
354                                 result [i] = generic_params [i];
355
356                         return result;
357                 }
358
359                 public void SetGenericMethodSignature (MethodAttributes attributes, CallingConventions callingConvention, Type return_type, Type[] parameter_types)
360                 {
361                         RejectIfCreated ();
362
363                         this.attrs = attributes;
364                         this.call_conv = callingConvention;
365                         if ((attributes & MethodAttributes.Static) == 0)
366                                 this.call_conv |= CallingConventions.HasThis;
367
368                         this.rtype = return_type;
369                         this.parameters = new Type [parameter_types.Length];
370                         System.Array.Copy (parameter_types, this.parameters, parameter_types.Length);
371                 }
372 #endif
373         }
374 }
375