2009-12-02 Jb Evain <jbevain@novell.com>
[mcs.git] / class / corlib / System.Reflection.Emit / TypeBuilder.cs
blob19302ac9b31f6f48d60e37f845ff9fd3547d3149
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 //
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
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.
34 using System;
35 using System.Text;
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Globalization;
41 using System.Collections;
42 using System.Security;
43 using System.Security.Permissions;
44 using System.Diagnostics.SymbolStore;
46 namespace System.Reflection.Emit
48 [ComVisible (true)]
49 [ComDefaultInterface (typeof (_TypeBuilder))]
50 [ClassInterface (ClassInterfaceType.None)]
51 public sealed class TypeBuilder : Type, _TypeBuilder
53 #pragma warning disable 169
54 #region Sync with reflection.h
55 private string tname;
56 private string nspace;
57 private Type parent;
58 private Type nesting_type;
59 internal Type[] interfaces;
60 internal int num_methods;
61 internal MethodBuilder[] methods;
62 internal ConstructorBuilder[] ctors;
63 internal PropertyBuilder[] properties;
64 internal int num_fields;
65 internal FieldBuilder[] fields;
66 internal EventBuilder[] events;
67 private CustomAttributeBuilder[] cattrs;
68 internal TypeBuilder[] subtypes;
69 internal TypeAttributes attrs;
70 private int table_idx;
71 private ModuleBuilder pmodule;
72 private int class_size;
73 private PackingSize packing_size;
74 private IntPtr generic_container;
75 private GenericTypeParameterBuilder[] generic_params;
76 private RefEmitPermissionSet[] permissions;
77 private Type created;
78 #endregion
79 #pragma warning restore 169
81 string fullname;
82 bool createTypeCalled;
83 private Type underlying_type;
85 public const int UnspecifiedTypeSize = 0;
87 protected override TypeAttributes GetAttributeFlagsImpl ()
89 return attrs;
92 [MethodImplAttribute(MethodImplOptions.InternalCall)]
93 private extern void setup_internal_class (TypeBuilder tb);
95 [MethodImplAttribute(MethodImplOptions.InternalCall)]
96 private extern void create_internal_class (TypeBuilder tb);
98 [MethodImplAttribute(MethodImplOptions.InternalCall)]
99 private extern void setup_generic_class ();
101 [MethodImplAttribute(MethodImplOptions.InternalCall)]
102 private extern void create_generic_class ();
104 [MethodImplAttribute(MethodImplOptions.InternalCall)]
105 private extern EventInfo get_event_info (EventBuilder eb);
107 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr, int table_idx)
109 this.parent = null;
110 this.attrs = attr;
111 this.class_size = UnspecifiedTypeSize;
112 this.table_idx = table_idx;
113 fullname = this.tname = table_idx == 1 ? "<Module>" : "type_" + table_idx.ToString ();
114 this.nspace = String.Empty;
115 pmodule = mb;
116 setup_internal_class (this);
119 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type)
121 int sep_index;
122 this.parent = parent;
123 this.attrs = attr;
124 this.class_size = type_size;
125 this.packing_size = packing_size;
126 this.nesting_type = nesting_type;
128 check_name ("fullname", name);
130 if (parent == null && (attr & TypeAttributes.Interface) != 0 && (attr & TypeAttributes.Abstract) == 0)
131 throw new InvalidOperationException ("Interface must be declared abstract.");
133 sep_index = name.LastIndexOf('.');
134 if (sep_index != -1) {
135 this.tname = name.Substring (sep_index + 1);
136 this.nspace = name.Substring (0, sep_index);
137 } else {
138 this.tname = name;
139 this.nspace = String.Empty;
141 if (interfaces != null) {
142 this.interfaces = new Type[interfaces.Length];
143 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
145 pmodule = mb;
147 if (((attr & TypeAttributes.Interface) == 0) && (parent == null) && !IsCompilerContext)
148 this.parent = typeof (object);
150 // skip .<Module> ?
151 table_idx = mb.get_next_table_index (this, 0x02, true);
152 setup_internal_class (this);
153 fullname = GetFullName ();
156 public override Assembly Assembly {
157 get {return pmodule.Assembly;}
160 public override string AssemblyQualifiedName {
161 get {
162 return fullname + ", " + Assembly.FullName;
166 public override Type BaseType {
167 get {
168 return parent;
172 public override Type DeclaringType {
173 get { return nesting_type; }
176 /* public override bool IsSubclassOf (Type c)
178 Type t;
179 if (c == null)
180 return false;
181 if (c == this)
182 return false;
183 t = parent;
184 while (t != null) {
185 if (c == t)
186 return true;
187 t = t.BaseType;
189 return false;
192 public override Type UnderlyingSystemType {
193 get {
194 if (is_created)
195 return created.UnderlyingSystemType;
197 if (IsEnum && !IsCompilerContext) {
198 if (underlying_type != null)
199 return underlying_type;
200 throw new InvalidOperationException (
201 "Enumeration type is not defined.");
204 return this;
208 string GetFullName ()
210 if (nesting_type != null)
211 return String.Concat (nesting_type.FullName, "+", tname);
212 if ((nspace != null) && (nspace.Length > 0))
213 return String.Concat (nspace, ".", tname);
214 return tname;
217 public override string FullName {
218 get {
219 return fullname;
223 public override Guid GUID {
224 get {
225 check_created ();
226 return created.GUID;
230 public override Module Module {
231 get {return pmodule;}
234 public override string Name {
235 get {return tname;}
238 public override string Namespace {
239 get {return nspace;}
242 public PackingSize PackingSize {
243 get {return packing_size;}
246 public int Size {
247 get { return class_size; }
250 public override Type ReflectedType {
251 get { return nesting_type; }
254 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
256 #if !NET_2_1
257 if (pset == null)
258 throw new ArgumentNullException ("pset");
259 if ((action == SecurityAction.RequestMinimum) ||
260 (action == SecurityAction.RequestOptional) ||
261 (action == SecurityAction.RequestRefuse))
262 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
264 check_not_created ();
266 if (permissions != null) {
267 /* Check duplicate actions */
268 foreach (RefEmitPermissionSet set in permissions)
269 if (set.action == action)
270 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
272 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
273 permissions.CopyTo (new_array, 0);
274 permissions = new_array;
276 else
277 permissions = new RefEmitPermissionSet [1];
279 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
280 attrs |= TypeAttributes.HasSecurity;
281 #endif
284 [ComVisible (true)]
285 public void AddInterfaceImplementation (Type interfaceType)
287 if (interfaceType == null)
288 throw new ArgumentNullException ("interfaceType");
289 check_not_created ();
291 if (interfaces != null) {
292 // Check for duplicates
293 foreach (Type t in interfaces)
294 if (t == interfaceType)
295 return;
297 Type[] ifnew = new Type [interfaces.Length + 1];
298 interfaces.CopyTo (ifnew, 0);
299 ifnew [interfaces.Length] = interfaceType;
300 interfaces = ifnew;
301 } else {
302 interfaces = new Type [1];
303 interfaces [0] = interfaceType;
307 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
308 CallingConventions callConvention, Type[] types,
309 ParameterModifier[] modifiers)
311 check_created ();
313 if (created == typeof (object)) {
315 * This happens when building corlib. Calling created.GetConstructor
316 * would return constructors from the real mscorlib, instead of the
317 * newly built one.
320 if (ctors == null)
321 return null;
323 ConstructorBuilder found = null;
324 int count = 0;
326 foreach (ConstructorBuilder cb in ctors) {
327 if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
328 continue;
329 found = cb;
330 count++;
333 if (count == 0)
334 return null;
335 if (types == null) {
336 if (count > 1)
337 throw new AmbiguousMatchException ();
338 return found;
340 MethodBase[] match = new MethodBase [count];
341 if (count == 1)
342 match [0] = found;
343 else {
344 count = 0;
345 foreach (ConstructorInfo m in ctors) {
346 if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
347 continue;
348 match [count++] = m;
351 if (binder == null)
352 binder = Binder.DefaultBinder;
353 return (ConstructorInfo) binder.SelectMethod (bindingAttr, match,
354 types, modifiers);
357 return created.GetConstructor (bindingAttr, binder,
358 callConvention, types, modifiers);
361 public override bool IsDefined (Type attributeType, bool inherit)
363 if (!is_created && !IsCompilerContext)
364 throw new NotSupportedException ();
366 * MS throws NotSupported here, but we can't because some corlib
367 * classes make calls to IsDefined.
369 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
372 public override object[] GetCustomAttributes(bool inherit)
374 check_created ();
376 return created.GetCustomAttributes (inherit);
379 public override object[] GetCustomAttributes(Type attributeType, bool inherit)
381 check_created ();
383 return created.GetCustomAttributes (attributeType, inherit);
386 public TypeBuilder DefineNestedType (string name)
388 return DefineNestedType (name, TypeAttributes.NestedPrivate,
389 pmodule.assemblyb.corlib_object_type, null);
392 public TypeBuilder DefineNestedType (string name, TypeAttributes attr)
394 return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
397 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent)
399 return DefineNestedType (name, attr, parent, null);
402 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
403 PackingSize packSize, int typeSize)
405 // Visibility must be NestedXXX
406 /* This breaks mcs
407 if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
408 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
409 throw new ArgumentException ("attr", "Bad type flags for nested type.");
411 if (interfaces != null)
412 foreach (Type iface in interfaces)
413 if (iface == null)
414 throw new ArgumentNullException ("interfaces");
416 TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packSize, typeSize, this);
417 res.fullname = res.GetFullName ();
418 pmodule.RegisterTypeName (res, res.fullname);
419 if (subtypes != null) {
420 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
421 System.Array.Copy (subtypes, new_types, subtypes.Length);
422 new_types [subtypes.Length] = res;
423 subtypes = new_types;
424 } else {
425 subtypes = new TypeBuilder [1];
426 subtypes [0] = res;
428 return res;
431 [ComVisible (true)]
432 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces)
434 return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
437 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typeSize)
439 return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typeSize);
442 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packSize)
444 return DefineNestedType (name, attr, parent, null, packSize, UnspecifiedTypeSize);
447 [ComVisible (true)]
448 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
450 return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
453 [ComVisible (true)]
454 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
456 check_not_created ();
457 ConstructorBuilder cb = new ConstructorBuilder (this, attributes,
458 callingConvention, parameterTypes, requiredCustomModifiers,
459 optionalCustomModifiers);
460 if (ctors != null) {
461 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
462 System.Array.Copy (ctors, new_ctors, ctors.Length);
463 new_ctors [ctors.Length] = cb;
464 ctors = new_ctors;
465 } else {
466 ctors = new ConstructorBuilder [1];
467 ctors [0] = cb;
469 return cb;
472 [ComVisible (true)]
473 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
475 Type parent_type;
477 if (parent != null)
478 parent_type = parent;
479 else
480 parent_type = pmodule.assemblyb.corlib_object_type;
482 ConstructorInfo parent_constructor =
483 parent_type.GetConstructor (
484 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
485 null, Type.EmptyTypes, null);
486 if (parent_constructor == null) {
487 throw new NotSupportedException ("Parent does"
488 + " not have a default constructor."
489 + " The default constructor must be"
490 + " explicitly defined.");
493 ConstructorBuilder cb = DefineConstructor (attributes,
494 CallingConventions.Standard, Type.EmptyTypes);
495 ILGenerator ig = cb.GetILGenerator ();
496 ig.Emit (OpCodes.Ldarg_0);
497 ig.Emit (OpCodes.Call, parent_constructor);
498 ig.Emit (OpCodes.Ret);
499 return cb;
502 private void append_method (MethodBuilder mb)
504 if (methods != null) {
505 if (methods.Length == num_methods) {
506 MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
507 System.Array.Copy (methods, new_methods, num_methods);
508 methods = new_methods;
510 } else {
511 methods = new MethodBuilder [1];
513 methods [num_methods] = mb;
514 num_methods ++;
517 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
519 return DefineMethod (name, attributes, CallingConventions.Standard,
520 returnType, parameterTypes);
523 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
525 return DefineMethod (name, attributes, callingConvention, returnType,
526 null, null, parameterTypes, null, null);
529 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
531 check_name ("name", name);
532 check_not_created ();
533 if (IsInterface && (
534 !((attributes & MethodAttributes.Abstract) != 0) ||
535 !((attributes & MethodAttributes.Virtual) != 0)) &&
536 !(((attributes & MethodAttributes.Static) != 0)))
537 throw new ArgumentException ("Interface method must be abstract and virtual.");
539 if (returnType == null)
540 returnType = pmodule.assemblyb.corlib_void_type;
541 MethodBuilder res = new MethodBuilder (this, name, attributes,
542 callingConvention, returnType,
543 returnTypeRequiredCustomModifiers,
544 returnTypeOptionalCustomModifiers, parameterTypes,
545 parameterTypeRequiredCustomModifiers,
546 parameterTypeOptionalCustomModifiers);
547 append_method (res);
548 return res;
551 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet)
553 return DefinePInvokeMethod (name, dllName, entryName, attributes,
554 callingConvention, returnType, null, null, parameterTypes,
555 null, null, nativeCallConv, nativeCharSet);
558 public MethodBuilder DefinePInvokeMethod (
559 string name,
560 string dllName,
561 string entryName, MethodAttributes attributes,
562 CallingConventions callingConvention,
563 Type returnType,
564 Type[] returnTypeRequiredCustomModifiers,
565 Type[] returnTypeOptionalCustomModifiers,
566 Type[] parameterTypes,
567 Type[][] parameterTypeRequiredCustomModifiers,
568 Type[][] parameterTypeOptionalCustomModifiers,
569 CallingConvention nativeCallConv,
570 CharSet nativeCharSet)
572 check_name ("name", name);
573 check_name ("dllName", dllName);
574 check_name ("entryName", entryName);
575 if ((attributes & MethodAttributes.Abstract) != 0)
576 throw new ArgumentException ("PInvoke methods must be static and native and cannot be abstract.");
577 if (IsInterface)
578 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
579 check_not_created ();
581 MethodBuilder res
582 = new MethodBuilder (
583 this,
584 name,
585 attributes,
586 callingConvention,
587 returnType,
588 returnTypeRequiredCustomModifiers,
589 returnTypeOptionalCustomModifiers,
590 parameterTypes,
591 parameterTypeRequiredCustomModifiers,
592 parameterTypeOptionalCustomModifiers,
593 dllName,
594 entryName,
595 nativeCallConv,
596 nativeCharSet);
597 append_method (res);
598 return res;
601 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
602 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
603 nativeCallConv, nativeCharSet);
606 public MethodBuilder DefineMethod (string name, MethodAttributes attributes)
608 return DefineMethod (name, attributes, CallingConventions.Standard);
611 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention)
613 return DefineMethod (name, attributes, callingConvention, null, null);
616 public void DefineMethodOverride (MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
618 if (methodInfoBody == null)
619 throw new ArgumentNullException ("methodInfoBody");
620 if (methodInfoDeclaration == null)
621 throw new ArgumentNullException ("methodInfoDeclaration");
622 check_not_created ();
623 if (methodInfoBody.DeclaringType != this)
624 throw new ArgumentException ("method body must belong to this type");
626 if (methodInfoBody is MethodBuilder) {
627 MethodBuilder mb = (MethodBuilder)methodInfoBody;
628 mb.set_override (methodInfoDeclaration);
632 public FieldBuilder DefineField (string fieldName, Type type, FieldAttributes attributes)
634 return DefineField (fieldName, type, null, null, attributes);
637 public FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
639 check_name ("fieldName", fieldName);
640 if (type == typeof (void))
641 throw new ArgumentException ("Bad field type in defining field.");
642 check_not_created ();
644 FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomModifiers, optionalCustomModifiers);
645 if (fields != null) {
646 if (fields.Length == num_fields) {
647 FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
648 System.Array.Copy (fields, new_fields, num_fields);
649 fields = new_fields;
651 fields [num_fields] = res;
652 num_fields ++;
653 } else {
654 fields = new FieldBuilder [1];
655 fields [0] = res;
656 num_fields ++;
657 create_internal_class (this);
660 if (IsEnum && !IsCompilerContext) {
661 if (underlying_type == null && (attributes & FieldAttributes.Static) == 0)
662 underlying_type = type;
665 return res;
668 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes)
670 return DefineProperty (name, attributes, returnType, null, null, parameterTypes, null, null);
673 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
675 check_name ("name", name);
676 if (parameterTypes != null)
677 foreach (Type param in parameterTypes)
678 if (param == null)
679 throw new ArgumentNullException ("parameterTypes");
680 check_not_created ();
682 PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
684 if (properties != null) {
685 PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
686 System.Array.Copy (properties, new_properties, properties.Length);
687 new_properties [properties.Length] = res;
688 properties = new_properties;
689 } else {
690 properties = new PropertyBuilder [1];
691 properties [0] = res;
693 return res;
696 [ComVisible (true)]
697 public ConstructorBuilder DefineTypeInitializer()
699 return DefineConstructor (MethodAttributes.Public |
700 MethodAttributes.Static | MethodAttributes.SpecialName |
701 MethodAttributes.RTSpecialName, CallingConventions.Standard,
702 null);
705 [MethodImplAttribute(MethodImplOptions.InternalCall)]
706 private extern Type create_runtime_class (TypeBuilder tb);
708 private bool is_nested_in (Type t)
710 while (t != null) {
711 if (t == this)
712 return true;
713 else
714 t = t.DeclaringType;
716 return false;
719 // Return whenever this type has a ctor defined using DefineMethod ()
720 private bool has_ctor_method () {
721 MethodAttributes ctor_attrs = MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
723 for (int i = 0; i < num_methods; ++i) {
724 MethodBuilder mb = (MethodBuilder)(methods[i]);
726 if (mb.Name == ConstructorInfo.ConstructorName && (mb.Attributes & ctor_attrs) == ctor_attrs)
727 return true;
730 return false;
733 public Type CreateType()
735 /* handle nesting_type */
736 if (createTypeCalled)
737 return created;
739 if (!IsInterface && (parent == null) && (this != pmodule.assemblyb.corlib_object_type) && (FullName != "<Module>")) {
740 SetParent (pmodule.assemblyb.corlib_object_type);
743 create_generic_class ();
745 // Fire TypeResolve events for fields whose type is an unfinished
746 // value type.
747 if (fields != null) {
748 foreach (FieldBuilder fb in fields) {
749 if (fb == null)
750 continue;
751 Type ft = fb.FieldType;
752 if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
753 TypeBuilder tb = (TypeBuilder)ft;
754 if (!tb.is_created) {
755 AppDomain.CurrentDomain.DoTypeResolve (tb);
756 if (!tb.is_created) {
757 // FIXME: We should throw an exception here,
758 // but mcs expects that the type is created
759 // even if the exception is thrown
760 //throw new TypeLoadException ("Could not load type " + tb);
767 if ((parent != null) && parent.IsSealed)
768 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
770 if (parent == pmodule.assemblyb.corlib_enum_type && methods != null)
771 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because it is an enum with methods.");
773 if (methods != null) {
774 bool is_concrete = !IsAbstract;
775 for (int i = 0; i < num_methods; ++i) {
776 MethodBuilder mb = (MethodBuilder)(methods[i]);
777 if (is_concrete && mb.IsAbstract)
778 throw new InvalidOperationException ("Type is concrete but has abstract method " + mb);
779 mb.check_override ();
780 mb.fixup ();
785 // On classes, define a default constructor if not provided
787 if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") &&
788 (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method ())
789 DefineDefaultConstructor (MethodAttributes.Public);
791 if (ctors != null){
792 foreach (ConstructorBuilder ctor in ctors)
793 ctor.fixup ();
796 createTypeCalled = true;
797 created = create_runtime_class (this);
798 if (created != null)
799 return created;
800 return this;
803 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
805 symbolWriter.OpenNamespace (this.Namespace);
807 if (methods != null) {
808 for (int i = 0; i < num_methods; ++i) {
809 MethodBuilder metb = (MethodBuilder) methods[i];
810 metb.GenerateDebugInfo (symbolWriter);
814 if (ctors != null) {
815 foreach (ConstructorBuilder ctor in ctors)
816 ctor.GenerateDebugInfo (symbolWriter);
819 symbolWriter.CloseNamespace ();
821 if (subtypes != null) {
822 for (int i = 0; i < subtypes.Length; ++i)
823 subtypes [i].GenerateDebugInfo (symbolWriter);
827 [ComVisible (true)]
828 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
830 if (is_created)
831 return created.GetConstructors (bindingAttr);
833 if (!IsCompilerContext)
834 throw new NotSupportedException ();
836 return GetConstructorsInternal (bindingAttr);
839 internal ConstructorInfo[] GetConstructorsInternal (BindingFlags bindingAttr)
841 if (ctors == null)
842 return new ConstructorInfo [0];
843 ArrayList l = new ArrayList ();
844 bool match;
845 MethodAttributes mattrs;
847 foreach (ConstructorBuilder c in ctors) {
848 match = false;
849 mattrs = c.Attributes;
850 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
851 if ((bindingAttr & BindingFlags.Public) != 0)
852 match = true;
853 } else {
854 if ((bindingAttr & BindingFlags.NonPublic) != 0)
855 match = true;
857 if (!match)
858 continue;
859 match = false;
860 if ((mattrs & MethodAttributes.Static) != 0) {
861 if ((bindingAttr & BindingFlags.Static) != 0)
862 match = true;
863 } else {
864 if ((bindingAttr & BindingFlags.Instance) != 0)
865 match = true;
867 if (!match)
868 continue;
869 l.Add (c);
871 ConstructorInfo[] result = new ConstructorInfo [l.Count];
872 l.CopyTo (result);
873 return result;
876 public override Type GetElementType ()
878 throw new NotSupportedException ();
881 public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
883 check_created ();
884 return created.GetEvent (name, bindingAttr);
887 /* Needed to keep signature compatibility with MS.NET */
888 public override EventInfo[] GetEvents ()
890 return GetEvents (DefaultBindingFlags);
893 public override EventInfo[] GetEvents (BindingFlags bindingAttr)
895 if (is_created)
896 return created.GetEvents (bindingAttr);
897 if (!IsCompilerContext)
898 throw new NotSupportedException ();
899 return new EventInfo [0]; /*FIXME shouldn't we return the events here?*/
902 // This is only used from MonoGenericInst.initialize().
903 internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
905 if (events == null)
906 return new EventInfo [0];
907 ArrayList l = new ArrayList ();
908 bool match;
909 MethodAttributes mattrs;
910 MethodInfo accessor;
912 foreach (EventBuilder eb in events) {
913 if (eb == null)
914 continue;
915 EventInfo c = get_event_info (eb);
916 match = false;
917 accessor = c.GetAddMethod (true);
918 if (accessor == null)
919 accessor = c.GetRemoveMethod (true);
920 if (accessor == null)
921 continue;
922 mattrs = accessor.Attributes;
923 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
924 if ((bindingAttr & BindingFlags.Public) != 0)
925 match = true;
926 } else {
927 if ((bindingAttr & BindingFlags.NonPublic) != 0)
928 match = true;
930 if (!match)
931 continue;
932 match = false;
933 if ((mattrs & MethodAttributes.Static) != 0) {
934 if ((bindingAttr & BindingFlags.Static) != 0)
935 match = true;
936 } else {
937 if ((bindingAttr & BindingFlags.Instance) != 0)
938 match = true;
940 if (!match)
941 continue;
942 l.Add (c);
944 EventInfo[] result = new EventInfo [l.Count];
945 l.CopyTo (result);
946 return result;
949 public override FieldInfo GetField (string name, BindingFlags bindingAttr)
951 if (created != null)
952 return created.GetField (name, bindingAttr);
954 if (fields == null)
955 return null;
957 bool match;
958 FieldAttributes mattrs;
960 foreach (FieldInfo c in fields) {
961 if (c == null)
962 continue;
963 if (c.Name != name)
964 continue;
965 match = false;
966 mattrs = c.Attributes;
967 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
968 if ((bindingAttr & BindingFlags.Public) != 0)
969 match = true;
970 } else {
971 if ((bindingAttr & BindingFlags.NonPublic) != 0)
972 match = true;
974 if (!match)
975 continue;
976 match = false;
977 if ((mattrs & FieldAttributes.Static) != 0) {
978 if ((bindingAttr & BindingFlags.Static) != 0)
979 match = true;
980 } else {
981 if ((bindingAttr & BindingFlags.Instance) != 0)
982 match = true;
984 if (!match)
985 continue;
986 return c;
988 return null;
991 public override FieldInfo[] GetFields (BindingFlags bindingAttr)
993 if (created != null)
994 return created.GetFields (bindingAttr);
996 if (fields == null)
997 return new FieldInfo [0];
998 ArrayList l = new ArrayList ();
999 bool match;
1000 FieldAttributes mattrs;
1002 foreach (FieldInfo c in fields) {
1003 if (c == null)
1004 continue;
1005 match = false;
1006 mattrs = c.Attributes;
1007 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
1008 if ((bindingAttr & BindingFlags.Public) != 0)
1009 match = true;
1010 } else {
1011 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1012 match = true;
1014 if (!match)
1015 continue;
1016 match = false;
1017 if ((mattrs & FieldAttributes.Static) != 0) {
1018 if ((bindingAttr & BindingFlags.Static) != 0)
1019 match = true;
1020 } else {
1021 if ((bindingAttr & BindingFlags.Instance) != 0)
1022 match = true;
1024 if (!match)
1025 continue;
1026 l.Add (c);
1028 FieldInfo[] result = new FieldInfo [l.Count];
1029 l.CopyTo (result);
1030 return result;
1033 public override Type GetInterface (string name, bool ignoreCase)
1035 check_created ();
1036 return created.GetInterface (name, ignoreCase);
1039 public override Type[] GetInterfaces ()
1041 if (is_created)
1042 return created.GetInterfaces ();
1044 if (interfaces != null) {
1045 Type[] ret = new Type [interfaces.Length];
1046 interfaces.CopyTo (ret, 0);
1047 return ret;
1048 } else {
1049 return Type.EmptyTypes;
1053 public override MemberInfo[] GetMember (string name, MemberTypes type,
1054 BindingFlags bindingAttr)
1056 check_created ();
1057 return created.GetMember (name, type, bindingAttr);
1060 public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
1062 check_created ();
1063 return created.GetMembers (bindingAttr);
1066 private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type)
1068 MethodInfo[] candidates;
1069 bool match;
1070 MethodAttributes mattrs;
1072 if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
1073 MethodInfo [] parent_methods = parent.GetMethods (bindingAttr);
1074 ArrayList parent_candidates = new ArrayList (parent_methods.Length);
1076 bool flatten = (bindingAttr & BindingFlags.FlattenHierarchy) != 0;
1078 for (int i = 0; i < parent_methods.Length; i++) {
1079 MethodInfo m = parent_methods [i];
1081 mattrs = m.Attributes;
1083 if (m.IsStatic && !flatten)
1084 continue;
1086 switch (mattrs & MethodAttributes.MemberAccessMask) {
1087 case MethodAttributes.Public:
1088 match = (bindingAttr & BindingFlags.Public) != 0;
1089 break;
1090 case MethodAttributes.Assembly:
1091 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1092 break;
1093 case MethodAttributes.Private:
1094 match = false;
1095 break;
1096 default:
1097 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1098 break;
1101 if (match)
1102 parent_candidates.Add (m);
1105 if (methods == null) {
1106 candidates = new MethodInfo [parent_candidates.Count];
1107 parent_candidates.CopyTo (candidates);
1108 } else {
1109 candidates = new MethodInfo [methods.Length + parent_candidates.Count];
1110 parent_candidates.CopyTo (candidates, 0);
1111 methods.CopyTo (candidates, parent_candidates.Count);
1114 else
1115 candidates = methods;
1117 if (candidates == null)
1118 return new MethodInfo [0];
1120 ArrayList l = new ArrayList ();
1122 foreach (MethodInfo c in candidates) {
1123 if (c == null)
1124 continue;
1125 if (name != null) {
1126 if (String.Compare (c.Name, name, ignoreCase) != 0)
1127 continue;
1129 match = false;
1130 mattrs = c.Attributes;
1131 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1132 if ((bindingAttr & BindingFlags.Public) != 0)
1133 match = true;
1134 } else {
1135 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1136 match = true;
1138 if (!match)
1139 continue;
1140 match = false;
1141 if ((mattrs & MethodAttributes.Static) != 0) {
1142 if ((bindingAttr & BindingFlags.Static) != 0)
1143 match = true;
1144 } else {
1145 if ((bindingAttr & BindingFlags.Instance) != 0)
1146 match = true;
1148 if (!match)
1149 continue;
1150 l.Add (c);
1153 MethodInfo[] result = new MethodInfo [l.Count];
1154 l.CopyTo (result);
1155 return result;
1158 public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
1160 return GetMethodsByName (null, bindingAttr, false, this);
1163 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
1164 Binder binder,
1165 CallingConventions callConvention,
1166 Type[] types, ParameterModifier[] modifiers)
1168 check_created ();
1170 bool ignoreCase = ((bindingAttr & BindingFlags.IgnoreCase) != 0);
1171 MethodInfo[] methods = GetMethodsByName (name, bindingAttr, ignoreCase, this);
1172 MethodInfo found = null;
1173 MethodBase[] match;
1174 int typesLen = (types != null) ? types.Length : 0;
1175 int count = 0;
1177 foreach (MethodInfo m in methods) {
1178 // Under MS.NET, Standard|HasThis matches Standard...
1179 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1180 continue;
1181 found = m;
1182 count++;
1185 if (count == 0)
1186 return null;
1188 if (count == 1 && typesLen == 0)
1189 return found;
1191 match = new MethodBase [count];
1192 if (count == 1)
1193 match [0] = found;
1194 else {
1195 count = 0;
1196 foreach (MethodInfo m in methods) {
1197 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1198 continue;
1199 match [count++] = m;
1203 if (types == null)
1204 return (MethodInfo) Binder.FindMostDerivedMatch (match);
1206 if (binder == null)
1207 binder = Binder.DefaultBinder;
1209 return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
1212 public override Type GetNestedType (string name, BindingFlags bindingAttr)
1214 check_created ();
1216 if (subtypes == null)
1217 return null;
1219 foreach (TypeBuilder t in subtypes) {
1220 if (!t.is_created)
1221 continue;
1222 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1223 if ((bindingAttr & BindingFlags.Public) == 0)
1224 continue;
1225 } else {
1226 if ((bindingAttr & BindingFlags.NonPublic) == 0)
1227 continue;
1229 if (t.Name == name)
1230 return t.created;
1233 return null;
1236 public override Type[] GetNestedTypes (BindingFlags bindingAttr)
1238 if (!is_created && !IsCompilerContext)
1239 throw new NotSupportedException ();
1241 bool match;
1242 ArrayList result = new ArrayList ();
1244 if (subtypes == null)
1245 return Type.EmptyTypes;
1246 foreach (TypeBuilder t in subtypes) {
1247 match = false;
1248 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1249 if ((bindingAttr & BindingFlags.Public) != 0)
1250 match = true;
1251 } else {
1252 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1253 match = true;
1255 if (!match)
1256 continue;
1257 result.Add (t);
1259 Type[] r = new Type [result.Count];
1260 result.CopyTo (r);
1261 return r;
1264 public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
1266 if (is_created)
1267 return created.GetProperties (bindingAttr);
1269 if (properties == null)
1270 return new PropertyInfo [0];
1271 ArrayList l = new ArrayList ();
1272 bool match;
1273 MethodAttributes mattrs;
1274 MethodInfo accessor;
1276 foreach (PropertyInfo c in properties) {
1277 match = false;
1278 accessor = c.GetGetMethod (true);
1279 if (accessor == null)
1280 accessor = c.GetSetMethod (true);
1281 if (accessor == null)
1282 continue;
1283 mattrs = accessor.Attributes;
1284 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1285 if ((bindingAttr & BindingFlags.Public) != 0)
1286 match = true;
1287 } else {
1288 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1289 match = true;
1291 if (!match)
1292 continue;
1293 match = false;
1294 if ((mattrs & MethodAttributes.Static) != 0) {
1295 if ((bindingAttr & BindingFlags.Static) != 0)
1296 match = true;
1297 } else {
1298 if ((bindingAttr & BindingFlags.Instance) != 0)
1299 match = true;
1301 if (!match)
1302 continue;
1303 l.Add (c);
1305 PropertyInfo[] result = new PropertyInfo [l.Count];
1306 l.CopyTo (result);
1307 return result;
1310 protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
1312 throw not_supported ();
1315 protected override bool HasElementTypeImpl ()
1317 // a TypeBuilder can never represent an array, pointer
1318 if (!is_created)
1319 return false;
1321 return created.HasElementType;
1324 public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
1326 check_created ();
1327 return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
1330 protected override bool IsArrayImpl ()
1332 return false; /*A TypeBuilder never represents a non typedef type.*/
1335 protected override bool IsByRefImpl ()
1337 return false; /*A TypeBuilder never represents a non typedef type.*/
1340 protected override bool IsCOMObjectImpl ()
1342 return ((GetAttributeFlagsImpl () & TypeAttributes.Import) != 0);
1345 protected override bool IsPointerImpl ()
1347 return false; /*A TypeBuilder never represents a non typedef type.*/
1350 protected override bool IsPrimitiveImpl ()
1352 // FIXME
1353 return false;
1356 // FIXME: I doubt just removing this still works.
1357 protected override bool IsValueTypeImpl ()
1359 return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
1360 this != pmodule.assemblyb.corlib_value_type &&
1361 this != pmodule.assemblyb.corlib_enum_type);
1364 public override Type MakeArrayType ()
1366 return new ArrayType (this, 0);
1369 public override Type MakeArrayType (int rank)
1371 if (rank < 1)
1372 throw new IndexOutOfRangeException ();
1373 return new ArrayType (this, rank);
1376 public override Type MakeByRefType ()
1378 return new ByRefType (this);
1381 [MonoTODO]
1382 public override Type MakeGenericType (params Type [] typeArguments)
1384 return base.MakeGenericType (typeArguments);
1387 public override Type MakePointerType ()
1389 return new PointerType (this);
1392 public override RuntimeTypeHandle TypeHandle {
1393 get {
1394 check_created ();
1395 return created.TypeHandle;
1400 // Used internally by mcs only
1402 internal void SetCharSet (TypeAttributes ta)
1404 this.attrs = ta;
1407 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
1409 if (customBuilder == null)
1410 throw new ArgumentNullException ("customBuilder");
1412 string attrname = customBuilder.Ctor.ReflectedType.FullName;
1413 if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
1414 byte[] data = customBuilder.Data;
1415 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
1416 layout_kind = (int)data [2];
1417 layout_kind |= ((int)data [3]) << 8;
1418 attrs &= ~TypeAttributes.LayoutMask;
1419 switch ((LayoutKind)layout_kind) {
1420 case LayoutKind.Auto:
1421 attrs |= TypeAttributes.AutoLayout;
1422 break;
1423 case LayoutKind.Explicit:
1424 attrs |= TypeAttributes.ExplicitLayout;
1425 break;
1426 case LayoutKind.Sequential:
1427 attrs |= TypeAttributes.SequentialLayout;
1428 break;
1429 default:
1430 // we should ignore it since it can be any value anyway...
1431 throw new Exception ("Error in customattr");
1433 string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
1434 int pos = 6;
1435 if (first_type_name == "System.Int16")
1436 pos = 4;
1437 int nnamed = (int)data [pos++];
1438 nnamed |= ((int)data [pos++]) << 8;
1439 for (int i = 0; i < nnamed; ++i) {
1440 //byte named_type = data [pos++];
1441 pos ++;
1442 byte type = data [pos++];
1443 int len;
1444 string named_name;
1446 if (type == 0x55) {
1447 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1448 //string named_typename =
1449 CustomAttributeBuilder.string_from_bytes (data, pos, len);
1450 pos += len;
1451 // FIXME: Check that 'named_type' and 'named_typename' match, etc.
1452 // See related code/FIXME in mono/mono/metadata/reflection.c
1455 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1456 named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1457 pos += len;
1458 /* all the fields are integers in StructLayout */
1459 int value = (int)data [pos++];
1460 value |= ((int)data [pos++]) << 8;
1461 value |= ((int)data [pos++]) << 16;
1462 value |= ((int)data [pos++]) << 24;
1463 switch (named_name) {
1464 case "CharSet":
1465 switch ((CharSet)value) {
1466 case CharSet.None:
1467 case CharSet.Ansi:
1468 attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass);
1469 break;
1470 case CharSet.Unicode:
1471 attrs &= ~TypeAttributes.AutoClass;
1472 attrs |= TypeAttributes.UnicodeClass;
1473 break;
1474 case CharSet.Auto:
1475 attrs &= ~TypeAttributes.UnicodeClass;
1476 attrs |= TypeAttributes.AutoClass;
1477 break;
1478 default:
1479 break; // error out...
1481 break;
1482 case "Pack":
1483 packing_size = (PackingSize)value;
1484 break;
1485 case "Size":
1486 class_size = value;
1487 break;
1488 default:
1489 break; // error out...
1492 return;
1493 } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
1494 attrs |= TypeAttributes.SpecialName;
1495 return;
1496 } else if (attrname == "System.SerializableAttribute") {
1497 attrs |= TypeAttributes.Serializable;
1498 return;
1499 } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
1500 attrs |= TypeAttributes.Import;
1501 return;
1502 } else if (attrname == "System.Security.SuppressUnmanagedCodeSecurityAttribute") {
1503 attrs |= TypeAttributes.HasSecurity;
1506 if (cattrs != null) {
1507 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1508 cattrs.CopyTo (new_array, 0);
1509 new_array [cattrs.Length] = customBuilder;
1510 cattrs = new_array;
1511 } else {
1512 cattrs = new CustomAttributeBuilder [1];
1513 cattrs [0] = customBuilder;
1517 [ComVisible (true)]
1518 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
1520 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1523 public EventBuilder DefineEvent (string name, EventAttributes attributes, Type eventtype)
1525 check_name ("name", name);
1526 if (eventtype == null)
1527 throw new ArgumentNullException ("type");
1528 check_not_created ();
1530 EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1531 if (events != null) {
1532 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1533 System.Array.Copy (events, new_events, events.Length);
1534 new_events [events.Length] = res;
1535 events = new_events;
1536 } else {
1537 events = new EventBuilder [1];
1538 events [0] = res;
1540 return res;
1543 public FieldBuilder DefineInitializedData (string name, byte[] data, FieldAttributes attributes) {
1544 if (data == null)
1545 throw new ArgumentNullException ("data");
1547 FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
1548 res.SetRVAData (data);
1549 return res;
1552 public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
1554 if (name == null)
1555 throw new ArgumentNullException ("name");
1556 if (name.Length == 0)
1557 throw new ArgumentException ("Empty name is not legal", "name");
1558 if ((size <= 0) || (size > 0x3f0000))
1559 throw new ArgumentException ("Data size must be > 0 and < 0x3f0000");
1560 check_not_created ();
1562 string typeName = "$ArrayType$" + size;
1563 Type datablobtype = pmodule.GetRegisteredType (fullname + "+" + typeName);
1564 if (datablobtype == null) {
1565 TypeBuilder tb = DefineNestedType (typeName,
1566 TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1567 pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
1568 tb.CreateType ();
1569 datablobtype = tb;
1571 return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1574 public TypeToken TypeToken {
1575 get {
1576 return new TypeToken (0x02000000 | table_idx);
1580 public void SetParent (Type parent)
1582 check_not_created ();
1584 if (parent == null) {
1585 if ((attrs & TypeAttributes.Interface) != 0) {
1586 if ((attrs & TypeAttributes.Abstract) == 0)
1587 throw new InvalidOperationException ("Interface must be declared abstract.");
1588 this.parent = null;
1589 } else {
1590 this.parent = typeof (object);
1592 } else {
1593 this.parent = parent;
1596 // will just set the parent-related bits if called a second time
1597 setup_internal_class (this);
1600 internal int get_next_table_index (object obj, int table, bool inc) {
1601 return pmodule.get_next_table_index (obj, table, inc);
1604 [ComVisible (true)]
1605 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1607 if (created == null)
1608 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1610 return created.GetInterfaceMap (interfaceType);
1613 internal bool IsCompilerContext {
1614 get {
1615 return pmodule.assemblyb.IsCompilerContext;
1619 internal bool is_created {
1620 get {
1621 return created != null;
1625 private Exception not_supported ()
1627 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1630 private void check_not_created ()
1632 if (is_created)
1633 throw new InvalidOperationException ("Unable to change after type has been created.");
1636 private void check_created ()
1638 if (!is_created)
1639 throw not_supported ();
1642 private void check_name (string argName, string name)
1644 if (name == null)
1645 throw new ArgumentNullException (argName);
1646 if (name.Length == 0)
1647 throw new ArgumentException ("Empty name is not legal", argName);
1648 if (name [0] == ((char)0))
1649 throw new ArgumentException ("Illegal name", argName);
1652 public override String ToString ()
1654 return FullName;
1657 [MonoTODO]
1658 public override bool IsAssignableFrom (Type c)
1660 return base.IsAssignableFrom (c);
1663 [ComVisible (true)]
1664 [MonoTODO]
1665 public override bool IsSubclassOf (Type c)
1667 return base.IsSubclassOf (c);
1670 [MonoTODO ("arrays")]
1671 internal bool IsAssignableTo (Type c)
1673 if (c == this)
1674 return true;
1676 if (c.IsInterface) {
1677 if (parent != null && is_created) {
1678 if (c.IsAssignableFrom (parent))
1679 return true;
1682 if (interfaces == null)
1683 return false;
1684 foreach (Type t in interfaces)
1685 if (c.IsAssignableFrom (t))
1686 return true;
1687 if (!is_created)
1688 return false;
1691 if (parent == null)
1692 return c == typeof (object);
1693 else
1694 return c.IsAssignableFrom (parent);
1697 public bool IsCreated ()
1699 return is_created;
1702 public override Type[] GetGenericArguments ()
1704 if (generic_params == null)
1705 return null;
1706 Type[] args = new Type [generic_params.Length];
1707 generic_params.CopyTo (args, 0);
1708 return args;
1711 public override Type GetGenericTypeDefinition ()
1713 if (generic_params == null)
1714 throw new InvalidOperationException ("Type is not generic");
1715 return this;
1718 public override bool ContainsGenericParameters {
1719 get {
1720 return generic_params != null;
1724 public extern override bool IsGenericParameter {
1725 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1726 get;
1729 public override GenericParameterAttributes GenericParameterAttributes {
1730 get { return GenericParameterAttributes.None; }
1733 public override bool IsGenericTypeDefinition {
1734 get {
1735 return generic_params != null;
1739 public override bool IsGenericType {
1740 get { return IsGenericTypeDefinition; }
1743 [MonoTODO]
1744 public override int GenericParameterPosition {
1745 get {
1746 return 0;
1750 public override MethodBase DeclaringMethod {
1751 get {
1752 return null;
1756 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
1758 if (names == null)
1759 throw new ArgumentNullException ("names");
1760 if (names.Length == 0)
1761 throw new ArgumentException ("names");
1763 setup_generic_class ();
1765 generic_params = new GenericTypeParameterBuilder [names.Length];
1766 for (int i = 0; i < names.Length; i++) {
1767 string item = names [i];
1768 if (item == null)
1769 throw new ArgumentNullException ("names");
1770 generic_params [i] = new GenericTypeParameterBuilder (this, null, item, i);
1773 return generic_params;
1776 public static ConstructorInfo GetConstructor (Type type, ConstructorInfo constructor)
1778 if (type == null)
1779 throw new ArgumentException ("Type is not generic", "type");
1781 ConstructorInfo res = type.GetConstructor (constructor);
1782 if (res == null)
1783 throw new ArgumentException ("constructor not found");
1785 return res;
1788 static bool IsValidGetMethodType (Type type)
1790 if (type is TypeBuilder || type is MonoGenericClass)
1791 return true;
1792 /*GetMethod() must work with TypeBuilders after CreateType() was called.*/
1793 if (type.Module is ModuleBuilder)
1794 return true;
1795 if (type.IsGenericParameter)
1796 return false;
1798 Type[] inst = type.GetGenericArguments ();
1799 if (inst == null)
1800 return false;
1801 for (int i = 0; i < inst.Length; ++i) {
1802 if (IsValidGetMethodType (inst [i]))
1803 return true;
1805 return false;
1808 public static MethodInfo GetMethod (Type type, MethodInfo method)
1810 if (!IsValidGetMethodType (type))
1811 throw new ArgumentException ("type is not TypeBuilder but " + type.GetType (), "type");
1813 if (!type.IsGenericType)
1814 throw new ArgumentException ("type is not a generic type", "type");
1816 if (!method.DeclaringType.IsGenericTypeDefinition)
1817 throw new ArgumentException ("method declaring type is not a generic type definition", "method");
1818 if (method.DeclaringType != type.GetGenericTypeDefinition ())
1819 throw new ArgumentException ("method declaring type is not the generic type definition of type", "method");
1821 MethodInfo res = type.GetMethod (method);
1822 if (res == null)
1823 throw new ArgumentException (String.Format ("method {0} not found in type {1}", method.Name, type));
1825 return res;
1828 public static FieldInfo GetField (Type type, FieldInfo field)
1830 FieldInfo res = type.GetField (field);
1831 if (res == null)
1832 throw new System.Exception ("field not found");
1833 else
1834 return res;
1837 void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1839 throw new NotImplementedException ();
1842 void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1844 throw new NotImplementedException ();
1847 void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
1849 throw new NotImplementedException ();
1852 void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1854 throw new NotImplementedException ();