Merge pull request #1079 from esdrubal/webclient_cancel
[mono.git] / mcs / class / corlib / System.Reflection.Emit / TypeBuilder.cs
1 //
2 // System.Reflection.Emit.TypeBuilder.cs
3 //
4 // Author:
5 //   Paolo Molaro (lupus@ximian.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // (C) 2001 Ximian, Inc.  http://www.ximian.com
9 //
10
11 //
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 #if !FULL_AOT_RUNTIME
35 using System;
36 using System.Text;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Globalization;
42 using System.Collections;
43 using System.Security;
44 using System.Security.Permissions;
45 using System.Diagnostics.SymbolStore;
46
47 #if !NET_4_5
48 using TypeInfo = System.Type;
49 #endif
50
51 namespace System.Reflection.Emit
52 {
53         [ComVisible (true)]
54         [ComDefaultInterface (typeof (_TypeBuilder))]
55         [ClassInterface (ClassInterfaceType.None)]
56         [StructLayout (LayoutKind.Sequential)]
57         public sealed class TypeBuilder : TypeInfo, _TypeBuilder
58         {
59 #pragma warning disable 169             
60                 #region Sync with reflection.h
61                 private string tname;
62                 private string nspace;
63                 private Type parent;
64                 private Type nesting_type;
65                 internal Type[] interfaces;
66                 internal int num_methods;
67                 internal MethodBuilder[] methods;
68                 internal ConstructorBuilder[] ctors;
69                 internal PropertyBuilder[] properties;
70                 internal int num_fields;
71                 internal FieldBuilder[] fields;
72                 internal EventBuilder[] events;
73                 private CustomAttributeBuilder[] cattrs;
74                 internal TypeBuilder[] subtypes;
75                 internal TypeAttributes attrs;
76                 private int table_idx;
77                 private ModuleBuilder pmodule;
78                 private int class_size;
79                 private PackingSize packing_size;
80                 private IntPtr generic_container;
81                 private GenericTypeParameterBuilder[] generic_params;
82                 private RefEmitPermissionSet[] permissions;
83                 private TypeInfo created;
84                 #endregion
85 #pragma warning restore 169             
86                 
87                 string fullname;
88                 bool createTypeCalled;
89                 private Type underlying_type;
90
91                 public const int UnspecifiedTypeSize = 0;
92                 
93                 protected override TypeAttributes GetAttributeFlagsImpl ()
94                 {
95                         return attrs;
96                 }
97                 
98                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
99                 private extern void setup_internal_class (TypeBuilder tb);
100                 
101                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
102                 private extern void create_internal_class (TypeBuilder tb);
103                 
104                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
105                 private extern void setup_generic_class ();
106
107                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
108                 private extern void create_generic_class ();
109
110                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
111                 private extern EventInfo get_event_info (EventBuilder eb);
112
113                 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr, int table_idx)
114                 {
115                         this.parent = null;
116                         this.attrs = attr;
117                         this.class_size = UnspecifiedTypeSize;
118                         this.table_idx = table_idx;
119                         fullname = this.tname = table_idx == 1 ? "<Module>" : "type_" + table_idx.ToString ();
120                         this.nspace = String.Empty;
121                         pmodule = mb;
122                         setup_internal_class (this);
123                 }
124
125                 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type)
126                 {
127                         int sep_index;
128                         this.parent = parent;
129                         this.attrs = attr;
130                         this.class_size = type_size;
131                         this.packing_size = packing_size;
132                         this.nesting_type = nesting_type;
133
134                         check_name ("fullname", name);
135
136                         if (parent == null && (attr & TypeAttributes.Interface) != 0 && (attr & TypeAttributes.Abstract) == 0)
137                                 throw new InvalidOperationException ("Interface must be declared abstract.");
138
139                         sep_index = name.LastIndexOf('.');
140                         if (sep_index != -1) {
141                                 this.tname = name.Substring (sep_index + 1);
142                                 this.nspace = name.Substring (0, sep_index);
143                         } else {
144                                 this.tname = name;
145                                 this.nspace = String.Empty;
146                         }
147                         if (interfaces != null) {
148                                 this.interfaces = new Type[interfaces.Length];
149                                 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
150                         }
151                         pmodule = mb;
152
153                         if (((attr & TypeAttributes.Interface) == 0) && (parent == null))
154                                 this.parent = typeof (object);
155
156                         // skip .<Module> ?
157                         table_idx = mb.get_next_table_index (this, 0x02, true);
158                         setup_internal_class (this);
159                         fullname = GetFullName ();
160                 }
161
162                 public override Assembly Assembly {
163                         get {return pmodule.Assembly;}
164                 }
165
166                 public override string AssemblyQualifiedName {
167                         get {
168                                 return fullname + ", " + Assembly.FullName;
169                         }
170                 }
171
172                 public override Type BaseType {
173                         get {
174                                 return parent;
175                         }
176                 }
177
178                 public override Type DeclaringType {
179                         get { return nesting_type; }
180                 }
181
182                 [ComVisible (true)]
183                 public override bool IsSubclassOf (Type c)
184                 {
185                         Type t;
186                         if (c == null)
187                                 return false;
188                         if (c == this)
189                                 return false;
190                         t = parent;
191                         while (t != null) {
192                                 if (c == t)
193                                         return true;
194                                 t = t.BaseType;
195                         }
196                         return false;
197                 }
198
199                 public override Type UnderlyingSystemType {
200                         get {
201                                 if (is_created)
202                                         return created.UnderlyingSystemType;
203
204                                 if (IsEnum) {
205                                         if (underlying_type != null)
206                                                 return underlying_type;
207                                         throw new InvalidOperationException (
208                                                 "Enumeration type is not defined.");
209                                 }
210
211                                 return this;
212                         }
213                 }
214
215                 string GetFullName ()
216                 {
217                         if (nesting_type != null)
218                                 return String.Concat (nesting_type.FullName, "+", tname);
219                         if ((nspace != null) && (nspace.Length > 0))
220                                 return String.Concat (nspace, ".", tname);
221                         return tname;
222                 }
223         
224                 public override string FullName {
225                         get {
226                                 return fullname;
227                         }
228                 }
229         
230                 public override Guid GUID {
231                         get {
232                                 check_created ();
233                                 return created.GUID;
234                         }
235                 }
236
237                 public override Module Module {
238                         get {return pmodule;}
239                 }
240
241                 public override string Name {
242                         get {return tname;}
243                 }
244
245                 public override string Namespace {
246                         get {return nspace;}
247                 }
248
249                 public PackingSize PackingSize {
250                         get {return packing_size;}
251                 }
252
253                 public int Size {
254                         get { return class_size; }
255                 }
256
257                 public override Type ReflectedType {
258                         get { return nesting_type; }
259                 }
260
261                 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
262                 {
263 #if !NET_2_1
264                         if (pset == null)
265                                 throw new ArgumentNullException ("pset");
266                         if ((action == SecurityAction.RequestMinimum) ||
267                                 (action == SecurityAction.RequestOptional) ||
268                                 (action == SecurityAction.RequestRefuse))
269                                 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
270
271                         check_not_created ();
272
273                         if (permissions != null) {
274                                 /* Check duplicate actions */
275                                 foreach (RefEmitPermissionSet set in permissions)
276                                         if (set.action == action)
277                                                 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
278
279                                 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
280                                 permissions.CopyTo (new_array, 0);
281                                 permissions = new_array;
282                         }
283                         else
284                                 permissions = new RefEmitPermissionSet [1];
285
286                         permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
287                         attrs |= TypeAttributes.HasSecurity;
288 #endif
289                 }
290
291                 [ComVisible (true)]
292                 public void AddInterfaceImplementation (Type interfaceType)
293                 {
294                         if (interfaceType == null)
295                                 throw new ArgumentNullException ("interfaceType");
296                         check_not_created ();
297
298                         if (interfaces != null) {
299                                 // Check for duplicates
300                                 foreach (Type t in interfaces)
301                                         if (t == interfaceType)
302                                                 return;
303
304                                 Type[] ifnew = new Type [interfaces.Length + 1];
305                                 interfaces.CopyTo (ifnew, 0);
306                                 ifnew [interfaces.Length] = interfaceType;
307                                 interfaces = ifnew;
308                         } else {
309                                 interfaces = new Type [1];
310                                 interfaces [0] = interfaceType;
311                         }
312                 }
313
314                 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
315                                                                        CallingConventions callConvention, Type[] types,
316                                                                        ParameterModifier[] modifiers)
317                 {
318                         check_created ();
319
320                         if (created == typeof (object)) {
321                                 /* 
322                                  * This happens when building corlib. Calling created.GetConstructor 
323                                  * would return constructors from the real mscorlib, instead of the
324                                  * newly built one.
325                                  */
326
327                                 if (ctors == null)
328                                         return null;
329  
330                                 ConstructorBuilder found = null;
331                                 int count = 0;
332                         
333                                 foreach (ConstructorBuilder cb in ctors) {
334                                         if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
335                                                 continue;
336                                         found = cb;
337                                         count++;
338                                 }
339
340                                 if (count == 0)
341                                         return null;
342                                 if (types == null) {
343                                         if (count > 1)
344                                                 throw new AmbiguousMatchException ();
345                                         return found;
346                                 }
347                                 MethodBase[] match = new MethodBase [count];
348                                 if (count == 1)
349                                         match [0] = found;
350                                 else {
351                                         count = 0;
352                                         foreach (ConstructorInfo m in ctors) {
353                                                 if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
354                                                         continue;
355                                                 match [count++] = m;
356                                         }
357                                 }
358                                 if (binder == null)
359                                         binder = Binder.DefaultBinder;
360                                 return (ConstructorInfo) binder.SelectMethod (bindingAttr, match,
361                                                                                                                           types, modifiers);
362                         }
363
364                         return created.GetConstructor (bindingAttr, binder, 
365                                 callConvention, types, modifiers);
366                 }
367
368                 public override bool IsDefined (Type attributeType, bool inherit)
369                 {
370                         if (!is_created)
371                                 throw new NotSupportedException ();
372                         /*
373                          * MS throws NotSupported here, but we can't because some corlib
374                          * classes make calls to IsDefined.
375                          */
376                         return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
377                 }
378                 
379                 public override object[] GetCustomAttributes(bool inherit)
380                 {
381                         check_created ();
382
383                         return created.GetCustomAttributes (inherit);
384                 }
385                 
386                 public override object[] GetCustomAttributes(Type attributeType, bool inherit)
387                 {
388                         check_created ();
389
390                         return created.GetCustomAttributes (attributeType, inherit);
391                 }
392
393                 public TypeBuilder DefineNestedType (string name)
394                 {
395                         return DefineNestedType (name, TypeAttributes.NestedPrivate,
396                                 pmodule.assemblyb.corlib_object_type, null);
397                 }
398
399                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr)
400                 {
401                         return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
402                 }
403
404                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent)
405                 {
406                         return DefineNestedType (name, attr, parent, null);
407                 }
408
409                 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
410                                                       PackingSize packSize, int typeSize)
411                 {
412                         // Visibility must be NestedXXX
413                         /* This breaks mcs
414                         if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
415                                 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
416                                 throw new ArgumentException ("attr", "Bad type flags for nested type.");
417                         */
418                         if (interfaces != null)
419                                 foreach (Type iface in interfaces)
420                                         if (iface == null)
421                                                 throw new ArgumentNullException ("interfaces");
422
423                         TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packSize, typeSize, this);
424                         res.fullname = res.GetFullName ();
425                         pmodule.RegisterTypeName (res, res.fullname);
426                         if (subtypes != null) {
427                                 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
428                                 System.Array.Copy (subtypes, new_types, subtypes.Length);
429                                 new_types [subtypes.Length] = res;
430                                 subtypes = new_types;
431                         } else {
432                                 subtypes = new TypeBuilder [1];
433                                 subtypes [0] = res;
434                         }
435                         return res;
436                 }
437
438                 [ComVisible (true)]
439                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces)
440                 {
441                         return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
442                 }
443
444                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typeSize)
445                 {
446                         return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typeSize);
447                 }
448
449                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packSize)
450                 {
451                         return DefineNestedType (name, attr, parent, null, packSize, UnspecifiedTypeSize);
452                 }
453
454                 [ComVisible (true)]
455                 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
456                 {
457                         return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
458                 }
459
460                 [ComVisible (true)]
461                 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
462                 {
463                         check_not_created ();
464                         ConstructorBuilder cb = new ConstructorBuilder (this, attributes,
465                                 callingConvention, parameterTypes, requiredCustomModifiers,
466                                 optionalCustomModifiers);
467                         if (ctors != null) {
468                                 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
469                                 System.Array.Copy (ctors, new_ctors, ctors.Length);
470                                 new_ctors [ctors.Length] = cb;
471                                 ctors = new_ctors;
472                         } else {
473                                 ctors = new ConstructorBuilder [1];
474                                 ctors [0] = cb;
475                         }
476                         return cb;
477                 }
478
479                 [ComVisible (true)]
480                 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
481                 {
482                         Type parent_type, old_parent_type;
483
484                         if (parent != null)
485                                 parent_type = parent;
486                         else
487                                 parent_type = pmodule.assemblyb.corlib_object_type;
488
489                         old_parent_type = parent_type;
490                         parent_type = parent_type.InternalResolve ();
491                         /*This avoids corlib to have self references.*/
492                         if (parent_type == typeof (object) || parent_type == typeof (ValueType))
493                                 parent_type = old_parent_type;
494
495                         ConstructorInfo parent_constructor =
496                                 parent_type.GetConstructor (
497                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
498                                         null, Type.EmptyTypes, null);
499                         if (parent_constructor == null) {
500                                 throw new NotSupportedException ("Parent does"
501                                         + " not have a default constructor."
502                                         + " The default constructor must be"
503                                         + " explicitly defined.");
504                         }
505
506                         ConstructorBuilder cb = DefineConstructor (attributes, 
507                                 CallingConventions.Standard, Type.EmptyTypes);
508                         ILGenerator ig = cb.GetILGenerator ();
509                         ig.Emit (OpCodes.Ldarg_0);
510                         ig.Emit (OpCodes.Call, parent_constructor);
511                         ig.Emit (OpCodes.Ret);
512                         return cb;
513                 }
514
515                 private void append_method (MethodBuilder mb)
516                 {
517                         if (methods != null) {
518                                 if (methods.Length == num_methods) {
519                                         MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
520                                         System.Array.Copy (methods, new_methods, num_methods);
521                                         methods = new_methods;
522                                 }
523                         } else {
524                                 methods = new MethodBuilder [1];
525                         }
526                         methods [num_methods] = mb;
527                         num_methods ++;
528                 }
529
530                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
531                 {
532                         return DefineMethod (name, attributes, CallingConventions.Standard,
533                                 returnType, parameterTypes);
534                 }
535
536                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
537                 {
538                         return DefineMethod (name, attributes, callingConvention, returnType,
539                                 null, null, parameterTypes, null, null);
540                 }
541
542                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
543                 {
544                         check_name ("name", name);
545                         check_not_created ();
546                         if (IsInterface && (
547                                 !((attributes & MethodAttributes.Abstract) != 0) || 
548                                 !((attributes & MethodAttributes.Virtual) != 0)) &&
549                                 !(((attributes & MethodAttributes.Static) != 0)))
550                                 throw new ArgumentException ("Interface method must be abstract and virtual.");
551
552                         if (returnType == null)
553                                 returnType = pmodule.assemblyb.corlib_void_type;
554                         MethodBuilder res = new MethodBuilder (this, name, attributes, 
555                                 callingConvention, returnType,
556                                 returnTypeRequiredCustomModifiers,
557                                 returnTypeOptionalCustomModifiers, parameterTypes,
558                                 parameterTypeRequiredCustomModifiers,
559                                 parameterTypeOptionalCustomModifiers);
560                         append_method (res);
561                         return res;
562                 }
563
564                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet)
565                 {
566                         return DefinePInvokeMethod (name, dllName, entryName, attributes,
567                                 callingConvention, returnType, null, null, parameterTypes,
568                                 null, null, nativeCallConv, nativeCharSet);
569                 }
570
571                 public MethodBuilder DefinePInvokeMethod (
572                                                 string name, 
573                                                 string dllName, 
574                                                 string entryName, MethodAttributes attributes, 
575                                                 CallingConventions callingConvention, 
576                                                 Type returnType, 
577                                                 Type[] returnTypeRequiredCustomModifiers, 
578                                                 Type[] returnTypeOptionalCustomModifiers, 
579                                                 Type[] parameterTypes, 
580                                                 Type[][] parameterTypeRequiredCustomModifiers, 
581                                                 Type[][] parameterTypeOptionalCustomModifiers, 
582                                                 CallingConvention nativeCallConv, 
583                                                 CharSet nativeCharSet)
584                 {
585                         check_name ("name", name);
586                         check_name ("dllName", dllName);
587                         check_name ("entryName", entryName);
588                         if ((attributes & MethodAttributes.Abstract) != 0)
589                                 throw new ArgumentException ("PInvoke methods must be static and native and cannot be abstract.");
590                         if (IsInterface)
591                                 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
592                         check_not_created ();
593
594                         MethodBuilder res 
595                                 = new MethodBuilder (
596                                                 this, 
597                                                 name, 
598                                                 attributes, 
599                                                 callingConvention,
600                                                 returnType, 
601                                                 returnTypeRequiredCustomModifiers, 
602                                                 returnTypeOptionalCustomModifiers, 
603                                                 parameterTypes, 
604                                                 parameterTypeRequiredCustomModifiers, 
605                                                 parameterTypeOptionalCustomModifiers,
606                                                 dllName, 
607                                                 entryName, 
608                                                 nativeCallConv, 
609                                                 nativeCharSet);
610                         append_method (res);
611                         return res;
612                 }
613
614                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
615                         return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
616                                 nativeCallConv, nativeCharSet);
617                 }
618
619                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes)
620                 {
621                         return DefineMethod (name, attributes, CallingConventions.Standard);
622                 }
623
624                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention)
625                 {
626                         return DefineMethod (name, attributes, callingConvention, null, null);
627                 }
628
629                 public void DefineMethodOverride (MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
630                 {
631                         if (methodInfoBody == null)
632                                 throw new ArgumentNullException ("methodInfoBody");
633                         if (methodInfoDeclaration == null)
634                                 throw new ArgumentNullException ("methodInfoDeclaration");
635                         check_not_created ();
636                         if (methodInfoBody.DeclaringType != this)
637                                 throw new ArgumentException ("method body must belong to this type");
638
639                         if (methodInfoBody is MethodBuilder) {
640                                 MethodBuilder mb = (MethodBuilder)methodInfoBody;
641                                 mb.set_override (methodInfoDeclaration);
642                         }
643                 }
644
645                 public FieldBuilder DefineField (string fieldName, Type type, FieldAttributes attributes)
646                 {
647                         return DefineField (fieldName, type, null, null, attributes);
648                 }
649
650                 public FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
651                 {
652                         check_name ("fieldName", fieldName);
653                         if (type == typeof (void))
654                                 throw new ArgumentException ("Bad field type in defining field.");
655                         check_not_created ();
656
657                         FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomModifiers, optionalCustomModifiers);
658                         if (fields != null) {
659                                 if (fields.Length == num_fields) {
660                                         FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
661                                         System.Array.Copy (fields, new_fields, num_fields);
662                                         fields = new_fields;
663                                 }
664                                 fields [num_fields] = res;
665                                 num_fields ++;
666                         } else {
667                                 fields = new FieldBuilder [1];
668                                 fields [0] = res;
669                                 num_fields ++;
670                                 create_internal_class (this);
671                         }
672
673                         if (IsEnum) {
674                                 if (underlying_type == null && (attributes & FieldAttributes.Static) == 0)
675                                         underlying_type = type;
676                         }
677
678                         return res;
679                 }
680
681                 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes)
682                 {
683                         return DefineProperty (name, attributes, 0, returnType, null, null, parameterTypes, null, null);
684                 }
685                 
686 #if NET_4_0
687                 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
688                 {
689                         return DefineProperty (name, attributes, callingConvention, returnType , null, null, parameterTypes, null, null);
690                 }       
691 #endif
692
693                 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
694                 {
695                         return DefineProperty (name, attributes, 0, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
696                 }
697                 
698                 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
699                 {
700                         check_name ("name", name);
701                         if (parameterTypes != null)
702                                 foreach (Type param in parameterTypes)
703                                         if (param == null)
704                                                 throw new ArgumentNullException ("parameterTypes");
705                         check_not_created ();
706
707                         PropertyBuilder res = new PropertyBuilder (this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
708
709                         if (properties != null) {
710                                 Array.Resize (ref properties, properties.Length + 1);
711                                 properties [properties.Length - 1] = res;
712                         } else {
713                                 properties = new PropertyBuilder [1] { res };
714                         }
715                         return res;
716                 }
717
718                 [ComVisible (true)]
719                 public ConstructorBuilder DefineTypeInitializer()
720                 {
721                         return DefineConstructor (MethodAttributes.Public |
722                                 MethodAttributes.Static | MethodAttributes.SpecialName |
723                                 MethodAttributes.RTSpecialName, CallingConventions.Standard,
724                                 null);
725                 }
726
727                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
728                 private extern TypeInfo create_runtime_class (TypeBuilder tb);
729
730                 private bool is_nested_in (Type t)
731                 {
732                         while (t != null) {
733                                 if (t == this)
734                                         return true;
735                                 else
736                                         t = t.DeclaringType;
737                         }
738                         return false;
739                 }
740
741                 // Return whenever this type has a ctor defined using DefineMethod ()
742                 private bool has_ctor_method () {
743                         MethodAttributes ctor_attrs = MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
744
745                         for (int i = 0; i < num_methods; ++i) {
746                                 MethodBuilder mb = (MethodBuilder)(methods[i]);
747
748                                 if (mb.Name == ConstructorInfo.ConstructorName && (mb.Attributes & ctor_attrs) == ctor_attrs)
749                                         return true;
750                         }
751
752                         return false;
753             }
754
755                 public Type CreateType ()
756                 {
757                         return CreateTypeInfo ();
758                 }
759                 
760 #if NET_4_5
761                 public
762 #endif
763                 TypeInfo CreateTypeInfo ()
764                 {
765                         /* handle nesting_type */
766                         if (createTypeCalled)
767                                 return created;
768
769                         if (!IsInterface && (parent == null) && (this != pmodule.assemblyb.corlib_object_type) && (FullName != "<Module>")) {
770                                 SetParent (pmodule.assemblyb.corlib_object_type);
771                         }
772
773                         create_generic_class ();
774
775                         // Fire TypeResolve events for fields whose type is an unfinished
776                         // value type.
777                         if (fields != null) {
778                                 foreach (FieldBuilder fb in fields) {
779                                         if (fb == null)
780                                                 continue;
781                                         Type ft = fb.FieldType;
782                                         if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
783                                                 TypeBuilder tb = (TypeBuilder)ft;
784                                                 if (!tb.is_created) {
785                                                         AppDomain.CurrentDomain.DoTypeResolve (tb);
786                                                         if (!tb.is_created) {
787                                                                 // FIXME: We should throw an exception here,
788                                                                 // but mcs expects that the type is created
789                                                                 // even if the exception is thrown
790                                                                 //throw new TypeLoadException ("Could not load type " + tb);
791                                                         }
792                                                 }
793                                         }
794                                 }
795                         }
796
797                         //
798                         // On classes, define a default constructor if not provided
799                         //
800                         if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") && 
801                                 (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method ())
802                                 DefineDefaultConstructor (MethodAttributes.Public);
803
804                         createTypeCalled = true;
805
806                         if ((parent != null) && parent.IsSealed)
807                                 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
808
809                         if (parent == pmodule.assemblyb.corlib_enum_type && methods != null)
810                                 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because it is an enum with methods.");
811
812                         if (methods != null) {
813                                 bool is_concrete = !IsAbstract;
814                                 for (int i = 0; i < num_methods; ++i) {
815                                         MethodBuilder mb = (MethodBuilder)(methods[i]);
816                                         if (is_concrete && mb.IsAbstract)
817                                                 throw new InvalidOperationException ("Type is concrete but has abstract method " + mb);
818                                         mb.check_override ();
819                                         mb.fixup ();
820                                 }
821                         }
822
823                         if (ctors != null){
824                                 foreach (ConstructorBuilder ctor in ctors) 
825                                         ctor.fixup ();
826                         }
827
828                         created = create_runtime_class (this);
829                         if (created != null)
830                                 return created;
831                         return this;
832                 }
833
834                 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
835                 {
836                         symbolWriter.OpenNamespace (this.Namespace);
837
838                         if (methods != null) {
839                                 for (int i = 0; i < num_methods; ++i) {
840                                         MethodBuilder metb = (MethodBuilder) methods[i]; 
841                                         metb.GenerateDebugInfo (symbolWriter);
842                                 }
843                         }
844
845                         if (ctors != null) {
846                                 foreach (ConstructorBuilder ctor in ctors)
847                                         ctor.GenerateDebugInfo (symbolWriter);
848                         }
849                         
850                         symbolWriter.CloseNamespace ();
851
852                         if (subtypes != null) {
853                                 for (int i = 0; i < subtypes.Length; ++i)
854                                         subtypes [i].GenerateDebugInfo (symbolWriter);
855                         }
856                 }
857
858                 [ComVisible (true)]
859                 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
860                 {
861                         if (is_created)
862                                 return created.GetConstructors (bindingAttr);
863
864                         throw new NotSupportedException ();
865                 }
866
867                 internal ConstructorInfo[] GetConstructorsInternal (BindingFlags bindingAttr)
868                 {
869                         if (ctors == null)
870                                 return new ConstructorInfo [0];
871                         ArrayList l = new ArrayList ();
872                         bool match;
873                         MethodAttributes mattrs;
874                         
875                         foreach (ConstructorBuilder c in ctors) {
876                                 match = false;
877                                 mattrs = c.Attributes;
878                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
879                                         if ((bindingAttr & BindingFlags.Public) != 0)
880                                                 match = true;
881                                 } else {
882                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
883                                                 match = true;
884                                 }
885                                 if (!match)
886                                         continue;
887                                 match = false;
888                                 if ((mattrs & MethodAttributes.Static) != 0) {
889                                         if ((bindingAttr & BindingFlags.Static) != 0)
890                                                 match = true;
891                                 } else {
892                                         if ((bindingAttr & BindingFlags.Instance) != 0)
893                                                 match = true;
894                                 }
895                                 if (!match)
896                                         continue;
897                                 l.Add (c);
898                         }
899                         ConstructorInfo[] result = new ConstructorInfo [l.Count];
900                         l.CopyTo (result);
901                         return result;
902                 }
903
904                 public override Type GetElementType ()
905                 {
906                         throw new NotSupportedException ();
907                 }
908
909                 public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
910                 {
911                         check_created ();
912                         return created.GetEvent (name, bindingAttr);
913                 }
914
915                 /* Needed to keep signature compatibility with MS.NET */
916                 public override EventInfo[] GetEvents ()
917                 {
918                         return GetEvents (DefaultBindingFlags);
919                 }
920
921                 public override EventInfo[] GetEvents (BindingFlags bindingAttr)
922                 {
923                         if (is_created)
924                                 return created.GetEvents (bindingAttr);
925                         throw new NotSupportedException ();
926                 }
927
928                 // This is only used from MonoGenericInst.initialize().
929                 internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
930                 {
931                         if (events == null)
932                                 return new EventInfo [0];
933                         ArrayList l = new ArrayList ();
934                         bool match;
935                         MethodAttributes mattrs;
936                         MethodInfo accessor;
937
938                         foreach (EventBuilder eb in events) {
939                                 if (eb == null)
940                                         continue;
941                                 EventInfo c = get_event_info (eb);
942                                 match = false;
943                                 accessor = c.GetAddMethod (true);
944                                 if (accessor == null)
945                                         accessor = c.GetRemoveMethod (true);
946                                 if (accessor == null)
947                                         continue;
948                                 mattrs = accessor.Attributes;
949                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
950                                         if ((bindingAttr & BindingFlags.Public) != 0)
951                                                 match = true;
952                                 } else {
953                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
954                                                 match = true;
955                                 }
956                                 if (!match)
957                                         continue;
958                                 match = false;
959                                 if ((mattrs & MethodAttributes.Static) != 0) {
960                                         if ((bindingAttr & BindingFlags.Static) != 0)
961                                                 match = true;
962                                 } else {
963                                         if ((bindingAttr & BindingFlags.Instance) != 0)
964                                                 match = true;
965                                 }
966                                 if (!match)
967                                         continue;
968                                 l.Add (c);
969                         }
970                         EventInfo[] result = new EventInfo [l.Count];
971                         l.CopyTo (result);
972                         return result;
973                 }
974
975                 public override FieldInfo GetField (string name, BindingFlags bindingAttr)
976                 {
977                         if (created != null)
978                                 return created.GetField (name, bindingAttr);
979
980                         if (fields == null)
981                                 return null;
982
983                         bool match;
984                         FieldAttributes mattrs;
985                         
986                         foreach (FieldInfo c in fields) {
987                                 if (c == null)
988                                         continue;
989                                 if (c.Name != name)
990                                         continue;
991                                 match = false;
992                                 mattrs = c.Attributes;
993                                 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
994                                         if ((bindingAttr & BindingFlags.Public) != 0)
995                                                 match = true;
996                                 } else {
997                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
998                                                 match = true;
999                                 }
1000                                 if (!match)
1001                                         continue;
1002                                 match = false;
1003                                 if ((mattrs & FieldAttributes.Static) != 0) {
1004                                         if ((bindingAttr & BindingFlags.Static) != 0)
1005                                                 match = true;
1006                                 } else {
1007                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1008                                                 match = true;
1009                                 }
1010                                 if (!match)
1011                                         continue;
1012                                 return c;
1013                         }
1014                         return null;
1015                 }
1016
1017                 public override FieldInfo[] GetFields (BindingFlags bindingAttr)
1018                 {
1019                         if (created != null)
1020                                 return created.GetFields (bindingAttr);
1021
1022                         if (fields == null)
1023                                 return new FieldInfo [0];
1024                         ArrayList l = new ArrayList ();
1025                         bool match;
1026                         FieldAttributes mattrs;
1027                         
1028                         foreach (FieldInfo c in fields) {
1029                                 if (c == null)
1030                                         continue;
1031                                 match = false;
1032                                 mattrs = c.Attributes;
1033                                 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
1034                                         if ((bindingAttr & BindingFlags.Public) != 0)
1035                                                 match = true;
1036                                 } else {
1037                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1038                                                 match = true;
1039                                 }
1040                                 if (!match)
1041                                         continue;
1042                                 match = false;
1043                                 if ((mattrs & FieldAttributes.Static) != 0) {
1044                                         if ((bindingAttr & BindingFlags.Static) != 0)
1045                                                 match = true;
1046                                 } else {
1047                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1048                                                 match = true;
1049                                 }
1050                                 if (!match)
1051                                         continue;
1052                                 l.Add (c);
1053                         }
1054                         FieldInfo[] result = new FieldInfo [l.Count];
1055                         l.CopyTo (result);
1056                         return result;
1057                 }
1058
1059                 public override Type GetInterface (string name, bool ignoreCase)
1060                 {
1061                         check_created ();
1062                         return created.GetInterface (name, ignoreCase);
1063                 }
1064                 
1065                 public override Type[] GetInterfaces ()
1066                 {
1067                         if (is_created)
1068                                 return created.GetInterfaces ();
1069
1070                         if (interfaces != null) {
1071                                 Type[] ret = new Type [interfaces.Length];
1072                                 interfaces.CopyTo (ret, 0);
1073                                 return ret;
1074                         } else {
1075                                 return Type.EmptyTypes;
1076                         }
1077                 }
1078
1079                 public override MemberInfo[] GetMember (string name, MemberTypes type,
1080                                                                                                 BindingFlags bindingAttr)
1081                 {
1082                         check_created ();
1083                         return created.GetMember (name, type, bindingAttr);
1084                 }
1085
1086                 public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
1087                 {
1088                         check_created ();
1089                         return created.GetMembers (bindingAttr);
1090                 }
1091
1092                 private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type)
1093                 {
1094                         MethodInfo[] candidates;
1095                         bool match;
1096                         MethodAttributes mattrs;
1097
1098                         if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
1099                                 MethodInfo [] parent_methods = parent.GetMethods (bindingAttr);
1100                                 ArrayList parent_candidates = new ArrayList (parent_methods.Length);
1101
1102                                 bool flatten = (bindingAttr & BindingFlags.FlattenHierarchy) != 0;
1103
1104                                 for (int i = 0; i < parent_methods.Length; i++) {
1105                                         MethodInfo m = parent_methods [i];
1106
1107                                         mattrs = m.Attributes;
1108
1109                                         if (m.IsStatic && !flatten)
1110                                                 continue;
1111
1112                                         switch (mattrs & MethodAttributes.MemberAccessMask) {
1113                                         case MethodAttributes.Public:
1114                                                 match = (bindingAttr & BindingFlags.Public) != 0;
1115                                                 break;
1116                                         case MethodAttributes.Assembly:
1117                                                 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1118                                                 break;
1119                                         case MethodAttributes.Private:
1120                                                 match = false;
1121                                                 break;
1122                                         default:
1123                                                 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1124                                                 break;
1125                                         }
1126
1127                                         if (match)
1128                                                 parent_candidates.Add (m);
1129                                 }
1130
1131                                 if (methods == null) {
1132                                         candidates = new MethodInfo [parent_candidates.Count];
1133                                         parent_candidates.CopyTo (candidates);
1134                                 } else {
1135                                         candidates = new MethodInfo [methods.Length + parent_candidates.Count];
1136                                         parent_candidates.CopyTo (candidates, 0);
1137                                         methods.CopyTo (candidates, parent_candidates.Count);
1138                                 }
1139                         }
1140                         else
1141                                 candidates = methods;
1142
1143                         if (candidates == null)
1144                                 return new MethodInfo [0];
1145
1146                         ArrayList l = new ArrayList ();
1147
1148                         foreach (MethodInfo c in candidates) {
1149                                 if (c == null)
1150                                         continue;
1151                                 if (name != null) {
1152                                         if (String.Compare (c.Name, name, ignoreCase) != 0)
1153                                                 continue;
1154                                 }
1155                                 match = false;
1156                                 mattrs = c.Attributes;
1157                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1158                                         if ((bindingAttr & BindingFlags.Public) != 0)
1159                                                 match = true;
1160                                 } else {
1161                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1162                                                 match = true;
1163                                 }
1164                                 if (!match)
1165                                         continue;
1166                                 match = false;
1167                                 if ((mattrs & MethodAttributes.Static) != 0) {
1168                                         if ((bindingAttr & BindingFlags.Static) != 0)
1169                                                 match = true;
1170                                 } else {
1171                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1172                                                 match = true;
1173                                 }
1174                                 if (!match)
1175                                         continue;
1176                                 l.Add (c);
1177                         }
1178
1179                         MethodInfo[] result = new MethodInfo [l.Count];
1180                         l.CopyTo (result);
1181                         return result;
1182                 }
1183
1184                 public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
1185                 {
1186                         return GetMethodsByName (null, bindingAttr, false, this);
1187                 }
1188
1189                 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
1190                                                              Binder binder,
1191                                                              CallingConventions callConvention,
1192                                                              Type[] types, ParameterModifier[] modifiers)
1193                 {
1194                         check_created ();
1195
1196                         bool ignoreCase = ((bindingAttr & BindingFlags.IgnoreCase) != 0);
1197                         MethodInfo[] methods = GetMethodsByName (name, bindingAttr, ignoreCase, this);
1198                         MethodInfo found = null;
1199                         MethodBase[] match;
1200                         int typesLen = (types != null) ? types.Length : 0;
1201                         int count = 0;
1202                         
1203                         foreach (MethodInfo m in methods) {
1204                                 // Under MS.NET, Standard|HasThis matches Standard...
1205                                 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1206                                         continue;
1207                                 found = m;
1208                                 count++;
1209                         }
1210
1211                         if (count == 0)
1212                                 return null;
1213                         
1214                         if (count == 1 && typesLen == 0) 
1215                                 return found;
1216
1217                         match = new MethodBase [count];
1218                         if (count == 1)
1219                                 match [0] = found;
1220                         else {
1221                                 count = 0;
1222                                 foreach (MethodInfo m in methods) {
1223                                         if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1224                                                 continue;
1225                                         match [count++] = m;
1226                                 }
1227                         }
1228                         
1229                         if (types == null) 
1230                                 return (MethodInfo) Binder.FindMostDerivedMatch (match);
1231
1232                         if (binder == null)
1233                                 binder = Binder.DefaultBinder;
1234                         
1235                         return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
1236                 }
1237
1238                 public override Type GetNestedType (string name, BindingFlags bindingAttr)
1239                 {
1240                         check_created ();
1241
1242                         if (subtypes == null)
1243                                 return null;
1244
1245                         foreach (TypeBuilder t in subtypes) {
1246                                 if (!t.is_created)
1247                                         continue;
1248                                 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1249                                         if ((bindingAttr & BindingFlags.Public) == 0)
1250                                                 continue;
1251                                 } else {
1252                                         if ((bindingAttr & BindingFlags.NonPublic) == 0)
1253                                                 continue;
1254                                 }
1255                                 if (t.Name == name)
1256                                         return t.created;
1257                         }
1258
1259                         return null;
1260                 }
1261
1262                 public override Type[] GetNestedTypes (BindingFlags bindingAttr)
1263                 {
1264                         if (!is_created)
1265                                 throw new NotSupportedException ();
1266
1267                         bool match;
1268                         ArrayList result = new ArrayList ();
1269
1270                         if (subtypes == null)
1271                                 return Type.EmptyTypes;
1272                         foreach (TypeBuilder t in subtypes) {
1273                                 match = false;
1274                                 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1275                                         if ((bindingAttr & BindingFlags.Public) != 0)
1276                                                 match = true;
1277                                 } else {
1278                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1279                                                 match = true;
1280                                 }
1281                                 if (!match)
1282                                         continue;
1283                                 result.Add (t);
1284                         }
1285                         Type[] r = new Type [result.Count];
1286                         result.CopyTo (r);
1287                         return r;
1288                 }
1289
1290                 public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
1291                 {
1292                         if (is_created)
1293                                 return created.GetProperties (bindingAttr);
1294
1295                         if (properties == null)
1296                                 return new PropertyInfo [0];
1297                         ArrayList l = new ArrayList ();
1298                         bool match;
1299                         MethodAttributes mattrs;
1300                         MethodInfo accessor;
1301                         
1302                         foreach (PropertyInfo c in properties) {
1303                                 match = false;
1304                                 accessor = c.GetGetMethod (true);
1305                                 if (accessor == null)
1306                                         accessor = c.GetSetMethod (true);
1307                                 if (accessor == null)
1308                                         continue;
1309                                 mattrs = accessor.Attributes;
1310                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1311                                         if ((bindingAttr & BindingFlags.Public) != 0)
1312                                                 match = true;
1313                                 } else {
1314                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1315                                                 match = true;
1316                                 }
1317                                 if (!match)
1318                                         continue;
1319                                 match = false;
1320                                 if ((mattrs & MethodAttributes.Static) != 0) {
1321                                         if ((bindingAttr & BindingFlags.Static) != 0)
1322                                                 match = true;
1323                                 } else {
1324                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1325                                                 match = true;
1326                                 }
1327                                 if (!match)
1328                                         continue;
1329                                 l.Add (c);
1330                         }
1331                         PropertyInfo[] result = new PropertyInfo [l.Count];
1332                         l.CopyTo (result);
1333                         return result;
1334                 }
1335                 
1336                 protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
1337                 {
1338                         throw not_supported ();
1339                 }
1340
1341                 protected override bool HasElementTypeImpl ()
1342                 {
1343                         // a TypeBuilder can never represent an array, pointer
1344                         if (!is_created)
1345                                 return false;
1346
1347                         return created.HasElementType;
1348                 }
1349
1350                 public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
1351                 {
1352                         check_created ();
1353                         return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
1354                 }
1355
1356                 protected override bool IsArrayImpl ()
1357                 {
1358                         return false; /*A TypeBuilder never represents a non typedef type.*/
1359                 }
1360
1361                 protected override bool IsByRefImpl ()
1362                 {
1363                         return false; /*A TypeBuilder never represents a non typedef type.*/
1364                 }
1365
1366                 protected override bool IsCOMObjectImpl ()
1367                 {
1368                         return ((GetAttributeFlagsImpl () & TypeAttributes.Import) != 0);
1369                 }
1370
1371                 protected override bool IsPointerImpl ()
1372                 {
1373                         return false; /*A TypeBuilder never represents a non typedef type.*/
1374                 }
1375
1376                 protected override bool IsPrimitiveImpl ()
1377                 {
1378                         // FIXME
1379                         return false;
1380                 }
1381
1382                 // FIXME: I doubt just removing this still works.
1383                 protected override bool IsValueTypeImpl ()
1384                 {
1385                         if (this == pmodule.assemblyb.corlib_value_type || this == pmodule.assemblyb.corlib_enum_type)
1386                                 return false;
1387                         Type parent_type = parent;
1388                         while (parent_type != null) {
1389                                 if (parent_type == pmodule.assemblyb.corlib_value_type)
1390                                         return true;
1391                                 parent_type = parent_type.BaseType;
1392                         }
1393                         return false;
1394                 }
1395                 
1396                 public override Type MakeArrayType ()
1397                 {
1398                         return new ArrayType (this, 0);
1399                 }
1400
1401                 public override Type MakeArrayType (int rank)
1402                 {
1403                         if (rank < 1)
1404                                 throw new IndexOutOfRangeException ();
1405                         return new ArrayType (this, rank);
1406                 }
1407
1408                 public override Type MakeByRefType ()
1409                 {
1410                         return new ByRefType (this);
1411                 }
1412
1413                 public override Type MakeGenericType (params Type [] typeArguments)
1414                 {
1415                         //return base.MakeGenericType (typeArguments);
1416
1417                         if (!IsGenericTypeDefinition)
1418                                 throw new InvalidOperationException ("not a generic type definition");
1419                         if (typeArguments == null)
1420                                 throw new ArgumentNullException ("typeArguments");
1421
1422                         if (generic_params.Length != typeArguments.Length)
1423                                 throw new ArgumentException (String.Format ("The type or method has {0} generic parameter(s) but {1} generic argument(s) where provided. A generic argument must be provided for each generic parameter.", generic_params.Length, typeArguments.Length), "typeArguments");
1424
1425                         foreach (Type t in typeArguments) {
1426                                 if (t == null)
1427                                         throw new ArgumentNullException ("typeArguments");                              
1428                         }
1429
1430                         Type[] copy = new Type [typeArguments.Length];
1431                         typeArguments.CopyTo (copy, 0);
1432                         return pmodule.assemblyb.MakeGenericType (this, copy);
1433                 }
1434
1435                 public override Type MakePointerType ()
1436                 {
1437                         return new PointerType (this);
1438                 }
1439
1440                 public override RuntimeTypeHandle TypeHandle {
1441                         get {
1442                                 check_created ();
1443                                 return created.TypeHandle;
1444                         }
1445                 }
1446                 
1447                 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
1448                 {
1449                         if (customBuilder == null)
1450                                 throw new ArgumentNullException ("customBuilder");
1451
1452                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
1453                         if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
1454                                 byte[] data = customBuilder.Data;
1455                                 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
1456                                 layout_kind = (int)data [2];
1457                                 layout_kind |= ((int)data [3]) << 8;
1458                                 attrs &= ~TypeAttributes.LayoutMask;
1459                                 switch ((LayoutKind)layout_kind) {
1460                                 case LayoutKind.Auto:
1461                                         attrs |= TypeAttributes.AutoLayout;
1462                                         break;
1463                                 case LayoutKind.Explicit:
1464                                         attrs |= TypeAttributes.ExplicitLayout;
1465                                         break;
1466                                 case LayoutKind.Sequential:
1467                                         attrs |= TypeAttributes.SequentialLayout;
1468                                         break;
1469                                 default:
1470                                         // we should ignore it since it can be any value anyway...
1471                                         throw new Exception ("Error in customattr");
1472                                 }
1473                                 
1474                                 var ctor_type = customBuilder.Ctor is ConstructorBuilder ? ((ConstructorBuilder)customBuilder.Ctor).parameters[0] : customBuilder.Ctor.GetParametersInternal()[0].ParameterType;
1475                                 int pos = 6;
1476                                 if (ctor_type.FullName == "System.Int16")
1477                                         pos = 4;
1478                                 int nnamed = (int)data [pos++];
1479                                 nnamed |= ((int)data [pos++]) << 8;
1480                                 for (int i = 0; i < nnamed; ++i) {
1481                                         //byte named_type = data [pos++];
1482                                         pos ++;
1483                                         byte type = data [pos++];
1484                                         int len;
1485                                         string named_name;
1486
1487                                         if (type == 0x55) {
1488                                                 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1489                                                 //string named_typename = 
1490                                                 CustomAttributeBuilder.string_from_bytes (data, pos, len);
1491                                                 pos += len;
1492                                                 // FIXME: Check that 'named_type' and 'named_typename' match, etc.
1493                                                 //        See related code/FIXME in mono/mono/metadata/reflection.c
1494                                         }
1495
1496                                         len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1497                                         named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1498                                         pos += len;
1499                                         /* all the fields are integers in StructLayout */
1500                                         int value = (int)data [pos++];
1501                                         value |= ((int)data [pos++]) << 8;
1502                                         value |= ((int)data [pos++]) << 16;
1503                                         value |= ((int)data [pos++]) << 24;
1504                                         switch (named_name) {
1505                                         case "CharSet":
1506                                                 switch ((CharSet)value) {
1507                                                 case CharSet.None:
1508                                                 case CharSet.Ansi:
1509                                                         attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass);
1510                                                         break;
1511                                                 case CharSet.Unicode:
1512                                                         attrs &= ~TypeAttributes.AutoClass;
1513                                                         attrs |= TypeAttributes.UnicodeClass;
1514                                                         break;
1515                                                 case CharSet.Auto:
1516                                                         attrs &= ~TypeAttributes.UnicodeClass;
1517                                                         attrs |= TypeAttributes.AutoClass;
1518                                                         break;
1519                                                 default:
1520                                                         break; // error out...
1521                                                 }
1522                                                 break;
1523                                         case "Pack":
1524                                                 packing_size = (PackingSize)value;
1525                                                 break;
1526                                         case "Size":
1527                                                 class_size = value;
1528                                                 break;
1529                                         default:
1530                                                 break; // error out...
1531                                         }
1532                                 }
1533                                 return;
1534                         } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
1535                                 attrs |= TypeAttributes.SpecialName;
1536                                 return;
1537                         } else if (attrname == "System.SerializableAttribute") {
1538                                 attrs |= TypeAttributes.Serializable;
1539                                 return;
1540                         } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
1541                                 attrs |= TypeAttributes.Import;
1542                                 return;
1543                         } else if (attrname == "System.Security.SuppressUnmanagedCodeSecurityAttribute") {
1544                                 attrs |= TypeAttributes.HasSecurity;
1545                         }
1546
1547                         if (cattrs != null) {
1548                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1549                                 cattrs.CopyTo (new_array, 0);
1550                                 new_array [cattrs.Length] = customBuilder;
1551                                 cattrs = new_array;
1552                         } else {
1553                                 cattrs = new CustomAttributeBuilder [1];
1554                                 cattrs [0] = customBuilder;
1555                         }
1556                 }
1557
1558                 [ComVisible (true)]
1559                 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
1560                 {
1561                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1562                 }
1563
1564                 public EventBuilder DefineEvent (string name, EventAttributes attributes, Type eventtype)
1565                 {
1566                         check_name ("name", name);
1567                         if (eventtype == null)
1568                                 throw new ArgumentNullException ("type");
1569                         check_not_created ();
1570
1571                         EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1572                         if (events != null) {
1573                                 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1574                                 System.Array.Copy (events, new_events, events.Length);
1575                                 new_events [events.Length] = res;
1576                                 events = new_events;
1577                         } else {
1578                                 events = new EventBuilder [1];
1579                                 events [0] = res;
1580                         }
1581                         return res;
1582                 }
1583
1584                 public FieldBuilder DefineInitializedData (string name, byte[] data, FieldAttributes attributes) {
1585                         if (data == null)
1586                                 throw new ArgumentNullException ("data");
1587
1588                         FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
1589                         res.SetRVAData (data);
1590                         return res;
1591                 }
1592
1593                 public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
1594                 {
1595                         if (name == null)
1596                                 throw new ArgumentNullException ("name");
1597                         if (name.Length == 0)
1598                                 throw new ArgumentException ("Empty name is not legal", "name");
1599                         if ((size <= 0) || (size > 0x3f0000))
1600                                 throw new ArgumentException ("Data size must be > 0 and < 0x3f0000");
1601                         check_not_created ();
1602
1603                         string typeName = "$ArrayType$" + size;
1604                         Type datablobtype = pmodule.GetRegisteredType (fullname + "+" + typeName);
1605                         if (datablobtype == null) {
1606                                 TypeBuilder tb = DefineNestedType (typeName,
1607                                         TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1608                                         pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
1609                                 tb.CreateType ();
1610                                 datablobtype = tb;
1611                         }
1612                         return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1613                 }
1614
1615                 public TypeToken TypeToken {
1616                         get {
1617                                 return new TypeToken (0x02000000 | table_idx);
1618                         }
1619                 }
1620
1621                 public void SetParent (Type parent)
1622                 {
1623                         check_not_created ();
1624
1625                         if (parent == null) {
1626                                 if ((attrs & TypeAttributes.Interface) != 0) {
1627                                         if ((attrs & TypeAttributes.Abstract) == 0)
1628                                                 throw new InvalidOperationException ("Interface must be declared abstract.");
1629                                         this.parent = null;
1630                                 } else {
1631                                         this.parent = typeof (object);
1632                                 }
1633                         } else {
1634                                 this.parent = parent;
1635                         }
1636
1637                         // will just set the parent-related bits if called a second time
1638                         setup_internal_class (this);
1639                 }
1640
1641                 internal int get_next_table_index (object obj, int table, bool inc) {
1642                         return pmodule.get_next_table_index (obj, table, inc);
1643                 }
1644
1645                 [ComVisible (true)]
1646                 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1647                 {
1648                         if (created == null)
1649                                 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1650
1651                         return created.GetInterfaceMap (interfaceType);
1652                 }
1653
1654                 internal override Type InternalResolve ()
1655                 {
1656                         check_created ();
1657                         return created;
1658                 }
1659
1660                 internal bool is_created {
1661                         get {
1662                                 return createTypeCalled;
1663                         }
1664                 }
1665
1666                 private Exception not_supported ()
1667                 {
1668                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1669                 }
1670
1671                 private void check_not_created ()
1672                 {
1673                         if (is_created)
1674                                 throw new InvalidOperationException ("Unable to change after type has been created.");
1675                 }
1676
1677                 private void check_created ()
1678                 {
1679                         if (!is_created)
1680                                 throw not_supported ();
1681                 }
1682
1683                 private void check_name (string argName, string name)
1684                 {
1685                         if (name == null)
1686                                 throw new ArgumentNullException (argName);
1687                         if (name.Length == 0)
1688                                 throw new ArgumentException ("Empty name is not legal", argName);
1689                         if (name [0] == ((char)0))
1690                                 throw new ArgumentException ("Illegal name", argName);
1691                 }
1692
1693                 public override String ToString ()
1694                 {
1695                         return FullName;
1696                 }
1697
1698                 [MonoTODO]
1699                 public override bool IsAssignableFrom (Type c)
1700                 {
1701                         return base.IsAssignableFrom (c);
1702                 }
1703
1704                 [MonoTODO ("arrays")]
1705                 internal bool IsAssignableTo (Type c)
1706                 {
1707                         if (c == this)
1708                                 return true;
1709
1710                         if (c.IsInterface) {
1711                                 if (parent != null && is_created) {
1712                                         if (c.IsAssignableFrom (parent))
1713                                                 return true;
1714                                 }
1715
1716                                 if (interfaces == null)
1717                                         return false;
1718                                 foreach (Type t in interfaces)
1719                                         if (c.IsAssignableFrom (t))
1720                                                 return true;
1721                                 if (!is_created)
1722                                         return false;
1723                         }
1724
1725                         if (parent == null)
1726                                 return c == typeof (object);
1727                         else
1728                                 return c.IsAssignableFrom (parent);
1729                 }
1730
1731                 public bool IsCreated ()
1732                 {
1733                         return is_created;
1734                 }
1735
1736                 public override Type[] GetGenericArguments ()
1737                 {
1738                         if (generic_params == null)
1739                                 return null;
1740                         Type[] args = new Type [generic_params.Length];
1741                         generic_params.CopyTo (args, 0);
1742                         return args;
1743                 }
1744
1745                 public override Type GetGenericTypeDefinition ()
1746                 {
1747                         if (generic_params == null)
1748                                 throw new InvalidOperationException ("Type is not generic");
1749                         return this;
1750                 }
1751
1752                 public override bool ContainsGenericParameters {
1753                         get {
1754                                 return generic_params != null;
1755                         }
1756                 }
1757
1758                 public extern override bool IsGenericParameter {
1759                         [MethodImplAttribute(MethodImplOptions.InternalCall)]
1760                         get;
1761                 }
1762
1763                 public override GenericParameterAttributes GenericParameterAttributes {
1764                         get { return GenericParameterAttributes.None; }
1765                 }
1766
1767                 public override bool IsGenericTypeDefinition {
1768                         get {
1769                                 return generic_params != null;
1770                         }
1771                 }
1772
1773                 public override bool IsGenericType {
1774                         get { return IsGenericTypeDefinition; }
1775                 }
1776
1777                 [MonoTODO]
1778                 public override int GenericParameterPosition {
1779                         get {
1780                                 return 0;
1781                         }
1782                 }
1783
1784                 public override MethodBase DeclaringMethod {
1785                         get {
1786                                 return null;
1787                         }
1788                 }
1789
1790                 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
1791                 {
1792                         if (names == null)
1793                                 throw new ArgumentNullException ("names");
1794                         if (names.Length == 0)
1795                                 throw new ArgumentException ("names");
1796
1797                         setup_generic_class ();
1798
1799                         generic_params = new GenericTypeParameterBuilder [names.Length];
1800                         for (int i = 0; i < names.Length; i++) {
1801                                 string item = names [i];
1802                                 if (item == null)
1803                                         throw new ArgumentNullException ("names");
1804                                 generic_params [i] = new GenericTypeParameterBuilder (this, null, item, i);
1805                         }
1806
1807                         return generic_params;
1808                 }
1809
1810                 public static ConstructorInfo GetConstructor (Type type, ConstructorInfo constructor)
1811                 {
1812                         /*FIXME I would expect the same checks of GetMethod here*/
1813                         if (type == null)
1814                                 throw new ArgumentException ("Type is not generic", "type");
1815
1816                         if (!type.IsGenericType)
1817                                 throw new ArgumentException ("Type is not a generic type", "type");
1818
1819                         if (type.IsGenericTypeDefinition)
1820                                 throw new ArgumentException ("Type cannot be a generic type definition", "type");
1821
1822                         if (constructor == null)
1823                                 throw new NullReferenceException (); //MS raises this instead of an ArgumentNullException
1824
1825                         if (!constructor.DeclaringType.IsGenericTypeDefinition)
1826                                 throw new ArgumentException ("constructor declaring type is not a generic type definition", "constructor");
1827                         if (constructor.DeclaringType != type.GetGenericTypeDefinition ())
1828                                 throw new ArgumentException ("constructor declaring type is not the generic type definition of type", "constructor");
1829
1830                         ConstructorInfo res = type.GetConstructor (constructor);
1831                         if (res == null)
1832                                 throw new ArgumentException ("constructor not found");
1833
1834                         return res;
1835                 }
1836
1837                 static bool IsValidGetMethodType (Type type)
1838                 {
1839                         if (type is TypeBuilder || type is MonoGenericClass)
1840                                 return true;
1841                         /*GetMethod() must work with TypeBuilders after CreateType() was called.*/
1842                         if (type.Module is ModuleBuilder)
1843                                 return true;
1844                         if (type.IsGenericParameter)
1845                                 return false;
1846
1847                         Type[] inst = type.GetGenericArguments ();
1848                         if (inst == null)
1849                                 return false;
1850                         for (int i = 0; i < inst.Length; ++i) {
1851                                 if (IsValidGetMethodType (inst [i]))
1852                                         return true;
1853                         }
1854                         return false;
1855                 }
1856
1857                 public static MethodInfo GetMethod (Type type, MethodInfo method)
1858                 {
1859                         if (!IsValidGetMethodType (type))
1860                                 throw new ArgumentException ("type is not TypeBuilder but " + type.GetType (), "type");
1861
1862                         if (type is TypeBuilder && type.ContainsGenericParameters)
1863                                 type = type.MakeGenericType (type.GetGenericArguments ());
1864
1865                         if (!type.IsGenericType)
1866                                 throw new ArgumentException ("type is not a generic type", "type");
1867
1868                         if (!method.DeclaringType.IsGenericTypeDefinition)
1869                                 throw new ArgumentException ("method declaring type is not a generic type definition", "method");
1870                         if (method.DeclaringType != type.GetGenericTypeDefinition ())
1871                                 throw new ArgumentException ("method declaring type is not the generic type definition of type", "method");
1872                         if (method == null)
1873                                 throw new NullReferenceException (); //MS raises this instead of an ArgumentNullException
1874
1875                         MethodInfo res = type.GetMethod (method);
1876                         if (res == null)
1877                                 throw new ArgumentException (String.Format ("method {0} not found in type {1}", method.Name, type));
1878                                 
1879                         return res;
1880                 }
1881
1882                 public static FieldInfo GetField (Type type, FieldInfo field)
1883                 {
1884                         if (!type.IsGenericType)
1885                                 throw new ArgumentException ("Type is not a generic type", "type");
1886
1887                         if (type.IsGenericTypeDefinition)
1888                                 throw new ArgumentException ("Type cannot be a generic type definition", "type");
1889
1890                         if (field is FieldOnTypeBuilderInst)
1891                                 throw new ArgumentException ("The specified field must be declared on a generic type definition.", "field");
1892
1893                         if (field.DeclaringType != type.GetGenericTypeDefinition ())
1894                                 throw new ArgumentException ("field declaring type is not the generic type definition of type", "method");
1895
1896                         FieldInfo res = type.GetField (field);
1897                         if (res == null)
1898                                 throw new System.Exception ("field not found");
1899                         else
1900                                 return res;
1901                 }
1902
1903                 internal TypeCode GetTypeCodeInternal () {
1904                         if (parent == pmodule.assemblyb.corlib_enum_type) {
1905                                 for (int i = 0; i < num_fields; ++i) {
1906                                         FieldBuilder f = fields [i];
1907                                         if (!f.IsStatic)
1908                                                 return Type.GetTypeCode (f.FieldType);
1909                                 }
1910                                 throw new InvalidOperationException ("Enum basetype field not defined");
1911                         } else {
1912                                 return Type.GetTypeCodeInternal (this);
1913                         }
1914                 }
1915
1916
1917                 void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1918                 {
1919                         throw new NotImplementedException ();
1920                 }
1921
1922                 void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1923                 {
1924                         throw new NotImplementedException ();
1925                 }
1926
1927                 void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
1928                 {
1929                         throw new NotImplementedException ();
1930                 }
1931
1932                 void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1933                 {
1934                         throw new NotImplementedException ();
1935                 }
1936
1937                 internal override bool IsUserType {
1938                         get {
1939                                 return false;
1940                         }
1941                 }
1942
1943 #if NET_4_5
1944                 public override bool IsConstructedGenericType {
1945                         get { return false; }
1946                 }
1947
1948                 public override bool IsAssignableFrom (TypeInfo typeInfo)
1949                 {
1950                         return base.IsAssignableFrom (typeInfo);
1951                 }
1952 #endif
1953         }
1954 }
1955 #endif