2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@gnome.org)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
13 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
15 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
16 // have fixed a remaining problem: not every AddXXXX was adding a
17 // fully qualified name.
19 // Now everyone registers a fully qualified name in the DeclSpace as
20 // being defined instead of the partial name.
22 // Downsides: we are slower than we need to be due to the excess
23 // copies and the names being registered this way.
25 // The reason for this is that we currently depend (on the corlib
26 // bootstrap for instance) that types are fully qualified, because
27 // we dump all the types in the namespace, and we should really have
28 // types inserted into the proper namespace, so we can only store the
29 // basenames in the defined_names array.
34 using System.Collections;
35 using System.Reflection;
36 using System.Reflection.Emit;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
40 namespace Mono.CSharp {
43 /// This is the base class for structs and classes.
45 public class TypeContainer : DeclSpace, IMemberContainer {
46 // Holds a list of classes and structures
49 // Holds the list of properties
52 // Holds the list of enumerations
55 // Holds the list of delegates
58 // Holds the list of constructors
59 ArrayList instance_constructors;
61 // Holds the list of fields
64 // Holds a list of fields that have initializers
65 ArrayList initialized_fields;
67 // Holds a list of static fields that have initializers
68 ArrayList initialized_static_fields;
70 // Holds the list of constants
76 // Holds order in which interfaces must be closed
77 ArrayList interface_order;
88 // Holds the operators
91 // The emit context for toplevel objects.
95 // Pointers to the default constructor and the default static constructor
97 Constructor default_constructor;
98 Constructor default_static_constructor;
101 // Whether we have seen a static constructor for this class or not
103 public bool UserDefinedStaticConstructor = false;
106 // Whether we have at least one non-static field
108 bool have_nonstatic_fields = false;
111 // This one is computed after we can distinguish interfaces
112 // from classes from the arraylist `type_bases'
114 string base_class_name;
115 public Type base_classs_type;
117 ArrayList type_bases;
119 bool members_defined;
120 bool members_defined_ok;
122 // The interfaces we implement.
124 Type[] base_inteface_types;
126 // The parent member container and our member cache
127 IMemberContainer parent_container;
128 MemberCache member_cache;
131 // The indexer name for this class
133 public string IndexerName;
135 public TypeContainer ():
136 this (null, null, "", null, new Location (-1)) {
139 public TypeContainer (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
140 : base (ns, parent, name, attrs, l)
142 types = new ArrayList ();
144 base_class_name = null;
147 public AdditionResult AddConstant (Const constant)
150 string basename = constant.Name;
151 string fullname = Name + "." + basename;
153 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
156 if (constants == null)
157 constants = new ArrayList ();
159 constants.Add (constant);
160 DefineName (fullname, constant);
162 return AdditionResult.Success;
165 public AdditionResult AddEnum (Mono.CSharp.Enum e)
169 if ((res = IsValid (e.Basename, e.Name)) != AdditionResult.Success)
173 enums = new ArrayList ();
176 DefineName (e.Name, e);
178 return AdditionResult.Success;
181 public AdditionResult AddClass (Class c)
184 string name = c.Basename;
186 if ((res = IsValid (name, c.Name)) != AdditionResult.Success)
189 DefineName (c.Name, c);
192 return AdditionResult.Success;
195 public AdditionResult AddStruct (Struct s)
198 string name = s.Basename;
200 if ((res = IsValid (name, s.Name)) != AdditionResult.Success)
203 DefineName (s.Name, s);
206 return AdditionResult.Success;
209 public AdditionResult AddDelegate (Delegate d)
212 string name = d.Basename;
214 if ((res = IsValid (name, d.Name)) != AdditionResult.Success)
217 if (delegates == null)
218 delegates = new ArrayList ();
220 DefineName (d.Name, d);
223 return AdditionResult.Success;
226 public AdditionResult AddMethod (Method method)
228 string basename = method.Name;
229 string fullname = Name + "." + basename;
231 Object value = defined_names [fullname];
233 if (value != null && (!(value is Method)))
234 return AdditionResult.NameExists;
236 if (basename == Basename)
237 return AdditionResult.EnclosingClash;
240 methods = new ArrayList ();
242 if (method.Name.IndexOf ('.') != -1)
243 methods.Insert (0, method);
245 methods.Add (method);
248 DefineName (fullname, method);
250 return AdditionResult.Success;
253 public AdditionResult AddConstructor (Constructor c)
255 if (c.Name != Basename)
256 return AdditionResult.NotAConstructor;
258 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
261 UserDefinedStaticConstructor = true;
262 if (default_static_constructor != null)
263 return AdditionResult.MethodExists;
265 default_static_constructor = c;
268 if (default_constructor != null)
269 return AdditionResult.MethodExists;
270 default_constructor = c;
273 if (instance_constructors == null)
274 instance_constructors = new ArrayList ();
276 instance_constructors.Add (c);
279 return AdditionResult.Success;
282 public AdditionResult AddInterface (Interface iface)
285 string name = iface.Basename;
287 if ((res = IsValid (name, iface.Name)) != AdditionResult.Success)
290 if (interfaces == null)
291 interfaces = new ArrayList ();
292 interfaces.Add (iface);
293 DefineName (iface.Name, iface);
295 return AdditionResult.Success;
298 public AdditionResult AddField (Field field)
301 string basename = field.Name;
302 string fullname = Name + "." + basename;
304 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
308 fields = new ArrayList ();
312 if (field.HasInitializer){
313 if ((field.ModFlags & Modifiers.STATIC) != 0){
314 if (initialized_static_fields == null)
315 initialized_static_fields = new ArrayList ();
317 initialized_static_fields.Add (field);
320 if (initialized_fields == null)
321 initialized_fields = new ArrayList ();
323 initialized_fields.Add (field);
327 if ((field.ModFlags & Modifiers.STATIC) == 0)
328 have_nonstatic_fields = true;
330 DefineName (fullname, field);
331 return AdditionResult.Success;
334 public AdditionResult AddProperty (Property prop)
338 if ((res = AddProperty (prop, prop.Name)) != AdditionResult.Success)
341 if (prop.Get != null) {
342 if ((res = AddProperty (prop, "get_" + prop.Name)) != AdditionResult.Success)
346 if (prop.Set != null) {
347 if ((res = AddProperty (prop, "set_" + prop.Name)) != AdditionResult.Success)
351 if (properties == null)
352 properties = new ArrayList ();
354 if (prop.Name.IndexOf ('.') != -1)
355 properties.Insert (0, prop);
357 properties.Add (prop);
359 return AdditionResult.Success;
362 AdditionResult AddProperty (Property prop, string basename)
365 string fullname = Name + "." + basename;
367 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
370 DefineName (fullname, prop);
372 return AdditionResult.Success;
375 public AdditionResult AddEvent (Event e)
378 string basename = e.Name;
379 string fullname = Name + "." + basename;
381 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
385 events = new ArrayList ();
388 DefineName (fullname, e);
390 return AdditionResult.Success;
393 public void AddIndexer (Indexer i)
395 if (indexers == null)
396 indexers = new ArrayList ();
398 if (i.ExplicitInterfaceName != null)
399 indexers.Insert (0, i);
404 public AdditionResult AddOperator (Operator op)
406 if (operators == null)
407 operators = new ArrayList ();
411 string basename = op.Name;
412 string fullname = Name + "." + basename;
413 if (!defined_names.Contains (fullname))
415 DefineName (fullname, op);
417 return AdditionResult.Success;
420 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
422 if (a.Type == TypeManager.default_member_type) {
423 if (Indexers != null) {
424 Report.Error (646, a.Location,
425 "Cannot specify the DefaultMember attribute on" +
426 " a type containing an indexer");
431 base.ApplyAttributeBuilder (a, cb);
434 public override AttributeTargets AttributeTargets {
436 throw new NotSupportedException ();
440 public void RegisterOrder (Interface iface)
442 if (interface_order == null)
443 interface_order = new ArrayList ();
445 interface_order.Add (iface);
448 public ArrayList Types {
454 public ArrayList Methods {
460 public ArrayList Constants {
466 public ArrayList Interfaces {
474 return base_class_name;
478 public ArrayList Bases {
488 public ArrayList Fields {
498 public ArrayList InstanceConstructors {
500 return instance_constructors;
504 public ArrayList Properties {
510 public ArrayList Events {
516 public ArrayList Enums {
522 public ArrayList Indexers {
528 public ArrayList Operators {
534 public ArrayList Delegates {
540 public virtual TypeAttributes TypeAttr {
542 return Modifiers.TypeAttr (ModFlags, this);
547 // Emits the instance field initializers
549 public bool EmitFieldInitializers (EmitContext ec)
552 Expression instance_expr;
555 fields = initialized_static_fields;
556 instance_expr = null;
558 fields = initialized_fields;
559 instance_expr = new This (Location.Null).Resolve (ec);
565 foreach (Field f in fields){
566 Expression e = f.GetInitializerExpression (ec);
570 Location l = f.Location;
571 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
572 fe.InstanceExpression = instance_expr;
573 ExpressionStatement a = new Assign (fe, e, l);
575 a = a.ResolveStatement (ec);
579 a.EmitStatement (ec);
586 // Defines the default constructors
588 void DefineDefaultConstructor (bool is_static)
592 // The default constructor is public
593 // If the class is abstract, the default constructor is protected
594 // The default static constructor is private
596 int mods = Modifiers.PUBLIC;
598 mods = Modifiers.STATIC | Modifiers.PRIVATE;
599 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
600 mods = Modifiers.PROTECTED;
602 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
603 new ConstructorBaseInitializer (
604 null, Parameters.EmptyReadOnlyParameters,
610 c.Block = new ToplevelBlock (null, Location);
614 public void ReportStructInitializedInstanceError ()
616 string n = TypeBuilder.FullName;
618 foreach (Field f in initialized_fields){
621 "`" + n + "." + f.Name + "': can not have " +
622 "instance field initializers in structs");
627 /// The pending methods that need to be implemented (interfaces or abstract methods)
629 public PendingImplementation Pending;
632 /// This function computes the Base class and also the
633 /// list of interfaces that the class or struct @c implements.
635 /// The return value is an array (might be null) of
636 /// interfaces implemented (as Types).
638 /// The @parent argument is set to the parent object or null
639 /// if this is `System.Object'.
641 TypeExpr [] GetClassBases (bool is_class, bool is_iface,
642 out TypeExpr parent, out bool error)
644 ArrayList bases = Bases;
650 if (is_class || is_iface)
653 parent = TypeManager.system_valuetype_expr;
657 if (RootContext.StdLib)
658 parent = TypeManager.system_object_expr;
659 else if (Name != "System.Object")
660 parent = TypeManager.system_object_expr;
663 // If we are compiling our runtime,
664 // and we are defining ValueType, then our
665 // parent is `System.Object'.
667 if (!RootContext.StdLib && Name == "System.ValueType")
668 parent = TypeManager.system_object_expr;
675 // Bases should be null if there are no bases at all
680 TypeExpr name = ResolveTypeExpr ((Expression) bases [0], false, Location);
691 parent = TypeManager.system_object_expr;
697 if (name.IsValueType)
698 detail = " (a class can not inherit from a struct/enum)";
700 Report.Error (509, "class `"+ Name +
701 "': Cannot inherit from sealed class `"+
702 name.Name + "'" + detail);
707 if (!parent.CanInheritFrom ()){
708 Report.Error (644, Location,
709 "`{0}' cannot inherit from special class `{1}'",
715 if (!parent.AsAccessible (this, ModFlags))
716 Report.Error (60, Location,
717 "Inconsistent accessibility: base class `" +
718 name.Name + "' is less accessible than class `" +
726 base_class_name = parent.Name;
728 TypeExpr [] ifaces = new TypeExpr [count-start];
730 for (i = start, j = 0; i < count; i++, j++){
731 Expression name = (Expression) bases [i];
732 TypeExpr resolved = ResolveTypeExpr (name, false, Location);
733 if (resolved == null)
736 bases [i] = resolved;
738 if (is_class == false && !resolved.IsInterface){
739 Report.Error (527, "In Struct `" + Name + "', type `"+
740 name +"' is not an interface");
745 if (resolved.IsClass) {
747 Report.Error (527, "In Class `" + Name + "', type `"+
748 name+"' is not an interface");
754 for (int x = 0; x < j; x++) {
755 if (resolved.Equals (ifaces [x])) {
756 Report.Error (528, "`" + name + "' is already listed in interface list");
763 !resolved.AsAccessible (Parent, ModFlags))
764 Report.Error (61, Location,
765 "Inconsistent accessibility: base interface `" +
766 name + "' is less accessible than interface `" +
769 ifaces [j] = resolved;
772 return TypeManager.ExpandInterfaces (ifaces);
778 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
780 public override TypeBuilder DefineType ()
783 bool is_class, is_iface;
785 if (TypeBuilder != null)
792 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
799 if (this is Interface) {
810 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
812 ifaces = GetClassBases (is_class, is_iface, out parent, out error);
817 if (!is_class && TypeManager.value_type == null)
818 throw new Exception ();
820 TypeAttributes type_attributes = TypeAttr;
823 base_classs_type = parent.ResolveType (ec);
826 if (TypeManager.NamespaceClash (Name, Location)) {
831 ModuleBuilder builder = CodeGen.Module.Builder;
832 TypeBuilder = builder.DefineType (
833 Name, type_attributes, base_classs_type, null);
836 TypeBuilder builder = Parent.DefineType ();
840 TypeBuilder = builder.DefineNestedType (
841 Basename, type_attributes, base_classs_type, null);
845 // Structs with no fields need to have at least one byte.
846 // The right thing would be to set the PackingSize in a DefineType
847 // but there are no functions that allow interfaces *and* the size to
851 if (!is_class && !is_iface && !have_nonstatic_fields){
852 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
853 FieldAttributes.Private);
856 // add interfaces that were not added at type creation
857 if (ifaces != null) {
858 base_inteface_types = new Type[ifaces.Length];
859 for (int i = 0; i < ifaces.Length; ++i) {
860 Type itype = ifaces [i].ResolveType (ec);
861 TypeBuilder.AddInterfaceImplementation (itype);
862 base_inteface_types [i] = itype;
867 // Finish the setup for the EmitContext
869 ec.ContainerType = TypeBuilder;
871 TypeManager.AddUserType (Name, TypeBuilder, this, ifaces);
873 if ((parent != null) && parent.IsAttribute) {
874 RootContext.RegisterAttribute (this);
876 RootContext.RegisterOrder (this);
878 if (Interfaces != null) {
879 foreach (Interface iface in Interfaces)
880 if (iface.DefineType () == null) {
887 foreach (TypeContainer tc in Types)
888 if (tc.DefineType () == null) {
894 if (Delegates != null) {
895 foreach (Delegate d in Delegates)
896 if (d.DefineType () == null) {
903 foreach (Enum en in Enums)
904 if (en.DefineType () == null) {
916 /// Defines the MemberCore objects that are in the `list' Arraylist
918 /// The `defined_names' array contains a list of members defined in
921 static ArrayList remove_list = new ArrayList ();
922 void DefineMembers (ArrayList list, MemberInfo [] defined_names)
926 remove_list.Clear ();
928 foreach (MemberCore mc in list){
930 if (defined_names != null)
931 idx = Array.BinarySearch (defined_names, mc.Name, mif_compare);
936 if (RootContext.WarningLevel >= 4){
937 if ((mc.ModFlags & Modifiers.NEW) != 0)
938 Warning_KeywordNewNotRequired (mc.Location, mc);
940 } else if (mc is MethodCore)
941 ((MethodCore) mc).OverridesSomething = true;
943 if (!mc.Define (this)){
944 remove_list.Add (mc);
951 MemberInfo match = defined_names [idx];
953 if (match is PropertyInfo && ((mc.ModFlags & Modifiers.OVERRIDE) != 0))
957 // If we are both methods, let the method resolution emit warnings
959 if (match is MethodBase && mc is MethodCore)
962 if ((mc.ModFlags & Modifiers.NEW) == 0) {
964 if (!(match is EventInfo)) {
965 Error_EventCanOnlyOverrideEvent (mc.Location, defined_names [idx]);
969 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
973 Warning_KeywordNewRequired (mc.Location, defined_names [idx]);
977 foreach (object o in remove_list)
980 remove_list.Clear ();
984 // Defines the indexers, and also verifies that the IndexerNameAttribute in the
985 // class is consistent. Either it is `Item' or it is the name defined by all the
986 // indexers with the `IndexerName' attribute.
988 // Turns out that the IndexerNameAttribute is applied to each indexer,
989 // but it is never emitted, instead a DefaultMember attribute is attached
992 void DefineIndexers ()
994 string class_indexer_name = null;
997 // If there's both an explicit and an implicit interface implementation, the
998 // explicit one actually implements the interface while the other one is just
999 // a normal indexer. See bug #37714.
1002 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1003 bool seen_normal_indexers = false;
1005 foreach (Indexer i in Indexers) {
1010 name = i.IndexerName;
1012 if (i.InterfaceType != null) {
1013 if (seen_normal_indexers)
1014 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1018 seen_normal_indexers = true;
1020 if (class_indexer_name == null)
1021 class_indexer_name = name;
1022 else if (name != class_indexer_name)
1023 Report.Error (668, i.Location, "Two indexers have different names, " +
1024 " you should use the same name for all your indexers");
1027 if (seen_normal_indexers && class_indexer_name == null)
1028 class_indexer_name = "Item";
1029 IndexerName = class_indexer_name;
1032 static void Error_KeywordNotAllowed (Location loc)
1034 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1038 /// Populates our TypeBuilder with fields and methods
1040 public override bool DefineMembers (TypeContainer container)
1042 if (members_defined)
1043 return members_defined_ok;
1045 members_defined_ok = DoDefineMembers ();
1046 members_defined = true;
1048 return members_defined_ok;
1051 bool DoDefineMembers ()
1053 MemberInfo [] defined_names = null;
1056 // We need to be able to use the member cache while we are checking/defining
1059 if (TypeBuilder.BaseType != null)
1060 parent_container = TypeManager.LookupMemberContainer (TypeBuilder.BaseType);
1063 if (interface_order != null){
1064 foreach (Interface iface in interface_order)
1065 if ((iface.ModFlags & Modifiers.NEW) == 0)
1066 iface.DefineMembers (this);
1068 Error_KeywordNotAllowed (iface.Location);
1071 if (RootContext.WarningLevel > 1){
1075 // This code throws an exception in the comparer
1076 // I guess the string is not an object?
1078 ptype = TypeBuilder.BaseType;
1080 defined_names = (MemberInfo []) FindMembers (
1081 ptype, MemberTypes.All & ~MemberTypes.Constructor,
1082 BindingFlags.Public | BindingFlags.Instance |
1083 BindingFlags.Static, null, null);
1085 Array.Sort (defined_names, mif_compare);
1089 Class pclass = Parent as Class;
1090 if (pclass != null) {
1091 string pname = null;
1093 Type t = pclass.TypeBuilder.BaseType;
1094 while ((t != null) && (ptype == null)) {
1095 pname = t.FullName + "." + Basename;
1096 ptype = RootContext.LookupType (this, pname, true, Location.Null);
1100 if ((ModFlags & Modifiers.NEW) != 0) {
1102 Report.Warning (109, Location, "The member '" + Name + "' does not hide an " +
1103 "inherited member. The keyword new is not required.");
1104 } else if (ptype != null) {
1105 Report.Warning (108, Location, "The keyword new is required on `" +
1106 Name + "' because it hides inherited member '" +
1109 } else if ((ModFlags & Modifiers.NEW) != 0)
1110 Error_KeywordNotAllowed (Location);
1112 if (constants != null)
1113 DefineMembers (constants, defined_names);
1116 DefineMembers (fields, defined_names);
1119 if (instance_constructors == null){
1120 if (default_constructor == null)
1121 DefineDefaultConstructor (false);
1124 if (initialized_static_fields != null &&
1125 default_static_constructor == null)
1126 DefineDefaultConstructor (true);
1129 if (this is Struct){
1131 // Structs can not have initialized instance
1134 if (initialized_static_fields != null &&
1135 default_static_constructor == null)
1136 DefineDefaultConstructor (true);
1138 if (initialized_fields != null)
1139 ReportStructInitializedInstanceError ();
1142 if (!(this is Interface))
1143 Pending = PendingImplementation.GetPendingImplementations (this);
1146 // Constructors are not in the defined_names array
1148 if (instance_constructors != null)
1149 DefineMembers (instance_constructors, null);
1151 if (default_static_constructor != null)
1152 default_static_constructor.Define (this);
1154 if (methods != null)
1155 DefineMembers (methods, defined_names);
1157 if (properties != null)
1158 DefineMembers (properties, defined_names);
1161 DefineMembers (events, defined_names);
1163 if (indexers != null)
1166 if (operators != null){
1167 DefineMembers (operators, null);
1169 CheckPairedOperators ();
1173 DefineMembers (enums, defined_names);
1175 if (delegates != null)
1176 DefineMembers (delegates, defined_names);
1179 member_cache = new MemberCache (this);
1186 public override bool Define (TypeContainer container)
1188 if (interface_order != null){
1189 foreach (Interface iface in interface_order)
1190 if ((iface.ModFlags & Modifiers.NEW) == 0)
1191 iface.Define (this);
1198 /// This function is based by a delegate to the FindMembers routine
1200 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1206 /// This filter is used by FindMembers, and we just keep
1207 /// a global for the filter to `AlwaysAccept'
1209 static MemberFilter accepting_filter;
1213 /// A member comparission method based on name only
1215 static IComparer mif_compare;
1217 static TypeContainer ()
1219 accepting_filter = new MemberFilter (AlwaysAccept);
1220 mif_compare = new MemberInfoCompare ();
1223 public MethodInfo[] GetMethods ()
1225 ArrayList members = new ArrayList ();
1227 DefineMembers (null);
1229 if (methods != null) {
1230 int len = methods.Count;
1231 for (int i = 0; i < len; i++) {
1232 Method m = (Method) methods [i];
1234 members.Add (m.MethodBuilder);
1238 if (operators != null) {
1239 int len = operators.Count;
1240 for (int i = 0; i < len; i++) {
1241 Operator o = (Operator) operators [i];
1243 members.Add (o.OperatorMethodBuilder);
1247 if (properties != null) {
1248 int len = properties.Count;
1249 for (int i = 0; i < len; i++) {
1250 Property p = (Property) properties [i];
1252 if (p.GetBuilder != null)
1253 members.Add (p.GetBuilder);
1254 if (p.SetBuilder != null)
1255 members.Add (p.SetBuilder);
1259 if (indexers != null) {
1260 int len = indexers.Count;
1261 for (int i = 0; i < len; i++) {
1262 Indexer ix = (Indexer) indexers [i];
1264 if (ix.GetBuilder != null)
1265 members.Add (ix.GetBuilder);
1266 if (ix.SetBuilder != null)
1267 members.Add (ix.SetBuilder);
1271 if (events != null) {
1272 int len = events.Count;
1273 for (int i = 0; i < len; i++) {
1274 Event e = (Event) events [i];
1276 if (e.AddBuilder != null)
1277 members.Add (e.AddBuilder);
1278 if (e.RemoveBuilder != null)
1279 members.Add (e.RemoveBuilder);
1283 MethodInfo[] retMethods = new MethodInfo [members.Count];
1284 members.CopyTo (retMethods, 0);
1289 /// This method returns the members of this type just like Type.FindMembers would
1290 /// Only, we need to use this for types which are _being_ defined because MS'
1291 /// implementation can't take care of that.
1294 // FIXME: return an empty static array instead of null, that cleans up
1295 // some code and is consistent with some coding conventions I just found
1299 // Notice that in various cases we check if our field is non-null,
1300 // something that would normally mean that there was a bug elsewhere.
1302 // The problem happens while we are defining p-invoke methods, as those
1303 // will trigger a FindMembers, but this happens before things are defined
1305 // Since the whole process is a no-op, it is fine to check for null here.
1307 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1308 MemberFilter filter, object criteria)
1310 ArrayList members = null;
1313 if ((bf & BindingFlags.Public) != 0)
1314 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1316 if ((bf & BindingFlags.NonPublic) != 0)
1317 modflags |= Modifiers.PRIVATE;
1319 int static_mask = 0, static_flags = 0;
1320 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1321 case BindingFlags.Static:
1322 static_mask = static_flags = Modifiers.STATIC;
1325 case BindingFlags.Instance:
1326 static_mask = Modifiers.STATIC;
1331 static_mask = static_flags = 0;
1335 Timer.StartTimer (TimerType.TcFindMembers);
1338 filter = accepting_filter;
1340 if ((mt & MemberTypes.Field) != 0) {
1341 if (fields != null) {
1342 int len = fields.Count;
1343 for (int i = 0; i < len; i++) {
1344 Field f = (Field) fields [i];
1346 if ((f.ModFlags & modflags) == 0)
1348 if ((f.ModFlags & static_mask) != static_flags)
1351 FieldBuilder fb = f.FieldBuilder;
1352 if (fb != null && filter (fb, criteria) == true) {
1353 if (members == null)
1354 members = new ArrayList ();
1361 if (constants != null) {
1362 int len = constants.Count;
1363 for (int i = 0; i < len; i++) {
1364 Const con = (Const) constants [i];
1366 if ((con.ModFlags & modflags) == 0)
1368 if ((con.ModFlags & static_mask) != static_flags)
1371 FieldBuilder fb = con.FieldBuilder;
1372 if (fb != null && filter (fb, criteria) == true) {
1373 if (members == null)
1374 members = new ArrayList ();
1382 if ((mt & MemberTypes.Method) != 0) {
1383 if (methods != null) {
1384 int len = methods.Count;
1385 for (int i = 0; i < len; i++) {
1386 Method m = (Method) methods [i];
1388 if ((m.ModFlags & modflags) == 0)
1390 if ((m.ModFlags & static_mask) != static_flags)
1393 MethodBuilder mb = m.MethodBuilder;
1395 if (mb != null && filter (mb, criteria) == true) {
1396 if (members == null)
1397 members = new ArrayList ();
1404 if (operators != null) {
1405 int len = operators.Count;
1406 for (int i = 0; i < len; i++) {
1407 Operator o = (Operator) operators [i];
1409 if ((o.ModFlags & modflags) == 0)
1411 if ((o.ModFlags & static_mask) != static_flags)
1414 MethodBuilder ob = o.OperatorMethodBuilder;
1415 if (ob != null && filter (ob, criteria) == true) {
1416 if (members == null)
1417 members = new ArrayList ();
1424 if (properties != null) {
1425 int len = properties.Count;
1426 for (int i = 0; i < len; i++) {
1427 Property p = (Property) properties [i];
1429 if ((p.ModFlags & modflags) == 0)
1431 if ((p.ModFlags & static_mask) != static_flags)
1437 if (b != null && filter (b, criteria) == true) {
1438 if (members == null)
1439 members = new ArrayList ();
1445 if (b != null && filter (b, criteria) == true) {
1446 if (members == null)
1447 members = new ArrayList ();
1454 if (indexers != null) {
1455 int len = indexers.Count;
1456 for (int i = 0; i < len; i++) {
1457 Indexer ix = (Indexer) indexers [i];
1459 if ((ix.ModFlags & modflags) == 0)
1461 if ((ix.ModFlags & static_mask) != static_flags)
1467 if (b != null && filter (b, criteria) == true) {
1468 if (members == null)
1469 members = new ArrayList ();
1475 if (b != null && filter (b, criteria) == true) {
1476 if (members == null)
1477 members = new ArrayList ();
1485 if ((mt & MemberTypes.Event) != 0) {
1486 if (events != null) {
1487 int len = events.Count;
1488 for (int i = 0; i < len; i++) {
1489 Event e = (Event) events [i];
1491 if ((e.ModFlags & modflags) == 0)
1493 if ((e.ModFlags & static_mask) != static_flags)
1496 MemberInfo eb = e.EventBuilder;
1497 if (eb != null && filter (eb, criteria) == true) {
1498 if (members == null)
1499 members = new ArrayList ();
1501 members.Add (e.EventBuilder);
1507 if ((mt & MemberTypes.Property) != 0){
1508 if (properties != null) {
1509 int len = properties.Count;
1510 for (int i = 0; i < len; i++) {
1511 Property p = (Property) properties [i];
1513 if ((p.ModFlags & modflags) == 0)
1515 if ((p.ModFlags & static_mask) != static_flags)
1518 MemberInfo pb = p.PropertyBuilder;
1519 if (pb != null && filter (pb, criteria) == true) {
1520 if (members == null)
1521 members = new ArrayList ();
1523 members.Add (p.PropertyBuilder);
1528 if (indexers != null) {
1529 int len = indexers.Count;
1530 for (int i = 0; i < len; i++) {
1531 Indexer ix = (Indexer) indexers [i];
1533 if ((ix.ModFlags & modflags) == 0)
1535 if ((ix.ModFlags & static_mask) != static_flags)
1538 MemberInfo ib = ix.PropertyBuilder;
1539 if (ib != null && filter (ib, criteria) == true) {
1540 if (members == null)
1541 members = new ArrayList ();
1543 members.Add (ix.PropertyBuilder);
1549 if ((mt & MemberTypes.NestedType) != 0) {
1550 if (types != null) {
1551 int len = types.Count;
1552 for (int i = 0; i < len; i++) {
1553 TypeContainer t = (TypeContainer) types [i];
1555 if ((t.ModFlags & modflags) == 0)
1558 TypeBuilder tb = t.TypeBuilder;
1559 if (tb != null && (filter (tb, criteria) == true)) {
1560 if (members == null)
1561 members = new ArrayList ();
1568 if (enums != null) {
1569 int len = enums.Count;
1570 for (int i = 0; i < len; i++) {
1571 Enum en = (Enum) enums [i];
1573 if ((en.ModFlags & modflags) == 0)
1576 TypeBuilder tb = en.TypeBuilder;
1577 if (tb != null && (filter (tb, criteria) == true)) {
1578 if (members == null)
1579 members = new ArrayList ();
1586 if (delegates != null) {
1587 int len = delegates.Count;
1588 for (int i = 0; i < len; i++) {
1589 Delegate d = (Delegate) delegates [i];
1591 if ((d.ModFlags & modflags) == 0)
1594 TypeBuilder tb = d.TypeBuilder;
1595 if (tb != null && (filter (tb, criteria) == true)) {
1596 if (members == null)
1597 members = new ArrayList ();
1604 if (interfaces != null) {
1605 int len = interfaces.Count;
1606 for (int i = 0; i < len; i++) {
1607 Interface iface = (Interface) interfaces [i];
1609 if ((iface.ModFlags & modflags) == 0)
1612 TypeBuilder tb = iface.TypeBuilder;
1613 if (tb != null && (filter (tb, criteria) == true)) {
1614 if (members == null)
1615 members = new ArrayList ();
1623 if ((mt & MemberTypes.Constructor) != 0){
1624 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1625 int len = instance_constructors.Count;
1626 for (int i = 0; i < len; i++) {
1627 Constructor c = (Constructor) instance_constructors [i];
1629 ConstructorBuilder cb = c.ConstructorBuilder;
1630 if (cb != null && filter (cb, criteria) == true) {
1631 if (members == null)
1632 members = new ArrayList ();
1639 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1640 ConstructorBuilder cb =
1641 default_static_constructor.ConstructorBuilder;
1643 if (cb != null && filter (cb, criteria) == true) {
1644 if (members == null)
1645 members = new ArrayList ();
1653 // Lookup members in parent if requested.
1655 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1656 if (TypeBuilder.BaseType != null) {
1657 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1658 if (list.Count > 0) {
1659 if (members == null)
1660 members = new ArrayList ();
1662 members.AddRange (list);
1665 if (base_inteface_types != null) {
1666 foreach (Type base_type in base_inteface_types) {
1667 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1669 if (list.Count > 0) {
1670 if (members == null)
1671 members = new ArrayList ();
1672 members.AddRange (list);
1678 Timer.StopTimer (TimerType.TcFindMembers);
1680 if (members == null)
1681 return MemberList.Empty;
1683 return new MemberList (members);
1686 public override MemberCache MemberCache {
1688 return member_cache;
1692 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1693 MemberFilter filter, object criteria)
1695 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1698 return ds.FindMembers (mt, bf, filter, criteria);
1700 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1705 // FindMethods will look for methods not only in the type `t', but in
1706 // any interfaces implemented by the type.
1708 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1709 MemberFilter filter, object criteria)
1715 /// Emits the values for the constants
1717 public void EmitConstants ()
1719 if (constants != null)
1720 foreach (Const con in constants)
1725 protected virtual void VerifyMembers (EmitContext ec)
1728 // Check for internal or private fields that were never assigned
1730 if (RootContext.WarningLevel >= 3) {
1731 if (fields != null){
1732 foreach (Field f in fields) {
1733 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1736 if ((f.status & Field.Status.USED) == 0){
1738 169, f.Location, "Private field " +
1739 MakeName (f.Name) + " is never used");
1744 // Only report 649 on level 4
1746 if (RootContext.WarningLevel < 4)
1749 if ((f.status & Field.Status.ASSIGNED) != 0)
1754 "Field " + MakeName (f.Name) + " is never assigned " +
1755 " to and will always have its default value");
1759 if (events != null){
1760 foreach (Event e in events){
1762 Report.Warning (67, "The event " + MakeName (e.Name) + " is never used");
1769 /// Emits the code, this step is performed after all
1770 /// the types, enumerations, constructors
1774 if (OptAttributes != null)
1775 OptAttributes.Emit (ec, this);
1779 if (instance_constructors != null) {
1780 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && IsClsCompliaceRequired (this)) {
1781 bool has_compliant_args = false;
1783 foreach (Constructor c in instance_constructors) {
1786 if (has_compliant_args)
1789 has_compliant_args = c.HasCompliantArgs;
1791 if (!has_compliant_args)
1792 Report.Error_T (3015, Location, GetSignatureForError ());
1794 foreach (Constructor c in instance_constructors)
1799 if (default_static_constructor != null)
1800 default_static_constructor.Emit (this);
1802 if (methods != null)
1803 foreach (Method m in methods)
1806 if (operators != null)
1807 foreach (Operator o in operators)
1810 if (properties != null)
1811 foreach (Property p in properties)
1814 if (indexers != null){
1815 foreach (Indexer ix in indexers)
1817 if (IndexerName != null) {
1818 CustomAttributeBuilder cb = EmitDefaultMemberAttr ();
1819 TypeBuilder.SetCustomAttribute (cb);
1824 foreach (Field f in fields)
1827 if (events != null){
1828 foreach (Event e in Events)
1832 if (delegates != null) {
1833 foreach (Delegate d in Delegates) {
1838 if (Pending != null)
1839 if (Pending.VerifyPendingMethods ())
1844 // if (types != null)
1845 // foreach (TypeContainer tc in types)
1849 CustomAttributeBuilder EmitDefaultMemberAttr ()
1851 EmitContext ec = new EmitContext (this, Location, null, null, ModFlags);
1853 Expression ml = Expression.MemberLookup (ec, TypeManager.default_member_type,
1854 ".ctor", MemberTypes.Constructor,
1855 BindingFlags.Public | BindingFlags.Instance,
1858 MethodGroupExpr mg = (MethodGroupExpr) ml;
1860 MethodBase constructor = mg.Methods [0];
1862 string [] vals = { IndexerName };
1864 CustomAttributeBuilder cb = null;
1866 cb = new CustomAttributeBuilder ((ConstructorInfo) constructor, vals);
1868 Report.Warning (-100, "Can not set the indexer default member attribute");
1874 public override void CloseType ()
1876 if ((caching_flags & Flags.CloseTypeCreated) != 0)
1880 caching_flags |= Flags.CloseTypeCreated;
1881 TypeBuilder.CreateType ();
1882 } catch (TypeLoadException){
1884 // This is fine, the code still created the type
1886 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1887 // Console.WriteLine (e.Message);
1889 Console.WriteLine ("In type: " + Name);
1894 foreach (Enum en in Enums)
1897 if (interface_order != null){
1898 foreach (Interface iface in interface_order)
1903 foreach (TypeContainer tc in Types)
1907 foreach (TypeContainer tc in Types)
1908 if (!(tc is Struct))
1912 if (Delegates != null)
1913 foreach (Delegate d in Delegates)
1921 initialized_fields = null;
1922 initialized_static_fields = null;
1925 interface_order = null;
1931 default_constructor = null;
1932 default_static_constructor = null;
1934 OptAttributes = null;
1936 parent_container = null;
1937 member_cache = null;
1940 public string MakeName (string n)
1942 return "`" + Name + "." + n + "'";
1945 public void Warning_KeywordNewRequired (Location l, MemberInfo mi)
1948 108, l, "The keyword new is required on " +
1949 MakeName (mi.Name) + " because it hides `" +
1950 mi.ReflectedType.Name + "." + mi.Name + "'");
1953 public void Warning_KeywordNewNotRequired (Location l, MemberCore mc)
1956 109, l, "The member " + MakeName (mc.Name) + " does not hide an " +
1957 "inherited member, the keyword new is not required");
1960 public void Error_EventCanOnlyOverrideEvent (Location l, MemberInfo mi)
1963 72, l, MakeName (mi.Name) + " : cannot override; `" +
1964 mi.ReflectedType.Name + "." + mi.Name + "' is not an event");
1967 public static int CheckMember (string name, MemberInfo mi, int ModFlags)
1973 // Performs the validation on a Method's modifiers (properties have
1974 // the same properties).
1976 public bool MethodModifiersValid (int flags, string n, Location loc)
1978 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1979 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1980 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1984 // At most one of static, virtual or override
1986 if ((flags & Modifiers.STATIC) != 0){
1987 if ((flags & vao) != 0){
1989 112, loc, "static method " + MakeName (n) + "can not be marked " +
1990 "as virtual, abstract or override");
1995 if (this is Struct){
1996 if ((flags & va) != 0){
1997 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
2002 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2004 113, loc, MakeName (n) +
2005 " marked as override cannot be marked as new or virtual");
2010 // If the declaration includes the abstract modifier, then the
2011 // declaration does not include static, virtual or extern
2013 if ((flags & Modifiers.ABSTRACT) != 0){
2014 if ((flags & Modifiers.EXTERN) != 0){
2016 180, loc, MakeName (n) + " can not be both abstract and extern");
2020 if ((flags & Modifiers.VIRTUAL) != 0){
2022 503, loc, MakeName (n) + " can not be both abstract and virtual");
2026 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2028 513, loc, MakeName (n) +
2029 " is abstract but its container class is not");
2035 if ((flags & Modifiers.PRIVATE) != 0){
2036 if ((flags & vao) != 0){
2038 621, loc, MakeName (n) +
2039 " virtual or abstract members can not be private");
2044 if ((flags & Modifiers.SEALED) != 0){
2045 if ((flags & Modifiers.OVERRIDE) == 0){
2047 238, loc, MakeName (n) +
2048 " cannot be sealed because it is not an override");
2056 Hashtable builder_and_args;
2058 public bool RegisterMethod (MethodBuilder mb, InternalParameters ip, Type [] args)
2060 if (builder_and_args == null)
2061 builder_and_args = new Hashtable ();
2065 protected override bool VerifyClsCompliance (DeclSpace ds)
2067 if (!base.VerifyClsCompliance (ds))
2070 // parent_container is null for System.Object
2071 if (parent_container != null && !AttributeTester.IsClsCompliant (parent_container.Type)) {
2072 Report.Error_T (3009, Location, GetSignatureForError (), TypeManager.CSharpName (parent_container.Type));
2079 /// Performs checks for an explicit interface implementation. First it
2080 /// checks whether the `interface_type' is a base inteface implementation.
2081 /// Then it checks whether `name' exists in the interface type.
2083 public bool VerifyImplements (Type interface_type, string full, string name, Location loc)
2087 if (ifaces != null){
2088 foreach (TypeExpr t in ifaces){
2089 if (t.Type == interface_type){
2097 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
2104 protected override void VerifyObsoleteAttribute()
2106 CheckUsageOfObsoleteAttribute (base_classs_type);
2111 foreach (TypeExpr expr in ifaces) {
2112 CheckUsageOfObsoleteAttribute (expr.Type);
2121 string IMemberContainer.Name {
2127 Type IMemberContainer.Type {
2133 IMemberContainer IMemberContainer.Parent {
2135 return parent_container;
2139 MemberCache IMemberContainer.MemberCache {
2141 return member_cache;
2145 bool IMemberContainer.IsInterface {
2147 return this is Interface;
2151 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2153 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2157 // Operator pair checking
2160 class OperatorEntry {
2162 public Type ret_type;
2163 public Type type1, type2;
2165 public Operator.OpType ot;
2167 public OperatorEntry (int f, Operator o)
2171 ret_type = o.OperatorMethod.GetReturnType ();
2172 Type [] pt = o.OperatorMethod.ParameterTypes;
2176 ot = o.OperatorType;
2179 public override int GetHashCode ()
2181 return ret_type.GetHashCode ();
2184 public override bool Equals (object o)
2186 OperatorEntry other = (OperatorEntry) o;
2188 if (other.ret_type != ret_type)
2190 if (other.type1 != type1)
2192 if (other.type2 != type2)
2199 // Checks that some operators come in pairs:
2205 // They are matched based on the return type and the argument types
2207 void CheckPairedOperators ()
2209 Hashtable pairs = new Hashtable (null, null);
2210 Operator true_op = null;
2211 Operator false_op = null;
2212 bool has_equality_or_inequality = false;
2214 // Register all the operators we care about.
2215 foreach (Operator op in operators){
2218 switch (op.OperatorType){
2219 case Operator.OpType.Equality:
2221 has_equality_or_inequality = true;
2223 case Operator.OpType.Inequality:
2225 has_equality_or_inequality = true;
2228 case Operator.OpType.True:
2231 case Operator.OpType.False:
2235 case Operator.OpType.GreaterThan:
2237 case Operator.OpType.LessThan:
2240 case Operator.OpType.GreaterThanOrEqual:
2242 case Operator.OpType.LessThanOrEqual:
2248 OperatorEntry oe = new OperatorEntry (reg, op);
2250 object o = pairs [oe];
2254 oe = (OperatorEntry) o;
2259 if (true_op != null){
2260 if (false_op == null)
2261 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
2262 } else if (false_op != null)
2263 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
2266 // Look for the mistakes.
2268 foreach (DictionaryEntry de in pairs){
2269 OperatorEntry oe = (OperatorEntry) de.Key;
2276 case Operator.OpType.Equality:
2279 case Operator.OpType.Inequality:
2282 case Operator.OpType.GreaterThan:
2285 case Operator.OpType.LessThan:
2288 case Operator.OpType.GreaterThanOrEqual:
2291 case Operator.OpType.LessThanOrEqual:
2295 Report.Error (216, oe.op.Location,
2296 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
2299 if ((has_equality_or_inequality) && (RootContext.WarningLevel >= 2)) {
2300 MethodSignature equals_ms = new MethodSignature (
2301 "Equals", TypeManager.bool_type, new Type [] { TypeManager.object_type });
2302 MethodSignature hash_ms = new MethodSignature (
2303 "GetHashCode", TypeManager.int32_type, new Type [0]);
2305 MemberList equals_ml = FindMembers (MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance |
2306 BindingFlags.DeclaredOnly, MethodSignature.method_signature_filter,
2308 MemberList hash_ml = FindMembers (MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance |
2309 BindingFlags.DeclaredOnly, MethodSignature.method_signature_filter,
2312 bool equals_ok = false;
2313 if ((equals_ml != null) && (equals_ml.Count == 1))
2314 equals_ok = equals_ml [0].DeclaringType == TypeBuilder;
2315 bool hash_ok = false;
2316 if ((hash_ml != null) && (hash_ml.Count == 1))
2317 hash_ok = hash_ml [0].DeclaringType == TypeBuilder;
2320 Report.Warning (660, Location, "`" + Name + "' defines operator == or operator != but does " +
2321 "not override Object.Equals (object o)");
2323 Report.Warning (661, Location, "`" + Name + "' defines operator == or operator != but does " +
2324 "not override Object.GetHashCode ()");
2331 public class ClassOrStruct : TypeContainer {
2332 bool hasExplicitLayout = false;
2333 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
2334 : base (ns, parent, name, attrs, l)
2338 protected override void VerifyMembers (EmitContext ec)
2340 if (Fields != null) {
2341 foreach (Field f in Fields) {
2342 if ((f.ModFlags & Modifiers.STATIC) != 0)
2344 if (hasExplicitLayout) {
2345 if (f.OptAttributes == null
2346 || !f.OptAttributes.Contains (TypeManager.field_offset_attribute_type, ec)) {
2347 Report.Error (625, f.Location,
2348 "Instance field of type marked with"
2349 + " StructLayout(LayoutKind.Explicit) must have a"
2350 + " FieldOffset attribute.");
2354 if (f.OptAttributes != null
2355 && f.OptAttributes.Contains (TypeManager.field_offset_attribute_type, ec)) {
2356 Report.Error (636, f.Location,
2357 "The FieldOffset attribute can only be placed on members of "
2358 + "types marked with the StructLayout(LayoutKind.Explicit)");
2363 base.VerifyMembers (ec);
2366 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2368 if (a.Type == TypeManager.struct_layout_attribute_type
2369 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2370 hasExplicitLayout = true;
2372 base.ApplyAttributeBuilder (a, cb);
2376 public class Class : ClassOrStruct {
2378 // Modifiers allowed in a class declaration
2380 public const int AllowedModifiers =
2383 Modifiers.PROTECTED |
2384 Modifiers.INTERNAL |
2386 Modifiers.ABSTRACT |
2391 // Information in the case we are an attribute type
2392 AttributeUsageAttribute attribute_usage;
2394 public Class (NamespaceEntry ns, TypeContainer parent, string name, int mod,
2395 Attributes attrs, Location l)
2396 : base (ns, parent, name, attrs, l)
2400 if (parent.Parent == null)
2401 accmods = Modifiers.INTERNAL;
2403 accmods = Modifiers.PRIVATE;
2405 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2406 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2409 public override AttributeTargets AttributeTargets {
2411 return AttributeTargets.Class;
2415 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2417 if (a.UsageAttribute != null)
2418 attribute_usage = a.UsageAttribute;
2420 base.ApplyAttributeBuilder (a, cb);
2423 public AttributeUsageAttribute AttributeUsage {
2425 return attribute_usage;
2430 // FIXME: How do we deal with the user specifying a different
2433 public override TypeAttributes TypeAttr {
2435 return base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2440 public class Struct : ClassOrStruct {
2442 // Modifiers allowed in a struct declaration
2444 public const int AllowedModifiers =
2447 Modifiers.PROTECTED |
2448 Modifiers.INTERNAL |
2452 public Struct (NamespaceEntry ns, TypeContainer parent, string name, int mod, Attributes attrs, Location l)
2453 : base (ns, parent, name, attrs, l)
2457 if (parent.Parent == null)
2458 accmods = Modifiers.INTERNAL;
2460 accmods = Modifiers.PRIVATE;
2462 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2464 this.ModFlags |= Modifiers.SEALED;
2467 public override AttributeTargets AttributeTargets {
2469 return AttributeTargets.Struct;
2475 // FIXME: Allow the user to specify a different set of attributes
2476 // in some cases (Sealed for example is mandatory for a class,
2477 // but what SequentialLayout can be changed
2479 public override TypeAttributes TypeAttr {
2481 return base.TypeAttr |
2482 TypeAttributes.SequentialLayout |
2483 TypeAttributes.Sealed |
2484 TypeAttributes.BeforeFieldInit;
2492 public class Interface : TypeContainer, IMemberContainer {
2494 /// Modifiers allowed in a class declaration
2496 public const int AllowedModifiers =
2499 Modifiers.PROTECTED |
2500 Modifiers.INTERNAL |
2504 public Interface (NamespaceEntry ns, TypeContainer parent, string name, int mod,
2505 Attributes attrs, Location l)
2506 : base (ns, parent, name, attrs, l)
2510 if (parent.Parent == null)
2511 accmods = Modifiers.INTERNAL;
2513 accmods = Modifiers.PRIVATE;
2515 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2518 public override AttributeTargets AttributeTargets {
2520 return AttributeTargets.Interface;
2524 public override TypeAttributes TypeAttr {
2526 return base.TypeAttr |
2527 TypeAttributes.AutoLayout |
2528 TypeAttributes.Abstract |
2529 TypeAttributes.Interface;
2534 public abstract class MethodCore : MemberBase {
2535 public readonly Parameters Parameters;
2536 protected Block block;
2537 public DeclSpace ds;
2540 // Parameters, cached for semantic analysis.
2542 protected InternalParameters parameter_info;
2543 protected Type [] parameter_types;
2546 // This is set from TypeContainer.DefineMembers if this method overrides something.
2548 public bool OverridesSomething;
2550 // Whether this is an operator method.
2551 public bool IsOperator;
2553 static string[] attribute_targets = new string [] { "method", "return" };
2555 public MethodCore (DeclSpace ds, Expression type, int mod, int allowed_mod,
2556 bool is_interface, string name, Attributes attrs,
2557 Parameters parameters, Location loc)
2558 : base (type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
2560 Parameters = parameters;
2561 IsInterface = is_interface;
2566 // Returns the System.Type array for the parameters of this method
2568 public Type [] ParameterTypes {
2570 return parameter_types;
2574 public InternalParameters ParameterInfo
2577 return parameter_info;
2581 public Block Block {
2591 protected virtual bool DoDefineParameters ()
2593 // Check if arguments were correct
2594 parameter_types = Parameters.GetParameterInfo (ds);
2595 if ((parameter_types == null) || !CheckParameters (ds, parameter_types))
2598 parameter_info = new InternalParameters (ds, Parameters);
2600 Parameter array_param = Parameters.ArrayParameter;
2601 if ((array_param != null) &&
2602 (!array_param.ParameterType.IsArray ||
2603 (array_param.ParameterType.GetArrayRank () != 1))) {
2604 Report.Error (225, Location, "params parameter has to be a single dimensional array");
2611 protected override string[] ValidAttributeTargets {
2613 return attribute_targets;
2617 protected override bool VerifyClsCompliance (DeclSpace ds)
2619 if (!base.VerifyClsCompliance (ds)) {
2620 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
2621 Report.Error_T (3011, Location, GetSignatureForError ());
2626 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
2628 if (!AttributeTester.IsClsCompliant (MemberType)) {
2629 Report.Error_T (3002, Location, GetSignatureForError ());
2635 protected bool IsDuplicateImplementation (TypeContainer tc, MethodCore method)
2637 if ((method == this) || (method.Name != Name))
2640 Type[] param_types = method.ParameterTypes;
2641 if (param_types == null)
2644 if (param_types.Length != ParameterTypes.Length)
2647 for (int i = 0; i < param_types.Length; i++)
2648 if (param_types [i] != ParameterTypes [i])
2652 // Try to report 663: method only differs on out/ref
2654 ParameterData info = ParameterInfo;
2655 ParameterData other_info = method.ParameterInfo;
2656 for (int i = 0; i < info.Count; i++){
2657 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
2658 Report.Error (663, Location, "Overload method only differs in parameter modifier");
2663 Report.Error (111, Location, "Class `{0}' already defines a " +
2664 "member called `{1}' with the same parameter types",
2669 public CallingConventions GetCallingConvention (bool is_class)
2671 CallingConventions cc = 0;
2673 cc = Parameters.GetCallingConvention ();
2676 if ((ModFlags & Modifiers.STATIC) == 0)
2677 cc |= CallingConventions.HasThis;
2679 // FIXME: How is `ExplicitThis' used in C#?
2684 protected override void VerifyObsoleteAttribute()
2686 base.VerifyObsoleteAttribute ();
2688 if (parameter_types == null)
2691 foreach (Type type in parameter_types) {
2692 CheckUsageOfObsoleteAttribute (type);
2697 public class Method : MethodCore, IIteratorContainer, IMethodData {
2698 public MethodBuilder MethodBuilder;
2699 public MethodData MethodData;
2700 ReturnParameter return_attributes;
2703 /// Modifiers allowed in a class declaration
2705 const int AllowedModifiers =
2708 Modifiers.PROTECTED |
2709 Modifiers.INTERNAL |
2714 Modifiers.OVERRIDE |
2715 Modifiers.ABSTRACT |
2717 Modifiers.METHOD_YIELDS |
2720 const int AllowedInterfaceModifiers =
2721 Modifiers.NEW | Modifiers.UNSAFE;
2724 // return_type can be "null" for VOID values.
2726 public Method (DeclSpace ds, Expression return_type, int mod, bool is_iface,
2727 string name, Parameters parameters, Attributes attrs, Location l)
2728 : base (ds, return_type, mod,
2729 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
2730 is_iface, name, attrs, parameters, l)
2734 public override AttributeTargets AttributeTargets {
2736 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2741 // Returns the `System.Type' for the ReturnType of this
2742 // function. Provides a nice cache. (used between semantic analysis
2743 // and actual code generation
2745 public Type GetReturnType ()
2750 public override string GetSignatureForError()
2752 return TypeManager.CSharpSignature (MethodBuilder);
2756 /// Use this method when MethodBuilder is null
2758 public override string GetSignatureForError (TypeContainer tc)
2760 // TODO: move to parameters
2761 System.Text.StringBuilder args = new System.Text.StringBuilder ();
2762 if (parameter_info.Parameters.FixedParameters != null) {
2763 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
2764 Parameter p = parameter_info.Parameters.FixedParameters [i];
2765 args.Append (p.GetSignatureForError ());
2767 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
2772 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
2775 void DuplicateEntryPoint (MethodInfo b, Location location)
2779 "Program `" + CodeGen.FileName +
2780 "' has more than one entry point defined: `" +
2781 TypeManager.CSharpSignature(b) + "'");
2784 void Report28 (MethodInfo b)
2788 "`" + TypeManager.CSharpSignature(b) +
2789 "' has the wrong signature to be an entry point");
2792 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
2794 if (b.ReturnType != TypeManager.void_type &&
2795 b.ReturnType != TypeManager.int32_type)
2798 if (pinfo.Count == 0)
2801 if (pinfo.Count > 1)
2804 Type t = pinfo.ParameterType(0);
2806 (t.GetArrayRank() == 1) &&
2807 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
2808 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
2814 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2816 if (a.Target == "return") {
2817 if (return_attributes == null)
2818 return_attributes = new ReturnParameter (MethodBuilder, Location);
2820 return_attributes.ApplyAttributeBuilder (a, cb);
2824 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
2825 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
2828 if (a.Type == TypeManager.dllimport_type) {
2829 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
2830 if ((ModFlags & extern_static) != extern_static) {
2831 //"The DllImport attribute must be specified on a method marked `static' and `extern'"
2832 Report.Error_T (601, a.Location);
2838 if (a.Type == TypeManager.conditional_attribute_type) {
2839 if (IsOperator || IsExplicitImpl) {
2840 // Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation
2841 Report.Error_T (577, Location, GetSignatureForError ());
2845 if (ReturnType != TypeManager.void_type) {
2846 // Conditional not valid on '{0}' because its return type is not void
2847 Report.Error_T (578, Location, GetSignatureForError ());
2851 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2852 // Conditional not valid on '{0}' because it is an override method
2853 Report.Error_T (243, Location, GetSignatureForError ());
2858 // Conditional not valid on interface members
2859 Report.Error_T (582, Location);
2863 if (MethodData.IsImplementing) {
2864 // Conditional member '{0}' cannot implement interface member
2865 Report.Error_T (629, Location, GetSignatureForError ());
2870 MethodBuilder.SetCustomAttribute (cb);
2874 // Checks our base implementation if any
2876 protected override bool CheckBase (TypeContainer container)
2878 base.CheckBase (container);
2880 // Check whether arguments were correct.
2881 if (!DoDefineParameters ())
2884 MethodSignature ms = new MethodSignature (Name, null, ParameterTypes);
2886 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2889 // Check in our class for dups
2891 ArrayList ar = container.Methods;
2893 int arLen = ar.Count;
2895 for (int i = 0; i < arLen; i++) {
2896 Method m = (Method) ar [i];
2897 if (IsDuplicateImplementation (container, m))
2905 // Verify if the parent has a type with the same name, and then
2906 // check whether we have to create a new slot for it or not.
2908 Type ptype = container.TypeBuilder.BaseType;
2910 // ptype is only null for System.Object while compiling corlib.
2911 if (ptype != null) {
2914 // Explicit implementations do not have `parent' methods, however,
2915 // the member cache stores them there. Without this check, we get
2916 // an incorrect warning in corlib.
2918 if (! IsExplicitImpl) {
2919 parent_method = (MethodInfo)((IMemberContainer)container).Parent.MemberCache.FindMemberToOverride (
2920 container.TypeBuilder, Name, ParameterTypes, false);
2923 if (parent_method != null) {
2924 string name = parent_method.DeclaringType.Name + "." +
2927 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
2930 if ((ModFlags & Modifiers.NEW) == 0) {
2931 Type parent_ret = TypeManager.TypeToCoreType (
2932 parent_method.ReturnType);
2934 if (parent_ret != MemberType) {
2936 508, Location, container.MakeName (Name) + ": cannot " +
2937 "change return type when overriding " +
2938 "inherited member " + name);
2943 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (parent_method);
2945 Report.SymbolRelatedToPreviousError (parent_method);
2946 Report.Warning_T (672, Location, GetSignatureForError (container));
2949 if (!OverridesSomething && ((ModFlags & Modifiers.NEW) != 0))
2950 WarningNotHiding (container);
2952 if ((ModFlags & Modifiers.OVERRIDE) != 0){
2953 Report.Error (115, Location,
2954 container.MakeName (Name) +
2955 " no suitable methods found to override");
2958 } else if ((ModFlags & Modifiers.NEW) != 0)
2959 WarningNotHiding (container);
2967 public override bool Define (TypeContainer container)
2969 if (!DoDefine (container))
2972 if (!CheckBase (container))
2975 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
2977 if (!MethodData.Define (container))
2981 // Setup iterator if we are one
2983 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
2984 IteratorHandler ih = new IteratorHandler (
2985 Name, container, MemberType,
2986 ParameterTypes, ParameterInfo,
2987 ModFlags, Location);
2989 Block new_block = ih.Setup (block);
2990 if (new_block == null)
2995 MethodBuilder = MethodData.MethodBuilder;
2998 // This is used to track the Entry Point,
3000 if (Name == "Main" &&
3001 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3002 (RootContext.MainClass == null ||
3003 RootContext.MainClass == container.TypeBuilder.FullName)){
3004 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3005 if (RootContext.EntryPoint == null) {
3006 RootContext.EntryPoint = MethodBuilder;
3007 RootContext.EntryPointLocation = Location;
3009 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3010 DuplicateEntryPoint (MethodBuilder, Location);
3013 Report28(MethodBuilder);
3022 public override void Emit (TypeContainer container)
3024 MethodData.Emit (container, this);
3025 base.Emit (container);
3030 void IIteratorContainer.SetYields ()
3032 ModFlags |= Modifiers.METHOD_YIELDS;
3035 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
3037 return IsIdentifierAndParamClsCompliant (ds, Name, MethodBuilder, parameter_types);
3040 #region IMethodData Members
3042 public CallingConventions CallingConventions {
3044 CallingConventions cc = Parameters.GetCallingConvention ();
3045 if (Parameters.HasArglist)
3046 block.HasVarargs = true;
3049 if ((ModFlags & Modifiers.STATIC) == 0)
3050 cc |= CallingConventions.HasThis;
3052 // FIXME: How is `ExplicitThis' used in C#?
3058 public Type ReturnType {
3064 public string MethodName {
3070 public new Location Location {
3072 return base.Location;
3076 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3078 return new EmitContext (tc, ds, Location, ig, ReturnType, ModFlags, false);
3081 public ObsoleteAttribute GetObsoleteAttribute ()
3083 return GetObsoleteAttribute (ds);
3087 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3089 public bool IsExcluded (EmitContext ec)
3091 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3092 return (caching_flags & Flags.Excluded) != 0;
3094 caching_flags &= ~Flags.Excluded_Undetected;
3096 if (parent_method == null) {
3097 if (OptAttributes == null)
3100 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3105 foreach (Attribute a in attrs) {
3106 string condition = a.GetConditionalAttributeValue (ds);
3107 if (RootContext.AllDefines.Contains (condition))
3111 caching_flags |= Flags.Excluded;
3115 IMethodData md = TypeManager.GetMethod (parent_method);
3117 if (AttributeTester.IsConditionalMethodExcluded (parent_method)) {
3118 caching_flags |= Flags.Excluded;
3124 if (md.IsExcluded (ec)) {
3125 caching_flags |= Flags.Excluded;
3134 public abstract class ConstructorInitializer {
3135 ArrayList argument_list;
3136 protected ConstructorInfo parent_constructor;
3137 Parameters parameters;
3140 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
3143 this.argument_list = argument_list;
3144 this.parameters = parameters;
3148 public ArrayList Arguments {
3150 return argument_list;
3154 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
3156 Expression parent_constructor_group;
3159 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
3161 if (argument_list != null){
3162 foreach (Argument a in argument_list){
3163 if (!a.Resolve (ec, loc))
3167 ec.CurrentBlock = null;
3169 if (this is ConstructorBaseInitializer) {
3170 if (ec.ContainerType.BaseType == null)
3173 t = ec.ContainerType.BaseType;
3174 if (ec.ContainerType.IsValueType) {
3175 Report.Error (522, loc,
3176 "structs cannot call base class constructors");
3180 t = ec.ContainerType;
3182 parent_constructor_group = Expression.MemberLookup (
3183 ec, t, ".ctor", MemberTypes.Constructor,
3184 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3187 if (parent_constructor_group == null){
3188 parent_constructor_group = Expression.MemberLookup (
3189 ec, t, ".ctor", MemberTypes.Constructor,
3190 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3193 if (parent_constructor_group != null)
3195 112, loc, "`{0}.{1}' is inaccessible due to " +
3196 "its protection level", t.FullName, t.Name);
3199 1501, loc, "Can not find a constructor for " +
3200 "this argument list");
3204 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (ec,
3205 (MethodGroupExpr) parent_constructor_group, argument_list, loc);
3207 if (parent_constructor == null){
3208 Report.Error (1501, loc,
3209 "Can not find a constructor for this argument list");
3213 if (parent_constructor == caller_builder){
3214 Report.Error (515, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
3221 public void Emit (EmitContext ec)
3223 if (parent_constructor != null){
3224 ec.Mark (loc, false);
3226 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
3228 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
3233 /// Method search for base ctor. (We do not cache it).
3235 Constructor GetOverloadedConstructor (TypeContainer tc)
3237 if (tc.InstanceConstructors == null)
3240 foreach (Constructor c in tc.InstanceConstructors) {
3241 if (Arguments == null) {
3242 if (c.ParameterTypes.Length == 0)
3250 int count = c.ParameterInfo.Count;
3252 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
3253 for (int i = 0; i < count-1; i++)
3254 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
3259 if (c.ParameterTypes.Length != Arguments.Count)
3262 for (int i = 0; i < Arguments.Count; ++i)
3263 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
3275 throw new InternalErrorException ();
3278 //TODO: implement caching when it will be necessary
3279 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
3281 Constructor ctor = GetOverloadedConstructor (tc);
3285 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
3289 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
3293 public class ConstructorBaseInitializer : ConstructorInitializer {
3294 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
3295 base (argument_list, pars, l)
3299 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
3300 if (parent_constructor == null)
3303 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.base_classs_type);
3304 if (type_ds == null) {
3305 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (parent_constructor);
3308 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (parent_constructor), loc);
3313 base.CheckObsoleteAttribute (type_ds, loc);
3318 public class ConstructorThisInitializer : ConstructorInitializer {
3319 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
3320 base (argument_list, pars, l)
3325 public class Constructor : MethodCore {
3326 public ConstructorBuilder ConstructorBuilder;
3327 public ConstructorInitializer Initializer;
3330 // Modifiers allowed for a constructor.
3332 public const int AllowedModifiers =
3334 Modifiers.PROTECTED |
3335 Modifiers.INTERNAL |
3341 bool has_compliant_args = false;
3343 // The spec claims that static is not permitted, but
3344 // my very own code has static constructors.
3346 public Constructor (DeclSpace ds, string name, int mod, Parameters args,
3347 ConstructorInitializer init, Location l)
3348 : base (ds, null, mod, AllowedModifiers, false, name, null, args, l)
3353 public override string GetSignatureForError()
3355 return TypeManager.CSharpSignature (ConstructorBuilder);
3358 public bool HasCompliantArgs {
3360 return has_compliant_args;
3364 public override AttributeTargets AttributeTargets {
3366 return AttributeTargets.Constructor;
3372 // Returns true if this is a default constructor
3374 public bool IsDefault ()
3376 if ((ModFlags & Modifiers.STATIC) != 0)
3377 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
3378 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
3381 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
3382 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
3383 (Initializer is ConstructorBaseInitializer) &&
3384 (Initializer.Arguments == null);
3387 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3389 ConstructorBuilder.SetCustomAttribute (cb);
3392 protected override bool CheckBase (TypeContainer container)
3394 base.CheckBase (container);
3396 // Check whether arguments were correct.
3397 if (!DoDefineParameters ())
3400 if ((ModFlags & Modifiers.STATIC) != 0)
3403 if (container is Struct && ParameterTypes.Length == 0) {
3404 Report.Error (568, Location,
3405 "Structs can not contain explicit parameterless " +
3411 // Check in our class for dups
3413 ArrayList ar = container.InstanceConstructors;
3415 int arLen = ar.Count;
3417 for (int i = 0; i < arLen; i++) {
3418 Constructor m = (Constructor) ar [i];
3419 if (IsDuplicateImplementation (container, m))
3428 // Creates the ConstructorBuilder
3430 public override bool Define (TypeContainer container)
3432 MethodAttributes ca = (MethodAttributes.RTSpecialName |
3433 MethodAttributes.SpecialName);
3435 if ((ModFlags & Modifiers.STATIC) != 0) {
3436 ca |= MethodAttributes.Static | MethodAttributes.Private;
3438 ca |= MethodAttributes.HideBySig;
3440 if ((ModFlags & Modifiers.PUBLIC) != 0)
3441 ca |= MethodAttributes.Public;
3442 else if ((ModFlags & Modifiers.PROTECTED) != 0){
3443 if ((ModFlags & Modifiers.INTERNAL) != 0)
3444 ca |= MethodAttributes.FamORAssem;
3446 ca |= MethodAttributes.Family;
3447 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
3448 ca |= MethodAttributes.Assembly;
3449 else if (IsDefault ())
3450 ca |= MethodAttributes.Public;
3452 ca |= MethodAttributes.Private;
3455 // Check if arguments were correct.
3456 if (!CheckBase (container))
3459 ConstructorBuilder = container.TypeBuilder.DefineConstructor (
3460 ca, GetCallingConvention (container is Class), ParameterTypes);
3462 if ((ModFlags & Modifiers.UNSAFE) != 0)
3463 ConstructorBuilder.InitLocals = false;
3466 // HACK because System.Reflection.Emit is lame
3468 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
3476 public override void Emit (TypeContainer container)
3478 ILGenerator ig = ConstructorBuilder.GetILGenerator ();
3479 EmitContext ec = new EmitContext (container, Location, ig, null, ModFlags, true);
3482 // extern methods have no bodies
3484 if ((ModFlags & Modifiers.EXTERN) != 0) {
3485 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
3487 179, Location, "External constructor `" +
3488 TypeManager.CSharpSignature (ConstructorBuilder) +
3489 "' can not have a body");
3492 } else if (block == null) {
3494 501, Location, "Constructor `" +
3495 TypeManager.CSharpSignature (ConstructorBuilder) +
3496 "' must declare a body since it is not marked extern");
3500 if ((ModFlags & Modifiers.STATIC) == 0){
3501 if (container is Class && Initializer == null)
3502 Initializer = new ConstructorBaseInitializer (
3503 null, Parameters.EmptyReadOnlyParameters, Location);
3507 // Spec mandates that Initializers will not have
3511 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
3513 ec.IsStatic = false;
3516 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
3518 SymbolWriter sw = CodeGen.SymbolWriter;
3519 bool generate_debugging = false;
3521 if ((sw != null) && (block != null) &&
3522 !Location.IsNull (Location) &&
3523 !Location.IsNull (block.EndLocation) &&
3524 (Location.SymbolDocument != null)) {
3525 sw.OpenMethod (container, ConstructorBuilder, Location, block.EndLocation);
3527 generate_debugging = true;
3531 // Classes can have base initializers and instance field initializers.
3533 if (container is Class){
3534 if ((ModFlags & Modifiers.STATIC) == 0){
3537 // If we use a "this (...)" constructor initializer, then
3538 // do not emit field initializers, they are initialized in the other constructor
3540 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
3541 container.EmitFieldInitializers (ec);
3544 if (Initializer != null) {
3545 Initializer.CheckObsoleteAttribute (container, Location);
3546 Initializer.Emit (ec);
3549 if ((ModFlags & Modifiers.STATIC) != 0)
3550 container.EmitFieldInitializers (ec);
3552 if (OptAttributes != null)
3553 OptAttributes.Emit (ec, this);
3555 // If this is a non-static `struct' constructor and doesn't have any
3556 // initializer, it must initialize all of the struct's fields.
3557 if ((container is Struct) && ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
3558 Block.AddThisVariable (container, Location);
3560 ec.EmitTopBlock (block, ParameterInfo, Location);
3562 if (generate_debugging)
3565 base.Emit (container);
3570 // For constructors is needed to test only parameters
3571 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
3573 if (parameter_types == null || parameter_types.Length == 0)
3576 TypeContainer tc = ds as TypeContainer;
3578 for (int i = 0; i < tc.InstanceConstructors.Count; i++) {
3579 Constructor c = (Constructor) tc.InstanceConstructors [i];
3581 if (c == this || c.ParameterTypes.Length == 0)
3584 if (!c.IsClsCompliaceRequired (ds))
3587 if (!AttributeTester.AreOverloadedMethodParamsClsCompliant (parameter_types, c.ParameterTypes)) {
3588 Report.Error_T (3006, Location, GetSignatureForError ());
3593 if (tc.TypeBuilder.BaseType == null)
3596 DeclSpace temp_ds = TypeManager.LookupDeclSpace (tc.TypeBuilder.BaseType);
3597 if (temp_ds != null)
3598 return IsIdentifierClsCompliant (temp_ds);
3600 MemberInfo[] ml = tc.TypeBuilder.BaseType.FindMembers (MemberTypes.Constructor, BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance, null, null);
3601 // Skip parameter-less ctor
3605 foreach (ConstructorInfo ci in ml) {
3606 object[] cls_attribute = ci.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
3607 if (cls_attribute.Length == 1 && (!((CLSCompliantAttribute)cls_attribute[0]).IsCompliant))
3610 if (!AttributeTester.AreOverloadedMethodParamsClsCompliant (parameter_types, TypeManager.GetArgumentTypes (ci))) {
3611 Report.Error_T (3006, Location, GetSignatureForError ());
3619 protected override bool VerifyClsCompliance (DeclSpace ds)
3621 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
3625 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
3626 foreach (Type param in parameter_types) {
3627 if (param.IsArray) {
3632 has_compliant_args = true;
3639 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
3641 public interface IMethodData
3643 CallingConventions CallingConventions { get; }
3644 Location Location { get; }
3645 string MethodName { get; }
3646 Type[] ParameterTypes { get; }
3647 Type ReturnType { get; }
3649 Attributes OptAttributes { get; }
3650 Block Block { get; }
3652 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
3653 ObsoleteAttribute GetObsoleteAttribute ();
3654 string GetSignatureForError (TypeContainer tc);
3655 bool IsExcluded (EmitContext ec);
3659 // Encapsulates most of the Method's state
3661 public class MethodData {
3663 readonly IMethodData method;
3666 // The return type of this method
3668 public readonly InternalParameters ParameterInfo;
3671 // Are we implementing an interface ?
3673 public bool IsImplementing = false;
3678 protected MemberBase member;
3679 protected int modifiers;
3680 protected MethodAttributes flags;
3682 MethodBuilder builder = null;
3683 public MethodBuilder MethodBuilder {
3689 public MethodData (MemberBase member, InternalParameters parameters,
3690 int modifiers, MethodAttributes flags, IMethodData method)
3692 this.member = member;
3693 this.ParameterInfo = parameters;
3694 this.modifiers = modifiers;
3697 this.method = method;
3700 public bool Define (TypeContainer container)
3702 MethodInfo implementing = null;
3705 if (member.IsExplicitImpl)
3706 prefix = member.InterfaceType.FullName + ".";
3710 string name = method.MethodName;
3711 string method_name = prefix + name;
3712 Type[] ParameterTypes = method.ParameterTypes;
3714 if (container.Pending != null){
3715 if (member is Indexer)
3716 implementing = container.Pending.IsInterfaceIndexer (
3717 member.InterfaceType, method.ReturnType, ParameterTypes);
3719 implementing = container.Pending.IsInterfaceMethod (
3720 member.InterfaceType, name, method.ReturnType, ParameterTypes);
3722 if (member.InterfaceType != null && implementing == null){
3723 Report.Error (539, method.Location, "'{0}' in explicit interface declaration is not an interface", method_name);
3729 // For implicit implementations, make sure we are public, for
3730 // explicit implementations, make sure we are private.
3732 if (implementing != null){
3734 // Setting null inside this block will trigger a more
3735 // verbose error reporting for missing interface implementations
3737 // The "candidate" function has been flagged already
3738 // but it wont get cleared
3740 if (member.IsExplicitImpl){
3741 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
3742 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
3743 implementing = null;
3745 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
3746 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
3748 // If this is an interface method implementation,
3749 // check for public accessibility
3751 implementing = null;
3752 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
3753 // We may never be private.
3754 implementing = null;
3755 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
3757 // We may be protected if we're overriding something.
3759 implementing = null;
3764 // Static is not allowed
3766 if ((modifiers & Modifiers.STATIC) != 0){
3767 implementing = null;
3768 Modifiers.Error_InvalidModifier (method.Location, "static");
3773 // If implementing is still valid, set flags
3775 if (implementing != null){
3777 // When implementing interface methods, set NewSlot
3778 // unless, we are overwriting a method.
3780 if (implementing.DeclaringType.IsInterface){
3781 if ((modifiers & Modifiers.OVERRIDE) == 0)
3782 flags |= MethodAttributes.NewSlot;
3785 MethodAttributes.Virtual |
3786 MethodAttributes.HideBySig;
3788 // Set Final unless we're virtual, abstract or already overriding a method.
3789 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
3790 flags |= MethodAttributes.Final;
3792 // Get the method name from the explicit interface.
3793 if (member.InterfaceType != null) {
3794 name = implementing.Name;
3795 method_name = prefix + name;
3798 IsImplementing = true;
3801 EmitContext ec = method.CreateEmitContext (container, null);
3803 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
3805 if (builder == null)
3808 if ((modifiers & Modifiers.UNSAFE) != 0)
3809 builder.InitLocals = false;
3811 if (IsImplementing){
3813 // clear the pending implemntation flag
3815 if (member is Indexer) {
3816 container.Pending.ImplementIndexer (
3817 member.InterfaceType, builder, method.ReturnType,
3818 ParameterTypes, true);
3820 container.Pending.ImplementMethod (
3821 member.InterfaceType, name, method.ReturnType,
3822 ParameterTypes, member.IsExplicitImpl);
3824 if (member.IsExplicitImpl)
3825 container.TypeBuilder.DefineMethodOverride (
3826 builder, implementing);
3830 if (!TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes)) {
3831 Report.Error (111, method.Location,
3832 "Class `" + container.Name +
3833 "' already contains a definition with the " +
3834 "same return value and parameter types as the " +
3835 "'get' method of property `" + member.Name + "'");
3839 TypeManager.AddMethod (builder, method);
3846 /// Create the MethodBuilder for the method
3848 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
3850 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3852 if ((modifiers & extern_static) == extern_static) {
3854 if (method.OptAttributes != null) {
3855 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
3856 if (dllimport_attribute != null) {
3857 flags |= MethodAttributes.PinvokeImpl;
3858 builder = dllimport_attribute.DefinePInvokeMethod (
3859 ec, container.TypeBuilder, method_name, flags,
3860 method.ReturnType, ParameterTypes);
3866 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3867 // We are more strict than Microsoft and report CS0626 like error
3868 if (method.OptAttributes == null ||
3869 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
3870 //"Method, operator, or accessor '{0}' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation"
3871 Report.Error_T (626, method.Location, method.GetSignatureForError (container));
3876 builder = container.TypeBuilder.DefineMethod (
3877 method_name, flags, method.CallingConventions,
3878 method.ReturnType, ParameterTypes);
3884 public void Emit (TypeContainer container, Attributable kind)
3888 if ((flags & MethodAttributes.PinvokeImpl) == 0)
3889 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
3891 ec = method.CreateEmitContext (container, null);
3893 Location loc = method.Location;
3894 Attributes OptAttributes = method.OptAttributes;
3896 if (OptAttributes != null)
3897 OptAttributes.Emit (ec, kind);
3899 if (member is MethodCore)
3900 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
3902 SymbolWriter sw = CodeGen.SymbolWriter;
3903 Block block = method.Block;
3906 // abstract or extern methods have no bodies
3908 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
3909 if (block == null) {
3910 if ((sw != null) && ((modifiers & Modifiers.EXTERN) != 0) &&
3911 !Location.IsNull (loc) &&
3912 (method.Location.SymbolDocument != null)) {
3913 sw.OpenMethod (container, MethodBuilder, loc, loc);
3921 // abstract or extern methods have no bodies.
3923 if ((modifiers & Modifiers.ABSTRACT) != 0)
3925 500, method.Location, "Abstract method `" +
3926 TypeManager.CSharpSignature (builder) +
3927 "' can not have a body");
3929 if ((modifiers & Modifiers.EXTERN) != 0)
3931 179, method.Location, "External method `" +
3932 TypeManager.CSharpSignature (builder) +
3933 "' can not have a body");
3939 // Methods must have a body unless they're extern or abstract
3941 if (block == null) {
3943 501, method.Location, "Method `" +
3944 TypeManager.CSharpSignature (builder) +
3945 "' must declare a body since it is not marked " +
3946 "abstract or extern");
3951 // Handle destructors specially
3953 // FIXME: This code generates buggy code
3955 if ((sw != null) && !Location.IsNull (loc) &&
3956 !Location.IsNull (block.EndLocation) &&
3957 (loc.SymbolDocument != null)) {
3958 sw.OpenMethod (container, MethodBuilder, loc, block.EndLocation);
3960 if (member is Destructor)
3961 EmitDestructor (ec, block);
3963 ec.EmitTopBlock (block, ParameterInfo, loc);
3967 if (member is Destructor)
3968 EmitDestructor (ec, block);
3970 ec.EmitTopBlock (block, ParameterInfo, loc);
3974 void EmitDestructor (EmitContext ec, Block block)
3976 ILGenerator ig = ec.ig;
3978 Label finish = ig.DefineLabel ();
3980 block.SetDestructor ();
3982 ig.BeginExceptionBlock ();
3983 ec.ReturnLabel = finish;
3984 ec.HasReturnLabel = true;
3985 ec.EmitTopBlock (block, null, method.Location);
3987 // ig.MarkLabel (finish);
3988 ig.BeginFinallyBlock ();
3990 if (ec.ContainerType.BaseType != null) {
3991 Expression member_lookup = Expression.MemberLookup (
3992 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
3993 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
3995 if (member_lookup != null){
3996 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
3998 ig.Emit (OpCodes.Ldarg_0);
3999 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
4003 ig.EndExceptionBlock ();
4004 //ig.MarkLabel (ec.ReturnLabel);
4005 ig.Emit (OpCodes.Ret);
4009 public class Destructor : Method {
4011 public Destructor (DeclSpace ds, Expression return_type, int mod, string name,
4012 Parameters parameters, Attributes attrs, Location l)
4013 : base (ds, return_type, mod, false, name, parameters, attrs, l)
4016 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4018 if (a.Type == TypeManager.conditional_attribute_type) {
4019 // Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation
4020 Report.Error_T (577, Location, GetSignatureForError ());
4024 base.ApplyAttributeBuilder (a, cb);
4028 abstract public class MemberBase : MemberCore {
4029 public Expression Type;
4031 public MethodAttributes flags;
4033 protected readonly int explicit_mod_flags;
4036 // The "short" name of this property / indexer / event. This is the
4037 // name without the explicit interface.
4039 public string ShortName;
4042 // The type of this property / indexer / event
4044 public Type MemberType;
4047 // If true, this is an explicit interface implementation
4049 public bool IsExplicitImpl = false;
4052 // The name of the interface we are explicitly implementing
4054 public string ExplicitInterfaceName = null;
4057 // Whether this is an interface member.
4059 public bool IsInterface;
4062 // If true, the interface type we are explicitly implementing
4064 public Type InterfaceType = null;
4067 // The method we're overriding if this is an override method.
4069 protected MethodInfo parent_method = null;
4070 public MethodInfo ParentMethod {
4072 return parent_method;
4077 // The constructor is only exposed to our children
4079 protected MemberBase (Expression type, int mod, int allowed_mod, int def_mod, string name,
4080 Attributes attrs, Location loc)
4081 : base (name, attrs, loc)
4083 explicit_mod_flags = mod;
4085 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4088 protected virtual bool CheckBase (TypeContainer container)
4090 if ((container is Struct) || (RootContext.WarningLevel > 3)){
4091 if ((ModFlags & Modifiers.PROTECTED) != 0 && (container.ModFlags & Modifiers.SEALED) != 0){
4092 if (container is Struct){
4093 Report.Error (666, Location, "Protected member in struct declaration");
4096 Report.Warning (628, Location, "Member " + container.MakeName (Name) + " protected in sealed class");
4102 protected void WarningNotHiding (TypeContainer parent)
4106 "The member " + parent.MakeName (Name) + " does not hide an " +
4107 "inherited member. The keyword new is not required");
4111 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method,
4115 // FIXME: report the old/new permissions?
4118 507, Location, parent.MakeName (Name) +
4119 ": can't change the access modifiers when overriding inherited " +
4120 "member `" + name + "'");
4124 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
4125 // that have been defined.
4127 // `name' is the user visible name for reporting errors (this is used to
4128 // provide the right name regarding method names and properties)
4130 protected bool CheckMethodAgainstBase (TypeContainer parent, MethodAttributes my_attrs,
4131 MethodInfo mb, string name)
4135 if ((ModFlags & Modifiers.OVERRIDE) != 0){
4136 if (!(mb.IsAbstract || mb.IsVirtual)){
4138 506, Location, parent.MakeName (Name) +
4139 ": cannot override inherited member `" +
4140 name + "' because it is not " +
4141 "virtual, abstract or override");
4145 // Now we check that the overriden method is not final
4148 // This happens when implementing interface methods.
4149 if (mb.IsHideBySig && mb.IsVirtual) {
4151 506, Location, parent.MakeName (Name) +
4152 ": cannot override inherited member `" +
4153 name + "' because it is not " +
4154 "virtual, abstract or override");
4156 Report.Error (239, Location, parent.MakeName (Name) + " : cannot " +
4157 "override inherited member `" + name +
4158 "' because it is sealed.");
4162 // Check that the permissions are not being changed
4164 MethodAttributes thisp = my_attrs & MethodAttributes.MemberAccessMask;
4165 MethodAttributes parentp = mb.Attributes & MethodAttributes.MemberAccessMask;
4168 // special case for "protected internal"
4171 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
4173 // when overriding protected internal, the method can be declared
4174 // protected internal only within the same assembly
4177 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
4178 if (parent.TypeBuilder.Assembly != mb.DeclaringType.Assembly){
4180 // assemblies differ - report an error
4183 Error_CannotChangeAccessModifiers (parent, mb, name);
4185 } else if (thisp != parentp) {
4187 // same assembly, but other attributes differ - report an error
4190 Error_CannotChangeAccessModifiers (parent, mb, name);
4193 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
4195 // if it's not "protected internal", it must be "protected"
4198 Error_CannotChangeAccessModifiers (parent, mb, name);
4200 } else if (parent.TypeBuilder.Assembly == mb.DeclaringType.Assembly) {
4202 // protected within the same assembly - an error
4204 Error_CannotChangeAccessModifiers (parent, mb, name);
4206 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
4207 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
4209 // protected ok, but other attributes differ - report an error
4211 Error_CannotChangeAccessModifiers (parent, mb, name);
4215 if (thisp != parentp){
4216 Error_CannotChangeAccessModifiers (parent, mb, name);
4222 if (mb.IsVirtual || mb.IsAbstract){
4223 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
4224 if (Name != "Finalize"){
4226 114, 2, Location, parent.MakeName (Name) +
4227 " hides inherited member `" + name +
4228 "'. To make the current member override that " +
4229 "implementation, add the override keyword, " +
4230 "otherwise use the new keyword");
4231 ModFlags |= Modifiers.NEW;
4235 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
4236 if (Name != "Finalize"){
4238 108, 1, Location, "The keyword new is required on " +
4239 parent.MakeName (Name) + " because it hides " +
4240 "inherited member `" + name + "'");
4241 ModFlags |= Modifiers.NEW;
4249 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4253 foreach (Type partype in parameters){
4254 if (partype == TypeManager.void_type) {
4256 1547, Location, "Keyword 'void' cannot " +
4257 "be used in this context");
4261 if (partype.IsPointer){
4264 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4268 if (ds.AsAccessible (partype, ModFlags))
4271 if (this is Indexer)
4272 Report.Error (55, Location,
4273 "Inconsistent accessibility: parameter type `" +
4274 TypeManager.CSharpName (partype) + "' is less " +
4275 "accessible than indexer `" + Name + "'");
4276 else if ((this is Method) && ((Method) this).IsOperator)
4277 Report.Error (57, Location,
4278 "Inconsistent accessibility: parameter type `" +
4279 TypeManager.CSharpName (partype) + "' is less " +
4280 "accessible than operator `" + Name + "'");
4282 Report.Error (51, Location,
4283 "Inconsistent accessibility: parameter type `" +
4284 TypeManager.CSharpName (partype) + "' is less " +
4285 "accessible than method `" + Name + "'");
4292 protected virtual bool DoDefine (TypeContainer container)
4298 ModFlags = Modifiers.PUBLIC |
4299 Modifiers.ABSTRACT |
4300 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE);
4302 flags = MethodAttributes.Public |
4303 MethodAttributes.Abstract |
4304 MethodAttributes.HideBySig |
4305 MethodAttributes.NewSlot |
4306 MethodAttributes.Virtual;
4308 if (!container.MethodModifiersValid (ModFlags, Name, Location))
4311 flags = Modifiers.MethodAttr (ModFlags);
4314 // Lookup Type, verify validity
4315 MemberType = container.ResolveType (Type, false, Location);
4316 if (MemberType == null)
4319 if ((container.ModFlags & Modifiers.SEALED) != 0){
4320 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
4321 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
4326 // verify accessibility
4327 if (!container.AsAccessible (MemberType, ModFlags)) {
4328 if (this is Property)
4329 Report.Error (53, Location,
4330 "Inconsistent accessibility: property type `" +
4331 TypeManager.CSharpName (MemberType) + "' is less " +
4332 "accessible than property `" + Name + "'");
4333 else if (this is Indexer)
4334 Report.Error (54, Location,
4335 "Inconsistent accessibility: indexer return type `" +
4336 TypeManager.CSharpName (MemberType) + "' is less " +
4337 "accessible than indexer `" + Name + "'");
4338 else if (this is Method) {
4339 if (((Method) this).IsOperator)
4340 Report.Error (56, Location,
4341 "Inconsistent accessibility: return type `" +
4342 TypeManager.CSharpName (MemberType) + "' is less " +
4343 "accessible than operator `" + Name + "'");
4345 Report.Error (50, Location,
4346 "Inconsistent accessibility: return type `" +
4347 TypeManager.CSharpName (MemberType) + "' is less " +
4348 "accessible than method `" + Name + "'");
4350 Report.Error (52, Location,
4351 "Inconsistent accessibility: field type `" +
4352 TypeManager.CSharpName (MemberType) + "' is less " +
4353 "accessible than field `" + Name + "'");
4357 if (MemberType.IsPointer && !UnsafeOK (container))
4361 // Check for explicit interface implementation
4363 if ((ExplicitInterfaceName == null) && (Name.IndexOf ('.') != -1)){
4364 int pos = Name.LastIndexOf ('.');
4366 ExplicitInterfaceName = Name.Substring (0, pos);
4367 ShortName = Name.Substring (pos + 1);
4371 if (ExplicitInterfaceName != null) {
4372 InterfaceType = container.FindType (
4373 Location, ExplicitInterfaceName);
4374 if (InterfaceType == null)
4377 if (InterfaceType.IsClass) {
4378 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", ExplicitInterfaceName);
4382 // Compute the full name that we need to export.
4383 Name = InterfaceType.FullName + "." + ShortName;
4385 if (!container.VerifyImplements (InterfaceType, ShortName, Name, Location))
4388 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
4390 IsExplicitImpl = true;
4392 IsExplicitImpl = false;
4398 /// Use this method when MethodBuilder is null
4400 public virtual string GetSignatureForError (TypeContainer tc)
4402 return String.Concat (tc.Name, '.', Name);
4405 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
4407 return IsIdentifierAndParamClsCompliant (ds, Name, null, null);
4410 protected override bool VerifyClsCompliance(DeclSpace ds)
4412 if (base.VerifyClsCompliance (ds)) {
4416 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
4417 Report.Error_T (3010, Location, GetSignatureForError ());
4422 protected override void VerifyObsoleteAttribute()
4424 CheckUsageOfObsoleteAttribute (MemberType);
4429 // Fields and Events both generate FieldBuilders, we use this to share
4430 // their common bits. This is also used to flag usage of the field
4432 abstract public class FieldBase : MemberBase {
4433 public FieldBuilder FieldBuilder;
4434 public Status status;
4437 public enum Status : byte { ASSIGNED = 1, USED = 2 }
4439 static string[] attribute_targets = new string [] { "field" };
4442 // The constructor is only exposed to our children
4444 protected FieldBase (Expression type, int mod, int allowed_mod, string name,
4445 object init, Attributes attrs, Location loc)
4446 : base (type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
4451 public override AttributeTargets AttributeTargets {
4453 return AttributeTargets.Field;
4457 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4459 if (a.Type == TypeManager.marshal_as_attr_type) {
4460 UnmanagedMarshal marshal = a.GetMarshal ();
4461 if (marshal != null) {
4462 FieldBuilder.SetMarshal (marshal);
4465 Report.Warning_T (-24, a.Location);
4470 FieldBuilder.SetCustomAttribute (cb);
4474 // Whether this field has an initializer.
4476 public bool HasInitializer {
4478 return init != null;
4482 protected readonly Object init;
4484 Expression init_expr;
4485 bool init_expr_initialized = false;
4488 // Resolves and returns the field initializer.
4490 public Expression GetInitializerExpression (EmitContext ec)
4492 if (init_expr_initialized)
4496 if (init is Expression)
4497 e = (Expression) init;
4499 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
4501 ec.IsFieldInitializer = true;
4502 e = e.DoResolve (ec);
4503 ec.IsFieldInitializer = false;
4506 init_expr_initialized = true;
4511 protected override bool DoDefine (TypeContainer container)
4513 if (!base.DoDefine (container))
4516 if (MemberType == TypeManager.void_type) {
4517 Report.Error (1547, Location,
4518 "Keyword 'void' cannot be used in this context");
4525 public override string GetSignatureForError ()
4527 return TypeManager.GetFullNameSignature (FieldBuilder);
4530 protected override string[] ValidAttributeTargets {
4532 return attribute_targets;
4536 protected override bool VerifyClsCompliance (DeclSpace ds)
4538 if (!base.VerifyClsCompliance (ds))
4541 if (FieldBuilder == null) {
4545 if (!AttributeTester.IsClsCompliant (FieldBuilder.FieldType)) {
4546 Report.Error_T (3003, Location, GetSignatureForError ());
4552 public void SetAssigned ()
4554 status |= Status.ASSIGNED;
4559 // The Field class is used to represents class/struct fields during parsing.
4561 public class Field : FieldBase {
4563 // Modifiers allowed in a class declaration
4565 const int AllowedModifiers =
4568 Modifiers.PROTECTED |
4569 Modifiers.INTERNAL |
4572 Modifiers.VOLATILE |
4576 public Field (Expression type, int mod, string name, Object expr_or_array_init,
4577 Attributes attrs, Location loc)
4578 : base (type, mod, AllowedModifiers, name, expr_or_array_init, attrs, loc)
4582 public override bool Define (TypeContainer container)
4584 MemberType = container.ResolveType (Type, false, Location);
4586 if (MemberType == null)
4589 CheckBase (container);
4591 if (!container.AsAccessible (MemberType, ModFlags)) {
4592 Report.Error (52, Location,
4593 "Inconsistent accessibility: field type `" +
4594 TypeManager.CSharpName (MemberType) + "' is less " +
4595 "accessible than field `" + Name + "'");
4599 if (MemberType.IsPointer && !UnsafeOK (container))
4602 if (RootContext.WarningLevel > 1){
4603 Type ptype = container.TypeBuilder.BaseType;
4605 // ptype is only null for System.Object while compiling corlib.
4607 TypeContainer.FindMembers (
4608 ptype, MemberTypes.Method,
4609 BindingFlags.Public |
4610 BindingFlags.Static | BindingFlags.Instance,
4611 System.Type.FilterName, Name);
4615 if ((ModFlags & Modifiers.VOLATILE) != 0){
4616 if (!MemberType.IsClass){
4617 Type vt = MemberType;
4619 if (TypeManager.IsEnumType (vt))
4620 vt = TypeManager.EnumToUnderlying (MemberType);
4622 if (!((vt == TypeManager.bool_type) ||
4623 (vt == TypeManager.sbyte_type) ||
4624 (vt == TypeManager.byte_type) ||
4625 (vt == TypeManager.short_type) ||
4626 (vt == TypeManager.ushort_type) ||
4627 (vt == TypeManager.int32_type) ||
4628 (vt == TypeManager.uint32_type) ||
4629 (vt == TypeManager.char_type) ||
4630 (vt == TypeManager.float_type) ||
4631 (!vt.IsValueType))){
4633 677, Location, container.MakeName (Name) +
4634 " A volatile field can not be of type `" +
4635 TypeManager.CSharpName (vt) + "'");
4640 if ((ModFlags & Modifiers.READONLY) != 0){
4643 "A field can not be both volatile and readonly");
4648 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
4650 if (container is Struct &&
4651 ((fa & FieldAttributes.Static) == 0) &&
4652 MemberType == container.TypeBuilder &&
4653 !TypeManager.IsBuiltinType (MemberType)){
4654 Report.Error (523, Location, "Struct member `" + container.Name + "." + Name +
4655 "' causes a cycle in the structure layout");
4660 FieldBuilder = container.TypeBuilder.DefineField (
4661 Name, MemberType, Modifiers.FieldAttr (ModFlags));
4663 TypeManager.RegisterFieldBase (FieldBuilder, this);
4665 catch (ArgumentException) {
4666 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
4673 public override void Emit (TypeContainer tc)
4675 if (OptAttributes != null) {
4676 EmitContext ec = new EmitContext (tc, Location, null, FieldBuilder.FieldType, ModFlags);
4677 OptAttributes.Emit (ec, this);
4685 // `set' and `get' accessors are represented with an Accessor.
4687 public class Accessor {
4689 // Null if the accessor is empty, or a Block if not
4692 public Attributes Attributes;
4694 public Accessor (Block b, Attributes attrs)
4702 // Properties and Indexers both generate PropertyBuilders, we use this to share
4703 // their common bits.
4705 abstract public class PropertyBase : MethodCore {
4707 public class GetMethod: PropertyMethod
4709 static string[] attribute_targets = new string [] { "method", "return" };
4711 public GetMethod (MethodCore method, Accessor accessor):
4712 base (method, accessor)
4716 public override MethodBuilder Define(TypeContainer container)
4718 method_data = new MethodData (method, method.ParameterInfo, method.ModFlags, method.flags, this);
4720 if (!method_data.Define (container))
4723 return method_data.MethodBuilder;
4726 public override string GetSignatureForError (TypeContainer tc)
4728 return String.Concat (base.GetSignatureForError (tc), ".get");
4731 public override string MethodName
4734 return "get_" + method.ShortName;
4738 public override Type ReturnType {
4740 return method.MemberType;
4744 protected override string[] ValidAttributeTargets {
4746 return attribute_targets;
4751 public class SetMethod: PropertyMethod {
4753 static string[] attribute_targets = new string [] { "method", "param", "return" };
4754 ImplicitParameter param_attr;
4756 public SetMethod (MethodCore method, Accessor accessor):
4757 base (method, accessor)
4761 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4763 if (a.Target == "param") {
4764 if (param_attr == null)
4765 param_attr = new ImplicitParameter (method_data.MethodBuilder);
4767 param_attr.ApplyAttributeBuilder (a, cb);
4771 base.ApplyAttributeBuilder (a, cb);
4774 protected virtual InternalParameters GetParameterInfo (TypeContainer container)
4776 Parameter [] parms = new Parameter [1];
4777 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
4778 return new InternalParameters (
4779 container, new Parameters (parms, null, method.Location));
4782 public override MethodBuilder Define(TypeContainer container)
4784 method_data = new MethodData (method, GetParameterInfo (container), method.ModFlags, method.flags, this);
4786 if (!method_data.Define (container))
4789 return method_data.MethodBuilder;
4792 public override string GetSignatureForError (TypeContainer tc)
4794 return String.Concat (base.GetSignatureForError (tc), ".set");
4797 public override string MethodName {
4799 return "set_" + method.ShortName;
4803 public override Type[] ParameterTypes {
4805 return new Type[] { method.MemberType };
4809 public override Type ReturnType {
4811 return TypeManager.void_type;
4815 protected override string[] ValidAttributeTargets {
4817 return attribute_targets;
4823 static string[] attribute_targets = new string [] { "property" };
4825 public abstract class PropertyMethod: Attributable, IMethodData
4827 protected readonly MethodCore method;
4828 protected MethodData method_data;
4831 ReturnParameter return_attributes;
4833 public PropertyMethod (MethodCore method, Accessor accessor):
4834 base (accessor.Attributes)
4836 this.method = method;
4837 this.block = accessor.Block;
4840 public override AttributeTargets AttributeTargets {
4842 return AttributeTargets.Method | AttributeTargets.ReturnValue;
4846 public override bool IsClsCompliaceRequired(DeclSpace ds)
4848 return method.IsClsCompliaceRequired (ds);
4851 public InternalParameters ParameterInfo
4854 return method_data.ParameterInfo;
4858 #region IMethodData Members
4860 public Block Block {
4866 public CallingConventions CallingConventions {
4868 return CallingConventions.Standard;
4872 public abstract MethodBuilder Define (TypeContainer container);
4874 public void Emit (TypeContainer container)
4876 method_data.Emit (container, this);
4880 public virtual string GetSignatureForError (TypeContainer tc)
4882 return String.Concat (tc.Name, '.', method.Name);
4885 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4887 if (a.Target == "return") {
4888 if (return_attributes == null)
4889 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
4891 return_attributes.ApplyAttributeBuilder (a, cb);
4895 method_data.MethodBuilder.SetCustomAttribute (cb);
4898 public virtual Type[] ParameterTypes {
4900 return TypeManager.NoTypes;
4904 public abstract Type ReturnType { get; }
4906 public Location Location {
4908 return method.Location;
4912 public abstract string MethodName { get; }
4914 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4916 return new EmitContext (tc, method.ds, method.Location, ig, ReturnType, method.ModFlags, false);
4919 public ObsoleteAttribute GetObsoleteAttribute ()
4921 return method.GetObsoleteAttribute (method.ds);
4924 public bool IsExcluded (EmitContext ec)
4933 public PropertyMethod Get, Set;
4934 public PropertyBuilder PropertyBuilder;
4935 public MethodBuilder GetBuilder, SetBuilder;
4937 protected EmitContext ec;
4939 public PropertyBase (DeclSpace ds, Expression type, int mod_flags,
4940 int allowed_mod, bool is_iface, string name,
4941 Parameters parameters, Attributes attrs,
4943 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
4944 attrs, parameters, loc)
4948 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4950 PropertyBuilder.SetCustomAttribute (cb);
4953 public override AttributeTargets AttributeTargets {
4955 return AttributeTargets.Property;
4959 protected override bool DoDefine (TypeContainer container)
4961 if (!base.DoDefine (container))
4964 ec = new EmitContext (container, Location, null, MemberType, ModFlags);
4969 public override string GetSignatureForError()
4971 return TypeManager.CSharpSignature (PropertyBuilder, false);
4974 protected virtual string RealMethodName {
4980 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
4982 if (!IsIdentifierAndParamClsCompliant (ds, RealMethodName, null, null))
4985 if (Get != null && !IsIdentifierAndParamClsCompliant (ds, "get_" + RealMethodName, null, null))
4988 if (Set != null && !IsIdentifierAndParamClsCompliant (ds, "set_" + RealMethodName, null, null))
4996 // Checks our base implementation if any
4998 protected override bool CheckBase (TypeContainer container)
5000 base.CheckBase (container);
5002 // Check whether arguments were correct.
5003 if (!DoDefineParameters ())
5010 // Check in our class for dups
5012 ArrayList ar = container.Properties;
5014 int arLen = ar.Count;
5016 for (int i = 0; i < arLen; i++) {
5017 Property m = (Property) ar [i];
5018 if (IsDuplicateImplementation (container, m))
5027 MethodSignature ms, base_ms;
5028 if (this is Indexer) {
5029 string name, base_name;
5031 report_name = "this";
5032 name = TypeManager.IndexerPropertyName (container.TypeBuilder);
5033 ms = new MethodSignature (name, null, ParameterTypes);
5034 base_name = TypeManager.IndexerPropertyName (container.TypeBuilder.BaseType);
5035 base_ms = new MethodSignature (base_name, null, ParameterTypes);
5038 ms = base_ms = new MethodSignature (Name, null, ParameterTypes);
5042 // Verify if the parent has a type with the same name, and then
5043 // check whether we have to create a new slot for it or not.
5045 Type ptype = container.TypeBuilder.BaseType;
5047 // ptype is only null for System.Object while compiling corlib.
5048 if (ptype == null) {
5049 if ((ModFlags & Modifiers.NEW) != 0)
5050 WarningNotHiding (container);
5055 MemberInfo parent_member = null;
5058 // Explicit implementations do not have `parent' methods, however,
5059 // the member cache stores them there. Without this check, we get
5060 // an incorrect warning in corlib.
5062 if (! IsExplicitImpl) {
5063 parent_member = ((IMemberContainer)container).Parent.MemberCache.FindMemberToOverride (
5064 container.TypeBuilder, Name, ParameterTypes, true);
5067 if (parent_member is PropertyInfo) {
5068 PropertyInfo parent_property = (PropertyInfo)parent_member;
5070 string name = parent_property.DeclaringType.Name + "." +
5071 parent_property.Name;
5073 MethodInfo get, set, parent_method;
5074 get = parent_property.GetGetMethod (true);
5075 set = parent_property.GetSetMethod (true);
5078 parent_method = get;
5079 else if (set != null)
5080 parent_method = set;
5082 throw new Exception ("Internal error!");
5084 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
5087 if ((ModFlags & Modifiers.NEW) == 0) {
5088 Type parent_type = TypeManager.TypeToCoreType (
5089 parent_property.PropertyType);
5091 if (parent_type != MemberType) {
5093 508, Location, container.MakeName (Name) + ": cannot " +
5094 "change return type when overriding " +
5095 "inherited member " + name);
5099 } else if (parent_member == null){
5100 if ((ModFlags & Modifiers.NEW) != 0)
5101 WarningNotHiding (container);
5103 if ((ModFlags & Modifiers.OVERRIDE) != 0){
5104 if (this is Indexer)
5105 Report.Error (115, Location,
5106 container.MakeName (Name) +
5107 " no suitable indexers found to override");
5109 Report.Error (115, Location,
5110 container.MakeName (Name) +
5111 " no suitable properties found to override");
5118 public override void Emit (TypeContainer tc)
5121 // The PropertyBuilder can be null for explicit implementations, in that
5122 // case, we do not actually emit the ".property", so there is nowhere to
5123 // put the attribute
5125 if (PropertyBuilder != null && OptAttributes != null)
5126 OptAttributes.Emit (ec, this);
5137 protected override string[] ValidAttributeTargets {
5139 return attribute_targets;
5144 public class Property : PropertyBase, IIteratorContainer {
5145 const int AllowedModifiers =
5148 Modifiers.PROTECTED |
5149 Modifiers.INTERNAL |
5153 Modifiers.OVERRIDE |
5154 Modifiers.ABSTRACT |
5157 Modifiers.METHOD_YIELDS |
5160 const int AllowedInterfaceModifiers =
5163 public Property (DeclSpace ds, Expression type, int mod_flags, bool is_iface,
5164 string name, Attributes attrs, Accessor get_block,
5165 Accessor set_block, Location loc)
5166 : base (ds, type, mod_flags,
5167 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
5168 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
5171 if (get_block != null)
5172 Get = new GetMethod (this, get_block);
5174 if (set_block != null)
5175 Set = new SetMethod (this, set_block);
5178 public override bool Define (TypeContainer container)
5180 if (!DoDefine (container))
5183 if (!CheckBase (container))
5186 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
5190 GetBuilder = Get.Define (container);
5191 if (GetBuilder == null)
5195 // Setup iterator if we are one
5197 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
5198 IteratorHandler ih = new IteratorHandler (
5199 "get", container, MemberType,
5200 TypeManager.NoTypes, Get.ParameterInfo, ModFlags, Location);
5202 Block new_block = ih.Setup (block);
5203 if (new_block == null)
5210 SetBuilder = Set.Define (container);
5211 if (SetBuilder == null)
5214 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
5217 // FIXME - PropertyAttributes.HasDefault ?
5219 PropertyAttributes prop_attr = PropertyAttributes.None;
5221 prop_attr |= PropertyAttributes.RTSpecialName |
5222 PropertyAttributes.SpecialName;
5224 if (!IsExplicitImpl){
5225 PropertyBuilder = container.TypeBuilder.DefineProperty (
5226 Name, prop_attr, MemberType, null);
5229 PropertyBuilder.SetGetMethod (GetBuilder);
5232 PropertyBuilder.SetSetMethod (SetBuilder);
5235 // HACK for the reasons exposed above
5237 if (!TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder)) {
5240 "Class `" + container.Name +
5241 "' already contains a definition for the property `" +
5249 public void SetYields ()
5251 ModFlags |= Modifiers.METHOD_YIELDS;
5256 /// Gigantic workaround for lameness in SRE follows :
5257 /// This class derives from EventInfo and attempts to basically
5258 /// wrap around the EventBuilder so that FindMembers can quickly
5259 /// return this in it search for members
5261 public class MyEventBuilder : EventInfo {
5264 // We use this to "point" to our Builder which is
5265 // not really a MemberInfo
5267 EventBuilder MyBuilder;
5270 // We "catch" and wrap these methods
5272 MethodInfo raise, remove, add;
5274 EventAttributes attributes;
5275 Type declaring_type, reflected_type, event_type;
5280 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
5282 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
5284 // And now store the values in our own fields.
5286 declaring_type = type_builder;
5288 reflected_type = type_builder;
5290 attributes = event_attr;
5293 this.event_type = event_type;
5297 // Methods that you have to override. Note that you only need
5298 // to "implement" the variants that take the argument (those are
5299 // the "abstract" methods, the others (GetAddMethod()) are
5302 public override MethodInfo GetAddMethod (bool nonPublic)
5307 public override MethodInfo GetRemoveMethod (bool nonPublic)
5312 public override MethodInfo GetRaiseMethod (bool nonPublic)
5318 // These methods make "MyEventInfo" look like a Builder
5320 public void SetRaiseMethod (MethodBuilder raiseMethod)
5322 raise = raiseMethod;
5323 MyBuilder.SetRaiseMethod (raiseMethod);
5326 public void SetRemoveOnMethod (MethodBuilder removeMethod)
5328 remove = removeMethod;
5329 MyBuilder.SetRemoveOnMethod (removeMethod);
5332 public void SetAddOnMethod (MethodBuilder addMethod)
5335 MyBuilder.SetAddOnMethod (addMethod);
5338 public void SetCustomAttribute (CustomAttributeBuilder cb)
5340 MyBuilder.SetCustomAttribute (cb);
5343 public override object [] GetCustomAttributes (bool inherit)
5345 // FIXME : There's nothing which can be seemingly done here because
5346 // we have no way of getting at the custom attribute objects of the
5351 public override object [] GetCustomAttributes (Type t, bool inherit)
5353 // FIXME : Same here !
5357 public override bool IsDefined (Type t, bool b)
5362 public override EventAttributes Attributes {
5368 public override string Name {
5374 public override Type DeclaringType {
5376 return declaring_type;
5380 public override Type ReflectedType {
5382 return reflected_type;
5386 public Type EventType {
5392 public void SetUsed ()
5394 if (my_event != null)
5395 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
5400 /// For case when event is declared like property (with add and remove accessors).
5402 public class EventProperty: Event {
5404 static string[] attribute_targets = new string [] { "event", "property" };
5406 public EventProperty (DeclSpace ds, Expression type, int mod_flags, bool is_iface, string name,
5407 Object init, Attributes attrs, Accessor add, Accessor remove, Location loc)
5408 : base (ds, type, mod_flags, is_iface, name, init, attrs, loc)
5410 Add = new AddDelegateMethod (this, add);
5411 Remove = new RemoveDelegateMethod (this, remove);
5414 protected override string[] ValidAttributeTargets {
5416 return attribute_targets;
5422 /// Event is declared like field.
5424 public class EventField: Event {
5426 static string[] attribute_targets = new string [] { "event", "field", "method" };
5428 public EventField (DeclSpace ds, Expression type, int mod_flags, bool is_iface, string name,
5429 Object init, Attributes attrs, Location loc)
5430 : base (ds, type, mod_flags, is_iface, name, init, attrs, loc)
5432 Add = new AddDelegateMethod (this);
5433 Remove = new RemoveDelegateMethod (this);
5436 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5438 if (a.Target == "field") {
5439 FieldBuilder.SetCustomAttribute (cb);
5443 if (a.Target == "method") {
5444 AddBuilder.SetCustomAttribute (cb);
5445 RemoveBuilder.SetCustomAttribute (cb);
5449 base.ApplyAttributeBuilder (a, cb);
5452 protected override string[] ValidAttributeTargets {
5454 return attribute_targets;
5459 public abstract class Event : FieldBase {
5461 protected sealed class AddDelegateMethod: DelegateMethod
5463 public AddDelegateMethod (Event method):
5468 public AddDelegateMethod (Event method, Accessor accessor):
5469 base (method, accessor)
5473 public override string MethodName {
5475 return "add_" + method.ShortName;
5479 protected override MethodInfo DelegateMethodInfo {
5481 return TypeManager.delegate_combine_delegate_delegate;
5487 protected sealed class RemoveDelegateMethod: DelegateMethod
5489 public RemoveDelegateMethod (Event method):
5494 public RemoveDelegateMethod (Event method, Accessor accessor):
5495 base (method, accessor)
5499 public override string MethodName {
5501 return "remove_" + method.ShortName;
5505 protected override MethodInfo DelegateMethodInfo {
5507 return TypeManager.delegate_remove_delegate_delegate;
5513 public abstract class DelegateMethod: Attributable, IMethodData
5515 protected readonly Event method;
5516 protected MethodData method_data;
5518 ReturnParameter return_attributes;
5519 ImplicitParameter param_attr;
5521 static string[] attribute_targets = new string [] { "method", "param", "return" };
5523 public DelegateMethod (Event method):
5526 this.method = method;
5529 public DelegateMethod (Event method, Accessor accessor):
5530 base (accessor.Attributes)
5532 this.method = method;
5533 this.block = accessor.Block;
5536 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5538 if (a.Target == "return") {
5539 if (return_attributes == null)
5540 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5542 return_attributes.ApplyAttributeBuilder (a, cb);
5546 if (a.Target == "param") {
5547 if (param_attr == null)
5548 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5550 param_attr.ApplyAttributeBuilder (a, cb);
5554 method_data.MethodBuilder.SetCustomAttribute (cb);
5557 public override AttributeTargets AttributeTargets {
5559 return AttributeTargets.Method;
5563 public override bool IsClsCompliaceRequired(DeclSpace ds)
5565 return method.IsClsCompliaceRequired (ds);
5568 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
5570 method_data = new MethodData (method, ip, method.ModFlags,
5571 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
5573 if (!method_data.Define (container))
5576 MethodBuilder mb = method_data.MethodBuilder;
5577 mb.DefineParameter (1, ParameterAttributes.None, "value");
5581 #region IMethodData Members
5583 public Block Block {
5589 public CallingConventions CallingConventions {
5591 return CallingConventions.Standard;
5595 public void Emit (TypeContainer tc)
5597 if (block != null) {
5598 method_data.Emit (tc, this);
5603 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
5604 EmitContext ec = CreateEmitContext (tc, ig);
5605 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
5607 if ((method.ModFlags & Modifiers.STATIC) != 0) {
5608 ig.Emit (OpCodes.Ldsfld, field_info);
5609 ig.Emit (OpCodes.Ldarg_0);
5610 ig.Emit (OpCodes.Call, DelegateMethodInfo);
5611 ig.Emit (OpCodes.Castclass, method.MemberType);
5612 ig.Emit (OpCodes.Stsfld, field_info);
5614 ig.Emit (OpCodes.Ldarg_0);
5615 ig.Emit (OpCodes.Ldarg_0);
5616 ig.Emit (OpCodes.Ldfld, field_info);
5617 ig.Emit (OpCodes.Ldarg_1);
5618 ig.Emit (OpCodes.Call, DelegateMethodInfo);
5619 ig.Emit (OpCodes.Castclass, method.MemberType);
5620 ig.Emit (OpCodes.Stfld, field_info);
5622 ig.Emit (OpCodes.Ret);
5625 public string GetSignatureForError (TypeContainer tc)
5627 return String.Concat (tc.Name, '.', method.Name);
5630 protected abstract MethodInfo DelegateMethodInfo { get; }
5632 public Type[] ParameterTypes {
5634 return new Type[] { method.MemberType };
5638 public Type ReturnType {
5640 return TypeManager.void_type;
5644 public Location Location {
5646 return method.Location;
5650 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
5652 return new EmitContext (tc, method.ds, Location, ig, ReturnType, method.ModFlags, false);
5655 public ObsoleteAttribute GetObsoleteAttribute ()
5657 return method.GetObsoleteAttribute (method.ds);
5660 public bool IsExcluded (EmitContext ec)
5665 public abstract string MethodName { get; }
5669 protected override string[] ValidAttributeTargets {
5671 return attribute_targets;
5677 const int AllowedModifiers =
5680 Modifiers.PROTECTED |
5681 Modifiers.INTERNAL |
5686 Modifiers.OVERRIDE |
5690 const int AllowedInterfaceModifiers =
5693 protected DelegateMethod Add, Remove;
5694 public MyEventBuilder EventBuilder;
5695 public MethodBuilder AddBuilder, RemoveBuilder;
5696 public DeclSpace ds;
5698 public Event (DeclSpace ds, Expression type, int mod_flags, bool is_iface, string name,
5699 Object init, Attributes attrs, Location loc)
5700 : base (type, mod_flags, is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
5701 name, init, attrs, loc)
5703 IsInterface = is_iface;
5707 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5709 EventBuilder.SetCustomAttribute (cb);
5712 public override AttributeTargets AttributeTargets {
5714 return AttributeTargets.Event;
5718 public override bool Define (TypeContainer container)
5720 EventAttributes e_attr;
5722 e_attr = EventAttributes.None;
5724 e_attr = EventAttributes.RTSpecialName |
5725 EventAttributes.SpecialName;
5727 if (!DoDefine (container))
5730 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
5731 Report.Error (74, Location, "'" + container.Name + "." + Name +
5732 "': abstract event can not have an initializer");
5736 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
5737 Report.Error (66, Location, "'" + container.Name + "." + Name +
5738 "' : event must be of a delegate type");
5742 Parameter [] parms = new Parameter [1];
5743 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
5744 InternalParameters ip = new InternalParameters (
5745 container, new Parameters (parms, null, Location));
5747 if (!CheckBase (container))
5751 // Now define the accessors
5754 AddBuilder = Add.Define (container, ip);
5755 if (AddBuilder == null)
5758 RemoveBuilder = Remove.Define (container, ip);
5759 if (RemoveBuilder == null)
5762 if (!IsExplicitImpl){
5763 EventBuilder = new MyEventBuilder (this,
5764 container.TypeBuilder, Name, e_attr, MemberType);
5766 if (Add.Block == null && Remove.Block == null &&
5768 FieldBuilder = container.TypeBuilder.DefineField (
5770 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
5771 TypeManager.RegisterPrivateFieldOfEvent (
5772 (EventInfo) EventBuilder, FieldBuilder);
5773 TypeManager.RegisterFieldBase (FieldBuilder, this);
5776 EventBuilder.SetAddOnMethod (AddBuilder);
5777 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
5779 if (!TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder)) {
5780 Report.Error (111, Location,
5781 "Class `" + container.Name +
5782 "' already contains a definition for the event `" +
5791 public override void Emit (TypeContainer tc)
5793 if (OptAttributes != null) {
5794 EmitContext ec = new EmitContext (tc, Location, null, MemberType, ModFlags);
5795 OptAttributes.Emit (ec, this);
5808 // FIXME: This does not handle:
5810 // int INTERFACENAME [ args ]
5815 // int this [ args ]
5817 public class Indexer : PropertyBase {
5819 class GetIndexerMethod: GetMethod
5821 public GetIndexerMethod (MethodCore method, Accessor accessor):
5822 base (method, accessor)
5826 public override Type[] ParameterTypes {
5828 return method.ParameterTypes;
5833 class SetIndexerMethod: SetMethod
5835 readonly Parameters parameters;
5837 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
5838 base (method, accessor)
5840 this.parameters = parameters;
5843 public override Type[] ParameterTypes {
5845 int top = method.ParameterTypes.Length;
5846 Type [] set_pars = new Type [top + 1];
5847 method.ParameterTypes.CopyTo (set_pars, 0);
5848 set_pars [top] = method.MemberType;
5853 protected override InternalParameters GetParameterInfo (TypeContainer container)
5855 Parameter [] fixed_parms = parameters.FixedParameters;
5857 if (fixed_parms == null){
5858 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
5859 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
5860 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
5862 // Here is the problem: the `value' parameter has
5863 // to come *after* the array parameter in the declaration
5865 // X (object [] x, Type value)
5868 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
5869 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
5873 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
5875 fixed_parms.CopyTo (tmp, 0);
5876 tmp [fixed_parms.Length] = new Parameter (
5877 method.Type, "value", Parameter.Modifier.NONE, null);
5879 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
5881 return new InternalParameters (container, set_formal_params);
5887 const int AllowedModifiers =
5890 Modifiers.PROTECTED |
5891 Modifiers.INTERNAL |
5895 Modifiers.OVERRIDE |
5900 const int AllowedInterfaceModifiers =
5903 public string IndexerName;
5904 public string InterfaceIndexerName;
5907 // Are we implementing an interface ?
5909 public Indexer (DeclSpace ds, Expression type, string int_type, int mod_flags,
5910 bool is_iface, Parameters parameters, Attributes attrs,
5911 Accessor get_block, Accessor set_block, Location loc)
5912 : base (ds, type, mod_flags,
5913 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
5914 is_iface, "", parameters, attrs, loc)
5916 ExplicitInterfaceName = int_type;
5918 if (get_block != null)
5919 Get = new GetIndexerMethod (this, get_block);
5921 if (set_block != null)
5922 Set = new SetIndexerMethod (this, parameters, set_block);
5925 public override bool Define (TypeContainer container)
5927 PropertyAttributes prop_attr =
5928 PropertyAttributes.RTSpecialName |
5929 PropertyAttributes.SpecialName;
5931 if (!DoDefine (container))
5934 if (OptAttributes != null)
5935 IndexerName = OptAttributes.ScanForIndexerName (ec);
5937 if (IndexerName == null)
5938 IndexerName = "Item";
5940 if (! Tokenizer.IsValidIdentifier (IndexerName)) {
5941 Report.Error (633, Location, "The IndexerName specified is an invalid identifier");
5945 if (IsExplicitImpl) {
5946 Report.Error (592, Location,
5947 "Attribute 'IndexerName' is not valid on explicit implementations.");
5952 ShortName = IndexerName;
5953 if (IsExplicitImpl) {
5954 InterfaceIndexerName = TypeManager.IndexerPropertyName (InterfaceType);
5955 Name = InterfaceType.FullName + "." + IndexerName;
5957 InterfaceIndexerName = IndexerName;
5961 if (!CheckNameCollision (container))
5964 if (!CheckBase (container))
5967 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
5969 GetBuilder = Get.Define (container);
5970 if (GetBuilder == null)
5975 SetBuilder = Set.Define (container);
5976 if (SetBuilder == null)
5981 // Now name the parameters
5983 Parameter [] p = Parameters.FixedParameters;
5987 for (i = 0; i < p.Length; ++i) {
5989 GetBuilder.DefineParameter (
5990 i + 1, p [i].Attributes, p [i].Name);
5993 SetBuilder.DefineParameter (
5994 i + 1, p [i].Attributes, p [i].Name);
5998 SetBuilder.DefineParameter (
5999 i + 1, ParameterAttributes.None, "value");
6001 if (i != ParameterTypes.Length) {
6002 Parameter array_param = Parameters.ArrayParameter;
6004 SetBuilder.DefineParameter (
6005 i + 1, array_param.Attributes, array_param.Name);
6010 // Define the PropertyBuilder if one of the following conditions are met:
6011 // a) we're not implementing an interface indexer.
6012 // b) the indexer has a different IndexerName and this is no
6013 // explicit interface implementation.
6015 if (!IsExplicitImpl) {
6016 PropertyBuilder = container.TypeBuilder.DefineProperty (
6017 IndexerName, prop_attr, MemberType, ParameterTypes);
6020 PropertyBuilder.SetGetMethod (GetBuilder);
6023 PropertyBuilder.SetSetMethod (SetBuilder);
6025 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder,
6032 bool CheckNameCollision (TypeContainer container) {
6033 switch (VerifyName (container)){
6034 case DeclSpace.AdditionResult.NameExists:
6035 Report.Error (102, Location, "The container '{0}' already contains a definition for '{1}'", container.GetSignatureForError (), Name);
6038 case DeclSpace.AdditionResult.Success:
6041 throw new NotImplementedException ();
6044 DeclSpace.AdditionResult VerifyName (TypeContainer container) {
6045 if (!AddIndexer (container, container.Name + "." + Name))
6046 return DeclSpace.AdditionResult.NameExists;
6049 if (!AddIndexer (container, container.Name + ".get_" + Name))
6050 return DeclSpace.AdditionResult.NameExists;
6054 if (!AddIndexer (container, container.Name + ".set_" + Name))
6055 return DeclSpace.AdditionResult.NameExists;
6057 return DeclSpace.AdditionResult.Success;
6060 bool AddIndexer (TypeContainer container, string fullname)
6062 object value = container.GetDefinition (fullname);
6064 if (value != null) {
6065 return value.GetType () != GetType () ? false : true;
6068 container.DefineName (fullname, this);
6072 public override string GetSignatureForError ()
6074 return TypeManager.CSharpSignature (PropertyBuilder, true);
6077 protected override string RealMethodName {
6084 public class Operator : MemberBase, IIteratorContainer {
6086 const int AllowedModifiers =
6092 const int RequiredModifiers =
6096 public enum OpType : byte {
6106 // Unary and Binary operators
6129 // Implicit and Explicit
6134 public readonly OpType OperatorType;
6135 public readonly Expression ReturnType;
6136 public readonly Expression FirstArgType, SecondArgType;
6137 public readonly string FirstArgName, SecondArgName;
6139 public MethodBuilder OperatorMethodBuilder;
6141 public string MethodName;
6142 public Method OperatorMethod;
6144 static string[] attribute_targets = new string [] { "method", "return" };
6146 public Operator (OpType type, Expression ret_type, int mod_flags,
6147 Expression arg1type, string arg1name,
6148 Expression arg2type, string arg2name,
6149 Block block, Attributes attrs, Location loc)
6150 : base (ret_type, mod_flags, AllowedModifiers, Modifiers.PUBLIC, "", attrs, loc)
6152 OperatorType = type;
6153 Name = "op_" + OperatorType;
6154 ReturnType = ret_type;
6155 FirstArgType = arg1type;
6156 FirstArgName = arg1name;
6157 SecondArgType = arg2type;
6158 SecondArgName = arg2name;
6162 string Prototype (TypeContainer container)
6164 return container.Name + ".operator " + OperatorType + " (" + FirstArgType + "," +
6165 SecondArgType + ")";
6168 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6170 OperatorMethod.ApplyAttributeBuilder (a, cb);
6173 public override AttributeTargets AttributeTargets {
6175 return AttributeTargets.Method;
6179 public override bool Define (TypeContainer container)
6182 MethodName = "op_" + OperatorType;
6184 if (SecondArgType != null)
6187 Parameter [] param_list = new Parameter [length];
6189 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
6192 "User defined operators `" +
6193 Prototype (container) +
6194 "' must be declared static and public");
6198 param_list[0] = new Parameter (FirstArgType, FirstArgName,
6199 Parameter.Modifier.NONE, null);
6200 if (SecondArgType != null)
6201 param_list[1] = new Parameter (SecondArgType, SecondArgName,
6202 Parameter.Modifier.NONE, null);
6204 OperatorMethod = new Method (
6205 container, ReturnType, ModFlags, false, MethodName,
6206 new Parameters (param_list, null, Location),
6207 OptAttributes, Location);
6209 OperatorMethod.Block = Block;
6210 OperatorMethod.IsOperator = true;
6211 OperatorMethod.Define (container);
6213 if (OperatorMethod.MethodBuilder == null)
6216 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
6218 Type [] param_types = OperatorMethod.ParameterTypes;
6219 Type declaring_type = OperatorMethodBuilder.DeclaringType;
6220 Type return_type = OperatorMethod.GetReturnType ();
6221 Type first_arg_type = param_types [0];
6223 // Rules for conversion operators
6225 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
6226 if (first_arg_type == return_type && first_arg_type == declaring_type){
6229 "User-defined conversion cannot take an object of the " +
6230 "enclosing type and convert to an object of the enclosing" +
6235 if (first_arg_type != declaring_type && return_type != declaring_type){
6238 "User-defined conversion must convert to or from the " +
6243 if (first_arg_type == TypeManager.object_type ||
6244 return_type == TypeManager.object_type){
6247 "User-defined conversion cannot convert to or from " +
6252 if (first_arg_type.IsInterface || return_type.IsInterface){
6255 "User-defined conversion cannot convert to or from an " +
6260 if (first_arg_type.IsSubclassOf (return_type) ||
6261 return_type.IsSubclassOf (first_arg_type)){
6264 "User-defined conversion cannot convert between types " +
6265 "that derive from each other");
6268 } else if (SecondArgType == null) {
6269 // Checks for Unary operators
6271 if (first_arg_type != declaring_type){
6274 "The parameter of a unary operator must be the " +
6279 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
6280 if (return_type != declaring_type){
6283 "The parameter and return type for ++ and -- " +
6284 "must be the containing type");
6290 if (OperatorType == OpType.True || OperatorType == OpType.False) {
6291 if (return_type != TypeManager.bool_type){
6294 "The return type of operator True or False " +
6301 // Checks for Binary operators
6303 if (first_arg_type != declaring_type &&
6304 param_types [1] != declaring_type){
6307 "One of the parameters of a binary operator must " +
6308 "be the containing type");
6316 public override void Emit (TypeContainer container)
6319 // abstract or extern methods have no bodies
6321 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6324 OperatorMethod.Emit (container);
6328 public static string GetName (OpType ot)
6331 case OpType.LogicalNot:
6333 case OpType.OnesComplement:
6335 case OpType.Increment:
6337 case OpType.Decrement:
6343 case OpType.Addition:
6345 case OpType.Subtraction:
6347 case OpType.UnaryPlus:
6349 case OpType.UnaryNegation:
6351 case OpType.Multiply:
6353 case OpType.Division:
6355 case OpType.Modulus:
6357 case OpType.BitwiseAnd:
6359 case OpType.BitwiseOr:
6361 case OpType.ExclusiveOr:
6363 case OpType.LeftShift:
6365 case OpType.RightShift:
6367 case OpType.Equality:
6369 case OpType.Inequality:
6371 case OpType.GreaterThan:
6373 case OpType.LessThan:
6375 case OpType.GreaterThanOrEqual:
6377 case OpType.LessThanOrEqual:
6379 case OpType.Implicit:
6381 case OpType.Explicit:
6387 public override string GetSignatureForError(TypeContainer tc)
6389 return Prototype (tc);
6392 public override string ToString ()
6394 Type return_type = OperatorMethod.GetReturnType();
6395 Type [] param_types = OperatorMethod.ParameterTypes;
6397 if (SecondArgType == null)
6398 return String.Format (
6399 "{0} operator {1}({2})",
6400 TypeManager.CSharpName (return_type),
6401 GetName (OperatorType),
6404 return String.Format (
6405 "{0} operator {1}({2}, {3})",
6406 TypeManager.CSharpName (return_type),
6407 GetName (OperatorType),
6408 param_types [0], param_types [1]);
6411 protected override string[] ValidAttributeTargets {
6413 return attribute_targets;
6417 public void SetYields ()
6419 ModFlags |= Modifiers.METHOD_YIELDS;
6424 // This is used to compare method signatures
6426 struct MethodSignature {
6428 public Type RetType;
6429 public Type [] Parameters;
6432 /// This delegate is used to extract methods which have the
6433 /// same signature as the argument
6435 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
6437 public MethodSignature (string name, Type ret_type, Type [] parameters)
6442 if (parameters == null)
6443 Parameters = TypeManager.NoTypes;
6445 Parameters = parameters;
6448 public override string ToString ()
6451 if (Parameters.Length != 0){
6452 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
6453 for (int i = 0; i < Parameters.Length; i++){
6454 sb.Append (Parameters [i]);
6455 if (i+1 < Parameters.Length)
6458 pars = sb.ToString ();
6461 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
6464 public override int GetHashCode ()
6466 return Name.GetHashCode ();
6469 public override bool Equals (Object o)
6471 MethodSignature other = (MethodSignature) o;
6473 if (other.Name != Name)
6476 if (other.RetType != RetType)
6479 if (Parameters == null){
6480 if (other.Parameters == null)
6485 if (other.Parameters == null)
6488 int c = Parameters.Length;
6489 if (other.Parameters.Length != c)
6492 for (int i = 0; i < c; i++)
6493 if (other.Parameters [i] != Parameters [i])
6499 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
6501 MethodSignature sig = (MethodSignature) filter_criteria;
6503 if (m.Name != sig.Name)
6507 MethodInfo mi = m as MethodInfo;
6508 PropertyInfo pi = m as PropertyInfo;
6511 ReturnType = mi.ReturnType;
6512 else if (pi != null)
6513 ReturnType = pi.PropertyType;
6518 // we use sig.RetType == null to mean `do not check the
6519 // method return value.
6521 if (sig.RetType != null)
6522 if (ReturnType != sig.RetType)
6527 args = TypeManager.GetArgumentTypes (mi);
6529 args = TypeManager.GetArgumentTypes (pi);
6530 Type [] sigp = sig.Parameters;
6532 if (args.Length != sigp.Length)
6535 for (int i = args.Length; i > 0; ){
6537 if (args [i] != sigp [i])