2 // System.Reflection.Emit/TypeBuilder.cs
5 // Paolo Molaro (lupus@ximian.com)
7 // (C) 2001 Ximian, Inc. http://www.ximian.com
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Reflection;
36 using System.Reflection.Emit;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
39 using System.Globalization;
40 using System.Collections;
41 using System.Security;
42 using System.Security.Permissions;
43 using System.Diagnostics.SymbolStore;
45 namespace System.Reflection.Emit {
48 [ComDefaultInterface (typeof (_TypeBuilder))]
50 [ClassInterface (ClassInterfaceType.None)]
51 public sealed class TypeBuilder : Type, _TypeBuilder {
52 #region Sync with reflection.h
54 private string nspace;
56 private Type nesting_type;
57 private Type[] interfaces;
58 private int num_methods;
59 private MethodBuilder[] methods;
60 private ConstructorBuilder[] ctors;
61 private PropertyBuilder[] properties;
62 private int num_fields;
63 private FieldBuilder[] fields;
64 private EventBuilder[] events;
65 private CustomAttributeBuilder[] cattrs;
66 internal TypeBuilder[] subtypes;
67 internal TypeAttributes attrs;
68 private int table_idx;
69 private ModuleBuilder pmodule;
70 private int class_size;
71 private PackingSize packing_size;
72 private IntPtr generic_container;
73 #if NET_2_0 || BOOTSTRAP_NET_2_0
74 private GenericTypeParameterBuilder[] generic_params;
76 private Object generic_params; /* so offsets don't change */
78 private RefEmitPermissionSet[] permissions;
83 public const int UnspecifiedTypeSize = 0;
85 protected override TypeAttributes GetAttributeFlagsImpl () {
89 [MethodImplAttribute(MethodImplOptions.InternalCall)]
90 private extern void setup_internal_class (TypeBuilder tb);
92 [MethodImplAttribute(MethodImplOptions.InternalCall)]
93 private extern void create_internal_class (TypeBuilder tb);
95 [MethodImplAttribute(MethodImplOptions.InternalCall)]
96 private extern void setup_generic_class ();
98 [MethodImplAttribute(MethodImplOptions.InternalCall)]
99 private extern void create_generic_class ();
101 [MethodImplAttribute(MethodImplOptions.InternalCall)]
102 private extern EventInfo get_event_info (EventBuilder eb);
104 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr) {
107 this.class_size = UnspecifiedTypeSize;
109 fullname = this.tname = "<Module>";
112 setup_internal_class (this);
115 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type) {
117 this.parent = parent;
119 this.class_size = type_size;
120 this.packing_size = packing_size;
121 this.nesting_type = nesting_type;
122 sep_index = name.LastIndexOf('.');
123 if (sep_index != -1) {
124 this.tname = name.Substring (sep_index + 1);
125 this.nspace = name.Substring (0, sep_index);
130 if (interfaces != null) {
131 this.interfaces = new Type[interfaces.Length];
132 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
136 table_idx = mb.get_next_table_index (this, 0x02, true);
137 setup_internal_class (this);
138 fullname = GetFullName ();
141 public override Assembly Assembly {
142 get {return pmodule.Assembly;}
145 public override string AssemblyQualifiedName {
147 return fullname + ", " + Assembly.GetName().FullName;
150 public override Type BaseType {
155 public override Type DeclaringType {get {return nesting_type;}}
157 /* public override bool IsSubclassOf (Type c)
174 public override Type UnderlyingSystemType {
177 // Return this as requested by Zoltan.
182 // Dont know what to do with the rest, should be killed:
185 ////// This should return the type itself for non-enum types but
186 ////// that breaks mcs.
187 if (fields != null) {
188 foreach (FieldBuilder f in fields) {
189 if ((f != null) && (f.Attributes & FieldAttributes.Static) == 0)
193 throw new InvalidOperationException ("Underlying type information on enumeration is not specified.");
198 string GetFullName () {
199 if (nesting_type != null)
200 return String.Concat (nesting_type.FullName, "+", tname);
201 if ((nspace != null) && (nspace.Length > 0))
202 return String.Concat (nspace, ".", tname);
206 public override string FullName {
212 public override Guid GUID {
219 public override Module Module {
220 get {return pmodule;}
222 public override string Name {
225 public override string Namespace {
228 public PackingSize PackingSize {
229 get {return packing_size;}
232 get { return class_size; }
234 public override Type ReflectedType {get {return nesting_type;}}
236 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
238 throw new ArgumentNullException ("pset");
239 if ((action == SecurityAction.RequestMinimum) ||
240 (action == SecurityAction.RequestOptional) ||
241 (action == SecurityAction.RequestRefuse))
242 throw new ArgumentException ("Request* values are not permitted", "action");
244 check_not_created ();
246 if (permissions != null) {
247 /* Check duplicate actions */
248 foreach (RefEmitPermissionSet set in permissions)
249 if (set.action == action)
250 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
252 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
253 permissions.CopyTo (new_array, 0);
254 permissions = new_array;
257 permissions = new RefEmitPermissionSet [1];
259 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
260 attrs |= TypeAttributes.HasSecurity;
266 public void AddInterfaceImplementation( Type interfaceType) {
267 if (interfaceType == null)
268 throw new ArgumentNullException ("interfaceType");
269 check_not_created ();
271 if (interfaces != null) {
272 // Check for duplicates
273 foreach (Type t in interfaces)
274 if (t == interfaceType)
277 Type[] ifnew = new Type [interfaces.Length + 1];
278 interfaces.CopyTo (ifnew, 0);
279 ifnew [interfaces.Length] = interfaceType;
282 interfaces = new Type [1];
283 interfaces [0] = interfaceType;
288 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
289 CallingConventions callConvention, Type[] types,
290 ParameterModifier[] modifiers)
297 ConstructorBuilder found = null;
300 foreach (ConstructorBuilder cb in ctors){
301 if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
311 throw new AmbiguousMatchException ();
314 MethodBase[] match = new MethodBase [count];
319 foreach (ConstructorInfo m in ctors) {
320 if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
326 binder = Binder.DefaultBinder;
327 return (ConstructorInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
330 public override bool IsDefined( Type attributeType, bool inherit)
333 * MS throws NotSupported here, but we can't because some corlib
334 * classes make calls to IsDefined.
336 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
339 public override object[] GetCustomAttributes(bool inherit)
343 return created.GetCustomAttributes (inherit);
346 public override object[] GetCustomAttributes(Type attributeType, bool inherit)
350 return created.GetCustomAttributes (attributeType, inherit);
353 public TypeBuilder DefineNestedType (string name) {
354 return DefineNestedType (name, TypeAttributes.NestedPrivate, pmodule.assemblyb.corlib_object_type, null);
357 public TypeBuilder DefineNestedType (string name, TypeAttributes attr) {
358 return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
361 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent) {
362 return DefineNestedType (name, attr, parent, null);
365 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
366 PackingSize packsize, int typesize)
368 check_name ("name", name);
369 // Visibility must be NestedXXX
371 if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
372 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
373 throw new ArgumentException ("attr", "Bad type flags for nested type.");
375 if (interfaces != null)
376 foreach (Type iface in interfaces)
378 throw new ArgumentNullException ("interfaces");
380 TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packsize, typesize, this);
381 res.fullname = res.GetFullName ();
382 pmodule.RegisterTypeName (res, res.fullname);
383 if (subtypes != null) {
384 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
385 System.Array.Copy (subtypes, new_types, subtypes.Length);
386 new_types [subtypes.Length] = res;
387 subtypes = new_types;
389 subtypes = new TypeBuilder [1];
398 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
399 return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
402 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typesize) {
403 return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typesize);
406 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
407 return DefineNestedType (name, attr, parent, null, packsize, UnspecifiedTypeSize);
413 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) {
414 return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
420 #if NET_2_0 || BOOTSTRAP_NET_2_0
425 ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
427 check_not_created ();
428 ConstructorBuilder cb = new ConstructorBuilder (this, attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
430 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
431 System.Array.Copy (ctors, new_ctors, ctors.Length);
432 new_ctors [ctors.Length] = cb;
435 ctors = new ConstructorBuilder [1];
444 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
449 parent_type = parent;
451 parent_type = pmodule.assemblyb.corlib_object_type;
453 ConstructorInfo parent_constructor =
454 parent_type.GetConstructor (
455 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
456 null, Type.EmptyTypes, null);
457 if (parent_constructor == null) {
458 throw new NotSupportedException ("Parent does"
459 + " not have a default constructor."
460 + " The default constructor must be"
461 + " explicitly defined.");
464 ConstructorBuilder cb = DefineConstructor (attributes,
465 CallingConventions.Standard, new Type[0]);
466 ILGenerator ig = cb.GetILGenerator ();
467 ig.Emit (OpCodes.Ldarg_0);
468 ig.Emit (OpCodes.Call, parent_constructor);
469 ig.Emit (OpCodes.Ret);
473 private void append_method (MethodBuilder mb) {
474 if (methods != null) {
475 if (methods.Length == num_methods) {
476 MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
477 System.Array.Copy (methods, new_methods, num_methods);
478 methods = new_methods;
481 methods = new MethodBuilder [1];
483 methods [num_methods] = mb;
487 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) {
488 return DefineMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
491 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
492 return DefineMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
495 #if NET_2_0 || BOOTSTRAP_NET_2_0
500 MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
501 check_name ("name", name);
502 check_not_created ();
504 !((attributes & MethodAttributes.Abstract) != 0) ||
505 !((attributes & MethodAttributes.Virtual) != 0)))
506 throw new ArgumentException ("attributes", "Interface method must be abstract and virtual.");
508 if (returnType == null)
509 returnType = pmodule.assemblyb.corlib_void_type;
510 MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
515 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
516 return DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet);
519 #if NET_2_0 || BOOTSTRAP_NET_2_0
524 MethodBuilder DefinePInvokeMethod (
527 string entryName, MethodAttributes attributes,
528 CallingConventions callingConvention,
530 Type[] returnTypeRequiredCustomModifiers,
531 Type[] returnTypeOptionalCustomModifiers,
532 Type[] parameterTypes,
533 Type[][] parameterTypeRequiredCustomModifiers,
534 Type[][] parameterTypeOptionalCustomModifiers,
535 CallingConvention nativeCallConv,
536 CharSet nativeCharSet) {
537 check_name ("name", name);
538 check_name ("dllName", dllName);
539 check_name ("entryName", entryName);
540 if ((attributes & MethodAttributes.Abstract) != 0)
541 throw new ArgumentException ("attributes", "PInvoke methods must be static and native and cannot be abstract.");
543 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
544 check_not_created ();
547 = new MethodBuilder (
553 returnTypeRequiredCustomModifiers,
554 returnTypeOptionalCustomModifiers,
556 parameterTypeRequiredCustomModifiers,
557 parameterTypeOptionalCustomModifiers,
566 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
567 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
568 nativeCallConv, nativeCharSet);
571 #if NET_2_0 || BOOTSTRAP_NET_2_0
572 public MethodBuilder DefineMethod (string name, MethodAttributes attributes) {
573 return DefineMethod (name, attributes, CallingConventions.Standard);
576 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callConv) {
577 return DefineMethod (name, attributes, callConv, null, null);
581 public void DefineMethodOverride( MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) {
582 if (methodInfoBody == null)
583 throw new ArgumentNullException ("methodInfoBody");
584 if (methodInfoDeclaration == null)
585 throw new ArgumentNullException ("methodInfoDeclaration");
586 check_not_created ();
588 if (methodInfoBody is MethodBuilder) {
589 MethodBuilder mb = (MethodBuilder)methodInfoBody;
590 mb.set_override (methodInfoDeclaration);
594 public FieldBuilder DefineField( string fieldName, Type type, FieldAttributes attributes) {
595 return DefineField (fieldName, type, null, null, attributes);
598 #if NET_2_0 || BOOTSTRAP_NET_2_0
603 FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomAttributes, Type[] optionalCustomAttributes, FieldAttributes attributes) {
604 check_name ("fieldName", fieldName);
605 if (type == typeof (void))
606 throw new ArgumentException ("type", "Bad field type in defining field.");
607 check_not_created ();
609 FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomAttributes, optionalCustomAttributes);
610 if (fields != null) {
611 if (fields.Length == num_fields) {
612 FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
613 System.Array.Copy (fields, new_fields, num_fields);
616 fields [num_fields] = res;
619 fields = new FieldBuilder [1];
622 create_internal_class (this);
627 public PropertyBuilder DefineProperty( string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) {
628 return DefineProperty (name, attributes, returnType, null, null, parameterTypes, null, null);
636 PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
637 check_name ("name", name);
638 if (parameterTypes != null)
639 foreach (Type param in parameterTypes)
641 throw new ArgumentNullException ("parameterTypes");
642 check_not_created ();
644 PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
646 if (properties != null) {
647 PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
648 System.Array.Copy (properties, new_properties, properties.Length);
649 new_properties [properties.Length] = res;
650 properties = new_properties;
652 properties = new PropertyBuilder [1];
653 properties [0] = res;
661 public ConstructorBuilder DefineTypeInitializer() {
662 return DefineConstructor (MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, null);
665 [MethodImplAttribute(MethodImplOptions.InternalCall)]
666 private extern Type create_runtime_class (TypeBuilder tb);
668 private bool is_nested_in (Type t) {
678 public Type CreateType() {
679 /* handle nesting_type */
683 create_generic_class ();
685 // Fire TypeResolve events for fields whose type is an unfinished
687 if (fields != null) {
688 foreach (FieldBuilder fb in fields) {
691 Type ft = fb.FieldType;
692 if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
693 TypeBuilder tb = (TypeBuilder)ft;
694 if (!tb.is_created) {
695 AppDomain.CurrentDomain.DoTypeResolve (tb);
696 if (!tb.is_created) {
697 // FIXME: We should throw an exception here,
698 // but mcs expects that the type is created
699 // even if the exception is thrown
700 //throw new TypeLoadException ("Could not load type " + tb);
707 if ((parent != null) && parent.IsSealed)
708 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
710 if (methods != null) {
711 for (int i = 0; i < num_methods; ++i)
712 ((MethodBuilder)(methods[i])).fixup ();
716 // On classes, define a default constructor if not provided
718 if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") &&
719 (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed))
720 DefineDefaultConstructor (MethodAttributes.Public);
723 foreach (ConstructorBuilder ctor in ctors)
727 created = create_runtime_class (this);
733 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
735 symbolWriter.OpenNamespace (this.Namespace);
737 if (methods != null) {
738 for (int i = 0; i < num_methods; ++i) {
739 MethodBuilder metb = (MethodBuilder) methods[i];
740 metb.GenerateDebugInfo (symbolWriter);
745 foreach (ConstructorBuilder ctor in ctors)
746 ctor.GenerateDebugInfo (symbolWriter);
749 symbolWriter.CloseNamespace ();
755 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
758 return new ConstructorInfo [0];
759 ArrayList l = new ArrayList ();
761 MethodAttributes mattrs;
763 foreach (ConstructorBuilder c in ctors) {
765 mattrs = c.Attributes;
766 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
767 if ((bindingAttr & BindingFlags.Public) != 0)
770 if ((bindingAttr & BindingFlags.NonPublic) != 0)
776 if ((mattrs & MethodAttributes.Static) != 0) {
777 if ((bindingAttr & BindingFlags.Static) != 0)
780 if ((bindingAttr & BindingFlags.Instance) != 0)
787 ConstructorInfo[] result = new ConstructorInfo [l.Count];
792 public override Type GetElementType () {
794 return created.GetElementType ();
797 public override EventInfo GetEvent (string name, BindingFlags bindingAttr) {
799 return created.GetEvent (name, bindingAttr);
802 /* Needed to keep signature compatibility with MS.NET */
803 public override EventInfo[] GetEvents ()
805 return GetEvents (DefaultBindingFlags);
808 public override EventInfo[] GetEvents (BindingFlags bindingAttr) {
809 /* FIXME: mcs calls this
813 return new EventInfo [0];
815 return created.GetEvents (bindingAttr);
818 // This is only used from MonoGenericInst.initialize().
819 internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
822 return new EventInfo [0];
823 ArrayList l = new ArrayList ();
825 MethodAttributes mattrs;
828 foreach (EventBuilder eb in events) {
831 EventInfo c = get_event_info (eb);
833 accessor = c.GetAddMethod (true);
834 if (accessor == null)
835 accessor = c.GetRemoveMethod (true);
836 if (accessor == null)
838 mattrs = accessor.Attributes;
839 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
840 if ((bindingAttr & BindingFlags.Public) != 0)
843 if ((bindingAttr & BindingFlags.NonPublic) != 0)
849 if ((mattrs & MethodAttributes.Static) != 0) {
850 if ((bindingAttr & BindingFlags.Static) != 0)
853 if ((bindingAttr & BindingFlags.Instance) != 0)
860 EventInfo[] result = new EventInfo [l.Count];
865 public override FieldInfo GetField( string name, BindingFlags bindingAttr) {
870 FieldAttributes mattrs;
872 foreach (FieldInfo c in fields) {
878 mattrs = c.Attributes;
879 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
880 if ((bindingAttr & BindingFlags.Public) != 0)
883 if ((bindingAttr & BindingFlags.NonPublic) != 0)
889 if ((mattrs & FieldAttributes.Static) != 0) {
890 if ((bindingAttr & BindingFlags.Static) != 0)
893 if ((bindingAttr & BindingFlags.Instance) != 0)
903 public override FieldInfo[] GetFields (BindingFlags bindingAttr) {
905 return new FieldInfo [0];
906 ArrayList l = new ArrayList ();
908 FieldAttributes mattrs;
910 foreach (FieldInfo c in fields) {
914 mattrs = c.Attributes;
915 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
916 if ((bindingAttr & BindingFlags.Public) != 0)
919 if ((bindingAttr & BindingFlags.NonPublic) != 0)
925 if ((mattrs & FieldAttributes.Static) != 0) {
926 if ((bindingAttr & BindingFlags.Static) != 0)
929 if ((bindingAttr & BindingFlags.Instance) != 0)
936 FieldInfo[] result = new FieldInfo [l.Count];
941 public override Type GetInterface (string name, bool ignoreCase) {
943 return created.GetInterface (name, ignoreCase);
946 public override Type[] GetInterfaces () {
947 if (interfaces != null) {
948 Type[] ret = new Type [interfaces.Length];
949 interfaces.CopyTo (ret, 0);
952 return Type.EmptyTypes;
956 public override MemberInfo[] GetMember (string name, MemberTypes type,
957 BindingFlags bindingAttr) {
959 return created.GetMember (name, type, bindingAttr);
962 public override MemberInfo[] GetMembers (BindingFlags bindingAttr) {
964 return created.GetMembers (bindingAttr);
967 private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type) {
968 MethodInfo[] candidates;
969 if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
970 MethodInfo[] parent_methods = parent.GetMethods (bindingAttr);
972 candidates = parent_methods;
974 candidates = new MethodInfo [methods.Length + parent_methods.Length];
975 parent_methods.CopyTo (candidates, 0);
976 methods.CopyTo (candidates, parent_methods.Length);
980 candidates = methods;
982 if (candidates == null)
983 return new MethodInfo [0];
985 ArrayList l = new ArrayList ();
987 MethodAttributes mattrs;
989 foreach (MethodInfo c in candidates) {
993 if (String.Compare (c.Name, name, ignoreCase) != 0)
997 mattrs = c.Attributes;
998 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
999 if ((bindingAttr & BindingFlags.Public) != 0)
1002 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1008 if ((mattrs & MethodAttributes.Static) != 0) {
1009 if ((bindingAttr & BindingFlags.Static) != 0)
1012 if ((bindingAttr & BindingFlags.Instance) != 0)
1020 MethodInfo[] result = new MethodInfo [l.Count];
1025 public override MethodInfo[] GetMethods (BindingFlags bindingAttr) {
1026 return GetMethodsByName (null, bindingAttr, false, this);
1029 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
1031 CallingConventions callConvention,
1032 Type[] types, ParameterModifier[] modifiers)
1036 bool ignoreCase = ((bindingAttr & BindingFlags.IgnoreCase) != 0);
1037 MethodInfo[] methods = GetMethodsByName (name, bindingAttr, ignoreCase, this);
1038 MethodInfo found = null;
1040 int typesLen = (types != null) ? types.Length : 0;
1043 foreach (MethodInfo m in methods) {
1044 // Under MS.NET, Standard|HasThis matches Standard...
1045 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1054 if (count == 1 && typesLen == 0)
1057 match = new MethodBase [count];
1062 foreach (MethodInfo m in methods) {
1063 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1065 match [count++] = m;
1070 return (MethodInfo) Binder.FindMostDerivedMatch (match);
1073 binder = Binder.DefaultBinder;
1075 return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
1078 public override Type GetNestedType( string name, BindingFlags bindingAttr) {
1080 return created.GetNestedType (name, bindingAttr);
1083 public override Type[] GetNestedTypes (BindingFlags bindingAttr) {
1085 ArrayList result = new ArrayList ();
1087 if (subtypes == null)
1088 return Type.EmptyTypes;
1089 foreach (TypeBuilder t in subtypes) {
1091 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1092 if ((bindingAttr & BindingFlags.Public) != 0)
1095 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1102 Type[] r = new Type [result.Count];
1107 public override PropertyInfo[] GetProperties( BindingFlags bindingAttr) {
1108 if (properties == null)
1109 return new PropertyInfo [0];
1110 ArrayList l = new ArrayList ();
1112 MethodAttributes mattrs;
1113 MethodInfo accessor;
1115 foreach (PropertyInfo c in properties) {
1117 accessor = c.GetGetMethod (true);
1118 if (accessor == null)
1119 accessor = c.GetSetMethod (true);
1120 if (accessor == null)
1122 mattrs = accessor.Attributes;
1123 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1124 if ((bindingAttr & BindingFlags.Public) != 0)
1127 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1133 if ((mattrs & MethodAttributes.Static) != 0) {
1134 if ((bindingAttr & BindingFlags.Static) != 0)
1137 if ((bindingAttr & BindingFlags.Instance) != 0)
1144 PropertyInfo[] result = new PropertyInfo [l.Count];
1149 protected override PropertyInfo GetPropertyImpl( string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) {
1150 throw not_supported ();
1153 protected override bool HasElementTypeImpl () {
1155 return created.HasElementType;
1158 public override object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) {
1160 return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
1163 protected override bool IsArrayImpl ()
1165 return Type.IsArrayImpl (this);
1168 protected override bool IsByRefImpl () {
1172 protected override bool IsCOMObjectImpl () {
1175 protected override bool IsPointerImpl () {
1179 protected override bool IsPrimitiveImpl () {
1183 protected override bool IsValueTypeImpl () {
1184 return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
1185 this != pmodule.assemblyb.corlib_value_type &&
1186 this != pmodule.assemblyb.corlib_enum_type);
1189 public override RuntimeTypeHandle TypeHandle {
1192 return created.TypeHandle;
1196 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
1197 if (customBuilder == null)
1198 throw new ArgumentNullException ("customBuilder");
1200 string attrname = customBuilder.Ctor.ReflectedType.FullName;
1201 if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
1202 byte[] data = customBuilder.Data;
1203 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
1204 layout_kind = (int)data [2];
1205 layout_kind |= ((int)data [3]) << 8;
1206 attrs &= ~TypeAttributes.LayoutMask;
1207 switch ((LayoutKind)layout_kind) {
1208 case LayoutKind.Auto:
1209 attrs |= TypeAttributes.AutoLayout;
1211 case LayoutKind.Explicit:
1212 attrs |= TypeAttributes.ExplicitLayout;
1214 case LayoutKind.Sequential:
1215 attrs |= TypeAttributes.SequentialLayout;
1218 // we should ignore it since it can be any value anyway...
1219 throw new Exception ("Error in customattr");
1221 string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
1223 if (first_type_name == "System.Int16")
1225 int nnamed = (int)data [pos++];
1226 nnamed |= ((int)data [pos++]) << 8;
1227 for (int i = 0; i < nnamed; ++i) {
1228 //byte named_type = data [pos++];
1230 byte type = data [pos++];
1235 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1236 //string named_typename =
1237 CustomAttributeBuilder.string_from_bytes (data, pos, len);
1239 // FIXME: Check that 'named_type' and 'named_typename' match, etc.
1240 // See related code/FIXME in mono/mono/metadata/reflection.c
1243 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1244 named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1246 /* all the fields are integers in StructLayout */
1247 int value = (int)data [pos++];
1248 value |= ((int)data [pos++]) << 8;
1249 value |= ((int)data [pos++]) << 16;
1250 value |= ((int)data [pos++]) << 24;
1251 switch (named_name) {
1253 switch ((CharSet)value) {
1256 attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass);
1258 case CharSet.Unicode:
1259 attrs &= ~TypeAttributes.AutoClass;
1260 attrs |= TypeAttributes.UnicodeClass;
1263 attrs &= ~TypeAttributes.UnicodeClass;
1264 attrs |= TypeAttributes.AutoClass;
1267 break; // error out...
1271 packing_size = (PackingSize)value;
1277 break; // error out...
1282 } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
1283 attrs |= TypeAttributes.SpecialName;
1286 } else if (attrname == "System.SerializableAttribute") {
1287 attrs |= TypeAttributes.Serializable;
1289 } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
1290 attrs |= TypeAttributes.Import;
1294 if (cattrs != null) {
1295 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1296 cattrs.CopyTo (new_array, 0);
1297 new_array [cattrs.Length] = customBuilder;
1300 cattrs = new CustomAttributeBuilder [1];
1301 cattrs [0] = customBuilder;
1308 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
1309 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1312 public EventBuilder DefineEvent( string name, EventAttributes attributes, Type eventtype) {
1313 check_name ("name", name);
1314 if (eventtype == null)
1315 throw new ArgumentNullException ("eventtype");
1316 check_not_created ();
1318 EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1319 if (events != null) {
1320 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1321 System.Array.Copy (events, new_events, events.Length);
1322 new_events [events.Length] = res;
1323 events = new_events;
1325 events = new EventBuilder [1];
1331 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
1333 throw new ArgumentNullException ("data");
1334 if ((data.Length == 0) || (data.Length > 0x3f0000))
1335 throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
1337 FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
1338 res.SetRVAData (data);
1343 static int UnmanagedDataCount = 0;
1345 public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
1346 check_name ("name", name);
1347 if ((size <= 0) || (size > 0x3f0000))
1348 throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
1349 check_not_created ();
1351 string s = "$ArrayType$"+UnmanagedDataCount.ToString();
1352 UnmanagedDataCount++;
1353 TypeBuilder datablobtype = DefineNestedType (s,
1354 TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1355 pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
1356 datablobtype.CreateType ();
1357 return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1360 public TypeToken TypeToken {
1362 return new TypeToken (0x02000000 | table_idx);
1365 public void SetParent (Type parentType) {
1366 if (parentType == null)
1367 throw new ArgumentNullException ("parentType");
1368 check_not_created ();
1370 parent = parentType;
1371 // will just set the parent-related bits if called a second time
1372 setup_internal_class (this);
1374 internal int get_next_table_index (object obj, int table, bool inc) {
1375 return pmodule.get_next_table_index (obj, table, inc);
1381 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1383 if (created == null)
1384 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1386 return created.GetInterfaceMap (interfaceType);
1389 internal bool is_created {
1391 return created != null;
1395 private Exception not_supported ()
1397 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1400 private void check_not_created ()
1403 throw new InvalidOperationException ("Unable to change after type has been created.");
1406 private void check_created ()
1409 throw not_supported ();
1412 private void check_name (string argName, string name)
1415 throw new ArgumentNullException (argName);
1416 if (name.Length == 0)
1417 throw new ArgumentException ("Empty name is not legal", argName);
1418 if (name.IndexOf ((char)0) != -1)
1419 throw new ArgumentException ("Illegal name", argName);
1422 public override String ToString ()
1428 public override bool IsAssignableFrom (Type c)
1430 return base.IsAssignableFrom (c);
1437 public override bool IsSubclassOf (Type c)
1439 return base.IsSubclassOf (c);
1442 [MonoTODO ("arrays")]
1443 internal bool IsAssignableTo (Type c)
1448 if (c.IsInterface) {
1449 if (interfaces == null)
1451 foreach (Type t in interfaces)
1452 if (c.IsAssignableFrom (t))
1458 return c == typeof (object);
1460 return c.IsAssignableFrom (parent);
1463 #if NET_2_0 || BOOTSTRAP_NET_2_0
1464 public bool IsCreated () {
1468 public override Type[] GetGenericArguments ()
1470 if (generic_params != null)
1471 return generic_params;
1473 throw new InvalidOperationException ();
1476 public override Type GetGenericTypeDefinition ()
1478 create_generic_class ();
1480 return base.GetGenericTypeDefinition ();
1483 public override bool ContainsGenericParameters {
1485 return generic_params != null;
1489 public extern override bool IsGenericParameter {
1490 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1494 public override bool IsGenericTypeDefinition {
1496 return generic_params != null;
1500 public override bool IsGenericType {
1501 get { return IsGenericTypeDefinition; }
1504 public override int GenericParameterPosition {
1506 throw new NotImplementedException ();
1510 public override MethodBase DeclaringMethod {
1512 throw new NotImplementedException ();
1516 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
1518 setup_generic_class ();
1520 generic_params = new GenericTypeParameterBuilder [names.Length];
1521 for (int i = 0; i < names.Length; i++)
1522 generic_params [i] = new GenericTypeParameterBuilder (
1523 this, null, names [i], i);
1525 return generic_params;
1528 public static ConstructorInfo GetConstructor (Type instanciated, ConstructorInfo ctor)
1530 ConstructorInfo res = instanciated.GetConstructor (ctor);
1532 throw new System.Exception ("constructor not found");
1537 public static MethodInfo GetMethod (Type instanciated, MethodInfo meth)
1539 MethodInfo res = instanciated.GetMethod (meth);
1541 throw new System.Exception ("method not found");
1546 public static FieldInfo GetField (Type instanciated, FieldInfo fld)
1548 FieldInfo res = instanciated.GetField (fld);
1550 throw new System.Exception ("field not found");
1556 void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1558 throw new NotImplementedException ();
1561 void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1563 throw new NotImplementedException ();
1566 void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
1568 throw new NotImplementedException ();
1571 void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1573 throw new NotImplementedException ();