bba54abd8664a7a82c9c80ec3a2e9651d1aee7b8
[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 ArgumentException ("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                         ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
215                         return ilgen;
216                 }
217
218                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
219                         if (customBuilder == null)
220                                 throw new ArgumentNullException ("customBuilder");
221
222                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
223                         if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
224                                 byte[] data = customBuilder.Data;
225                                 int impla; // the (stupid) ctor takes a short or an int ... 
226                                 impla = (int)data [2];
227                                 impla |= ((int)data [3]) << 8;
228                                 SetImplementationFlags ((MethodImplAttributes)impla);
229                                 return;
230                         }
231                         if (cattrs != null) {
232                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
233                                 cattrs.CopyTo (new_array, 0);
234                                 new_array [cattrs.Length] = customBuilder;
235                                 cattrs = new_array;
236                         } else {
237                                 cattrs = new CustomAttributeBuilder [1];
238                                 cattrs [0] = customBuilder;
239                         }
240                 }
241
242 #if NET_2_0
243                 [ComVisible (true)]
244 #endif
245                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
246                         if (con == null)
247                                 throw new ArgumentNullException ("con");
248                         if (binaryAttribute == null)
249                                 throw new ArgumentNullException ("binaryAttribute");
250
251                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
252                 }
253                 public void SetImplementationFlags( MethodImplAttributes attributes) {
254                         if (type.is_created)
255                                 throw not_after_created ();
256
257                         iattrs = attributes;
258                 }
259                 public Module GetModule() {
260                         return type.Module;
261                 }
262                 public MethodToken GetToken() {
263                         return new MethodToken (0x06000000 | table_idx);
264                 }
265
266                 [MonoTODO]
267                 public void SetSymCustomAttribute( string name, byte[] data) {
268                         if (type.is_created)
269                                 throw not_after_created ();
270                 }
271
272 #if NET_2_0 || BOOTSTRAP_NET_2_0
273                 public override bool Mono_IsInflatedMethod {
274                         get {
275                                 return false;
276                         }
277                 }
278
279                 public override bool HasGenericParameters {
280                         get {
281                                 return false;
282                         }
283                 }
284
285                 public override bool IsGenericMethodDefinition {
286                         get {
287                                 return false;
288                         }
289                 }
290
291                 public override bool IsGenericMethod {
292                         get {
293                                 return false;
294                         }
295                 }
296
297
298                 public override Module Module {
299                         get {
300                                 return base.Module;
301                         }
302                 }
303 #endif
304
305                 public override string ToString() {
306                         return "ConstructorBuilder ['" + type.Name + "']";
307                 }
308
309                 internal void fixup () {
310                         if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
311                         if ((ilgen == null) || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0))
312                                 throw new InvalidOperationException ("Method '" + Name + "' does not have a method body.");
313                         }
314                         if (ilgen != null)
315                                 ilgen.label_fixup ();
316                 }
317                 
318                 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
319                 {
320                         if (ilgen != null && ilgen.HasDebugInfo) {
321                                 SymbolToken token = new SymbolToken (GetToken().Token);
322                                 symbolWriter.OpenMethod (token);
323                                 symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
324                                 ilgen.GenerateDebugInfo (symbolWriter);
325                                 symbolWriter.CloseMethod ();
326                         }
327                 }
328
329                 internal override int get_next_table_index (object obj, int table, bool inc) {
330                         return type.get_next_table_index (obj, table, inc);
331                 }
332
333                 private void RejectIfCreated () {
334                         if (type.is_created)
335                                 throw new InvalidOperationException ("Type definition of the method is complete.");
336                 }
337
338                 private Exception not_supported () {
339                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
340                 }
341
342                 private Exception not_after_created () {
343                         return new InvalidOperationException ("Unable to change after type has been created.");
344                 }
345
346                 void _ConstructorBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
347                 {
348                         throw new NotImplementedException ();
349                 }
350
351                 void _ConstructorBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
352                 {
353                         throw new NotImplementedException ();
354                 }
355
356                 void _ConstructorBuilder.GetTypeInfoCount (out uint pcTInfo)
357                 {
358                         throw new NotImplementedException ();
359                 }
360
361                 void _ConstructorBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
362                 {
363                         throw new NotImplementedException ();
364                 }
365         }
366 }