2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@gnome.org)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
12 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
14 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
15 // have fixed a remaining problem: not every AddXXXX was adding a
16 // fully qualified name.
18 // Now everyone registers a fully qualified name in the DeclSpace as
19 // being defined instead of the partial name.
21 // Downsides: we are slower than we need to be due to the excess
22 // copies and the names being registered this way.
24 // The reason for this is that we currently depend (on the corlib
25 // bootstrap for instance) that types are fully qualified, because
26 // we dump all the types in the namespace, and we should really have
27 // types inserted into the proper namespace, so we can only store the
28 // basenames in the defined_names array.
33 using System.Collections;
34 using System.Reflection;
35 using System.Reflection.Emit;
36 using System.Runtime.CompilerServices;
38 namespace Mono.CSharp {
41 /// This is the base class for structs and classes.
43 public class TypeContainer : DeclSpace, IMemberContainer {
44 // Holds a list of classes and structures
47 // Holds the list of properties
50 // Holds the list of enumerations
53 // Holds the list of delegates
56 // Holds the list of constructors
57 ArrayList instance_constructors;
59 // Holds the list of fields
62 // Holds a list of fields that have initializers
63 ArrayList initialized_fields;
65 // Holds a list of static fields that have initializers
66 ArrayList initialized_static_fields;
68 // Holds the list of constants
74 // Holds order in which interfaces must be closed
75 ArrayList interface_order;
86 // Holds the operators
89 // The emit context for toplevel objects.
93 // Pointers to the default constructor and the default static constructor
95 Constructor default_constructor;
96 Constructor default_static_constructor;
99 // Whether we have seen a static constructor for this class or not
101 bool have_static_constructor = false;
104 // Whether we have at least one non-static field
106 bool have_nonstatic_fields = false;
109 // This one is computed after we can distinguish interfaces
110 // from classes from the arraylist `type_bases'
112 string base_class_name;
114 ArrayList type_bases;
116 // Attributes for this type
117 protected Attributes attributes;
119 // Information in the case we are an attribute type
121 public AttributeTargets Targets = AttributeTargets.All;
122 public bool AllowMultiple = false;
123 public bool Inherited;
125 // The interfaces we implement.
128 // The parent member container and our member cache
129 IMemberContainer parent_container;
130 MemberCache member_cache;
133 // The indexer name for this class
135 public string IndexerName;
137 public TypeContainer (NamespaceEntry ns, TypeContainer parent, string name, Location l)
138 : base (ns, parent, name, l)
141 types = new ArrayList ();
148 base_class_name = null;
150 //Console.WriteLine ("New class " + name + " inside " + n);
153 public AdditionResult AddConstant (Const constant)
156 string basename = constant.Name;
157 string fullname = Name + "." + basename;
159 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
162 if (constants == null)
163 constants = new ArrayList ();
165 constants.Add (constant);
166 DefineName (fullname, constant);
168 return AdditionResult.Success;
171 public AdditionResult AddEnum (Mono.CSharp.Enum e)
175 if ((res = IsValid (e.Basename, e.Name)) != AdditionResult.Success)
179 enums = new ArrayList ();
182 DefineName (e.Name, e);
184 return AdditionResult.Success;
187 public AdditionResult AddClass (Class c)
190 string name = c.Basename;
192 if ((res = IsValid (name, c.Name)) != AdditionResult.Success)
195 DefineName (c.Name, c);
198 return AdditionResult.Success;
201 public AdditionResult AddStruct (Struct s)
204 string name = s.Basename;
206 if ((res = IsValid (name, s.Name)) != AdditionResult.Success)
209 DefineName (s.Name, s);
212 return AdditionResult.Success;
215 public AdditionResult AddDelegate (Delegate d)
218 string name = d.Basename;
220 if ((res = IsValid (name, d.Name)) != AdditionResult.Success)
223 if (delegates == null)
224 delegates = new ArrayList ();
226 DefineName (d.Name, d);
229 return AdditionResult.Success;
232 public AdditionResult AddMethod (Method method)
234 string basename = method.Name;
235 string fullname = Name + "." + basename;
237 Object value = defined_names [fullname];
239 if (value != null && (!(value is Method)))
240 return AdditionResult.NameExists;
242 if (basename == Basename)
243 return AdditionResult.EnclosingClash;
246 methods = new ArrayList ();
248 if (method.Name.IndexOf (".") != -1)
249 methods.Insert (0, method);
251 methods.Add (method);
254 DefineName (fullname, method);
256 return AdditionResult.Success;
259 public AdditionResult AddConstructor (Constructor c)
261 if (c.Name != Basename)
262 return AdditionResult.NotAConstructor;
264 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
267 have_static_constructor = true;
268 if (default_static_constructor != null){
269 Console.WriteLine ("I have a static constructor already");
270 Console.WriteLine (" " + default_static_constructor);
271 return AdditionResult.MethodExists;
274 default_static_constructor = c;
277 if (default_constructor != null)
278 return AdditionResult.MethodExists;
279 default_constructor = c;
282 if (instance_constructors == null)
283 instance_constructors = new ArrayList ();
285 instance_constructors.Add (c);
288 return AdditionResult.Success;
291 public AdditionResult AddInterface (Interface iface)
294 string name = iface.Basename;
296 if ((res = IsValid (name, iface.Name)) != AdditionResult.Success)
299 if (interfaces == null)
300 interfaces = new ArrayList ();
301 interfaces.Add (iface);
302 DefineName (iface.Name, iface);
304 return AdditionResult.Success;
307 public AdditionResult AddField (Field field)
310 string basename = field.Name;
311 string fullname = Name + "." + basename;
313 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
317 fields = new ArrayList ();
321 if (field.HasInitializer){
322 if ((field.ModFlags & Modifiers.STATIC) != 0){
323 if (initialized_static_fields == null)
324 initialized_static_fields = new ArrayList ();
326 initialized_static_fields.Add (field);
329 // We have not seen a static constructor,
330 // but we will provide static initialization of fields
332 have_static_constructor = true;
334 if (initialized_fields == null)
335 initialized_fields = new ArrayList ();
337 initialized_fields.Add (field);
341 if ((field.ModFlags & Modifiers.STATIC) == 0)
342 have_nonstatic_fields = true;
344 DefineName (fullname, field);
345 return AdditionResult.Success;
348 public AdditionResult AddProperty (Property prop)
351 string basename = prop.Name;
352 string fullname = Name + "." + basename;
354 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
357 if (properties == null)
358 properties = new ArrayList ();
360 if (prop.Name.IndexOf (".") != -1)
361 properties.Insert (0, prop);
363 properties.Add (prop);
364 DefineName (fullname, prop);
366 return AdditionResult.Success;
369 public AdditionResult AddEvent (Event e)
372 string basename = e.Name;
373 string fullname = Name + "." + basename;
375 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
379 events = new ArrayList ();
382 DefineName (fullname, e);
384 return AdditionResult.Success;
387 public AdditionResult AddIndexer (Indexer i)
389 if (indexers == null)
390 indexers = new ArrayList ();
392 if (i.InterfaceType != null)
393 indexers.Insert (0, i);
397 return AdditionResult.Success;
400 public AdditionResult AddOperator (Operator op)
402 if (operators == null)
403 operators = new ArrayList ();
407 return AdditionResult.Success;
410 public void RegisterOrder (Interface iface)
412 if (interface_order == null)
413 interface_order = new ArrayList ();
415 interface_order.Add (iface);
418 public ArrayList Types {
424 public ArrayList Methods {
430 public ArrayList Constants {
436 public ArrayList Interfaces {
444 return base_class_name;
448 public ArrayList Bases {
458 public ArrayList Fields {
468 public ArrayList InstanceConstructors {
470 return instance_constructors;
474 public ArrayList Properties {
480 public ArrayList Events {
486 public ArrayList Enums {
492 public ArrayList Indexers {
498 public ArrayList Operators {
504 public ArrayList Delegates {
510 public Attributes OptAttributes {
516 public bool HaveStaticConstructor {
518 return have_static_constructor;
522 public virtual TypeAttributes TypeAttr {
524 return Modifiers.TypeAttr (ModFlags, this);
529 // Emits the instance field initializers
531 public bool EmitFieldInitializers (EmitContext ec)
534 ILGenerator ig = ec.ig;
535 Expression instance_expr;
538 fields = initialized_static_fields;
539 instance_expr = null;
541 fields = initialized_fields;
542 instance_expr = new This (Location.Null).Resolve (ec);
548 foreach (Field f in fields){
549 Expression e = f.GetInitializerExpression (ec);
553 Location l = f.Location;
554 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
555 fe.InstanceExpression = instance_expr;
556 ExpressionStatement a = new Assign (fe, e, l);
558 a = a.ResolveStatement (ec);
562 a.EmitStatement (ec);
569 // Defines the default constructors
571 void DefineDefaultConstructor (bool is_static)
576 c = new Constructor (this, Basename, Parameters.EmptyReadOnlyParameters,
577 new ConstructorBaseInitializer (
578 null, Parameters.EmptyReadOnlyParameters,
583 mods = Modifiers.STATIC;
589 c.Block = new Block (null);
593 public void ReportStructInitializedInstanceError ()
595 string n = TypeBuilder.FullName;
597 foreach (Field f in initialized_fields){
600 "`" + n + "." + f.Name + "': can not have " +
601 "instance field initializers in structs");
606 /// The pending methods that need to be implemented (interfaces or abstract methods)
608 public PendingImplementation Pending;
611 /// This function computes the Base class and also the
612 /// list of interfaces that the class or struct @c implements.
614 /// The return value is an array (might be null) of
615 /// interfaces implemented (as Types).
617 /// The @parent argument is set to the parent object or null
618 /// if this is `System.Object'.
620 Type [] GetClassBases (bool is_class, out Type parent, out bool error)
622 ArrayList bases = Bases;
631 parent = TypeManager.value_type;
635 if (RootContext.StdLib)
636 parent = TypeManager.object_type;
637 else if (Name != "System.Object")
638 parent = TypeManager.object_type;
641 // If we are compiling our runtime,
642 // and we are defining ValueType, then our
643 // parent is `System.Object'.
645 if (!RootContext.StdLib && Name == "System.ValueType")
646 parent = TypeManager.object_type;
653 // Bases should be null if there are no bases at all
658 Expression name = (Expression) bases [0];
659 name = ResolveTypeExpr (name, false, Location);
666 Type first = name.Type;
672 parent = TypeManager.object_type;
678 if (first.IsValueType)
679 detail = " (a class can not inherit from a struct/enum)";
681 Report.Error (509, "class `"+ Name +
682 "': Cannot inherit from sealed class `"+
683 first + "'" + detail);
688 if (!AsAccessible (parent, ModFlags))
689 Report.Error (60, Location,
690 "Inconsistent accessibility: base class `" +
691 TypeManager.CSharpName (parent) + "' is less " +
692 "accessible than class `" +
700 base_class_name = parent.Name;
702 Type [] ifaces = new Type [count-start];
704 for (i = start, j = 0; i < count; i++, j++){
705 Expression name = (Expression) bases [i];
706 Expression resolved = ResolveTypeExpr (name, false, Location);
707 if (resolved == null)
710 bases [i] = resolved;
711 Type t = resolved.Type;
718 if (is_class == false && !t.IsInterface){
719 Report.Error (527, "In Struct `" + Name + "', type `"+
720 name +"' is not an interface");
727 Report.Error (527, "In Class `" + Name + "', type `"+
728 name+"' is not an interface");
734 for (int x = 0; x < j; x++) {
735 if (t == ifaces [x]) {
736 Report.Error (528, "`" + name + "' is already listed in interface list");
745 return TypeManager.ExpandInterfaces (ifaces);
751 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
753 public override TypeBuilder DefineType ()
758 if (TypeBuilder != null)
765 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
777 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
779 ifaces = GetClassBases (is_class, out parent, out error);
784 if (is_class && parent != null){
785 if (parent == TypeManager.enum_type ||
786 (parent == TypeManager.value_type && RootContext.StdLib) ||
787 parent == TypeManager.delegate_type ||
788 parent == TypeManager.array_type){
790 644, Location, "`" + Name + "' cannot inherit from " +
791 "special class `" + TypeManager.CSharpName (parent) + "'");
797 if (!is_class && TypeManager.value_type == null)
798 throw new Exception ();
800 TypeAttributes type_attributes = TypeAttr;
803 if (TypeManager.NamespaceClash (Name, Location)) {
808 ModuleBuilder builder = CodeGen.ModuleBuilder;
809 TypeBuilder = builder.DefineType (
810 Name, type_attributes, parent, ifaces);
813 TypeBuilder builder = Parent.DefineType ();
817 TypeBuilder = builder.DefineNestedType (
818 Basename, type_attributes, parent, ifaces);
822 // Structs with no fields need to have at least one byte.
823 // The right thing would be to set the PackingSize in a DefineType
824 // but there are no functions that allow interfaces *and* the size to
828 if (!is_class && !have_nonstatic_fields){
829 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
830 FieldAttributes.Private);
831 // add interfaces that were not added at type creation
832 if (ifaces != null) {
833 foreach (Type i in ifaces)
834 TypeBuilder.AddInterfaceImplementation (i);
839 // Finish the setup for the EmitContext
841 ec.ContainerType = TypeBuilder;
843 TypeManager.AddUserType (Name, TypeBuilder, this, ifaces);
845 if ((parent != null) &&
846 (parent == TypeManager.attribute_type ||
847 parent.IsSubclassOf (TypeManager.attribute_type))) {
848 RootContext.RegisterAttribute (this);
849 TypeManager.RegisterAttrType (TypeBuilder, this);
851 RootContext.RegisterOrder (this);
853 if (Interfaces != null) {
854 foreach (Interface iface in Interfaces)
855 if (iface.DefineType () == null) {
862 foreach (TypeContainer tc in Types)
863 if (tc.DefineType () == null) {
869 if (Delegates != null) {
870 foreach (Delegate d in Delegates)
871 if (d.DefineType () == null) {
878 foreach (Enum en in Enums)
879 if (en.DefineType () == null) {
891 /// Defines the MemberCore objects that are in the `list' Arraylist
893 /// The `defined_names' array contains a list of members defined in
896 static ArrayList remove_list = new ArrayList ();
897 void DefineMembers (ArrayList list, MemberInfo [] defined_names)
901 remove_list.Clear ();
903 foreach (MemberCore mc in list){
905 if (defined_names != null)
906 idx = Array.BinarySearch (defined_names, mc.Name, mif_compare);
911 if (RootContext.WarningLevel >= 4){
912 if ((mc.ModFlags & Modifiers.NEW) != 0)
913 Warning_KeywordNewNotRequired (mc.Location, mc);
915 } else if (mc is MethodCore)
916 ((MethodCore) mc).OverridesSomething = true;
918 if (!mc.Define (this)){
919 remove_list.Add (mc);
926 MemberInfo match = defined_names [idx];
928 if (match is PropertyInfo && ((mc.ModFlags & Modifiers.OVERRIDE) != 0))
932 // If we are both methods, let the method resolution emit warnings
934 if (match is MethodBase && mc is MethodCore)
937 if ((mc.ModFlags & Modifiers.NEW) == 0) {
939 if (!(match is EventInfo)) {
940 Error_EventCanOnlyOverrideEvent (mc.Location, defined_names [idx]);
944 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
948 Warning_KeywordNewRequired (mc.Location, defined_names [idx]);
952 foreach (object o in remove_list)
955 remove_list.Clear ();
959 // Defines the indexers, and also verifies that the IndexerNameAttribute in the
960 // class is consisten. Either it is `Item' or it is the name defined by all the
961 // indexers with the `IndexerName' attribute.
963 // Turns out that the IndexerNameAttribute is applied to each indexer,
964 // but it is never emitted, instead a DefaultName attribute is attached
967 void DefineIndexers ()
969 string class_indexer_name = null;
972 // If there's both an explicit and an implicit interface implementation, the
973 // explicit one actually implements the interface while the other one is just
974 // a normal indexer. See bug #37714.
976 ArrayList list = new ArrayList ();
977 foreach (Indexer i in Indexers){
978 if (i.ExplicitInterfaceName != null)
981 foreach (Indexer i in Indexers){
982 if (i.ExplicitInterfaceName == null)
986 foreach (Indexer i in list){
991 name = i.IndexerName;
993 if (i.InterfaceType != null)
996 if (class_indexer_name == null){
997 class_indexer_name = name;
1001 if (name == class_indexer_name)
1005 668, "Two indexers have different names, " +
1006 " you should use the same name for all your indexers");
1008 if (class_indexer_name == null)
1009 class_indexer_name = "Item";
1010 IndexerName = class_indexer_name;
1013 static void Error_KeywordNotAllowed (Location loc)
1015 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1019 /// Populates our TypeBuilder with fields and methods
1021 public override bool DefineMembers (TypeContainer container)
1023 MemberInfo [] defined_names = null;
1025 if (interface_order != null){
1026 foreach (Interface iface in interface_order)
1027 if ((iface.ModFlags & Modifiers.NEW) == 0)
1028 iface.DefineMembers (this);
1030 Error_KeywordNotAllowed (iface.Location);
1033 if (RootContext.WarningLevel > 1){
1037 // This code throws an exception in the comparer
1038 // I guess the string is not an object?
1040 ptype = TypeBuilder.BaseType;
1042 defined_names = (MemberInfo []) FindMembers (
1043 ptype, MemberTypes.All & ~MemberTypes.Constructor,
1044 BindingFlags.Public | BindingFlags.Instance |
1045 BindingFlags.Static, null, null);
1047 Array.Sort (defined_names, mif_compare);
1051 Class pclass = Parent as Class;
1052 if (pclass != null) {
1053 string pname = null;
1055 Type t = pclass.TypeBuilder.BaseType;
1056 while ((t != null) && (ptype == null)) {
1057 pname = t.FullName + "." + Basename;
1058 ptype = RootContext.LookupType (this, pname, true, Location.Null);
1062 if ((ModFlags & Modifiers.NEW) != 0) {
1064 Report.Warning (109, Location, "The member '" + Name + "' does not hide an " +
1065 "inherited member. The keyword new is not required.");
1066 } else if (ptype != null) {
1067 Report.Warning (108, Location, "The keyword new is required on `" +
1068 Name + "' because it hides inherited member '" +
1071 } else if ((ModFlags & Modifiers.NEW) != 0)
1072 Error_KeywordNotAllowed (Location);
1074 if (constants != null)
1075 DefineMembers (constants, defined_names);
1078 DefineMembers (fields, defined_names);
1080 if ((RootContext.WarningLevel >= 4) && (fields != null)) {
1081 foreach (Field f in fields) {
1082 if (((f.ModFlags & Modifiers.READONLY) != 0) && !f.IsAssigned)
1083 Report.Warning (649, "Field `" + MakeFQN (Name, f.Name) + "; is never " +
1084 "assigned and will ever have its default value");
1089 if (instance_constructors == null){
1090 if (default_constructor == null)
1091 DefineDefaultConstructor (false);
1094 if (initialized_static_fields != null &&
1095 default_static_constructor == null)
1096 DefineDefaultConstructor (true);
1099 if (this is Struct){
1101 // Structs can not have initialized instance
1104 if (initialized_static_fields != null &&
1105 default_static_constructor == null)
1106 DefineDefaultConstructor (true);
1108 if (initialized_fields != null)
1109 ReportStructInitializedInstanceError ();
1112 Pending = PendingImplementation.GetPendingImplementations (this);
1115 // Constructors are not in the defined_names array
1117 if (instance_constructors != null)
1118 DefineMembers (instance_constructors, null);
1120 if (default_static_constructor != null)
1121 default_static_constructor.Define (this);
1123 if (methods != null)
1124 DefineMembers (methods, defined_names);
1126 if (properties != null)
1127 DefineMembers (properties, defined_names);
1130 DefineMembers (events, defined_names);
1132 if (indexers != null) {
1135 IndexerName = "Item";
1137 if (operators != null){
1138 DefineMembers (operators, null);
1140 CheckPairedOperators ();
1144 DefineMembers (enums, defined_names);
1146 if (delegates != null)
1147 DefineMembers (delegates, defined_names);
1150 if (TypeBuilder.BaseType != null)
1151 parent_container = TypeManager.LookupMemberContainer (TypeBuilder.BaseType);
1153 member_cache = new MemberCache (this);
1160 public override bool Define (TypeContainer container)
1162 if (interface_order != null){
1163 foreach (Interface iface in interface_order)
1164 if ((iface.ModFlags & Modifiers.NEW) == 0)
1165 iface.Define (this);
1172 /// This function is based by a delegate to the FindMembers routine
1174 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1180 /// This filter is used by FindMembers, and we just keep
1181 /// a global for the filter to `AlwaysAccept'
1183 static MemberFilter accepting_filter;
1187 /// A member comparission method based on name only
1189 static IComparer mif_compare;
1191 static TypeContainer ()
1193 accepting_filter = new MemberFilter (AlwaysAccept);
1194 mif_compare = new MemberInfoCompare ();
1198 /// This method returns the members of this type just like Type.FindMembers would
1199 /// Only, we need to use this for types which are _being_ defined because MS'
1200 /// implementation can't take care of that.
1203 // FIXME: return an empty static array instead of null, that cleans up
1204 // some code and is consistent with some coding conventions I just found
1208 // Notice that in various cases we check if our field is non-null,
1209 // something that would normally mean that there was a bug elsewhere.
1211 // The problem happens while we are defining p-invoke methods, as those
1212 // will trigger a FindMembers, but this happens before things are defined
1214 // Since the whole process is a no-op, it is fine to check for null here.
1216 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1217 MemberFilter filter, object criteria)
1219 ArrayList members = new ArrayList ();
1222 if ((bf & BindingFlags.Public) != 0)
1223 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1225 if ((bf & BindingFlags.NonPublic) != 0)
1226 modflags |= Modifiers.PRIVATE;
1228 int static_mask = 0, static_flags = 0;
1229 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1230 case BindingFlags.Static:
1231 static_mask = static_flags = Modifiers.STATIC;
1234 case BindingFlags.Instance:
1235 static_mask = Modifiers.STATIC;
1240 static_mask = static_flags = 0;
1244 Timer.StartTimer (TimerType.TcFindMembers);
1247 filter = accepting_filter;
1249 if ((mt & MemberTypes.Field) != 0) {
1250 if (fields != null) {
1251 foreach (Field f in fields) {
1252 if ((f.ModFlags & modflags) == 0)
1254 if ((f.ModFlags & static_mask) != static_flags)
1257 FieldBuilder fb = f.FieldBuilder;
1258 if (fb != null && filter (fb, criteria) == true)
1263 if (constants != null) {
1264 foreach (Const con in constants) {
1265 if ((con.ModFlags & modflags) == 0)
1267 if ((con.ModFlags & static_mask) != static_flags)
1270 FieldBuilder fb = con.FieldBuilder;
1271 if (fb != null && filter (fb, criteria) == true)
1277 if ((mt & MemberTypes.Method) != 0) {
1278 if (methods != null) {
1279 foreach (Method m in methods) {
1280 if ((m.ModFlags & modflags) == 0)
1282 if ((m.ModFlags & static_mask) != static_flags)
1285 MethodBuilder mb = m.MethodBuilder;
1287 if (mb != null && filter (mb, criteria) == true)
1292 if (operators != null){
1293 foreach (Operator o in operators) {
1294 if ((o.ModFlags & modflags) == 0)
1296 if ((o.ModFlags & static_mask) != static_flags)
1299 MethodBuilder ob = o.OperatorMethodBuilder;
1300 if (ob != null && filter (ob, criteria) == true)
1305 if (properties != null){
1306 foreach (Property p in properties){
1307 if ((p.ModFlags & modflags) == 0)
1309 if ((p.ModFlags & static_mask) != static_flags)
1315 if (b != null && filter (b, criteria) == true)
1319 if (b != null && filter (b, criteria) == true)
1324 if (indexers != null){
1325 foreach (Indexer ix in indexers){
1326 if ((ix.ModFlags & modflags) == 0)
1328 if ((ix.ModFlags & static_mask) != static_flags)
1334 if (b != null && filter (b, criteria) == true)
1338 if (b != null && filter (b, criteria) == true)
1344 if ((mt & MemberTypes.Event) != 0) {
1346 foreach (Event e in events) {
1347 if ((e.ModFlags & modflags) == 0)
1349 if ((e.ModFlags & static_mask) != static_flags)
1352 MemberInfo eb = e.EventBuilder;
1353 if (eb != null && filter (eb, criteria) == true)
1354 members.Add (e.EventBuilder);
1358 if ((mt & MemberTypes.Property) != 0){
1359 if (properties != null)
1360 foreach (Property p in properties) {
1361 if ((p.ModFlags & modflags) == 0)
1363 if ((p.ModFlags & static_mask) != static_flags)
1366 MemberInfo pb = p.PropertyBuilder;
1367 if (pb != null && filter (pb, criteria) == true) {
1368 members.Add (p.PropertyBuilder);
1372 if (indexers != null)
1373 foreach (Indexer ix in indexers) {
1374 if ((ix.ModFlags & modflags) == 0)
1376 if ((ix.ModFlags & static_mask) != static_flags)
1379 MemberInfo ib = ix.PropertyBuilder;
1380 if (ib != null && filter (ib, criteria) == true) {
1381 members.Add (ix.PropertyBuilder);
1386 if ((mt & MemberTypes.NestedType) != 0) {
1388 foreach (TypeContainer t in types) {
1389 if ((t.ModFlags & modflags) == 0)
1392 TypeBuilder tb = t.TypeBuilder;
1393 if (tb != null && (filter (tb, criteria) == true))
1399 foreach (Enum en in enums){
1400 if ((en.ModFlags & modflags) == 0)
1403 TypeBuilder tb = en.TypeBuilder;
1404 if (tb != null && (filter (tb, criteria) == true))
1409 if (delegates != null){
1410 foreach (Delegate d in delegates){
1411 if ((d.ModFlags & modflags) == 0)
1414 TypeBuilder tb = d.TypeBuilder;
1415 if (tb != null && (filter (tb, criteria) == true))
1420 if (interfaces != null){
1421 foreach (Interface iface in interfaces){
1422 if ((iface.ModFlags & modflags) == 0)
1425 TypeBuilder tb = iface.TypeBuilder;
1426 if (tb != null && (filter (tb, criteria) == true))
1432 if ((mt & MemberTypes.Constructor) != 0){
1433 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1434 foreach (Constructor c in instance_constructors){
1435 ConstructorBuilder cb = c.ConstructorBuilder;
1437 if (filter (cb, criteria) == true)
1442 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1443 ConstructorBuilder cb =
1444 default_static_constructor.ConstructorBuilder;
1447 if (filter (cb, criteria) == true)
1453 // Lookup members in parent if requested.
1455 if (((bf & BindingFlags.DeclaredOnly) == 0) && (TypeBuilder.BaseType != null)) {
1456 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1457 members.AddRange (list);
1460 Timer.StopTimer (TimerType.TcFindMembers);
1462 return new MemberList (members);
1465 public override MemberCache MemberCache {
1467 return member_cache;
1471 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1472 MemberFilter filter, object criteria)
1474 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1477 return ds.FindMembers (mt, bf, filter, criteria);
1479 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1484 // FindMethods will look for methods not only in the type `t', but in
1485 // any interfaces implemented by the type.
1487 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1488 MemberFilter filter, object criteria)
1494 /// Emits the values for the constants
1496 public void EmitConstants ()
1498 if (constants != null)
1499 foreach (Const con in constants)
1500 con.EmitConstant (this);
1505 /// Emits the code, this step is performed after all
1506 /// the types, enumerations, constructors
1510 if (instance_constructors != null)
1511 foreach (Constructor c in instance_constructors)
1514 if (default_static_constructor != null)
1515 default_static_constructor.Emit (this);
1517 if (methods != null)
1518 foreach (Method m in methods)
1521 if (operators != null)
1522 foreach (Operator o in operators)
1525 if (properties != null)
1526 foreach (Property p in properties)
1529 if (indexers != null){
1530 foreach (Indexer ix in indexers)
1533 CustomAttributeBuilder cb = Interface.EmitDefaultMemberAttr (
1534 this, IndexerName, ModFlags, Location);
1535 TypeBuilder.SetCustomAttribute (cb);
1539 foreach (Field f in fields)
1542 if (events != null){
1543 foreach (Event e in Events)
1547 if (Pending != null)
1548 if (Pending.VerifyPendingMethods ())
1551 Attribute.ApplyAttributes (ec, TypeBuilder, this, OptAttributes);
1554 // Check for internal or private fields that were never assigned
1556 if (RootContext.WarningLevel >= 3) {
1557 if (fields != null){
1558 foreach (Field f in fields) {
1559 if ((f.ModFlags & Modifiers.PUBLIC) != 0)
1564 169, f.Location, "Private field " +
1565 MakeName (f.Name) + " is never used");
1570 // Only report 649 on level 4
1572 if (RootContext.WarningLevel < 4)
1575 if ((f.status & Field.Status.ASSIGNED) != 0)
1580 "Field " + MakeName (f.Name) + " is never assigned " +
1581 " to and will always have its default value");
1585 if (events != null){
1586 foreach (Event e in events){
1588 Report.Warning (67, "The event " + MakeName (e.Name) + " is never used");
1593 // if (types != null)
1594 // foreach (TypeContainer tc in types)
1598 public override void CloseType ()
1603 TypeBuilder.CreateType ();
1605 } catch (TypeLoadException){
1607 // This is fine, the code still created the type
1609 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1610 // Console.WriteLine (e.Message);
1612 Console.WriteLine ("In type: " + Name);
1617 foreach (Enum en in Enums)
1620 if (interface_order != null){
1621 foreach (Interface iface in interface_order)
1626 foreach (TypeContainer tc in Types)
1630 foreach (TypeContainer tc in Types)
1631 if (!(tc is Struct))
1635 if (Delegates != null)
1636 foreach (Delegate d in Delegates)
1640 public string MakeName (string n)
1642 return "`" + Name + "." + n + "'";
1645 public void Warning_KeywordNewRequired (Location l, MemberInfo mi)
1648 108, l, "The keyword new is required on " +
1649 MakeName (mi.Name) + " because it hides `" +
1650 mi.ReflectedType.Name + "." + mi.Name + "'");
1653 public void Warning_KeywordNewNotRequired (Location l, MemberCore mc)
1656 109, l, "The member " + MakeName (mc.Name) + " does not hide an " +
1657 "inherited member, the keyword new is not required");
1660 public void Error_EventCanOnlyOverrideEvent (Location l, MemberInfo mi)
1663 72, l, MakeName (mi.Name) + " : cannot override; `" +
1664 mi.ReflectedType.Name + "." + mi.Name + "' is not an event");
1667 public static int CheckMember (string name, MemberInfo mi, int ModFlags)
1673 // Performs the validation on a Method's modifiers (properties have
1674 // the same properties).
1676 public bool MethodModifiersValid (int flags, string n, Location loc)
1678 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1679 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1680 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1684 // At most one of static, virtual or override
1686 if ((flags & Modifiers.STATIC) != 0){
1687 if ((flags & vao) != 0){
1689 112, loc, "static method " + MakeName (n) + "can not be marked " +
1690 "as virtual, abstract or override");
1695 if (this is Struct){
1696 if ((flags & va) != 0){
1697 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
1702 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1704 113, loc, MakeName (n) +
1705 " marked as override cannot be marked as new or virtual");
1710 // If the declaration includes the abstract modifier, then the
1711 // declaration does not include static, virtual or extern
1713 if ((flags & Modifiers.ABSTRACT) != 0){
1714 if ((flags & Modifiers.EXTERN) != 0){
1716 180, loc, MakeName (n) + " can not be both abstract and extern");
1720 if ((flags & Modifiers.VIRTUAL) != 0){
1722 503, loc, MakeName (n) + " can not be both abstract and virtual");
1726 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1728 513, loc, MakeName (n) +
1729 " is abstract but its container class is not");
1735 if ((flags & Modifiers.PRIVATE) != 0){
1736 if ((flags & vao) != 0){
1738 621, loc, MakeName (n) +
1739 " virtual or abstract members can not be private");
1744 if ((flags & Modifiers.SEALED) != 0){
1745 if ((flags & Modifiers.OVERRIDE) == 0){
1747 238, loc, MakeName (n) +
1748 " cannot be sealed because it is not an override");
1756 Hashtable builder_and_args;
1758 public bool RegisterMethod (MethodBuilder mb, InternalParameters ip, Type [] args)
1760 if (builder_and_args == null)
1761 builder_and_args = new Hashtable ();
1766 /// Performs checks for an explicit interface implementation. First it
1767 /// checks whether the `interface_type' is a base inteface implementation.
1768 /// Then it checks whether `name' exists in the interface type.
1770 public bool VerifyImplements (Type interface_type, string full, string name, Location loc)
1774 if (ifaces != null){
1775 foreach (Type t in ifaces){
1776 if (t == interface_type){
1784 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
1791 public static void Error_ExplicitInterfaceNotMemberInterface (Location loc, string name)
1793 Report.Error (539, loc, "Explicit implementation: `" + name + "' is not a member of the interface");
1800 string IMemberContainer.Name {
1806 Type IMemberContainer.Type {
1812 IMemberContainer IMemberContainer.Parent {
1814 return parent_container;
1818 MemberCache IMemberContainer.MemberCache {
1820 return member_cache;
1824 bool IMemberContainer.IsInterface {
1830 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
1832 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
1836 // Operator pair checking
1839 class OperatorEntry {
1841 public Type ret_type;
1842 public Type type1, type2;
1844 public Operator.OpType ot;
1846 public OperatorEntry (int f, Operator o)
1850 ret_type = o.OperatorMethod.GetReturnType ();
1851 Type [] pt = o.OperatorMethod.ParameterTypes;
1855 ot = o.OperatorType;
1858 public override int GetHashCode ()
1860 return ret_type.GetHashCode ();
1863 public override bool Equals (object o)
1865 OperatorEntry other = (OperatorEntry) o;
1867 if (other.ret_type != ret_type)
1869 if (other.type1 != type1)
1871 if (other.type2 != type2)
1878 // Checks that some operators come in pairs:
1884 // They are matched based on the return type and the argument types
1886 void CheckPairedOperators ()
1888 Hashtable pairs = new Hashtable (null, null);
1889 Operator true_op = null;
1890 Operator false_op = null;
1891 bool has_equality_or_inequality = false;
1893 // Register all the operators we care about.
1894 foreach (Operator op in operators){
1897 switch (op.OperatorType){
1898 case Operator.OpType.Equality:
1900 has_equality_or_inequality = true;
1902 case Operator.OpType.Inequality:
1904 has_equality_or_inequality = true;
1907 case Operator.OpType.True:
1910 case Operator.OpType.False:
1914 case Operator.OpType.GreaterThan:
1916 case Operator.OpType.LessThan:
1919 case Operator.OpType.GreaterThanOrEqual:
1921 case Operator.OpType.LessThanOrEqual:
1927 OperatorEntry oe = new OperatorEntry (reg, op);
1929 object o = pairs [oe];
1933 oe = (OperatorEntry) o;
1938 if (true_op != null){
1939 if (false_op == null)
1940 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
1941 } else if (false_op != null)
1942 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
1945 // Look for the mistakes.
1947 foreach (DictionaryEntry de in pairs){
1948 OperatorEntry oe = (OperatorEntry) de.Key;
1955 case Operator.OpType.Equality:
1958 case Operator.OpType.Inequality:
1961 case Operator.OpType.GreaterThan:
1964 case Operator.OpType.LessThan:
1967 case Operator.OpType.GreaterThanOrEqual:
1970 case Operator.OpType.LessThanOrEqual:
1974 Report.Error (216, oe.op.Location,
1975 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
1978 if ((has_equality_or_inequality) && (RootContext.WarningLevel >= 2)) {
1979 MethodSignature equals_ms = new MethodSignature (
1980 "Equals", TypeManager.bool_type, new Type [] { TypeManager.object_type });
1981 MethodSignature hash_ms = new MethodSignature (
1982 "GetHashCode", TypeManager.int32_type, new Type [0]);
1984 MemberList equals_ml = FindMembers (MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance |
1985 BindingFlags.DeclaredOnly, MethodSignature.method_signature_filter,
1987 MemberList hash_ml = FindMembers (MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance |
1988 BindingFlags.DeclaredOnly, MethodSignature.method_signature_filter,
1991 bool equals_ok = false;
1992 if ((equals_ml != null) && (equals_ml.Count == 1))
1993 equals_ok = equals_ml [0].DeclaringType == TypeBuilder;
1994 bool hash_ok = false;
1995 if ((hash_ml != null) && (hash_ml.Count == 1))
1996 hash_ok = hash_ml [0].DeclaringType == TypeBuilder;
1999 Report.Warning (660, Location, "`" + Name + "' defines operator == or operator != but does " +
2000 "not override Object.Equals (object o)");
2002 Report.Warning (661, Location, "`" + Name + "' defines operator == or operator != but does " +
2003 "not override Object.GetHashCode ()");
2010 public class Class : TypeContainer {
2012 // Modifiers allowed in a class declaration
2014 public const int AllowedModifiers =
2017 Modifiers.PROTECTED |
2018 Modifiers.INTERNAL |
2020 Modifiers.ABSTRACT |
2024 public Class (NamespaceEntry ns, TypeContainer parent, string name, int mod, Attributes attrs, Location l)
2025 : base (ns, parent, name, l)
2029 if (parent.Parent == null)
2030 accmods = Modifiers.INTERNAL;
2032 accmods = Modifiers.PRIVATE;
2034 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2035 this.attributes = attrs;
2039 // FIXME: How do we deal with the user specifying a different
2042 public override TypeAttributes TypeAttr {
2044 return base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2049 public class Struct : TypeContainer {
2051 // Modifiers allowed in a struct declaration
2053 public const int AllowedModifiers =
2056 Modifiers.PROTECTED |
2057 Modifiers.INTERNAL |
2061 public Struct (NamespaceEntry ns, TypeContainer parent, string name, int mod, Attributes attrs, Location l)
2062 : base (ns, parent, name, l)
2066 if (parent.Parent == null)
2067 accmods = Modifiers.INTERNAL;
2069 accmods = Modifiers.PRIVATE;
2071 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2073 this.ModFlags |= Modifiers.SEALED;
2074 this.attributes = attrs;
2079 // FIXME: Allow the user to specify a different set of attributes
2080 // in some cases (Sealed for example is mandatory for a class,
2081 // but what SequentialLayout can be changed
2083 public override TypeAttributes TypeAttr {
2085 return base.TypeAttr |
2086 TypeAttributes.SequentialLayout |
2087 TypeAttributes.Sealed |
2088 TypeAttributes.BeforeFieldInit;
2093 public abstract class MethodCore : MemberBase {
2094 public readonly Parameters Parameters;
2095 protected Block block;
2096 protected DeclSpace ds;
2099 // Parameters, cached for semantic analysis.
2101 protected InternalParameters parameter_info;
2102 protected Type [] parameter_types;
2105 // This is set from TypeContainer.DefineMembers if this method overrides something.
2107 public bool OverridesSomething;
2109 public MethodCore (DeclSpace ds, Expression type, int mod, int allowed_mod,
2110 string name, Attributes attrs, Parameters parameters, Location loc)
2111 : base (type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
2113 Parameters = parameters;
2118 // Returns the System.Type array for the parameters of this method
2120 public Type [] ParameterTypes {
2122 return parameter_types;
2126 public InternalParameters ParameterInfo
2129 return parameter_info;
2133 public Block Block {
2143 protected virtual bool DoDefineParameters ()
2145 // Check if arguments were correct
2146 parameter_types = Parameters.GetParameterInfo (ds);
2147 if ((parameter_types == null) || !CheckParameters (ds, parameter_types))
2150 parameter_info = new InternalParameters (ds, Parameters);
2152 Parameter array_param = Parameters.ArrayParameter;
2153 if ((array_param != null) &&
2154 (!array_param.ParameterType.IsArray ||
2155 (array_param.ParameterType.GetArrayRank () != 1))) {
2156 Report.Error (225, Location, "params parameter has to be a single dimensional array");
2163 public CallingConventions GetCallingConvention (bool is_class)
2165 CallingConventions cc = 0;
2167 cc = Parameters.GetCallingConvention ();
2170 if ((ModFlags & Modifiers.STATIC) == 0)
2171 cc |= CallingConventions.HasThis;
2173 // FIXME: How is `ExplicitThis' used in C#?
2179 // The method's attributes are passed in because we need to extract
2180 // the "return:" attribute from there to apply on the return type
2182 static public void LabelParameters (EmitContext ec,
2184 Parameters parameters,
2185 Attributes method_attrs,
2189 // Define each type attribute (in/out/ref) and
2190 // the argument names.
2192 Parameter [] p = parameters.FixedParameters;
2195 MethodBuilder mb = null;
2196 ConstructorBuilder cb = null;
2198 if (builder is MethodBuilder)
2199 mb = (MethodBuilder) builder;
2201 cb = (ConstructorBuilder) builder;
2204 for (i = 0; i < p.Length; i++) {
2205 ParameterBuilder pb;
2206 ParameterAttributes par_attr = p [i].Attributes;
2209 pb = cb.DefineParameter (
2210 i + 1, par_attr, p [i].Name);
2212 pb = mb.DefineParameter (
2213 i + 1, par_attr, p [i].Name);
2215 Attributes attr = p [i].OptAttributes;
2217 Attribute.ApplyAttributes (ec, pb, pb, attr);
2219 if (par_attr == ParameterAttributes.Out){
2220 if (attr.Contains (TypeManager.in_attribute_type))
2221 Report.Error (36, loc,
2222 "Can not use [In] attribute on out parameter");
2228 if (parameters.ArrayParameter != null){
2229 ParameterBuilder pb;
2230 Parameter array_param = parameters.ArrayParameter;
2233 pb = cb.DefineParameter (
2234 i + 1, array_param.Attributes,
2237 pb = mb.DefineParameter (
2238 i + 1, array_param.Attributes,
2241 CustomAttributeBuilder a = new CustomAttributeBuilder (
2242 TypeManager.cons_param_array_attribute, new object [0]);
2244 pb.SetCustomAttribute (a);
2248 // And now for the return type attribute decoration
2250 ParameterBuilder ret_pb;
2251 Attributes ret_attrs = null;
2253 if (mb == null || method_attrs == null)
2256 foreach (AttributeSection asec in method_attrs.AttributeSections) {
2258 if (asec.Target != "return")
2261 if (ret_attrs == null)
2262 ret_attrs = new Attributes (asec);
2264 ret_attrs.AddAttributeSection (asec);
2267 if (ret_attrs != null) {
2269 ret_pb = mb.DefineParameter (0, ParameterAttributes.None, "");
2270 Attribute.ApplyAttributes (ec, ret_pb, ret_pb, ret_attrs);
2272 } catch (ArgumentOutOfRangeException) {
2275 ".NET SDK 1.0 does not permit setting custom attributes" +
2276 " on the return type of a method");
2282 public class Method : MethodCore, IIteratorContainer {
2283 public MethodBuilder MethodBuilder;
2284 public MethodData MethodData;
2287 /// Modifiers allowed in a class declaration
2289 const int AllowedModifiers =
2292 Modifiers.PROTECTED |
2293 Modifiers.INTERNAL |
2298 Modifiers.OVERRIDE |
2299 Modifiers.ABSTRACT |
2304 // return_type can be "null" for VOID values.
2306 public Method (DeclSpace ds, Expression return_type, int mod, string name,
2307 Parameters parameters, Attributes attrs, Location l)
2308 : base (ds, return_type, mod, AllowedModifiers, name, attrs, parameters, l)
2312 // Returns the `System.Type' for the ReturnType of this
2313 // function. Provides a nice cache. (used between semantic analysis
2314 // and actual code generation
2316 public Type GetReturnType ()
2321 // Whether this is an operator method.
2322 public bool IsOperator;
2324 void DuplicateEntryPoint (MethodInfo b, Location location)
2328 "Program `" + CodeGen.FileName +
2329 "' has more than one entry point defined: `" +
2330 TypeManager.CSharpSignature(b) + "'");
2333 void Report28 (MethodInfo b)
2337 "`" + TypeManager.CSharpSignature(b) +
2338 "' has the wrong signature to be an entry point");
2341 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
2343 if (b.ReturnType != TypeManager.void_type &&
2344 b.ReturnType != TypeManager.int32_type)
2347 if (pinfo.Count == 0)
2350 if (pinfo.Count > 1)
2353 Type t = pinfo.ParameterType(0);
2355 (t.GetArrayRank() == 1) &&
2356 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
2357 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
2364 // Checks our base implementation if any
2366 protected override bool CheckBase (TypeContainer container)
2368 base.CheckBase (container);
2370 // Check whether arguments were correct.
2371 if (!DoDefineParameters ())
2374 MethodSignature ms = new MethodSignature (Name, null, ParameterTypes);
2376 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2380 mi_this = TypeContainer.FindMembers (
2381 container.TypeBuilder, MemberTypes.Method,
2382 BindingFlags.NonPublic | BindingFlags.Public |
2383 BindingFlags.Static | BindingFlags.Instance |
2384 BindingFlags.DeclaredOnly,
2385 MethodSignature.method_signature_filter, ms);
2387 if (mi_this.Count > 0) {
2388 Report.Error (111, Location, "Class `" + container.Name + "' " +
2389 "already defines a member called `" + Name + "' " +
2390 "with the same parameter types");
2396 // Verify if the parent has a type with the same name, and then
2397 // check whether we have to create a new slot for it or not.
2399 Type ptype = container.TypeBuilder.BaseType;
2401 // ptype is only null for System.Object while compiling corlib.
2403 MemberList mi, mi_static, mi_instance;
2405 mi_instance = TypeContainer.FindMembers (
2406 ptype, MemberTypes.Method,
2407 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
2408 MethodSignature.inheritable_method_signature_filter,
2411 if (mi_instance.Count > 0){
2414 mi_static = TypeContainer.FindMembers (
2415 ptype, MemberTypes.Method,
2416 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static,
2417 MethodSignature.inheritable_method_signature_filter, ms);
2419 if (mi_static.Count > 0)
2425 if (mi != null && mi.Count > 0){
2426 parent_method = (MethodInfo) mi [0];
2427 string name = parent_method.DeclaringType.Name + "." +
2430 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
2433 if ((ModFlags & Modifiers.NEW) == 0) {
2434 Type parent_ret = TypeManager.TypeToCoreType (
2435 parent_method.ReturnType);
2437 if (parent_ret != MemberType) {
2439 508, Location, container.MakeName (Name) + ": cannot " +
2440 "change return type when overriding " +
2441 "inherited member " + name);
2446 if (!OverridesSomething && ((ModFlags & Modifiers.NEW) != 0))
2447 WarningNotHiding (container);
2449 if ((ModFlags & Modifiers.OVERRIDE) != 0){
2450 Report.Error (115, Location,
2451 container.MakeName (Name) +
2452 " no suitable methods found to override");
2455 } else if ((ModFlags & Modifiers.NEW) != 0)
2456 WarningNotHiding (container);
2464 public override bool Define (TypeContainer container)
2466 if (!DoDefine (container))
2469 if (!CheckBase (container))
2472 CallingConventions cc = GetCallingConvention (container is Class);
2474 MethodData = new MethodData (container, this, null, MemberType,
2475 ParameterTypes, ParameterInfo, cc,
2476 OptAttributes, ModFlags, flags, true);
2478 if (!MethodData.Define (container))
2482 // Setup iterator if we are one
2484 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
2485 IteratorHandler ih = new IteratorHandler (
2486 Name, container, MemberType,
2487 ParameterTypes, ParameterInfo,
2488 ModFlags, Location);
2490 Block new_block = ih.Setup (block);
2491 if (new_block == null)
2496 MethodBuilder = MethodData.MethodBuilder;
2499 // This is used to track the Entry Point,
2501 if (Name == "Main" &&
2502 ((ModFlags & Modifiers.STATIC) != 0) &&
2503 (RootContext.MainClass == null ||
2504 RootContext.MainClass == container.TypeBuilder.FullName)){
2505 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
2506 if (RootContext.EntryPoint == null) {
2507 RootContext.EntryPoint = MethodBuilder;
2508 RootContext.EntryPointLocation = Location;
2510 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
2511 DuplicateEntryPoint (MethodBuilder, Location);
2514 Report28(MethodBuilder);
2523 public void Emit (TypeContainer container)
2525 MethodData.Emit (container, Block, this);
2529 void IIteratorContainer.SetYields ()
2531 ModFlags |= Modifiers.METHOD_YIELDS;
2535 public abstract class ConstructorInitializer {
2536 ArrayList argument_list;
2537 ConstructorInfo parent_constructor;
2538 Parameters parameters;
2541 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
2544 this.argument_list = argument_list;
2545 this.parameters = parameters;
2549 public ArrayList Arguments {
2551 return argument_list;
2555 public bool Resolve (EmitContext ec)
2557 Expression parent_constructor_group;
2560 ec.CurrentBlock = new Block (null, Block.Flags.Implicit, parameters);
2562 if (argument_list != null){
2563 foreach (Argument a in argument_list){
2564 if (!a.Resolve (ec, loc))
2568 ec.CurrentBlock = null;
2570 if (this is ConstructorBaseInitializer) {
2571 if (ec.ContainerType.BaseType == null)
2574 t = ec.ContainerType.BaseType;
2575 if (ec.ContainerType.IsValueType) {
2576 Report.Error (522, loc,
2577 "structs cannot call base class constructors");
2581 t = ec.ContainerType;
2583 parent_constructor_group = Expression.MemberLookup (
2584 ec, t, null, t, ".ctor",
2585 MemberTypes.Constructor,
2586 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
2589 if (parent_constructor_group == null){
2590 Report.Error (1501, loc,
2591 "Can not find a constructor for this argument list");
2595 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (ec,
2596 (MethodGroupExpr) parent_constructor_group, argument_list, loc);
2598 if (parent_constructor == null){
2599 Report.Error (1501, loc,
2600 "Can not find a constructor for this argument list");
2607 public void Emit (EmitContext ec)
2609 if (parent_constructor != null){
2610 ec.Mark (loc, false);
2612 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
2614 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
2619 public class ConstructorBaseInitializer : ConstructorInitializer {
2620 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
2621 base (argument_list, pars, l)
2626 public class ConstructorThisInitializer : ConstructorInitializer {
2627 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
2628 base (argument_list, pars, l)
2633 public class Constructor : MethodCore {
2634 public ConstructorBuilder ConstructorBuilder;
2635 public ConstructorInitializer Initializer;
2636 new public Attributes OptAttributes;
2639 // Modifiers allowed for a constructor.
2641 public const int AllowedModifiers =
2643 Modifiers.PROTECTED |
2644 Modifiers.INTERNAL |
2651 // The spec claims that static is not permitted, but
2652 // my very own code has static constructors.
2654 public Constructor (DeclSpace ds, string name, Parameters args,
2655 ConstructorInitializer init, Location l)
2656 : base (ds, null, 0, AllowedModifiers, name, null, args, l)
2662 // Returns true if this is a default constructor
2664 public bool IsDefault ()
2666 if ((ModFlags & Modifiers.STATIC) != 0)
2667 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
2668 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
2671 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
2672 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
2673 (Initializer is ConstructorBaseInitializer) &&
2674 (Initializer.Arguments == null);
2678 // Creates the ConstructorBuilder
2680 public override bool Define (TypeContainer container)
2682 MethodAttributes ca = (MethodAttributes.RTSpecialName |
2683 MethodAttributes.SpecialName);
2685 // Check if arguments were correct.
2686 if (!DoDefineParameters ())
2689 if ((ModFlags & Modifiers.STATIC) != 0){
2690 ca |= MethodAttributes.Static | MethodAttributes.Private;
2692 if (container is Struct && ParameterTypes.Length == 0){
2695 "Structs can not contain explicit parameterless " +
2699 ca |= MethodAttributes.HideBySig;
2701 if ((ModFlags & Modifiers.PUBLIC) != 0)
2702 ca |= MethodAttributes.Public;
2703 else if ((ModFlags & Modifiers.PROTECTED) != 0){
2704 if ((ModFlags & Modifiers.INTERNAL) != 0)
2705 ca |= MethodAttributes.FamORAssem;
2707 ca |= MethodAttributes.Family;
2708 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
2709 ca |= MethodAttributes.Assembly;
2710 else if (IsDefault ())
2711 ca |= MethodAttributes.Public;
2713 ca |= MethodAttributes.Private;
2716 ConstructorBuilder = container.TypeBuilder.DefineConstructor (
2717 ca, GetCallingConvention (container is Class), ParameterTypes);
2719 if ((ModFlags & Modifiers.UNSAFE) != 0)
2720 ConstructorBuilder.InitLocals = false;
2723 // HACK because System.Reflection.Emit is lame
2725 if (!TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes)) {
2728 "Class `" +container.Name+ "' already contains a definition with the " +
2729 "same return value and parameter types for constructor `" + Name
2740 public void Emit (TypeContainer container)
2742 ILGenerator ig = ConstructorBuilder.GetILGenerator ();
2743 EmitContext ec = new EmitContext (container, Location, ig, null, ModFlags, true);
2746 // extern methods have no bodies
2748 if ((ModFlags & Modifiers.EXTERN) != 0) {
2749 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
2751 179, Location, "External constructor `" +
2752 TypeManager.CSharpSignature (ConstructorBuilder) +
2753 "' can not have a body");
2756 } else if (block == null) {
2758 501, Location, "Constructor `" +
2759 TypeManager.CSharpSignature (ConstructorBuilder) +
2760 "' must declare a body since it is not marked extern");
2764 if ((ModFlags & Modifiers.STATIC) == 0){
2765 if (container is Class && Initializer == null)
2766 Initializer = new ConstructorBaseInitializer (
2767 null, Parameters.EmptyReadOnlyParameters, Location);
2771 // Spec mandates that Initializers will not have
2775 if (Initializer != null && !Initializer.Resolve (ec))
2777 ec.IsStatic = false;
2780 MethodCore.LabelParameters (ec, ConstructorBuilder,
2781 Parameters, OptAttributes, Location);
2783 SymbolWriter sw = CodeGen.SymbolWriter;
2784 bool generate_debugging = false;
2786 if ((sw != null) && (block != null) &&
2787 !Location.IsNull (Location) &&
2788 !Location.IsNull (block.EndLocation)) {
2790 sw.OpenMethod (container, ConstructorBuilder, Location, block.EndLocation);
2792 generate_debugging = true;
2796 // Classes can have base initializers and instance field initializers.
2798 if (container is Class){
2799 if ((ModFlags & Modifiers.STATIC) == 0){
2802 // If we use a "this (...)" constructor initializer, then
2803 // do not emit field initializers, they are initialized in the other constructor
2805 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
2806 container.EmitFieldInitializers (ec);
2809 if (Initializer != null)
2810 Initializer.Emit (ec);
2812 if ((ModFlags & Modifiers.STATIC) != 0)
2813 container.EmitFieldInitializers (ec);
2815 Attribute.ApplyAttributes (ec, ConstructorBuilder, this, OptAttributes);
2817 // If this is a non-static `struct' constructor and doesn't have any
2818 // initializer, it must initialize all of the struct's fields.
2819 if ((container is Struct) && ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
2820 Block.AddThisVariable (container, Location);
2822 ec.EmitTopBlock (block, ParameterInfo, Location);
2824 if (generate_debugging)
2832 // Encapsulates most of the Method's state
2834 public class MethodData {
2836 // The return type of this method
2838 public readonly Type ReturnType;
2839 public readonly Type[] ParameterTypes;
2840 public readonly InternalParameters ParameterInfo;
2841 public readonly CallingConventions CallingConventions;
2842 public readonly Attributes OptAttributes;
2843 public readonly Location Location;
2846 // Are we implementing an interface ?
2848 public bool IsImplementing = false;
2853 protected DeclSpace ds;
2854 protected MemberBase member;
2855 protected int modifiers;
2856 protected MethodAttributes flags;
2857 protected bool is_method;
2858 protected string accessor_name;
2861 // It can either hold a string with the condition, or an arraylist of conditions.
2862 object conditionals;
2864 MethodBuilder builder = null;
2865 public MethodBuilder MethodBuilder {
2871 public MethodData (DeclSpace ds, MemberBase member, string name, Type return_type,
2872 Type [] parameter_types, InternalParameters parameters,
2873 CallingConventions cc, Attributes opt_attrs,
2874 int modifiers, MethodAttributes flags, bool is_method)
2877 this.member = member;
2878 this.accessor_name = name;
2879 this.ReturnType = return_type;
2880 this.ParameterTypes = parameter_types;
2881 this.ParameterInfo = parameters;
2882 this.CallingConventions = cc;
2883 this.OptAttributes = opt_attrs;
2884 this.modifiers = modifiers;
2886 this.is_method = is_method;
2887 this.Location = member.Location;
2888 this.conditionals = null;
2894 Attribute dllimport_attribute = null;
2895 string obsolete = null;
2896 bool obsolete_error = false;
2898 public virtual bool ApplyAttributes (Attributes opt_attrs, bool is_method)
2900 if ((opt_attrs == null) || (opt_attrs.AttributeSections == null))
2903 foreach (AttributeSection asec in opt_attrs.AttributeSections) {
2904 if (asec.Attributes == null)
2907 foreach (Attribute a in asec.Attributes) {
2908 if (a.Name == "Conditional") {
2909 if (!ApplyConditionalAttribute (a))
2911 } else if (a.Name == "Obsolete") {
2912 if (!ApplyObsoleteAttribute (a))
2914 } else if (a.Name.IndexOf ("DllImport") != -1) {
2916 a.Type = TypeManager.dllimport_type;
2917 Attribute.Error_AttributeNotValidForElement (a, Location);
2920 if (!ApplyDllImportAttribute (a))
2930 // Applies the `DllImport' attribute to the method.
2932 protected virtual bool ApplyDllImportAttribute (Attribute a)
2934 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
2935 if ((modifiers & extern_static) != extern_static) {
2936 Report.Error (601, Location,
2937 "The DllImport attribute must be specified on a method " +
2938 "marked `static' and `extern'.");
2942 flags |= MethodAttributes.PinvokeImpl;
2943 dllimport_attribute = a;
2948 // Applies the `Obsolete' attribute to the method.
2950 protected virtual bool ApplyObsoleteAttribute (Attribute a)
2952 if (obsolete != null) {
2953 Report.Error (579, Location, "Duplicate `Obsolete' attribute");
2957 obsolete = a.Obsolete_GetObsoleteMessage (out obsolete_error);
2958 return obsolete != null;
2962 // Applies the `Conditional' attribute to the method.
2964 protected virtual bool ApplyConditionalAttribute (Attribute a)
2966 // The Conditional attribute is only valid on methods.
2968 Attribute.Error_AttributeNotValidForElement (a, Location);
2972 string condition = a.Conditional_GetConditionName ();
2974 if (condition == null)
2977 if (ReturnType != TypeManager.void_type) {
2978 Report.Error (578, Location,
2979 "Conditional not valid on `" + member.Name + "' " +
2980 "because its return type is not void");
2984 if ((modifiers & Modifiers.OVERRIDE) != 0) {
2985 Report.Error (243, Location,
2986 "Conditional not valid on `" + member.Name + "' " +
2987 "because it is an override method");
2991 if (member.IsExplicitImpl) {
2992 Report.Error (577, Location,
2993 "Conditional not valid on `" + member.Name + "' " +
2994 "because it is an explicit interface implementation");
2998 if (IsImplementing) {
2999 Report.Error (623, Location,
3000 "Conditional not valid on `" + member.Name + "' " +
3001 "because it is an interface method");
3006 // The likelyhood that the conditional will be more than 1 is very slim
3008 if (conditionals == null)
3009 conditionals = condition;
3010 else if (conditionals is string){
3011 string s = (string) conditionals;
3012 conditionals = new ArrayList ();
3013 ((ArrayList)conditionals).Add (s);
3015 ((ArrayList)conditionals).Add (condition);
3021 // Checks whether this method should be ignored due to its Conditional attributes.
3023 bool ShouldIgnore (Location loc)
3025 // When we're overriding a virtual method, we implicitly inherit the
3026 // Conditional attributes from our parent.
3027 if (member.ParentMethod != null) {
3028 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (
3029 member.ParentMethod, loc);
3031 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
3035 if (conditionals != null){
3036 if (conditionals is string){
3037 if (RootContext.AllDefines [conditionals] == null)
3040 foreach (string condition in (ArrayList) conditionals)
3041 if (RootContext.AllDefines [condition] == null)
3049 // Returns the TypeManager.MethodFlags for this method.
3050 // This emits an error 619 / warning 618 if the method is obsolete.
3051 // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
3053 public virtual TypeManager.MethodFlags GetMethodFlags (Location loc)
3055 TypeManager.MethodFlags flags = 0;
3057 if (obsolete != null) {
3058 if (obsolete_error) {
3059 Report.Error (619, loc, "Method `" + member.Name +
3060 "' is obsolete: `" + obsolete + "'");
3061 return TypeManager.MethodFlags.IsObsoleteError;
3063 Report.Warning (618, loc, "Method `" + member.Name +
3064 "' is obsolete: `" + obsolete + "'");
3066 flags |= TypeManager.MethodFlags.IsObsolete;
3069 if (ShouldIgnore (loc))
3070 flags |= TypeManager.MethodFlags.ShouldIgnore;
3075 public virtual bool Define (TypeContainer container)
3077 MethodInfo implementing = null;
3078 string method_name, name, prefix;
3080 if (OptAttributes != null)
3081 if (!ApplyAttributes (OptAttributes, is_method))
3084 if (member.IsExplicitImpl)
3085 prefix = member.InterfaceType.FullName + ".";
3089 if (accessor_name != null)
3090 name = accessor_name + "_" + member.ShortName;
3092 name = member.ShortName;
3093 method_name = prefix + name;
3095 if (container.Pending != null){
3096 if (member is Indexer)
3097 implementing = container.Pending.IsInterfaceIndexer (
3098 member.InterfaceType, ReturnType, ParameterTypes);
3100 implementing = container.Pending.IsInterfaceMethod (
3101 member.InterfaceType, name, ReturnType, ParameterTypes);
3103 if (member.InterfaceType != null && implementing == null){
3104 TypeContainer.Error_ExplicitInterfaceNotMemberInterface (
3111 // For implicit implementations, make sure we are public, for
3112 // explicit implementations, make sure we are private.
3114 if (implementing != null){
3116 // Setting null inside this block will trigger a more
3117 // verbose error reporting for missing interface implementations
3119 // The "candidate" function has been flagged already
3120 // but it wont get cleared
3122 if (member.IsExplicitImpl){
3123 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
3124 Modifiers.Error_InvalidModifier (Location, "public, virtual or abstract");
3125 implementing = null;
3127 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
3128 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
3130 // If this is an interface method implementation,
3131 // check for public accessibility
3133 implementing = null;
3134 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
3135 // We may never be private.
3136 implementing = null;
3137 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
3139 // We may be protected if we're overriding something.
3141 implementing = null;
3146 // Static is not allowed
3148 if ((modifiers & Modifiers.STATIC) != 0){
3149 implementing = null;
3150 Modifiers.Error_InvalidModifier (Location, "static");
3155 // If implementing is still valid, set flags
3157 if (implementing != null){
3159 // When implementing interface methods, set NewSlot
3160 // unless, we are overwriting a method.
3162 if (implementing.DeclaringType.IsInterface){
3163 if ((modifiers & Modifiers.OVERRIDE) == 0)
3164 flags |= MethodAttributes.NewSlot;
3167 MethodAttributes.Virtual |
3168 MethodAttributes.HideBySig;
3170 // Set Final unless we're virtual, abstract or already overriding a method.
3171 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
3172 flags |= MethodAttributes.Final;
3174 // Get the method name from the explicit interface.
3175 if (member.InterfaceType != null) {
3176 name = implementing.Name;
3177 method_name = prefix + name;
3180 IsImplementing = true;
3184 // Create the MethodBuilder for the method
3186 if ((flags & MethodAttributes.PinvokeImpl) != 0) {
3187 if ((modifiers & Modifiers.STATIC) == 0) {
3188 Report.Error (601, Location,
3189 "The DllImport attribute must be specified on " +
3190 "a method marked 'static' and 'extern'.");
3194 EmitContext ec = new EmitContext (
3195 container, ds, Location, null, ReturnType, modifiers, false);
3197 builder = dllimport_attribute.DefinePInvokeMethod (
3198 ec, container.TypeBuilder, method_name, flags,
3199 ReturnType, ParameterTypes);
3201 builder = container.TypeBuilder.DefineMethod (
3202 method_name, flags, CallingConventions,
3203 ReturnType, ParameterTypes);
3205 if (builder == null)
3208 if ((modifiers & Modifiers.UNSAFE) != 0)
3209 builder.InitLocals = false;
3211 if (IsImplementing){
3213 // clear the pending implemntation flag
3215 if (member is Indexer) {
3216 container.Pending.ImplementIndexer (
3217 member.InterfaceType, builder, ReturnType,
3218 ParameterTypes, true);
3220 container.Pending.ImplementMethod (
3221 member.InterfaceType, name, ReturnType,
3222 ParameterTypes, member.IsExplicitImpl);
3224 if (member.IsExplicitImpl)
3225 container.TypeBuilder.DefineMethodOverride (
3226 builder, implementing);
3230 if (!TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes)) {
3231 Report.Error (111, Location,
3232 "Class `" + container.Name +
3233 "' already contains a definition with the " +
3234 "same return value and parameter types as the " +
3235 "'get' method of property `" + member.Name + "'");
3239 TypeManager.AddMethod (builder, this);
3247 public virtual void Emit (TypeContainer container, Block block, object kind)
3252 if ((flags & MethodAttributes.PinvokeImpl) == 0)
3253 ig = builder.GetILGenerator ();
3257 ec = new EmitContext (container, ds, Location, ig, ReturnType, modifiers, false);
3259 if (OptAttributes != null)
3260 Attribute.ApplyAttributes (ec, builder, kind, OptAttributes);
3262 if (member is MethodCore)
3263 MethodCore.LabelParameters (ec, MethodBuilder,
3264 ((MethodCore) member).Parameters,
3269 // abstract or extern methods have no bodies
3271 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
3272 if (block == null) {
3273 SymbolWriter sw = CodeGen.SymbolWriter;
3275 if ((sw != null) && ((modifiers & Modifiers.EXTERN) != 0)) {
3276 sw.OpenMethod (container, MethodBuilder, Location, Location);
3284 // abstract or extern methods have no bodies.
3286 if ((modifiers & Modifiers.ABSTRACT) != 0)
3288 500, Location, "Abstract method `" +
3289 TypeManager.CSharpSignature (builder) +
3290 "' can not have a body");
3292 if ((modifiers & Modifiers.EXTERN) != 0)
3294 179, Location, "External method `" +
3295 TypeManager.CSharpSignature (builder) +
3296 "' can not have a body");
3302 // Methods must have a body unless they're extern or abstract
3304 if (block == null) {
3306 501, Location, "Method `" +
3307 TypeManager.CSharpSignature (builder) +
3308 "' must declare a body since it is not marked " +
3309 "abstract or extern");
3314 // Handle destructors specially
3316 // FIXME: This code generates buggy code
3318 if (member.Name == "Finalize" && ReturnType == TypeManager.void_type)
3319 EmitDestructor (ec, block);
3321 SymbolWriter sw = CodeGen.SymbolWriter;
3323 if ((sw != null) && !Location.IsNull (Location) &&
3324 !Location.IsNull (block.EndLocation)) {
3325 sw.OpenMethod (container, MethodBuilder, Location, block.EndLocation);
3327 ec.EmitTopBlock (block, ParameterInfo, Location);
3331 ec.EmitTopBlock (block, ParameterInfo, Location);
3335 void EmitDestructor (EmitContext ec, Block block)
3337 ILGenerator ig = ec.ig;
3339 Label finish = ig.DefineLabel ();
3340 bool old_in_try = ec.InTry;
3342 ig.BeginExceptionBlock ();
3344 ec.ReturnLabel = finish;
3345 ec.HasReturnLabel = true;
3346 ec.EmitTopBlock (block, null, Location);
3347 ec.InTry = old_in_try;
3349 // ig.MarkLabel (finish);
3350 bool old_in_finally = ec.InFinally;
3351 ec.InFinally = true;
3352 ig.BeginFinallyBlock ();
3354 if (ec.ContainerType.BaseType != null) {
3355 Expression member_lookup = Expression.MemberLookup (
3356 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
3357 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, Location);
3359 if (member_lookup != null){
3360 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
3362 ig.Emit (OpCodes.Ldarg_0);
3363 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
3366 ec.InFinally = old_in_finally;
3368 ig.EndExceptionBlock ();
3369 //ig.MarkLabel (ec.ReturnLabel);
3370 ig.Emit (OpCodes.Ret);
3374 abstract public class MemberBase : MemberCore {
3375 public Expression Type;
3376 public readonly Attributes OptAttributes;
3378 protected MethodAttributes flags;
3381 // The "short" name of this property / indexer / event. This is the
3382 // name without the explicit interface.
3384 public string ShortName;
3387 // The type of this property / indexer / event
3389 public Type MemberType;
3392 // If true, this is an explicit interface implementation
3394 public bool IsExplicitImpl = false;
3397 // The name of the interface we are explicitly implementing
3399 public string ExplicitInterfaceName = null;
3402 // If true, the interface type we are explicitly implementing
3404 public Type InterfaceType = null;
3407 // The method we're overriding if this is an override method.
3409 protected MethodInfo parent_method = null;
3410 public MethodInfo ParentMethod {
3412 return parent_method;
3417 // The constructor is only exposed to our children
3419 protected MemberBase (Expression type, int mod, int allowed_mod, int def_mod, string name,
3420 Attributes attrs, Location loc)
3424 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
3425 OptAttributes = attrs;
3428 protected virtual bool CheckBase (TypeContainer container)
3430 if ((container is Struct) || (RootContext.WarningLevel > 3)){
3431 if ((ModFlags & Modifiers.PROTECTED) != 0 && (container.ModFlags & Modifiers.SEALED) != 0){
3432 if (container is Struct){
3433 Report.Error (666, Location, "Protected member in struct declaration");
3436 Report.Warning (628, Location, "Member " + container.MakeName (Name) + " protected in sealed class");
3442 protected void WarningNotHiding (TypeContainer parent)
3446 "The member " + parent.MakeName (Name) + " does not hide an " +
3447 "inherited member. The keyword new is not required");
3451 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method,
3455 // FIXME: report the old/new permissions?
3458 507, Location, parent.MakeName (Name) +
3459 ": can't change the access modifiers when overriding inherited " +
3460 "member `" + name + "'");
3464 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3465 // that have been defined.
3467 // `name' is the user visible name for reporting errors (this is used to
3468 // provide the right name regarding method names and properties)
3470 protected bool CheckMethodAgainstBase (TypeContainer parent, MethodAttributes my_attrs,
3471 MethodInfo mb, string name)
3475 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3476 if (!(mb.IsAbstract || mb.IsVirtual)){
3478 506, Location, parent.MakeName (Name) +
3479 ": cannot override inherited member `" +
3480 name + "' because it is not " +
3481 "virtual, abstract or override");
3485 // Now we check that the overriden method is not final
3488 // This happens when implementing interface methods.
3489 if (mb.IsHideBySig && mb.IsVirtual) {
3491 506, Location, parent.MakeName (Name) +
3492 ": cannot override inherited member `" +
3493 name + "' because it is not " +
3494 "virtual, abstract or override");
3496 Report.Error (239, Location, parent.MakeName (Name) + " : cannot " +
3497 "override inherited member `" + name +
3498 "' because it is sealed.");
3502 // Check that the permissions are not being changed
3504 MethodAttributes thisp = my_attrs & MethodAttributes.MemberAccessMask;
3505 MethodAttributes parentp = mb.Attributes & MethodAttributes.MemberAccessMask;
3508 // special case for "protected internal"
3511 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3513 // when overriding protected internal, the method can be declared
3514 // protected internal only within the same assembly
3517 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3518 if (parent.TypeBuilder.Assembly != mb.DeclaringType.Assembly){
3520 // assemblies differ - report an error
3523 Error_CannotChangeAccessModifiers (parent, mb, name);
3525 } else if (thisp != parentp) {
3527 // same assembly, but other attributes differ - report an error
3530 Error_CannotChangeAccessModifiers (parent, mb, name);
3533 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3535 // if it's not "protected internal", it must be "protected"
3538 Error_CannotChangeAccessModifiers (parent, mb, name);
3540 } else if (parent.TypeBuilder.Assembly == mb.DeclaringType.Assembly) {
3542 // protected within the same assembly - an error
3544 Error_CannotChangeAccessModifiers (parent, mb, name);
3546 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3547 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3549 // protected ok, but other attributes differ - report an error
3551 Error_CannotChangeAccessModifiers (parent, mb, name);
3555 if (thisp != parentp){
3556 Error_CannotChangeAccessModifiers (parent, mb, name);
3562 if (mb.IsVirtual || mb.IsAbstract){
3563 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
3564 if (Name != "Finalize"){
3566 114, 2, Location, parent.MakeName (Name) +
3567 " hides inherited member `" + name +
3568 "'. To make the current member override that " +
3569 "implementation, add the override keyword, " +
3570 "otherwise use the new keyword");
3571 ModFlags |= Modifiers.NEW;
3575 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
3576 if (Name != "Finalize"){
3578 108, 1, Location, "The keyword new is required on " +
3579 parent.MakeName (Name) + " because it hides " +
3580 "inherited member `" + name + "'");
3581 ModFlags |= Modifiers.NEW;
3589 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
3593 foreach (Type partype in parameters){
3594 if (partype.IsPointer){
3597 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3601 if (ds.AsAccessible (partype, ModFlags))
3604 if (this is Indexer)
3605 Report.Error (55, Location,
3606 "Inconsistent accessibility: parameter type `" +
3607 TypeManager.CSharpName (partype) + "' is less " +
3608 "accessible than indexer `" + Name + "'");
3609 else if ((this is Method) && ((Method) this).IsOperator)
3610 Report.Error (57, Location,
3611 "Inconsistent accessibility: parameter type `" +
3612 TypeManager.CSharpName (partype) + "' is less " +
3613 "accessible than operator `" + Name + "'");
3615 Report.Error (51, Location,
3616 "Inconsistent accessibility: parameter type `" +
3617 TypeManager.CSharpName (partype) + "' is less " +
3618 "accessible than method `" + Name + "'");
3625 protected virtual bool DoDefine (TypeContainer container)
3630 if (!container.MethodModifiersValid (ModFlags, Name, Location))
3633 flags = Modifiers.MethodAttr (ModFlags);
3635 // Lookup Type, verify validity
3636 MemberType = container.ResolveType (Type, false, Location);
3637 if (MemberType == null)
3640 if ((container.ModFlags & Modifiers.SEALED) != 0){
3641 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
3642 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
3647 // verify accessibility
3648 if (!container.AsAccessible (MemberType, ModFlags)) {
3649 if (this is Property)
3650 Report.Error (53, Location,
3651 "Inconsistent accessibility: property type `" +
3652 TypeManager.CSharpName (MemberType) + "' is less " +
3653 "accessible than property `" + Name + "'");
3654 else if (this is Indexer)
3655 Report.Error (54, Location,
3656 "Inconsistent accessibility: indexer return type `" +
3657 TypeManager.CSharpName (MemberType) + "' is less " +
3658 "accessible than indexer `" + Name + "'");
3659 else if (this is Method) {
3660 if (((Method) this).IsOperator)
3661 Report.Error (56, Location,
3662 "Inconsistent accessibility: return type `" +
3663 TypeManager.CSharpName (MemberType) + "' is less " +
3664 "accessible than operator `" + Name + "'");
3666 Report.Error (50, Location,
3667 "Inconsistent accessibility: return type `" +
3668 TypeManager.CSharpName (MemberType) + "' is less " +
3669 "accessible than method `" + Name + "'");
3671 Report.Error (52, Location,
3672 "Inconsistent accessibility: field type `" +
3673 TypeManager.CSharpName (MemberType) + "' is less " +
3674 "accessible than field `" + Name + "'");
3678 if (MemberType.IsPointer && !UnsafeOK (container))
3682 // Check for explicit interface implementation
3684 if ((ExplicitInterfaceName == null) && (Name.IndexOf (".") != -1)){
3685 int pos = Name.LastIndexOf (".");
3687 ExplicitInterfaceName = Name.Substring (0, pos);
3688 ShortName = Name.Substring (pos + 1);
3692 if (ExplicitInterfaceName != null) {
3693 InterfaceType = RootContext.LookupType (
3694 container, ExplicitInterfaceName, false, Location);
3695 if (InterfaceType == null)
3698 // Compute the full name that we need to export.
3699 Name = InterfaceType.FullName + "." + ShortName;
3701 if (!container.VerifyImplements (InterfaceType, ShortName, Name, Location))
3704 IsExplicitImpl = true;
3706 IsExplicitImpl = false;
3713 // Fields and Events both generate FieldBuilders, we use this to share
3714 // their common bits. This is also used to flag usage of the field
3716 abstract public class FieldBase : MemberBase {
3717 public FieldBuilder FieldBuilder;
3718 public Status status;
3721 public enum Status : byte { ASSIGNED = 1, USED = 2 }
3724 // The constructor is only exposed to our children
3726 protected FieldBase (Expression type, int mod, int allowed_mod, string name,
3727 object init, Attributes attrs, Location loc)
3728 : base (type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
3734 // Whether this field has an initializer.
3736 public bool HasInitializer {
3738 return init != null;
3742 public bool IsAssigned;
3744 protected readonly Object init;
3746 Expression init_expr;
3747 bool init_expr_initialized = false;
3750 // Resolves and returns the field initializer.
3752 public Expression GetInitializerExpression (EmitContext ec)
3754 if (init_expr_initialized)
3758 if (init is Expression)
3759 e = (Expression) init;
3761 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
3763 ec.IsFieldInitializer = true;
3764 e = e.DoResolve (ec);
3765 ec.IsFieldInitializer = false;
3768 init_expr_initialized = true;
3775 // The Field class is used to represents class/struct fields during parsing.
3777 public class Field : FieldBase {
3779 // Modifiers allowed in a class declaration
3781 const int AllowedModifiers =
3784 Modifiers.PROTECTED |
3785 Modifiers.INTERNAL |
3788 Modifiers.VOLATILE |
3792 public Field (Expression type, int mod, string name, Object expr_or_array_init,
3793 Attributes attrs, Location loc)
3794 : base (type, mod, AllowedModifiers, name, expr_or_array_init, attrs, loc)
3798 public override bool Define (TypeContainer container)
3800 Type t = container.ResolveType (Type, false, Location);
3805 CheckBase (container);
3807 if (!container.AsAccessible (t, ModFlags)) {
3808 Report.Error (52, Location,
3809 "Inconsistent accessibility: field type `" +
3810 TypeManager.CSharpName (t) + "' is less " +
3811 "accessible than field `" + Name + "'");
3815 if (t.IsPointer && !UnsafeOK (container))
3818 if (RootContext.WarningLevel > 1){
3819 Type ptype = container.TypeBuilder.BaseType;
3821 // ptype is only null for System.Object while compiling corlib.
3823 TypeContainer.FindMembers (
3824 ptype, MemberTypes.Method,
3825 BindingFlags.Public |
3826 BindingFlags.Static | BindingFlags.Instance,
3827 System.Type.FilterName, Name);
3831 if ((ModFlags & Modifiers.VOLATILE) != 0){
3835 if (TypeManager.IsEnumType (vt))
3836 vt = TypeManager.EnumToUnderlying (t);
3838 if (!((vt == TypeManager.bool_type) ||
3839 (vt == TypeManager.sbyte_type) ||
3840 (vt == TypeManager.byte_type) ||
3841 (vt == TypeManager.short_type) ||
3842 (vt == TypeManager.ushort_type) ||
3843 (vt == TypeManager.int32_type) ||
3844 (vt == TypeManager.uint32_type) ||
3845 (vt == TypeManager.char_type) ||
3846 (vt == TypeManager.float_type))){
3848 677, Location, container.MakeName (Name) +
3849 " A volatile field can not be of type `" +
3850 TypeManager.CSharpName (vt) + "'");
3855 if ((ModFlags & Modifiers.READONLY) != 0){
3858 "A field can not be both volatile and readonly");
3863 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
3865 if (container is Struct &&
3866 ((fa & FieldAttributes.Static) == 0) &&
3867 t == container.TypeBuilder &&
3868 !TypeManager.IsBuiltinType (t)){
3869 Report.Error (523, Location, "Struct member `" + container.Name + "." + Name +
3870 "' causes a cycle in the structure layout");
3874 FieldBuilder = container.TypeBuilder.DefineField (
3875 Name, t, Modifiers.FieldAttr (ModFlags));
3877 TypeManager.RegisterFieldBase (FieldBuilder, this);
3881 public void Emit (TypeContainer tc)
3883 EmitContext ec = new EmitContext (tc, Location, null,
3884 FieldBuilder.FieldType, ModFlags);
3886 Attribute.ApplyAttributes (ec, FieldBuilder, this, OptAttributes);
3891 // `set' and `get' accessors are represented with an Accessor.
3893 public class Accessor {
3895 // Null if the accessor is empty, or a Block if not
3898 public Attributes OptAttributes;
3900 public Accessor (Block b, Attributes attrs)
3903 OptAttributes = attrs;
3908 // Properties and Indexers both generate PropertyBuilders, we use this to share
3909 // their common bits.
3911 abstract public class PropertyBase : MethodCore {
3912 public Accessor Get, Set;
3913 public PropertyBuilder PropertyBuilder;
3914 public MethodBuilder GetBuilder, SetBuilder;
3915 public MethodData GetData, SetData;
3917 protected EmitContext ec;
3919 public PropertyBase (DeclSpace ds, Expression type, string name, int mod_flags,
3920 int allowed_mod, Parameters parameters,
3921 Accessor get_block, Accessor set_block,
3922 Attributes attrs, Location loc)
3923 : base (ds, type, mod_flags, allowed_mod, name, attrs, parameters, loc)
3929 protected override bool DoDefine (TypeContainer container)
3931 if (!base.DoDefine (container))
3934 ec = new EmitContext (container, Location, null, MemberType, ModFlags);
3940 // Checks our base implementation if any
3942 protected override bool CheckBase (TypeContainer container)
3944 base.CheckBase (container);
3946 // Check whether arguments were correct.
3947 if (!DoDefineParameters ())
3954 MethodSignature ms, base_ms;
3955 if (this is Indexer) {
3956 string name, base_name;
3958 report_name = "this";
3959 name = TypeManager.IndexerPropertyName (container.TypeBuilder);
3960 ms = new MethodSignature (name, null, ParameterTypes);
3961 base_name = TypeManager.IndexerPropertyName (container.TypeBuilder.BaseType);
3962 base_ms = new MethodSignature (base_name, null, ParameterTypes);
3965 ms = base_ms = new MethodSignature (Name, null, ParameterTypes);
3969 // Verify if the parent has a type with the same name, and then
3970 // check whether we have to create a new slot for it or not.
3972 Type ptype = container.TypeBuilder.BaseType;
3974 // ptype is only null for System.Object while compiling corlib.
3975 if (ptype == null) {
3976 if ((ModFlags & Modifiers.NEW) != 0)
3977 WarningNotHiding (container);
3982 MemberList props_this;
3984 props_this = TypeContainer.FindMembers (
3985 container.TypeBuilder, MemberTypes.Property,
3986 BindingFlags.NonPublic | BindingFlags.Public |
3987 BindingFlags.Static | BindingFlags.Instance |
3988 BindingFlags.DeclaredOnly,
3989 MethodSignature.method_signature_filter, ms);
3991 if (props_this.Count > 0) {
3992 Report.Error (111, Location, "Class `" + container.Name + "' " +
3993 "already defines a member called `" + report_name + "' " +
3994 "with the same parameter types");
3998 MemberList mi_props;
4000 mi_props = TypeContainer.FindMembers (
4001 ptype, MemberTypes.Property,
4002 BindingFlags.NonPublic | BindingFlags.Public |
4003 BindingFlags.Instance | BindingFlags.Static,
4004 MethodSignature.inheritable_method_signature_filter, base_ms);
4006 if (mi_props.Count > 0){
4007 PropertyInfo parent_property = (PropertyInfo) mi_props [0];
4008 string name = parent_property.DeclaringType.Name + "." +
4009 parent_property.Name;
4011 MethodInfo get, set, parent_method;
4012 get = parent_property.GetGetMethod (true);
4013 set = parent_property.GetSetMethod (true);
4016 parent_method = get;
4017 else if (set != null)
4018 parent_method = set;
4020 throw new Exception ("Internal error!");
4022 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
4025 if ((ModFlags & Modifiers.NEW) == 0) {
4026 Type parent_type = TypeManager.TypeToCoreType (
4027 parent_property.PropertyType);
4029 if (parent_type != MemberType) {
4031 508, Location, container.MakeName (Name) + ": cannot " +
4032 "change return type when overriding " +
4033 "inherited member " + name);
4038 if ((ModFlags & Modifiers.NEW) != 0)
4039 WarningNotHiding (container);
4041 if ((ModFlags & Modifiers.OVERRIDE) != 0){
4042 if (this is Indexer)
4043 Report.Error (115, Location,
4044 container.MakeName (Name) +
4045 " no suitable indexers found to override");
4047 Report.Error (115, Location,
4048 container.MakeName (Name) +
4049 " no suitable properties found to override");
4056 public void Emit (TypeContainer tc)
4059 // The PropertyBuilder can be null for explicit implementations, in that
4060 // case, we do not actually emit the ".property", so there is nowhere to
4061 // put the attribute
4063 if (PropertyBuilder != null)
4064 Attribute.ApplyAttributes (ec, PropertyBuilder, this, OptAttributes);
4066 if (GetData != null) {
4067 GetData.Emit (tc, Get.Block, Get);
4071 if (SetData != null) {
4072 SetData.Emit (tc, Set.Block, Set);
4078 public class Property : PropertyBase {
4079 const int AllowedModifiers =
4082 Modifiers.PROTECTED |
4083 Modifiers.INTERNAL |
4087 Modifiers.OVERRIDE |
4088 Modifiers.ABSTRACT |
4093 public Property (DeclSpace ds, Expression type, string name, int mod_flags,
4094 Accessor get_block, Accessor set_block,
4095 Attributes attrs, Location loc)
4096 : base (ds, type, name, mod_flags, AllowedModifiers,
4097 Parameters.EmptyReadOnlyParameters,
4098 get_block, set_block, attrs, loc)
4102 public override bool Define (TypeContainer container)
4104 if (!DoDefine (container))
4107 if (!CheckBase (container))
4110 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
4113 Type [] parameters = TypeManager.NoTypes;
4115 InternalParameters ip = new InternalParameters (
4116 container, Parameters.EmptyReadOnlyParameters);
4118 GetData = new MethodData (container, this, "get", MemberType,
4119 parameters, ip, CallingConventions.Standard,
4120 Get.OptAttributes, ModFlags, flags, false);
4122 if (!GetData.Define (container))
4125 GetBuilder = GetData.MethodBuilder;
4129 Type [] parameters = new Type [1];
4130 parameters [0] = MemberType;
4132 Parameter [] parms = new Parameter [1];
4133 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
4134 InternalParameters ip = new InternalParameters (
4135 container, new Parameters (parms, null, Location));
4137 SetData = new MethodData (container, this, "set", TypeManager.void_type,
4138 parameters, ip, CallingConventions.Standard,
4139 Set.OptAttributes, ModFlags, flags, false);
4141 if (!SetData.Define (container))
4144 SetBuilder = SetData.MethodBuilder;
4145 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4148 // FIXME - PropertyAttributes.HasDefault ?
4150 PropertyAttributes prop_attr =
4151 PropertyAttributes.RTSpecialName |
4152 PropertyAttributes.SpecialName;
4154 if (!IsExplicitImpl){
4155 PropertyBuilder = container.TypeBuilder.DefineProperty (
4156 Name, prop_attr, MemberType, null);
4159 PropertyBuilder.SetGetMethod (GetBuilder);
4162 PropertyBuilder.SetSetMethod (SetBuilder);
4165 // HACK for the reasons exposed above
4167 if (!TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder)) {
4170 "Class `" + container.Name +
4171 "' already contains a definition for the property `" +
4181 /// Gigantic workaround for lameness in SRE follows :
4182 /// This class derives from EventInfo and attempts to basically
4183 /// wrap around the EventBuilder so that FindMembers can quickly
4184 /// return this in it search for members
4186 public class MyEventBuilder : EventInfo {
4189 // We use this to "point" to our Builder which is
4190 // not really a MemberInfo
4192 EventBuilder MyBuilder;
4195 // We "catch" and wrap these methods
4197 MethodInfo raise, remove, add;
4199 EventAttributes attributes;
4200 Type declaring_type, reflected_type, event_type;
4205 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
4207 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
4209 // And now store the values in our own fields.
4211 declaring_type = type_builder;
4213 reflected_type = type_builder;
4215 attributes = event_attr;
4218 this.event_type = event_type;
4222 // Methods that you have to override. Note that you only need
4223 // to "implement" the variants that take the argument (those are
4224 // the "abstract" methods, the others (GetAddMethod()) are
4227 public override MethodInfo GetAddMethod (bool nonPublic)
4232 public override MethodInfo GetRemoveMethod (bool nonPublic)
4237 public override MethodInfo GetRaiseMethod (bool nonPublic)
4243 // These methods make "MyEventInfo" look like a Builder
4245 public void SetRaiseMethod (MethodBuilder raiseMethod)
4247 raise = raiseMethod;
4248 MyBuilder.SetRaiseMethod (raiseMethod);
4251 public void SetRemoveOnMethod (MethodBuilder removeMethod)
4253 remove = removeMethod;
4254 MyBuilder.SetRemoveOnMethod (removeMethod);
4257 public void SetAddOnMethod (MethodBuilder addMethod)
4260 MyBuilder.SetAddOnMethod (addMethod);
4263 public void SetCustomAttribute (CustomAttributeBuilder cb)
4265 MyBuilder.SetCustomAttribute (cb);
4268 public override object [] GetCustomAttributes (bool inherit)
4270 // FIXME : There's nothing which can be seemingly done here because
4271 // we have no way of getting at the custom attribute objects of the
4276 public override object [] GetCustomAttributes (Type t, bool inherit)
4278 // FIXME : Same here !
4282 public override bool IsDefined (Type t, bool b)
4287 public override EventAttributes Attributes {
4293 public override string Name {
4299 public override Type DeclaringType {
4301 return declaring_type;
4305 public override Type ReflectedType {
4307 return reflected_type;
4311 public Type EventType {
4317 public void SetUsed ()
4319 if (my_event != null)
4320 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
4324 public class Event : FieldBase {
4325 const int AllowedModifiers =
4328 Modifiers.PROTECTED |
4329 Modifiers.INTERNAL |
4334 Modifiers.OVERRIDE |
4338 public readonly Accessor Add;
4339 public readonly Accessor Remove;
4340 public MyEventBuilder EventBuilder;
4342 MethodBuilder AddBuilder, RemoveBuilder;
4343 MethodData AddData, RemoveData;
4345 public Event (Expression type, string name, Object init, int mod, Accessor add,
4346 Accessor remove, Attributes attrs, Location loc)
4347 : base (type, mod, AllowedModifiers, name, init, attrs, loc)
4353 public override bool Define (TypeContainer container)
4355 EventAttributes e_attr = EventAttributes.RTSpecialName | EventAttributes.SpecialName;
4356 MethodAttributes m_attr = MethodAttributes.HideBySig | MethodAttributes.SpecialName
4358 if (!DoDefine (container))
4361 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
4362 Report.Error (74, Location, "'" + container.Name + "." + Name +
4363 "': abstract event can not have an initializer");
4367 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
4368 Report.Error (66, Location, "'" + container.Name + "." + Name +
4369 "' : event must be of a delegate type");
4373 Type [] parameter_types = new Type [1];
4374 parameter_types [0] = MemberType;
4376 Parameter [] parms = new Parameter [1];
4377 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
4378 InternalParameters ip = new InternalParameters (
4379 container, new Parameters (parms, null, Location));
4381 if (!CheckBase (container))
4385 // Now define the accessors
4387 AddData = new MethodData (container, this, "add", TypeManager.void_type,
4388 parameter_types, ip, CallingConventions.Standard,
4389 (Add != null) ? Add.OptAttributes : null,
4390 ModFlags, flags | m_attr, false);
4392 if (!AddData.Define (container))
4395 AddBuilder = AddData.MethodBuilder;
4396 AddBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4398 RemoveData = new MethodData (container, this, "remove", TypeManager.void_type,
4399 parameter_types, ip, CallingConventions.Standard,
4400 (Remove != null) ? Remove.OptAttributes : null,
4401 ModFlags, flags | m_attr, false);
4403 if (!RemoveData.Define (container))
4406 RemoveBuilder = RemoveData.MethodBuilder;
4407 RemoveBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4409 if (!IsExplicitImpl){
4410 EventBuilder = new MyEventBuilder (this,
4411 container.TypeBuilder, Name, e_attr, MemberType);
4413 if (Add == null && Remove == null) {
4414 FieldBuilder = container.TypeBuilder.DefineField (
4416 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
4417 TypeManager.RegisterPrivateFieldOfEvent (
4418 (EventInfo) EventBuilder, FieldBuilder);
4419 TypeManager.RegisterFieldBase (FieldBuilder, this);
4422 EventBuilder.SetAddOnMethod (AddBuilder);
4423 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
4425 if (!TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder)) {
4426 Report.Error (111, Location,
4427 "Class `" + container.Name +
4428 "' already contains a definition for the event `" +
4437 void EmitDefaultMethod (EmitContext ec, bool is_add)
4439 ILGenerator ig = ec.ig;
4440 MethodInfo method = null;
4443 method = TypeManager.delegate_combine_delegate_delegate;
4445 method = TypeManager.delegate_remove_delegate_delegate;
4447 if ((ModFlags & Modifiers.STATIC) != 0) {
4448 ig.Emit (OpCodes.Ldsfld, (FieldInfo) FieldBuilder);
4449 ig.Emit (OpCodes.Ldarg_0);
4450 ig.Emit (OpCodes.Call, method);
4451 ig.Emit (OpCodes.Castclass, MemberType);
4452 ig.Emit (OpCodes.Stsfld, (FieldInfo) FieldBuilder);
4454 ig.Emit (OpCodes.Ldarg_0);
4455 ig.Emit (OpCodes.Ldarg_0);
4456 ig.Emit (OpCodes.Ldfld, (FieldInfo) FieldBuilder);
4457 ig.Emit (OpCodes.Ldarg_1);
4458 ig.Emit (OpCodes.Call, method);
4459 ig.Emit (OpCodes.Castclass, MemberType);
4460 ig.Emit (OpCodes.Stfld, (FieldInfo) FieldBuilder);
4462 ig.Emit (OpCodes.Ret);
4465 public void Emit (TypeContainer tc)
4469 ec = new EmitContext (tc, Location, null, MemberType, ModFlags);
4470 Attribute.ApplyAttributes (ec, EventBuilder, this, OptAttributes);
4473 AddData.Emit (tc, Add.Block, Add);
4476 ILGenerator ig = AddData.MethodBuilder.GetILGenerator ();
4477 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
4478 EmitDefaultMethod (ec, true);
4481 if (Remove != null) {
4482 RemoveData.Emit (tc, Remove.Block, Remove);
4483 Remove.Block = null;
4485 ILGenerator ig = RemoveData.MethodBuilder.GetILGenerator ();
4486 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
4487 EmitDefaultMethod (ec, false);
4494 // FIXME: This does not handle:
4496 // int INTERFACENAME [ args ]
4501 // int this [ args ]
4503 public class Indexer : PropertyBase {
4505 const int AllowedModifiers =
4508 Modifiers.PROTECTED |
4509 Modifiers.INTERNAL |
4513 Modifiers.OVERRIDE |
4518 public string IndexerName;
4519 public string InterfaceIndexerName;
4522 // Are we implementing an interface ?
4524 bool IsImplementing = false;
4526 public Indexer (DeclSpace ds, Expression type, string int_type, int flags,
4527 Parameters parameters, Accessor get_block, Accessor set_block,
4528 Attributes attrs, Location loc)
4529 : base (ds, type, "", flags, AllowedModifiers, parameters, get_block, set_block,
4532 ExplicitInterfaceName = int_type;
4535 public override bool Define (TypeContainer container)
4537 PropertyAttributes prop_attr =
4538 PropertyAttributes.RTSpecialName |
4539 PropertyAttributes.SpecialName;
4541 if (!DoDefine (container))
4544 IndexerName = Attribute.ScanForIndexerName (ec, OptAttributes);
4545 if (IndexerName == null)
4546 IndexerName = "Item";
4547 else if (IsExplicitImpl)
4548 Report.Error (592, Location,
4549 "Attribute 'IndexerName' is not valid on this declaration " +
4550 "type. It is valid on `property' declarations only.");
4552 ShortName = IndexerName;
4553 if (IsExplicitImpl) {
4554 InterfaceIndexerName = TypeManager.IndexerPropertyName (InterfaceType);
4555 Name = InterfaceType.FullName + "." + IndexerName;
4557 InterfaceIndexerName = IndexerName;
4561 if (!CheckBase (container))
4564 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
4566 InternalParameters ip = new InternalParameters (container, Parameters);
4568 GetData = new MethodData (container, this, "get", MemberType,
4569 ParameterTypes, ip, CallingConventions.Standard,
4570 Get.OptAttributes, ModFlags, flags, false);
4572 if (!GetData.Define (container))
4575 GetBuilder = GetData.MethodBuilder;
4579 int top = ParameterTypes.Length;
4580 Type [] set_pars = new Type [top + 1];
4581 ParameterTypes.CopyTo (set_pars, 0);
4582 set_pars [top] = MemberType;
4584 Parameter [] fixed_parms = Parameters.FixedParameters;
4586 if (fixed_parms == null){
4587 throw new Exception ("We currently do not support only array arguments in an indexer at: " + Location);
4588 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4589 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4591 // Here is the problem: the `value' parameter has
4592 // to come *after* the array parameter in the declaration
4594 // X (object [] x, Type value)
4597 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4598 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4602 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
4605 fixed_parms.CopyTo (tmp, 0);
4606 tmp [fixed_parms.Length] = new Parameter (
4607 Type, "value", Parameter.Modifier.NONE, null);
4609 Parameters set_formal_params = new Parameters (tmp, null, Location);
4611 InternalParameters ip = new InternalParameters (container, set_formal_params);
4613 SetData = new MethodData (container, this, "set", TypeManager.void_type,
4614 set_pars, ip, CallingConventions.Standard,
4615 Set.OptAttributes, ModFlags, flags, false);
4617 if (!SetData.Define (container))
4620 SetBuilder = SetData.MethodBuilder;
4624 // Now name the parameters
4626 Parameter [] p = Parameters.FixedParameters;
4630 for (i = 0; i < p.Length; ++i) {
4632 GetBuilder.DefineParameter (
4633 i + 1, p [i].Attributes, p [i].Name);
4636 SetBuilder.DefineParameter (
4637 i + 1, p [i].Attributes, p [i].Name);
4641 SetBuilder.DefineParameter (
4642 i + 1, ParameterAttributes.None, "value");
4644 if (i != ParameterTypes.Length) {
4645 Parameter array_param = Parameters.ArrayParameter;
4647 SetBuilder.DefineParameter (
4648 i + 1, array_param.Attributes, array_param.Name);
4652 if (GetData != null)
4653 IsImplementing = GetData.IsImplementing;
4654 else if (SetData != null)
4655 IsImplementing = SetData.IsImplementing;
4658 // Define the PropertyBuilder if one of the following conditions are met:
4659 // a) we're not implementing an interface indexer.
4660 // b) the indexer has a different IndexerName and this is no
4661 // explicit interface implementation.
4663 if (!IsExplicitImpl) {
4664 PropertyBuilder = container.TypeBuilder.DefineProperty (
4665 IndexerName, prop_attr, MemberType, ParameterTypes);
4667 if (GetData != null)
4668 PropertyBuilder.SetGetMethod (GetBuilder);
4670 if (SetData != null)
4671 PropertyBuilder.SetSetMethod (SetBuilder);
4673 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder,
4681 public class Operator : MemberBase {
4683 const int AllowedModifiers =
4689 const int RequiredModifiers =
4693 public enum OpType : byte {
4703 // Unary and Binary operators
4726 // Implicit and Explicit
4731 public readonly OpType OperatorType;
4732 public readonly Expression ReturnType;
4733 public readonly Expression FirstArgType, SecondArgType;
4734 public readonly string FirstArgName, SecondArgName;
4736 public MethodBuilder OperatorMethodBuilder;
4738 public string MethodName;
4739 public Method OperatorMethod;
4741 public Operator (OpType type, Expression ret_type, int mod_flags,
4742 Expression arg1type, string arg1name,
4743 Expression arg2type, string arg2name,
4744 Block block, Attributes attrs, Location loc)
4745 : base (ret_type, mod_flags, AllowedModifiers, Modifiers.PUBLIC, "", attrs, loc)
4747 OperatorType = type;
4748 ReturnType = ret_type;
4749 FirstArgType = arg1type;
4750 FirstArgName = arg1name;
4751 SecondArgType = arg2type;
4752 SecondArgName = arg2name;
4756 string Prototype (TypeContainer container)
4758 return container.Name + ".operator " + OperatorType + " (" + FirstArgType + "," +
4759 SecondArgType + ")";
4762 public override bool Define (TypeContainer container)
4765 MethodName = "op_" + OperatorType;
4767 if (SecondArgType != null)
4770 Parameter [] param_list = new Parameter [length];
4772 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
4775 "User defined operators `" +
4776 Prototype (container) +
4777 "' must be declared static and public");
4781 param_list[0] = new Parameter (FirstArgType, FirstArgName,
4782 Parameter.Modifier.NONE, null);
4783 if (SecondArgType != null)
4784 param_list[1] = new Parameter (SecondArgType, SecondArgName,
4785 Parameter.Modifier.NONE, null);
4787 OperatorMethod = new Method (container, ReturnType, ModFlags, MethodName,
4788 new Parameters (param_list, null, Location),
4789 OptAttributes, Location);
4791 OperatorMethod.IsOperator = true;
4792 OperatorMethod.Define (container);
4794 if (OperatorMethod.MethodBuilder == null)
4797 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
4799 Type [] param_types = OperatorMethod.ParameterTypes;
4800 Type declaring_type = OperatorMethodBuilder.DeclaringType;
4801 Type return_type = OperatorMethod.GetReturnType ();
4802 Type first_arg_type = param_types [0];
4804 // Rules for conversion operators
4806 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
4807 if (first_arg_type == return_type && first_arg_type == declaring_type){
4810 "User-defined conversion cannot take an object of the " +
4811 "enclosing type and convert to an object of the enclosing" +
4816 if (first_arg_type != declaring_type && return_type != declaring_type){
4819 "User-defined conversion must convert to or from the " +
4824 if (first_arg_type == TypeManager.object_type ||
4825 return_type == TypeManager.object_type){
4828 "User-defined conversion cannot convert to or from " +
4833 if (first_arg_type.IsInterface || return_type.IsInterface){
4836 "User-defined conversion cannot convert to or from an " +
4841 if (first_arg_type.IsSubclassOf (return_type) ||
4842 return_type.IsSubclassOf (first_arg_type)){
4845 "User-defined conversion cannot convert between types " +
4846 "that derive from each other");
4849 } else if (SecondArgType == null) {
4850 // Checks for Unary operators
4852 if (first_arg_type != declaring_type){
4855 "The parameter of a unary operator must be the " +
4860 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
4861 if (return_type != declaring_type){
4864 "The parameter and return type for ++ and -- " +
4865 "must be the containing type");
4871 if (OperatorType == OpType.True || OperatorType == OpType.False) {
4872 if (return_type != TypeManager.bool_type){
4875 "The return type of operator True or False " +
4882 // Checks for Binary operators
4884 if (first_arg_type != declaring_type &&
4885 param_types [1] != declaring_type){
4888 "One of the parameters of a binary operator must " +
4889 "be the containing type");
4897 public void Emit (TypeContainer container)
4900 // abstract or extern methods have no bodies
4902 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
4905 OperatorMethod.Block = Block;
4906 OperatorMethod.Emit (container);
4910 public static string GetName (OpType ot)
4913 case OpType.LogicalNot:
4915 case OpType.OnesComplement:
4917 case OpType.Increment:
4919 case OpType.Decrement:
4925 case OpType.Addition:
4927 case OpType.Subtraction:
4929 case OpType.UnaryPlus:
4931 case OpType.UnaryNegation:
4933 case OpType.Multiply:
4935 case OpType.Division:
4937 case OpType.Modulus:
4939 case OpType.BitwiseAnd:
4941 case OpType.BitwiseOr:
4943 case OpType.ExclusiveOr:
4945 case OpType.LeftShift:
4947 case OpType.RightShift:
4949 case OpType.Equality:
4951 case OpType.Inequality:
4953 case OpType.GreaterThan:
4955 case OpType.LessThan:
4957 case OpType.GreaterThanOrEqual:
4959 case OpType.LessThanOrEqual:
4961 case OpType.Implicit:
4963 case OpType.Explicit:
4969 public override string ToString ()
4971 Type return_type = OperatorMethod.GetReturnType();
4972 Type [] param_types = OperatorMethod.ParameterTypes;
4974 if (SecondArgType == null)
4975 return String.Format (
4976 "{0} operator {1}({2})",
4977 TypeManager.CSharpName (return_type),
4978 GetName (OperatorType),
4981 return String.Format (
4982 "{0} operator {1}({2}, {3})",
4983 TypeManager.CSharpName (return_type),
4984 GetName (OperatorType),
4985 param_types [0], param_types [1]);
4990 // This is used to compare method signatures
4992 struct MethodSignature {
4994 public Type RetType;
4995 public Type [] Parameters;
4998 /// This delegate is used to extract methods which have the
4999 /// same signature as the argument
5001 public static MemberFilter method_signature_filter;
5004 /// This delegate is used to extract inheritable methods which
5005 /// have the same signature as the argument. By inheritable,
5006 /// this means that we have permissions to override the method
5007 /// from the current assembly and class
5009 public static MemberFilter inheritable_method_signature_filter;
5011 static MethodSignature ()
5013 method_signature_filter = new MemberFilter (MemberSignatureCompare);
5014 inheritable_method_signature_filter = new MemberFilter (
5015 InheritableMemberSignatureCompare);
5018 public MethodSignature (string name, Type ret_type, Type [] parameters)
5023 if (parameters == null)
5024 Parameters = TypeManager.NoTypes;
5026 Parameters = parameters;
5029 public override string ToString ()
5032 if (Parameters.Length != 0){
5033 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
5034 for (int i = 0; i < Parameters.Length; i++){
5035 sb.Append (Parameters [i]);
5036 if (i+1 < Parameters.Length)
5039 pars = sb.ToString ();
5042 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
5045 public override int GetHashCode ()
5047 return Name.GetHashCode ();
5050 public override bool Equals (Object o)
5052 MethodSignature other = (MethodSignature) o;
5054 if (other.Name != Name)
5057 if (other.RetType != RetType)
5060 if (Parameters == null){
5061 if (other.Parameters == null)
5066 if (other.Parameters == null)
5069 int c = Parameters.Length;
5070 if (other.Parameters.Length != c)
5073 for (int i = 0; i < c; i++)
5074 if (other.Parameters [i] != Parameters [i])
5080 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
5082 MethodSignature sig = (MethodSignature) filter_criteria;
5084 if (m.Name != sig.Name)
5088 MethodInfo mi = m as MethodInfo;
5089 PropertyInfo pi = m as PropertyInfo;
5092 ReturnType = mi.ReturnType;
5093 else if (pi != null)
5094 ReturnType = pi.PropertyType;
5099 // we use sig.RetType == null to mean `do not check the
5100 // method return value.
5102 if (sig.RetType != null)
5103 if (ReturnType != sig.RetType)
5108 args = TypeManager.GetArgumentTypes (mi);
5110 args = TypeManager.GetArgumentTypes (pi);
5111 Type [] sigp = sig.Parameters;
5113 if (args.Length != sigp.Length)
5116 for (int i = args.Length; i > 0; ){
5118 if (args [i] != sigp [i])
5125 // This filter should be used when we are requesting methods that
5126 // we want to override.
5128 // This makes a number of assumptions, for example
5129 // that the methods being extracted are of a parent
5130 // class (this means we know implicitly that we are
5131 // being called to find out about members by a derived
5134 static bool InheritableMemberSignatureCompare (MemberInfo m, object filter_criteria)
5137 PropertyInfo pi = m as PropertyInfo;
5140 mi = pi.GetGetMethod (true);
5142 mi = pi.GetSetMethod (true);
5144 mi = m as MethodInfo;
5147 Console.WriteLine ("Nothing found");
5150 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5152 // If only accessible to the current class.
5153 if (prot == MethodAttributes.Private)
5156 if (!MemberSignatureCompare (m, filter_criteria))
5159 // If only accessible to the defining assembly or
5160 if (prot == MethodAttributes.FamANDAssem ||
5161 prot == MethodAttributes.Assembly){
5162 if (m.DeclaringType.Assembly == CodeGen.AssemblyBuilder)
5168 // Anything else (FamOrAssembly and Public) is fine