2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@gnome.org)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
12 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
14 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
15 // have fixed a remaining problem: not every AddXXXX was adding a
16 // fully qualified name.
18 // Now everyone registers a fully qualified name in the DeclSpace as
19 // being defined instead of the partial name.
21 // Downsides: we are slower than we need to be due to the excess
22 // copies and the names being registered this way.
24 // The reason for this is that we currently depend (on the corlib
25 // bootstrap for instance) that types are fully qualified, because
26 // we dump all the types in the namespace, and we should really have
27 // types inserted into the proper namespace, so we can only store the
28 // basenames in the defined_names array.
33 using System.Collections;
34 using System.Reflection;
35 using System.Reflection.Emit;
36 using System.Runtime.CompilerServices;
38 namespace Mono.CSharp {
41 /// This is the base class for structs and classes.
43 public class TypeContainer : DeclSpace, IMemberContainer {
44 // Holds a list of classes and structures
47 // Holds the list of properties
50 // Holds the list of enumerations
53 // Holds the list of delegates
56 // Holds the list of constructors
57 ArrayList instance_constructors;
59 // Holds the list of fields
62 // Holds a list of fields that have initializers
63 ArrayList initialized_fields;
65 // Holds a list of static fields that have initializers
66 ArrayList initialized_static_fields;
68 // Holds the list of constants
74 // Holds order in which interfaces must be closed
75 ArrayList interface_order;
86 // Holds the operators
89 // The emit context for toplevel objects.
93 // Pointers to the default constructor and the default static constructor
95 Constructor default_constructor;
96 Constructor default_static_constructor;
99 // Whether we have seen a static constructor for this class or not
101 bool have_static_constructor = false;
104 // Whether we have at least one non-static field
106 bool have_nonstatic_fields = false;
109 // This one is computed after we can distinguish interfaces
110 // from classes from the arraylist `type_bases'
112 string base_class_name;
114 ArrayList type_bases;
116 // Attributes for this type
117 protected Attributes attributes;
119 // Information in the case we are an attribute type
121 public AttributeTargets Targets = AttributeTargets.All;
122 public bool AllowMultiple = false;
123 public bool Inherited;
125 // The interfaces we implement.
128 // The parent member container and our member cache
129 IMemberContainer parent_container;
130 MemberCache member_cache;
133 // The indexer name for this class
135 public string IndexerName;
137 public TypeContainer (TypeContainer parent, string name, Location l)
138 : base (parent, name, l)
141 types = new ArrayList ();
148 base_class_name = null;
150 //Console.WriteLine ("New class " + name + " inside " + n);
153 public AdditionResult AddConstant (Const constant)
156 string basename = constant.Name;
157 string fullname = Name + "." + basename;
159 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
162 if (constants == null)
163 constants = new ArrayList ();
165 constants.Add (constant);
166 DefineName (fullname, constant);
168 return AdditionResult.Success;
171 public AdditionResult AddEnum (Mono.CSharp.Enum e)
175 if ((res = IsValid (e.Basename, e.Name)) != AdditionResult.Success)
179 enums = new ArrayList ();
182 DefineName (e.Name, e);
184 return AdditionResult.Success;
187 public AdditionResult AddClass (Class c)
190 string name = c.Basename;
192 if ((res = IsValid (name, c.Name)) != AdditionResult.Success)
195 DefineName (c.Name, c);
198 return AdditionResult.Success;
201 public AdditionResult AddStruct (Struct s)
204 string name = s.Basename;
206 if ((res = IsValid (name, s.Name)) != AdditionResult.Success)
209 DefineName (s.Name, s);
212 return AdditionResult.Success;
215 public AdditionResult AddDelegate (Delegate d)
218 string name = d.Basename;
220 if ((res = IsValid (name, d.Name)) != AdditionResult.Success)
223 if (delegates == null)
224 delegates = new ArrayList ();
226 DefineName (d.Name, d);
229 return AdditionResult.Success;
232 public AdditionResult AddMethod (Method method)
234 string basename = method.Name;
235 string fullname = Name + "." + basename;
237 Object value = defined_names [fullname];
239 if (value != null && (!(value is Method)))
240 return AdditionResult.NameExists;
242 if (basename == Basename)
243 return AdditionResult.EnclosingClash;
246 methods = new ArrayList ();
248 if (method.Name.IndexOf (".") != -1)
249 methods.Insert (0, method);
251 methods.Add (method);
254 DefineName (fullname, method);
256 return AdditionResult.Success;
259 public AdditionResult AddConstructor (Constructor c)
261 if (c.Name != Basename)
262 return AdditionResult.NotAConstructor;
264 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
267 have_static_constructor = true;
268 if (default_static_constructor != null){
269 Console.WriteLine ("I have a static constructor already");
270 Console.WriteLine (" " + default_static_constructor);
271 return AdditionResult.MethodExists;
274 default_static_constructor = c;
277 if (default_constructor != null)
278 return AdditionResult.MethodExists;
279 default_constructor = c;
282 if (instance_constructors == null)
283 instance_constructors = new ArrayList ();
285 instance_constructors.Add (c);
288 return AdditionResult.Success;
291 public AdditionResult AddInterface (Interface iface)
294 string name = iface.Basename;
296 if ((res = IsValid (name, iface.Name)) != AdditionResult.Success)
299 if (interfaces == null)
300 interfaces = new ArrayList ();
301 interfaces.Add (iface);
302 DefineName (iface.Name, iface);
304 return AdditionResult.Success;
307 public AdditionResult AddField (Field field)
310 string basename = field.Name;
311 string fullname = Name + "." + basename;
313 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
317 fields = new ArrayList ();
321 if (field.HasInitializer){
322 if ((field.ModFlags & Modifiers.STATIC) != 0){
323 if (initialized_static_fields == null)
324 initialized_static_fields = new ArrayList ();
326 initialized_static_fields.Add (field);
329 // We have not seen a static constructor,
330 // but we will provide static initialization of fields
332 have_static_constructor = true;
334 if (initialized_fields == null)
335 initialized_fields = new ArrayList ();
337 initialized_fields.Add (field);
341 if ((field.ModFlags & Modifiers.STATIC) == 0)
342 have_nonstatic_fields = true;
344 DefineName (fullname, field);
345 return AdditionResult.Success;
348 public AdditionResult AddProperty (Property prop)
351 string basename = prop.Name;
352 string fullname = Name + "." + basename;
354 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
357 if (properties == null)
358 properties = new ArrayList ();
360 if (prop.Name.IndexOf (".") != -1)
361 properties.Insert (0, prop);
363 properties.Add (prop);
364 DefineName (fullname, prop);
366 return AdditionResult.Success;
369 public AdditionResult AddEvent (Event e)
372 string basename = e.Name;
373 string fullname = Name + "." + basename;
375 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
379 events = new ArrayList ();
382 DefineName (fullname, e);
384 return AdditionResult.Success;
387 public AdditionResult AddIndexer (Indexer i)
389 if (indexers == null)
390 indexers = new ArrayList ();
392 if (i.InterfaceType != null)
393 indexers.Insert (0, i);
397 return AdditionResult.Success;
400 public AdditionResult AddOperator (Operator op)
402 if (operators == null)
403 operators = new ArrayList ();
407 return AdditionResult.Success;
410 public void RegisterOrder (Interface iface)
412 if (interface_order == null)
413 interface_order = new ArrayList ();
415 interface_order.Add (iface);
418 public ArrayList Types {
424 public ArrayList Methods {
430 public ArrayList Constants {
436 public ArrayList Interfaces {
444 return base_class_name;
448 public ArrayList Bases {
458 public ArrayList Fields {
468 public ArrayList InstanceConstructors {
470 return instance_constructors;
474 public ArrayList Properties {
480 public ArrayList Events {
486 public ArrayList Enums {
492 public ArrayList Indexers {
498 public ArrayList Operators {
504 public ArrayList Delegates {
510 public Attributes OptAttributes {
516 public bool HaveStaticConstructor {
518 return have_static_constructor;
522 public virtual TypeAttributes TypeAttr {
524 return Modifiers.TypeAttr (ModFlags, this);
529 // Emits the instance field initializers
531 public bool EmitFieldInitializers (EmitContext ec)
534 ILGenerator ig = ec.ig;
535 Expression instance_expr;
538 fields = initialized_static_fields;
539 instance_expr = null;
541 fields = initialized_fields;
542 instance_expr = new This (Location.Null).Resolve (ec);
548 foreach (Field f in fields){
549 Expression e = f.GetInitializerExpression (ec);
553 Location l = f.Location;
554 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
555 fe.InstanceExpression = instance_expr;
556 ExpressionStatement a = new Assign (fe, e, l);
558 a = a.ResolveStatement (ec);
562 a.EmitStatement (ec);
569 // Defines the default constructors
571 void DefineDefaultConstructor (bool is_static)
576 c = new Constructor (Basename, Parameters.EmptyReadOnlyParameters,
577 new ConstructorBaseInitializer (
578 null, Parameters.EmptyReadOnlyParameters,
583 mods = Modifiers.STATIC;
589 c.Block = new Block (null);
593 public void ReportStructInitializedInstanceError ()
595 string n = TypeBuilder.FullName;
597 foreach (Field f in initialized_fields){
600 "`" + n + "." + f.Name + "': can not have " +
601 "instance field initializers in structs");
606 /// The pending methods that need to be implemented (interfaces or abstract methods)
608 public PendingImplementation Pending;
611 /// This function computes the Base class and also the
612 /// list of interfaces that the class or struct @c implements.
614 /// The return value is an array (might be null) of
615 /// interfaces implemented (as Types).
617 /// The @parent argument is set to the parent object or null
618 /// if this is `System.Object'.
620 Type [] GetClassBases (bool is_class, out Type parent, out bool error)
622 ArrayList bases = Bases;
631 parent = TypeManager.value_type;
635 if (RootContext.StdLib)
636 parent = TypeManager.object_type;
637 else if (Name != "System.Object")
638 parent = TypeManager.object_type;
641 // If we are compiling our runtime,
642 // and we are defining ValueType, then our
643 // parent is `System.Object'.
645 if (!RootContext.StdLib && Name == "System.ValueType")
646 parent = TypeManager.object_type;
653 // Bases should be null if there are no bases at all
658 Expression name = (Expression) bases [0];
659 name = ResolveTypeExpr (name, false, Location);
666 Type first = name.Type;
672 parent = TypeManager.object_type;
678 if (first.IsValueType)
679 detail = " (a class can not inherit from a struct/enum)";
681 Report.Error (509, "class `"+ Name +
682 "': Cannot inherit from sealed class `"+
683 first + "'" + detail);
688 if (!AsAccessible (parent, ModFlags))
689 Report.Error (60, Location,
690 "Inconsistent accessibility: base class `" +
691 TypeManager.CSharpName (parent) + "' is less " +
692 "accessible than class `" +
700 base_class_name = parent.Name;
702 Type [] ifaces = new Type [count-start];
704 for (i = start, j = 0; i < count; i++, j++){
705 Expression name = (Expression) bases [i];
706 Expression resolved = ResolveTypeExpr (name, false, Location);
707 if (resolved == null)
710 bases [i] = resolved;
711 Type t = resolved.Type;
718 if (is_class == false && !t.IsInterface){
719 Report.Error (527, "In Struct `" + Name + "', type `"+
720 name +"' is not an interface");
727 Report.Error (527, "In Class `" + Name + "', type `"+
728 name+"' is not an interface");
734 for (int x = 0; x < j; x++) {
735 if (t == ifaces [x]) {
736 Report.Error (528, "`" + name + "' is already listed in interface list");
745 return TypeManager.ExpandInterfaces (ifaces);
749 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
751 public override TypeBuilder DefineType ()
757 if (TypeBuilder != null)
770 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
772 ifaces = GetClassBases (is_class, out parent, out error);
777 if (is_class && parent != null){
778 if (parent == TypeManager.enum_type ||
779 (parent == TypeManager.value_type && RootContext.StdLib) ||
780 parent == TypeManager.delegate_type ||
781 parent == TypeManager.array_type){
783 644, Location, "`" + Name + "' cannot inherit from " +
784 "special class `" + TypeManager.CSharpName (parent) + "'");
789 if (!is_class && TypeManager.value_type == null)
790 throw new Exception ();
792 TypeAttributes type_attributes = TypeAttr;
794 // if (parent_builder is ModuleBuilder) {
796 if (TypeManager.NamespaceClash (Name, Location))
799 ModuleBuilder builder = CodeGen.ModuleBuilder;
800 TypeBuilder = builder.DefineType (
801 Name, type_attributes, parent, ifaces);
804 TypeBuilder builder = Parent.TypeBuilder;
805 TypeBuilder = builder.DefineNestedType (
806 Basename, type_attributes, parent, ifaces);
810 // Structs with no fields need to have at least one byte.
811 // The right thing would be to set the PackingSize in a DefineType
812 // but there are no functions that allow interfaces *and* the size to
816 if (!is_class && !have_nonstatic_fields){
817 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
818 FieldAttributes.Private);
819 // add interfaces that were not added at type creation
820 if (ifaces != null) {
821 foreach (Type i in ifaces)
822 TypeBuilder.AddInterfaceImplementation (i);
827 // Finish the setup for the EmitContext
829 ec.ContainerType = TypeBuilder;
831 TypeManager.AddUserType (Name, TypeBuilder, this, ifaces);
833 if ((parent != null) &&
834 (parent == TypeManager.attribute_type ||
835 parent.IsSubclassOf (TypeManager.attribute_type))) {
836 RootContext.RegisterAttribute (this);
837 TypeManager.RegisterAttrType (TypeBuilder, this);
839 RootContext.RegisterOrder (this);
841 if (Interfaces != null) {
842 foreach (Interface iface in Interfaces)
847 foreach (TypeContainer tc in Types)
851 if (Delegates != null) {
852 foreach (Delegate d in Delegates)
857 foreach (Enum en in Enums)
867 /// Defines the MemberCore objects that are in the `list' Arraylist
869 /// The `defined_names' array contains a list of members defined in
872 static ArrayList remove_list = new ArrayList ();
873 void DefineMembers (ArrayList list, MemberInfo [] defined_names)
877 remove_list.Clear ();
879 foreach (MemberCore mc in list){
880 if (!mc.Define (this)){
881 remove_list.Add (mc);
885 if (defined_names == null)
888 idx = Array.BinarySearch (defined_names, mc.Name, mif_compare);
890 if (RootContext.WarningLevel >= 4){
891 if ((mc.ModFlags & Modifiers.NEW) != 0)
892 Warning_KewywordNewNotRequired (mc.Location, mc);
897 MemberInfo match = defined_names [idx];
899 if (match is PropertyInfo && ((mc.ModFlags & Modifiers.OVERRIDE) != 0))
903 // If we are both methods, let the method resolution emit warnings
905 if (match is MethodBase && mc is MethodCore)
908 if ((mc.ModFlags & Modifiers.NEW) == 0) {
910 if (!(match is EventInfo)) {
911 Error_EventCanOnlyOverrideEvent (mc.Location, defined_names [idx]);
915 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
919 Warning_KeywordNewRequired (mc.Location, defined_names [idx]);
923 foreach (object o in remove_list)
926 remove_list.Clear ();
930 // Defines the indexers, and also verifies that the IndexerNameAttribute in the
931 // class is consisten. Either it is `Item' or it is the name defined by all the
932 // indexers with the `IndexerName' attribute.
934 // Turns out that the IndexerNameAttribute is applied to each indexer,
935 // but it is never emitted, instead a DefaultName attribute is attached
938 void DefineIndexers ()
940 string class_indexer_name = null;
943 // If there's both an explicit and an implicit interface implementation, the
944 // explicit one actually implements the interface while the other one is just
945 // a normal indexer. See bug #37714.
947 ArrayList list = new ArrayList ();
948 foreach (Indexer i in Indexers){
949 if (i.ExplicitInterfaceName != null)
952 foreach (Indexer i in Indexers){
953 if (i.ExplicitInterfaceName == null)
957 foreach (Indexer i in list){
962 name = i.IndexerName;
964 if (i.InterfaceType != null)
967 if (class_indexer_name == null){
968 class_indexer_name = name;
972 if (name == class_indexer_name)
976 668, "Two indexers have different names, " +
977 " you should use the same name for all your indexers");
979 if (class_indexer_name == null)
980 class_indexer_name = "Item";
981 IndexerName = class_indexer_name;
984 static void Error_KeywordNotAllowed (Location loc)
986 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
990 /// Populates our TypeBuilder with fields and methods
992 public override bool DefineMembers (TypeContainer container)
994 MemberInfo [] defined_names = null;
996 if (interface_order != null){
997 foreach (Interface iface in interface_order)
998 if ((iface.ModFlags & Modifiers.NEW) == 0)
999 iface.DefineMembers (this);
1001 Error_KeywordNotAllowed (iface.Location);
1004 if (RootContext.WarningLevel > 1){
1008 // This code throws an exception in the comparer
1009 // I guess the string is not an object?
1011 ptype = TypeBuilder.BaseType;
1013 defined_names = (MemberInfo []) FindMembers (
1014 ptype, MemberTypes.All & ~MemberTypes.Constructor,
1015 BindingFlags.Public | BindingFlags.Instance |
1016 BindingFlags.Static, null, null);
1018 Array.Sort (defined_names, mif_compare);
1022 Class pclass = Parent as Class;
1023 if (pclass != null) {
1024 string pname = null;
1026 Type t = pclass.TypeBuilder.BaseType;
1027 while ((t != null) && (ptype == null)) {
1028 pname = MakeFQN (t.Name, Basename);
1029 ptype = RootContext.LookupType (this, pname, true, Location.Null);
1033 if ((ModFlags & Modifiers.NEW) != 0) {
1035 Report.Warning (109, Location, "The member '" + Name + "' does not hide an " +
1036 "inherited member. The keyword new is not required.");
1037 } else if (ptype != null) {
1038 Report.Warning (108, Location, "The keyword new is required on `" +
1039 Name + "' because it hides inherited member '" +
1042 } else if ((ModFlags & Modifiers.NEW) != 0)
1043 Error_KeywordNotAllowed (Location);
1045 if (constants != null)
1046 DefineMembers (constants, defined_names);
1049 DefineMembers (fields, defined_names);
1052 if (instance_constructors == null){
1053 if (default_constructor == null)
1054 DefineDefaultConstructor (false);
1057 if (initialized_static_fields != null &&
1058 default_static_constructor == null)
1059 DefineDefaultConstructor (true);
1062 if (this is Struct){
1064 // Structs can not have initialized instance
1067 if (initialized_static_fields != null &&
1068 default_static_constructor == null)
1069 DefineDefaultConstructor (true);
1071 if (initialized_fields != null)
1072 ReportStructInitializedInstanceError ();
1075 Pending = PendingImplementation.GetPendingImplementations (this);
1078 // Constructors are not in the defined_names array
1080 if (instance_constructors != null)
1081 DefineMembers (instance_constructors, null);
1083 if (default_static_constructor != null)
1084 default_static_constructor.Define (this);
1086 if (methods != null)
1087 DefineMembers (methods, defined_names);
1089 if (properties != null)
1090 DefineMembers (properties, defined_names);
1093 DefineMembers (events, defined_names);
1095 if (indexers != null) {
1098 IndexerName = "Item";
1100 if (operators != null){
1101 DefineMembers (operators, null);
1103 CheckPairedOperators ();
1107 DefineMembers (enums, defined_names);
1109 if (delegates != null)
1110 DefineMembers (delegates, defined_names);
1113 if (TypeBuilder.BaseType != null)
1114 parent_container = TypeManager.LookupMemberContainer (TypeBuilder.BaseType);
1116 member_cache = new MemberCache (this);
1123 public override bool Define (TypeContainer container)
1125 if (interface_order != null){
1126 foreach (Interface iface in interface_order)
1127 if ((iface.ModFlags & Modifiers.NEW) == 0)
1128 iface.Define (this);
1135 /// This function is based by a delegate to the FindMembers routine
1137 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1143 /// This filter is used by FindMembers, and we just keep
1144 /// a global for the filter to `AlwaysAccept'
1146 static MemberFilter accepting_filter;
1150 /// A member comparission method based on name only
1152 static IComparer mif_compare;
1154 static TypeContainer ()
1156 accepting_filter = new MemberFilter (AlwaysAccept);
1157 mif_compare = new MemberInfoCompare ();
1161 /// This method returns the members of this type just like Type.FindMembers would
1162 /// Only, we need to use this for types which are _being_ defined because MS'
1163 /// implementation can't take care of that.
1166 // FIXME: return an empty static array instead of null, that cleans up
1167 // some code and is consistent with some coding conventions I just found
1171 // Notice that in various cases we check if our field is non-null,
1172 // something that would normally mean that there was a bug elsewhere.
1174 // The problem happens while we are defining p-invoke methods, as those
1175 // will trigger a FindMembers, but this happens before things are defined
1177 // Since the whole process is a no-op, it is fine to check for null here.
1179 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1180 MemberFilter filter, object criteria)
1182 ArrayList members = new ArrayList ();
1185 if ((bf & BindingFlags.Public) != 0)
1186 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1188 if ((bf & BindingFlags.NonPublic) != 0)
1189 modflags |= Modifiers.PRIVATE;
1191 int static_mask = 0, static_flags = 0;
1192 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1193 case BindingFlags.Static:
1194 static_mask = static_flags = Modifiers.STATIC;
1197 case BindingFlags.Instance:
1198 static_mask = Modifiers.STATIC;
1203 static_mask = static_flags = 0;
1207 Timer.StartTimer (TimerType.TcFindMembers);
1210 filter = accepting_filter;
1212 if ((mt & MemberTypes.Field) != 0) {
1213 if (fields != null) {
1214 foreach (Field f in fields) {
1215 if ((f.ModFlags & modflags) == 0)
1217 if ((f.ModFlags & static_mask) != static_flags)
1220 FieldBuilder fb = f.FieldBuilder;
1221 if (fb != null && filter (fb, criteria) == true)
1226 if (constants != null) {
1227 foreach (Const con in constants) {
1228 if ((con.ModFlags & modflags) == 0)
1230 if ((con.ModFlags & static_mask) != static_flags)
1233 FieldBuilder fb = con.FieldBuilder;
1234 if (fb != null && filter (fb, criteria) == true)
1240 if ((mt & MemberTypes.Method) != 0) {
1241 if (methods != null) {
1242 foreach (Method m in methods) {
1243 if ((m.ModFlags & modflags) == 0)
1245 if ((m.ModFlags & static_mask) != static_flags)
1248 MethodBuilder mb = m.MethodBuilder;
1250 if (mb != null && filter (mb, criteria) == true)
1255 if (operators != null){
1256 foreach (Operator o in operators) {
1257 if ((o.ModFlags & modflags) == 0)
1259 if ((o.ModFlags & static_mask) != static_flags)
1262 MethodBuilder ob = o.OperatorMethodBuilder;
1263 if (ob != null && filter (ob, criteria) == true)
1268 if (properties != null){
1269 foreach (Property p in properties){
1270 if ((p.ModFlags & modflags) == 0)
1272 if ((p.ModFlags & static_mask) != static_flags)
1278 if (b != null && filter (b, criteria) == true)
1282 if (b != null && filter (b, criteria) == true)
1287 if (indexers != null){
1288 foreach (Indexer ix in indexers){
1289 if ((ix.ModFlags & modflags) == 0)
1291 if ((ix.ModFlags & static_mask) != static_flags)
1297 if (b != null && filter (b, criteria) == true)
1301 if (b != null && filter (b, criteria) == true)
1307 if ((mt & MemberTypes.Event) != 0) {
1309 foreach (Event e in events) {
1310 if ((e.ModFlags & modflags) == 0)
1312 if ((e.ModFlags & static_mask) != static_flags)
1315 MemberInfo eb = e.EventBuilder;
1316 if (eb != null && filter (eb, criteria) == true)
1317 members.Add (e.EventBuilder);
1321 if ((mt & MemberTypes.Property) != 0){
1322 if (properties != null)
1323 foreach (Property p in properties) {
1324 if ((p.ModFlags & modflags) == 0)
1326 if ((p.ModFlags & static_mask) != static_flags)
1329 MemberInfo pb = p.PropertyBuilder;
1330 if (pb != null && filter (pb, criteria) == true) {
1331 members.Add (p.PropertyBuilder);
1335 if (indexers != null)
1336 foreach (Indexer ix in indexers) {
1337 if ((ix.ModFlags & modflags) == 0)
1339 if ((ix.ModFlags & static_mask) != static_flags)
1342 MemberInfo ib = ix.PropertyBuilder;
1343 if (ib != null && filter (ib, criteria) == true) {
1344 members.Add (ix.PropertyBuilder);
1349 if ((mt & MemberTypes.NestedType) != 0) {
1351 foreach (TypeContainer t in types) {
1352 if ((t.ModFlags & modflags) == 0)
1355 TypeBuilder tb = t.TypeBuilder;
1356 if (tb != null && (filter (tb, criteria) == true))
1362 foreach (Enum en in enums){
1363 if ((en.ModFlags & modflags) == 0)
1366 TypeBuilder tb = en.TypeBuilder;
1367 if (tb != null && (filter (tb, criteria) == true))
1372 if (delegates != null){
1373 foreach (Delegate d in delegates){
1374 if ((d.ModFlags & modflags) == 0)
1377 TypeBuilder tb = d.TypeBuilder;
1378 if (tb != null && (filter (tb, criteria) == true))
1383 if (interfaces != null){
1384 foreach (Interface iface in interfaces){
1385 if ((iface.ModFlags & modflags) == 0)
1388 TypeBuilder tb = iface.TypeBuilder;
1389 if (tb != null && (filter (tb, criteria) == true))
1395 if ((mt & MemberTypes.Constructor) != 0){
1396 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1397 foreach (Constructor c in instance_constructors){
1398 ConstructorBuilder cb = c.ConstructorBuilder;
1400 if (filter (cb, criteria) == true)
1405 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1406 ConstructorBuilder cb =
1407 default_static_constructor.ConstructorBuilder;
1410 if (filter (cb, criteria) == true)
1416 // Lookup members in parent if requested.
1418 if (((bf & BindingFlags.DeclaredOnly) == 0) && (TypeBuilder.BaseType != null)) {
1419 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1420 members.AddRange (list);
1423 Timer.StopTimer (TimerType.TcFindMembers);
1425 return new MemberList (members);
1428 public override MemberCache MemberCache {
1430 return member_cache;
1434 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1435 MemberFilter filter, object criteria)
1437 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1440 return ds.FindMembers (mt, bf, filter, criteria);
1442 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1446 // FindMethods will look for methods not only in the type `t', but in
1447 // any interfaces implemented by the type.
1449 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1450 MemberFilter filter, object criteria)
1456 /// Emits the values for the constants
1458 public void EmitConstants ()
1460 if (constants != null)
1461 foreach (Const con in constants)
1462 con.EmitConstant (this);
1467 /// Emits the code, this step is performed after all
1468 /// the types, enumerations, constructors
1472 if (instance_constructors != null)
1473 foreach (Constructor c in instance_constructors)
1476 if (default_static_constructor != null)
1477 default_static_constructor.Emit (this);
1479 if (methods != null)
1480 foreach (Method m in methods)
1483 if (operators != null)
1484 foreach (Operator o in operators)
1487 if (properties != null)
1488 foreach (Property p in properties)
1491 if (indexers != null){
1492 foreach (Indexer ix in indexers)
1495 CustomAttributeBuilder cb = Interface.EmitDefaultMemberAttr (
1496 this, IndexerName, ModFlags, Location);
1497 TypeBuilder.SetCustomAttribute (cb);
1501 foreach (Field f in fields)
1504 if (events != null){
1505 foreach (Event e in Events)
1509 if (Pending != null)
1510 if (Pending.VerifyPendingMethods ())
1513 Attribute.ApplyAttributes (ec, TypeBuilder, this, OptAttributes);
1516 // Check for internal or private fields that were never assigned
1518 if (RootContext.WarningLevel >= 3) {
1519 if (fields != null){
1520 foreach (Field f in fields) {
1521 if ((f.ModFlags & Modifiers.PUBLIC) != 0)
1526 169, f.Location, "Private field " +
1527 MakeName (f.Name) + " is never used");
1532 // Only report 649 on level 4
1534 if (RootContext.WarningLevel < 4)
1537 if ((f.status & Field.Status.ASSIGNED) != 0)
1542 "Field " + MakeName (f.Name) + " is never assigned " +
1543 " to and will always have its default value");
1547 if (events != null){
1548 foreach (Event e in events){
1550 Report.Warning (67, "The event " + MakeName (e.Name) + " is never used");
1555 // if (types != null)
1556 // foreach (TypeContainer tc in types)
1560 public override void CloseType ()
1565 TypeBuilder.CreateType ();
1567 } catch (TypeLoadException){
1569 // This is fine, the code still created the type
1571 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1572 // Console.WriteLine (e.Message);
1574 Console.WriteLine ("In type: " + Name);
1579 foreach (Enum en in Enums)
1582 if (interface_order != null){
1583 foreach (Interface iface in interface_order)
1588 foreach (TypeContainer tc in Types)
1592 foreach (TypeContainer tc in Types)
1593 if (!(tc is Struct))
1597 if (Delegates != null)
1598 foreach (Delegate d in Delegates)
1602 public string MakeName (string n)
1604 return "`" + Name + "." + n + "'";
1607 public void Warning_KeywordNewRequired (Location l, MemberInfo mi)
1610 108, l, "The keyword new is required on " +
1611 MakeName (mi.Name) + " because it hides `" +
1612 mi.ReflectedType.Name + "." + mi.Name + "'");
1615 public void Warning_KewywordNewNotRequired (Location l, MemberCore mc)
1618 109, l, "The member " + MakeName (mc.Name) + " does not hide an " +
1619 "inherited member, the keyword new is not required");
1622 public void Error_EventCanOnlyOverrideEvent (Location l, MemberInfo mi)
1625 72, l, MakeName (mi.Name) + " : cannot override; `" +
1626 mi.ReflectedType.Name + "." + mi.Name + "' is not an event");
1629 public static int CheckMember (string name, MemberInfo mi, int ModFlags)
1635 // Performs the validation on a Method's modifiers (properties have
1636 // the same properties).
1638 public bool MethodModifiersValid (int flags, string n, Location loc)
1640 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1641 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1642 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1646 // At most one of static, virtual or override
1648 if ((flags & Modifiers.STATIC) != 0){
1649 if ((flags & vao) != 0){
1651 112, loc, "static method " + MakeName (n) + "can not be marked " +
1652 "as virtual, abstract or override");
1657 if (this is Struct){
1658 if ((flags & va) != 0){
1659 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
1664 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1666 113, loc, MakeName (n) +
1667 " marked as override cannot be marked as new or virtual");
1672 // If the declaration includes the abstract modifier, then the
1673 // declaration does not include static, virtual or extern
1675 if ((flags & Modifiers.ABSTRACT) != 0){
1676 if ((flags & Modifiers.EXTERN) != 0){
1678 180, loc, MakeName (n) + " can not be both abstract and extern");
1682 if ((flags & Modifiers.VIRTUAL) != 0){
1684 503, loc, MakeName (n) + " can not be both abstract and virtual");
1688 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1690 513, loc, MakeName (n) +
1691 " is abstract but its container class is not");
1697 if ((flags & Modifiers.PRIVATE) != 0){
1698 if ((flags & vao) != 0){
1700 621, loc, MakeName (n) +
1701 " virtual or abstract members can not be private");
1706 if ((flags & Modifiers.SEALED) != 0){
1707 if ((flags & Modifiers.OVERRIDE) == 0){
1709 238, loc, MakeName (n) +
1710 " cannot be sealed because it is not an override");
1718 // Access level of a type.
1721 ProtectedInternal = 1,
1727 // Check whether `flags' denotes a more restricted access than `level'
1728 // and return the new level.
1729 static AccessLevel CheckAccessLevel (AccessLevel level, int flags)
1731 AccessLevel old_level = level;
1733 if ((flags & Modifiers.INTERNAL) != 0) {
1734 if ((flags & Modifiers.PROTECTED) != 0) {
1735 if ((int) level < (int) AccessLevel.ProtectedInternal)
1736 level = AccessLevel.ProtectedInternal;
1738 if ((int) level < (int) AccessLevel.Internal)
1739 level = AccessLevel.Internal;
1741 } else if ((flags & Modifiers.PROTECTED) != 0) {
1742 if ((int) level < (int) AccessLevel.Protected)
1743 level = AccessLevel.Protected;
1744 } else if ((flags & Modifiers.PRIVATE) != 0)
1745 level = AccessLevel.Private;
1750 // Return the access level for a new member which is defined in the current
1751 // TypeContainer with access modifiers `flags'.
1752 AccessLevel GetAccessLevel (int flags)
1754 if ((flags & Modifiers.PRIVATE) != 0)
1755 return AccessLevel.Private;
1758 if (!IsTopLevel && (Parent != null))
1759 level = Parent.GetAccessLevel (flags);
1761 level = AccessLevel.Public;
1763 return CheckAccessLevel (CheckAccessLevel (level, flags), ModFlags);
1766 // Return the access level for type `t', but don't give more access than `flags'.
1767 static AccessLevel GetAccessLevel (Type t, int flags)
1769 if (((flags & Modifiers.PRIVATE) != 0) || t.IsNestedPrivate)
1770 return AccessLevel.Private;
1773 if (TypeManager.IsBuiltinType (t))
1774 return AccessLevel.Public;
1775 else if ((t.DeclaringType != null) && (t != t.DeclaringType))
1776 level = GetAccessLevel (t.DeclaringType, flags);
1778 level = CheckAccessLevel (AccessLevel.Public, flags);
1781 if (t.IsNestedPublic)
1784 if (t.IsNestedAssembly || t.IsNotPublic) {
1785 if ((int) level < (int) AccessLevel.Internal)
1786 level = AccessLevel.Internal;
1789 if (t.IsNestedFamily) {
1790 if ((int) level < (int) AccessLevel.Protected)
1791 level = AccessLevel.Protected;
1794 if (t.IsNestedFamORAssem) {
1795 if ((int) level < (int) AccessLevel.ProtectedInternal)
1796 level = AccessLevel.ProtectedInternal;
1803 // Returns true if `parent' is as accessible as the flags `flags'
1804 // given for this member.
1806 public bool AsAccessible (Type parent, int flags)
1808 while (parent.IsArray || parent.IsPointer || parent.IsByRef)
1809 parent = TypeManager.GetElementType (parent);
1811 AccessLevel level = GetAccessLevel (flags);
1812 AccessLevel level2 = GetAccessLevel (parent, flags);
1814 return (int) level >= (int) level2;
1817 Hashtable builder_and_args;
1819 public bool RegisterMethod (MethodBuilder mb, InternalParameters ip, Type [] args)
1821 if (builder_and_args == null)
1822 builder_and_args = new Hashtable ();
1827 /// Performs checks for an explicit interface implementation. First it
1828 /// checks whether the `interface_type' is a base inteface implementation.
1829 /// Then it checks whether `name' exists in the interface type.
1831 public bool VerifyImplements (Type interface_type, string full, string name, Location loc)
1835 if (ifaces != null){
1836 foreach (Type t in ifaces){
1837 if (t == interface_type){
1845 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
1852 public static void Error_ExplicitInterfaceNotMemberInterface (Location loc, string name)
1854 Report.Error (539, loc, "Explicit implementation: `" + name + "' is not a member of the interface");
1861 string IMemberContainer.Name {
1867 Type IMemberContainer.Type {
1873 IMemberContainer IMemberContainer.Parent {
1875 return parent_container;
1879 MemberCache IMemberContainer.MemberCache {
1881 return member_cache;
1885 bool IMemberContainer.IsInterface {
1891 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
1893 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
1897 // Operator pair checking
1900 class OperatorEntry {
1902 public Type ret_type;
1903 public Type type1, type2;
1905 public Operator.OpType ot;
1907 public OperatorEntry (int f, Operator o)
1911 ret_type = o.OperatorMethod.GetReturnType ();
1912 Type [] pt = o.OperatorMethod.ParameterTypes;
1916 ot = o.OperatorType;
1919 public override int GetHashCode ()
1921 return ret_type.GetHashCode ();
1924 public override bool Equals (object o)
1926 OperatorEntry other = (OperatorEntry) o;
1928 if (other.ret_type != ret_type)
1930 if (other.type1 != type1)
1932 if (other.type2 != type2)
1939 // Checks that some operators come in pairs:
1945 // They are matched based on the return type and the argument types
1947 void CheckPairedOperators ()
1949 Hashtable pairs = new Hashtable (null, null);
1950 Operator true_op = null;
1951 Operator false_op = null;
1952 bool has_equality_or_inequality = false;
1954 // Register all the operators we care about.
1955 foreach (Operator op in operators){
1958 switch (op.OperatorType){
1959 case Operator.OpType.Equality:
1961 has_equality_or_inequality = true;
1963 case Operator.OpType.Inequality:
1965 has_equality_or_inequality = true;
1968 case Operator.OpType.True:
1971 case Operator.OpType.False:
1975 case Operator.OpType.GreaterThan:
1977 case Operator.OpType.LessThan:
1980 case Operator.OpType.GreaterThanOrEqual:
1982 case Operator.OpType.LessThanOrEqual:
1988 OperatorEntry oe = new OperatorEntry (reg, op);
1990 object o = pairs [oe];
1994 oe = (OperatorEntry) o;
1999 if (true_op != null){
2000 if (false_op == null)
2001 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
2002 } else if (false_op != null)
2003 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
2006 // Look for the mistakes.
2008 foreach (DictionaryEntry de in pairs){
2009 OperatorEntry oe = (OperatorEntry) de.Key;
2016 case Operator.OpType.Equality:
2019 case Operator.OpType.Inequality:
2022 case Operator.OpType.GreaterThan:
2025 case Operator.OpType.LessThan:
2028 case Operator.OpType.GreaterThanOrEqual:
2031 case Operator.OpType.LessThanOrEqual:
2035 Report.Error (216, oe.op.Location,
2036 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
2039 if ((has_equality_or_inequality) && (RootContext.WarningLevel >= 2)) {
2040 MethodSignature equals_ms = new MethodSignature (
2041 "Equals", TypeManager.bool_type, new Type [] { TypeManager.object_type });
2042 MethodSignature hash_ms = new MethodSignature (
2043 "GetHashCode", TypeManager.int32_type, new Type [0]);
2045 MemberList equals_ml = FindMembers (MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance |
2046 BindingFlags.DeclaredOnly, MethodSignature.method_signature_filter,
2048 MemberList hash_ml = FindMembers (MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance |
2049 BindingFlags.DeclaredOnly, MethodSignature.method_signature_filter,
2052 bool equals_ok = false;
2053 if ((equals_ml != null) && (equals_ml.Count == 1))
2054 equals_ok = equals_ml [0].DeclaringType == TypeBuilder;
2055 bool hash_ok = false;
2056 if ((hash_ml != null) && (hash_ml.Count == 1))
2057 hash_ok = hash_ml [0].DeclaringType == TypeBuilder;
2060 Report.Warning (660, Location, "`" + Name + "' defines operator == or operator != but does " +
2061 "not override Object.Equals (object o)");
2063 Report.Warning (661, Location, "`" + Name + "' defines operator == or operator != but does " +
2064 "not override Object.GetHashCode ()");
2071 public class Class : TypeContainer {
2073 // Modifiers allowed in a class declaration
2075 public const int AllowedModifiers =
2078 Modifiers.PROTECTED |
2079 Modifiers.INTERNAL |
2081 Modifiers.ABSTRACT |
2085 public Class (TypeContainer parent, string name, int mod, Attributes attrs, Location l)
2086 : base (parent, name, l)
2090 if (parent.Parent == null)
2091 accmods = Modifiers.INTERNAL;
2093 accmods = Modifiers.PRIVATE;
2095 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2096 this.attributes = attrs;
2100 // FIXME: How do we deal with the user specifying a different
2103 public override TypeAttributes TypeAttr {
2105 return base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2110 public class Struct : TypeContainer {
2112 // Modifiers allowed in a struct declaration
2114 public const int AllowedModifiers =
2117 Modifiers.PROTECTED |
2118 Modifiers.INTERNAL |
2122 public Struct (TypeContainer parent, string name, int mod, Attributes attrs, Location l)
2123 : base (parent, name, l)
2127 if (parent.Parent == null)
2128 accmods = Modifiers.INTERNAL;
2130 accmods = Modifiers.PRIVATE;
2132 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2134 this.ModFlags |= Modifiers.SEALED;
2135 this.attributes = attrs;
2140 // FIXME: Allow the user to specify a different set of attributes
2141 // in some cases (Sealed for example is mandatory for a class,
2142 // but what SequentialLayout can be changed
2144 public override TypeAttributes TypeAttr {
2146 return base.TypeAttr |
2147 TypeAttributes.SequentialLayout |
2148 TypeAttributes.Sealed |
2149 TypeAttributes.BeforeFieldInit;
2154 public abstract class MethodCore : MemberBase {
2155 public readonly Parameters Parameters;
2156 protected Block block;
2159 // Parameters, cached for semantic analysis.
2161 protected InternalParameters parameter_info;
2162 protected Type [] parameter_types;
2164 public MethodCore (Expression type, int mod, int allowed_mod, string name,
2165 Attributes attrs, Parameters parameters, Location loc)
2166 : base (type, mod, allowed_mod, name, attrs, loc)
2168 Parameters = parameters;
2172 // Returns the System.Type array for the parameters of this method
2174 public Type [] ParameterTypes {
2176 return parameter_types;
2180 public InternalParameters ParameterInfo
2183 return parameter_info;
2187 public Block Block {
2197 protected virtual bool DoDefineParameters (TypeContainer container)
2199 // Check if arguments were correct
2200 parameter_types = Parameters.GetParameterInfo (container);
2201 if ((parameter_types == null) || !CheckParameters (container, parameter_types))
2204 parameter_info = new InternalParameters (container, Parameters);
2206 Parameter array_param = Parameters.ArrayParameter;
2207 if ((array_param != null) &&
2208 (!array_param.ParameterType.IsArray ||
2209 (array_param.ParameterType.GetArrayRank () != 1))) {
2210 Report.Error (225, Location, "params parameter has to be a single dimensional array");
2217 public CallingConventions GetCallingConvention (bool is_class)
2219 CallingConventions cc = 0;
2221 cc = Parameters.GetCallingConvention ();
2224 if ((ModFlags & Modifiers.STATIC) == 0)
2225 cc |= CallingConventions.HasThis;
2227 // FIXME: How is `ExplicitThis' used in C#?
2233 // The method's attributes are passed in because we need to extract
2234 // the "return:" attribute from there to apply on the return type
2236 public void LabelParameters (EmitContext ec, MethodBase builder, Attributes method_attrs)
2239 // Define each type attribute (in/out/ref) and
2240 // the argument names.
2242 Parameter [] p = Parameters.FixedParameters;
2245 MethodBuilder mb = null;
2246 ConstructorBuilder cb = null;
2248 if (builder is MethodBuilder)
2249 mb = (MethodBuilder) builder;
2251 cb = (ConstructorBuilder) builder;
2254 for (i = 0; i < p.Length; i++) {
2255 ParameterBuilder pb;
2256 ParameterAttributes par_attr = p [i].Attributes;
2259 pb = cb.DefineParameter (
2260 i + 1, par_attr, p [i].Name);
2262 pb = mb.DefineParameter (
2263 i + 1, par_attr, p [i].Name);
2265 Attributes attr = p [i].OptAttributes;
2267 Attribute.ApplyAttributes (ec, pb, pb, attr);
2269 if (par_attr == ParameterAttributes.Out){
2270 if (attr.Contains (TypeManager.in_attribute_type))
2271 Report.Error (36, Location, "Can not use [In] attribute on out parameter");
2277 if (Parameters.ArrayParameter != null){
2278 ParameterBuilder pb;
2279 Parameter array_param = Parameters.ArrayParameter;
2282 pb = cb.DefineParameter (
2283 i + 1, array_param.Attributes,
2286 pb = mb.DefineParameter (
2287 i + 1, array_param.Attributes,
2290 CustomAttributeBuilder a = new CustomAttributeBuilder (
2291 TypeManager.cons_param_array_attribute, new object [0]);
2293 pb.SetCustomAttribute (a);
2297 // And now for the return type attribute decoration
2299 ParameterBuilder ret_pb;
2300 Attributes ret_attrs = null;
2302 if (mb == null || method_attrs == null)
2305 foreach (AttributeSection asec in method_attrs.AttributeSections) {
2307 if (asec.Target != "return")
2310 if (ret_attrs == null)
2311 ret_attrs = new Attributes (asec);
2313 ret_attrs.AddAttributeSection (asec);
2316 if (ret_attrs != null) {
2318 ret_pb = mb.DefineParameter (0, ParameterAttributes.None, "");
2319 Attribute.ApplyAttributes (ec, ret_pb, ret_pb, ret_attrs);
2320 } catch (ArgumentOutOfRangeException) {
2323 ".NET SDK 1.0 does not permit to set custom attributes to the return type of a method");
2329 public class Method : MethodCore, IIteratorContainer {
2330 public MethodBuilder MethodBuilder;
2331 public MethodData MethodData;
2334 /// Modifiers allowed in a class declaration
2336 const int AllowedModifiers =
2339 Modifiers.PROTECTED |
2340 Modifiers.INTERNAL |
2345 Modifiers.OVERRIDE |
2346 Modifiers.ABSTRACT |
2351 // return_type can be "null" for VOID values.
2353 public Method (Expression return_type, int mod, string name, Parameters parameters,
2354 Attributes attrs, Location l)
2355 : base (return_type, mod, AllowedModifiers, name, attrs, parameters, l)
2359 // Returns the `System.Type' for the ReturnType of this
2360 // function. Provides a nice cache. (used between semantic analysis
2361 // and actual code generation
2363 public Type GetReturnType ()
2368 // Whether this is an operator method.
2369 public bool IsOperator;
2371 void DuplicateEntryPoint (MethodInfo b, Location location)
2375 "Program `" + CodeGen.FileName +
2376 "' has more than one entry point defined: `" +
2377 TypeManager.CSharpSignature(b) + "'");
2380 void Report28 (MethodInfo b)
2384 "`" + TypeManager.CSharpSignature(b) +
2385 "' has the wrong signature to be an entry point");
2388 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
2390 if (b.ReturnType != TypeManager.void_type &&
2391 b.ReturnType != TypeManager.int32_type)
2394 if (pinfo.Count == 0)
2397 if (pinfo.Count > 1)
2400 Type t = pinfo.ParameterType(0);
2402 (t.GetArrayRank() == 1) &&
2403 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
2404 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
2411 // Checks our base implementation if any
2413 protected override bool CheckBase (TypeContainer container)
2415 base.CheckBase (container);
2417 // Check whether arguments were correct.
2418 if (!DoDefineParameters (container))
2421 MethodSignature ms = new MethodSignature (Name, null, ParameterTypes);
2423 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2427 mi_this = TypeContainer.FindMembers (
2428 container.TypeBuilder, MemberTypes.Method,
2429 BindingFlags.NonPublic | BindingFlags.Public |
2430 BindingFlags.Static | BindingFlags.Instance |
2431 BindingFlags.DeclaredOnly,
2432 MethodSignature.method_signature_filter, ms);
2434 if (mi_this.Count > 0) {
2435 Report.Error (111, Location, "Class `" + container.Name + "' " +
2436 "already defines a member called `" + Name + "' " +
2437 "with the same parameter types");
2443 // Verify if the parent has a type with the same name, and then
2444 // check whether we have to create a new slot for it or not.
2446 Type ptype = container.TypeBuilder.BaseType;
2448 // ptype is only null for System.Object while compiling corlib.
2450 MemberList mi, mi_static, mi_instance;
2452 mi_instance = TypeContainer.FindMembers (
2453 ptype, MemberTypes.Method,
2454 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
2455 MethodSignature.inheritable_method_signature_filter,
2458 if (mi_instance.Count > 0){
2461 mi_static = TypeContainer.FindMembers (
2462 ptype, MemberTypes.Method,
2463 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static,
2464 MethodSignature.inheritable_method_signature_filter, ms);
2466 if (mi_static.Count > 0)
2472 if (mi != null && mi.Count > 0){
2473 parent_method = (MethodInfo) mi [0];
2474 string name = parent_method.DeclaringType.Name + "." +
2477 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
2480 if ((ModFlags & Modifiers.NEW) == 0) {
2481 Type parent_ret = TypeManager.TypeToCoreType (
2482 parent_method.ReturnType);
2484 if (parent_ret != MemberType) {
2486 508, Location, container.MakeName (Name) + ": cannot " +
2487 "change return type when overriding " +
2488 "inherited member " + name);
2493 if ((ModFlags & Modifiers.NEW) != 0)
2494 WarningNotHiding (container);
2496 if ((ModFlags & Modifiers.OVERRIDE) != 0){
2497 Report.Error (115, Location,
2498 container.MakeName (Name) +
2499 " no suitable methods found to override");
2502 } else if ((ModFlags & Modifiers.NEW) != 0)
2503 WarningNotHiding (container);
2511 public override bool Define (TypeContainer container)
2513 if (!DoDefine (container))
2516 if (!CheckBase (container))
2519 CallingConventions cc = GetCallingConvention (container is Class);
2521 MethodData = new MethodData (this, null, MemberType, ParameterTypes,
2522 ParameterInfo, cc, OptAttributes,
2523 ModFlags, flags, true);
2525 if (!MethodData.Define (container))
2529 // Setup iterator if we are one
2531 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
2532 IteratorHandler ih = new IteratorHandler (
2533 Name, container, MemberType,
2534 ParameterTypes, ParameterInfo,
2535 ModFlags, Location);
2537 Block new_block = ih.Setup (block);
2538 if (new_block == null)
2543 MethodBuilder = MethodData.MethodBuilder;
2546 // This is used to track the Entry Point,
2548 if (Name == "Main" &&
2549 ((ModFlags & Modifiers.STATIC) != 0) &&
2550 (RootContext.MainClass == null ||
2551 RootContext.MainClass == container.TypeBuilder.FullName)){
2552 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
2553 if (RootContext.EntryPoint == null) {
2554 RootContext.EntryPoint = MethodBuilder;
2555 RootContext.EntryPointLocation = Location;
2557 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
2558 DuplicateEntryPoint (MethodBuilder, Location);
2561 Report28(MethodBuilder);
2570 public void Emit (TypeContainer container)
2572 MethodData.Emit (container, Block, this);
2576 void IIteratorContainer.SetYields ()
2578 ModFlags |= Modifiers.METHOD_YIELDS;
2582 public abstract class ConstructorInitializer {
2583 ArrayList argument_list;
2584 ConstructorInfo parent_constructor;
2585 Parameters parameters;
2588 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
2591 this.argument_list = argument_list;
2592 this.parameters = parameters;
2596 public ArrayList Arguments {
2598 return argument_list;
2602 public bool Resolve (EmitContext ec)
2604 Expression parent_constructor_group;
2607 ec.CurrentBlock = new Block (null, Block.Flags.Implicit, parameters);
2609 if (argument_list != null){
2610 foreach (Argument a in argument_list){
2611 if (!a.Resolve (ec, loc))
2615 ec.CurrentBlock = null;
2617 if (this is ConstructorBaseInitializer) {
2618 if (ec.ContainerType.BaseType == null)
2621 t = ec.ContainerType.BaseType;
2622 if (ec.ContainerType.IsValueType) {
2623 Report.Error (522, loc,
2624 "structs cannot call base class constructors");
2628 t = ec.ContainerType;
2630 parent_constructor_group = Expression.MemberLookup (
2631 ec, t, null, t, ".ctor",
2632 MemberTypes.Constructor,
2633 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
2636 if (parent_constructor_group == null){
2637 Report.Error (1501, loc,
2638 "Can not find a constructor for this argument list");
2642 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (ec,
2643 (MethodGroupExpr) parent_constructor_group, argument_list, loc);
2645 if (parent_constructor == null){
2646 Report.Error (1501, loc,
2647 "Can not find a constructor for this argument list");
2654 public void Emit (EmitContext ec)
2656 if (parent_constructor != null){
2657 ec.Mark (loc, false);
2659 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
2661 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
2666 public class ConstructorBaseInitializer : ConstructorInitializer {
2667 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
2668 base (argument_list, pars, l)
2673 public class ConstructorThisInitializer : ConstructorInitializer {
2674 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
2675 base (argument_list, pars, l)
2680 public class Constructor : MethodCore {
2681 public ConstructorBuilder ConstructorBuilder;
2682 public ConstructorInitializer Initializer;
2683 new public Attributes OptAttributes;
2686 // Modifiers allowed for a constructor.
2688 public const int AllowedModifiers =
2690 Modifiers.PROTECTED |
2691 Modifiers.INTERNAL |
2698 // The spec claims that static is not permitted, but
2699 // my very own code has static constructors.
2701 public Constructor (string name, Parameters args, ConstructorInitializer init, Location l)
2702 : base (null, 0, AllowedModifiers, name, null, args, l)
2708 // Returns true if this is a default constructor
2710 public bool IsDefault ()
2712 if ((ModFlags & Modifiers.STATIC) != 0)
2713 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
2714 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
2717 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
2718 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
2719 (Initializer is ConstructorBaseInitializer) &&
2720 (Initializer.Arguments == null);
2724 // Creates the ConstructorBuilder
2726 public override bool Define (TypeContainer container)
2728 MethodAttributes ca = (MethodAttributes.RTSpecialName |
2729 MethodAttributes.SpecialName);
2731 // Check if arguments were correct.
2732 if (!DoDefineParameters (container))
2735 if ((ModFlags & Modifiers.STATIC) != 0){
2736 ca |= MethodAttributes.Static | MethodAttributes.Private;
2738 if (container is Struct && ParameterTypes.Length == 0){
2741 "Structs can not contain explicit parameterless " +
2745 ca |= MethodAttributes.HideBySig;
2747 if ((ModFlags & Modifiers.PUBLIC) != 0)
2748 ca |= MethodAttributes.Public;
2749 else if ((ModFlags & Modifiers.PROTECTED) != 0){
2750 if ((ModFlags & Modifiers.INTERNAL) != 0)
2751 ca |= MethodAttributes.FamORAssem;
2753 ca |= MethodAttributes.Family;
2754 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
2755 ca |= MethodAttributes.Assembly;
2756 else if (IsDefault ())
2757 ca |= MethodAttributes.Public;
2759 ca |= MethodAttributes.Private;
2762 ConstructorBuilder = container.TypeBuilder.DefineConstructor (
2763 ca, GetCallingConvention (container is Class), ParameterTypes);
2765 if ((ModFlags & Modifiers.UNSAFE) != 0)
2766 ConstructorBuilder.InitLocals = false;
2769 // HACK because System.Reflection.Emit is lame
2771 if (!TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes)) {
2774 "Class `" +container.Name+ "' already contains a definition with the " +
2775 "same return value and parameter types for constructor `" + Name
2786 public void Emit (TypeContainer container)
2788 ILGenerator ig = ConstructorBuilder.GetILGenerator ();
2789 EmitContext ec = new EmitContext (container, Location, ig, null, ModFlags, true);
2792 // extern methods have no bodies
2794 if ((ModFlags & Modifiers.EXTERN) != 0) {
2795 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
2797 179, Location, "External constructor `" +
2798 TypeManager.CSharpSignature (ConstructorBuilder) +
2799 "' can not have a body");
2802 } else if (block == null) {
2804 501, Location, "Constructor `" +
2805 TypeManager.CSharpSignature (ConstructorBuilder) +
2806 "' must declare a body since it is not marked extern");
2810 if ((ModFlags & Modifiers.STATIC) == 0){
2811 if (container is Class && Initializer == null)
2812 Initializer = new ConstructorBaseInitializer (
2813 null, Parameters.EmptyReadOnlyParameters, Location);
2817 // Spec mandates that Initializers will not have
2821 if (Initializer != null && !Initializer.Resolve (ec))
2823 ec.IsStatic = false;
2826 LabelParameters (ec, ConstructorBuilder, OptAttributes);
2828 SymbolWriter sw = CodeGen.SymbolWriter;
2829 bool generate_debugging = false;
2831 if ((sw != null) && (block != null) &&
2832 !Location.IsNull (Location) &&
2833 !Location.IsNull (block.EndLocation)) {
2835 sw.OpenMethod (container, ConstructorBuilder, Location, block.EndLocation);
2837 generate_debugging = true;
2841 // Classes can have base initializers and instance field initializers.
2843 if (container is Class){
2844 if ((ModFlags & Modifiers.STATIC) == 0){
2847 // If we use a "this (...)" constructor initializer, then
2848 // do not emit field initializers, they are initialized in the other constructor
2850 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
2851 container.EmitFieldInitializers (ec);
2854 if (Initializer != null)
2855 Initializer.Emit (ec);
2857 if ((ModFlags & Modifiers.STATIC) != 0)
2858 container.EmitFieldInitializers (ec);
2860 Attribute.ApplyAttributes (ec, ConstructorBuilder, this, OptAttributes);
2862 // If this is a non-static `struct' constructor and doesn't have any
2863 // initializer, it must initialize all of the struct's fields.
2864 if ((container is Struct) && ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
2865 Block.AddThisVariable (container, Location);
2867 ec.EmitTopBlock (block, ParameterInfo, Location);
2869 if (generate_debugging)
2877 // Encapsulates most of the Method's state
2879 public class MethodData {
2881 // The return type of this method
2883 public readonly Type ReturnType;
2884 public readonly Type[] ParameterTypes;
2885 public readonly InternalParameters ParameterInfo;
2886 public readonly CallingConventions CallingConventions;
2887 public readonly Attributes OptAttributes;
2888 public readonly Location Location;
2891 // Are we implementing an interface ?
2893 public bool IsImplementing = false;
2898 protected MemberBase member;
2899 protected int modifiers;
2900 protected MethodAttributes flags;
2901 protected bool is_method;
2902 protected string accessor_name;
2905 // It can either hold a string with the condition, or an arraylist of conditions.
2906 object conditionals;
2908 MethodBuilder builder = null;
2909 public MethodBuilder MethodBuilder {
2915 public MethodData (MemberBase member, string name, Type return_type,
2916 Type [] parameter_types, InternalParameters parameters,
2917 CallingConventions cc, Attributes opt_attrs,
2918 int modifiers, MethodAttributes flags, bool is_method)
2920 this.member = member;
2921 this.accessor_name = name;
2922 this.ReturnType = return_type;
2923 this.ParameterTypes = parameter_types;
2924 this.ParameterInfo = parameters;
2925 this.CallingConventions = cc;
2926 this.OptAttributes = opt_attrs;
2927 this.modifiers = modifiers;
2929 this.is_method = is_method;
2930 this.Location = member.Location;
2931 this.conditionals = null;
2937 Attribute dllimport_attribute = null;
2938 string obsolete = null;
2939 bool obsolete_error = false;
2941 public virtual bool ApplyAttributes (Attributes opt_attrs, bool is_method)
2943 if ((opt_attrs == null) || (opt_attrs.AttributeSections == null))
2946 foreach (AttributeSection asec in opt_attrs.AttributeSections) {
2947 if (asec.Attributes == null)
2950 foreach (Attribute a in asec.Attributes) {
2951 if (a.Name == "Conditional") {
2952 if (!ApplyConditionalAttribute (a))
2954 } else if (a.Name == "Obsolete") {
2955 if (!ApplyObsoleteAttribute (a))
2957 } else if (a.Name.IndexOf ("DllImport") != -1) {
2959 a.Type = TypeManager.dllimport_type;
2960 Attribute.Error_AttributeNotValidForElement (a, Location);
2963 if (!ApplyDllImportAttribute (a))
2973 // Applies the `DllImport' attribute to the method.
2975 protected virtual bool ApplyDllImportAttribute (Attribute a)
2977 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
2978 if ((modifiers & extern_static) != extern_static) {
2979 Report.Error (601, Location,
2980 "The DllImport attribute must be specified on a method " +
2981 "marked `static' and `extern'.");
2985 flags |= MethodAttributes.PinvokeImpl;
2986 dllimport_attribute = a;
2991 // Applies the `Obsolete' attribute to the method.
2993 protected virtual bool ApplyObsoleteAttribute (Attribute a)
2995 if (obsolete != null) {
2996 Report.Error (579, Location, "Duplicate `Obsolete' attribute");
3000 obsolete = a.Obsolete_GetObsoleteMessage (out obsolete_error);
3001 return obsolete != null;
3005 // Applies the `Conditional' attribute to the method.
3007 protected virtual bool ApplyConditionalAttribute (Attribute a)
3009 // The Conditional attribute is only valid on methods.
3011 Attribute.Error_AttributeNotValidForElement (a, Location);
3015 string condition = a.Conditional_GetConditionName ();
3017 if (condition == null)
3020 if (ReturnType != TypeManager.void_type) {
3021 Report.Error (578, Location,
3022 "Conditional not valid on `" + member.Name + "' " +
3023 "because its return type is not void");
3027 if ((modifiers & Modifiers.OVERRIDE) != 0) {
3028 Report.Error (243, Location,
3029 "Conditional not valid on `" + member.Name + "' " +
3030 "because it is an override method");
3034 if (member.IsExplicitImpl) {
3035 Report.Error (577, Location,
3036 "Conditional not valid on `" + member.Name + "' " +
3037 "because it is an explicit interface implementation");
3041 if (IsImplementing) {
3042 Report.Error (623, Location,
3043 "Conditional not valid on `" + member.Name + "' " +
3044 "because it is an interface method");
3049 // The likelyhood that the conditional will be more than 1 is very slim
3051 if (conditionals == null)
3052 conditionals = condition;
3053 else if (conditionals is string){
3054 string s = (string) conditionals;
3055 conditionals = new ArrayList ();
3056 ((ArrayList)conditionals).Add (s);
3058 ((ArrayList)conditionals).Add (condition);
3064 // Checks whether this method should be ignored due to its Conditional attributes.
3066 bool ShouldIgnore (Location loc)
3068 // When we're overriding a virtual method, we implicitly inherit the
3069 // Conditional attributes from our parent.
3070 if (member.ParentMethod != null) {
3071 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (
3072 member.ParentMethod, loc);
3074 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
3078 if (conditionals != null){
3079 if (conditionals is string){
3080 if (RootContext.AllDefines [conditionals] == null)
3083 foreach (string condition in (ArrayList) conditionals)
3084 if (RootContext.AllDefines [condition] == null)
3092 // Returns the TypeManager.MethodFlags for this method.
3093 // This emits an error 619 / warning 618 if the method is obsolete.
3094 // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
3096 public virtual TypeManager.MethodFlags GetMethodFlags (Location loc)
3098 TypeManager.MethodFlags flags = 0;
3100 if (obsolete != null) {
3101 if (obsolete_error) {
3102 Report.Error (619, loc, "Method `" + member.Name +
3103 "' is obsolete: `" + obsolete + "'");
3104 return TypeManager.MethodFlags.IsObsoleteError;
3106 Report.Warning (618, loc, "Method `" + member.Name +
3107 "' is obsolete: `" + obsolete + "'");
3109 flags |= TypeManager.MethodFlags.IsObsolete;
3112 if (ShouldIgnore (loc))
3113 flags |= TypeManager.MethodFlags.ShouldIgnore;
3118 public virtual bool Define (TypeContainer container)
3120 MethodInfo implementing = null;
3121 string method_name, name, prefix;
3123 if (OptAttributes != null)
3124 if (!ApplyAttributes (OptAttributes, is_method))
3127 if (member.IsExplicitImpl)
3128 prefix = member.InterfaceType.FullName + ".";
3132 if (accessor_name != null)
3133 name = accessor_name + "_" + member.ShortName;
3135 name = member.ShortName;
3136 method_name = prefix + name;
3138 if (container.Pending != null){
3139 if (member is Indexer)
3140 implementing = container.Pending.IsInterfaceIndexer (
3141 member.InterfaceType, ReturnType, ParameterTypes);
3143 implementing = container.Pending.IsInterfaceMethod (
3144 member.InterfaceType, name, ReturnType, ParameterTypes);
3146 if (member.InterfaceType != null && implementing == null){
3147 TypeContainer.Error_ExplicitInterfaceNotMemberInterface (
3154 // For implicit implementations, make sure we are public, for
3155 // explicit implementations, make sure we are private.
3157 if (implementing != null){
3159 // Setting null inside this block will trigger a more
3160 // verbose error reporting for missing interface implementations
3162 // The "candidate" function has been flagged already
3163 // but it wont get cleared
3165 if (member.IsExplicitImpl){
3166 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
3167 Modifiers.Error_InvalidModifier (Location, "public, virtual or abstract");
3168 implementing = null;
3172 // If this is an interface method implementation,
3173 // check for public accessibility
3175 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
3176 if (TypeManager.IsInterfaceType (implementing.DeclaringType))
3177 implementing = null;
3182 // Static is not allowed
3184 if ((modifiers & Modifiers.STATIC) != 0){
3185 implementing = null;
3186 Modifiers.Error_InvalidModifier (Location, "static");
3191 // If implementing is still valid, set flags
3193 if (implementing != null){
3195 // When implementing interface methods, set NewSlot
3196 // unless, we are overwriting a method.
3198 if (implementing.DeclaringType.IsInterface){
3199 if ((modifiers & Modifiers.OVERRIDE) == 0)
3200 flags |= MethodAttributes.NewSlot;
3203 MethodAttributes.Virtual |
3204 MethodAttributes.HideBySig;
3206 // Set Final unless we're virtual, abstract or already overriding a method.
3207 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
3208 flags |= MethodAttributes.Final;
3210 // Get the method name from the explicit interface.
3211 if (member.InterfaceType != null) {
3212 name = implementing.Name;
3213 method_name = prefix + name;
3216 IsImplementing = true;
3220 // Create the MethodBuilder for the method
3222 if ((flags & MethodAttributes.PinvokeImpl) != 0) {
3223 if ((modifiers & Modifiers.STATIC) == 0) {
3224 Report.Error (601, Location,
3225 "The DllImport attribute must be specified on " +
3226 "a method marked 'static' and 'extern'.");
3230 EmitContext ec = new EmitContext (
3231 container, Location, null, ReturnType, modifiers);
3233 builder = dllimport_attribute.DefinePInvokeMethod (
3234 ec, container.TypeBuilder, method_name, flags,
3235 ReturnType, ParameterTypes);
3237 builder = container.TypeBuilder.DefineMethod (
3238 method_name, flags, CallingConventions,
3239 ReturnType, ParameterTypes);
3241 if (builder == null)
3244 if ((modifiers & Modifiers.UNSAFE) != 0)
3245 builder.InitLocals = false;
3247 if (IsImplementing){
3249 // clear the pending implemntation flag
3251 if (member is Indexer) {
3252 container.Pending.ImplementIndexer (
3253 member.InterfaceType, builder, ReturnType,
3254 ParameterTypes, true);
3256 container.Pending.ImplementMethod (
3257 member.InterfaceType, name, ReturnType,
3258 ParameterTypes, member.IsExplicitImpl);
3260 if (member.IsExplicitImpl)
3261 container.TypeBuilder.DefineMethodOverride (
3262 builder, implementing);
3266 if (!TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes)) {
3267 Report.Error (111, Location,
3268 "Class `" + container.Name +
3269 "' already contains a definition with the " +
3270 "same return value and parameter types as the " +
3271 "'get' method of property `" + member.Name + "'");
3275 TypeManager.AddMethod (builder, this);
3283 public virtual void Emit (TypeContainer container, Block block, object kind)
3288 if ((flags & MethodAttributes.PinvokeImpl) == 0)
3289 ig = builder.GetILGenerator ();
3293 ec = new EmitContext (container, Location, ig, ReturnType, modifiers);
3295 if (OptAttributes != null)
3296 Attribute.ApplyAttributes (ec, builder, kind, OptAttributes);
3298 if (member is MethodCore)
3299 ((MethodCore) member).LabelParameters (ec, MethodBuilder, OptAttributes);
3302 // abstract or extern methods have no bodies
3304 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
3305 if (block == null) {
3306 SymbolWriter sw = CodeGen.SymbolWriter;
3308 if ((sw != null) && ((modifiers & Modifiers.EXTERN) != 0)) {
3309 sw.OpenMethod (container, MethodBuilder, Location, Location);
3317 // abstract or extern methods have no bodies.
3319 if ((modifiers & Modifiers.ABSTRACT) != 0)
3321 500, Location, "Abstract method `" +
3322 TypeManager.CSharpSignature (builder) +
3323 "' can not have a body");
3325 if ((modifiers & Modifiers.EXTERN) != 0)
3327 179, Location, "External method `" +
3328 TypeManager.CSharpSignature (builder) +
3329 "' can not have a body");
3335 // Methods must have a body unless they're extern or abstract
3337 if (block == null) {
3339 501, Location, "Method `" +
3340 TypeManager.CSharpSignature (builder) +
3341 "' must declare a body since it is not marked " +
3342 "abstract or extern");
3347 // Handle destructors specially
3349 // FIXME: This code generates buggy code
3351 if (member.Name == "Finalize" && ReturnType == TypeManager.void_type)
3352 EmitDestructor (ec, block);
3354 SymbolWriter sw = CodeGen.SymbolWriter;
3356 if ((sw != null) && !Location.IsNull (Location) &&
3357 !Location.IsNull (block.EndLocation)) {
3358 sw.OpenMethod (container, MethodBuilder, Location, block.EndLocation);
3360 ec.EmitTopBlock (block, ParameterInfo, Location);
3364 ec.EmitTopBlock (block, ParameterInfo, Location);
3368 void EmitDestructor (EmitContext ec, Block block)
3370 ILGenerator ig = ec.ig;
3372 Label finish = ig.DefineLabel ();
3373 bool old_in_try = ec.InTry;
3375 ig.BeginExceptionBlock ();
3377 ec.ReturnLabel = finish;
3378 ec.HasReturnLabel = true;
3379 ec.EmitTopBlock (block, null, Location);
3380 ec.InTry = old_in_try;
3382 // ig.MarkLabel (finish);
3383 bool old_in_finally = ec.InFinally;
3384 ec.InFinally = true;
3385 ig.BeginFinallyBlock ();
3387 if (ec.ContainerType.BaseType != null) {
3388 Expression member_lookup = Expression.MemberLookup (
3389 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
3390 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, Location);
3392 if (member_lookup != null){
3393 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
3395 ig.Emit (OpCodes.Ldarg_0);
3396 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
3399 ec.InFinally = old_in_finally;
3401 ig.EndExceptionBlock ();
3402 //ig.MarkLabel (ec.ReturnLabel);
3403 ig.Emit (OpCodes.Ret);
3407 abstract public class MemberBase : MemberCore {
3408 public Expression Type;
3409 public readonly Attributes OptAttributes;
3411 protected MethodAttributes flags;
3414 // The "short" name of this property / indexer / event. This is the
3415 // name without the explicit interface.
3417 public string ShortName;
3420 // The type of this property / indexer / event
3422 public Type MemberType;
3425 // If true, this is an explicit interface implementation
3427 public bool IsExplicitImpl = false;
3430 // The name of the interface we are explicitly implementing
3432 public string ExplicitInterfaceName = null;
3435 // If true, the interface type we are explicitly implementing
3437 public Type InterfaceType = null;
3440 // The method we're overriding if this is an override method.
3442 protected MethodInfo parent_method = null;
3443 public MethodInfo ParentMethod {
3445 return parent_method;
3450 // The constructor is only exposed to our children
3452 protected MemberBase (Expression type, int mod, int allowed_mod, string name,
3453 Attributes attrs, Location loc)
3457 ModFlags = Modifiers.Check (allowed_mod, mod, Modifiers.PRIVATE, loc);
3458 OptAttributes = attrs;
3461 protected virtual bool CheckBase (TypeContainer container)
3463 if ((container is Struct) || (RootContext.WarningLevel > 3)){
3464 if ((ModFlags & Modifiers.PROTECTED) != 0 && (container.ModFlags & Modifiers.SEALED) != 0){
3465 if (container is Struct){
3466 Report.Error (666, Location, "Protected member in struct declaration");
3469 Report.Warning (628, Location, "Member " + container.MakeName (Name) + " protected in sealed class");
3475 protected virtual bool CheckParameters (TypeContainer container, Type [] parameters)
3479 foreach (Type partype in parameters){
3480 if (partype.IsPointer){
3481 if (!UnsafeOK (container))
3483 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3487 if (container.AsAccessible (partype, ModFlags))
3490 if (this is Indexer)
3491 Report.Error (55, Location,
3492 "Inconsistent accessibility: parameter type `" +
3493 TypeManager.CSharpName (partype) + "' is less " +
3494 "accessible than indexer `" + Name + "'");
3495 else if ((this is Method) && ((Method) this).IsOperator)
3496 Report.Error (57, Location,
3497 "Inconsistent accessibility: parameter type `" +
3498 TypeManager.CSharpName (partype) + "' is less " +
3499 "accessible than operator `" + Name + "'");
3501 Report.Error (51, Location,
3502 "Inconsistent accessibility: parameter type `" +
3503 TypeManager.CSharpName (partype) + "' is less " +
3504 "accessible than method `" + Name + "'");
3511 protected virtual bool DoDefine (TypeContainer container)
3516 if (!container.MethodModifiersValid (ModFlags, Name, Location))
3519 flags = Modifiers.MethodAttr (ModFlags);
3521 // Lookup Type, verify validity
3522 MemberType = container.ResolveType (Type, false, Location);
3523 if (MemberType == null)
3526 if ((container.ModFlags & Modifiers.SEALED) != 0){
3527 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
3528 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
3533 // verify accessibility
3534 if (!container.AsAccessible (MemberType, ModFlags)) {
3535 if (this is Property)
3536 Report.Error (53, Location,
3537 "Inconsistent accessibility: property type `" +
3538 TypeManager.CSharpName (MemberType) + "' is less " +
3539 "accessible than property `" + Name + "'");
3540 else if (this is Indexer)
3541 Report.Error (54, Location,
3542 "Inconsistent accessibility: indexer return type `" +
3543 TypeManager.CSharpName (MemberType) + "' is less " +
3544 "accessible than indexer `" + Name + "'");
3545 else if (this is Method) {
3546 if (((Method) this).IsOperator)
3547 Report.Error (56, Location,
3548 "Inconsistent accessibility: return type `" +
3549 TypeManager.CSharpName (MemberType) + "' is less " +
3550 "accessible than operator `" + Name + "'");
3552 Report.Error (50, Location,
3553 "Inconsistent accessibility: return type `" +
3554 TypeManager.CSharpName (MemberType) + "' is less " +
3555 "accessible than method `" + Name + "'");
3557 Report.Error (52, Location,
3558 "Inconsistent accessibility: field type `" +
3559 TypeManager.CSharpName (MemberType) + "' is less " +
3560 "accessible than field `" + Name + "'");
3564 if (MemberType.IsPointer && !UnsafeOK (container))
3568 // Check for explicit interface implementation
3570 if ((ExplicitInterfaceName == null) && (Name.IndexOf (".") != -1)){
3571 int pos = Name.LastIndexOf (".");
3573 ExplicitInterfaceName = Name.Substring (0, pos);
3574 ShortName = Name.Substring (pos + 1);
3578 if (ExplicitInterfaceName != null) {
3579 InterfaceType = RootContext.LookupType (
3580 container, ExplicitInterfaceName, false, Location);
3581 if (InterfaceType == null)
3584 // Compute the full name that we need to export.
3585 Name = InterfaceType.FullName + "." + ShortName;
3587 if (!container.VerifyImplements (InterfaceType, ShortName, Name, Location))
3590 IsExplicitImpl = true;
3592 IsExplicitImpl = false;
3599 // Fields and Events both generate FieldBuilders, we use this to share
3600 // their common bits. This is also used to flag usage of the field
3602 abstract public class FieldBase : MemberBase {
3603 public FieldBuilder FieldBuilder;
3604 public Status status;
3607 public enum Status : byte { ASSIGNED = 1, USED = 2 }
3610 // The constructor is only exposed to our children
3612 protected FieldBase (Expression type, int mod, int allowed_mod, string name,
3613 object init, Attributes attrs, Location loc)
3614 : base (type, mod, allowed_mod, name, attrs, loc)
3620 // Whether this field has an initializer.
3622 public bool HasInitializer {
3624 return init != null;
3628 protected readonly Object init;
3630 Expression init_expr;
3631 bool init_expr_initialized = false;
3634 // Resolves and returns the field initializer.
3636 public Expression GetInitializerExpression (EmitContext ec)
3638 if (init_expr_initialized)
3642 if (init is Expression)
3643 e = (Expression) init;
3645 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
3647 ec.IsFieldInitializer = true;
3648 e = e.DoResolve (ec);
3649 ec.IsFieldInitializer = false;
3652 init_expr_initialized = true;
3659 // The Field class is used to represents class/struct fields during parsing.
3661 public class Field : FieldBase {
3663 // Modifiers allowed in a class declaration
3665 const int AllowedModifiers =
3668 Modifiers.PROTECTED |
3669 Modifiers.INTERNAL |
3672 Modifiers.VOLATILE |
3676 public Field (Expression type, int mod, string name, Object expr_or_array_init,
3677 Attributes attrs, Location loc)
3678 : base (type, mod, AllowedModifiers, name, expr_or_array_init, attrs, loc)
3682 public override bool Define (TypeContainer container)
3684 Type t = container.ResolveType (Type, false, Location);
3689 CheckBase (container);
3691 if (!container.AsAccessible (t, ModFlags)) {
3692 Report.Error (52, Location,
3693 "Inconsistent accessibility: field type `" +
3694 TypeManager.CSharpName (t) + "' is less " +
3695 "accessible than field `" + Name + "'");
3699 if (t.IsPointer && !UnsafeOK (container))
3702 if (RootContext.WarningLevel > 1){
3703 Type ptype = container.TypeBuilder.BaseType;
3705 // ptype is only null for System.Object while compiling corlib.
3707 TypeContainer.FindMembers (
3708 ptype, MemberTypes.Method,
3709 BindingFlags.Public |
3710 BindingFlags.Static | BindingFlags.Instance,
3711 System.Type.FilterName, Name);
3715 if ((ModFlags & Modifiers.VOLATILE) != 0){
3719 if (TypeManager.IsEnumType (vt))
3720 vt = TypeManager.EnumToUnderlying (t);
3722 if (!((vt == TypeManager.bool_type) ||
3723 (vt == TypeManager.sbyte_type) ||
3724 (vt == TypeManager.byte_type) ||
3725 (vt == TypeManager.short_type) ||
3726 (vt == TypeManager.ushort_type) ||
3727 (vt == TypeManager.int32_type) ||
3728 (vt == TypeManager.uint32_type) ||
3729 (vt == TypeManager.char_type) ||
3730 (vt == TypeManager.float_type))){
3732 677, Location, container.MakeName (Name) +
3733 " A volatile field can not be of type `" +
3734 TypeManager.CSharpName (vt) + "'");
3739 if ((ModFlags & Modifiers.READONLY) != 0){
3742 "A field can not be both volatile and readonly");
3747 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
3749 if (container is Struct &&
3750 ((fa & FieldAttributes.Static) == 0) &&
3751 t == container.TypeBuilder &&
3752 !TypeManager.IsBuiltinType (t)){
3753 Report.Error (523, Location, "Struct member `" + container.Name + "." + Name +
3754 "' causes a cycle in the structure layout");
3758 FieldBuilder = container.TypeBuilder.DefineField (
3759 Name, t, Modifiers.FieldAttr (ModFlags));
3761 TypeManager.RegisterFieldBase (FieldBuilder, this);
3765 public void Emit (TypeContainer tc)
3767 EmitContext ec = new EmitContext (tc, Location, null,
3768 FieldBuilder.FieldType, ModFlags);
3770 Attribute.ApplyAttributes (ec, FieldBuilder, this, OptAttributes);
3775 // `set' and `get' accessors are represented with an Accessor.
3777 public class Accessor {
3779 // Null if the accessor is empty, or a Block if not
3782 public Attributes OptAttributes;
3784 public Accessor (Block b, Attributes attrs)
3787 OptAttributes = attrs;
3792 // Properties and Indexers both generate PropertyBuilders, we use this to share
3793 // their common bits.
3795 abstract public class PropertyBase : MethodCore {
3796 public Accessor Get, Set;
3797 public PropertyBuilder PropertyBuilder;
3798 public MethodBuilder GetBuilder, SetBuilder;
3799 public MethodData GetData, SetData;
3801 protected EmitContext ec;
3803 public PropertyBase (Expression type, string name, int mod_flags, int allowed_mod,
3804 Parameters parameters, Accessor get_block, Accessor set_block,
3805 Attributes attrs, Location loc)
3806 : base (type, mod_flags, allowed_mod, name, attrs, parameters, loc)
3812 protected override bool DoDefine (TypeContainer container)
3814 if (!base.DoDefine (container))
3817 ec = new EmitContext (container, Location, null, MemberType, ModFlags);
3823 // Checks our base implementation if any
3825 protected override bool CheckBase (TypeContainer container)
3827 base.CheckBase (container);
3829 // Check whether arguments were correct.
3830 if (!DoDefineParameters (container))
3837 MethodSignature ms, base_ms;
3838 if (this is Indexer) {
3839 string name, base_name;
3841 report_name = "this";
3842 name = TypeManager.IndexerPropertyName (container.TypeBuilder);
3843 ms = new MethodSignature (name, null, ParameterTypes);
3844 base_name = TypeManager.IndexerPropertyName (container.TypeBuilder.BaseType);
3845 base_ms = new MethodSignature (base_name, null, ParameterTypes);
3848 ms = base_ms = new MethodSignature (Name, null, ParameterTypes);
3852 // Verify if the parent has a type with the same name, and then
3853 // check whether we have to create a new slot for it or not.
3855 Type ptype = container.TypeBuilder.BaseType;
3857 // ptype is only null for System.Object while compiling corlib.
3858 if (ptype == null) {
3859 if ((ModFlags & Modifiers.NEW) != 0)
3860 WarningNotHiding (container);
3865 MemberList props_this;
3867 props_this = TypeContainer.FindMembers (
3868 container.TypeBuilder, MemberTypes.Property,
3869 BindingFlags.NonPublic | BindingFlags.Public |
3870 BindingFlags.Static | BindingFlags.Instance |
3871 BindingFlags.DeclaredOnly,
3872 MethodSignature.method_signature_filter, ms);
3874 if (props_this.Count > 0) {
3875 Report.Error (111, Location, "Class `" + container.Name + "' " +
3876 "already defines a member called `" + report_name + "' " +
3877 "with the same parameter types");
3881 MemberList mi_props;
3883 mi_props = TypeContainer.FindMembers (
3884 ptype, MemberTypes.Property,
3885 BindingFlags.NonPublic | BindingFlags.Public |
3886 BindingFlags.Instance | BindingFlags.Static,
3887 MethodSignature.inheritable_method_signature_filter, base_ms);
3889 if (mi_props.Count > 0){
3890 PropertyInfo parent_property = (PropertyInfo) mi_props [0];
3891 string name = parent_property.DeclaringType.Name + "." +
3892 parent_property.Name;
3894 MethodInfo get, set, parent_method;
3895 get = parent_property.GetGetMethod (true);
3896 set = parent_property.GetSetMethod (true);
3899 parent_method = get;
3900 else if (set != null)
3901 parent_method = set;
3903 throw new Exception ("Internal error!");
3905 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
3908 if ((ModFlags & Modifiers.NEW) == 0) {
3909 Type parent_type = TypeManager.TypeToCoreType (
3910 parent_property.PropertyType);
3912 if (parent_type != MemberType) {
3914 508, Location, container.MakeName (Name) + ": cannot " +
3915 "change return type when overriding " +
3916 "inherited member " + name);
3921 if ((ModFlags & Modifiers.NEW) != 0)
3922 WarningNotHiding (container);
3924 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3925 if (this is Indexer)
3926 Report.Error (115, Location,
3927 container.MakeName (Name) +
3928 " no suitable indexers found to override");
3930 Report.Error (115, Location,
3931 container.MakeName (Name) +
3932 " no suitable properties found to override");
3939 public void Emit (TypeContainer tc)
3942 // The PropertyBuilder can be null for explicit implementations, in that
3943 // case, we do not actually emit the ".property", so there is nowhere to
3944 // put the attribute
3946 if (PropertyBuilder != null)
3947 Attribute.ApplyAttributes (ec, PropertyBuilder, this, OptAttributes);
3949 if (GetData != null) {
3950 GetData.Emit (tc, Get.Block, Get);
3954 if (SetData != null) {
3955 SetData.Emit (tc, Set.Block, Set);
3961 public class Property : PropertyBase {
3962 const int AllowedModifiers =
3965 Modifiers.PROTECTED |
3966 Modifiers.INTERNAL |
3970 Modifiers.OVERRIDE |
3971 Modifiers.ABSTRACT |
3976 public Property (Expression type, string name, int mod_flags,
3977 Accessor get_block, Accessor set_block,
3978 Attributes attrs, Location loc)
3979 : base (type, name, mod_flags, AllowedModifiers,
3980 Parameters.EmptyReadOnlyParameters,
3981 get_block, set_block, attrs, loc)
3985 public override bool Define (TypeContainer container)
3987 if (!DoDefine (container))
3990 if (!CheckBase (container))
3993 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
3996 Type [] parameters = TypeManager.NoTypes;
3998 InternalParameters ip = new InternalParameters (
3999 container, Parameters.EmptyReadOnlyParameters);
4001 GetData = new MethodData (this, "get", MemberType,
4002 parameters, ip, CallingConventions.Standard,
4003 Get.OptAttributes, ModFlags, flags, false);
4005 if (!GetData.Define (container))
4008 GetBuilder = GetData.MethodBuilder;
4012 Type [] parameters = new Type [1];
4013 parameters [0] = MemberType;
4015 Parameter [] parms = new Parameter [1];
4016 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
4017 InternalParameters ip = new InternalParameters (
4018 container, new Parameters (parms, null, Location));
4020 SetData = new MethodData (this, "set", TypeManager.void_type,
4021 parameters, ip, CallingConventions.Standard,
4022 Set.OptAttributes, ModFlags, flags, false);
4024 if (!SetData.Define (container))
4027 SetBuilder = SetData.MethodBuilder;
4028 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4031 // FIXME - PropertyAttributes.HasDefault ?
4033 PropertyAttributes prop_attr =
4034 PropertyAttributes.RTSpecialName |
4035 PropertyAttributes.SpecialName;
4037 if (!IsExplicitImpl){
4038 PropertyBuilder = container.TypeBuilder.DefineProperty (
4039 Name, prop_attr, MemberType, null);
4042 PropertyBuilder.SetGetMethod (GetBuilder);
4045 PropertyBuilder.SetSetMethod (SetBuilder);
4048 // HACK for the reasons exposed above
4050 if (!TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder)) {
4053 "Class `" + container.Name +
4054 "' already contains a definition for the property `" +
4064 /// Gigantic workaround for lameness in SRE follows :
4065 /// This class derives from EventInfo and attempts to basically
4066 /// wrap around the EventBuilder so that FindMembers can quickly
4067 /// return this in it search for members
4069 public class MyEventBuilder : EventInfo {
4072 // We use this to "point" to our Builder which is
4073 // not really a MemberInfo
4075 EventBuilder MyBuilder;
4078 // We "catch" and wrap these methods
4080 MethodInfo raise, remove, add;
4082 EventAttributes attributes;
4083 Type declaring_type, reflected_type, event_type;
4088 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
4090 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
4092 // And now store the values in our own fields.
4094 declaring_type = type_builder;
4096 reflected_type = type_builder;
4098 attributes = event_attr;
4101 this.event_type = event_type;
4105 // Methods that you have to override. Note that you only need
4106 // to "implement" the variants that take the argument (those are
4107 // the "abstract" methods, the others (GetAddMethod()) are
4110 public override MethodInfo GetAddMethod (bool nonPublic)
4115 public override MethodInfo GetRemoveMethod (bool nonPublic)
4120 public override MethodInfo GetRaiseMethod (bool nonPublic)
4126 // These methods make "MyEventInfo" look like a Builder
4128 public void SetRaiseMethod (MethodBuilder raiseMethod)
4130 raise = raiseMethod;
4131 MyBuilder.SetRaiseMethod (raiseMethod);
4134 public void SetRemoveOnMethod (MethodBuilder removeMethod)
4136 remove = removeMethod;
4137 MyBuilder.SetRemoveOnMethod (removeMethod);
4140 public void SetAddOnMethod (MethodBuilder addMethod)
4143 MyBuilder.SetAddOnMethod (addMethod);
4146 public void SetCustomAttribute (CustomAttributeBuilder cb)
4148 MyBuilder.SetCustomAttribute (cb);
4151 public override object [] GetCustomAttributes (bool inherit)
4153 // FIXME : There's nothing which can be seemingly done here because
4154 // we have no way of getting at the custom attribute objects of the
4159 public override object [] GetCustomAttributes (Type t, bool inherit)
4161 // FIXME : Same here !
4165 public override bool IsDefined (Type t, bool b)
4170 public override EventAttributes Attributes {
4176 public override string Name {
4182 public override Type DeclaringType {
4184 return declaring_type;
4188 public override Type ReflectedType {
4190 return reflected_type;
4194 public Type EventType {
4200 public void SetUsed ()
4202 if (my_event != null)
4203 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
4207 public class Event : FieldBase {
4208 const int AllowedModifiers =
4211 Modifiers.PROTECTED |
4212 Modifiers.INTERNAL |
4217 Modifiers.OVERRIDE |
4221 public readonly Accessor Add;
4222 public readonly Accessor Remove;
4223 public MyEventBuilder EventBuilder;
4225 MethodBuilder AddBuilder, RemoveBuilder;
4226 MethodData AddData, RemoveData;
4228 public Event (Expression type, string name, Object init, int mod, Accessor add,
4229 Accessor remove, Attributes attrs, Location loc)
4230 : base (type, mod, AllowedModifiers, name, init, attrs, loc)
4236 public override bool Define (TypeContainer container)
4238 EventAttributes e_attr = EventAttributes.RTSpecialName | EventAttributes.SpecialName;
4239 MethodAttributes m_attr = MethodAttributes.HideBySig | MethodAttributes.SpecialName
4241 if (!DoDefine (container))
4244 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
4245 Report.Error (74, Location, "'" + container.Name + "." + Name +
4246 "': abstract event can not have an initializer");
4250 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
4251 Report.Error (66, Location, "'" + container.Name + "." + Name +
4252 "' : event must be of a delegate type");
4256 Type [] parameter_types = new Type [1];
4257 parameter_types [0] = MemberType;
4259 Parameter [] parms = new Parameter [1];
4260 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
4261 InternalParameters ip = new InternalParameters (
4262 container, new Parameters (parms, null, Location));
4264 if (!CheckBase (container))
4268 // Now define the accessors
4270 AddData = new MethodData (this, "add", TypeManager.void_type,
4271 parameter_types, ip, CallingConventions.Standard,
4272 (Add != null) ? Add.OptAttributes : null,
4273 ModFlags, flags | m_attr, false);
4275 if (!AddData.Define (container))
4278 AddBuilder = AddData.MethodBuilder;
4279 AddBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4281 RemoveData = new MethodData (this, "remove", TypeManager.void_type,
4282 parameter_types, ip, CallingConventions.Standard,
4283 (Remove != null) ? Remove.OptAttributes : null,
4284 ModFlags, flags | m_attr, false);
4286 if (!RemoveData.Define (container))
4289 RemoveBuilder = RemoveData.MethodBuilder;
4290 RemoveBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4292 if (!IsExplicitImpl){
4293 EventBuilder = new MyEventBuilder (this,
4294 container.TypeBuilder, Name, e_attr, MemberType);
4296 if (Add == null && Remove == null) {
4297 FieldBuilder = container.TypeBuilder.DefineField (
4299 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
4300 TypeManager.RegisterPrivateFieldOfEvent (
4301 (EventInfo) EventBuilder, FieldBuilder);
4302 TypeManager.RegisterFieldBase (FieldBuilder, this);
4305 EventBuilder.SetAddOnMethod (AddBuilder);
4306 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
4308 if (!TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder)) {
4309 Report.Error (111, Location,
4310 "Class `" + container.Name +
4311 "' already contains a definition for the event `" +
4320 void EmitDefaultMethod (EmitContext ec, bool is_add)
4322 ILGenerator ig = ec.ig;
4323 MethodInfo method = null;
4326 method = TypeManager.delegate_combine_delegate_delegate;
4328 method = TypeManager.delegate_remove_delegate_delegate;
4330 if ((ModFlags & Modifiers.STATIC) != 0) {
4331 ig.Emit (OpCodes.Ldsfld, (FieldInfo) FieldBuilder);
4332 ig.Emit (OpCodes.Ldarg_0);
4333 ig.Emit (OpCodes.Call, method);
4334 ig.Emit (OpCodes.Castclass, MemberType);
4335 ig.Emit (OpCodes.Stsfld, (FieldInfo) FieldBuilder);
4337 ig.Emit (OpCodes.Ldarg_0);
4338 ig.Emit (OpCodes.Ldarg_0);
4339 ig.Emit (OpCodes.Ldfld, (FieldInfo) FieldBuilder);
4340 ig.Emit (OpCodes.Ldarg_1);
4341 ig.Emit (OpCodes.Call, method);
4342 ig.Emit (OpCodes.Castclass, MemberType);
4343 ig.Emit (OpCodes.Stfld, (FieldInfo) FieldBuilder);
4345 ig.Emit (OpCodes.Ret);
4348 public void Emit (TypeContainer tc)
4352 ec = new EmitContext (tc, Location, null, MemberType, ModFlags);
4353 Attribute.ApplyAttributes (ec, EventBuilder, this, OptAttributes);
4356 AddData.Emit (tc, Add.Block, Add);
4359 ILGenerator ig = AddData.MethodBuilder.GetILGenerator ();
4360 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
4361 EmitDefaultMethod (ec, true);
4364 if (Remove != null) {
4365 RemoveData.Emit (tc, Remove.Block, Remove);
4366 Remove.Block = null;
4368 ILGenerator ig = RemoveData.MethodBuilder.GetILGenerator ();
4369 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
4370 EmitDefaultMethod (ec, false);
4377 // FIXME: This does not handle:
4379 // int INTERFACENAME [ args ]
4384 // int this [ args ]
4386 public class Indexer : PropertyBase {
4388 const int AllowedModifiers =
4391 Modifiers.PROTECTED |
4392 Modifiers.INTERNAL |
4396 Modifiers.OVERRIDE |
4401 public string IndexerName;
4402 public string InterfaceIndexerName;
4405 // Are we implementing an interface ?
4407 bool IsImplementing = false;
4409 public Indexer (Expression type, string int_type, int flags, Parameters parameters,
4410 Accessor get_block, Accessor set_block, Attributes attrs, Location loc)
4411 : base (type, "", flags, AllowedModifiers, parameters, get_block, set_block,
4414 ExplicitInterfaceName = int_type;
4417 public override bool Define (TypeContainer container)
4419 PropertyAttributes prop_attr =
4420 PropertyAttributes.RTSpecialName |
4421 PropertyAttributes.SpecialName;
4423 if (!DoDefine (container))
4426 IndexerName = Attribute.ScanForIndexerName (ec, OptAttributes);
4427 if (IndexerName == null)
4428 IndexerName = "Item";
4429 else if (IsExplicitImpl)
4430 Report.Error (592, Location,
4431 "Attribute 'IndexerName' is not valid on this declaration " +
4432 "type. It is valid on `property' declarations only.");
4434 ShortName = IndexerName;
4435 if (IsExplicitImpl) {
4436 InterfaceIndexerName = TypeManager.IndexerPropertyName (InterfaceType);
4437 Name = InterfaceType.FullName + "." + IndexerName;
4439 InterfaceIndexerName = IndexerName;
4443 if (!CheckBase (container))
4446 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
4448 InternalParameters ip = new InternalParameters (container, Parameters);
4450 GetData = new MethodData (this, "get", MemberType,
4451 ParameterTypes, ip, CallingConventions.Standard,
4452 Get.OptAttributes, ModFlags, flags, false);
4454 if (!GetData.Define (container))
4457 GetBuilder = GetData.MethodBuilder;
4461 int top = ParameterTypes.Length;
4462 Type [] set_pars = new Type [top + 1];
4463 ParameterTypes.CopyTo (set_pars, 0);
4464 set_pars [top] = MemberType;
4466 Parameter [] fixed_parms = Parameters.FixedParameters;
4468 if (fixed_parms == null){
4469 throw new Exception ("We currently do not support only array arguments in an indexer at: " + Location);
4470 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4471 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4473 // Here is the problem: the `value' parameter has
4474 // to come *after* the array parameter in the declaration
4476 // X (object [] x, Type value)
4479 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4480 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4484 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
4487 fixed_parms.CopyTo (tmp, 0);
4488 tmp [fixed_parms.Length] = new Parameter (
4489 Type, "value", Parameter.Modifier.NONE, null);
4491 Parameters set_formal_params = new Parameters (tmp, null, Location);
4493 InternalParameters ip = new InternalParameters (container, set_formal_params);
4495 SetData = new MethodData (this, "set", TypeManager.void_type,
4496 set_pars, ip, CallingConventions.Standard,
4497 Set.OptAttributes, ModFlags, flags, false);
4499 if (!SetData.Define (container))
4502 SetBuilder = SetData.MethodBuilder;
4506 // Now name the parameters
4508 Parameter [] p = Parameters.FixedParameters;
4512 for (i = 0; i < p.Length; ++i) {
4514 GetBuilder.DefineParameter (
4515 i + 1, p [i].Attributes, p [i].Name);
4518 SetBuilder.DefineParameter (
4519 i + 1, p [i].Attributes, p [i].Name);
4523 SetBuilder.DefineParameter (
4524 i + 1, ParameterAttributes.None, "value");
4526 if (i != ParameterTypes.Length) {
4527 Parameter array_param = Parameters.ArrayParameter;
4529 SetBuilder.DefineParameter (
4530 i + 1, array_param.Attributes, array_param.Name);
4534 if (GetData != null)
4535 IsImplementing = GetData.IsImplementing;
4536 else if (SetData != null)
4537 IsImplementing = SetData.IsImplementing;
4540 // Define the PropertyBuilder if one of the following conditions are met:
4541 // a) we're not implementing an interface indexer.
4542 // b) the indexer has a different IndexerName and this is no
4543 // explicit interface implementation.
4545 if (!IsExplicitImpl) {
4546 PropertyBuilder = container.TypeBuilder.DefineProperty (
4547 IndexerName, prop_attr, MemberType, ParameterTypes);
4549 if (GetData != null)
4550 PropertyBuilder.SetGetMethod (GetBuilder);
4552 if (SetData != null)
4553 PropertyBuilder.SetSetMethod (SetBuilder);
4555 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder,
4563 public class Operator : MemberCore {
4565 const int AllowedModifiers =
4571 const int RequiredModifiers =
4575 public enum OpType : byte {
4585 // Unary and Binary operators
4608 // Implicit and Explicit
4613 public readonly OpType OperatorType;
4614 public readonly Expression ReturnType;
4615 public readonly Expression FirstArgType, SecondArgType;
4616 public readonly string FirstArgName, SecondArgName;
4618 public Attributes OptAttributes;
4619 public MethodBuilder OperatorMethodBuilder;
4621 public string MethodName;
4622 public Method OperatorMethod;
4624 public Operator (OpType type, Expression ret_type, int flags,
4625 Expression arg1type, string arg1name,
4626 Expression arg2type, string arg2name,
4627 Block block, Attributes attrs, Location loc)
4630 OperatorType = type;
4631 ReturnType = ret_type;
4632 ModFlags = Modifiers.Check (AllowedModifiers, flags, Modifiers.PUBLIC, loc);
4633 FirstArgType = arg1type;
4634 FirstArgName = arg1name;
4635 SecondArgType = arg2type;
4636 SecondArgName = arg2name;
4638 OptAttributes = attrs;
4641 string Prototype (TypeContainer container)
4643 return container.Name + ".operator " + OperatorType + " (" + FirstArgType + "," +
4644 SecondArgType + ")";
4647 public override bool Define (TypeContainer container)
4650 MethodName = "op_" + OperatorType;
4652 if (SecondArgType != null)
4655 Parameter [] param_list = new Parameter [length];
4657 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
4660 "User defined operators `" +
4661 Prototype (container) +
4662 "' must be declared static and public");
4666 param_list[0] = new Parameter (FirstArgType, FirstArgName,
4667 Parameter.Modifier.NONE, null);
4668 if (SecondArgType != null)
4669 param_list[1] = new Parameter (SecondArgType, SecondArgName,
4670 Parameter.Modifier.NONE, null);
4672 OperatorMethod = new Method (ReturnType, ModFlags, MethodName,
4673 new Parameters (param_list, null, Location),
4674 OptAttributes, Location);
4676 OperatorMethod.IsOperator = true;
4677 OperatorMethod.Define (container);
4679 if (OperatorMethod.MethodBuilder == null)
4682 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
4684 Type [] param_types = OperatorMethod.ParameterTypes;
4685 Type declaring_type = OperatorMethodBuilder.DeclaringType;
4686 Type return_type = OperatorMethod.GetReturnType ();
4687 Type first_arg_type = param_types [0];
4689 // Rules for conversion operators
4691 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
4692 if (first_arg_type == return_type && first_arg_type == declaring_type){
4695 "User-defined conversion cannot take an object of the " +
4696 "enclosing type and convert to an object of the enclosing" +
4701 if (first_arg_type != declaring_type && return_type != declaring_type){
4704 "User-defined conversion must convert to or from the " +
4709 if (first_arg_type == TypeManager.object_type ||
4710 return_type == TypeManager.object_type){
4713 "User-defined conversion cannot convert to or from " +
4718 if (first_arg_type.IsInterface || return_type.IsInterface){
4721 "User-defined conversion cannot convert to or from an " +
4726 if (first_arg_type.IsSubclassOf (return_type) ||
4727 return_type.IsSubclassOf (first_arg_type)){
4730 "User-defined conversion cannot convert between types " +
4731 "that derive from each other");
4734 } else if (SecondArgType == null) {
4735 // Checks for Unary operators
4737 if (first_arg_type != declaring_type){
4740 "The parameter of a unary operator must be the " +
4745 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
4746 if (return_type != declaring_type){
4749 "The parameter and return type for ++ and -- " +
4750 "must be the containing type");
4756 if (OperatorType == OpType.True || OperatorType == OpType.False) {
4757 if (return_type != TypeManager.bool_type){
4760 "The return type of operator True or False " +
4767 // Checks for Binary operators
4769 if (first_arg_type != declaring_type &&
4770 param_types [1] != declaring_type){
4773 "One of the parameters of a binary operator must " +
4774 "be the containing type");
4782 public void Emit (TypeContainer container)
4785 // abstract or extern methods have no bodies
4787 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
4790 OperatorMethod.Block = Block;
4791 OperatorMethod.Emit (container);
4795 public static string GetName (OpType ot)
4798 case OpType.LogicalNot:
4800 case OpType.OnesComplement:
4802 case OpType.Increment:
4804 case OpType.Decrement:
4810 case OpType.Addition:
4812 case OpType.Subtraction:
4814 case OpType.UnaryPlus:
4816 case OpType.UnaryNegation:
4818 case OpType.Multiply:
4820 case OpType.Division:
4822 case OpType.Modulus:
4824 case OpType.BitwiseAnd:
4826 case OpType.BitwiseOr:
4828 case OpType.ExclusiveOr:
4830 case OpType.LeftShift:
4832 case OpType.RightShift:
4834 case OpType.Equality:
4836 case OpType.Inequality:
4838 case OpType.GreaterThan:
4840 case OpType.LessThan:
4842 case OpType.GreaterThanOrEqual:
4844 case OpType.LessThanOrEqual:
4846 case OpType.Implicit:
4848 case OpType.Explicit:
4854 public override string ToString ()
4856 Type return_type = OperatorMethod.GetReturnType();
4857 Type [] param_types = OperatorMethod.ParameterTypes;
4859 if (SecondArgType == null)
4860 return String.Format (
4861 "{0} operator {1}({2})",
4862 TypeManager.CSharpName (return_type),
4863 GetName (OperatorType),
4866 return String.Format (
4867 "{0} operator {1}({2}, {3})",
4868 TypeManager.CSharpName (return_type),
4869 GetName (OperatorType),
4870 param_types [0], param_types [1]);
4875 // This is used to compare method signatures
4877 struct MethodSignature {
4879 public Type RetType;
4880 public Type [] Parameters;
4883 /// This delegate is used to extract methods which have the
4884 /// same signature as the argument
4886 public static MemberFilter method_signature_filter;
4889 /// This delegate is used to extract inheritable methods which
4890 /// have the same signature as the argument. By inheritable,
4891 /// this means that we have permissions to override the method
4892 /// from the current assembly and class
4894 public static MemberFilter inheritable_method_signature_filter;
4896 static MethodSignature ()
4898 method_signature_filter = new MemberFilter (MemberSignatureCompare);
4899 inheritable_method_signature_filter = new MemberFilter (
4900 InheritableMemberSignatureCompare);
4903 public MethodSignature (string name, Type ret_type, Type [] parameters)
4908 if (parameters == null)
4909 Parameters = TypeManager.NoTypes;
4911 Parameters = parameters;
4914 public override string ToString ()
4917 if (Parameters.Length != 0){
4918 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
4919 for (int i = 0; i < Parameters.Length; i++){
4920 sb.Append (Parameters [i]);
4921 if (i+1 < Parameters.Length)
4924 pars = sb.ToString ();
4927 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
4930 public override int GetHashCode ()
4932 return Name.GetHashCode ();
4935 public override bool Equals (Object o)
4937 MethodSignature other = (MethodSignature) o;
4939 if (other.Name != Name)
4942 if (other.RetType != RetType)
4945 if (Parameters == null){
4946 if (other.Parameters == null)
4951 if (other.Parameters == null)
4954 int c = Parameters.Length;
4955 if (other.Parameters.Length != c)
4958 for (int i = 0; i < c; i++)
4959 if (other.Parameters [i] != Parameters [i])
4965 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
4967 MethodSignature sig = (MethodSignature) filter_criteria;
4969 if (m.Name != sig.Name)
4973 MethodInfo mi = m as MethodInfo;
4974 PropertyInfo pi = m as PropertyInfo;
4977 ReturnType = mi.ReturnType;
4978 else if (pi != null)
4979 ReturnType = pi.PropertyType;
4984 // we use sig.RetType == null to mean `do not check the
4985 // method return value.
4987 if (sig.RetType != null)
4988 if (ReturnType != sig.RetType)
4993 args = TypeManager.GetArgumentTypes (mi);
4995 args = TypeManager.GetArgumentTypes (pi);
4996 Type [] sigp = sig.Parameters;
4998 if (args.Length != sigp.Length)
5001 for (int i = args.Length; i > 0; ){
5003 if (args [i] != sigp [i])
5010 // This filter should be used when we are requesting methods that
5011 // we want to override.
5013 // This makes a number of assumptions, for example
5014 // that the methods being extracted are of a parent
5015 // class (this means we know implicitly that we are
5016 // being called to find out about members by a derived
5019 static bool InheritableMemberSignatureCompare (MemberInfo m, object filter_criteria)
5022 PropertyInfo pi = m as PropertyInfo;
5025 mi = pi.GetGetMethod (true);
5027 mi = pi.GetSetMethod (true);
5029 mi = m as MethodInfo;
5032 Console.WriteLine ("Nothing found");
5035 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5037 // If only accessible to the current class.
5038 if (prot == MethodAttributes.Private)
5041 if (!MemberSignatureCompare (m, filter_criteria))
5044 // If only accessible to the defining assembly or
5045 if (prot == MethodAttributes.FamANDAssem ||
5046 prot == MethodAttributes.Assembly){
5047 if (m.DeclaringType.Assembly == CodeGen.AssemblyBuilder)
5053 // Anything else (FamOrAssembly and Public) is fine