New test + update.
[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 #if NET_2_0
45         [ComVisible (true)]
46         [ComDefaultInterface (typeof (_ConstructorBuilder))]
47 #endif
48         [ClassInterface (ClassInterfaceType.None)]
49         public sealed class ConstructorBuilder : ConstructorInfo, _ConstructorBuilder {
50                 private RuntimeMethodHandle mhandle;
51                 private ILGenerator ilgen;
52                 private 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                 private 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
65                 internal ConstructorBuilder (TypeBuilder tb, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt) {
66                         attrs = attributes | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
67                         call_conv = callingConvention;
68                         if (parameterTypes != null) {
69                                 for (int i = 0; i < parameterTypes.Length; ++i)
70                                         if (parameterTypes [i] == null)
71                                                 throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
72
73                                 this.parameters = new Type [parameterTypes.Length];
74                                 System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
75                         }
76                         type = tb;
77                         this.paramModReq = paramModReq;
78                         this.paramModOpt = paramModOpt;
79                         table_idx = get_next_table_index (this, 0x06, true);
80
81                         ((ModuleBuilder)tb.Module).RegisterToken (this, GetToken ().Token);
82                 }
83
84 #if NET_2_0
85                 [MonoTODO]
86                 public override CallingConventions CallingConvention {
87                         get { return call_conv; }
88                 }
89 #endif
90                 public bool InitLocals {
91                         get {return init_locals;}
92                         set {init_locals = value;}
93                 }
94
95                 internal TypeBuilder TypeBuilder {
96                         get {return type;}
97                 }
98                 
99                 public override MethodImplAttributes GetMethodImplementationFlags() {
100                         return iattrs;
101                 }
102                 public override ParameterInfo[] GetParameters() {
103                         if (parameters == null)
104                                 return null;
105
106                         ParameterInfo[] retval = new ParameterInfo [parameters.Length];
107                         for (int i = 0; i < parameters.Length; i++) {
108                                 retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i+1], parameters [i], this, i + 1);
109                         }
110
111                         return retval;
112                 }
113                 
114                 internal override int GetParameterCount ()
115                 {
116                         if (parameters == null)
117                                 return 0;
118                         
119                         return parameters.Length;
120                 }
121                 
122                 public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
123                         throw not_supported ();
124                 }
125                 public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) {
126                         throw not_supported ();
127                 }
128
129                 public override RuntimeMethodHandle MethodHandle { 
130                         get {
131                                 return mhandle;
132                         }
133                 }
134
135                 public override MethodAttributes Attributes { 
136                         get {return attrs;} 
137                 }
138                 public override Type ReflectedType { get {return type;}}
139                 public override Type DeclaringType { get {return type;}}
140                 public Type ReturnType { get {return null;}}
141                 public override string Name { 
142                         get {return (attrs & MethodAttributes.Static) != 0 ? ConstructorInfo.TypeConstructorName : ConstructorInfo.ConstructorName;}
143                 }
144                 public string Signature {
145                         get {return "constructor signature";}
146                 }
147
148                 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
149                         if (pset == null)
150                                 throw new ArgumentNullException ("pset");
151                         if ((action == SecurityAction.RequestMinimum) ||
152                                 (action == SecurityAction.RequestOptional) ||
153                                 (action == SecurityAction.RequestRefuse))
154                                 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
155
156                         RejectIfCreated ();
157
158                         if (permissions != null) {
159                                 /* Check duplicate actions */
160                                 foreach (RefEmitPermissionSet set in permissions)
161                                         if (set.action == action)
162                                                 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
163
164                                 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
165                                 permissions.CopyTo (new_array, 0);
166                                 permissions = new_array;
167                         }
168                         else
169                                 permissions = new RefEmitPermissionSet [1];
170
171                         permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
172                         attrs |= MethodAttributes.HasSecurity;
173                 }
174
175                 public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, string strParamName)
176                 {
177                         if ((iSequence < 1) || (iSequence > parameters.Length))
178                                 throw new ArgumentOutOfRangeException ("iSequence");
179                         if (type.is_created)
180                                 throw not_after_created ();
181
182                         ParameterBuilder pb = new ParameterBuilder (this, iSequence, attributes, strParamName);
183                         if (pinfo == null)
184                                 pinfo = new ParameterBuilder [parameters.Length + 1];
185                         pinfo [iSequence] = pb;
186                         return pb;
187                 }
188
189                 public override bool IsDefined (Type attribute_type, bool inherit) {
190                         throw not_supported ();
191                 }
192
193                 public override object [] GetCustomAttributes (bool inherit) {
194                         /*
195                          * On MS.NET, this always returns not_supported, but we can't do this
196                          * since there would be no way to obtain custom attributes of 
197                          * dynamically created ctors.
198                          */
199                         if (type.is_created)
200                                 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
201                         else
202                                 throw not_supported ();
203                 }
204
205                 public override object [] GetCustomAttributes (Type attributeType, bool inherit) {
206                         if (type.is_created)
207                                 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
208                         else
209                                 throw not_supported ();
210                 }
211
212                 public ILGenerator GetILGenerator () {
213                         return GetILGenerator (64);
214                 }
215
216 #if NET_2_0
217                 public
218 #else
219                 internal 
220 #endif
221                 ILGenerator GetILGenerator (int size) {
222                         if (ilgen != null)
223                                 return ilgen;
224                         ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
225                         return ilgen;
226                 }
227
228                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
229                         if (customBuilder == null)
230                                 throw new ArgumentNullException ("customBuilder");
231
232                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
233                         if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
234                                 byte[] data = customBuilder.Data;
235                                 int impla; // the (stupid) ctor takes a short or an int ... 
236                                 impla = (int)data [2];
237                                 impla |= ((int)data [3]) << 8;
238                                 SetImplementationFlags ((MethodImplAttributes)impla);
239                                 return;
240                         }
241                         if (cattrs != null) {
242                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
243                                 cattrs.CopyTo (new_array, 0);
244                                 new_array [cattrs.Length] = customBuilder;
245                                 cattrs = new_array;
246                         } else {
247                                 cattrs = new CustomAttributeBuilder [1];
248                                 cattrs [0] = customBuilder;
249                         }
250                 }
251
252 #if NET_2_0
253                 [ComVisible (true)]
254 #endif
255                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
256                         if (con == null)
257                                 throw new ArgumentNullException ("con");
258                         if (binaryAttribute == null)
259                                 throw new ArgumentNullException ("binaryAttribute");
260
261                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
262                 }
263                 public void SetImplementationFlags( MethodImplAttributes attributes) {
264                         if (type.is_created)
265                                 throw not_after_created ();
266
267                         iattrs = attributes;
268                 }
269                 public Module GetModule() {
270                         return type.Module;
271                 }
272                 public MethodToken GetToken() {
273                         return new MethodToken (0x06000000 | table_idx);
274                 }
275
276                 [MonoTODO]
277                 public void SetSymCustomAttribute( string name, byte[] data) {
278                         if (type.is_created)
279                                 throw not_after_created ();
280                 }
281
282 #if NET_2_0 || BOOTSTRAP_NET_2_0
283                 public override Module Module {
284                         get {
285                                 return base.Module;
286                         }
287                 }
288 #endif
289
290                 public override string ToString() {
291                         return "ConstructorBuilder ['" + type.Name + "']";
292                 }
293
294                 internal void fixup () {
295                         if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
296                         if ((ilgen == null) || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0))
297                                 throw new InvalidOperationException ("Method '" + Name + "' does not have a method body.");
298                         }
299                         if (ilgen != null)
300                                 ilgen.label_fixup ();
301                 }
302                 
303                 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
304                 {
305                         if (ilgen != null && ilgen.HasDebugInfo) {
306                                 SymbolToken token = new SymbolToken (GetToken().Token);
307                                 symbolWriter.OpenMethod (token);
308                                 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
309                                 ilgen.GenerateDebugInfo (symbolWriter);
310                                 symbolWriter.CloseMethod ();
311                         }
312                 }
313
314                 internal override int get_next_table_index (object obj, int table, bool inc) {
315                         return type.get_next_table_index (obj, table, inc);
316                 }
317
318                 private void RejectIfCreated () {
319                         if (type.is_created)
320                                 throw new InvalidOperationException ("Type definition of the method is complete.");
321                 }
322
323                 private Exception not_supported () {
324                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
325                 }
326
327                 private Exception not_after_created () {
328                         return new InvalidOperationException ("Unable to change after type has been created.");
329                 }
330
331                 void _ConstructorBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
332                 {
333                         throw new NotImplementedException ();
334                 }
335
336                 void _ConstructorBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
337                 {
338                         throw new NotImplementedException ();
339                 }
340
341                 void _ConstructorBuilder.GetTypeInfoCount (out uint pcTInfo)
342                 {
343                         throw new NotImplementedException ();
344                 }
345
346                 void _ConstructorBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
347                 {
348                         throw new NotImplementedException ();
349                 }
350         }
351 }