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