2009-11-16 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / ConstructorBuilder.cs
1 //
2 // System.Reflection.Emit.ConstructorBuilder.cs
3 //
4 // Author:
5 //   Paolo Molaro (lupus@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.  http://www.ximian.com
8 //
9
10 //
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System;
34 using System.Reflection;
35 using System.Reflection.Emit;
36 using System.Globalization;
37 using System.Security;
38 using System.Security.Permissions;
39 using System.Runtime.InteropServices;
40 using System.Diagnostics.SymbolStore;
41
42 namespace System.Reflection.Emit {
43
44         [ComVisible (true)]
45         [ComDefaultInterface (typeof (_ConstructorBuilder))]
46         [ClassInterface (ClassInterfaceType.None)]
47         public sealed class ConstructorBuilder : ConstructorInfo, _ConstructorBuilder {
48         
49 #pragma warning disable 169, 414
50                 private RuntimeMethodHandle mhandle;
51                 private ILGenerator ilgen;
52                 internal Type[] parameters;
53                 private MethodAttributes attrs;
54                 private MethodImplAttributes iattrs;
55                 private int table_idx;
56                 private CallingConventions call_conv;
57                 private TypeBuilder type;
58                 internal ParameterBuilder[] pinfo;
59                 private CustomAttributeBuilder[] cattrs;
60                 private bool init_locals = true;
61                 private Type[][] paramModReq;
62                 private Type[][] paramModOpt;
63                 private RefEmitPermissionSet[] permissions;
64 #pragma warning restore 169, 414
65
66                 internal ConstructorBuilder (TypeBuilder tb, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt)
67                 {
68                         attrs = attributes | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
69                         call_conv = callingConvention;
70                         if (parameterTypes != null) {
71                                 for (int i = 0; i < parameterTypes.Length; ++i)
72                                         if (parameterTypes [i] == null)
73                                                 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
74
75                                 this.parameters = new Type [parameterTypes.Length];
76                                 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
77                         }
78                         type = tb;
79                         this.paramModReq = paramModReq;
80                         this.paramModOpt = paramModOpt;
81                         table_idx = get_next_table_index (this, 0x06, true);
82
83                         ((ModuleBuilder) tb.Module).RegisterToken (this, GetToken ().Token);
84                 }
85
86                 [MonoTODO]
87                 public override CallingConventions CallingConvention {
88                         get {
89                                 return call_conv;
90                         }
91                 }
92
93                 public bool InitLocals {
94                         get {
95                                 return init_locals;
96                         }
97                         set {
98                                 init_locals = value;
99                         }
100                 }
101
102                 internal TypeBuilder TypeBuilder {
103                         get {
104                                 return type;
105                         }
106                 }
107                 
108                 public override MethodImplAttributes GetMethodImplementationFlags ()
109                 {
110                         return iattrs;
111                 }
112
113                 public override ParameterInfo[] GetParameters ()
114                 {
115                         if (!type.is_created && !IsCompilerContext)
116                                 throw not_created ();
117
118                         return GetParametersInternal ();
119                 }
120
121                 internal ParameterInfo [] GetParametersInternal ()
122                 {
123                         if (parameters == null)
124                                 return new ParameterInfo [0];
125
126                         ParameterInfo [] retval = new ParameterInfo [parameters.Length];
127                         for (int i = 0; i < parameters.Length; i++)
128                                 retval [i] = new ParameterInfo (pinfo == null ? null
129                                         : pinfo [i + 1], parameters [i], this, i + 1);
130
131                         return retval;
132                 }
133                 
134                 internal override int GetParameterCount ()
135                 {
136                         if (parameters == null)
137                                 return 0;
138                         
139                         return parameters.Length;
140                 }
141                 
142                 public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
143                 {
144                         throw not_supported ();
145                 }
146
147                 public override object Invoke (BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
148                 {
149                         throw not_supported ();
150                 }
151
152                 public override RuntimeMethodHandle MethodHandle {
153                         get {
154                                 throw not_supported ();
155                         }
156                 }
157
158                 public override MethodAttributes Attributes {
159                         get {
160                                 return attrs;
161                         }
162                 }
163
164                 public override Type ReflectedType {
165                         get {
166                                 return type;
167                         }
168                 }
169
170                 public override Type DeclaringType {
171                         get {
172                                 return type;
173                         }
174                 }
175
176 #if NET_4_0
177                 [Obsolete]
178 #endif
179                 public Type ReturnType {
180                         get {
181                                 return null;
182                         }
183                 }
184
185                 public override string Name {
186                         get {
187                                 return (attrs & MethodAttributes.Static) != 0 ? ConstructorInfo.TypeConstructorName : ConstructorInfo.ConstructorName;
188                         }
189                 }
190
191                 public string Signature {
192                         get {
193                                 return "constructor signature";
194                         }
195                 }
196
197                 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
198                 {
199 #if !NET_2_1
200                         if (pset == null)
201                                 throw new ArgumentNullException ("pset");
202                         if ((action == SecurityAction.RequestMinimum) ||
203                                 (action == SecurityAction.RequestOptional) ||
204                                 (action == SecurityAction.RequestRefuse))
205                                 throw new ArgumentOutOfRangeException ("action", "Request* values are not permitted");
206
207                         RejectIfCreated ();
208
209                         if (permissions != null) {
210                                 /* Check duplicate actions */
211                                 foreach (RefEmitPermissionSet set in permissions)
212                                         if (set.action == action)
213                                                 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
214
215                                 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
216                                 permissions.CopyTo (new_array, 0);
217                                 permissions = new_array;
218                         }
219                         else
220                                 permissions = new RefEmitPermissionSet [1];
221
222                         permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
223                         attrs |= MethodAttributes.HasSecurity;
224 #endif
225                 }
226
227                 public ParameterBuilder DefineParameter (int iSequence, ParameterAttributes attributes, string strParamName)
228                 {
229                         if (iSequence < 1 || iSequence > GetParameterCount ())
230                                 throw new ArgumentOutOfRangeException ("iSequence");
231                         if (type.is_created)
232                                 throw not_after_created ();
233
234                         ParameterBuilder pb = new ParameterBuilder (this, iSequence, attributes, strParamName);
235                         if (pinfo == null)
236                                 pinfo = new ParameterBuilder [parameters.Length + 1];
237                         pinfo [iSequence] = pb;
238                         return pb;
239                 }
240
241                 public override bool IsDefined (Type attributeType, bool inherit)
242                 {
243                         throw not_supported ();
244                 }
245
246                 public override object [] GetCustomAttributes (bool inherit)
247                 {
248                         /*
249                          * On MS.NET, this always returns not_supported, but we can't do this
250                          * since there would be no way to obtain custom attributes of 
251                          * dynamically created ctors.
252                          */
253                         if (type.is_created && IsCompilerContext)
254                                 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
255                         else
256                                 throw not_supported ();
257                 }
258
259                 public override object [] GetCustomAttributes (Type attributeType, bool inherit)
260                 {
261                         if (type.is_created && IsCompilerContext)
262                                 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
263                         else
264                                 throw not_supported ();
265                 }
266
267                 public ILGenerator GetILGenerator ()
268                 {
269                         return GetILGenerator (64);
270                 }
271
272                 public ILGenerator GetILGenerator (int streamSize)
273                 {
274                         if (ilgen != null)
275                                 return ilgen;
276                         ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), streamSize);
277                         return ilgen;
278                 }
279
280                 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
281                 {
282                         if (customBuilder == null)
283                                 throw new ArgumentNullException ("customBuilder");
284
285                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
286                         if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
287                                 byte[] data = customBuilder.Data;
288                                 int impla; // the (stupid) ctor takes a short or an int ... 
289                                 impla = (int)data [2];
290                                 impla |= ((int)data [3]) << 8;
291                                 SetImplementationFlags ((MethodImplAttributes)impla);
292                                 return;
293                         }
294                         if (cattrs != null) {
295                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
296                                 cattrs.CopyTo (new_array, 0);
297                                 new_array [cattrs.Length] = customBuilder;
298                                 cattrs = new_array;
299                         } else {
300                                 cattrs = new CustomAttributeBuilder [1];
301                                 cattrs [0] = customBuilder;
302                         }
303                 }
304
305                 [ComVisible (true)]
306                 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
307                 {
308                         if (con == null)
309                                 throw new ArgumentNullException ("con");
310                         if (binaryAttribute == null)
311                                 throw new ArgumentNullException ("binaryAttribute");
312
313                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
314                 }
315
316                 public void SetImplementationFlags (MethodImplAttributes attributes)
317                 {
318                         if (type.is_created)
319                                 throw not_after_created ();
320
321                         iattrs = attributes;
322                 }
323
324                 public Module GetModule ()
325                 {
326                         return type.Module;
327                 }
328
329                 public MethodToken GetToken ()
330                 {
331                         return new MethodToken (0x06000000 | table_idx);
332                 }
333
334                 [MonoTODO]
335                 public void SetSymCustomAttribute (string name, byte[] data)
336                 {
337                         if (type.is_created)
338                                 throw not_after_created ();
339                 }
340
341                 public override Module Module {
342                         get {
343                                 return base.Module;
344                         }
345                 }
346
347                 public override string ToString ()
348                 {
349                         return "ConstructorBuilder ['" + type.Name + "']";
350                 }
351
352                 internal void fixup ()
353                 {
354                         if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
355                         if ((ilgen == null) || (ilgen.ILOffset == 0))
356                                 throw new InvalidOperationException ("Method '" + Name + "' does not have a method body.");
357                         }
358                         if (ilgen != null)
359                                 ilgen.label_fixup ();
360                 }
361                 
362                 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
363                 {
364                         if (ilgen != null && ilgen.HasDebugInfo) {
365                                 SymbolToken token = new SymbolToken (GetToken().Token);
366                                 symbolWriter.OpenMethod (token);
367                                 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
368                                 ilgen.GenerateDebugInfo (symbolWriter);
369                                 symbolWriter.CloseMethod ();
370                         }
371                 }
372
373                 internal override int get_next_table_index (object obj, int table, bool inc)
374                 {
375                         return type.get_next_table_index (obj, table, inc);
376                 }
377
378                 private bool IsCompilerContext {
379                         get {
380                                 ModuleBuilder mb = (ModuleBuilder) TypeBuilder.Module;
381                                 AssemblyBuilder ab = (AssemblyBuilder) mb.Assembly;
382                                 return ab.IsCompilerContext;
383                         }
384                 }
385
386                 private void RejectIfCreated ()
387                 {
388                         if (type.is_created)
389                                 throw new InvalidOperationException ("Type definition of the method is complete.");
390                 }
391
392                 private Exception not_supported ()
393                 {
394                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
395                 }
396
397                 private Exception not_after_created ()
398                 {
399                         return new InvalidOperationException ("Unable to change after type has been created.");
400                 }
401
402                 private Exception not_created ()
403                 {
404                         return new NotSupportedException ("The type is not yet created.");
405                 }
406
407                 void _ConstructorBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
408                 {
409                         throw new NotImplementedException ();
410                 }
411
412                 void _ConstructorBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
413                 {
414                         throw new NotImplementedException ();
415                 }
416
417                 void _ConstructorBuilder.GetTypeInfoCount (out uint pcTInfo)
418                 {
419                         throw new NotImplementedException ();
420                 }
421
422                 void _ConstructorBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
423                 {
424                         throw new NotImplementedException ();
425                 }
426         }
427 }