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 Expression a = new Assign (fe, e, l);
562 if (a is ExpressionStatement)
563 ((ExpressionStatement) a).EmitStatement (ec);
565 throw new Exception ("Assign.Resolve returned a non ExpressionStatement");
573 // Defines the default constructors
575 void DefineDefaultConstructor (bool is_static)
580 c = new Constructor (Basename, Parameters.EmptyReadOnlyParameters,
581 new ConstructorBaseInitializer (
582 null, Parameters.EmptyReadOnlyParameters,
587 mods = Modifiers.STATIC;
593 c.Block = new Block (null);
597 public void ReportStructInitializedInstanceError ()
599 string n = TypeBuilder.FullName;
601 foreach (Field f in initialized_fields){
604 "`" + n + "." + f.Name + "': can not have " +
605 "instance field initializers in structs");
610 /// The pending methods that need to be implemented (interfaces or abstract methods)
612 public PendingImplementation Pending;
615 /// This function computes the Base class and also the
616 /// list of interfaces that the class or struct @c implements.
618 /// The return value is an array (might be null) of
619 /// interfaces implemented (as Types).
621 /// The @parent argument is set to the parent object or null
622 /// if this is `System.Object'.
624 Type [] GetClassBases (bool is_class, out Type parent, out bool error)
626 ArrayList bases = Bases;
635 parent = TypeManager.value_type;
639 if (RootContext.StdLib)
640 parent = TypeManager.object_type;
641 else if (Name != "System.Object")
642 parent = TypeManager.object_type;
645 // If we are compiling our runtime,
646 // and we are defining ValueType, then our
647 // parent is `System.Object'.
649 if (!RootContext.StdLib && Name == "System.ValueType")
650 parent = TypeManager.object_type;
657 // Bases should be null if there are no bases at all
662 Expression name = (Expression) bases [0];
663 name = ResolveTypeExpr (name, false, Location);
670 Type first = name.Type;
675 } else if (first.IsSealed){
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);
687 parent = TypeManager.object_type;
691 if (!AsAccessible (parent, ModFlags))
692 Report.Error (60, Location,
693 "Inconsistent accessibility: base class `" +
694 TypeManager.CSharpName (parent) + "' is less " +
695 "accessible than class `" +
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))
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)
909 Warning_KeywordNewRequired (mc.Location, defined_names [idx]);
912 foreach (object o in remove_list)
915 remove_list.Clear ();
919 // Defines the indexers, and also verifies that the IndexerNameAttribute in the
920 // class is consisten. Either it is `Item' or it is the name defined by all the
921 // indexers with the `IndexerName' attribute.
923 // Turns out that the IndexerNameAttribute is applied to each indexer,
924 // but it is never emitted, instead a DefaultName attribute is attached
927 void DefineIndexers ()
929 string class_indexer_name = null;
931 foreach (Indexer i in Indexers){
936 name = i.IndexerName;
938 if (i.InterfaceType != null)
941 if (class_indexer_name == null){
942 class_indexer_name = name;
946 if (name == class_indexer_name)
950 668, "Two indexers have different names, " +
951 " you should use the same name for all your indexers");
953 if (class_indexer_name == null)
954 class_indexer_name = "Item";
955 IndexerName = class_indexer_name;
958 static void Error_KeywordNotAllowed (Location loc)
960 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
964 /// Populates our TypeBuilder with fields and methods
966 public override bool DefineMembers (TypeContainer container)
968 MemberInfo [] defined_names = null;
970 if (interface_order != null){
971 foreach (Interface iface in interface_order)
972 if ((iface.ModFlags & Modifiers.NEW) == 0)
973 iface.DefineMembers (this);
975 Error_KeywordNotAllowed (iface.Location);
978 if (RootContext.WarningLevel > 1){
982 // This code throws an exception in the comparer
983 // I guess the string is not an object?
985 ptype = TypeBuilder.BaseType;
987 defined_names = (MemberInfo []) FindMembers (
988 ptype, MemberTypes.All & ~MemberTypes.Constructor,
989 BindingFlags.Public | BindingFlags.Instance |
990 BindingFlags.Static, null, null);
992 Array.Sort (defined_names, mif_compare);
996 if (constants != null)
997 DefineMembers (constants, defined_names);
1000 DefineMembers (fields, defined_names);
1003 if (instance_constructors == null){
1004 if (default_constructor == null)
1005 DefineDefaultConstructor (false);
1008 if (initialized_static_fields != null &&
1009 default_static_constructor == null)
1010 DefineDefaultConstructor (true);
1013 if (this is Struct){
1015 // Structs can not have initialized instance
1018 if (initialized_static_fields != null &&
1019 default_static_constructor == null)
1020 DefineDefaultConstructor (true);
1022 if (initialized_fields != null)
1023 ReportStructInitializedInstanceError ();
1026 Pending = PendingImplementation.GetPendingImplementations (this);
1029 // Constructors are not in the defined_names array
1031 if (instance_constructors != null)
1032 DefineMembers (instance_constructors, null);
1034 if (default_static_constructor != null)
1035 default_static_constructor.Define (this);
1037 if (methods != null)
1038 DefineMembers (methods, defined_names);
1040 if (properties != null)
1041 DefineMembers (properties, defined_names);
1044 DefineMembers (events, defined_names);
1046 if (indexers != null) {
1049 IndexerName = "Item";
1051 if (operators != null){
1052 DefineMembers (operators, null);
1054 CheckPairedOperators ();
1058 DefineMembers (enums, defined_names);
1060 if (delegates != null)
1061 DefineMembers (delegates, defined_names);
1064 if (TypeBuilder.BaseType != null)
1065 parent_container = TypeManager.LookupMemberContainer (TypeBuilder.BaseType);
1067 member_cache = new MemberCache (this);
1074 public override bool Define (TypeContainer container)
1076 if (interface_order != null){
1077 foreach (Interface iface in interface_order)
1078 if ((iface.ModFlags & Modifiers.NEW) == 0)
1079 iface.Define (this);
1086 /// This function is based by a delegate to the FindMembers routine
1088 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1094 /// This filter is used by FindMembers, and we just keep
1095 /// a global for the filter to `AlwaysAccept'
1097 static MemberFilter accepting_filter;
1101 /// A member comparission method based on name only
1103 static IComparer mif_compare;
1105 static TypeContainer ()
1107 accepting_filter = new MemberFilter (AlwaysAccept);
1108 mif_compare = new MemberInfoCompare ();
1112 /// This method returns the members of this type just like Type.FindMembers would
1113 /// Only, we need to use this for types which are _being_ defined because MS'
1114 /// implementation can't take care of that.
1117 // FIXME: return an empty static array instead of null, that cleans up
1118 // some code and is consistent with some coding conventions I just found
1122 // Notice that in various cases we check if our field is non-null,
1123 // something that would normally mean that there was a bug elsewhere.
1125 // The problem happens while we are defining p-invoke methods, as those
1126 // will trigger a FindMembers, but this happens before things are defined
1128 // Since the whole process is a no-op, it is fine to check for null here.
1130 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1131 MemberFilter filter, object criteria)
1133 ArrayList members = new ArrayList ();
1136 if ((bf & BindingFlags.Public) != 0)
1137 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1139 if ((bf & BindingFlags.NonPublic) != 0)
1140 modflags |= Modifiers.PRIVATE;
1142 int static_mask = 0, static_flags = 0;
1143 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1144 case BindingFlags.Static:
1145 static_mask = static_flags = Modifiers.STATIC;
1148 case BindingFlags.Instance:
1149 static_mask = Modifiers.STATIC;
1154 static_mask = static_flags = 0;
1158 Timer.StartTimer (TimerType.TcFindMembers);
1161 filter = accepting_filter;
1163 if ((mt & MemberTypes.Field) != 0) {
1164 if (fields != null) {
1165 foreach (Field f in fields) {
1166 if ((f.ModFlags & modflags) == 0)
1168 if ((f.ModFlags & static_mask) != static_flags)
1171 FieldBuilder fb = f.FieldBuilder;
1172 if (fb != null && filter (fb, criteria) == true)
1177 if (constants != null) {
1178 foreach (Const con in constants) {
1179 if ((con.ModFlags & modflags) == 0)
1181 if ((con.ModFlags & static_mask) != static_flags)
1184 FieldBuilder fb = con.FieldBuilder;
1185 if (fb != null && filter (fb, criteria) == true)
1191 if ((mt & MemberTypes.Method) != 0) {
1192 if (methods != null) {
1193 foreach (Method m in methods) {
1194 if ((m.ModFlags & modflags) == 0)
1196 if ((m.ModFlags & static_mask) != static_flags)
1199 MethodBuilder mb = m.MethodBuilder;
1201 if (mb != null && filter (mb, criteria) == true)
1206 if (operators != null){
1207 foreach (Operator o in operators) {
1208 if ((o.ModFlags & modflags) == 0)
1210 if ((o.ModFlags & static_mask) != static_flags)
1213 MethodBuilder ob = o.OperatorMethodBuilder;
1214 if (ob != null && filter (ob, criteria) == true)
1219 if (properties != null){
1220 foreach (Property p in properties){
1221 if ((p.ModFlags & modflags) == 0)
1223 if ((p.ModFlags & static_mask) != static_flags)
1229 if (b != null && filter (b, criteria) == true)
1233 if (b != null && filter (b, criteria) == true)
1238 if (indexers != null){
1239 foreach (Indexer ix in indexers){
1240 if ((ix.ModFlags & modflags) == 0)
1242 if ((ix.ModFlags & static_mask) != static_flags)
1248 if (b != null && filter (b, criteria) == true)
1252 if (b != null && filter (b, criteria) == true)
1258 if ((mt & MemberTypes.Event) != 0) {
1260 foreach (Event e in events) {
1261 if ((e.ModFlags & modflags) == 0)
1263 if ((e.ModFlags & static_mask) != static_flags)
1266 MemberInfo eb = e.EventBuilder;
1267 if (eb != null && filter (eb, criteria) == true)
1268 members.Add (e.EventBuilder);
1272 if ((mt & MemberTypes.Property) != 0){
1273 if (properties != null)
1274 foreach (Property p in properties) {
1275 if ((p.ModFlags & modflags) == 0)
1277 if ((p.ModFlags & static_mask) != static_flags)
1280 MemberInfo pb = p.PropertyBuilder;
1281 if (pb != null && filter (pb, criteria) == true) {
1282 members.Add (p.PropertyBuilder);
1286 if (indexers != null)
1287 foreach (Indexer ix in indexers) {
1288 if ((ix.ModFlags & modflags) == 0)
1290 if ((ix.ModFlags & static_mask) != static_flags)
1293 MemberInfo ib = ix.PropertyBuilder;
1294 if (ib != null && filter (ib, criteria) == true) {
1295 members.Add (ix.PropertyBuilder);
1300 if ((mt & MemberTypes.NestedType) != 0) {
1302 foreach (TypeContainer t in types) {
1303 if ((t.ModFlags & modflags) == 0)
1306 TypeBuilder tb = t.TypeBuilder;
1307 if (tb != null && (filter (tb, criteria) == true))
1313 foreach (Enum en in enums){
1314 if ((en.ModFlags & modflags) == 0)
1317 TypeBuilder tb = en.TypeBuilder;
1318 if (tb != null && (filter (tb, criteria) == true))
1323 if (delegates != null){
1324 foreach (Delegate d in delegates){
1325 if ((d.ModFlags & modflags) == 0)
1328 TypeBuilder tb = d.TypeBuilder;
1329 if (tb != null && (filter (tb, criteria) == true))
1334 if (interfaces != null){
1335 foreach (Interface iface in interfaces){
1336 if ((iface.ModFlags & modflags) == 0)
1339 TypeBuilder tb = iface.TypeBuilder;
1340 if (tb != null && (filter (tb, criteria) == true))
1346 if ((mt & MemberTypes.Constructor) != 0){
1347 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1348 foreach (Constructor c in instance_constructors){
1349 ConstructorBuilder cb = c.ConstructorBuilder;
1351 if (filter (cb, criteria) == true)
1356 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1357 ConstructorBuilder cb =
1358 default_static_constructor.ConstructorBuilder;
1361 if (filter (cb, criteria) == true)
1367 // Lookup members in parent if requested.
1369 if (((bf & BindingFlags.DeclaredOnly) == 0) && (TypeBuilder.BaseType != null)) {
1370 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1371 members.AddRange (list);
1374 Timer.StopTimer (TimerType.TcFindMembers);
1376 return new MemberList (members);
1379 public override MemberCache MemberCache {
1381 return member_cache;
1385 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1386 MemberFilter filter, object criteria)
1388 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1391 return ds.FindMembers (mt, bf, filter, criteria);
1393 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1397 // FindMethods will look for methods not only in the type `t', but in
1398 // any interfaces implemented by the type.
1400 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1401 MemberFilter filter, object criteria)
1407 /// Emits the values for the constants
1409 public void EmitConstants ()
1411 if (constants != null)
1412 foreach (Const con in constants)
1413 con.EmitConstant (this);
1418 /// Emits the code, this step is performed after all
1419 /// the types, enumerations, constructors
1423 if (instance_constructors != null)
1424 foreach (Constructor c in instance_constructors)
1427 if (default_static_constructor != null)
1428 default_static_constructor.Emit (this);
1430 if (methods != null)
1431 foreach (Method m in methods)
1434 if (operators != null)
1435 foreach (Operator o in operators)
1438 if (properties != null)
1439 foreach (Property p in properties)
1442 if (indexers != null){
1443 foreach (Indexer ix in indexers)
1446 CustomAttributeBuilder cb = Interface.EmitDefaultMemberAttr (
1447 this, IndexerName, ModFlags, Location);
1448 TypeBuilder.SetCustomAttribute (cb);
1452 foreach (Field f in fields)
1455 if (events != null){
1456 foreach (Event e in Events)
1460 if (Pending != null)
1461 if (Pending.VerifyPendingMethods ())
1464 Attribute.ApplyAttributes (ec, TypeBuilder, this, OptAttributes);
1467 // Check for internal or private fields that were never assigned
1469 if (RootContext.WarningLevel >= 3) {
1470 if (fields != null){
1471 foreach (Field f in fields) {
1472 if ((f.ModFlags & Modifiers.PUBLIC) != 0)
1477 169, f.Location, "Private field " +
1478 MakeName (f.Name) + " is never used");
1483 // Only report 649 on level 4
1485 if (RootContext.WarningLevel < 4)
1488 if ((f.status & Field.Status.ASSIGNED) != 0)
1493 "Field " + MakeName (f.Name) + " is never assigned " +
1494 " to and will always have its default value");
1498 if (events != null){
1499 foreach (Event e in events){
1501 Report.Warning (67, "The event " + MakeName (e.Name) + " is never used");
1506 // if (types != null)
1507 // foreach (TypeContainer tc in types)
1511 public override void CloseType ()
1516 TypeBuilder.CreateType ();
1518 } catch (TypeLoadException){
1520 // This is fine, the code still created the type
1522 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1523 // Console.WriteLine (e.Message);
1525 Console.WriteLine ("In type: " + Name);
1530 foreach (Enum en in Enums)
1533 if (interface_order != null){
1534 foreach (Interface iface in interface_order)
1539 foreach (TypeContainer tc in Types)
1543 foreach (TypeContainer tc in Types)
1544 if (!(tc is Struct))
1548 if (Delegates != null)
1549 foreach (Delegate d in Delegates)
1553 public string MakeName (string n)
1555 return "`" + Name + "." + n + "'";
1558 public void Warning_KeywordNewRequired (Location l, MemberInfo mi)
1561 108, l, "The keyword new is required on " +
1562 MakeName (mi.Name) + " because it hides `" +
1563 mi.ReflectedType.Name + "." + mi.Name + "'");
1566 public void Warning_KewywordNewNotRequired (Location l, MemberCore mc)
1569 109, l, "The member " + MakeName (mc.Name) + " does not hide an " +
1570 "inherited member, the keyword new is not required");
1573 public static int CheckMember (string name, MemberInfo mi, int ModFlags)
1579 // Performs the validation on a Method's modifiers (properties have
1580 // the same properties).
1582 public bool MethodModifiersValid (int flags, string n, Location loc)
1584 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1585 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1586 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1590 // At most one of static, virtual or override
1592 if ((flags & Modifiers.STATIC) != 0){
1593 if ((flags & vao) != 0){
1595 112, loc, "static method " + MakeName (n) + "can not be marked " +
1596 "as virtual, abstract or override");
1601 if (this is Struct){
1602 if ((flags & va) != 0){
1603 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
1608 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1610 113, loc, MakeName (n) +
1611 " marked as override cannot be marked as new or virtual");
1616 // If the declaration includes the abstract modifier, then the
1617 // declaration does not include static, virtual or extern
1619 if ((flags & Modifiers.ABSTRACT) != 0){
1620 if ((flags & Modifiers.EXTERN) != 0){
1622 180, loc, MakeName (n) + " can not be both abstract and extern");
1626 if ((flags & Modifiers.VIRTUAL) != 0){
1628 503, loc, MakeName (n) + " can not be both abstract and virtual");
1632 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1634 513, loc, MakeName (n) +
1635 " is abstract but its container class is not");
1641 if ((flags & Modifiers.PRIVATE) != 0){
1642 if ((flags & vao) != 0){
1644 621, loc, MakeName (n) +
1645 " virtual or abstract members can not be private");
1650 if ((flags & Modifiers.SEALED) != 0){
1651 if ((flags & Modifiers.OVERRIDE) == 0){
1653 238, loc, MakeName (n) +
1654 " cannot be sealed because it is not an override");
1662 // Access level of a type.
1665 ProtectedInternal = 1,
1671 // Check whether `flags' denotes a more restricted access than `level'
1672 // and return the new level.
1673 static AccessLevel CheckAccessLevel (AccessLevel level, int flags)
1675 AccessLevel old_level = level;
1677 if ((flags & Modifiers.INTERNAL) != 0) {
1678 if ((flags & Modifiers.PROTECTED) != 0) {
1679 if ((int) level < (int) AccessLevel.ProtectedInternal)
1680 level = AccessLevel.ProtectedInternal;
1682 if ((int) level < (int) AccessLevel.Internal)
1683 level = AccessLevel.Internal;
1685 } else if ((flags & Modifiers.PROTECTED) != 0) {
1686 if ((int) level < (int) AccessLevel.Protected)
1687 level = AccessLevel.Protected;
1688 } else if ((flags & Modifiers.PRIVATE) != 0)
1689 level = AccessLevel.Private;
1694 // Return the access level for a new member which is defined in the current
1695 // TypeContainer with access modifiers `flags'.
1696 AccessLevel GetAccessLevel (int flags)
1698 if ((flags & Modifiers.PRIVATE) != 0)
1699 return AccessLevel.Private;
1702 if (!IsTopLevel && (Parent != null))
1703 level = Parent.GetAccessLevel (flags);
1705 level = AccessLevel.Public;
1707 return CheckAccessLevel (CheckAccessLevel (level, flags), ModFlags);
1710 // Return the access level for type `t', but don't give more access than `flags'.
1711 static AccessLevel GetAccessLevel (Type t, int flags)
1713 if (((flags & Modifiers.PRIVATE) != 0) || t.IsNestedPrivate)
1714 return AccessLevel.Private;
1717 if (TypeManager.IsBuiltinType (t))
1718 return AccessLevel.Public;
1719 else if ((t.DeclaringType != null) && (t != t.DeclaringType))
1720 level = GetAccessLevel (t.DeclaringType, flags);
1722 level = CheckAccessLevel (AccessLevel.Public, flags);
1725 if (t.IsNestedPublic)
1728 if (t.IsNestedAssembly || t.IsNotPublic) {
1729 if ((int) level < (int) AccessLevel.Internal)
1730 level = AccessLevel.Internal;
1733 if (t.IsNestedFamily) {
1734 if ((int) level < (int) AccessLevel.Protected)
1735 level = AccessLevel.Protected;
1738 if (t.IsNestedFamORAssem) {
1739 if ((int) level < (int) AccessLevel.ProtectedInternal)
1740 level = AccessLevel.ProtectedInternal;
1747 // Returns true if `parent' is as accessible as the flags `flags'
1748 // given for this member.
1750 public bool AsAccessible (Type parent, int flags)
1752 while (parent.IsArray || parent.IsPointer || parent.IsByRef)
1753 parent = parent.GetElementType ();
1755 AccessLevel level = GetAccessLevel (flags);
1756 AccessLevel level2 = GetAccessLevel (parent, flags);
1758 return (int) level >= (int) level2;
1761 Hashtable builder_and_args;
1763 public bool RegisterMethod (MethodBuilder mb, InternalParameters ip, Type [] args)
1765 if (builder_and_args == null)
1766 builder_and_args = new Hashtable ();
1771 /// Performs checks for an explicit interface implementation. First it
1772 /// checks whether the `interface_type' is a base inteface implementation.
1773 /// Then it checks whether `name' exists in the interface type.
1775 public bool VerifyImplements (Type interface_type, string full, string name, Location loc)
1779 if (ifaces != null){
1780 foreach (Type t in ifaces){
1781 if (t == interface_type){
1789 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
1796 public static void Error_ExplicitInterfaceNotMemberInterface (Location loc, string name)
1798 Report.Error (539, loc, "Explicit implementation: `" + name + "' is not a member of the interface");
1805 string IMemberContainer.Name {
1811 Type IMemberContainer.Type {
1817 IMemberContainer IMemberContainer.Parent {
1819 return parent_container;
1823 MemberCache IMemberContainer.MemberCache {
1825 return member_cache;
1829 bool IMemberContainer.IsInterface {
1835 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
1837 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
1841 // Operator pair checking
1844 class OperatorEntry {
1846 public Type ret_type;
1847 public Type type1, type2;
1849 public Operator.OpType ot;
1851 public OperatorEntry (int f, Operator o)
1855 ret_type = o.OperatorMethod.GetReturnType ();
1856 Type [] pt = o.OperatorMethod.ParameterTypes;
1860 ot = o.OperatorType;
1863 public override int GetHashCode ()
1865 return ret_type.GetHashCode ();
1868 public override bool Equals (object o)
1870 OperatorEntry other = (OperatorEntry) o;
1872 if (other.ret_type != ret_type)
1874 if (other.type1 != type1)
1876 if (other.type2 != type2)
1883 // Checks that some operators come in pairs:
1889 // They are matched based on the return type and the argument types
1891 void CheckPairedOperators ()
1893 Hashtable pairs = new Hashtable (null, null);
1894 Operator true_op = null;
1895 Operator false_op = null;
1897 // Register all the operators we care about.
1898 foreach (Operator op in operators){
1901 switch (op.OperatorType){
1902 case Operator.OpType.Equality:
1904 case Operator.OpType.Inequality:
1907 case Operator.OpType.True:
1910 case Operator.OpType.False:
1914 case Operator.OpType.GreaterThan:
1916 case Operator.OpType.LessThan:
1919 case Operator.OpType.GreaterThanOrEqual:
1921 case Operator.OpType.LessThanOrEqual:
1927 OperatorEntry oe = new OperatorEntry (reg, op);
1929 object o = pairs [oe];
1933 oe = (OperatorEntry) o;
1938 if (true_op != null){
1939 if (false_op == null)
1940 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
1941 } else if (false_op != null)
1942 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
1945 // Look for the mistakes.
1947 foreach (DictionaryEntry de in pairs){
1948 OperatorEntry oe = (OperatorEntry) de.Key;
1955 case Operator.OpType.Equality:
1958 case Operator.OpType.Inequality:
1961 case Operator.OpType.GreaterThan:
1964 case Operator.OpType.LessThan:
1967 case Operator.OpType.GreaterThanOrEqual:
1970 case Operator.OpType.LessThanOrEqual:
1974 Report.Error (216, oe.op.Location,
1975 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
1982 public class Class : TypeContainer {
1984 // Modifiers allowed in a class declaration
1986 public const int AllowedModifiers =
1989 Modifiers.PROTECTED |
1990 Modifiers.INTERNAL |
1992 Modifiers.ABSTRACT |
1996 public Class (TypeContainer parent, string name, int mod, Attributes attrs, Location l)
1997 : base (parent, name, l)
2001 if (parent.Parent == null)
2002 accmods = Modifiers.INTERNAL;
2004 accmods = Modifiers.PRIVATE;
2006 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2007 this.attributes = attrs;
2011 // FIXME: How do we deal with the user specifying a different
2014 public override TypeAttributes TypeAttr {
2016 return base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2021 public class Struct : TypeContainer {
2023 // Modifiers allowed in a struct declaration
2025 public const int AllowedModifiers =
2028 Modifiers.PROTECTED |
2029 Modifiers.INTERNAL |
2033 public Struct (TypeContainer parent, string name, int mod, Attributes attrs, Location l)
2034 : base (parent, name, l)
2038 if (parent.Parent == null)
2039 accmods = Modifiers.INTERNAL;
2041 accmods = Modifiers.PRIVATE;
2043 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2045 this.ModFlags |= Modifiers.SEALED;
2046 this.attributes = attrs;
2051 // FIXME: Allow the user to specify a different set of attributes
2052 // in some cases (Sealed for example is mandatory for a class,
2053 // but what SequentialLayout can be changed
2055 public override TypeAttributes TypeAttr {
2057 return base.TypeAttr |
2058 TypeAttributes.SequentialLayout |
2059 TypeAttributes.Sealed |
2060 TypeAttributes.BeforeFieldInit;
2065 public abstract class MethodCore : MemberBase {
2066 public readonly Parameters Parameters;
2067 protected Block block;
2070 // Parameters, cached for semantic analysis.
2072 protected InternalParameters parameter_info;
2073 protected Type [] parameter_types;
2075 public MethodCore (Expression type, int mod, int allowed_mod, string name,
2076 Attributes attrs, Parameters parameters, Location loc)
2077 : base (type, mod, allowed_mod, name, attrs, loc)
2079 Parameters = parameters;
2083 // Returns the System.Type array for the parameters of this method
2085 public Type [] ParameterTypes {
2087 return parameter_types;
2091 public InternalParameters ParameterInfo
2094 return parameter_info;
2098 public Block Block {
2108 protected virtual bool DoDefineParameters (TypeContainer container)
2110 // Check if arguments were correct
2111 parameter_types = Parameters.GetParameterInfo (container);
2112 if ((parameter_types == null) || !CheckParameters (container, parameter_types))
2115 parameter_info = new InternalParameters (container, Parameters);
2120 public CallingConventions GetCallingConvention (bool is_class)
2122 CallingConventions cc = 0;
2124 cc = Parameters.GetCallingConvention ();
2127 if ((ModFlags & Modifiers.STATIC) == 0)
2128 cc |= CallingConventions.HasThis;
2130 // FIXME: How is `ExplicitThis' used in C#?
2136 // The method's attributes are passed in because we need to extract
2137 // the "return:" attribute from there to apply on the return type
2139 public void LabelParameters (EmitContext ec, MethodBase builder, Attributes method_attrs)
2142 // Define each type attribute (in/out/ref) and
2143 // the argument names.
2145 Parameter [] p = Parameters.FixedParameters;
2148 MethodBuilder mb = null;
2149 ConstructorBuilder cb = null;
2151 if (builder is MethodBuilder)
2152 mb = (MethodBuilder) builder;
2154 cb = (ConstructorBuilder) builder;
2157 for (i = 0; i < p.Length; i++) {
2158 ParameterBuilder pb;
2159 ParameterAttributes par_attr = p [i].Attributes;
2162 pb = cb.DefineParameter (
2163 i + 1, par_attr, p [i].Name);
2165 pb = mb.DefineParameter (
2166 i + 1, par_attr, p [i].Name);
2168 Attributes attr = p [i].OptAttributes;
2170 Attribute.ApplyAttributes (ec, pb, pb, attr);
2172 if (par_attr == ParameterAttributes.Out){
2173 if (attr.Contains (TypeManager.in_attribute_type))
2174 Report.Error (36, Location, "Can not use [In] attribute on out parameter");
2180 if (Parameters.ArrayParameter != null){
2181 ParameterBuilder pb;
2182 Parameter array_param = Parameters.ArrayParameter;
2185 pb = cb.DefineParameter (
2186 i + 1, array_param.Attributes,
2189 pb = mb.DefineParameter (
2190 i + 1, array_param.Attributes,
2193 CustomAttributeBuilder a = new CustomAttributeBuilder (
2194 TypeManager.cons_param_array_attribute, new object [0]);
2196 pb.SetCustomAttribute (a);
2200 // And now for the return type attribute decoration
2202 ParameterBuilder ret_pb;
2203 Attributes ret_attrs = null;
2205 if (mb == null || method_attrs == null)
2208 foreach (AttributeSection asec in method_attrs.AttributeSections) {
2210 if (asec.Target != "return")
2213 if (ret_attrs == null)
2214 ret_attrs = new Attributes (asec);
2216 ret_attrs.AddAttributeSection (asec);
2219 if (ret_attrs != null) {
2221 ret_pb = mb.DefineParameter (0, ParameterAttributes.None, "");
2222 Attribute.ApplyAttributes (ec, ret_pb, ret_pb, ret_attrs);
2223 } catch (ArgumentOutOfRangeException) {
2226 ".NET SDK 1.0 does not permit to set custom attributes to the return type of a method");
2232 public class Method : MethodCore, IIteratorContainer {
2233 public MethodBuilder MethodBuilder;
2234 public MethodData MethodData;
2237 /// Modifiers allowed in a class declaration
2239 const int AllowedModifiers =
2242 Modifiers.PROTECTED |
2243 Modifiers.INTERNAL |
2248 Modifiers.OVERRIDE |
2249 Modifiers.ABSTRACT |
2254 // return_type can be "null" for VOID values.
2256 public Method (Expression return_type, int mod, string name, Parameters parameters,
2257 Attributes attrs, Location l)
2258 : base (return_type, mod, AllowedModifiers, name, attrs, parameters, l)
2262 // Returns the `System.Type' for the ReturnType of this
2263 // function. Provides a nice cache. (used between semantic analysis
2264 // and actual code generation
2266 public Type GetReturnType ()
2271 // Whether this is an operator method.
2272 public bool IsOperator;
2274 void DuplicateEntryPoint (MethodInfo b, Location location)
2278 "Program `" + CodeGen.FileName +
2279 "' has more than one entry point defined: `" +
2280 TypeManager.CSharpSignature(b) + "'");
2283 void Report28 (MethodInfo b)
2287 "`" + TypeManager.CSharpSignature(b) +
2288 "' has the wrong signature to be an entry point");
2291 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
2293 if (b.ReturnType != TypeManager.void_type &&
2294 b.ReturnType != TypeManager.int32_type)
2297 if (pinfo.Count == 0)
2300 if (pinfo.Count > 1)
2303 Type t = pinfo.ParameterType(0);
2305 (t.GetArrayRank() == 1) &&
2306 (t.GetElementType() == TypeManager.string_type) &&
2307 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
2314 // Checks our base implementation if any
2316 protected override bool CheckBase (TypeContainer container)
2318 base.CheckBase (container);
2320 // Check whether arguments were correct.
2321 if (!DoDefineParameters (container))
2324 MethodSignature ms = new MethodSignature (Name, null, ParameterTypes);
2326 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2330 mi_this = TypeContainer.FindMembers (
2331 container.TypeBuilder, MemberTypes.Method,
2332 BindingFlags.NonPublic | BindingFlags.Public |
2333 BindingFlags.Static | BindingFlags.Instance |
2334 BindingFlags.DeclaredOnly,
2335 MethodSignature.method_signature_filter, ms);
2337 if (mi_this.Count > 0) {
2338 Report.Error (111, Location, "Class `" + container.Name + "' " +
2339 "already defines a member called `" + Name + "' " +
2340 "with the same parameter types");
2346 // Verify if the parent has a type with the same name, and then
2347 // check whether we have to create a new slot for it or not.
2349 Type ptype = container.TypeBuilder.BaseType;
2351 // ptype is only null for System.Object while compiling corlib.
2353 MemberList mi, mi_static, mi_instance;
2355 mi_instance = TypeContainer.FindMembers (
2356 ptype, MemberTypes.Method,
2357 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
2358 MethodSignature.inheritable_method_signature_filter,
2361 if (mi_instance.Count > 0){
2364 mi_static = TypeContainer.FindMembers (
2365 ptype, MemberTypes.Method,
2366 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static,
2367 MethodSignature.inheritable_method_signature_filter, ms);
2369 if (mi_static.Count > 0)
2375 if (mi != null && mi.Count > 0){
2376 parent_method = (MethodInfo) mi [0];
2377 string name = parent_method.DeclaringType.Name + "." +
2380 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
2383 if ((ModFlags & Modifiers.NEW) == 0) {
2384 Type parent_ret = TypeManager.TypeToCoreType (
2385 parent_method.ReturnType);
2387 if (parent_ret != MemberType) {
2389 508, Location, container.MakeName (Name) + ": cannot " +
2390 "change return type when overriding " +
2391 "inherited member " + name);
2396 if ((ModFlags & Modifiers.NEW) != 0)
2397 WarningNotHiding (container);
2399 if ((ModFlags & Modifiers.OVERRIDE) != 0){
2400 Report.Error (115, Location,
2401 container.MakeName (Name) +
2402 " no suitable methods found to override");
2405 } else if ((ModFlags & Modifiers.NEW) != 0)
2406 WarningNotHiding (container);
2414 public override bool Define (TypeContainer container)
2416 if (!DoDefine (container))
2419 if (!CheckBase (container))
2422 CallingConventions cc = GetCallingConvention (container is Class);
2424 MethodData = new MethodData (this, null, MemberType, ParameterTypes,
2425 ParameterInfo, cc, OptAttributes,
2426 ModFlags, flags, true);
2428 if (!MethodData.Define (container))
2432 // Setup iterator if we are one
2434 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
2435 IteratorHandler ih = new IteratorHandler (
2436 Name, container, MemberType,
2437 ParameterTypes, ParameterInfo,
2438 ModFlags, Location);
2440 Block new_block = ih.Setup (block);
2441 if (new_block == null)
2446 MethodBuilder = MethodData.MethodBuilder;
2449 // This is used to track the Entry Point,
2451 if (Name == "Main" &&
2452 ((ModFlags & Modifiers.STATIC) != 0) &&
2453 (RootContext.MainClass == null ||
2454 RootContext.MainClass == container.TypeBuilder.FullName)){
2455 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
2456 if (RootContext.EntryPoint == null) {
2457 RootContext.EntryPoint = MethodBuilder;
2458 RootContext.EntryPointLocation = Location;
2460 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
2461 DuplicateEntryPoint (MethodBuilder, Location);
2464 Report28(MethodBuilder);
2473 public void Emit (TypeContainer container)
2475 MethodData.Emit (container, Block, this);
2479 void IIteratorContainer.SetYields ()
2481 ModFlags |= Modifiers.METHOD_YIELDS;
2485 public abstract class ConstructorInitializer {
2486 ArrayList argument_list;
2487 ConstructorInfo parent_constructor;
2488 Parameters parameters;
2491 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
2494 this.argument_list = argument_list;
2495 this.parameters = parameters;
2499 public ArrayList Arguments {
2501 return argument_list;
2505 public bool Resolve (EmitContext ec)
2507 Expression parent_constructor_group;
2510 ec.CurrentBlock = new Block (null, Block.Flags.Implicit, parameters);
2512 if (argument_list != null){
2513 foreach (Argument a in argument_list){
2514 if (!a.Resolve (ec, loc))
2518 ec.CurrentBlock = null;
2520 if (this is ConstructorBaseInitializer) {
2521 if (ec.ContainerType.BaseType == null)
2524 t = ec.ContainerType.BaseType;
2525 if (ec.ContainerType.IsValueType) {
2526 Report.Error (522, loc,
2527 "structs cannot call base class constructors");
2531 t = ec.ContainerType;
2533 parent_constructor_group = Expression.MemberLookup (
2534 ec, t, null, t, ".ctor",
2535 MemberTypes.Constructor,
2536 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
2539 if (parent_constructor_group == null){
2540 Report.Error (1501, loc,
2541 "Can not find a constructor for this argument list");
2545 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (ec,
2546 (MethodGroupExpr) parent_constructor_group, argument_list, loc);
2548 if (parent_constructor == null){
2549 Report.Error (1501, loc,
2550 "Can not find a constructor for this argument list");
2557 public void Emit (EmitContext ec)
2559 if (parent_constructor != null){
2560 ec.Mark (loc, false);
2562 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
2564 Invocation.EmitCall (ec, true, false, ec.This, parent_constructor, argument_list, loc);
2569 public class ConstructorBaseInitializer : ConstructorInitializer {
2570 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
2571 base (argument_list, pars, l)
2576 public class ConstructorThisInitializer : ConstructorInitializer {
2577 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
2578 base (argument_list, pars, l)
2583 public class Constructor : MethodCore {
2584 public ConstructorBuilder ConstructorBuilder;
2585 public ConstructorInitializer Initializer;
2586 new public Attributes OptAttributes;
2589 // Modifiers allowed for a constructor.
2591 public const int AllowedModifiers =
2593 Modifiers.PROTECTED |
2594 Modifiers.INTERNAL |
2601 // The spec claims that static is not permitted, but
2602 // my very own code has static constructors.
2604 public Constructor (string name, Parameters args, ConstructorInitializer init, Location l)
2605 : base (null, 0, AllowedModifiers, name, null, args, l)
2611 // Returns true if this is a default constructor
2613 public bool IsDefault ()
2615 if ((ModFlags & Modifiers.STATIC) != 0)
2616 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
2617 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
2620 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
2621 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
2622 (Initializer is ConstructorBaseInitializer) &&
2623 (Initializer.Arguments == null);
2627 // Creates the ConstructorBuilder
2629 public override bool Define (TypeContainer container)
2631 MethodAttributes ca = (MethodAttributes.RTSpecialName |
2632 MethodAttributes.SpecialName);
2634 // Check if arguments were correct.
2635 if (!DoDefineParameters (container))
2638 if ((ModFlags & Modifiers.STATIC) != 0){
2639 ca |= MethodAttributes.Static | MethodAttributes.Private;
2641 if (container is Struct && ParameterTypes.Length == 0){
2644 "Structs can not contain explicit parameterless " +
2648 ca |= MethodAttributes.HideBySig;
2650 if ((ModFlags & Modifiers.PUBLIC) != 0)
2651 ca |= MethodAttributes.Public;
2652 else if ((ModFlags & Modifiers.PROTECTED) != 0){
2653 if ((ModFlags & Modifiers.INTERNAL) != 0)
2654 ca |= MethodAttributes.FamORAssem;
2656 ca |= MethodAttributes.Family;
2657 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
2658 ca |= MethodAttributes.Assembly;
2659 else if (IsDefault ())
2660 ca |= MethodAttributes.Public;
2662 ca |= MethodAttributes.Private;
2665 ConstructorBuilder = container.TypeBuilder.DefineConstructor (
2666 ca, GetCallingConvention (container is Class), ParameterTypes);
2669 // HACK because System.Reflection.Emit is lame
2671 if (!TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes)) {
2674 "Class `" +container.Name+ "' already contains a definition with the " +
2675 "same return value and parameter types for constructor `" + Name
2686 public void Emit (TypeContainer container)
2688 ILGenerator ig = ConstructorBuilder.GetILGenerator ();
2689 EmitContext ec = new EmitContext (container, Location, ig, null, ModFlags, true);
2692 // extern methods have no bodies
2694 if ((ModFlags & Modifiers.EXTERN) != 0) {
2695 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
2697 179, Location, "External constructor `" +
2698 TypeManager.CSharpSignature (ConstructorBuilder) +
2699 "' can not have a body");
2702 } else if (block == null) {
2704 501, Location, "Constructor `" +
2705 TypeManager.CSharpSignature (ConstructorBuilder) +
2706 "' must declare a body since it is not marked extern");
2710 if ((ModFlags & Modifiers.STATIC) == 0){
2711 if (container is Class && Initializer == null)
2712 Initializer = new ConstructorBaseInitializer (
2713 null, Parameters.EmptyReadOnlyParameters, Location);
2717 // Spec mandates that Initializers will not have
2721 if (Initializer != null && !Initializer.Resolve (ec))
2723 ec.IsStatic = false;
2726 LabelParameters (ec, ConstructorBuilder, OptAttributes);
2728 SymbolWriter sw = CodeGen.SymbolWriter;
2729 bool generate_debugging = false;
2731 if ((sw != null) && (block != null) &&
2732 !Location.IsNull (Location) &&
2733 !Location.IsNull (block.EndLocation)) {
2735 sw.OpenMethod (container, ConstructorBuilder, Location, block.EndLocation);
2737 generate_debugging = true;
2741 // Classes can have base initializers and instance field initializers.
2743 if (container is Class){
2744 if ((ModFlags & Modifiers.STATIC) == 0){
2747 // If we use a "this (...)" constructor initializer, then
2748 // do not emit field initializers, they are initialized in the other constructor
2750 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
2751 container.EmitFieldInitializers (ec);
2754 if (Initializer != null)
2755 Initializer.Emit (ec);
2757 if ((ModFlags & Modifiers.STATIC) != 0)
2758 container.EmitFieldInitializers (ec);
2760 Attribute.ApplyAttributes (ec, ConstructorBuilder, this, OptAttributes);
2762 // If this is a non-static `struct' constructor and doesn't have any
2763 // initializer, it must initialize all of the struct's fields.
2764 if ((container is Struct) && ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
2765 Block.AddThisVariable (container, Location);
2767 ec.EmitTopBlock (block, ParameterInfo, Location);
2769 if (generate_debugging)
2777 // Encapsulates most of the Method's state
2779 public class MethodData {
2781 // The return type of this method
2783 public readonly Type ReturnType;
2784 public readonly Type[] ParameterTypes;
2785 public readonly InternalParameters ParameterInfo;
2786 public readonly CallingConventions CallingConventions;
2787 public readonly Attributes OptAttributes;
2788 public readonly Location Location;
2791 // Are we implementing an interface ?
2793 public bool IsImplementing = false;
2798 protected MemberBase member;
2799 protected int modifiers;
2800 protected MethodAttributes flags;
2801 protected bool is_method;
2802 protected string accessor_name;
2805 // It can either hold a string with the condition, or an arraylist of conditions.
2806 object conditionals;
2808 MethodBuilder builder = null;
2809 public MethodBuilder MethodBuilder {
2815 public MethodData (MemberBase member, string name, Type return_type,
2816 Type [] parameter_types, InternalParameters parameters,
2817 CallingConventions cc, Attributes opt_attrs,
2818 int modifiers, MethodAttributes flags, bool is_method)
2820 this.member = member;
2821 this.accessor_name = name;
2822 this.ReturnType = return_type;
2823 this.ParameterTypes = parameter_types;
2824 this.ParameterInfo = parameters;
2825 this.CallingConventions = cc;
2826 this.OptAttributes = opt_attrs;
2827 this.modifiers = modifiers;
2829 this.is_method = is_method;
2830 this.Location = member.Location;
2831 this.conditionals = null;
2837 Attribute dllimport_attribute = null;
2838 string obsolete = null;
2839 bool obsolete_error = false;
2841 public virtual bool ApplyAttributes (Attributes opt_attrs, bool is_method)
2843 if ((opt_attrs == null) || (opt_attrs.AttributeSections == null))
2846 foreach (AttributeSection asec in opt_attrs.AttributeSections) {
2847 if (asec.Attributes == null)
2850 foreach (Attribute a in asec.Attributes) {
2851 if (a.Name == "Conditional") {
2852 if (!ApplyConditionalAttribute (a))
2854 } else if (a.Name == "Obsolete") {
2855 if (!ApplyObsoleteAttribute (a))
2857 } else if (a.Name.IndexOf ("DllImport") != -1) {
2859 a.Type = TypeManager.dllimport_type;
2860 Attribute.Error_AttributeNotValidForElement (a, Location);
2863 if (!ApplyDllImportAttribute (a))
2873 // Applies the `DllImport' attribute to the method.
2875 protected virtual bool ApplyDllImportAttribute (Attribute a)
2877 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
2878 if ((modifiers & extern_static) != extern_static) {
2879 Report.Error (601, Location,
2880 "The DllImport attribute must be specified on a method " +
2881 "marked `static' and `extern'.");
2885 flags |= MethodAttributes.PinvokeImpl;
2886 dllimport_attribute = a;
2891 // Applies the `Obsolete' attribute to the method.
2893 protected virtual bool ApplyObsoleteAttribute (Attribute a)
2895 if (obsolete != null) {
2896 Report.Error (579, Location, "Duplicate `Obsolete' attribute");
2900 obsolete = a.Obsolete_GetObsoleteMessage (out obsolete_error);
2901 return obsolete != null;
2905 // Applies the `Conditional' attribute to the method.
2907 protected virtual bool ApplyConditionalAttribute (Attribute a)
2909 // The Conditional attribute is only valid on methods.
2911 Attribute.Error_AttributeNotValidForElement (a, Location);
2915 string condition = a.Conditional_GetConditionName ();
2917 if (condition == null)
2920 if (ReturnType != TypeManager.void_type) {
2921 Report.Error (578, Location,
2922 "Conditional not valid on `" + member.Name + "' " +
2923 "because its return type is not void");
2927 if ((modifiers & Modifiers.OVERRIDE) != 0) {
2928 Report.Error (243, Location,
2929 "Conditional not valid on `" + member.Name + "' " +
2930 "because it is an override method");
2934 if (member.IsExplicitImpl) {
2935 Report.Error (577, Location,
2936 "Conditional not valid on `" + member.Name + "' " +
2937 "because it is an explicit interface implementation");
2941 if (IsImplementing) {
2942 Report.Error (623, Location,
2943 "Conditional not valid on `" + member.Name + "' " +
2944 "because it is an interface method");
2949 // The likelyhood that the conditional will be more than 1 is very slim
2951 if (conditionals == null)
2952 conditionals = condition;
2953 else if (conditionals is string){
2954 string s = (string) conditionals;
2955 conditionals = new ArrayList ();
2956 ((ArrayList)conditionals).Add (s);
2958 ((ArrayList)conditionals).Add (condition);
2964 // Checks whether this method should be ignored due to its Conditional attributes.
2966 bool ShouldIgnore (Location loc)
2968 // When we're overriding a virtual method, we implicitly inherit the
2969 // Conditional attributes from our parent.
2970 if (member.ParentMethod != null) {
2971 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (
2972 member.ParentMethod, loc);
2974 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
2978 if (conditionals != null){
2979 if (conditionals is string){
2980 if (RootContext.AllDefines [conditionals] == null)
2983 foreach (string condition in (ArrayList) conditionals)
2984 if (RootContext.AllDefines [condition] == null)
2992 // Returns the TypeManager.MethodFlags for this method.
2993 // This emits an error 619 / warning 618 if the method is obsolete.
2994 // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
2996 public virtual TypeManager.MethodFlags GetMethodFlags (Location loc)
2998 TypeManager.MethodFlags flags = 0;
3000 if (obsolete != null) {
3001 if (obsolete_error) {
3002 Report.Error (619, loc, "Method `" + member.Name +
3003 "' is obsolete: `" + obsolete + "'");
3004 return TypeManager.MethodFlags.IsObsoleteError;
3006 Report.Warning (618, loc, "Method `" + member.Name +
3007 "' is obsolete: `" + obsolete + "'");
3009 flags |= TypeManager.MethodFlags.IsObsolete;
3012 if (ShouldIgnore (loc))
3013 flags |= TypeManager.MethodFlags.ShouldIgnore;
3018 public virtual bool Define (TypeContainer container)
3020 MethodInfo implementing = null;
3021 string method_name, name, prefix;
3023 if (OptAttributes != null)
3024 if (!ApplyAttributes (OptAttributes, is_method))
3027 if (member.IsExplicitImpl)
3028 prefix = member.InterfaceType.FullName + ".";
3032 if (accessor_name != null)
3033 name = accessor_name + "_" + member.ShortName;
3035 name = member.ShortName;
3036 method_name = prefix + name;
3038 if (container.Pending != null){
3039 if (member is Indexer)
3040 implementing = container.Pending.IsInterfaceIndexer (
3041 member.InterfaceType, ReturnType, ParameterTypes);
3043 implementing = container.Pending.IsInterfaceMethod (
3044 member.InterfaceType, name, ReturnType, ParameterTypes);
3046 if (member.InterfaceType != null && implementing == null){
3047 TypeContainer.Error_ExplicitInterfaceNotMemberInterface (
3054 // For implicit implementations, make sure we are public, for
3055 // explicit implementations, make sure we are private.
3057 if (implementing != null){
3059 // Setting null inside this block will trigger a more
3060 // verbose error reporting for missing interface implementations
3062 // The "candidate" function has been flagged already
3063 // but it wont get cleared
3065 if (member.IsExplicitImpl){
3066 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
3067 Modifiers.Error_InvalidModifier (Location, "public, virtual or abstract");
3068 implementing = null;
3072 // We already catch different accessibility settings
3073 // so we just need to check that we are not private
3075 if ((modifiers & Modifiers.PRIVATE) != 0)
3076 implementing = null;
3080 // Static is not allowed
3082 if ((modifiers & Modifiers.STATIC) != 0){
3083 implementing = null;
3084 Modifiers.Error_InvalidModifier (Location, "static");
3089 // If implementing is still valid, set flags
3091 if (implementing != null){
3093 // When implementing interface methods, set NewSlot
3094 // unless, we are overwriting a method.
3096 if (implementing.DeclaringType.IsInterface){
3097 if ((modifiers & Modifiers.OVERRIDE) == 0)
3098 flags |= MethodAttributes.NewSlot;
3101 MethodAttributes.Virtual |
3102 MethodAttributes.HideBySig;
3104 // Get the method name from the explicit interface.
3105 if (member.InterfaceType != null) {
3106 name = implementing.Name;
3107 method_name = prefix + name;
3110 IsImplementing = true;
3114 // Create the MethodBuilder for the method
3116 if ((flags & MethodAttributes.PinvokeImpl) != 0) {
3117 if ((modifiers & Modifiers.STATIC) == 0) {
3118 Report.Error (601, Location,
3119 "The DllImport attribute must be specified on " +
3120 "a method marked 'static' and 'extern'.");
3124 EmitContext ec = new EmitContext (
3125 container, Location, null, ReturnType, modifiers);
3127 builder = dllimport_attribute.DefinePInvokeMethod (
3128 ec, container.TypeBuilder, method_name, flags,
3129 ReturnType, ParameterTypes);
3131 builder = container.TypeBuilder.DefineMethod (
3132 method_name, flags, CallingConventions,
3133 ReturnType, ParameterTypes);
3135 if (builder == null)
3138 if (IsImplementing) {
3140 // clear the pending implemntation flag
3142 if (member is Indexer) {
3143 container.Pending.ImplementIndexer (
3144 member.InterfaceType, builder, ReturnType,
3145 ParameterTypes, true);
3147 container.Pending.ImplementMethod (
3148 member.InterfaceType, name, ReturnType,
3149 ParameterTypes, member.IsExplicitImpl);
3151 if (member.IsExplicitImpl)
3152 container.TypeBuilder.DefineMethodOverride (
3153 builder, implementing);
3156 if (!TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes)) {
3157 Report.Error (111, Location,
3158 "Class `" + container.Name +
3159 "' already contains a definition with the " +
3160 "same return value and parameter types as the " +
3161 "'get' method of property `" + member.Name + "'");
3165 TypeManager.AddMethod (builder, this);
3173 public virtual void Emit (TypeContainer container, Block block, object kind)
3178 if ((flags & MethodAttributes.PinvokeImpl) == 0)
3179 ig = builder.GetILGenerator ();
3183 ec = new EmitContext (container, Location, ig, ReturnType, modifiers);
3185 if (OptAttributes != null)
3186 Attribute.ApplyAttributes (ec, builder, kind, OptAttributes);
3188 if (member is MethodCore)
3189 ((MethodCore) member).LabelParameters (ec, MethodBuilder, OptAttributes);
3192 // abstract or extern methods have no bodies
3194 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
3195 if (block == null) {
3196 SymbolWriter sw = CodeGen.SymbolWriter;
3198 if ((sw != null) && ((modifiers & Modifiers.EXTERN) != 0)) {
3199 sw.OpenMethod (container, MethodBuilder, Location, Location);
3207 // abstract or extern methods have no bodies.
3209 if ((modifiers & Modifiers.ABSTRACT) != 0)
3211 500, Location, "Abstract method `" +
3212 TypeManager.CSharpSignature (builder) +
3213 "' can not have a body");
3215 if ((modifiers & Modifiers.EXTERN) != 0)
3217 179, Location, "External method `" +
3218 TypeManager.CSharpSignature (builder) +
3219 "' can not have a body");
3225 // Methods must have a body unless they're extern or abstract
3227 if (block == null) {
3229 501, Location, "Method `" +
3230 TypeManager.CSharpSignature (builder) +
3231 "' must declare a body since it is not marked " +
3232 "abstract or extern");
3237 // Handle destructors specially
3239 // FIXME: This code generates buggy code
3241 if (member.Name == "Finalize" && ReturnType == TypeManager.void_type)
3242 EmitDestructor (ec, block);
3244 SymbolWriter sw = CodeGen.SymbolWriter;
3246 if ((sw != null) && !Location.IsNull (Location) &&
3247 !Location.IsNull (block.EndLocation)) {
3248 sw.OpenMethod (container, MethodBuilder, Location, block.EndLocation);
3250 ec.EmitTopBlock (block, ParameterInfo, Location);
3254 ec.EmitTopBlock (block, ParameterInfo, Location);
3258 void EmitDestructor (EmitContext ec, Block block)
3260 ILGenerator ig = ec.ig;
3262 Label finish = ig.DefineLabel ();
3263 bool old_in_try = ec.InTry;
3265 ig.BeginExceptionBlock ();
3267 ec.ReturnLabel = finish;
3268 ec.HasReturnLabel = true;
3269 ec.EmitTopBlock (block, null, Location);
3270 ec.InTry = old_in_try;
3272 // ig.MarkLabel (finish);
3273 bool old_in_finally = ec.InFinally;
3274 ec.InFinally = true;
3275 ig.BeginFinallyBlock ();
3277 if (ec.ContainerType.BaseType != null) {
3278 Expression member_lookup = Expression.MemberLookup (
3279 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
3280 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, Location);
3282 if (member_lookup != null){
3283 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
3285 ig.Emit (OpCodes.Ldarg_0);
3286 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
3289 ec.InFinally = old_in_finally;
3291 ig.EndExceptionBlock ();
3292 //ig.MarkLabel (ec.ReturnLabel);
3293 ig.Emit (OpCodes.Ret);
3297 abstract public class MemberBase : MemberCore {
3298 public Expression Type;
3299 public readonly Attributes OptAttributes;
3301 protected MethodAttributes flags;
3304 // The "short" name of this property / indexer / event. This is the
3305 // name without the explicit interface.
3307 public string ShortName;
3310 // The type of this property / indexer / event
3312 public Type MemberType;
3315 // If true, this is an explicit interface implementation
3317 public bool IsExplicitImpl = false;
3320 // The name of the interface we are explicitly implementing
3322 public string ExplicitInterfaceName = null;
3325 // If true, the interface type we are explicitly implementing
3327 public Type InterfaceType = null;
3330 // The method we're overriding if this is an override method.
3332 protected MethodInfo parent_method = null;
3333 public MethodInfo ParentMethod {
3335 return parent_method;
3340 // The constructor is only exposed to our children
3342 protected MemberBase (Expression type, int mod, int allowed_mod, string name,
3343 Attributes attrs, Location loc)
3347 ModFlags = Modifiers.Check (allowed_mod, mod, Modifiers.PRIVATE, loc);
3348 OptAttributes = attrs;
3351 protected virtual bool CheckBase (TypeContainer container)
3353 if ((container is Struct) || (RootContext.WarningLevel > 3)){
3354 if ((ModFlags & Modifiers.PROTECTED) != 0 && (container.ModFlags & Modifiers.SEALED) != 0){
3355 if (container is Struct){
3356 Report.Error (666, Location, "Protected member in struct declaration");
3359 Report.Warning (628, Location, "Member " + container.MakeName (Name) + " protected in sealed class");
3365 protected virtual bool CheckParameters (TypeContainer container, Type [] parameters)
3369 foreach (Type partype in parameters){
3370 if (partype.IsPointer){
3371 if (!UnsafeOK (container))
3373 if (!TypeManager.VerifyUnManaged (partype.GetElementType (), Location))
3377 if (container.AsAccessible (partype, ModFlags))
3380 if (this is Indexer)
3381 Report.Error (55, Location,
3382 "Inconsistent accessibility: parameter type `" +
3383 TypeManager.CSharpName (partype) + "' is less " +
3384 "accessible than indexer `" + Name + "'");
3386 Report.Error (51, Location,
3387 "Inconsistent accessibility: parameter type `" +
3388 TypeManager.CSharpName (partype) + "' is less " +
3389 "accessible than method `" + Name + "'");
3396 protected virtual bool DoDefine (TypeContainer container)
3401 if (!container.MethodModifiersValid (ModFlags, Name, Location))
3404 flags = Modifiers.MethodAttr (ModFlags);
3406 // Lookup Type, verify validity
3407 MemberType = container.ResolveType (Type, false, Location);
3408 if (MemberType == null)
3411 if ((container.ModFlags & Modifiers.SEALED) != 0){
3412 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
3413 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
3418 // verify accessibility
3419 if (!container.AsAccessible (MemberType, ModFlags)) {
3420 if (this is Property)
3421 Report.Error (53, Location,
3422 "Inconsistent accessibility: property type `" +
3423 TypeManager.CSharpName (MemberType) + "' is less " +
3424 "accessible than property `" + Name + "'");
3425 else if (this is Indexer)
3426 Report.Error (54, Location,
3427 "Inconsistent accessibility: indexer return type `" +
3428 TypeManager.CSharpName (MemberType) + "' is less " +
3429 "accessible than indexer `" + Name + "'");
3430 else if (this is Method)
3431 Report.Error (50, Location,
3432 "Inconsistent accessibility: return type `" +
3433 TypeManager.CSharpName (MemberType) + "' is less " +
3434 "accessible than method `" + Name + "'");
3436 Report.Error (52, Location,
3437 "Inconsistent accessibility: field type `" +
3438 TypeManager.CSharpName (MemberType) + "' is less " +
3439 "accessible than field `" + Name + "'");
3443 if (MemberType.IsPointer && !UnsafeOK (container))
3447 // Check for explicit interface implementation
3449 if ((ExplicitInterfaceName == null) && (Name.IndexOf (".") != -1)){
3450 int pos = Name.LastIndexOf (".");
3452 ExplicitInterfaceName = Name.Substring (0, pos);
3453 ShortName = Name.Substring (pos + 1);
3457 if (ExplicitInterfaceName != null) {
3458 InterfaceType = RootContext.LookupType (
3459 container, ExplicitInterfaceName, false, Location);
3460 if (InterfaceType == null)
3463 // Compute the full name that we need to export.
3464 Name = InterfaceType.FullName + "." + ShortName;
3466 if (!container.VerifyImplements (InterfaceType, ShortName, Name, Location))
3469 IsExplicitImpl = true;
3471 IsExplicitImpl = false;
3478 // Fields and Events both generate FieldBuilders, we use this to share
3479 // their common bits. This is also used to flag usage of the field
3481 abstract public class FieldBase : MemberBase {
3482 public FieldBuilder FieldBuilder;
3483 public Status status;
3486 public enum Status : byte { ASSIGNED = 1, USED = 2 }
3489 // The constructor is only exposed to our children
3491 protected FieldBase (Expression type, int mod, int allowed_mod, string name,
3492 object init, Attributes attrs, Location loc)
3493 : base (type, mod, allowed_mod, name, attrs, loc)
3499 // Whether this field has an initializer.
3501 public bool HasInitializer {
3503 return init != null;
3507 protected readonly Object init;
3509 Expression init_expr;
3510 bool init_expr_initialized = false;
3513 // Resolves and returns the field initializer.
3515 public Expression GetInitializerExpression (EmitContext ec)
3517 if (init_expr_initialized)
3521 if (init is Expression)
3522 e = (Expression) init;
3524 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
3526 ec.IsFieldInitializer = true;
3527 e = e.DoResolve (ec);
3528 ec.IsFieldInitializer = false;
3531 init_expr_initialized = true;
3538 // The Field class is used to represents class/struct fields during parsing.
3540 public class Field : FieldBase {
3542 // Modifiers allowed in a class declaration
3544 const int AllowedModifiers =
3547 Modifiers.PROTECTED |
3548 Modifiers.INTERNAL |
3551 Modifiers.VOLATILE |
3555 public Field (Expression type, int mod, string name, Object expr_or_array_init,
3556 Attributes attrs, Location loc)
3557 : base (type, mod, AllowedModifiers, name, expr_or_array_init, attrs, loc)
3561 public override bool Define (TypeContainer container)
3563 Type t = container.ResolveType (Type, false, Location);
3568 CheckBase (container);
3570 if (!container.AsAccessible (t, ModFlags)) {
3571 Report.Error (52, Location,
3572 "Inconsistent accessibility: field type `" +
3573 TypeManager.CSharpName (t) + "' is less " +
3574 "accessible than field `" + Name + "'");
3578 if (t.IsPointer && !UnsafeOK (container))
3581 if (RootContext.WarningLevel > 1){
3582 Type ptype = container.TypeBuilder.BaseType;
3584 // ptype is only null for System.Object while compiling corlib.
3586 TypeContainer.FindMembers (
3587 ptype, MemberTypes.Method,
3588 BindingFlags.Public |
3589 BindingFlags.Static | BindingFlags.Instance,
3590 System.Type.FilterName, Name);
3594 if ((ModFlags & Modifiers.VOLATILE) != 0){
3598 if (TypeManager.IsEnumType (vt))
3599 vt = TypeManager.EnumToUnderlying (t);
3601 if (!((vt == TypeManager.bool_type) ||
3602 (vt == TypeManager.sbyte_type) ||
3603 (vt == TypeManager.byte_type) ||
3604 (vt == TypeManager.short_type) ||
3605 (vt == TypeManager.ushort_type) ||
3606 (vt == TypeManager.int32_type) ||
3607 (vt == TypeManager.uint32_type) ||
3608 (vt == TypeManager.char_type) ||
3609 (vt == TypeManager.float_type))){
3611 677, Location, container.MakeName (Name) +
3612 " A volatile field can not be of type `" +
3613 TypeManager.CSharpName (vt) + "'");
3618 if ((ModFlags & Modifiers.READONLY) != 0){
3621 "A field can not be both volatile and readonly");
3626 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
3628 if (container is Struct &&
3629 ((fa & FieldAttributes.Static) == 0) &&
3630 t == container.TypeBuilder &&
3631 !TypeManager.IsBuiltinType (t)){
3632 Report.Error (523, Location, "Struct member `" + container.Name + "." + Name +
3633 "' causes a cycle in the structure layout");
3637 FieldBuilder = container.TypeBuilder.DefineField (
3638 Name, t, Modifiers.FieldAttr (ModFlags));
3640 TypeManager.RegisterFieldBase (FieldBuilder, this);
3644 public void Emit (TypeContainer tc)
3646 EmitContext ec = new EmitContext (tc, Location, null,
3647 FieldBuilder.FieldType, ModFlags);
3649 Attribute.ApplyAttributes (ec, FieldBuilder, this, OptAttributes);
3654 // `set' and `get' accessors are represented with an Accessor.
3656 public class Accessor {
3658 // Null if the accessor is empty, or a Block if not
3661 public Attributes OptAttributes;
3663 public Accessor (Block b, Attributes attrs)
3666 OptAttributes = attrs;
3671 // Properties and Indexers both generate PropertyBuilders, we use this to share
3672 // their common bits.
3674 abstract public class PropertyBase : MethodCore {
3675 public Accessor Get, Set;
3676 public PropertyBuilder PropertyBuilder;
3677 public MethodBuilder GetBuilder, SetBuilder;
3678 public MethodData GetData, SetData;
3680 protected EmitContext ec;
3682 public PropertyBase (Expression type, string name, int mod_flags, int allowed_mod,
3683 Parameters parameters, Accessor get_block, Accessor set_block,
3684 Attributes attrs, Location loc)
3685 : base (type, mod_flags, allowed_mod, name, attrs, parameters, loc)
3691 protected override bool DoDefine (TypeContainer container)
3693 if (!base.DoDefine (container))
3696 ec = new EmitContext (container, Location, null, MemberType, ModFlags);
3702 // Checks our base implementation if any
3704 protected override bool CheckBase (TypeContainer container)
3706 base.CheckBase (container);
3708 // Check whether arguments were correct.
3709 if (!DoDefineParameters (container))
3716 MethodSignature ms, base_ms;
3717 if (this is Indexer) {
3718 string name, base_name;
3720 report_name = "this";
3721 name = TypeManager.IndexerPropertyName (container.TypeBuilder);
3722 ms = new MethodSignature (name, null, ParameterTypes);
3723 base_name = TypeManager.IndexerPropertyName (container.TypeBuilder.BaseType);
3724 base_ms = new MethodSignature (base_name, null, ParameterTypes);
3727 ms = base_ms = new MethodSignature (Name, null, ParameterTypes);
3731 // Verify if the parent has a type with the same name, and then
3732 // check whether we have to create a new slot for it or not.
3734 Type ptype = container.TypeBuilder.BaseType;
3736 // ptype is only null for System.Object while compiling corlib.
3737 if (ptype == null) {
3738 if ((ModFlags & Modifiers.NEW) != 0)
3739 WarningNotHiding (container);
3744 MemberList props_this;
3746 props_this = TypeContainer.FindMembers (
3747 container.TypeBuilder, MemberTypes.Property,
3748 BindingFlags.NonPublic | BindingFlags.Public |
3749 BindingFlags.Static | BindingFlags.Instance |
3750 BindingFlags.DeclaredOnly,
3751 MethodSignature.method_signature_filter, ms);
3753 if (props_this.Count > 0) {
3754 Report.Error (111, Location, "Class `" + container.Name + "' " +
3755 "already defines a member called `" + report_name + "' " +
3756 "with the same parameter types");
3760 MemberList mi_props;
3762 mi_props = TypeContainer.FindMembers (
3763 ptype, MemberTypes.Property,
3764 BindingFlags.NonPublic | BindingFlags.Public |
3765 BindingFlags.Instance | BindingFlags.Static,
3766 MethodSignature.inheritable_method_signature_filter, base_ms);
3768 if (mi_props.Count > 0){
3769 PropertyInfo parent_property = (PropertyInfo) mi_props [0];
3770 string name = parent_property.DeclaringType.Name + "." +
3771 parent_property.Name;
3773 MethodInfo get, set, parent_method;
3774 get = parent_property.GetGetMethod (true);
3775 set = parent_property.GetSetMethod (true);
3778 parent_method = get;
3779 else if (set != null)
3780 parent_method = set;
3782 throw new Exception ("Internal error!");
3784 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
3787 if ((ModFlags & Modifiers.NEW) == 0) {
3788 Type parent_type = TypeManager.TypeToCoreType (
3789 parent_property.PropertyType);
3791 if (parent_type != MemberType) {
3793 508, Location, container.MakeName (Name) + ": cannot " +
3794 "change return type when overriding " +
3795 "inherited member " + name);
3800 if ((ModFlags & Modifiers.NEW) != 0)
3801 WarningNotHiding (container);
3803 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3804 if (this is Indexer)
3805 Report.Error (115, Location,
3806 container.MakeName (Name) +
3807 " no suitable indexers found to override");
3809 Report.Error (115, Location,
3810 container.MakeName (Name) +
3811 " no suitable properties found to override");
3818 public void Emit (TypeContainer tc)
3821 // The PropertyBuilder can be null for explicit implementations, in that
3822 // case, we do not actually emit the ".property", so there is nowhere to
3823 // put the attribute
3825 if (PropertyBuilder != null)
3826 Attribute.ApplyAttributes (ec, PropertyBuilder, this, OptAttributes);
3828 if (GetData != null) {
3829 GetData.Emit (tc, Get.Block, Get);
3833 if (SetData != null) {
3834 SetData.Emit (tc, Set.Block, Set);
3840 public class Property : PropertyBase {
3841 const int AllowedModifiers =
3844 Modifiers.PROTECTED |
3845 Modifiers.INTERNAL |
3849 Modifiers.OVERRIDE |
3850 Modifiers.ABSTRACT |
3855 public Property (Expression type, string name, int mod_flags,
3856 Accessor get_block, Accessor set_block,
3857 Attributes attrs, Location loc)
3858 : base (type, name, mod_flags, AllowedModifiers,
3859 Parameters.EmptyReadOnlyParameters,
3860 get_block, set_block, attrs, loc)
3864 public override bool Define (TypeContainer container)
3866 if (!DoDefine (container))
3869 if (!CheckBase (container))
3872 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
3875 Type [] parameters = TypeManager.NoTypes;
3877 InternalParameters ip = new InternalParameters (
3878 container, Parameters.EmptyReadOnlyParameters);
3880 GetData = new MethodData (this, "get", MemberType,
3881 parameters, ip, CallingConventions.Standard,
3882 Get.OptAttributes, ModFlags, flags, false);
3884 if (!GetData.Define (container))
3887 GetBuilder = GetData.MethodBuilder;
3891 Type [] parameters = new Type [1];
3892 parameters [0] = MemberType;
3894 Parameter [] parms = new Parameter [1];
3895 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
3896 InternalParameters ip = new InternalParameters (
3897 container, new Parameters (parms, null, Location));
3899 SetData = new MethodData (this, "set", TypeManager.void_type,
3900 parameters, ip, CallingConventions.Standard,
3901 Set.OptAttributes, ModFlags, flags, false);
3903 if (!SetData.Define (container))
3906 SetBuilder = SetData.MethodBuilder;
3907 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
3910 // FIXME - PropertyAttributes.HasDefault ?
3912 PropertyAttributes prop_attr =
3913 PropertyAttributes.RTSpecialName |
3914 PropertyAttributes.SpecialName;
3916 if (!IsExplicitImpl){
3917 PropertyBuilder = container.TypeBuilder.DefineProperty (
3918 Name, prop_attr, MemberType, null);
3921 PropertyBuilder.SetGetMethod (GetBuilder);
3924 PropertyBuilder.SetSetMethod (SetBuilder);
3927 // HACK for the reasons exposed above
3929 if (!TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder)) {
3932 "Class `" + container.Name +
3933 "' already contains a definition for the property `" +
3943 /// Gigantic workaround for lameness in SRE follows :
3944 /// This class derives from EventInfo and attempts to basically
3945 /// wrap around the EventBuilder so that FindMembers can quickly
3946 /// return this in it search for members
3948 public class MyEventBuilder : EventInfo {
3951 // We use this to "point" to our Builder which is
3952 // not really a MemberInfo
3954 EventBuilder MyBuilder;
3957 // We "catch" and wrap these methods
3959 MethodInfo raise, remove, add;
3961 EventAttributes attributes;
3962 Type declaring_type, reflected_type, event_type;
3967 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
3969 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
3971 // And now store the values in our own fields.
3973 declaring_type = type_builder;
3975 reflected_type = type_builder;
3977 attributes = event_attr;
3980 this.event_type = event_type;
3984 // Methods that you have to override. Note that you only need
3985 // to "implement" the variants that take the argument (those are
3986 // the "abstract" methods, the others (GetAddMethod()) are
3989 public override MethodInfo GetAddMethod (bool nonPublic)
3994 public override MethodInfo GetRemoveMethod (bool nonPublic)
3999 public override MethodInfo GetRaiseMethod (bool nonPublic)
4005 // These methods make "MyEventInfo" look like a Builder
4007 public void SetRaiseMethod (MethodBuilder raiseMethod)
4009 raise = raiseMethod;
4010 MyBuilder.SetRaiseMethod (raiseMethod);
4013 public void SetRemoveOnMethod (MethodBuilder removeMethod)
4015 remove = removeMethod;
4016 MyBuilder.SetRemoveOnMethod (removeMethod);
4019 public void SetAddOnMethod (MethodBuilder addMethod)
4022 MyBuilder.SetAddOnMethod (addMethod);
4025 public void SetCustomAttribute (CustomAttributeBuilder cb)
4027 MyBuilder.SetCustomAttribute (cb);
4030 public override object [] GetCustomAttributes (bool inherit)
4032 // FIXME : There's nothing which can be seemingly done here because
4033 // we have no way of getting at the custom attribute objects of the
4038 public override object [] GetCustomAttributes (Type t, bool inherit)
4040 // FIXME : Same here !
4044 public override bool IsDefined (Type t, bool b)
4049 public override EventAttributes Attributes {
4055 public override string Name {
4061 public override Type DeclaringType {
4063 return declaring_type;
4067 public override Type ReflectedType {
4069 return reflected_type;
4073 public Type EventType {
4079 public void SetUsed ()
4081 if (my_event != null)
4082 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
4086 public class Event : FieldBase {
4087 const int AllowedModifiers =
4090 Modifiers.PROTECTED |
4091 Modifiers.INTERNAL |
4096 Modifiers.OVERRIDE |
4100 public readonly Accessor Add;
4101 public readonly Accessor Remove;
4102 public MyEventBuilder EventBuilder;
4104 MethodBuilder AddBuilder, RemoveBuilder;
4105 MethodData AddData, RemoveData;
4107 public Event (Expression type, string name, Object init, int mod, Accessor add,
4108 Accessor remove, Attributes attrs, Location loc)
4109 : base (type, mod, AllowedModifiers, name, init, attrs, loc)
4115 public override bool Define (TypeContainer container)
4117 EventAttributes e_attr = EventAttributes.RTSpecialName | EventAttributes.SpecialName;
4119 if (!DoDefine (container))
4122 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
4123 Report.Error (74, Location, "'" + container.Name + "." + Name +
4124 "': abstract event can not have an initializer");
4128 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
4129 Report.Error (66, Location, "'" + container.Name + "." + Name +
4130 "' : event must be of a delegate type");
4134 Type [] parameter_types = new Type [1];
4135 parameter_types [0] = MemberType;
4137 Parameter [] parms = new Parameter [1];
4138 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
4139 InternalParameters ip = new InternalParameters (
4140 container, new Parameters (parms, null, Location));
4142 if (!CheckBase (container))
4146 // Now define the accessors
4148 AddData = new MethodData (this, "add", TypeManager.void_type,
4149 parameter_types, ip, CallingConventions.Standard,
4150 (Add != null) ? Add.OptAttributes : null,
4151 ModFlags, flags, false);
4153 if (!AddData.Define (container))
4156 AddBuilder = AddData.MethodBuilder;
4157 AddBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4159 RemoveData = new MethodData (this, "remove", TypeManager.void_type,
4160 parameter_types, ip, CallingConventions.Standard,
4161 (Remove != null) ? Remove.OptAttributes : null,
4162 ModFlags, flags, false);
4164 if (!RemoveData.Define (container))
4167 RemoveBuilder = RemoveData.MethodBuilder;
4168 RemoveBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4170 if (!IsExplicitImpl){
4171 EventBuilder = new MyEventBuilder (this,
4172 container.TypeBuilder, Name, e_attr, MemberType);
4174 if (Add == null && Remove == null) {
4175 FieldBuilder = container.TypeBuilder.DefineField (
4177 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
4178 TypeManager.RegisterPrivateFieldOfEvent (
4179 (EventInfo) EventBuilder, FieldBuilder);
4180 TypeManager.RegisterFieldBase (FieldBuilder, this);
4183 EventBuilder.SetAddOnMethod (AddBuilder);
4184 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
4186 if (!TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder)) {
4187 Report.Error (111, Location,
4188 "Class `" + container.Name +
4189 "' already contains a definition for the event `" +
4198 void EmitDefaultMethod (EmitContext ec, bool is_add)
4200 ILGenerator ig = ec.ig;
4201 MethodInfo method = null;
4204 method = TypeManager.delegate_combine_delegate_delegate;
4206 method = TypeManager.delegate_remove_delegate_delegate;
4208 if ((ModFlags & Modifiers.STATIC) != 0) {
4209 ig.Emit (OpCodes.Ldsfld, (FieldInfo) FieldBuilder);
4210 ig.Emit (OpCodes.Ldarg_0);
4211 ig.Emit (OpCodes.Call, method);
4212 ig.Emit (OpCodes.Castclass, MemberType);
4213 ig.Emit (OpCodes.Stsfld, (FieldInfo) FieldBuilder);
4215 ig.Emit (OpCodes.Ldarg_0);
4216 ig.Emit (OpCodes.Ldarg_0);
4217 ig.Emit (OpCodes.Ldfld, (FieldInfo) FieldBuilder);
4218 ig.Emit (OpCodes.Ldarg_1);
4219 ig.Emit (OpCodes.Call, method);
4220 ig.Emit (OpCodes.Castclass, MemberType);
4221 ig.Emit (OpCodes.Stfld, (FieldInfo) FieldBuilder);
4223 ig.Emit (OpCodes.Ret);
4226 public void Emit (TypeContainer tc)
4230 ec = new EmitContext (tc, Location, null, MemberType, ModFlags);
4231 Attribute.ApplyAttributes (ec, EventBuilder, this, OptAttributes);
4234 AddData.Emit (tc, Add.Block, Add);
4237 ILGenerator ig = AddData.MethodBuilder.GetILGenerator ();
4238 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
4239 EmitDefaultMethod (ec, true);
4242 if (Remove != null) {
4243 RemoveData.Emit (tc, Remove.Block, Remove);
4244 Remove.Block = null;
4246 ILGenerator ig = RemoveData.MethodBuilder.GetILGenerator ();
4247 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
4248 EmitDefaultMethod (ec, false);
4255 // FIXME: This does not handle:
4257 // int INTERFACENAME [ args ]
4262 // int this [ args ]
4264 public class Indexer : PropertyBase {
4266 const int AllowedModifiers =
4269 Modifiers.PROTECTED |
4270 Modifiers.INTERNAL |
4274 Modifiers.OVERRIDE |
4279 public string IndexerName;
4280 public string InterfaceIndexerName;
4283 // Are we implementing an interface ?
4285 bool IsImplementing = false;
4287 public Indexer (Expression type, string int_type, int flags, Parameters parameters,
4288 Accessor get_block, Accessor set_block, Attributes attrs, Location loc)
4289 : base (type, "", flags, AllowedModifiers, parameters, get_block, set_block,
4292 ExplicitInterfaceName = int_type;
4295 public override bool Define (TypeContainer container)
4297 PropertyAttributes prop_attr =
4298 PropertyAttributes.RTSpecialName |
4299 PropertyAttributes.SpecialName;
4301 if (!DoDefine (container))
4304 IndexerName = Attribute.ScanForIndexerName (ec, OptAttributes);
4305 if (IndexerName == null)
4306 IndexerName = "Item";
4307 else if (IsExplicitImpl)
4308 Report.Error (592, Location,
4309 "Attribute 'IndexerName' is not valid on this declaration " +
4310 "type. It is valid on `property' declarations only.");
4312 ShortName = IndexerName;
4313 if (IsExplicitImpl) {
4314 InterfaceIndexerName = TypeManager.IndexerPropertyName (InterfaceType);
4315 Name = InterfaceType.FullName + "." + IndexerName;
4317 InterfaceIndexerName = IndexerName;
4321 if (!CheckBase (container))
4324 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
4326 InternalParameters ip = new InternalParameters (container, Parameters);
4328 GetData = new MethodData (this, "get", MemberType,
4329 ParameterTypes, ip, CallingConventions.Standard,
4330 Get.OptAttributes, ModFlags, flags, false);
4332 if (!GetData.Define (container))
4335 GetBuilder = GetData.MethodBuilder;
4339 int top = ParameterTypes.Length;
4340 Type [] set_pars = new Type [top + 1];
4341 ParameterTypes.CopyTo (set_pars, 0);
4342 set_pars [top] = MemberType;
4344 Parameter [] fixed_parms = Parameters.FixedParameters;
4346 if (fixed_parms == null){
4347 throw new Exception ("We currently do not support only array arguments in an indexer at: " + Location);
4348 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4349 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4351 // Here is the problem: the `value' parameter has
4352 // to come *after* the array parameter in the declaration
4354 // X (object [] x, Type value)
4357 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4358 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4362 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
4365 fixed_parms.CopyTo (tmp, 0);
4366 tmp [fixed_parms.Length] = new Parameter (
4367 Type, "value", Parameter.Modifier.NONE, null);
4369 Parameters set_formal_params = new Parameters (tmp, null, Location);
4371 InternalParameters ip = new InternalParameters (container, set_formal_params);
4373 SetData = new MethodData (this, "set", TypeManager.void_type,
4374 set_pars, ip, CallingConventions.Standard,
4375 Set.OptAttributes, ModFlags, flags, false);
4377 if (!SetData.Define (container))
4380 SetBuilder = SetData.MethodBuilder;
4384 // Now name the parameters
4386 Parameter [] p = Parameters.FixedParameters;
4390 for (i = 0; i < p.Length; ++i) {
4392 GetBuilder.DefineParameter (
4393 i + 1, p [i].Attributes, p [i].Name);
4396 SetBuilder.DefineParameter (
4397 i + 1, p [i].Attributes, p [i].Name);
4401 SetBuilder.DefineParameter (
4402 i + 1, ParameterAttributes.None, "value");
4404 if (i != ParameterTypes.Length) {
4405 Parameter array_param = Parameters.ArrayParameter;
4406 SetBuilder.DefineParameter (
4407 i + 1, array_param.Attributes, array_param.Name);
4411 if (GetData != null)
4412 IsImplementing = GetData.IsImplementing;
4413 else if (SetData != null)
4414 IsImplementing = SetData.IsImplementing;
4417 // Define the PropertyBuilder if one of the following conditions are met:
4418 // a) we're not implementing an interface indexer.
4419 // b) the indexer has a different IndexerName and this is no
4420 // explicit interface implementation.
4422 if (!IsExplicitImpl) {
4423 PropertyBuilder = container.TypeBuilder.DefineProperty (
4424 IndexerName, prop_attr, MemberType, ParameterTypes);
4426 if (GetData != null)
4427 PropertyBuilder.SetGetMethod (GetBuilder);
4429 if (SetData != null)
4430 PropertyBuilder.SetSetMethod (SetBuilder);
4432 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder,
4440 public class Operator : MemberCore {
4442 const int AllowedModifiers =
4448 const int RequiredModifiers =
4452 public enum OpType : byte {
4462 // Unary and Binary operators
4485 // Implicit and Explicit
4490 public readonly OpType OperatorType;
4491 public readonly Expression ReturnType;
4492 public readonly Expression FirstArgType, SecondArgType;
4493 public readonly string FirstArgName, SecondArgName;
4495 public Attributes OptAttributes;
4496 public MethodBuilder OperatorMethodBuilder;
4498 public string MethodName;
4499 public Method OperatorMethod;
4501 public Operator (OpType type, Expression ret_type, int flags,
4502 Expression arg1type, string arg1name,
4503 Expression arg2type, string arg2name,
4504 Block block, Attributes attrs, Location loc)
4507 OperatorType = type;
4508 ReturnType = ret_type;
4509 ModFlags = Modifiers.Check (AllowedModifiers, flags, Modifiers.PUBLIC, loc);
4510 FirstArgType = arg1type;
4511 FirstArgName = arg1name;
4512 SecondArgType = arg2type;
4513 SecondArgName = arg2name;
4515 OptAttributes = attrs;
4518 string Prototype (TypeContainer container)
4520 return container.Name + ".operator " + OperatorType + " (" + FirstArgType + "," +
4521 SecondArgType + ")";
4524 public override bool Define (TypeContainer container)
4527 MethodName = "op_" + OperatorType;
4529 if (SecondArgType != null)
4532 Parameter [] param_list = new Parameter [length];
4534 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
4537 "User defined operators `" +
4538 Prototype (container) +
4539 "' must be declared static and public");
4543 param_list[0] = new Parameter (FirstArgType, FirstArgName,
4544 Parameter.Modifier.NONE, null);
4545 if (SecondArgType != null)
4546 param_list[1] = new Parameter (SecondArgType, SecondArgName,
4547 Parameter.Modifier.NONE, null);
4549 OperatorMethod = new Method (ReturnType, ModFlags, MethodName,
4550 new Parameters (param_list, null, Location),
4551 OptAttributes, Location);
4553 OperatorMethod.IsOperator = true;
4554 OperatorMethod.Define (container);
4556 if (OperatorMethod.MethodBuilder == null)
4559 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
4561 Type [] param_types = OperatorMethod.ParameterTypes;
4562 Type declaring_type = OperatorMethodBuilder.DeclaringType;
4563 Type return_type = OperatorMethod.GetReturnType ();
4564 Type first_arg_type = param_types [0];
4566 // Rules for conversion operators
4568 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
4569 if (first_arg_type == return_type && first_arg_type == declaring_type){
4572 "User-defined conversion cannot take an object of the " +
4573 "enclosing type and convert to an object of the enclosing" +
4578 if (first_arg_type != declaring_type && return_type != declaring_type){
4581 "User-defined conversion must convert to or from the " +
4586 if (first_arg_type == TypeManager.object_type ||
4587 return_type == TypeManager.object_type){
4590 "User-defined conversion cannot convert to or from " +
4595 if (first_arg_type.IsInterface || return_type.IsInterface){
4598 "User-defined conversion cannot convert to or from an " +
4603 if (first_arg_type.IsSubclassOf (return_type) ||
4604 return_type.IsSubclassOf (first_arg_type)){
4607 "User-defined conversion cannot convert between types " +
4608 "that derive from each other");
4611 } else if (SecondArgType == null) {
4612 // Checks for Unary operators
4614 if (first_arg_type != declaring_type){
4617 "The parameter of a unary operator must be the " +
4622 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
4623 if (return_type != declaring_type){
4626 "The parameter and return type for ++ and -- " +
4627 "must be the containing type");
4633 if (OperatorType == OpType.True || OperatorType == OpType.False) {
4634 if (return_type != TypeManager.bool_type){
4637 "The return type of operator True or False " +
4644 // Checks for Binary operators
4646 if (first_arg_type != declaring_type &&
4647 param_types [1] != declaring_type){
4650 "One of the parameters of a binary operator must " +
4651 "be the containing type");
4659 public void Emit (TypeContainer container)
4661 EmitContext ec = new EmitContext (container, Location, null, null, ModFlags);
4662 Attribute.ApplyAttributes (ec, OperatorMethodBuilder, this, OptAttributes);
4665 // abstract or extern methods have no bodies
4667 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
4670 OperatorMethod.Block = Block;
4671 OperatorMethod.Emit (container);
4675 public static string GetName (OpType ot)
4678 case OpType.LogicalNot:
4680 case OpType.OnesComplement:
4682 case OpType.Increment:
4684 case OpType.Decrement:
4690 case OpType.Addition:
4692 case OpType.Subtraction:
4694 case OpType.UnaryPlus:
4696 case OpType.UnaryNegation:
4698 case OpType.Multiply:
4700 case OpType.Division:
4702 case OpType.Modulus:
4704 case OpType.BitwiseAnd:
4706 case OpType.BitwiseOr:
4708 case OpType.ExclusiveOr:
4710 case OpType.LeftShift:
4712 case OpType.RightShift:
4714 case OpType.Equality:
4716 case OpType.Inequality:
4718 case OpType.GreaterThan:
4720 case OpType.LessThan:
4722 case OpType.GreaterThanOrEqual:
4724 case OpType.LessThanOrEqual:
4726 case OpType.Implicit:
4728 case OpType.Explicit:
4734 public override string ToString ()
4736 Type return_type = OperatorMethod.GetReturnType();
4737 Type [] param_types = OperatorMethod.ParameterTypes;
4739 if (SecondArgType == null)
4740 return String.Format (
4741 "{0} operator {1}({2})",
4742 TypeManager.CSharpName (return_type),
4743 GetName (OperatorType),
4746 return String.Format (
4747 "{0} operator {1}({2}, {3})",
4748 TypeManager.CSharpName (return_type),
4749 GetName (OperatorType),
4750 param_types [0], param_types [1]);
4755 // This is used to compare method signatures
4757 struct MethodSignature {
4759 public Type RetType;
4760 public Type [] Parameters;
4763 /// This delegate is used to extract methods which have the
4764 /// same signature as the argument
4766 public static MemberFilter method_signature_filter;
4769 /// This delegate is used to extract inheritable methods which
4770 /// have the same signature as the argument. By inheritable,
4771 /// this means that we have permissions to override the method
4772 /// from the current assembly and class
4774 public static MemberFilter inheritable_method_signature_filter;
4776 static MethodSignature ()
4778 method_signature_filter = new MemberFilter (MemberSignatureCompare);
4779 inheritable_method_signature_filter = new MemberFilter (
4780 InheritableMemberSignatureCompare);
4783 public MethodSignature (string name, Type ret_type, Type [] parameters)
4788 if (parameters == null)
4789 Parameters = TypeManager.NoTypes;
4791 Parameters = parameters;
4794 public override string ToString ()
4797 if (Parameters.Length != 0){
4798 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
4799 for (int i = 0; i < Parameters.Length; i++){
4800 sb.Append (Parameters [i]);
4801 if (i+1 < Parameters.Length)
4804 pars = sb.ToString ();
4807 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
4810 public override int GetHashCode ()
4812 return Name.GetHashCode ();
4815 public override bool Equals (Object o)
4817 MethodSignature other = (MethodSignature) o;
4819 if (other.Name != Name)
4822 if (other.RetType != RetType)
4825 if (Parameters == null){
4826 if (other.Parameters == null)
4831 if (other.Parameters == null)
4834 int c = Parameters.Length;
4835 if (other.Parameters.Length != c)
4838 for (int i = 0; i < c; i++)
4839 if (other.Parameters [i] != Parameters [i])
4845 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
4847 MethodSignature sig = (MethodSignature) filter_criteria;
4849 if (m.Name != sig.Name)
4853 MethodInfo mi = m as MethodInfo;
4854 PropertyInfo pi = m as PropertyInfo;
4857 ReturnType = mi.ReturnType;
4858 else if (pi != null)
4859 ReturnType = pi.PropertyType;
4864 // we use sig.RetType == null to mean `do not check the
4865 // method return value.
4867 if (sig.RetType != null)
4868 if (ReturnType != sig.RetType)
4873 args = TypeManager.GetArgumentTypes (mi);
4875 args = TypeManager.GetArgumentTypes (pi);
4876 Type [] sigp = sig.Parameters;
4878 if (args.Length != sigp.Length)
4881 for (int i = args.Length; i > 0; ){
4883 if (args [i] != sigp [i])
4890 // This filter should be used when we are requesting methods that
4891 // we want to override.
4893 // This makes a number of assumptions, for example
4894 // that the methods being extracted are of a parent
4895 // class (this means we know implicitly that we are
4896 // being called to find out about members by a derived
4899 static bool InheritableMemberSignatureCompare (MemberInfo m, object filter_criteria)
4902 PropertyInfo pi = m as PropertyInfo;
4905 mi = pi.GetGetMethod (true);
4907 mi = pi.GetSetMethod (true);
4909 mi = m as MethodInfo;
4912 Console.WriteLine ("Nothing found");
4915 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4917 // If only accessible to the current class.
4918 if (prot == MethodAttributes.Private)
4921 if (!MemberSignatureCompare (m, filter_criteria))
4924 // If only accessible to the defining assembly or
4925 if (prot == MethodAttributes.FamANDAssem ||
4926 prot == MethodAttributes.Assembly){
4927 if (m.DeclaringType.Assembly == CodeGen.AssemblyBuilder)
4933 // Anything else (FamOrAssembly and Public) is fine