2 // System.Reflection.Emit.TypeBuilder.cs
5 // Paolo Molaro (lupus@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // (C) 2001 Ximian, Inc. http://www.ximian.com
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:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
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.
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
50 [ComDefaultInterface (typeof (_TypeBuilder))]
52 [ClassInterface (ClassInterfaceType.None)]
53 public sealed class TypeBuilder : Type, _TypeBuilder
55 #pragma warning disable 169
56 #region Sync with reflection.h
58 private string nspace;
60 private Type nesting_type;
61 private Type[] interfaces;
62 private int num_methods;
63 private MethodBuilder[] methods;
64 private ConstructorBuilder[] ctors;
65 private PropertyBuilder[] properties;
66 private int num_fields;
67 private FieldBuilder[] fields;
68 private EventBuilder[] events;
69 private CustomAttributeBuilder[] cattrs;
70 internal TypeBuilder[] subtypes;
71 internal TypeAttributes attrs;
72 private int table_idx;
73 private ModuleBuilder pmodule;
74 private int class_size;
75 private PackingSize packing_size;
76 private IntPtr generic_container;
77 #if NET_2_0 || BOOTSTRAP_NET_2_0
78 private GenericTypeParameterBuilder[] generic_params;
80 private Object generic_params; /* so offsets don't change */
82 private RefEmitPermissionSet[] permissions;
85 #pragma warning restore 169
88 bool createTypeCalled;
89 private Type underlying_type;
91 public const int UnspecifiedTypeSize = 0;
93 protected override TypeAttributes GetAttributeFlagsImpl ()
98 [MethodImplAttribute(MethodImplOptions.InternalCall)]
99 private extern void setup_internal_class (TypeBuilder tb);
101 [MethodImplAttribute(MethodImplOptions.InternalCall)]
102 private extern void create_internal_class (TypeBuilder tb);
104 #if NET_2_0 || BOOTSTRAP_NET_2_0
105 [MethodImplAttribute(MethodImplOptions.InternalCall)]
106 private extern void setup_generic_class ();
109 [MethodImplAttribute(MethodImplOptions.InternalCall)]
110 private extern void create_generic_class ();
112 [MethodImplAttribute(MethodImplOptions.InternalCall)]
113 private extern EventInfo get_event_info (EventBuilder eb);
115 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr, int table_idx)
119 this.class_size = UnspecifiedTypeSize;
120 this.table_idx = table_idx;
121 fullname = this.tname = table_idx == 1 ? "<Module>" : "type_"+table_idx;
122 this.nspace = String.Empty;
124 setup_internal_class (this);
127 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type)
130 this.parent = parent;
132 this.class_size = type_size;
133 this.packing_size = packing_size;
134 this.nesting_type = nesting_type;
136 check_name ("fullname", name);
138 if (parent == null && (attr & TypeAttributes.Interface) != 0 && (attr & TypeAttributes.Abstract) == 0)
139 throw new InvalidOperationException ("Interface must be declared abstract.");
141 sep_index = name.LastIndexOf('.');
142 if (sep_index != -1) {
143 this.tname = name.Substring (sep_index + 1);
144 this.nspace = name.Substring (0, sep_index);
147 this.nspace = String.Empty;
149 if (interfaces != null) {
150 this.interfaces = new Type[interfaces.Length];
151 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
155 if (((attr & TypeAttributes.Interface) == 0) && (parent == null) && !IsCompilerContext)
156 this.parent = typeof (object);
159 table_idx = mb.get_next_table_index (this, 0x02, true);
160 setup_internal_class (this);
161 fullname = GetFullName ();
164 public override Assembly Assembly {
165 get {return pmodule.Assembly;}
168 public override string AssemblyQualifiedName {
170 return fullname + ", " + Assembly.FullName;
174 public override Type BaseType {
180 public override Type DeclaringType {
181 get { return nesting_type; }
184 /* public override bool IsSubclassOf (Type c)
200 public override Type UnderlyingSystemType {
203 return created.UnderlyingSystemType;
205 if (IsEnum && !IsCompilerContext) {
206 if (underlying_type != null)
207 return underlying_type;
208 throw new InvalidOperationException (
209 "Enumeration type is not defined.");
216 string GetFullName ()
218 if (nesting_type != null)
219 return String.Concat (nesting_type.FullName, "+", tname);
220 if ((nspace != null) && (nspace.Length > 0))
221 return String.Concat (nspace, ".", tname);
225 public override string FullName {
231 public override Guid GUID {
238 public override Module Module {
239 get {return pmodule;}
242 public override string Name {
246 public override string Namespace {
250 public PackingSize PackingSize {
251 get {return packing_size;}
255 get { return class_size; }
258 public override Type ReflectedType {
259 get { return nesting_type; }
262 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
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");
271 check_not_created ();
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.");
279 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
280 permissions.CopyTo (new_array, 0);
281 permissions = new_array;
284 permissions = new RefEmitPermissionSet [1];
286 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
287 attrs |= TypeAttributes.HasSecurity;
293 public void AddInterfaceImplementation (Type interfaceType)
295 if (interfaceType == null)
296 throw new ArgumentNullException ("interfaceType");
297 check_not_created ();
299 if (interfaces != null) {
300 // Check for duplicates
301 foreach (Type t in interfaces)
302 if (t == interfaceType)
305 Type[] ifnew = new Type [interfaces.Length + 1];
306 interfaces.CopyTo (ifnew, 0);
307 ifnew [interfaces.Length] = interfaceType;
310 interfaces = new Type [1];
311 interfaces [0] = interfaceType;
315 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
316 CallingConventions callConvention, Type[] types,
317 ParameterModifier[] modifiers)
321 if (created == typeof (object)) {
323 * This happens when building corlib. Calling created.GetConstructor
324 * would return constructors from the real mscorlib, instead of the
331 ConstructorBuilder found = null;
334 foreach (ConstructorBuilder cb in ctors) {
335 if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
345 throw new AmbiguousMatchException ();
348 MethodBase[] match = new MethodBase [count];
353 foreach (ConstructorInfo m in ctors) {
354 if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
360 binder = Binder.DefaultBinder;
361 return (ConstructorInfo) binder.SelectMethod (bindingAttr, match,
365 return created.GetConstructor (bindingAttr, binder,
366 callConvention, types, modifiers);
369 public override bool IsDefined (Type attributeType, bool inherit)
372 * MS throws NotSupported here, but we can't because some corlib
373 * classes make calls to IsDefined.
375 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
378 public override object[] GetCustomAttributes(bool inherit)
382 return created.GetCustomAttributes (inherit);
385 public override object[] GetCustomAttributes(Type attributeType, bool inherit)
389 return created.GetCustomAttributes (attributeType, inherit);
392 public TypeBuilder DefineNestedType (string name)
394 return DefineNestedType (name, TypeAttributes.NestedPrivate,
395 pmodule.assemblyb.corlib_object_type, null);
398 public TypeBuilder DefineNestedType (string name, TypeAttributes attr)
400 return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
403 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent)
405 return DefineNestedType (name, attr, parent, null);
408 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
409 PackingSize packSize, int typeSize)
411 // Visibility must be NestedXXX
413 if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
414 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
415 throw new ArgumentException ("attr", "Bad type flags for nested type.");
417 if (interfaces != null)
418 foreach (Type iface in interfaces)
420 throw new ArgumentNullException ("interfaces");
422 TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packSize, typeSize, this);
423 res.fullname = res.GetFullName ();
424 pmodule.RegisterTypeName (res, res.fullname);
425 if (subtypes != null) {
426 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
427 System.Array.Copy (subtypes, new_types, subtypes.Length);
428 new_types [subtypes.Length] = res;
429 subtypes = new_types;
431 subtypes = new TypeBuilder [1];
440 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces)
442 return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
445 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typeSize)
447 return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typeSize);
450 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packSize)
452 return DefineNestedType (name, attr, parent, null, packSize, UnspecifiedTypeSize);
458 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
460 return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
466 #if NET_2_0 || BOOTSTRAP_NET_2_0
471 ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
473 check_not_created ();
474 ConstructorBuilder cb = new ConstructorBuilder (this, attributes,
475 callingConvention, parameterTypes, requiredCustomModifiers,
476 optionalCustomModifiers);
478 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
479 System.Array.Copy (ctors, new_ctors, ctors.Length);
480 new_ctors [ctors.Length] = cb;
483 ctors = new ConstructorBuilder [1];
492 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
497 parent_type = parent;
499 parent_type = pmodule.assemblyb.corlib_object_type;
501 ConstructorInfo parent_constructor =
502 parent_type.GetConstructor (
503 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
504 null, Type.EmptyTypes, null);
505 if (parent_constructor == null) {
506 throw new NotSupportedException ("Parent does"
507 + " not have a default constructor."
508 + " The default constructor must be"
509 + " explicitly defined.");
512 ConstructorBuilder cb = DefineConstructor (attributes,
513 CallingConventions.Standard, Type.EmptyTypes);
514 ILGenerator ig = cb.GetILGenerator ();
515 ig.Emit (OpCodes.Ldarg_0);
516 ig.Emit (OpCodes.Call, parent_constructor);
517 ig.Emit (OpCodes.Ret);
521 private void append_method (MethodBuilder mb)
523 if (methods != null) {
524 if (methods.Length == num_methods) {
525 MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
526 System.Array.Copy (methods, new_methods, num_methods);
527 methods = new_methods;
530 methods = new MethodBuilder [1];
532 methods [num_methods] = mb;
536 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
538 return DefineMethod (name, attributes, CallingConventions.Standard,
539 returnType, parameterTypes);
542 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
544 return DefineMethod (name, attributes, callingConvention, returnType,
545 null, null, parameterTypes, null, null);
548 #if NET_2_0 || BOOTSTRAP_NET_2_0
553 MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
555 check_name ("name", name);
556 check_not_created ();
558 !((attributes & MethodAttributes.Abstract) != 0) ||
559 !((attributes & MethodAttributes.Virtual) != 0)) &&
560 !(((attributes & MethodAttributes.Static) != 0)))
561 throw new ArgumentException ("Interface method must be abstract and virtual.");
563 if (returnType == null)
564 returnType = pmodule.assemblyb.corlib_void_type;
565 MethodBuilder res = new MethodBuilder (this, name, attributes,
566 callingConvention, returnType,
567 returnTypeRequiredCustomModifiers,
568 returnTypeOptionalCustomModifiers, parameterTypes,
569 parameterTypeRequiredCustomModifiers,
570 parameterTypeOptionalCustomModifiers);
575 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet)
577 return DefinePInvokeMethod (name, dllName, entryName, attributes,
578 callingConvention, returnType, null, null, parameterTypes,
579 null, null, nativeCallConv, nativeCharSet);
582 #if NET_2_0 || BOOTSTRAP_NET_2_0
587 MethodBuilder DefinePInvokeMethod (
590 string entryName, MethodAttributes attributes,
591 CallingConventions callingConvention,
593 Type[] returnTypeRequiredCustomModifiers,
594 Type[] returnTypeOptionalCustomModifiers,
595 Type[] parameterTypes,
596 Type[][] parameterTypeRequiredCustomModifiers,
597 Type[][] parameterTypeOptionalCustomModifiers,
598 CallingConvention nativeCallConv,
599 CharSet nativeCharSet)
601 check_name ("name", name);
602 check_name ("dllName", dllName);
603 check_name ("entryName", entryName);
604 if ((attributes & MethodAttributes.Abstract) != 0)
605 throw new ArgumentException ("PInvoke methods must be static and native and cannot be abstract.");
607 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
608 check_not_created ();
611 = new MethodBuilder (
617 returnTypeRequiredCustomModifiers,
618 returnTypeOptionalCustomModifiers,
620 parameterTypeRequiredCustomModifiers,
621 parameterTypeOptionalCustomModifiers,
630 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
631 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
632 nativeCallConv, nativeCharSet);
635 #if NET_2_0 || BOOTSTRAP_NET_2_0
636 public MethodBuilder DefineMethod (string name, MethodAttributes attributes)
638 return DefineMethod (name, attributes, CallingConventions.Standard);
641 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention)
643 return DefineMethod (name, attributes, callingConvention, null, null);
647 public void DefineMethodOverride (MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
649 if (methodInfoBody == null)
650 throw new ArgumentNullException ("methodInfoBody");
651 if (methodInfoDeclaration == null)
652 throw new ArgumentNullException ("methodInfoDeclaration");
653 check_not_created ();
655 if (methodInfoBody is MethodBuilder) {
656 MethodBuilder mb = (MethodBuilder)methodInfoBody;
657 mb.set_override (methodInfoDeclaration);
661 public FieldBuilder DefineField (string fieldName, Type type, FieldAttributes attributes)
663 return DefineField (fieldName, type, null, null, attributes);
666 #if NET_2_0 || BOOTSTRAP_NET_2_0
671 FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
673 check_name ("fieldName", fieldName);
674 if (type == typeof (void))
675 throw new ArgumentException ("Bad field type in defining field.");
676 check_not_created ();
678 FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomModifiers, optionalCustomModifiers);
679 if (fields != null) {
680 if (fields.Length == num_fields) {
681 FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
682 System.Array.Copy (fields, new_fields, num_fields);
685 fields [num_fields] = res;
688 fields = new FieldBuilder [1];
691 create_internal_class (this);
694 if (IsEnum && !IsCompilerContext) {
695 if (underlying_type == null && (attributes & FieldAttributes.Static) == 0)
696 underlying_type = type;
702 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes)
704 return DefineProperty (name, attributes, returnType, null, null, parameterTypes, null, null);
712 PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
714 check_name ("name", name);
715 if (parameterTypes != null)
716 foreach (Type param in parameterTypes)
718 throw new ArgumentNullException ("parameterTypes");
719 check_not_created ();
721 PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
723 if (properties != null) {
724 PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
725 System.Array.Copy (properties, new_properties, properties.Length);
726 new_properties [properties.Length] = res;
727 properties = new_properties;
729 properties = new PropertyBuilder [1];
730 properties [0] = res;
738 public ConstructorBuilder DefineTypeInitializer()
740 return DefineConstructor (MethodAttributes.Public |
741 MethodAttributes.Static | MethodAttributes.SpecialName |
742 MethodAttributes.RTSpecialName, CallingConventions.Standard,
746 [MethodImplAttribute(MethodImplOptions.InternalCall)]
747 private extern Type create_runtime_class (TypeBuilder tb);
749 private bool is_nested_in (Type t)
760 // Return whenever this type has a ctor defined using DefineMethod ()
761 private bool has_ctor_method () {
762 MethodAttributes ctor_attrs = MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
764 for (int i = 0; i < num_methods; ++i) {
765 MethodBuilder mb = (MethodBuilder)(methods[i]);
767 if (mb.Name == ConstructorInfo.ConstructorName && (mb.Attributes & ctor_attrs) == ctor_attrs)
774 public Type CreateType()
776 /* handle nesting_type */
777 if (createTypeCalled)
780 if (!IsInterface && (parent == null) && (this != pmodule.assemblyb.corlib_object_type) && (FullName != "<Module>")) {
781 SetParent (pmodule.assemblyb.corlib_object_type);
784 create_generic_class ();
786 // Fire TypeResolve events for fields whose type is an unfinished
788 if (fields != null) {
789 foreach (FieldBuilder fb in fields) {
792 Type ft = fb.FieldType;
793 if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
794 TypeBuilder tb = (TypeBuilder)ft;
795 if (!tb.is_created) {
796 AppDomain.CurrentDomain.DoTypeResolve (tb);
797 if (!tb.is_created) {
798 // FIXME: We should throw an exception here,
799 // but mcs expects that the type is created
800 // even if the exception is thrown
801 //throw new TypeLoadException ("Could not load type " + tb);
808 if ((parent != null) && parent.IsSealed)
809 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
811 if (parent == pmodule.assemblyb.corlib_enum_type && methods != null)
812 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because it is an enum with methods.");
814 if (methods != null) {
815 for (int i = 0; i < num_methods; ++i) {
816 MethodBuilder mb = (MethodBuilder)(methods[i]);
817 mb.check_override ();
823 // On classes, define a default constructor if not provided
825 if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") &&
826 (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method ())
827 DefineDefaultConstructor (MethodAttributes.Public);
830 foreach (ConstructorBuilder ctor in ctors)
834 createTypeCalled = true;
835 created = create_runtime_class (this);
841 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
843 symbolWriter.OpenNamespace (this.Namespace);
845 if (methods != null) {
846 for (int i = 0; i < num_methods; ++i) {
847 MethodBuilder metb = (MethodBuilder) methods[i];
848 metb.GenerateDebugInfo (symbolWriter);
853 foreach (ConstructorBuilder ctor in ctors)
854 ctor.GenerateDebugInfo (symbolWriter);
857 symbolWriter.CloseNamespace ();
859 if (subtypes != null) {
860 for (int i = 0; i < subtypes.Length; ++i)
861 subtypes [i].GenerateDebugInfo (symbolWriter);
868 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
871 return created.GetConstructors (bindingAttr);
874 return new ConstructorInfo [0];
875 ArrayList l = new ArrayList ();
877 MethodAttributes mattrs;
879 foreach (ConstructorBuilder c in ctors) {
881 mattrs = c.Attributes;
882 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
883 if ((bindingAttr & BindingFlags.Public) != 0)
886 if ((bindingAttr & BindingFlags.NonPublic) != 0)
892 if ((mattrs & MethodAttributes.Static) != 0) {
893 if ((bindingAttr & BindingFlags.Static) != 0)
896 if ((bindingAttr & BindingFlags.Instance) != 0)
903 ConstructorInfo[] result = new ConstructorInfo [l.Count];
908 public override Type GetElementType ()
911 return created.GetElementType ();
914 public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
917 return created.GetEvent (name, bindingAttr);
920 /* Needed to keep signature compatibility with MS.NET */
921 public override EventInfo[] GetEvents ()
923 return GetEvents (DefaultBindingFlags);
926 public override EventInfo[] GetEvents (BindingFlags bindingAttr)
928 /* FIXME: mcs calls this
932 return new EventInfo [0];
934 return created.GetEvents (bindingAttr);
937 // This is only used from MonoGenericInst.initialize().
938 internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
941 return new EventInfo [0];
942 ArrayList l = new ArrayList ();
944 MethodAttributes mattrs;
947 foreach (EventBuilder eb in events) {
950 EventInfo c = get_event_info (eb);
952 accessor = c.GetAddMethod (true);
953 if (accessor == null)
954 accessor = c.GetRemoveMethod (true);
955 if (accessor == null)
957 mattrs = accessor.Attributes;
958 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
959 if ((bindingAttr & BindingFlags.Public) != 0)
962 if ((bindingAttr & BindingFlags.NonPublic) != 0)
968 if ((mattrs & MethodAttributes.Static) != 0) {
969 if ((bindingAttr & BindingFlags.Static) != 0)
972 if ((bindingAttr & BindingFlags.Instance) != 0)
979 EventInfo[] result = new EventInfo [l.Count];
984 public override FieldInfo GetField (string name, BindingFlags bindingAttr)
987 return created.GetField (name, bindingAttr);
993 FieldAttributes mattrs;
995 foreach (FieldInfo c in fields) {
1001 mattrs = c.Attributes;
1002 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
1003 if ((bindingAttr & BindingFlags.Public) != 0)
1006 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1012 if ((mattrs & FieldAttributes.Static) != 0) {
1013 if ((bindingAttr & BindingFlags.Static) != 0)
1016 if ((bindingAttr & BindingFlags.Instance) != 0)
1026 public override FieldInfo[] GetFields (BindingFlags bindingAttr)
1028 if (created != null)
1029 return created.GetFields (bindingAttr);
1032 return new FieldInfo [0];
1033 ArrayList l = new ArrayList ();
1035 FieldAttributes mattrs;
1037 foreach (FieldInfo c in fields) {
1041 mattrs = c.Attributes;
1042 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
1043 if ((bindingAttr & BindingFlags.Public) != 0)
1046 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1052 if ((mattrs & FieldAttributes.Static) != 0) {
1053 if ((bindingAttr & BindingFlags.Static) != 0)
1056 if ((bindingAttr & BindingFlags.Instance) != 0)
1063 FieldInfo[] result = new FieldInfo [l.Count];
1068 public override Type GetInterface (string name, bool ignoreCase)
1071 return created.GetInterface (name, ignoreCase);
1074 public override Type[] GetInterfaces ()
1076 if (interfaces != null) {
1077 Type[] ret = new Type [interfaces.Length];
1078 interfaces.CopyTo (ret, 0);
1081 return Type.EmptyTypes;
1085 public override MemberInfo[] GetMember (string name, MemberTypes type,
1086 BindingFlags bindingAttr)
1089 return created.GetMember (name, type, bindingAttr);
1092 public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
1095 return created.GetMembers (bindingAttr);
1098 private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type)
1100 MethodInfo[] candidates;
1102 MethodAttributes mattrs;
1104 if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
1105 MethodInfo [] parent_methods = parent.GetMethods (bindingAttr);
1106 ArrayList parent_candidates = new ArrayList (parent_methods.Length);
1108 bool flatten = (bindingAttr & BindingFlags.FlattenHierarchy) != 0;
1110 for (int i = 0; i < parent_methods.Length; i++) {
1111 MethodInfo m = parent_methods [i];
1113 mattrs = m.Attributes;
1115 if (m.IsStatic && !flatten)
1118 switch (mattrs & MethodAttributes.MemberAccessMask) {
1119 case MethodAttributes.Public:
1120 match = (bindingAttr & BindingFlags.Public) != 0;
1122 case MethodAttributes.Assembly:
1124 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1129 case MethodAttributes.Private:
1133 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1138 parent_candidates.Add (m);
1141 if (methods == null) {
1142 candidates = new MethodInfo [parent_candidates.Count];
1143 parent_candidates.CopyTo (candidates);
1145 candidates = new MethodInfo [methods.Length + parent_candidates.Count];
1146 parent_candidates.CopyTo (candidates, 0);
1147 methods.CopyTo (candidates, parent_candidates.Count);
1151 candidates = methods;
1153 if (candidates == null)
1154 return new MethodInfo [0];
1156 ArrayList l = new ArrayList ();
1158 foreach (MethodInfo c in candidates) {
1162 if (String.Compare (c.Name, name, ignoreCase) != 0)
1166 mattrs = c.Attributes;
1167 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1168 if ((bindingAttr & BindingFlags.Public) != 0)
1171 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1177 if ((mattrs & MethodAttributes.Static) != 0) {
1178 if ((bindingAttr & BindingFlags.Static) != 0)
1181 if ((bindingAttr & BindingFlags.Instance) != 0)
1189 MethodInfo[] result = new MethodInfo [l.Count];
1194 public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
1196 return GetMethodsByName (null, bindingAttr, false, this);
1199 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
1201 CallingConventions callConvention,
1202 Type[] types, ParameterModifier[] modifiers)
1206 bool ignoreCase = ((bindingAttr & BindingFlags.IgnoreCase) != 0);
1207 MethodInfo[] methods = GetMethodsByName (name, bindingAttr, ignoreCase, this);
1208 MethodInfo found = null;
1210 int typesLen = (types != null) ? types.Length : 0;
1213 foreach (MethodInfo m in methods) {
1214 // Under MS.NET, Standard|HasThis matches Standard...
1215 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1224 if (count == 1 && typesLen == 0)
1227 match = new MethodBase [count];
1232 foreach (MethodInfo m in methods) {
1233 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1235 match [count++] = m;
1240 return (MethodInfo) Binder.FindMostDerivedMatch (match);
1243 binder = Binder.DefaultBinder;
1245 return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
1248 public override Type GetNestedType (string name, BindingFlags bindingAttr)
1251 return created.GetNestedType (name, bindingAttr);
1254 public override Type[] GetNestedTypes (BindingFlags bindingAttr)
1257 ArrayList result = new ArrayList ();
1259 if (subtypes == null)
1260 return Type.EmptyTypes;
1261 foreach (TypeBuilder t in subtypes) {
1263 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1264 if ((bindingAttr & BindingFlags.Public) != 0)
1267 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1274 Type[] r = new Type [result.Count];
1279 public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
1282 return created.GetProperties (bindingAttr);
1284 if (properties == null)
1285 return new PropertyInfo [0];
1286 ArrayList l = new ArrayList ();
1288 MethodAttributes mattrs;
1289 MethodInfo accessor;
1291 foreach (PropertyInfo c in properties) {
1293 accessor = c.GetGetMethod (true);
1294 if (accessor == null)
1295 accessor = c.GetSetMethod (true);
1296 if (accessor == null)
1298 mattrs = accessor.Attributes;
1299 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1300 if ((bindingAttr & BindingFlags.Public) != 0)
1303 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1309 if ((mattrs & MethodAttributes.Static) != 0) {
1310 if ((bindingAttr & BindingFlags.Static) != 0)
1313 if ((bindingAttr & BindingFlags.Instance) != 0)
1320 PropertyInfo[] result = new PropertyInfo [l.Count];
1325 protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
1327 throw not_supported ();
1330 protected override bool HasElementTypeImpl ()
1333 // a TypeBuilder can never represent an array, pointer
1339 return created.HasElementType;
1342 public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
1345 return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
1348 protected override bool IsArrayImpl ()
1350 return false; /*A TypeBuilder never represents a non typedef type.*/
1353 protected override bool IsByRefImpl ()
1355 return false; /*A TypeBuilder never represents a non typedef type.*/
1358 protected override bool IsCOMObjectImpl ()
1360 return ((GetAttributeFlagsImpl () & TypeAttributes.Import) != 0);
1363 protected override bool IsPointerImpl ()
1365 return false; /*A TypeBuilder never represents a non typedef type.*/
1368 protected override bool IsPrimitiveImpl ()
1374 // FIXME: I doubt just removing this still works.
1375 protected override bool IsValueTypeImpl ()
1377 return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
1378 this != pmodule.assemblyb.corlib_value_type &&
1379 this != pmodule.assemblyb.corlib_enum_type);
1384 public override Type MakeArrayType ()
1386 return MakeArrayType (1);
1390 public override Type MakeArrayType (int rank)
1392 return new ArrayType (this, rank);
1396 public override Type MakeByRefType ()
1398 return new ByRefType (this);;
1402 public override Type MakeGenericType (params Type [] typeArguments)
1404 return base.MakeGenericType (typeArguments);
1408 public override Type MakePointerType ()
1410 return new PointerType (this);
1414 public override RuntimeTypeHandle TypeHandle {
1417 return created.TypeHandle;
1422 // Used internally by mcs only
1424 internal void SetCharSet (TypeAttributes ta)
1429 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
1431 if (customBuilder == null)
1432 throw new ArgumentNullException ("customBuilder");
1434 string attrname = customBuilder.Ctor.ReflectedType.FullName;
1435 if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
1436 byte[] data = customBuilder.Data;
1437 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
1438 layout_kind = (int)data [2];
1439 layout_kind |= ((int)data [3]) << 8;
1440 attrs &= ~TypeAttributes.LayoutMask;
1441 switch ((LayoutKind)layout_kind) {
1442 case LayoutKind.Auto:
1443 attrs |= TypeAttributes.AutoLayout;
1445 case LayoutKind.Explicit:
1446 attrs |= TypeAttributes.ExplicitLayout;
1448 case LayoutKind.Sequential:
1449 attrs |= TypeAttributes.SequentialLayout;
1452 // we should ignore it since it can be any value anyway...
1453 throw new Exception ("Error in customattr");
1455 string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
1457 if (first_type_name == "System.Int16")
1459 int nnamed = (int)data [pos++];
1460 nnamed |= ((int)data [pos++]) << 8;
1461 for (int i = 0; i < nnamed; ++i) {
1462 //byte named_type = data [pos++];
1464 byte type = data [pos++];
1469 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1470 //string named_typename =
1471 CustomAttributeBuilder.string_from_bytes (data, pos, len);
1473 // FIXME: Check that 'named_type' and 'named_typename' match, etc.
1474 // See related code/FIXME in mono/mono/metadata/reflection.c
1477 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1478 named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1480 /* all the fields are integers in StructLayout */
1481 int value = (int)data [pos++];
1482 value |= ((int)data [pos++]) << 8;
1483 value |= ((int)data [pos++]) << 16;
1484 value |= ((int)data [pos++]) << 24;
1485 switch (named_name) {
1487 switch ((CharSet)value) {
1490 attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass);
1492 case CharSet.Unicode:
1493 attrs &= ~TypeAttributes.AutoClass;
1494 attrs |= TypeAttributes.UnicodeClass;
1497 attrs &= ~TypeAttributes.UnicodeClass;
1498 attrs |= TypeAttributes.AutoClass;
1501 break; // error out...
1505 packing_size = (PackingSize)value;
1511 break; // error out...
1516 } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
1517 attrs |= TypeAttributes.SpecialName;
1520 } else if (attrname == "System.SerializableAttribute") {
1521 attrs |= TypeAttributes.Serializable;
1523 } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
1524 attrs |= TypeAttributes.Import;
1526 } else if (attrname == "System.Security.SuppressUnmanagedCodeSecurityAttribute") {
1527 attrs |= TypeAttributes.HasSecurity;
1530 if (cattrs != null) {
1531 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1532 cattrs.CopyTo (new_array, 0);
1533 new_array [cattrs.Length] = customBuilder;
1536 cattrs = new CustomAttributeBuilder [1];
1537 cattrs [0] = customBuilder;
1544 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
1546 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1549 public EventBuilder DefineEvent (string name, EventAttributes attributes, Type eventtype)
1551 check_name ("name", name);
1552 if (eventtype == null)
1553 throw new ArgumentNullException ("type");
1554 check_not_created ();
1556 EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1557 if (events != null) {
1558 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1559 System.Array.Copy (events, new_events, events.Length);
1560 new_events [events.Length] = res;
1561 events = new_events;
1563 events = new EventBuilder [1];
1569 public FieldBuilder DefineInitializedData (string name, byte[] data, FieldAttributes attributes) {
1571 throw new ArgumentNullException ("data");
1573 FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
1574 res.SetRVAData (data);
1578 public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
1581 throw new ArgumentNullException ("name");
1582 if (name.Length == 0)
1583 throw new ArgumentException ("Empty name is not legal", "name");
1584 if ((size <= 0) || (size > 0x3f0000))
1585 throw new ArgumentException ("Data size must be > 0 and < 0x3f0000");
1586 check_not_created ();
1588 string typeName = "$ArrayType$" + size;
1589 Type datablobtype = pmodule.GetRegisteredType (fullname + "+" + typeName);
1590 if (datablobtype == null) {
1591 TypeBuilder tb = DefineNestedType (typeName,
1592 TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1593 pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
1597 return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1600 public TypeToken TypeToken {
1602 return new TypeToken (0x02000000 | table_idx);
1606 public void SetParent (Type parent)
1608 check_not_created ();
1611 if (parent == null) {
1612 if ((attrs & TypeAttributes.Interface) != 0) {
1613 if ((attrs & TypeAttributes.Abstract) == 0)
1614 throw new InvalidOperationException ("Interface must be declared abstract.");
1617 this.parent = typeof (object);
1620 this.parent = parent;
1624 throw new ArgumentNullException ("parent");
1625 this.parent = parent;
1628 // will just set the parent-related bits if called a second time
1629 setup_internal_class (this);
1632 internal int get_next_table_index (object obj, int table, bool inc) {
1633 return pmodule.get_next_table_index (obj, table, inc);
1639 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1641 if (created == null)
1642 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1644 return created.GetInterfaceMap (interfaceType);
1647 internal bool IsCompilerContext {
1649 return pmodule.assemblyb.IsCompilerContext;
1653 internal bool is_created {
1655 return created != null;
1659 private Exception not_supported ()
1661 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1664 private void check_not_created ()
1667 throw new InvalidOperationException ("Unable to change after type has been created.");
1670 private void check_created ()
1673 throw not_supported ();
1676 private void check_name (string argName, string name)
1679 throw new ArgumentNullException (argName);
1680 if (name.Length == 0)
1681 throw new ArgumentException ("Empty name is not legal", argName);
1682 if (name [0] == ((char)0))
1683 throw new ArgumentException ("Illegal name", argName);
1686 public override String ToString ()
1692 public override bool IsAssignableFrom (Type c)
1694 return base.IsAssignableFrom (c);
1701 public override bool IsSubclassOf (Type c)
1703 return base.IsSubclassOf (c);
1706 [MonoTODO ("arrays")]
1707 internal bool IsAssignableTo (Type c)
1712 if (c.IsInterface) {
1713 if (parent != null && is_created) {
1714 if (c.IsAssignableFrom (parent))
1718 if (interfaces == null)
1720 foreach (Type t in interfaces)
1721 if (c.IsAssignableFrom (t))
1728 return c == typeof (object);
1730 return c.IsAssignableFrom (parent);
1733 #if NET_2_0 || BOOTSTRAP_NET_2_0
1734 public bool IsCreated ()
1739 public override Type[] GetGenericArguments ()
1741 if (generic_params != null)
1742 return generic_params;
1744 throw new InvalidOperationException ();
1747 public override Type GetGenericTypeDefinition ()
1749 create_generic_class ();
1751 return base.GetGenericTypeDefinition_impl ();
1754 public override bool ContainsGenericParameters {
1756 return generic_params != null;
1760 public extern override bool IsGenericParameter {
1761 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1765 public override bool IsGenericTypeDefinition {
1767 return generic_params != null;
1771 public override bool IsGenericType {
1772 get { return IsGenericTypeDefinition; }
1776 public override int GenericParameterPosition {
1778 throw new NotImplementedException ();
1782 public override MethodBase DeclaringMethod {
1784 throw new NotImplementedException ();
1788 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
1790 setup_generic_class ();
1792 generic_params = new GenericTypeParameterBuilder [names.Length];
1793 for (int i = 0; i < names.Length; i++)
1794 generic_params [i] = new GenericTypeParameterBuilder (
1795 this, null, names [i], i);
1797 return generic_params;
1800 public static ConstructorInfo GetConstructor (Type type, ConstructorInfo constructor)
1802 ConstructorInfo res = type.GetConstructor (constructor);
1804 throw new System.Exception ("constructor not found");
1809 static bool IsValidGetMethodType (Type type)
1811 if (type is TypeBuilder || type is MonoGenericClass)
1813 /*GetMethod() must work with TypeBuilders after CreateType() was called.*/
1814 if (type.Module is ModuleBuilder)
1816 if (type.IsGenericParameter)
1819 Type[] inst = type.GetGenericArguments ();
1822 for (int i = 0; i < inst.Length; ++i) {
1823 if (IsValidGetMethodType (inst [i]))
1829 public static MethodInfo GetMethod (Type type, MethodInfo method)
1831 if (!IsValidGetMethodType (type))
1832 throw new ArgumentException ("type is not TypeBuilder but " + type.GetType (), "type");
1834 if (!type.IsGenericType)
1835 throw new ArgumentException ("type is not a generic type", "type");
1837 if (!method.DeclaringType.IsGenericTypeDefinition)
1838 throw new ArgumentException ("method declaring type is not a generic type definition", "method");
1839 if (method.DeclaringType != type.GetGenericTypeDefinition ())
1840 throw new ArgumentException ("method declaring type is not the generic type definition of type", "method");
1842 MethodInfo res = type.GetMethod (method);
1844 throw new ArgumentException (String.Format ("method {0} not found in type {1}", method.Name, type));
1849 public static FieldInfo GetField (Type type, FieldInfo field)
1851 FieldInfo res = type.GetField (field);
1853 throw new System.Exception ("field not found");
1859 void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1861 throw new NotImplementedException ();
1864 void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1866 throw new NotImplementedException ();
1869 void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
1871 throw new NotImplementedException ();
1874 void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1876 throw new NotImplementedException ();