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 // Information in the case we are an attribute type
118 public AttributeTargets Targets = AttributeTargets.All;
119 public bool AllowMultiple = false;
120 public bool Inherited;
122 // The interfaces we implement.
125 // The parent member container and our member cache
126 IMemberContainer parent_container;
127 MemberCache member_cache;
130 // The indexer name for this class
132 public string IndexerName;
134 public TypeContainer ():
135 this (null, null, "", null, new Location (-1)) {
138 public TypeContainer (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
139 : base (ns, parent, name, attrs, l)
141 types = new ArrayList ();
143 base_class_name = null;
146 public AdditionResult AddConstant (Const constant)
149 string basename = constant.Name;
150 string fullname = Name + "." + basename;
152 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
155 if (constants == null)
156 constants = new ArrayList ();
158 constants.Add (constant);
159 DefineName (fullname, constant);
161 return AdditionResult.Success;
164 public AdditionResult AddEnum (Mono.CSharp.Enum e)
168 if ((res = IsValid (e.Basename, e.Name)) != AdditionResult.Success)
172 enums = new ArrayList ();
175 DefineName (e.Name, e);
177 return AdditionResult.Success;
180 public AdditionResult AddClass (Class c)
183 string name = c.Basename;
185 if ((res = IsValid (name, c.Name)) != AdditionResult.Success)
188 DefineName (c.Name, c);
191 return AdditionResult.Success;
194 public AdditionResult AddStruct (Struct s)
197 string name = s.Basename;
199 if ((res = IsValid (name, s.Name)) != AdditionResult.Success)
202 DefineName (s.Name, s);
205 return AdditionResult.Success;
208 public AdditionResult AddDelegate (Delegate d)
211 string name = d.Basename;
213 if ((res = IsValid (name, d.Name)) != AdditionResult.Success)
216 if (delegates == null)
217 delegates = new ArrayList ();
219 DefineName (d.Name, d);
222 return AdditionResult.Success;
225 public AdditionResult AddMethod (Method method)
227 string basename = method.Name;
228 string fullname = Name + "." + basename;
230 Object value = defined_names [fullname];
232 if (value != null && (!(value is Method)))
233 return AdditionResult.NameExists;
235 if (basename == Basename)
236 return AdditionResult.EnclosingClash;
239 methods = new ArrayList ();
241 if (method.Name.IndexOf ('.') != -1)
242 methods.Insert (0, method);
244 methods.Add (method);
247 DefineName (fullname, method);
249 return AdditionResult.Success;
252 public AdditionResult AddConstructor (Constructor c)
254 if (c.Name != Basename)
255 return AdditionResult.NotAConstructor;
257 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
260 have_static_constructor = true;
261 if (default_static_constructor != null){
262 Console.WriteLine ("I have a static constructor already");
263 Console.WriteLine (" " + default_static_constructor);
264 return AdditionResult.MethodExists;
267 default_static_constructor = c;
270 if (default_constructor != null)
271 return AdditionResult.MethodExists;
272 default_constructor = c;
275 if (instance_constructors == null)
276 instance_constructors = new ArrayList ();
278 instance_constructors.Add (c);
281 return AdditionResult.Success;
284 public AdditionResult AddInterface (Interface iface)
287 string name = iface.Basename;
289 if ((res = IsValid (name, iface.Name)) != AdditionResult.Success)
292 if (interfaces == null)
293 interfaces = new ArrayList ();
294 interfaces.Add (iface);
295 DefineName (iface.Name, iface);
297 return AdditionResult.Success;
300 public AdditionResult AddField (Field field)
303 string basename = field.Name;
304 string fullname = Name + "." + basename;
306 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
310 fields = new ArrayList ();
314 if (field.HasInitializer){
315 if ((field.ModFlags & Modifiers.STATIC) != 0){
316 if (initialized_static_fields == null)
317 initialized_static_fields = new ArrayList ();
319 initialized_static_fields.Add (field);
322 // We have not seen a static constructor,
323 // but we will provide static initialization of fields
325 have_static_constructor = true;
327 if (initialized_fields == null)
328 initialized_fields = new ArrayList ();
330 initialized_fields.Add (field);
334 if ((field.ModFlags & Modifiers.STATIC) == 0)
335 have_nonstatic_fields = true;
337 DefineName (fullname, field);
338 return AdditionResult.Success;
341 public AdditionResult AddProperty (Property prop)
344 string basename = prop.Name;
345 string fullname = Name + "." + basename;
347 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
350 if (properties == null)
351 properties = new ArrayList ();
353 if (prop.Name.IndexOf ('.') != -1)
354 properties.Insert (0, prop);
356 properties.Add (prop);
357 DefineName (fullname, prop);
359 return AdditionResult.Success;
362 public AdditionResult AddEvent (Event e)
365 string basename = e.Name;
366 string fullname = Name + "." + basename;
368 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
372 events = new ArrayList ();
375 DefineName (fullname, e);
377 return AdditionResult.Success;
380 public AdditionResult AddIndexer (Indexer i)
382 if (indexers == null)
383 indexers = new ArrayList ();
385 if (i.InterfaceType != null)
386 indexers.Insert (0, i);
390 return AdditionResult.Success;
393 public AdditionResult AddOperator (Operator op)
395 if (operators == null)
396 operators = new ArrayList ();
400 return AdditionResult.Success;
403 public void RegisterOrder (Interface iface)
405 if (interface_order == null)
406 interface_order = new ArrayList ();
408 interface_order.Add (iface);
411 public ArrayList Types {
417 public ArrayList Methods {
423 public ArrayList Constants {
429 public ArrayList Interfaces {
437 return base_class_name;
441 public ArrayList Bases {
451 public ArrayList Fields {
461 public ArrayList InstanceConstructors {
463 return instance_constructors;
467 public ArrayList Properties {
473 public ArrayList Events {
479 public ArrayList Enums {
485 public ArrayList Indexers {
491 public ArrayList Operators {
497 public ArrayList Delegates {
503 public bool HaveStaticConstructor {
505 return have_static_constructor;
509 public virtual TypeAttributes TypeAttr {
511 return Modifiers.TypeAttr (ModFlags, this);
516 // Emits the instance field initializers
518 public bool EmitFieldInitializers (EmitContext ec)
521 Expression instance_expr;
524 fields = initialized_static_fields;
525 instance_expr = null;
527 fields = initialized_fields;
528 instance_expr = new This (Location.Null).Resolve (ec);
534 foreach (Field f in fields){
535 Expression e = f.GetInitializerExpression (ec);
539 Location l = f.Location;
540 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
541 fe.InstanceExpression = instance_expr;
542 ExpressionStatement a = new Assign (fe, e, l);
544 a = a.ResolveStatement (ec);
548 a.EmitStatement (ec);
555 // Defines the default constructors
557 void DefineDefaultConstructor (bool is_static)
561 // The default constructor is public
562 // If the class is abstract, the default constructor is protected
563 // The default static constructor is private
565 int mods = Modifiers.PUBLIC;
567 mods = Modifiers.STATIC | Modifiers.PRIVATE;
568 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
569 mods = Modifiers.PROTECTED;
571 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
572 new ConstructorBaseInitializer (
573 null, Parameters.EmptyReadOnlyParameters,
579 c.Block = new ToplevelBlock (null, Location);
583 public void ReportStructInitializedInstanceError ()
585 string n = TypeBuilder.FullName;
587 foreach (Field f in initialized_fields){
590 "`" + n + "." + f.Name + "': can not have " +
591 "instance field initializers in structs");
596 /// The pending methods that need to be implemented (interfaces or abstract methods)
598 public PendingImplementation Pending;
601 /// This function computes the Base class and also the
602 /// list of interfaces that the class or struct @c implements.
604 /// The return value is an array (might be null) of
605 /// interfaces implemented (as Types).
607 /// The @parent argument is set to the parent object or null
608 /// if this is `System.Object'.
610 TypeExpr [] GetClassBases (bool is_class, out TypeExpr parent, out bool error)
612 ArrayList bases = Bases;
621 parent = TypeManager.system_valuetype_expr;
625 if (RootContext.StdLib)
626 parent = TypeManager.system_object_expr;
627 else if (Name != "System.Object")
628 parent = TypeManager.system_object_expr;
631 // If we are compiling our runtime,
632 // and we are defining ValueType, then our
633 // parent is `System.Object'.
635 if (!RootContext.StdLib && Name == "System.ValueType")
636 parent = TypeManager.system_object_expr;
643 // Bases should be null if there are no bases at all
648 TypeExpr name = ResolveTypeExpr ((Expression) bases [0], false, Location);
659 parent = TypeManager.system_object_expr;
665 if (name.IsValueType)
666 detail = " (a class can not inherit from a struct/enum)";
668 Report.Error (509, "class `"+ Name +
669 "': Cannot inherit from sealed class `"+
670 name.Name + "'" + detail);
675 if (!parent.CanInheritFrom ()){
676 Report.Error (644, Location,
677 "`{0}' cannot inherit from special class `{1}'",
683 if (!parent.AsAccessible (this, ModFlags))
684 Report.Error (60, Location,
685 "Inconsistent accessibility: base class `" +
686 name.Name + "' is less accessible than class `" +
694 base_class_name = parent.Name;
696 TypeExpr [] ifaces = new TypeExpr [count-start];
698 for (i = start, j = 0; i < count; i++, j++){
699 Expression name = (Expression) bases [i];
700 TypeExpr resolved = ResolveTypeExpr (name, false, Location);
701 if (resolved == null)
704 bases [i] = resolved;
706 if (is_class == false && !resolved.IsInterface){
707 Report.Error (527, "In Struct `" + Name + "', type `"+
708 name +"' is not an interface");
713 if (resolved.IsClass) {
715 Report.Error (527, "In Class `" + Name + "', type `"+
716 name+"' is not an interface");
722 for (int x = 0; x < j; x++) {
723 if (resolved == ifaces [x]) {
724 Report.Error (528, "`" + name + "' is already listed in interface list");
730 ifaces [j] = resolved;
733 return TypeManager.ExpandInterfaces (ifaces);
739 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
741 public override TypeBuilder DefineType ()
746 if (TypeBuilder != null)
753 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
765 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
767 ifaces = GetClassBases (is_class, out parent, out error);
772 if (!is_class && TypeManager.value_type == null)
773 throw new Exception ();
775 TypeAttributes type_attributes = TypeAttr;
779 ptype = parent.ResolveType (ec);
784 if (TypeManager.NamespaceClash (Name, Location)) {
789 ModuleBuilder builder = CodeGen.ModuleBuilder;
790 TypeBuilder = builder.DefineType (
791 Name, type_attributes, ptype, null);
794 TypeBuilder builder = Parent.DefineType ();
798 TypeBuilder = builder.DefineNestedType (
799 Basename, type_attributes, ptype, null);
803 // Structs with no fields need to have at least one byte.
804 // The right thing would be to set the PackingSize in a DefineType
805 // but there are no functions that allow interfaces *and* the size to
809 if (!is_class && !have_nonstatic_fields){
810 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
811 FieldAttributes.Private);
814 // add interfaces that were not added at type creation
815 if (ifaces != null) {
816 foreach (TypeExpr iface in ifaces) {
817 Type itype = iface.ResolveType (ec);
818 TypeBuilder.AddInterfaceImplementation (itype);
823 // Finish the setup for the EmitContext
825 ec.ContainerType = TypeBuilder;
827 TypeManager.AddUserType (Name, TypeBuilder, this, ifaces);
829 if ((parent != null) && parent.IsAttribute) {
830 RootContext.RegisterAttribute (this);
831 TypeManager.RegisterAttrType (TypeBuilder, this);
833 RootContext.RegisterOrder (this);
835 if (Interfaces != null) {
836 foreach (Interface iface in Interfaces)
837 if (iface.DefineType () == null) {
844 foreach (TypeContainer tc in Types)
845 if (tc.DefineType () == null) {
851 if (Delegates != null) {
852 foreach (Delegate d in Delegates)
853 if (d.DefineType () == null) {
860 foreach (Enum en in Enums)
861 if (en.DefineType () == null) {
873 /// Defines the MemberCore objects that are in the `list' Arraylist
875 /// The `defined_names' array contains a list of members defined in
878 static ArrayList remove_list = new ArrayList ();
879 void DefineMembers (ArrayList list, MemberInfo [] defined_names)
883 remove_list.Clear ();
885 foreach (MemberCore mc in list){
887 if (defined_names != null)
888 idx = Array.BinarySearch (defined_names, mc.Name, mif_compare);
893 if (RootContext.WarningLevel >= 4){
894 if ((mc.ModFlags & Modifiers.NEW) != 0)
895 Warning_KeywordNewNotRequired (mc.Location, mc);
897 } else if (mc is MethodCore)
898 ((MethodCore) mc).OverridesSomething = true;
900 if (!mc.Define (this)){
901 remove_list.Add (mc);
908 MemberInfo match = defined_names [idx];
910 if (match is PropertyInfo && ((mc.ModFlags & Modifiers.OVERRIDE) != 0))
914 // If we are both methods, let the method resolution emit warnings
916 if (match is MethodBase && mc is MethodCore)
919 if ((mc.ModFlags & Modifiers.NEW) == 0) {
921 if (!(match is EventInfo)) {
922 Error_EventCanOnlyOverrideEvent (mc.Location, defined_names [idx]);
926 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
930 Warning_KeywordNewRequired (mc.Location, defined_names [idx]);
934 foreach (object o in remove_list)
937 remove_list.Clear ();
941 // Defines the indexers, and also verifies that the IndexerNameAttribute in the
942 // class is consisten. Either it is `Item' or it is the name defined by all the
943 // indexers with the `IndexerName' attribute.
945 // Turns out that the IndexerNameAttribute is applied to each indexer,
946 // but it is never emitted, instead a DefaultName attribute is attached
949 void DefineIndexers ()
951 string class_indexer_name = null;
954 // If there's both an explicit and an implicit interface implementation, the
955 // explicit one actually implements the interface while the other one is just
956 // a normal indexer. See bug #37714.
958 ArrayList list = new ArrayList ();
959 foreach (Indexer i in Indexers){
960 if (i.ExplicitInterfaceName != null)
963 foreach (Indexer i in Indexers){
964 if (i.ExplicitInterfaceName == null)
968 foreach (Indexer i in list){
973 name = i.IndexerName;
975 if (i.InterfaceType != null)
978 if (class_indexer_name == null){
979 class_indexer_name = name;
983 if (name == class_indexer_name)
987 668, "Two indexers have different names, " +
988 " you should use the same name for all your indexers");
990 if (class_indexer_name == null)
991 class_indexer_name = "Item";
992 IndexerName = class_indexer_name;
995 static void Error_KeywordNotAllowed (Location loc)
997 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1001 /// Populates our TypeBuilder with fields and methods
1003 public override bool DefineMembers (TypeContainer container)
1005 MemberInfo [] defined_names = null;
1007 if (interface_order != null){
1008 foreach (Interface iface in interface_order)
1009 if ((iface.ModFlags & Modifiers.NEW) == 0)
1010 iface.DefineMembers (this);
1012 Error_KeywordNotAllowed (iface.Location);
1015 if (RootContext.WarningLevel > 1){
1019 // This code throws an exception in the comparer
1020 // I guess the string is not an object?
1022 ptype = TypeBuilder.BaseType;
1024 defined_names = (MemberInfo []) FindMembers (
1025 ptype, MemberTypes.All & ~MemberTypes.Constructor,
1026 BindingFlags.Public | BindingFlags.Instance |
1027 BindingFlags.Static, null, null);
1029 Array.Sort (defined_names, mif_compare);
1033 Class pclass = Parent as Class;
1034 if (pclass != null) {
1035 string pname = null;
1037 Type t = pclass.TypeBuilder.BaseType;
1038 while ((t != null) && (ptype == null)) {
1039 pname = t.FullName + "." + Basename;
1040 ptype = RootContext.LookupType (this, pname, true, Location.Null);
1044 if ((ModFlags & Modifiers.NEW) != 0) {
1046 Report.Warning (109, Location, "The member '" + Name + "' does not hide an " +
1047 "inherited member. The keyword new is not required.");
1048 } else if (ptype != null) {
1049 Report.Warning (108, Location, "The keyword new is required on `" +
1050 Name + "' because it hides inherited member '" +
1053 } else if ((ModFlags & Modifiers.NEW) != 0)
1054 Error_KeywordNotAllowed (Location);
1056 if (constants != null)
1057 DefineMembers (constants, defined_names);
1060 DefineMembers (fields, defined_names);
1063 if (instance_constructors == null){
1064 if (default_constructor == null)
1065 DefineDefaultConstructor (false);
1068 if (initialized_static_fields != null &&
1069 default_static_constructor == null)
1070 DefineDefaultConstructor (true);
1073 if (this is Struct){
1075 // Structs can not have initialized instance
1078 if (initialized_static_fields != null &&
1079 default_static_constructor == null)
1080 DefineDefaultConstructor (true);
1082 if (initialized_fields != null)
1083 ReportStructInitializedInstanceError ();
1086 Pending = PendingImplementation.GetPendingImplementations (this);
1089 // Constructors are not in the defined_names array
1091 if (instance_constructors != null)
1092 DefineMembers (instance_constructors, null);
1094 if (default_static_constructor != null)
1095 default_static_constructor.Define (this);
1097 if (methods != null)
1098 DefineMembers (methods, defined_names);
1100 if (properties != null)
1101 DefineMembers (properties, defined_names);
1104 DefineMembers (events, defined_names);
1106 if (indexers != null) {
1109 IndexerName = "Item";
1111 if (operators != null){
1112 DefineMembers (operators, null);
1114 CheckPairedOperators ();
1118 DefineMembers (enums, defined_names);
1120 if (delegates != null)
1121 DefineMembers (delegates, defined_names);
1124 if (TypeBuilder.BaseType != null)
1125 parent_container = TypeManager.LookupMemberContainer (TypeBuilder.BaseType);
1127 member_cache = new MemberCache (this);
1134 public override bool Define (TypeContainer container)
1136 if (interface_order != null){
1137 foreach (Interface iface in interface_order)
1138 if ((iface.ModFlags & Modifiers.NEW) == 0)
1139 iface.Define (this);
1146 /// This function is based by a delegate to the FindMembers routine
1148 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1154 /// This filter is used by FindMembers, and we just keep
1155 /// a global for the filter to `AlwaysAccept'
1157 static MemberFilter accepting_filter;
1161 /// A member comparission method based on name only
1163 static IComparer mif_compare;
1165 static TypeContainer ()
1167 accepting_filter = new MemberFilter (AlwaysAccept);
1168 mif_compare = new MemberInfoCompare ();
1172 /// This method returns the members of this type just like Type.FindMembers would
1173 /// Only, we need to use this for types which are _being_ defined because MS'
1174 /// implementation can't take care of that.
1177 // FIXME: return an empty static array instead of null, that cleans up
1178 // some code and is consistent with some coding conventions I just found
1182 // Notice that in various cases we check if our field is non-null,
1183 // something that would normally mean that there was a bug elsewhere.
1185 // The problem happens while we are defining p-invoke methods, as those
1186 // will trigger a FindMembers, but this happens before things are defined
1188 // Since the whole process is a no-op, it is fine to check for null here.
1190 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1191 MemberFilter filter, object criteria)
1193 ArrayList members = null;
1196 if ((bf & BindingFlags.Public) != 0)
1197 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1199 if ((bf & BindingFlags.NonPublic) != 0)
1200 modflags |= Modifiers.PRIVATE;
1202 int static_mask = 0, static_flags = 0;
1203 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1204 case BindingFlags.Static:
1205 static_mask = static_flags = Modifiers.STATIC;
1208 case BindingFlags.Instance:
1209 static_mask = Modifiers.STATIC;
1214 static_mask = static_flags = 0;
1218 Timer.StartTimer (TimerType.TcFindMembers);
1221 filter = accepting_filter;
1223 if ((mt & MemberTypes.Field) != 0) {
1224 if (fields != null) {
1225 int len = fields.Count;
1226 for (int i = 0; i < len; i++) {
1227 Field f = (Field) fields [i];
1229 if ((f.ModFlags & modflags) == 0)
1231 if ((f.ModFlags & static_mask) != static_flags)
1234 FieldBuilder fb = f.FieldBuilder;
1235 if (fb != null && filter (fb, criteria) == true) {
1236 if (members == null)
1237 members = new ArrayList ();
1244 if (constants != null) {
1245 int len = constants.Count;
1246 for (int i = 0; i < len; i++) {
1247 Const con = (Const) constants [i];
1249 if ((con.ModFlags & modflags) == 0)
1251 if ((con.ModFlags & static_mask) != static_flags)
1254 FieldBuilder fb = con.FieldBuilder;
1255 if (fb != null && filter (fb, criteria) == true) {
1256 if (members == null)
1257 members = new ArrayList ();
1265 if ((mt & MemberTypes.Method) != 0) {
1266 if (methods != null) {
1267 int len = methods.Count;
1268 for (int i = 0; i < len; i++) {
1269 Method m = (Method) methods [i];
1271 if ((m.ModFlags & modflags) == 0)
1273 if ((m.ModFlags & static_mask) != static_flags)
1276 MethodBuilder mb = m.MethodBuilder;
1278 if (mb != null && filter (mb, criteria) == true) {
1279 if (members == null)
1280 members = new ArrayList ();
1287 if (operators != null) {
1288 int len = operators.Count;
1289 for (int i = 0; i < len; i++) {
1290 Operator o = (Operator) operators [i];
1292 if ((o.ModFlags & modflags) == 0)
1294 if ((o.ModFlags & static_mask) != static_flags)
1297 MethodBuilder ob = o.OperatorMethodBuilder;
1298 if (ob != null && filter (ob, criteria) == true) {
1299 if (members == null)
1300 members = new ArrayList ();
1307 if (properties != null) {
1308 int len = properties.Count;
1309 for (int i = 0; i < len; i++) {
1310 Property p = (Property) properties [i];
1312 if ((p.ModFlags & modflags) == 0)
1314 if ((p.ModFlags & static_mask) != static_flags)
1320 if (b != null && filter (b, criteria) == true) {
1321 if (members == null)
1322 members = new ArrayList ();
1328 if (b != null && filter (b, criteria) == true) {
1329 if (members == null)
1330 members = new ArrayList ();
1337 if (indexers != null) {
1338 int len = indexers.Count;
1339 for (int i = 0; i < len; i++) {
1340 Indexer ix = (Indexer) indexers [i];
1342 if ((ix.ModFlags & modflags) == 0)
1344 if ((ix.ModFlags & static_mask) != static_flags)
1350 if (b != null && filter (b, criteria) == true) {
1351 if (members == null)
1352 members = new ArrayList ();
1358 if (b != null && filter (b, criteria) == true) {
1359 if (members == null)
1360 members = new ArrayList ();
1368 if ((mt & MemberTypes.Event) != 0) {
1369 if (events != null) {
1370 int len = events.Count;
1371 for (int i = 0; i < len; i++) {
1372 Event e = (Event) events [i];
1374 if ((e.ModFlags & modflags) == 0)
1376 if ((e.ModFlags & static_mask) != static_flags)
1379 MemberInfo eb = e.EventBuilder;
1380 if (eb != null && filter (eb, criteria) == true) {
1381 if (members == null)
1382 members = new ArrayList ();
1384 members.Add (e.EventBuilder);
1390 if ((mt & MemberTypes.Property) != 0){
1391 if (properties != null) {
1392 int len = properties.Count;
1393 for (int i = 0; i < len; i++) {
1394 Property p = (Property) properties [i];
1396 if ((p.ModFlags & modflags) == 0)
1398 if ((p.ModFlags & static_mask) != static_flags)
1401 MemberInfo pb = p.PropertyBuilder;
1402 if (pb != null && filter (pb, criteria) == true) {
1403 if (members == null)
1404 members = new ArrayList ();
1406 members.Add (p.PropertyBuilder);
1411 if (indexers != null) {
1412 int len = indexers.Count;
1413 for (int i = 0; i < len; i++) {
1414 Indexer ix = (Indexer) indexers [i];
1416 if ((ix.ModFlags & modflags) == 0)
1418 if ((ix.ModFlags & static_mask) != static_flags)
1421 MemberInfo ib = ix.PropertyBuilder;
1422 if (ib != null && filter (ib, criteria) == true) {
1423 if (members == null)
1424 members = new ArrayList ();
1426 members.Add (ix.PropertyBuilder);
1432 if ((mt & MemberTypes.NestedType) != 0) {
1433 if (types != null) {
1434 int len = types.Count;
1435 for (int i = 0; i < len; i++) {
1436 TypeContainer t = (TypeContainer) types [i];
1438 if ((t.ModFlags & modflags) == 0)
1441 TypeBuilder tb = t.TypeBuilder;
1442 if (tb != null && (filter (tb, criteria) == true)) {
1443 if (members == null)
1444 members = new ArrayList ();
1451 if (enums != null) {
1452 int len = enums.Count;
1453 for (int i = 0; i < len; i++) {
1454 Enum en = (Enum) enums [i];
1456 if ((en.ModFlags & modflags) == 0)
1459 TypeBuilder tb = en.TypeBuilder;
1460 if (tb != null && (filter (tb, criteria) == true)) {
1461 if (members == null)
1462 members = new ArrayList ();
1469 if (delegates != null) {
1470 int len = delegates.Count;
1471 for (int i = 0; i < len; i++) {
1472 Delegate d = (Delegate) delegates [i];
1474 if ((d.ModFlags & modflags) == 0)
1477 TypeBuilder tb = d.TypeBuilder;
1478 if (tb != null && (filter (tb, criteria) == true)) {
1479 if (members == null)
1480 members = new ArrayList ();
1487 if (interfaces != null) {
1488 int len = interfaces.Count;
1489 for (int i = 0; i < len; i++) {
1490 Interface iface = (Interface) interfaces [i];
1492 if ((iface.ModFlags & modflags) == 0)
1495 TypeBuilder tb = iface.TypeBuilder;
1496 if (tb != null && (filter (tb, criteria) == true)) {
1497 if (members == null)
1498 members = new ArrayList ();
1506 if ((mt & MemberTypes.Constructor) != 0){
1507 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1508 int len = instance_constructors.Count;
1509 for (int i = 0; i < len; i++) {
1510 Constructor c = (Constructor) instance_constructors [i];
1512 ConstructorBuilder cb = c.ConstructorBuilder;
1513 if (cb != null && filter (cb, criteria) == true) {
1514 if (members == null)
1515 members = new ArrayList ();
1522 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1523 ConstructorBuilder cb =
1524 default_static_constructor.ConstructorBuilder;
1526 if (cb != null && filter (cb, criteria) == true) {
1527 if (members == null)
1528 members = new ArrayList ();
1536 // Lookup members in parent if requested.
1538 if (((bf & BindingFlags.DeclaredOnly) == 0) && (TypeBuilder.BaseType != null)) {
1539 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1540 if (list.Count > 0) {
1541 if (members == null)
1542 members = new ArrayList ();
1544 members.AddRange (list);
1548 Timer.StopTimer (TimerType.TcFindMembers);
1550 if (members == null)
1551 return MemberList.Empty;
1553 return new MemberList (members);
1556 public override MemberCache MemberCache {
1558 return member_cache;
1562 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1563 MemberFilter filter, object criteria)
1565 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1568 return ds.FindMembers (mt, bf, filter, criteria);
1570 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1575 // FindMethods will look for methods not only in the type `t', but in
1576 // any interfaces implemented by the type.
1578 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1579 MemberFilter filter, object criteria)
1585 /// Emits the values for the constants
1587 public void EmitConstants ()
1589 if (constants != null)
1590 foreach (Const con in constants)
1591 con.EmitConstant (this);
1596 /// Emits the code, this step is performed after all
1597 /// the types, enumerations, constructors
1601 if (instance_constructors != null)
1602 foreach (Constructor c in instance_constructors)
1605 if (default_static_constructor != null)
1606 default_static_constructor.Emit (this);
1608 if (methods != null)
1609 foreach (Method m in methods)
1612 if (operators != null)
1613 foreach (Operator o in operators)
1616 if (properties != null)
1617 foreach (Property p in properties)
1620 if (indexers != null){
1621 foreach (Indexer ix in indexers)
1624 CustomAttributeBuilder cb = Interface.EmitDefaultMemberAttr (
1625 this, IndexerName, ModFlags, Location);
1626 TypeBuilder.SetCustomAttribute (cb);
1630 foreach (Field f in fields)
1633 if (events != null){
1634 foreach (Event e in Events)
1638 if (Pending != null)
1639 if (Pending.VerifyPendingMethods ())
1642 Attribute.ApplyAttributes (ec, TypeBuilder, this, OptAttributes);
1645 // Check for internal or private fields that were never assigned
1647 if (RootContext.WarningLevel >= 3) {
1648 if (fields != null){
1649 foreach (Field f in fields) {
1650 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1653 if ((f.status & Field.Status.USED) == 0){
1655 169, f.Location, "Private field " +
1656 MakeName (f.Name) + " is never used");
1661 // Only report 649 on level 4
1663 if (RootContext.WarningLevel < 4)
1666 if ((f.status & Field.Status.ASSIGNED) != 0)
1671 "Field " + MakeName (f.Name) + " is never assigned " +
1672 " to and will always have its default value");
1676 if (events != null){
1677 foreach (Event e in events){
1679 Report.Warning (67, "The event " + MakeName (e.Name) + " is never used");
1684 // if (types != null)
1685 // foreach (TypeContainer tc in types)
1689 public override void CloseType ()
1696 TypeBuilder.CreateType ();
1697 } catch (TypeLoadException){
1699 // This is fine, the code still created the type
1701 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1702 // Console.WriteLine (e.Message);
1704 Console.WriteLine ("In type: " + Name);
1709 foreach (Enum en in Enums)
1712 if (interface_order != null){
1713 foreach (Interface iface in interface_order)
1718 foreach (TypeContainer tc in Types)
1722 foreach (TypeContainer tc in Types)
1723 if (!(tc is Struct))
1727 if (Delegates != null)
1728 foreach (Delegate d in Delegates)
1736 initialized_fields = null;
1737 initialized_static_fields = null;
1740 interface_order = null;
1746 default_constructor = null;
1747 default_static_constructor = null;
1749 OptAttributes = null;
1751 parent_container = null;
1752 member_cache = null;
1755 public string MakeName (string n)
1757 return "`" + Name + "." + n + "'";
1760 public void Warning_KeywordNewRequired (Location l, MemberInfo mi)
1763 108, l, "The keyword new is required on " +
1764 MakeName (mi.Name) + " because it hides `" +
1765 mi.ReflectedType.Name + "." + mi.Name + "'");
1768 public void Warning_KeywordNewNotRequired (Location l, MemberCore mc)
1771 109, l, "The member " + MakeName (mc.Name) + " does not hide an " +
1772 "inherited member, the keyword new is not required");
1775 public void Error_EventCanOnlyOverrideEvent (Location l, MemberInfo mi)
1778 72, l, MakeName (mi.Name) + " : cannot override; `" +
1779 mi.ReflectedType.Name + "." + mi.Name + "' is not an event");
1782 public static int CheckMember (string name, MemberInfo mi, int ModFlags)
1788 // Performs the validation on a Method's modifiers (properties have
1789 // the same properties).
1791 public bool MethodModifiersValid (int flags, string n, Location loc)
1793 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1794 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1795 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1799 // At most one of static, virtual or override
1801 if ((flags & Modifiers.STATIC) != 0){
1802 if ((flags & vao) != 0){
1804 112, loc, "static method " + MakeName (n) + "can not be marked " +
1805 "as virtual, abstract or override");
1810 if (this is Struct){
1811 if ((flags & va) != 0){
1812 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
1817 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1819 113, loc, MakeName (n) +
1820 " marked as override cannot be marked as new or virtual");
1825 // If the declaration includes the abstract modifier, then the
1826 // declaration does not include static, virtual or extern
1828 if ((flags & Modifiers.ABSTRACT) != 0){
1829 if ((flags & Modifiers.EXTERN) != 0){
1831 180, loc, MakeName (n) + " can not be both abstract and extern");
1835 if ((flags & Modifiers.VIRTUAL) != 0){
1837 503, loc, MakeName (n) + " can not be both abstract and virtual");
1841 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1843 513, loc, MakeName (n) +
1844 " is abstract but its container class is not");
1850 if ((flags & Modifiers.PRIVATE) != 0){
1851 if ((flags & vao) != 0){
1853 621, loc, MakeName (n) +
1854 " virtual or abstract members can not be private");
1859 if ((flags & Modifiers.SEALED) != 0){
1860 if ((flags & Modifiers.OVERRIDE) == 0){
1862 238, loc, MakeName (n) +
1863 " cannot be sealed because it is not an override");
1871 Hashtable builder_and_args;
1873 public bool RegisterMethod (MethodBuilder mb, InternalParameters ip, Type [] args)
1875 if (builder_and_args == null)
1876 builder_and_args = new Hashtable ();
1881 /// Performs checks for an explicit interface implementation. First it
1882 /// checks whether the `interface_type' is a base inteface implementation.
1883 /// Then it checks whether `name' exists in the interface type.
1885 public bool VerifyImplements (Type interface_type, string full, string name, Location loc)
1889 if (ifaces != null){
1890 foreach (TypeExpr t in ifaces){
1891 if (t.Type == interface_type){
1899 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
1910 string IMemberContainer.Name {
1916 Type IMemberContainer.Type {
1922 IMemberContainer IMemberContainer.Parent {
1924 return parent_container;
1928 MemberCache IMemberContainer.MemberCache {
1930 return member_cache;
1934 bool IMemberContainer.IsInterface {
1940 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
1942 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
1946 // Operator pair checking
1949 class OperatorEntry {
1951 public Type ret_type;
1952 public Type type1, type2;
1954 public Operator.OpType ot;
1956 public OperatorEntry (int f, Operator o)
1960 ret_type = o.OperatorMethod.GetReturnType ();
1961 Type [] pt = o.OperatorMethod.ParameterTypes;
1965 ot = o.OperatorType;
1968 public override int GetHashCode ()
1970 return ret_type.GetHashCode ();
1973 public override bool Equals (object o)
1975 OperatorEntry other = (OperatorEntry) o;
1977 if (other.ret_type != ret_type)
1979 if (other.type1 != type1)
1981 if (other.type2 != type2)
1988 // Checks that some operators come in pairs:
1994 // They are matched based on the return type and the argument types
1996 void CheckPairedOperators ()
1998 Hashtable pairs = new Hashtable (null, null);
1999 Operator true_op = null;
2000 Operator false_op = null;
2001 bool has_equality_or_inequality = false;
2003 // Register all the operators we care about.
2004 foreach (Operator op in operators){
2007 switch (op.OperatorType){
2008 case Operator.OpType.Equality:
2010 has_equality_or_inequality = true;
2012 case Operator.OpType.Inequality:
2014 has_equality_or_inequality = true;
2017 case Operator.OpType.True:
2020 case Operator.OpType.False:
2024 case Operator.OpType.GreaterThan:
2026 case Operator.OpType.LessThan:
2029 case Operator.OpType.GreaterThanOrEqual:
2031 case Operator.OpType.LessThanOrEqual:
2037 OperatorEntry oe = new OperatorEntry (reg, op);
2039 object o = pairs [oe];
2043 oe = (OperatorEntry) o;
2048 if (true_op != null){
2049 if (false_op == null)
2050 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
2051 } else if (false_op != null)
2052 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
2055 // Look for the mistakes.
2057 foreach (DictionaryEntry de in pairs){
2058 OperatorEntry oe = (OperatorEntry) de.Key;
2065 case Operator.OpType.Equality:
2068 case Operator.OpType.Inequality:
2071 case Operator.OpType.GreaterThan:
2074 case Operator.OpType.LessThan:
2077 case Operator.OpType.GreaterThanOrEqual:
2080 case Operator.OpType.LessThanOrEqual:
2084 Report.Error (216, oe.op.Location,
2085 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
2088 if ((has_equality_or_inequality) && (RootContext.WarningLevel >= 2)) {
2089 MethodSignature equals_ms = new MethodSignature (
2090 "Equals", TypeManager.bool_type, new Type [] { TypeManager.object_type });
2091 MethodSignature hash_ms = new MethodSignature (
2092 "GetHashCode", TypeManager.int32_type, new Type [0]);
2094 MemberList equals_ml = FindMembers (MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance |
2095 BindingFlags.DeclaredOnly, MethodSignature.method_signature_filter,
2097 MemberList hash_ml = FindMembers (MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance |
2098 BindingFlags.DeclaredOnly, MethodSignature.method_signature_filter,
2101 bool equals_ok = false;
2102 if ((equals_ml != null) && (equals_ml.Count == 1))
2103 equals_ok = equals_ml [0].DeclaringType == TypeBuilder;
2104 bool hash_ok = false;
2105 if ((hash_ml != null) && (hash_ml.Count == 1))
2106 hash_ok = hash_ml [0].DeclaringType == TypeBuilder;
2109 Report.Warning (660, Location, "`" + Name + "' defines operator == or operator != but does " +
2110 "not override Object.Equals (object o)");
2112 Report.Warning (661, Location, "`" + Name + "' defines operator == or operator != but does " +
2113 "not override Object.GetHashCode ()");
2120 public class Class : TypeContainer {
2122 // Modifiers allowed in a class declaration
2124 public const int AllowedModifiers =
2127 Modifiers.PROTECTED |
2128 Modifiers.INTERNAL |
2130 Modifiers.ABSTRACT |
2134 public Class (NamespaceEntry ns, TypeContainer parent, string name, int mod, Attributes attrs, Location l)
2135 : base (ns, parent, name, attrs, l)
2139 if (parent.Parent == null)
2140 accmods = Modifiers.INTERNAL;
2142 accmods = Modifiers.PRIVATE;
2144 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2148 // FIXME: How do we deal with the user specifying a different
2151 public override TypeAttributes TypeAttr {
2153 return base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2158 public class Struct : TypeContainer {
2160 // Modifiers allowed in a struct declaration
2162 public const int AllowedModifiers =
2165 Modifiers.PROTECTED |
2166 Modifiers.INTERNAL |
2170 public Struct (NamespaceEntry ns, TypeContainer parent, string name, int mod, Attributes attrs, Location l)
2171 : base (ns, parent, name, attrs, l)
2175 if (parent.Parent == null)
2176 accmods = Modifiers.INTERNAL;
2178 accmods = Modifiers.PRIVATE;
2180 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2182 this.ModFlags |= Modifiers.SEALED;
2186 // FIXME: Allow the user to specify a different set of attributes
2187 // in some cases (Sealed for example is mandatory for a class,
2188 // but what SequentialLayout can be changed
2190 public override TypeAttributes TypeAttr {
2192 return base.TypeAttr |
2193 TypeAttributes.SequentialLayout |
2194 TypeAttributes.Sealed |
2195 TypeAttributes.BeforeFieldInit;
2200 public abstract class MethodCore : MemberBase {
2201 public readonly Parameters Parameters;
2202 protected Block block;
2203 protected DeclSpace ds;
2206 // Parameters, cached for semantic analysis.
2208 protected InternalParameters parameter_info;
2209 protected Type [] parameter_types;
2212 // This is set from TypeContainer.DefineMembers if this method overrides something.
2214 public bool OverridesSomething;
2216 public MethodCore (DeclSpace ds, Expression type, int mod, int allowed_mod,
2217 string name, Attributes attrs, Parameters parameters, Location loc)
2218 : base (type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
2220 Parameters = parameters;
2225 // Returns the System.Type array for the parameters of this method
2227 public Type [] ParameterTypes {
2229 return parameter_types;
2233 public InternalParameters ParameterInfo
2236 return parameter_info;
2240 public Block Block {
2250 protected virtual bool DoDefineParameters ()
2252 // Check if arguments were correct
2253 parameter_types = Parameters.GetParameterInfo (ds);
2254 if ((parameter_types == null) || !CheckParameters (ds, parameter_types))
2257 parameter_info = new InternalParameters (ds, Parameters);
2259 Parameter array_param = Parameters.ArrayParameter;
2260 if ((array_param != null) &&
2261 (!array_param.ParameterType.IsArray ||
2262 (array_param.ParameterType.GetArrayRank () != 1))) {
2263 Report.Error (225, Location, "params parameter has to be a single dimensional array");
2270 public CallingConventions GetCallingConvention (bool is_class)
2272 CallingConventions cc = 0;
2274 cc = Parameters.GetCallingConvention ();
2277 if ((ModFlags & Modifiers.STATIC) == 0)
2278 cc |= CallingConventions.HasThis;
2280 // FIXME: How is `ExplicitThis' used in C#?
2286 // The method's attributes are passed in because we need to extract
2287 // the "return:" attribute from there to apply on the return type
2289 static public void LabelParameters (EmitContext ec,
2291 Parameters parameters,
2292 Attributes method_attrs,
2296 // Define each type attribute (in/out/ref) and
2297 // the argument names.
2299 Parameter [] p = parameters.FixedParameters;
2302 MethodBuilder mb = null;
2303 ConstructorBuilder cb = null;
2305 if (builder is MethodBuilder)
2306 mb = (MethodBuilder) builder;
2308 cb = (ConstructorBuilder) builder;
2311 for (i = 0; i < p.Length; i++) {
2312 ParameterBuilder pb;
2313 ParameterAttributes par_attr = p [i].Attributes;
2316 pb = cb.DefineParameter (
2317 i + 1, par_attr, p [i].Name);
2319 pb = mb.DefineParameter (
2320 i + 1, par_attr, p [i].Name);
2322 Attributes attr = p [i].OptAttributes;
2324 Attribute.ApplyAttributes (ec, pb, pb, attr);
2326 if (par_attr == ParameterAttributes.Out){
2327 if (attr.Contains (TypeManager.in_attribute_type))
2328 Report.Error (36, loc,
2329 "Can not use [In] attribute on out parameter");
2335 if (parameters.ArrayParameter != null){
2336 ParameterBuilder pb;
2337 Parameter array_param = parameters.ArrayParameter;
2340 pb = cb.DefineParameter (
2341 i + 1, array_param.Attributes,
2344 pb = mb.DefineParameter (
2345 i + 1, array_param.Attributes,
2348 CustomAttributeBuilder a = new CustomAttributeBuilder (
2349 TypeManager.cons_param_array_attribute, new object [0]);
2351 pb.SetCustomAttribute (a);
2355 // And now for the return type attribute decoration
2357 ParameterBuilder ret_pb;
2358 Attributes ret_attrs = null;
2360 if (mb == null || method_attrs == null)
2363 foreach (AttributeSection asec in method_attrs.AttributeSections) {
2365 if (asec.Target != "return")
2368 if (ret_attrs == null)
2369 ret_attrs = new Attributes (asec);
2371 ret_attrs.AddAttributeSection (asec);
2374 if (ret_attrs != null) {
2376 ret_pb = mb.DefineParameter (0, ParameterAttributes.None, "");
2377 Attribute.ApplyAttributes (ec, ret_pb, ret_pb, ret_attrs);
2379 } catch (ArgumentOutOfRangeException) {
2382 ".NET SDK 1.0 does not permit setting custom attributes" +
2383 " on the return type of a method");
2389 public class Method : MethodCore, IIteratorContainer {
2390 public MethodBuilder MethodBuilder;
2391 public MethodData MethodData;
2394 /// Modifiers allowed in a class declaration
2396 const int AllowedModifiers =
2399 Modifiers.PROTECTED |
2400 Modifiers.INTERNAL |
2405 Modifiers.OVERRIDE |
2406 Modifiers.ABSTRACT |
2411 // return_type can be "null" for VOID values.
2413 public Method (DeclSpace ds, Expression return_type, int mod, string name,
2414 Parameters parameters, Attributes attrs, Location l)
2415 : base (ds, return_type, mod, AllowedModifiers, name, attrs, parameters, l)
2419 // Returns the `System.Type' for the ReturnType of this
2420 // function. Provides a nice cache. (used between semantic analysis
2421 // and actual code generation
2423 public Type GetReturnType ()
2428 // Whether this is an operator method.
2429 public bool IsOperator;
2431 void DuplicateEntryPoint (MethodInfo b, Location location)
2435 "Program `" + CodeGen.FileName +
2436 "' has more than one entry point defined: `" +
2437 TypeManager.CSharpSignature(b) + "'");
2440 void Report28 (MethodInfo b)
2444 "`" + TypeManager.CSharpSignature(b) +
2445 "' has the wrong signature to be an entry point");
2448 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
2450 if (b.ReturnType != TypeManager.void_type &&
2451 b.ReturnType != TypeManager.int32_type)
2454 if (pinfo.Count == 0)
2457 if (pinfo.Count > 1)
2460 Type t = pinfo.ParameterType(0);
2462 (t.GetArrayRank() == 1) &&
2463 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
2464 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
2471 // Checks our base implementation if any
2473 protected override bool CheckBase (TypeContainer container)
2475 base.CheckBase (container);
2477 // Check whether arguments were correct.
2478 if (!DoDefineParameters ())
2481 MethodSignature ms = new MethodSignature (Name, null, ParameterTypes);
2483 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2487 mi_this = TypeContainer.FindMembers (
2488 container.TypeBuilder, MemberTypes.Method,
2489 BindingFlags.NonPublic | BindingFlags.Public |
2490 BindingFlags.Static | BindingFlags.Instance |
2491 BindingFlags.DeclaredOnly,
2492 MethodSignature.method_signature_filter, ms);
2494 if (mi_this.Count > 0) {
2495 Report.Error (111, Location, "Class `" + container.Name + "' " +
2496 "already defines a member called `" + Name + "' " +
2497 "with the same parameter types");
2503 // Verify if the parent has a type with the same name, and then
2504 // check whether we have to create a new slot for it or not.
2506 Type ptype = container.TypeBuilder.BaseType;
2508 // ptype is only null for System.Object while compiling corlib.
2510 MemberList mi, mi_static, mi_instance;
2512 mi_instance = TypeContainer.FindMembers (
2513 ptype, MemberTypes.Method,
2514 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
2515 MethodSignature.inheritable_method_signature_filter,
2518 if (mi_instance.Count > 0){
2521 mi_static = TypeContainer.FindMembers (
2522 ptype, MemberTypes.Method,
2523 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static,
2524 MethodSignature.inheritable_method_signature_filter, ms);
2526 if (mi_static.Count > 0)
2532 if (mi != null && mi.Count > 0){
2533 parent_method = (MethodInfo) mi [0];
2534 string name = parent_method.DeclaringType.Name + "." +
2537 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
2540 if ((ModFlags & Modifiers.NEW) == 0) {
2541 Type parent_ret = TypeManager.TypeToCoreType (
2542 parent_method.ReturnType);
2544 if (parent_ret != MemberType) {
2546 508, Location, container.MakeName (Name) + ": cannot " +
2547 "change return type when overriding " +
2548 "inherited member " + name);
2553 if (!OverridesSomething && ((ModFlags & Modifiers.NEW) != 0))
2554 WarningNotHiding (container);
2556 if ((ModFlags & Modifiers.OVERRIDE) != 0){
2557 Report.Error (115, Location,
2558 container.MakeName (Name) +
2559 " no suitable methods found to override");
2562 } else if ((ModFlags & Modifiers.NEW) != 0)
2563 WarningNotHiding (container);
2571 public override bool Define (TypeContainer container)
2573 if (!DoDefine (container))
2576 if (!CheckBase (container))
2579 CallingConventions cc = GetCallingConvention (container is Class);
2581 MethodData = new MethodData (container, this, null, MemberType,
2582 ParameterTypes, ParameterInfo, cc,
2583 OptAttributes, ModFlags, flags, true);
2585 if (!MethodData.Define (container))
2589 // Setup iterator if we are one
2591 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
2592 IteratorHandler ih = new IteratorHandler (
2593 Name, container, MemberType,
2594 ParameterTypes, ParameterInfo,
2595 ModFlags, Location);
2597 Block new_block = ih.Setup (block);
2598 if (new_block == null)
2603 MethodBuilder = MethodData.MethodBuilder;
2606 // This is used to track the Entry Point,
2608 if (Name == "Main" &&
2609 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
2610 (RootContext.MainClass == null ||
2611 RootContext.MainClass == container.TypeBuilder.FullName)){
2612 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
2613 if (RootContext.EntryPoint == null) {
2614 RootContext.EntryPoint = MethodBuilder;
2615 RootContext.EntryPointLocation = Location;
2617 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
2618 DuplicateEntryPoint (MethodBuilder, Location);
2621 Report28(MethodBuilder);
2630 public void Emit (TypeContainer container)
2632 MethodData.Emit (container, Block, this);
2637 void IIteratorContainer.SetYields ()
2639 ModFlags |= Modifiers.METHOD_YIELDS;
2643 public abstract class ConstructorInitializer {
2644 ArrayList argument_list;
2645 ConstructorInfo parent_constructor;
2646 Parameters parameters;
2649 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
2652 this.argument_list = argument_list;
2653 this.parameters = parameters;
2657 public ArrayList Arguments {
2659 return argument_list;
2663 public bool Resolve (EmitContext ec)
2665 Expression parent_constructor_group;
2668 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
2670 if (argument_list != null){
2671 foreach (Argument a in argument_list){
2672 if (!a.Resolve (ec, loc))
2676 ec.CurrentBlock = null;
2678 if (this is ConstructorBaseInitializer) {
2679 if (ec.ContainerType.BaseType == null)
2682 t = ec.ContainerType.BaseType;
2683 if (ec.ContainerType.IsValueType) {
2684 Report.Error (522, loc,
2685 "structs cannot call base class constructors");
2689 t = ec.ContainerType;
2691 parent_constructor_group = Expression.MemberLookup (
2692 ec, t, null, t, ".ctor",
2693 MemberTypes.Constructor,
2694 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
2697 if (parent_constructor_group == null){
2698 Report.Error (1501, loc,
2699 "Can not find a constructor for this argument list");
2703 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (ec,
2704 (MethodGroupExpr) parent_constructor_group, argument_list, loc);
2706 if (parent_constructor == null){
2707 Report.Error (1501, loc,
2708 "Can not find a constructor for this argument list");
2715 public void Emit (EmitContext ec)
2717 if (parent_constructor != null){
2718 ec.Mark (loc, false);
2720 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
2722 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
2727 public class ConstructorBaseInitializer : ConstructorInitializer {
2728 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
2729 base (argument_list, pars, l)
2734 public class ConstructorThisInitializer : ConstructorInitializer {
2735 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
2736 base (argument_list, pars, l)
2741 public class Constructor : MethodCore {
2742 public ConstructorBuilder ConstructorBuilder;
2743 public ConstructorInitializer Initializer;
2746 // Modifiers allowed for a constructor.
2748 public const int AllowedModifiers =
2750 Modifiers.PROTECTED |
2751 Modifiers.INTERNAL |
2758 // The spec claims that static is not permitted, but
2759 // my very own code has static constructors.
2761 public Constructor (DeclSpace ds, string name, int mod, Parameters args,
2762 ConstructorInitializer init, Location l)
2763 : base (ds, null, mod, AllowedModifiers, name, null, args, l)
2769 // Returns true if this is a default constructor
2771 public bool IsDefault ()
2773 if ((ModFlags & Modifiers.STATIC) != 0)
2774 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
2775 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
2778 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
2779 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
2780 (Initializer is ConstructorBaseInitializer) &&
2781 (Initializer.Arguments == null);
2785 // Creates the ConstructorBuilder
2787 public override bool Define (TypeContainer container)
2789 MethodAttributes ca = (MethodAttributes.RTSpecialName |
2790 MethodAttributes.SpecialName);
2792 // Check if arguments were correct.
2793 if (!DoDefineParameters ())
2796 if ((ModFlags & Modifiers.STATIC) != 0){
2797 ca |= MethodAttributes.Static | MethodAttributes.Private;
2799 if (container is Struct && ParameterTypes.Length == 0){
2802 "Structs can not contain explicit parameterless " +
2806 ca |= MethodAttributes.HideBySig;
2808 if ((ModFlags & Modifiers.PUBLIC) != 0)
2809 ca |= MethodAttributes.Public;
2810 else if ((ModFlags & Modifiers.PROTECTED) != 0){
2811 if ((ModFlags & Modifiers.INTERNAL) != 0)
2812 ca |= MethodAttributes.FamORAssem;
2814 ca |= MethodAttributes.Family;
2815 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
2816 ca |= MethodAttributes.Assembly;
2817 else if (IsDefault ())
2818 ca |= MethodAttributes.Public;
2820 ca |= MethodAttributes.Private;
2823 ConstructorBuilder = container.TypeBuilder.DefineConstructor (
2824 ca, GetCallingConvention (container is Class), ParameterTypes);
2826 if ((ModFlags & Modifiers.UNSAFE) != 0)
2827 ConstructorBuilder.InitLocals = false;
2830 // HACK because System.Reflection.Emit is lame
2832 if (!TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes)) {
2835 "Class `" +container.Name+ "' already contains a definition with the " +
2836 "same return value and parameter types for constructor `" + Name
2847 public void Emit (TypeContainer container)
2849 ILGenerator ig = ConstructorBuilder.GetILGenerator ();
2850 EmitContext ec = new EmitContext (container, Location, ig, null, ModFlags, true);
2853 // extern methods have no bodies
2855 if ((ModFlags & Modifiers.EXTERN) != 0) {
2856 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
2858 179, Location, "External constructor `" +
2859 TypeManager.CSharpSignature (ConstructorBuilder) +
2860 "' can not have a body");
2863 } else if (block == null) {
2865 501, Location, "Constructor `" +
2866 TypeManager.CSharpSignature (ConstructorBuilder) +
2867 "' must declare a body since it is not marked extern");
2871 if ((ModFlags & Modifiers.STATIC) == 0){
2872 if (container is Class && Initializer == null)
2873 Initializer = new ConstructorBaseInitializer (
2874 null, Parameters.EmptyReadOnlyParameters, Location);
2878 // Spec mandates that Initializers will not have
2882 if (Initializer != null && !Initializer.Resolve (ec))
2884 ec.IsStatic = false;
2887 MethodCore.LabelParameters (ec, ConstructorBuilder,
2888 Parameters, OptAttributes, Location);
2890 SymbolWriter sw = CodeGen.SymbolWriter;
2891 bool generate_debugging = false;
2893 if ((sw != null) && (block != null) &&
2894 !Location.IsNull (Location) &&
2895 !Location.IsNull (block.EndLocation)) {
2897 sw.OpenMethod (container, ConstructorBuilder, Location, block.EndLocation);
2899 generate_debugging = true;
2903 // Classes can have base initializers and instance field initializers.
2905 if (container is Class){
2906 if ((ModFlags & Modifiers.STATIC) == 0){
2909 // If we use a "this (...)" constructor initializer, then
2910 // do not emit field initializers, they are initialized in the other constructor
2912 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
2913 container.EmitFieldInitializers (ec);
2916 if (Initializer != null)
2917 Initializer.Emit (ec);
2919 if ((ModFlags & Modifiers.STATIC) != 0)
2920 container.EmitFieldInitializers (ec);
2922 Attribute.ApplyAttributes (ec, ConstructorBuilder, this, OptAttributes);
2924 // If this is a non-static `struct' constructor and doesn't have any
2925 // initializer, it must initialize all of the struct's fields.
2926 if ((container is Struct) && ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
2927 Block.AddThisVariable (container, Location);
2929 ec.EmitTopBlock (block, ParameterInfo, Location);
2931 if (generate_debugging)
2939 // Encapsulates most of the Method's state
2941 public class MethodData {
2943 // The return type of this method
2945 public readonly Type ReturnType;
2946 public readonly Type[] ParameterTypes;
2947 public readonly InternalParameters ParameterInfo;
2948 public readonly CallingConventions CallingConventions;
2949 public readonly Attributes OptAttributes;
2950 public readonly Location Location;
2953 // Are we implementing an interface ?
2955 public bool IsImplementing = false;
2960 protected DeclSpace ds;
2961 protected MemberBase member;
2962 protected int modifiers;
2963 protected MethodAttributes flags;
2964 protected bool is_method;
2965 protected string accessor_name;
2968 // It can either hold a string with the condition, or an arraylist of conditions.
2969 object conditionals;
2971 MethodBuilder builder = null;
2972 public MethodBuilder MethodBuilder {
2978 public MethodData (DeclSpace ds, MemberBase member, string name, Type return_type,
2979 Type [] parameter_types, InternalParameters parameters,
2980 CallingConventions cc, Attributes opt_attrs,
2981 int modifiers, MethodAttributes flags, bool is_method)
2984 this.member = member;
2985 this.accessor_name = name;
2986 this.ReturnType = return_type;
2987 this.ParameterTypes = parameter_types;
2988 this.ParameterInfo = parameters;
2989 this.CallingConventions = cc;
2990 this.OptAttributes = opt_attrs;
2991 this.modifiers = modifiers;
2993 this.is_method = is_method;
2994 this.Location = member.Location;
2995 this.conditionals = null;
3001 Attribute dllimport_attribute = null;
3002 string obsolete = null;
3003 bool obsolete_error = false;
3005 public virtual bool ApplyAttributes (Attributes opt_attrs, bool is_method)
3007 if ((opt_attrs == null) || (opt_attrs.AttributeSections == null))
3010 foreach (AttributeSection asec in opt_attrs.AttributeSections) {
3011 if (asec.Attributes == null)
3014 foreach (Attribute a in asec.Attributes) {
3015 if (a.Name == "Conditional") {
3016 if (!ApplyConditionalAttribute (a))
3018 } else if (a.Name == "Obsolete") {
3019 if (!ApplyObsoleteAttribute (a))
3021 } else if (a.Name.IndexOf ("DllImport") != -1) {
3023 a.Type = TypeManager.dllimport_type;
3024 Attribute.Error_AttributeNotValidForElement (a, Location);
3027 if (!ApplyDllImportAttribute (a))
3037 // Applies the `DllImport' attribute to the method.
3039 protected virtual bool ApplyDllImportAttribute (Attribute a)
3041 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3042 if ((modifiers & extern_static) != extern_static) {
3043 Report.Error (601, Location,
3044 "The DllImport attribute must be specified on a method " +
3045 "marked `static' and `extern'.");
3049 flags |= MethodAttributes.PinvokeImpl;
3050 dllimport_attribute = a;
3055 // Applies the `Obsolete' attribute to the method.
3057 protected virtual bool ApplyObsoleteAttribute (Attribute a)
3059 if (obsolete != null) {
3060 Report.Error (579, Location, "Duplicate `Obsolete' attribute");
3064 obsolete = a.Obsolete_GetObsoleteMessage (out obsolete_error);
3065 return obsolete != null;
3069 // Applies the `Conditional' attribute to the method.
3071 protected virtual bool ApplyConditionalAttribute (Attribute a)
3073 // The Conditional attribute is only valid on methods.
3075 Attribute.Error_AttributeNotValidForElement (a, Location);
3079 string condition = a.Conditional_GetConditionName ();
3081 if (condition == null)
3084 if (ReturnType != TypeManager.void_type) {
3085 Report.Error (578, Location,
3086 "Conditional not valid on `" + member.Name + "' " +
3087 "because its return type is not void");
3091 if ((modifiers & Modifiers.OVERRIDE) != 0) {
3092 Report.Error (243, Location,
3093 "Conditional not valid on `" + member.Name + "' " +
3094 "because it is an override method");
3098 if (member.IsExplicitImpl) {
3099 Report.Error (577, Location,
3100 "Conditional not valid on `" + member.Name + "' " +
3101 "because it is an explicit interface implementation");
3105 if (IsImplementing) {
3106 Report.Error (623, Location,
3107 "Conditional not valid on `" + member.Name + "' " +
3108 "because it is an interface method");
3113 // The likelyhood that the conditional will be more than 1 is very slim
3115 if (conditionals == null)
3116 conditionals = condition;
3117 else if (conditionals is string){
3118 string s = (string) conditionals;
3119 conditionals = new ArrayList ();
3120 ((ArrayList)conditionals).Add (s);
3122 ((ArrayList)conditionals).Add (condition);
3128 // Checks whether this method should be ignored due to its Conditional attributes.
3130 bool ShouldIgnore (Location loc)
3132 // When we're overriding a virtual method, we implicitly inherit the
3133 // Conditional attributes from our parent.
3134 if (member.ParentMethod != null) {
3135 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (
3136 member.ParentMethod, loc);
3138 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
3142 if (conditionals != null){
3143 if (conditionals is string){
3144 if (RootContext.AllDefines [conditionals] == null)
3147 foreach (string condition in (ArrayList) conditionals)
3148 if (RootContext.AllDefines [condition] == null)
3156 // Returns the TypeManager.MethodFlags for this method.
3157 // This emits an error 619 / warning 618 if the method is obsolete.
3158 // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
3160 public virtual TypeManager.MethodFlags GetMethodFlags (Location loc)
3162 TypeManager.MethodFlags flags = 0;
3164 if (obsolete != null) {
3165 if (obsolete_error) {
3166 Report.Error (619, loc, "Method `" + member.Name +
3167 "' is obsolete: `" + obsolete + "'");
3168 return TypeManager.MethodFlags.IsObsoleteError;
3170 Report.Warning (618, loc, "Method `" + member.Name +
3171 "' is obsolete: `" + obsolete + "'");
3173 flags |= TypeManager.MethodFlags.IsObsolete;
3176 if (ShouldIgnore (loc))
3177 flags |= TypeManager.MethodFlags.ShouldIgnore;
3182 public virtual bool Define (TypeContainer container)
3184 MethodInfo implementing = null;
3185 string method_name, name, prefix;
3187 if (OptAttributes != null)
3188 if (!ApplyAttributes (OptAttributes, is_method))
3191 if (member.IsExplicitImpl)
3192 prefix = member.InterfaceType.FullName + ".";
3196 if (accessor_name != null)
3197 name = accessor_name + "_" + member.ShortName;
3199 name = member.ShortName;
3200 method_name = prefix + name;
3202 if (container.Pending != null){
3203 if (member is Indexer)
3204 implementing = container.Pending.IsInterfaceIndexer (
3205 member.InterfaceType, ReturnType, ParameterTypes);
3207 implementing = container.Pending.IsInterfaceMethod (
3208 member.InterfaceType, name, ReturnType, ParameterTypes);
3210 if (member.InterfaceType != null && implementing == null){
3211 Report.Error (539, Location, "'{0}' in explicit interface declaration is not an interface", method_name);
3217 // For implicit implementations, make sure we are public, for
3218 // explicit implementations, make sure we are private.
3220 if (implementing != null){
3222 // Setting null inside this block will trigger a more
3223 // verbose error reporting for missing interface implementations
3225 // The "candidate" function has been flagged already
3226 // but it wont get cleared
3228 if (member.IsExplicitImpl){
3229 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
3230 Modifiers.Error_InvalidModifier (Location, "public, virtual or abstract");
3231 implementing = null;
3233 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
3234 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
3236 // If this is an interface method implementation,
3237 // check for public accessibility
3239 implementing = null;
3240 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
3241 // We may never be private.
3242 implementing = null;
3243 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
3245 // We may be protected if we're overriding something.
3247 implementing = null;
3252 // Static is not allowed
3254 if ((modifiers & Modifiers.STATIC) != 0){
3255 implementing = null;
3256 Modifiers.Error_InvalidModifier (Location, "static");
3261 // If implementing is still valid, set flags
3263 if (implementing != null){
3265 // When implementing interface methods, set NewSlot
3266 // unless, we are overwriting a method.
3268 if (implementing.DeclaringType.IsInterface){
3269 if ((modifiers & Modifiers.OVERRIDE) == 0)
3270 flags |= MethodAttributes.NewSlot;
3273 MethodAttributes.Virtual |
3274 MethodAttributes.HideBySig;
3276 // Set Final unless we're virtual, abstract or already overriding a method.
3277 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
3278 flags |= MethodAttributes.Final;
3280 // Get the method name from the explicit interface.
3281 if (member.InterfaceType != null) {
3282 name = implementing.Name;
3283 method_name = prefix + name;
3286 IsImplementing = true;
3290 // Create the MethodBuilder for the method
3292 if ((flags & MethodAttributes.PinvokeImpl) != 0) {
3293 if ((modifiers & Modifiers.STATIC) == 0) {
3294 Report.Error (601, Location,
3295 "The DllImport attribute must be specified on " +
3296 "a method marked 'static' and 'extern'.");
3300 EmitContext ec = new EmitContext (
3301 container, ds, Location, null, ReturnType, modifiers, false);
3303 builder = dllimport_attribute.DefinePInvokeMethod (
3304 ec, container.TypeBuilder, method_name, flags,
3305 ReturnType, ParameterTypes);
3307 builder = container.TypeBuilder.DefineMethod (
3308 method_name, flags, CallingConventions,
3309 ReturnType, ParameterTypes);
3311 if (builder == null)
3314 if ((modifiers & Modifiers.UNSAFE) != 0)
3315 builder.InitLocals = false;
3317 if (IsImplementing){
3319 // clear the pending implemntation flag
3321 if (member is Indexer) {
3322 container.Pending.ImplementIndexer (
3323 member.InterfaceType, builder, ReturnType,
3324 ParameterTypes, true);
3326 container.Pending.ImplementMethod (
3327 member.InterfaceType, name, ReturnType,
3328 ParameterTypes, member.IsExplicitImpl);
3330 if (member.IsExplicitImpl)
3331 container.TypeBuilder.DefineMethodOverride (
3332 builder, implementing);
3336 if (!TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes)) {
3337 Report.Error (111, Location,
3338 "Class `" + container.Name +
3339 "' already contains a definition with the " +
3340 "same return value and parameter types as the " +
3341 "'get' method of property `" + member.Name + "'");
3345 TypeManager.AddMethod (builder, this);
3353 public virtual void Emit (TypeContainer container, Block block, object kind)
3358 if ((flags & MethodAttributes.PinvokeImpl) == 0)
3359 ig = builder.GetILGenerator ();
3363 ec = new EmitContext (container, ds, Location, ig, ReturnType, modifiers, false);
3365 if (OptAttributes != null)
3366 Attribute.ApplyAttributes (ec, builder, kind, OptAttributes);
3368 if (member is MethodCore)
3369 MethodCore.LabelParameters (ec, MethodBuilder,
3370 ((MethodCore) member).Parameters,
3375 // abstract or extern methods have no bodies
3377 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
3378 if (block == null) {
3379 SymbolWriter sw = CodeGen.SymbolWriter;
3381 if ((sw != null) && ((modifiers & Modifiers.EXTERN) != 0)) {
3382 sw.OpenMethod (container, MethodBuilder, Location, Location);
3390 // abstract or extern methods have no bodies.
3392 if ((modifiers & Modifiers.ABSTRACT) != 0)
3394 500, Location, "Abstract method `" +
3395 TypeManager.CSharpSignature (builder) +
3396 "' can not have a body");
3398 if ((modifiers & Modifiers.EXTERN) != 0)
3400 179, Location, "External method `" +
3401 TypeManager.CSharpSignature (builder) +
3402 "' can not have a body");
3408 // Methods must have a body unless they're extern or abstract
3410 if (block == null) {
3412 501, Location, "Method `" +
3413 TypeManager.CSharpSignature (builder) +
3414 "' must declare a body since it is not marked " +
3415 "abstract or extern");
3420 // Handle destructors specially
3422 // FIXME: This code generates buggy code
3424 if (member is Destructor)
3425 EmitDestructor (ec, block);
3427 SymbolWriter sw = CodeGen.SymbolWriter;
3429 if ((sw != null) && !Location.IsNull (Location) &&
3430 !Location.IsNull (block.EndLocation)) {
3431 sw.OpenMethod (container, MethodBuilder, Location, block.EndLocation);
3433 ec.EmitTopBlock (block, ParameterInfo, Location);
3437 ec.EmitTopBlock (block, ParameterInfo, Location);
3441 void EmitDestructor (EmitContext ec, Block block)
3443 ILGenerator ig = ec.ig;
3445 Label finish = ig.DefineLabel ();
3447 block.SetDestructor ();
3449 ig.BeginExceptionBlock ();
3450 ec.ReturnLabel = finish;
3451 ec.HasReturnLabel = true;
3452 ec.EmitTopBlock (block, null, Location);
3454 // ig.MarkLabel (finish);
3455 ig.BeginFinallyBlock ();
3457 if (ec.ContainerType.BaseType != null) {
3458 Expression member_lookup = Expression.MemberLookup (
3459 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
3460 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, Location);
3462 if (member_lookup != null){
3463 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
3465 ig.Emit (OpCodes.Ldarg_0);
3466 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
3470 ig.EndExceptionBlock ();
3471 //ig.MarkLabel (ec.ReturnLabel);
3472 ig.Emit (OpCodes.Ret);
3476 public class Destructor : Method {
3478 public Destructor (DeclSpace ds, Expression return_type, int mod, string name,
3479 Parameters parameters, Attributes attrs, Location l)
3480 : base (ds, return_type, mod, name, parameters, attrs, l)
3485 abstract public class MemberBase : MemberCore {
3486 public Expression Type;
3488 protected MethodAttributes flags;
3490 protected readonly int explicit_mod_flags;
3493 // The "short" name of this property / indexer / event. This is the
3494 // name without the explicit interface.
3496 public string ShortName;
3499 // The type of this property / indexer / event
3501 public Type MemberType;
3504 // If true, this is an explicit interface implementation
3506 public bool IsExplicitImpl = false;
3509 // The name of the interface we are explicitly implementing
3511 public string ExplicitInterfaceName = null;
3514 // If true, the interface type we are explicitly implementing
3516 public Type InterfaceType = null;
3519 // The method we're overriding if this is an override method.
3521 protected MethodInfo parent_method = null;
3522 public MethodInfo ParentMethod {
3524 return parent_method;
3529 // The constructor is only exposed to our children
3531 protected MemberBase (Expression type, int mod, int allowed_mod, int def_mod, string name,
3532 Attributes attrs, Location loc)
3533 : base (name, attrs, loc)
3535 explicit_mod_flags = mod;
3537 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
3540 protected virtual bool CheckBase (TypeContainer container)
3542 if ((container is Struct) || (RootContext.WarningLevel > 3)){
3543 if ((ModFlags & Modifiers.PROTECTED) != 0 && (container.ModFlags & Modifiers.SEALED) != 0){
3544 if (container is Struct){
3545 Report.Error (666, Location, "Protected member in struct declaration");
3548 Report.Warning (628, Location, "Member " + container.MakeName (Name) + " protected in sealed class");
3554 protected void WarningNotHiding (TypeContainer parent)
3558 "The member " + parent.MakeName (Name) + " does not hide an " +
3559 "inherited member. The keyword new is not required");
3563 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method,
3567 // FIXME: report the old/new permissions?
3570 507, Location, parent.MakeName (Name) +
3571 ": can't change the access modifiers when overriding inherited " +
3572 "member `" + name + "'");
3576 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3577 // that have been defined.
3579 // `name' is the user visible name for reporting errors (this is used to
3580 // provide the right name regarding method names and properties)
3582 protected bool CheckMethodAgainstBase (TypeContainer parent, MethodAttributes my_attrs,
3583 MethodInfo mb, string name)
3587 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3588 if (!(mb.IsAbstract || mb.IsVirtual)){
3590 506, Location, parent.MakeName (Name) +
3591 ": cannot override inherited member `" +
3592 name + "' because it is not " +
3593 "virtual, abstract or override");
3597 // Now we check that the overriden method is not final
3600 // This happens when implementing interface methods.
3601 if (mb.IsHideBySig && mb.IsVirtual) {
3603 506, Location, parent.MakeName (Name) +
3604 ": cannot override inherited member `" +
3605 name + "' because it is not " +
3606 "virtual, abstract or override");
3608 Report.Error (239, Location, parent.MakeName (Name) + " : cannot " +
3609 "override inherited member `" + name +
3610 "' because it is sealed.");
3614 // Check that the permissions are not being changed
3616 MethodAttributes thisp = my_attrs & MethodAttributes.MemberAccessMask;
3617 MethodAttributes parentp = mb.Attributes & MethodAttributes.MemberAccessMask;
3620 // special case for "protected internal"
3623 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3625 // when overriding protected internal, the method can be declared
3626 // protected internal only within the same assembly
3629 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3630 if (parent.TypeBuilder.Assembly != mb.DeclaringType.Assembly){
3632 // assemblies differ - report an error
3635 Error_CannotChangeAccessModifiers (parent, mb, name);
3637 } else if (thisp != parentp) {
3639 // same assembly, but other attributes differ - report an error
3642 Error_CannotChangeAccessModifiers (parent, mb, name);
3645 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3647 // if it's not "protected internal", it must be "protected"
3650 Error_CannotChangeAccessModifiers (parent, mb, name);
3652 } else if (parent.TypeBuilder.Assembly == mb.DeclaringType.Assembly) {
3654 // protected within the same assembly - an error
3656 Error_CannotChangeAccessModifiers (parent, mb, name);
3658 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3659 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3661 // protected ok, but other attributes differ - report an error
3663 Error_CannotChangeAccessModifiers (parent, mb, name);
3667 if (thisp != parentp){
3668 Error_CannotChangeAccessModifiers (parent, mb, name);
3674 if (mb.IsVirtual || mb.IsAbstract){
3675 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
3676 if (Name != "Finalize"){
3678 114, 2, Location, parent.MakeName (Name) +
3679 " hides inherited member `" + name +
3680 "'. To make the current member override that " +
3681 "implementation, add the override keyword, " +
3682 "otherwise use the new keyword");
3683 ModFlags |= Modifiers.NEW;
3687 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
3688 if (Name != "Finalize"){
3690 108, 1, Location, "The keyword new is required on " +
3691 parent.MakeName (Name) + " because it hides " +
3692 "inherited member `" + name + "'");
3693 ModFlags |= Modifiers.NEW;
3701 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
3705 foreach (Type partype in parameters){
3706 if (partype.IsPointer){
3709 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3713 if (ds.AsAccessible (partype, ModFlags))
3716 if (this is Indexer)
3717 Report.Error (55, Location,
3718 "Inconsistent accessibility: parameter type `" +
3719 TypeManager.CSharpName (partype) + "' is less " +
3720 "accessible than indexer `" + Name + "'");
3721 else if ((this is Method) && ((Method) this).IsOperator)
3722 Report.Error (57, Location,
3723 "Inconsistent accessibility: parameter type `" +
3724 TypeManager.CSharpName (partype) + "' is less " +
3725 "accessible than operator `" + Name + "'");
3727 Report.Error (51, Location,
3728 "Inconsistent accessibility: parameter type `" +
3729 TypeManager.CSharpName (partype) + "' is less " +
3730 "accessible than method `" + Name + "'");
3737 protected virtual bool DoDefine (TypeContainer container)
3742 if (!container.MethodModifiersValid (ModFlags, Name, Location))
3745 flags = Modifiers.MethodAttr (ModFlags);
3747 // Lookup Type, verify validity
3748 MemberType = container.ResolveType (Type, false, Location);
3749 if (MemberType == null)
3752 if ((container.ModFlags & Modifiers.SEALED) != 0){
3753 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
3754 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
3759 // verify accessibility
3760 if (!container.AsAccessible (MemberType, ModFlags)) {
3761 if (this is Property)
3762 Report.Error (53, Location,
3763 "Inconsistent accessibility: property type `" +
3764 TypeManager.CSharpName (MemberType) + "' is less " +
3765 "accessible than property `" + Name + "'");
3766 else if (this is Indexer)
3767 Report.Error (54, Location,
3768 "Inconsistent accessibility: indexer return type `" +
3769 TypeManager.CSharpName (MemberType) + "' is less " +
3770 "accessible than indexer `" + Name + "'");
3771 else if (this is Method) {
3772 if (((Method) this).IsOperator)
3773 Report.Error (56, Location,
3774 "Inconsistent accessibility: return type `" +
3775 TypeManager.CSharpName (MemberType) + "' is less " +
3776 "accessible than operator `" + Name + "'");
3778 Report.Error (50, Location,
3779 "Inconsistent accessibility: return type `" +
3780 TypeManager.CSharpName (MemberType) + "' is less " +
3781 "accessible than method `" + Name + "'");
3783 Report.Error (52, Location,
3784 "Inconsistent accessibility: field type `" +
3785 TypeManager.CSharpName (MemberType) + "' is less " +
3786 "accessible than field `" + Name + "'");
3790 if (MemberType.IsPointer && !UnsafeOK (container))
3794 // Check for explicit interface implementation
3796 if ((ExplicitInterfaceName == null) && (Name.IndexOf ('.') != -1)){
3797 int pos = Name.LastIndexOf ('.');
3799 ExplicitInterfaceName = Name.Substring (0, pos);
3800 ShortName = Name.Substring (pos + 1);
3804 if (ExplicitInterfaceName != null) {
3805 InterfaceType = RootContext.LookupType (
3806 container, ExplicitInterfaceName, false, Location);
3807 if (InterfaceType == null)
3810 if (InterfaceType.IsClass) {
3811 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", ExplicitInterfaceName);
3815 // Compute the full name that we need to export.
3816 Name = InterfaceType.FullName + "." + ShortName;
3818 if (!container.VerifyImplements (InterfaceType, ShortName, Name, Location))
3821 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3823 IsExplicitImpl = true;
3825 IsExplicitImpl = false;
3832 // Fields and Events both generate FieldBuilders, we use this to share
3833 // their common bits. This is also used to flag usage of the field
3835 abstract public class FieldBase : MemberBase {
3836 public FieldBuilder FieldBuilder;
3837 public Status status;
3840 public enum Status : byte { ASSIGNED = 1, USED = 2 }
3843 // The constructor is only exposed to our children
3845 protected FieldBase (Expression type, int mod, int allowed_mod, string name,
3846 object init, Attributes attrs, Location loc)
3847 : base (type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
3853 // Whether this field has an initializer.
3855 public bool HasInitializer {
3857 return init != null;
3861 protected readonly Object init;
3863 Expression init_expr;
3864 bool init_expr_initialized = false;
3867 // Resolves and returns the field initializer.
3869 public Expression GetInitializerExpression (EmitContext ec)
3871 if (init_expr_initialized)
3875 if (init is Expression)
3876 e = (Expression) init;
3878 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
3880 ec.IsFieldInitializer = true;
3881 e = e.DoResolve (ec);
3882 ec.IsFieldInitializer = false;
3885 init_expr_initialized = true;
3890 public void SetAssigned ()
3892 status |= Status.ASSIGNED;
3897 // The Field class is used to represents class/struct fields during parsing.
3899 public class Field : FieldBase {
3901 // Modifiers allowed in a class declaration
3903 const int AllowedModifiers =
3906 Modifiers.PROTECTED |
3907 Modifiers.INTERNAL |
3910 Modifiers.VOLATILE |
3914 public Field (Expression type, int mod, string name, Object expr_or_array_init,
3915 Attributes attrs, Location loc)
3916 : base (type, mod, AllowedModifiers, name, expr_or_array_init, attrs, loc)
3920 public override bool Define (TypeContainer container)
3922 Type t = container.ResolveType (Type, false, Location);
3927 CheckBase (container);
3929 if (!container.AsAccessible (t, ModFlags)) {
3930 Report.Error (52, Location,
3931 "Inconsistent accessibility: field type `" +
3932 TypeManager.CSharpName (t) + "' is less " +
3933 "accessible than field `" + Name + "'");
3937 if (t.IsPointer && !UnsafeOK (container))
3940 if (RootContext.WarningLevel > 1){
3941 Type ptype = container.TypeBuilder.BaseType;
3943 // ptype is only null for System.Object while compiling corlib.
3945 TypeContainer.FindMembers (
3946 ptype, MemberTypes.Method,
3947 BindingFlags.Public |
3948 BindingFlags.Static | BindingFlags.Instance,
3949 System.Type.FilterName, Name);
3953 if ((ModFlags & Modifiers.VOLATILE) != 0){
3957 if (TypeManager.IsEnumType (vt))
3958 vt = TypeManager.EnumToUnderlying (t);
3960 if (!((vt == TypeManager.bool_type) ||
3961 (vt == TypeManager.sbyte_type) ||
3962 (vt == TypeManager.byte_type) ||
3963 (vt == TypeManager.short_type) ||
3964 (vt == TypeManager.ushort_type) ||
3965 (vt == TypeManager.int32_type) ||
3966 (vt == TypeManager.uint32_type) ||
3967 (vt == TypeManager.char_type) ||
3968 (vt == TypeManager.float_type))){
3970 677, Location, container.MakeName (Name) +
3971 " A volatile field can not be of type `" +
3972 TypeManager.CSharpName (vt) + "'");
3977 if ((ModFlags & Modifiers.READONLY) != 0){
3980 "A field can not be both volatile and readonly");
3985 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
3987 if (container is Struct &&
3988 ((fa & FieldAttributes.Static) == 0) &&
3989 t == container.TypeBuilder &&
3990 !TypeManager.IsBuiltinType (t)){
3991 Report.Error (523, Location, "Struct member `" + container.Name + "." + Name +
3992 "' causes a cycle in the structure layout");
3997 FieldBuilder = container.TypeBuilder.DefineField (
3998 Name, t, Modifiers.FieldAttr (ModFlags));
4000 TypeManager.RegisterFieldBase (FieldBuilder, this);
4002 catch (ArgumentException) {
4003 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
4010 public void Emit (TypeContainer tc)
4012 EmitContext ec = new EmitContext (tc, Location, null,
4013 FieldBuilder.FieldType, ModFlags);
4015 Attribute.ApplyAttributes (ec, FieldBuilder, this, OptAttributes);
4020 // `set' and `get' accessors are represented with an Accessor.
4022 public class Accessor {
4024 // Null if the accessor is empty, or a Block if not
4027 public Attributes OptAttributes;
4029 public Accessor (Block b, Attributes attrs)
4032 OptAttributes = attrs;
4037 // Properties and Indexers both generate PropertyBuilders, we use this to share
4038 // their common bits.
4040 abstract public class PropertyBase : MethodCore {
4041 public Accessor Get, Set;
4042 public PropertyBuilder PropertyBuilder;
4043 public MethodBuilder GetBuilder, SetBuilder;
4044 public MethodData GetData, SetData;
4046 protected EmitContext ec;
4048 public PropertyBase (DeclSpace ds, Expression type, string name, int mod_flags,
4049 int allowed_mod, Parameters parameters,
4050 Accessor get_block, Accessor set_block,
4051 Attributes attrs, Location loc)
4052 : base (ds, type, mod_flags, allowed_mod, name, attrs, parameters, loc)
4058 protected override bool DoDefine (TypeContainer container)
4060 if (!base.DoDefine (container))
4063 ec = new EmitContext (container, Location, null, MemberType, ModFlags);
4069 // Checks our base implementation if any
4071 protected override bool CheckBase (TypeContainer container)
4073 base.CheckBase (container);
4075 // Check whether arguments were correct.
4076 if (!DoDefineParameters ())
4083 MethodSignature ms, base_ms;
4084 if (this is Indexer) {
4085 string name, base_name;
4087 report_name = "this";
4088 name = TypeManager.IndexerPropertyName (container.TypeBuilder);
4089 ms = new MethodSignature (name, null, ParameterTypes);
4090 base_name = TypeManager.IndexerPropertyName (container.TypeBuilder.BaseType);
4091 base_ms = new MethodSignature (base_name, null, ParameterTypes);
4094 ms = base_ms = new MethodSignature (Name, null, ParameterTypes);
4098 // Verify if the parent has a type with the same name, and then
4099 // check whether we have to create a new slot for it or not.
4101 Type ptype = container.TypeBuilder.BaseType;
4103 // ptype is only null for System.Object while compiling corlib.
4104 if (ptype == null) {
4105 if ((ModFlags & Modifiers.NEW) != 0)
4106 WarningNotHiding (container);
4111 MemberList props_this;
4113 props_this = TypeContainer.FindMembers (
4114 container.TypeBuilder, MemberTypes.Property,
4115 BindingFlags.NonPublic | BindingFlags.Public |
4116 BindingFlags.Static | BindingFlags.Instance |
4117 BindingFlags.DeclaredOnly,
4118 MethodSignature.method_signature_filter, ms);
4120 if (props_this.Count > 0) {
4121 Report.Error (111, Location, "Class `" + container.Name + "' " +
4122 "already defines a member called `" + report_name + "' " +
4123 "with the same parameter types");
4127 MemberList mi_props;
4129 mi_props = TypeContainer.FindMembers (
4130 ptype, MemberTypes.Property,
4131 BindingFlags.NonPublic | BindingFlags.Public |
4132 BindingFlags.Instance | BindingFlags.Static,
4133 MethodSignature.inheritable_method_signature_filter, base_ms);
4135 if (mi_props.Count > 0){
4136 PropertyInfo parent_property = (PropertyInfo) mi_props [0];
4137 string name = parent_property.DeclaringType.Name + "." +
4138 parent_property.Name;
4140 MethodInfo get, set, parent_method;
4141 get = parent_property.GetGetMethod (true);
4142 set = parent_property.GetSetMethod (true);
4145 parent_method = get;
4146 else if (set != null)
4147 parent_method = set;
4149 throw new Exception ("Internal error!");
4151 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
4154 if ((ModFlags & Modifiers.NEW) == 0) {
4155 Type parent_type = TypeManager.TypeToCoreType (
4156 parent_property.PropertyType);
4158 if (parent_type != MemberType) {
4160 508, Location, container.MakeName (Name) + ": cannot " +
4161 "change return type when overriding " +
4162 "inherited member " + name);
4167 if ((ModFlags & Modifiers.NEW) != 0)
4168 WarningNotHiding (container);
4170 if ((ModFlags & Modifiers.OVERRIDE) != 0){
4171 if (this is Indexer)
4172 Report.Error (115, Location,
4173 container.MakeName (Name) +
4174 " no suitable indexers found to override");
4176 Report.Error (115, Location,
4177 container.MakeName (Name) +
4178 " no suitable properties found to override");
4185 public void Emit (TypeContainer tc)
4188 // The PropertyBuilder can be null for explicit implementations, in that
4189 // case, we do not actually emit the ".property", so there is nowhere to
4190 // put the attribute
4192 if (PropertyBuilder != null)
4193 Attribute.ApplyAttributes (ec, PropertyBuilder, this, OptAttributes);
4195 if (GetData != null) {
4196 GetData.Emit (tc, Get.Block, Get);
4200 if (SetData != null) {
4201 SetData.Emit (tc, Set.Block, Set);
4207 public class Property : PropertyBase {
4208 const int AllowedModifiers =
4211 Modifiers.PROTECTED |
4212 Modifiers.INTERNAL |
4216 Modifiers.OVERRIDE |
4217 Modifiers.ABSTRACT |
4222 public Property (DeclSpace ds, Expression type, string name, int mod_flags,
4223 Accessor get_block, Accessor set_block,
4224 Attributes attrs, Location loc)
4225 : base (ds, type, name, mod_flags, AllowedModifiers,
4226 Parameters.EmptyReadOnlyParameters,
4227 get_block, set_block, attrs, loc)
4231 public override bool Define (TypeContainer container)
4233 if (!DoDefine (container))
4236 if (!CheckBase (container))
4239 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
4242 Type [] parameters = TypeManager.NoTypes;
4244 InternalParameters ip = new InternalParameters (
4245 container, Parameters.EmptyReadOnlyParameters);
4247 GetData = new MethodData (container, this, "get", MemberType,
4248 parameters, ip, CallingConventions.Standard,
4249 Get.OptAttributes, ModFlags, flags, false);
4251 if (!GetData.Define (container))
4254 GetBuilder = GetData.MethodBuilder;
4258 Type [] parameters = new Type [1];
4259 parameters [0] = MemberType;
4261 Parameter [] parms = new Parameter [1];
4262 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
4263 InternalParameters ip = new InternalParameters (
4264 container, new Parameters (parms, null, Location));
4266 SetData = new MethodData (container, this, "set", TypeManager.void_type,
4267 parameters, ip, CallingConventions.Standard,
4268 Set.OptAttributes, ModFlags, flags, false);
4270 if (!SetData.Define (container))
4273 SetBuilder = SetData.MethodBuilder;
4274 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4277 // FIXME - PropertyAttributes.HasDefault ?
4279 PropertyAttributes prop_attr =
4280 PropertyAttributes.RTSpecialName |
4281 PropertyAttributes.SpecialName;
4283 if (!IsExplicitImpl){
4284 PropertyBuilder = container.TypeBuilder.DefineProperty (
4285 Name, prop_attr, MemberType, null);
4288 PropertyBuilder.SetGetMethod (GetBuilder);
4291 PropertyBuilder.SetSetMethod (SetBuilder);
4294 // HACK for the reasons exposed above
4296 if (!TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder)) {
4299 "Class `" + container.Name +
4300 "' already contains a definition for the property `" +
4310 /// Gigantic workaround for lameness in SRE follows :
4311 /// This class derives from EventInfo and attempts to basically
4312 /// wrap around the EventBuilder so that FindMembers can quickly
4313 /// return this in it search for members
4315 public class MyEventBuilder : EventInfo {
4318 // We use this to "point" to our Builder which is
4319 // not really a MemberInfo
4321 EventBuilder MyBuilder;
4324 // We "catch" and wrap these methods
4326 MethodInfo raise, remove, add;
4328 EventAttributes attributes;
4329 Type declaring_type, reflected_type, event_type;
4334 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
4336 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
4338 // And now store the values in our own fields.
4340 declaring_type = type_builder;
4342 reflected_type = type_builder;
4344 attributes = event_attr;
4347 this.event_type = event_type;
4351 // Methods that you have to override. Note that you only need
4352 // to "implement" the variants that take the argument (those are
4353 // the "abstract" methods, the others (GetAddMethod()) are
4356 public override MethodInfo GetAddMethod (bool nonPublic)
4361 public override MethodInfo GetRemoveMethod (bool nonPublic)
4366 public override MethodInfo GetRaiseMethod (bool nonPublic)
4372 // These methods make "MyEventInfo" look like a Builder
4374 public void SetRaiseMethod (MethodBuilder raiseMethod)
4376 raise = raiseMethod;
4377 MyBuilder.SetRaiseMethod (raiseMethod);
4380 public void SetRemoveOnMethod (MethodBuilder removeMethod)
4382 remove = removeMethod;
4383 MyBuilder.SetRemoveOnMethod (removeMethod);
4386 public void SetAddOnMethod (MethodBuilder addMethod)
4389 MyBuilder.SetAddOnMethod (addMethod);
4392 public void SetCustomAttribute (CustomAttributeBuilder cb)
4394 MyBuilder.SetCustomAttribute (cb);
4397 public override object [] GetCustomAttributes (bool inherit)
4399 // FIXME : There's nothing which can be seemingly done here because
4400 // we have no way of getting at the custom attribute objects of the
4405 public override object [] GetCustomAttributes (Type t, bool inherit)
4407 // FIXME : Same here !
4411 public override bool IsDefined (Type t, bool b)
4416 public override EventAttributes Attributes {
4422 public override string Name {
4428 public override Type DeclaringType {
4430 return declaring_type;
4434 public override Type ReflectedType {
4436 return reflected_type;
4440 public Type EventType {
4446 public void SetUsed ()
4448 if (my_event != null)
4449 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
4453 public class Event : FieldBase {
4454 const int AllowedModifiers =
4457 Modifiers.PROTECTED |
4458 Modifiers.INTERNAL |
4463 Modifiers.OVERRIDE |
4467 public readonly Accessor Add;
4468 public readonly Accessor Remove;
4469 public MyEventBuilder EventBuilder;
4471 MethodBuilder AddBuilder, RemoveBuilder;
4472 MethodData AddData, RemoveData;
4474 public Event (Expression type, string name, Object init, int mod, Accessor add,
4475 Accessor remove, Attributes attrs, Location loc)
4476 : base (type, mod, AllowedModifiers, name, init, attrs, loc)
4482 public override bool Define (TypeContainer container)
4484 EventAttributes e_attr = EventAttributes.RTSpecialName | EventAttributes.SpecialName;
4485 MethodAttributes m_attr = MethodAttributes.HideBySig | MethodAttributes.SpecialName
4487 if (!DoDefine (container))
4490 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
4491 Report.Error (74, Location, "'" + container.Name + "." + Name +
4492 "': abstract event can not have an initializer");
4496 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
4497 Report.Error (66, Location, "'" + container.Name + "." + Name +
4498 "' : event must be of a delegate type");
4502 Type [] parameter_types = new Type [1];
4503 parameter_types [0] = MemberType;
4505 Parameter [] parms = new Parameter [1];
4506 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
4507 InternalParameters ip = new InternalParameters (
4508 container, new Parameters (parms, null, Location));
4510 if (!CheckBase (container))
4514 // Now define the accessors
4516 AddData = new MethodData (container, this, "add", TypeManager.void_type,
4517 parameter_types, ip, CallingConventions.Standard,
4518 (Add != null) ? Add.OptAttributes : null,
4519 ModFlags, flags | m_attr, false);
4521 if (!AddData.Define (container))
4524 AddBuilder = AddData.MethodBuilder;
4525 AddBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4527 RemoveData = new MethodData (container, this, "remove", TypeManager.void_type,
4528 parameter_types, ip, CallingConventions.Standard,
4529 (Remove != null) ? Remove.OptAttributes : null,
4530 ModFlags, flags | m_attr, false);
4532 if (!RemoveData.Define (container))
4535 RemoveBuilder = RemoveData.MethodBuilder;
4536 RemoveBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4538 if (!IsExplicitImpl){
4539 EventBuilder = new MyEventBuilder (this,
4540 container.TypeBuilder, Name, e_attr, MemberType);
4542 if (Add == null && Remove == null) {
4543 FieldBuilder = container.TypeBuilder.DefineField (
4545 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
4546 TypeManager.RegisterPrivateFieldOfEvent (
4547 (EventInfo) EventBuilder, FieldBuilder);
4548 TypeManager.RegisterFieldBase (FieldBuilder, this);
4551 EventBuilder.SetAddOnMethod (AddBuilder);
4552 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
4554 if (!TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder)) {
4555 Report.Error (111, Location,
4556 "Class `" + container.Name +
4557 "' already contains a definition for the event `" +
4566 void EmitDefaultMethod (EmitContext ec, bool is_add)
4568 ILGenerator ig = ec.ig;
4569 MethodInfo method = null;
4572 method = TypeManager.delegate_combine_delegate_delegate;
4574 method = TypeManager.delegate_remove_delegate_delegate;
4576 if ((ModFlags & Modifiers.STATIC) != 0) {
4577 ig.Emit (OpCodes.Ldsfld, (FieldInfo) FieldBuilder);
4578 ig.Emit (OpCodes.Ldarg_0);
4579 ig.Emit (OpCodes.Call, method);
4580 ig.Emit (OpCodes.Castclass, MemberType);
4581 ig.Emit (OpCodes.Stsfld, (FieldInfo) FieldBuilder);
4583 ig.Emit (OpCodes.Ldarg_0);
4584 ig.Emit (OpCodes.Ldarg_0);
4585 ig.Emit (OpCodes.Ldfld, (FieldInfo) FieldBuilder);
4586 ig.Emit (OpCodes.Ldarg_1);
4587 ig.Emit (OpCodes.Call, method);
4588 ig.Emit (OpCodes.Castclass, MemberType);
4589 ig.Emit (OpCodes.Stfld, (FieldInfo) FieldBuilder);
4591 ig.Emit (OpCodes.Ret);
4594 public void Emit (TypeContainer tc)
4598 ec = new EmitContext (tc, Location, null, MemberType, ModFlags);
4599 Attribute.ApplyAttributes (ec, EventBuilder, this, OptAttributes);
4602 AddData.Emit (tc, Add.Block, Add);
4605 ILGenerator ig = AddData.MethodBuilder.GetILGenerator ();
4606 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
4607 EmitDefaultMethod (ec, true);
4610 if (Remove != null) {
4611 RemoveData.Emit (tc, Remove.Block, Remove);
4612 Remove.Block = null;
4614 ILGenerator ig = RemoveData.MethodBuilder.GetILGenerator ();
4615 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
4616 EmitDefaultMethod (ec, false);
4623 // FIXME: This does not handle:
4625 // int INTERFACENAME [ args ]
4630 // int this [ args ]
4632 public class Indexer : PropertyBase {
4634 const int AllowedModifiers =
4637 Modifiers.PROTECTED |
4638 Modifiers.INTERNAL |
4642 Modifiers.OVERRIDE |
4647 public string IndexerName;
4648 public string InterfaceIndexerName;
4651 // Are we implementing an interface ?
4653 public Indexer (DeclSpace ds, Expression type, string int_type, int flags,
4654 Parameters parameters, Accessor get_block, Accessor set_block,
4655 Attributes attrs, Location loc)
4656 : base (ds, type, "", flags, AllowedModifiers, parameters, get_block, set_block,
4659 ExplicitInterfaceName = int_type;
4662 public override bool Define (TypeContainer container)
4664 PropertyAttributes prop_attr =
4665 PropertyAttributes.RTSpecialName |
4666 PropertyAttributes.SpecialName;
4668 if (!DoDefine (container))
4671 IndexerName = Attribute.ScanForIndexerName (ec, OptAttributes);
4672 if (IndexerName == null)
4673 IndexerName = "Item";
4674 else if (IsExplicitImpl)
4675 Report.Error (592, Location,
4676 "Attribute 'IndexerName' is not valid on this declaration " +
4677 "type. It is valid on `property' declarations only.");
4679 ShortName = IndexerName;
4680 if (IsExplicitImpl) {
4681 InterfaceIndexerName = TypeManager.IndexerPropertyName (InterfaceType);
4682 Name = InterfaceType.FullName + "." + IndexerName;
4684 InterfaceIndexerName = IndexerName;
4688 if (!CheckBase (container))
4691 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
4693 InternalParameters ip = new InternalParameters (container, Parameters);
4695 GetData = new MethodData (container, this, "get", MemberType,
4696 ParameterTypes, ip, CallingConventions.Standard,
4697 Get.OptAttributes, ModFlags, flags, false);
4699 if (!GetData.Define (container))
4702 GetBuilder = GetData.MethodBuilder;
4706 int top = ParameterTypes.Length;
4707 Type [] set_pars = new Type [top + 1];
4708 ParameterTypes.CopyTo (set_pars, 0);
4709 set_pars [top] = MemberType;
4711 Parameter [] fixed_parms = Parameters.FixedParameters;
4713 if (fixed_parms == null){
4714 throw new Exception ("We currently do not support only array arguments in an indexer at: " + Location);
4715 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4716 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4718 // Here is the problem: the `value' parameter has
4719 // to come *after* the array parameter in the declaration
4721 // X (object [] x, Type value)
4724 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4725 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4729 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
4732 fixed_parms.CopyTo (tmp, 0);
4733 tmp [fixed_parms.Length] = new Parameter (
4734 Type, "value", Parameter.Modifier.NONE, null);
4736 Parameters set_formal_params = new Parameters (tmp, null, Location);
4738 InternalParameters ip = new InternalParameters (container, set_formal_params);
4740 SetData = new MethodData (container, this, "set", TypeManager.void_type,
4741 set_pars, ip, CallingConventions.Standard,
4742 Set.OptAttributes, ModFlags, flags, false);
4744 if (!SetData.Define (container))
4747 SetBuilder = SetData.MethodBuilder;
4751 // Now name the parameters
4753 Parameter [] p = Parameters.FixedParameters;
4757 for (i = 0; i < p.Length; ++i) {
4759 GetBuilder.DefineParameter (
4760 i + 1, p [i].Attributes, p [i].Name);
4763 SetBuilder.DefineParameter (
4764 i + 1, p [i].Attributes, p [i].Name);
4768 SetBuilder.DefineParameter (
4769 i + 1, ParameterAttributes.None, "value");
4771 if (i != ParameterTypes.Length) {
4772 Parameter array_param = Parameters.ArrayParameter;
4774 SetBuilder.DefineParameter (
4775 i + 1, array_param.Attributes, array_param.Name);
4780 // Define the PropertyBuilder if one of the following conditions are met:
4781 // a) we're not implementing an interface indexer.
4782 // b) the indexer has a different IndexerName and this is no
4783 // explicit interface implementation.
4785 if (!IsExplicitImpl) {
4786 PropertyBuilder = container.TypeBuilder.DefineProperty (
4787 IndexerName, prop_attr, MemberType, ParameterTypes);
4789 if (GetData != null)
4790 PropertyBuilder.SetGetMethod (GetBuilder);
4792 if (SetData != null)
4793 PropertyBuilder.SetSetMethod (SetBuilder);
4795 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder,
4803 public class Operator : MemberBase {
4805 const int AllowedModifiers =
4811 const int RequiredModifiers =
4815 public enum OpType : byte {
4825 // Unary and Binary operators
4848 // Implicit and Explicit
4853 public readonly OpType OperatorType;
4854 public readonly Expression ReturnType;
4855 public readonly Expression FirstArgType, SecondArgType;
4856 public readonly string FirstArgName, SecondArgName;
4858 public MethodBuilder OperatorMethodBuilder;
4860 public string MethodName;
4861 public Method OperatorMethod;
4863 public Operator (OpType type, Expression ret_type, int mod_flags,
4864 Expression arg1type, string arg1name,
4865 Expression arg2type, string arg2name,
4866 Block block, Attributes attrs, Location loc)
4867 : base (ret_type, mod_flags, AllowedModifiers, Modifiers.PUBLIC, "", attrs, loc)
4869 OperatorType = type;
4870 ReturnType = ret_type;
4871 FirstArgType = arg1type;
4872 FirstArgName = arg1name;
4873 SecondArgType = arg2type;
4874 SecondArgName = arg2name;
4878 string Prototype (TypeContainer container)
4880 return container.Name + ".operator " + OperatorType + " (" + FirstArgType + "," +
4881 SecondArgType + ")";
4884 public override bool Define (TypeContainer container)
4887 MethodName = "op_" + OperatorType;
4889 if (SecondArgType != null)
4892 Parameter [] param_list = new Parameter [length];
4894 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
4897 "User defined operators `" +
4898 Prototype (container) +
4899 "' must be declared static and public");
4903 param_list[0] = new Parameter (FirstArgType, FirstArgName,
4904 Parameter.Modifier.NONE, null);
4905 if (SecondArgType != null)
4906 param_list[1] = new Parameter (SecondArgType, SecondArgName,
4907 Parameter.Modifier.NONE, null);
4909 OperatorMethod = new Method (container, ReturnType, ModFlags, MethodName,
4910 new Parameters (param_list, null, Location),
4911 OptAttributes, Location);
4913 OperatorMethod.IsOperator = true;
4914 OperatorMethod.Define (container);
4916 if (OperatorMethod.MethodBuilder == null)
4919 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
4921 Type [] param_types = OperatorMethod.ParameterTypes;
4922 Type declaring_type = OperatorMethodBuilder.DeclaringType;
4923 Type return_type = OperatorMethod.GetReturnType ();
4924 Type first_arg_type = param_types [0];
4926 // Rules for conversion operators
4928 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
4929 if (first_arg_type == return_type && first_arg_type == declaring_type){
4932 "User-defined conversion cannot take an object of the " +
4933 "enclosing type and convert to an object of the enclosing" +
4938 if (first_arg_type != declaring_type && return_type != declaring_type){
4941 "User-defined conversion must convert to or from the " +
4946 if (first_arg_type == TypeManager.object_type ||
4947 return_type == TypeManager.object_type){
4950 "User-defined conversion cannot convert to or from " +
4955 if (first_arg_type.IsInterface || return_type.IsInterface){
4958 "User-defined conversion cannot convert to or from an " +
4963 if (first_arg_type.IsSubclassOf (return_type) ||
4964 return_type.IsSubclassOf (first_arg_type)){
4967 "User-defined conversion cannot convert between types " +
4968 "that derive from each other");
4971 } else if (SecondArgType == null) {
4972 // Checks for Unary operators
4974 if (first_arg_type != declaring_type){
4977 "The parameter of a unary operator must be the " +
4982 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
4983 if (return_type != declaring_type){
4986 "The parameter and return type for ++ and -- " +
4987 "must be the containing type");
4993 if (OperatorType == OpType.True || OperatorType == OpType.False) {
4994 if (return_type != TypeManager.bool_type){
4997 "The return type of operator True or False " +
5004 // Checks for Binary operators
5006 if (first_arg_type != declaring_type &&
5007 param_types [1] != declaring_type){
5010 "One of the parameters of a binary operator must " +
5011 "be the containing type");
5019 public void Emit (TypeContainer container)
5022 // abstract or extern methods have no bodies
5024 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
5027 OperatorMethod.Block = Block;
5028 OperatorMethod.Emit (container);
5032 public static string GetName (OpType ot)
5035 case OpType.LogicalNot:
5037 case OpType.OnesComplement:
5039 case OpType.Increment:
5041 case OpType.Decrement:
5047 case OpType.Addition:
5049 case OpType.Subtraction:
5051 case OpType.UnaryPlus:
5053 case OpType.UnaryNegation:
5055 case OpType.Multiply:
5057 case OpType.Division:
5059 case OpType.Modulus:
5061 case OpType.BitwiseAnd:
5063 case OpType.BitwiseOr:
5065 case OpType.ExclusiveOr:
5067 case OpType.LeftShift:
5069 case OpType.RightShift:
5071 case OpType.Equality:
5073 case OpType.Inequality:
5075 case OpType.GreaterThan:
5077 case OpType.LessThan:
5079 case OpType.GreaterThanOrEqual:
5081 case OpType.LessThanOrEqual:
5083 case OpType.Implicit:
5085 case OpType.Explicit:
5091 public override string ToString ()
5093 Type return_type = OperatorMethod.GetReturnType();
5094 Type [] param_types = OperatorMethod.ParameterTypes;
5096 if (SecondArgType == null)
5097 return String.Format (
5098 "{0} operator {1}({2})",
5099 TypeManager.CSharpName (return_type),
5100 GetName (OperatorType),
5103 return String.Format (
5104 "{0} operator {1}({2}, {3})",
5105 TypeManager.CSharpName (return_type),
5106 GetName (OperatorType),
5107 param_types [0], param_types [1]);
5112 // This is used to compare method signatures
5114 struct MethodSignature {
5116 public Type RetType;
5117 public Type [] Parameters;
5120 /// This delegate is used to extract methods which have the
5121 /// same signature as the argument
5123 public static MemberFilter method_signature_filter;
5126 /// This delegate is used to extract inheritable methods which
5127 /// have the same signature as the argument. By inheritable,
5128 /// this means that we have permissions to override the method
5129 /// from the current assembly and class
5131 public static MemberFilter inheritable_method_signature_filter;
5133 static MethodSignature ()
5135 method_signature_filter = new MemberFilter (MemberSignatureCompare);
5136 inheritable_method_signature_filter = new MemberFilter (
5137 InheritableMemberSignatureCompare);
5140 public MethodSignature (string name, Type ret_type, Type [] parameters)
5145 if (parameters == null)
5146 Parameters = TypeManager.NoTypes;
5148 Parameters = parameters;
5151 public override string ToString ()
5154 if (Parameters.Length != 0){
5155 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
5156 for (int i = 0; i < Parameters.Length; i++){
5157 sb.Append (Parameters [i]);
5158 if (i+1 < Parameters.Length)
5161 pars = sb.ToString ();
5164 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
5167 public override int GetHashCode ()
5169 return Name.GetHashCode ();
5172 public override bool Equals (Object o)
5174 MethodSignature other = (MethodSignature) o;
5176 if (other.Name != Name)
5179 if (other.RetType != RetType)
5182 if (Parameters == null){
5183 if (other.Parameters == null)
5188 if (other.Parameters == null)
5191 int c = Parameters.Length;
5192 if (other.Parameters.Length != c)
5195 for (int i = 0; i < c; i++)
5196 if (other.Parameters [i] != Parameters [i])
5202 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
5204 MethodSignature sig = (MethodSignature) filter_criteria;
5206 if (m.Name != sig.Name)
5210 MethodInfo mi = m as MethodInfo;
5211 PropertyInfo pi = m as PropertyInfo;
5214 ReturnType = mi.ReturnType;
5215 else if (pi != null)
5216 ReturnType = pi.PropertyType;
5221 // we use sig.RetType == null to mean `do not check the
5222 // method return value.
5224 if (sig.RetType != null)
5225 if (ReturnType != sig.RetType)
5230 args = TypeManager.GetArgumentTypes (mi);
5232 args = TypeManager.GetArgumentTypes (pi);
5233 Type [] sigp = sig.Parameters;
5235 if (args.Length != sigp.Length)
5238 for (int i = args.Length; i > 0; ){
5240 if (args [i] != sigp [i])
5247 // This filter should be used when we are requesting methods that
5248 // we want to override.
5250 // This makes a number of assumptions, for example
5251 // that the methods being extracted are of a parent
5252 // class (this means we know implicitly that we are
5253 // being called to find out about members by a derived
5256 static bool InheritableMemberSignatureCompare (MemberInfo m, object filter_criteria)
5259 PropertyInfo pi = m as PropertyInfo;
5262 mi = pi.GetGetMethod (true);
5264 mi = pi.GetSetMethod (true);
5266 mi = m as MethodInfo;
5269 Console.WriteLine ("Nothing found");
5272 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5274 // If only accessible to the current class.
5275 if (prot == MethodAttributes.Private)
5278 if (!MemberSignatureCompare (m, filter_criteria))
5281 // If only accessible to the defining assembly or
5282 if (prot == MethodAttributes.FamANDAssem ||
5283 prot == MethodAttributes.Assembly){
5284 if (m.DeclaringType.Assembly == CodeGen.AssemblyBuilder)
5290 // Anything else (FamOrAssembly and Public) is fine