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 public bool UserDefinedStaticConstructor = 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 bool members_defined;
117 bool members_defined_ok;
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;
139 public TypeContainer ():
140 this (null, null, "", null, new Location (-1)) {
143 public TypeContainer (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
144 : base (ns, parent, name, attrs, l)
146 types = new ArrayList ();
148 base_class_name = null;
151 public AdditionResult AddConstant (Const constant)
154 string basename = constant.Name;
155 string fullname = Name + "." + basename;
157 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
160 if (constants == null)
161 constants = new ArrayList ();
163 constants.Add (constant);
164 DefineName (fullname, constant);
166 return AdditionResult.Success;
169 public AdditionResult AddEnum (Mono.CSharp.Enum e)
173 if ((res = IsValid (e.Basename, e.Name)) != AdditionResult.Success)
177 enums = new ArrayList ();
180 DefineName (e.Name, e);
182 return AdditionResult.Success;
185 public AdditionResult AddClass (Class c)
188 string name = c.Basename;
190 if ((res = IsValid (name, c.Name)) != AdditionResult.Success)
193 DefineName (c.Name, c);
196 return AdditionResult.Success;
199 public AdditionResult AddStruct (Struct s)
202 string name = s.Basename;
204 if ((res = IsValid (name, s.Name)) != AdditionResult.Success)
207 DefineName (s.Name, s);
210 return AdditionResult.Success;
213 public AdditionResult AddDelegate (Delegate d)
216 string name = d.Basename;
218 if ((res = IsValid (name, d.Name)) != AdditionResult.Success)
221 if (delegates == null)
222 delegates = new ArrayList ();
224 DefineName (d.Name, d);
227 return AdditionResult.Success;
230 public AdditionResult AddMethod (Method method)
232 string basename = method.Name;
233 string fullname = Name + "." + basename;
235 Object value = defined_names [fullname];
237 if (value != null && (!(value is Method)))
238 return AdditionResult.NameExists;
240 if (basename == Basename)
241 return AdditionResult.EnclosingClash;
244 methods = new ArrayList ();
246 if (method.Name.IndexOf ('.') != -1)
247 methods.Insert (0, method);
249 methods.Add (method);
252 DefineName (fullname, method);
254 return AdditionResult.Success;
257 public AdditionResult AddConstructor (Constructor c)
259 if (c.Name != Basename)
260 return AdditionResult.NotAConstructor;
262 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
265 UserDefinedStaticConstructor = true;
266 if (default_static_constructor != null)
267 return AdditionResult.MethodExists;
269 default_static_constructor = c;
272 if (default_constructor != null)
273 return AdditionResult.MethodExists;
274 default_constructor = c;
277 if (instance_constructors == null)
278 instance_constructors = new ArrayList ();
280 instance_constructors.Add (c);
283 return AdditionResult.Success;
286 public AdditionResult AddInterface (Interface iface)
289 string name = iface.Basename;
291 if ((res = IsValid (name, iface.Name)) != AdditionResult.Success)
294 if (interfaces == null)
295 interfaces = new ArrayList ();
296 interfaces.Add (iface);
297 DefineName (iface.Name, iface);
299 return AdditionResult.Success;
302 public AdditionResult AddField (Field field)
305 string basename = field.Name;
306 string fullname = Name + "." + basename;
308 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
312 fields = new ArrayList ();
316 if (field.HasInitializer){
317 if ((field.ModFlags & Modifiers.STATIC) != 0){
318 if (initialized_static_fields == null)
319 initialized_static_fields = new ArrayList ();
321 initialized_static_fields.Add (field);
324 if (initialized_fields == null)
325 initialized_fields = new ArrayList ();
327 initialized_fields.Add (field);
331 if ((field.ModFlags & Modifiers.STATIC) == 0)
332 have_nonstatic_fields = true;
334 DefineName (fullname, field);
335 return AdditionResult.Success;
338 public AdditionResult AddProperty (Property prop)
342 if ((res = AddProperty (prop, prop.Name)) != AdditionResult.Success)
345 if (prop.Get != null) {
346 if ((res = AddProperty (prop, "get_" + prop.Name)) != AdditionResult.Success)
350 if (prop.Set != null) {
351 if ((res = AddProperty (prop, "set_" + prop.Name)) != AdditionResult.Success)
355 if (properties == null)
356 properties = new ArrayList ();
358 if (prop.Name.IndexOf ('.') != -1)
359 properties.Insert (0, prop);
361 properties.Add (prop);
363 return AdditionResult.Success;
366 AdditionResult AddProperty (Property prop, string basename)
369 string fullname = Name + "." + basename;
371 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
374 DefineName (fullname, prop);
376 return AdditionResult.Success;
379 public AdditionResult AddEvent (Event e)
382 string basename = e.Name;
383 string fullname = Name + "." + basename;
385 if ((res = IsValid (basename, fullname)) != AdditionResult.Success)
389 events = new ArrayList ();
392 DefineName (fullname, e);
394 return AdditionResult.Success;
397 public void AddIndexer (Indexer i)
399 if (indexers == null)
400 indexers = new ArrayList ();
402 if (i.InterfaceType != null)
403 indexers.Insert (0, i);
408 public AdditionResult AddOperator (Operator op)
410 if (operators == null)
411 operators = new ArrayList ();
415 string basename = op.Name;
416 string fullname = Name + "." + basename;
417 if (!defined_names.Contains (fullname))
419 DefineName (fullname, op);
421 return AdditionResult.Success;
424 public void RegisterOrder (Interface iface)
426 if (interface_order == null)
427 interface_order = new ArrayList ();
429 interface_order.Add (iface);
432 public ArrayList Types {
438 public ArrayList Methods {
444 public ArrayList Constants {
450 public ArrayList Interfaces {
458 return base_class_name;
462 public ArrayList Bases {
472 public ArrayList Fields {
482 public ArrayList InstanceConstructors {
484 return instance_constructors;
488 public ArrayList Properties {
494 public ArrayList Events {
500 public ArrayList Enums {
506 public ArrayList Indexers {
512 public ArrayList Operators {
518 public ArrayList Delegates {
524 public virtual TypeAttributes TypeAttr {
526 return Modifiers.TypeAttr (ModFlags, this);
531 // Emits the instance field initializers
533 public bool EmitFieldInitializers (EmitContext ec)
536 Expression instance_expr;
539 fields = initialized_static_fields;
540 instance_expr = null;
542 fields = initialized_fields;
543 instance_expr = new This (Location.Null).Resolve (ec);
549 foreach (Field f in fields){
550 Expression e = f.GetInitializerExpression (ec);
554 Location l = f.Location;
555 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
556 fe.InstanceExpression = instance_expr;
557 ExpressionStatement a = new Assign (fe, e, l);
559 a = a.ResolveStatement (ec);
563 a.EmitStatement (ec);
570 // Defines the default constructors
572 void DefineDefaultConstructor (bool is_static)
576 // The default constructor is public
577 // If the class is abstract, the default constructor is protected
578 // The default static constructor is private
580 int mods = Modifiers.PUBLIC;
582 mods = Modifiers.STATIC | Modifiers.PRIVATE;
583 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
584 mods = Modifiers.PROTECTED;
586 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
587 new ConstructorBaseInitializer (
588 null, Parameters.EmptyReadOnlyParameters,
594 c.Block = new ToplevelBlock (null, Location);
598 public void ReportStructInitializedInstanceError ()
600 string n = TypeBuilder.FullName;
602 foreach (Field f in initialized_fields){
605 "`" + n + "." + f.Name + "': can not have " +
606 "instance field initializers in structs");
611 /// The pending methods that need to be implemented (interfaces or abstract methods)
613 public PendingImplementation Pending;
616 /// This function computes the Base class and also the
617 /// list of interfaces that the class or struct @c implements.
619 /// The return value is an array (might be null) of
620 /// interfaces implemented (as Types).
622 /// The @parent argument is set to the parent object or null
623 /// if this is `System.Object'.
625 TypeExpr [] GetClassBases (bool is_class, bool is_iface,
626 out TypeExpr parent, out bool error)
628 ArrayList bases = Bases;
634 if (is_class || is_iface)
637 parent = TypeManager.system_valuetype_expr;
641 if (RootContext.StdLib)
642 parent = TypeManager.system_object_expr;
643 else if (Name != "System.Object")
644 parent = TypeManager.system_object_expr;
647 // If we are compiling our runtime,
648 // and we are defining ValueType, then our
649 // parent is `System.Object'.
651 if (!RootContext.StdLib && Name == "System.ValueType")
652 parent = TypeManager.system_object_expr;
659 // Bases should be null if there are no bases at all
664 TypeExpr name = ResolveTypeExpr ((Expression) bases [0], false, Location);
671 if (name is TypeParameterExpr){
674 "Type parameter `{0}' can not be used as a " +
675 "base class or interface", name.Name);
680 if (IsGeneric && name.IsAttribute){
683 "A generic type cannot derive from `{0}' " +
684 "because it is an attribute class", name.Name);
693 parent = TypeManager.system_object_expr;
699 if (name.IsValueType)
700 detail = " (a class can not inherit from a struct/enum)";
702 Report.Error (509, "class `"+ Name +
703 "': Cannot inherit from sealed class `"+
704 name.Name + "'" + detail);
709 if (!parent.CanInheritFrom ()){
710 Report.Error (644, Location,
711 "`{0}' cannot inherit from special class `{1}'",
717 if (!parent.AsAccessible (this, ModFlags))
718 Report.Error (60, Location,
719 "Inconsistent accessibility: base class `" +
720 name.Name + "' is less accessible than class `" +
728 base_class_name = parent.Name;
730 TypeExpr [] ifaces = new TypeExpr [count-start];
732 for (i = start, j = 0; i < count; i++, j++){
733 Expression name = (Expression) bases [i];
734 TypeExpr resolved = ResolveTypeExpr (name, false, Location);
736 if (resolved == null)
739 bases [i] = resolved;
741 if (is_class == false && !resolved.IsInterface){
742 Report.Error (527, "In Struct `" + Name + "', type `"+
743 name +"' is not an interface");
748 if (resolved.IsClass) {
750 Report.Error (527, "In Class `" + Name + "', type `"+
751 name+"' is not an interface");
757 for (int x = 0; x < j; x++) {
758 if (resolved.Equals (ifaces [x])) {
759 Report.Error (528, "`" + name + "' is already listed in interface list");
766 !resolved.AsAccessible (Parent, ModFlags))
767 Report.Error (61, Location,
768 "Inconsistent accessibility: base interface `" +
769 name + "' is less accessible than interface `" +
772 ifaces [j] = resolved;
775 return TypeManager.ExpandInterfaces (ifaces);
778 bool CheckGenericInterfaces (Type[] ifaces)
780 ArrayList already_checked = new ArrayList ();
782 for (int i = 0; i < ifaces.Length; i++) {
783 Type iface = ifaces [i];
784 foreach (Type t in already_checked) {
788 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t))
793 "`{0}' cannot implement both `{1}' and `{2}' " +
794 "because they may unify for some type " +
795 "parameter substitutions",
796 TypeManager.GetFullName (TypeBuilder),
801 already_checked.Add (iface);
810 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
812 public override TypeBuilder DefineType ()
815 bool is_class, is_iface;
817 if (TypeBuilder != null)
824 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
831 if (this is Interface) {
842 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
844 ifaces = GetClassBases (is_class, is_iface, out parent, out error);
850 foreach (TypeParameter type_param in TypeParameters)
851 if (!type_param.Resolve (this)) {
857 if (!is_class && TypeManager.value_type == null)
858 throw new Exception ();
860 TypeAttributes type_attributes = TypeAttr;
863 ConstructedType constructed = parent as ConstructedType;
864 if ((constructed == null) && (parent != null))
865 ptype = parent.ResolveType (ec);
870 if (TypeManager.NamespaceClash (Name, Location)) {
875 ModuleBuilder builder = CodeGen.Module.Builder;
876 TypeBuilder = builder.DefineType (
877 Name, type_attributes, ptype, null);
880 TypeBuilder builder = Parent.DefineType ();
884 TypeBuilder = builder.DefineNestedType (
885 Basename, type_attributes, ptype, null);
888 TypeManager.AddUserType (Name, TypeBuilder, this, ifaces);
891 CurrentType = new ConstructedType (
892 Name, TypeParameters, Location);
894 foreach (TypeParameter type_param in TypeParameters)
895 type_param.Define (TypeBuilder);
898 if (constructed != null) {
899 ptype = constructed.ResolveType (ec);
903 TypeBuilder.SetParent (ptype);
907 foreach (TypeParameter type_param in TypeParameters)
908 type_param.DefineType (ec, TypeBuilder);
912 // Structs with no fields need to have at least one byte.
913 // The right thing would be to set the PackingSize in a DefineType
914 // but there are no functions that allow interfaces *and* the size to
918 if (!is_class && !is_iface && !have_nonstatic_fields){
919 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
920 FieldAttributes.Private);
923 // add interfaces that were not added at type creation
924 if (ifaces != null) {
925 Type[] itypes = new Type [ifaces.Length];
926 for (int i = 0; i < ifaces.Length; i++) {
927 itypes [i] = ifaces [i].ResolveType (ec);
928 if (itypes [i] == null)
935 if (!CheckGenericInterfaces (itypes)) {
940 for (int i = 0; i < ifaces.Length; i++)
941 TypeBuilder.AddInterfaceImplementation (itypes [i]);
945 // Finish the setup for the EmitContext
947 ec.ContainerType = TypeBuilder;
949 if ((parent != null) && parent.IsAttribute) {
950 RootContext.RegisterAttribute (this);
951 TypeManager.RegisterAttrType (TypeBuilder, this);
953 RootContext.RegisterOrder (this);
955 if (Interfaces != null) {
956 foreach (Interface iface in Interfaces)
957 if (iface.DefineType () == null) {
964 foreach (TypeContainer tc in Types)
965 if (tc.DefineType () == null) {
971 if (Delegates != null) {
972 foreach (Delegate d in Delegates)
973 if (d.DefineType () == null) {
980 foreach (Enum en in Enums)
981 if (en.DefineType () == null) {
993 /// Defines the MemberCore objects that are in the `list' Arraylist
995 /// The `defined_names' array contains a list of members defined in
998 static ArrayList remove_list = new ArrayList ();
999 void DefineMembers (ArrayList list, MemberInfo [] defined_names)
1003 remove_list.Clear ();
1005 foreach (MemberCore mc in list){
1007 if (defined_names != null)
1008 idx = Array.BinarySearch (defined_names, mc.Name, mif_compare);
1013 if (RootContext.WarningLevel >= 4){
1014 if ((mc.ModFlags & Modifiers.NEW) != 0)
1015 Warning_KeywordNewNotRequired (mc.Location, mc);
1017 } else if (mc is MethodCore)
1018 ((MethodCore) mc).OverridesSomething = true;
1020 if (!mc.Define (this)){
1021 remove_list.Add (mc);
1028 MemberInfo match = defined_names [idx];
1030 if (match is PropertyInfo && ((mc.ModFlags & Modifiers.OVERRIDE) != 0))
1034 // If we are both methods, let the method resolution emit warnings
1036 if (match is MethodBase && mc is MethodCore)
1039 if ((mc.ModFlags & Modifiers.NEW) == 0) {
1041 if (!(match is EventInfo)) {
1042 Error_EventCanOnlyOverrideEvent (mc.Location, defined_names [idx]);
1046 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
1050 Warning_KeywordNewRequired (mc.Location, defined_names [idx]);
1054 foreach (object o in remove_list)
1057 remove_list.Clear ();
1061 // Defines the indexers, and also verifies that the IndexerNameAttribute in the
1062 // class is consisten. Either it is `Item' or it is the name defined by all the
1063 // indexers with the `IndexerName' attribute.
1065 // Turns out that the IndexerNameAttribute is applied to each indexer,
1066 // but it is never emitted, instead a DefaultName attribute is attached
1069 void DefineIndexers ()
1071 string class_indexer_name = null;
1074 // If there's both an explicit and an implicit interface implementation, the
1075 // explicit one actually implements the interface while the other one is just
1076 // a normal indexer. See bug #37714.
1079 ArrayList list = new ArrayList ();
1080 foreach (Indexer i in Indexers){
1081 if (i.MemberName.Left != null)
1084 foreach (Indexer i in Indexers){
1085 if (i.MemberName.Left == null)
1089 foreach (Indexer i in list){
1094 name = i.IndexerName;
1096 if (i.InterfaceType != null)
1099 if (class_indexer_name == null){
1100 class_indexer_name = name;
1104 if (name == class_indexer_name)
1108 668, "Two indexers have different names, " +
1109 " you should use the same name for all your indexers");
1111 if (class_indexer_name == null)
1112 class_indexer_name = "Item";
1113 IndexerName = class_indexer_name;
1116 static void Error_KeywordNotAllowed (Location loc)
1118 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1122 /// Populates our TypeBuilder with fields and methods
1124 public override bool DefineMembers (TypeContainer container)
1126 if (members_defined)
1127 return members_defined_ok;
1129 members_defined_ok = DoDefineMembers ();
1130 members_defined = true;
1132 return members_defined_ok;
1135 bool DoDefineMembers ()
1137 MemberInfo [] defined_names = null;
1140 // We need to be able to use the member cache while we are checking/defining
1143 if (TypeBuilder.BaseType != null)
1144 parent_container = TypeManager.LookupMemberContainer (TypeBuilder.BaseType);
1147 if (interface_order != null){
1148 foreach (Interface iface in interface_order)
1149 if ((iface.ModFlags & Modifiers.NEW) == 0)
1150 iface.DefineMembers (this);
1152 Error_KeywordNotAllowed (iface.Location);
1155 if (RootContext.WarningLevel > 1){
1159 // This code throws an exception in the comparer
1160 // I guess the string is not an object?
1162 ptype = TypeBuilder.BaseType;
1164 defined_names = (MemberInfo []) FindMembers (
1165 ptype, MemberTypes.All & ~MemberTypes.Constructor,
1166 BindingFlags.Public | BindingFlags.Instance |
1167 BindingFlags.Static, null, null);
1169 Array.Sort (defined_names, mif_compare);
1173 Class pclass = Parent as Class;
1174 if (pclass != null) {
1175 string pname = null;
1177 Type t = pclass.TypeBuilder.BaseType;
1178 while ((t != null) && (ptype == null)) {
1179 pname = t.FullName + "." + Basename;
1180 ptype = RootContext.LookupType (this, pname, true, Location.Null);
1184 if ((ModFlags & Modifiers.NEW) != 0) {
1186 Report.Warning (109, Location, "The member '" + Name + "' does not hide an " +
1187 "inherited member. The keyword new is not required.");
1188 } else if (ptype != null) {
1189 Report.Warning (108, Location, "The keyword new is required on `" +
1190 Name + "' because it hides inherited member '" +
1193 } else if ((ModFlags & Modifiers.NEW) != 0)
1194 Error_KeywordNotAllowed (Location);
1196 if (constants != null)
1197 DefineMembers (constants, defined_names);
1200 DefineMembers (fields, defined_names);
1203 if (instance_constructors == null){
1204 if (default_constructor == null)
1205 DefineDefaultConstructor (false);
1208 if (initialized_static_fields != null &&
1209 default_static_constructor == null)
1210 DefineDefaultConstructor (true);
1213 if (this is Struct){
1215 // Structs can not have initialized instance
1218 if (initialized_static_fields != null &&
1219 default_static_constructor == null)
1220 DefineDefaultConstructor (true);
1222 if (initialized_fields != null)
1223 ReportStructInitializedInstanceError ();
1226 if (!(this is Interface))
1227 Pending = PendingImplementation.GetPendingImplementations (this);
1230 // Constructors are not in the defined_names array
1232 if (instance_constructors != null)
1233 DefineMembers (instance_constructors, null);
1235 if (default_static_constructor != null)
1236 default_static_constructor.Define (this);
1238 if (methods != null)
1239 DefineMembers (methods, defined_names);
1241 if (properties != null)
1242 DefineMembers (properties, defined_names);
1245 DefineMembers (events, defined_names);
1247 if (indexers != null) {
1250 IndexerName = "Item";
1252 if (operators != null){
1253 DefineMembers (operators, null);
1255 CheckPairedOperators ();
1259 DefineMembers (enums, defined_names);
1261 if (delegates != null)
1262 DefineMembers (delegates, defined_names);
1264 if (CurrentType != null) {
1265 GenericType = CurrentType.ResolveType (ec);
1267 ec.ContainerType = GenericType;
1272 member_cache = new MemberCache (this);
1279 public override bool Define (TypeContainer container)
1281 if (interface_order != null){
1282 foreach (Interface iface in interface_order)
1283 if ((iface.ModFlags & Modifiers.NEW) == 0)
1284 iface.Define (this);
1291 /// This function is based by a delegate to the FindMembers routine
1293 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1299 /// This filter is used by FindMembers, and we just keep
1300 /// a global for the filter to `AlwaysAccept'
1302 static MemberFilter accepting_filter;
1306 /// A member comparission method based on name only
1308 static IComparer mif_compare;
1310 static TypeContainer ()
1312 accepting_filter = new MemberFilter (AlwaysAccept);
1313 mif_compare = new MemberInfoCompare ();
1316 public MethodInfo[] GetMethods ()
1318 ArrayList members = new ArrayList ();
1320 DefineMembers (null);
1322 if (methods != null) {
1323 int len = methods.Count;
1324 for (int i = 0; i < len; i++) {
1325 Method m = (Method) methods [i];
1327 members.Add (m.MethodBuilder);
1331 if (operators != null) {
1332 int len = operators.Count;
1333 for (int i = 0; i < len; i++) {
1334 Operator o = (Operator) operators [i];
1336 members.Add (o.OperatorMethodBuilder);
1340 if (properties != null) {
1341 int len = properties.Count;
1342 for (int i = 0; i < len; i++) {
1343 Property p = (Property) properties [i];
1345 if (p.GetBuilder != null)
1346 members.Add (p.GetBuilder);
1347 if (p.SetBuilder != null)
1348 members.Add (p.SetBuilder);
1352 if (indexers != null) {
1353 int len = indexers.Count;
1354 for (int i = 0; i < len; i++) {
1355 Indexer ix = (Indexer) indexers [i];
1357 if (ix.GetBuilder != null)
1358 members.Add (ix.GetBuilder);
1359 if (ix.SetBuilder != null)
1360 members.Add (ix.SetBuilder);
1364 if (events != null) {
1365 int len = events.Count;
1366 for (int i = 0; i < len; i++) {
1367 Event e = (Event) events [i];
1369 if (e.AddBuilder != null)
1370 members.Add (e.AddBuilder);
1371 if (e.RemoveBuilder != null)
1372 members.Add (e.RemoveBuilder);
1376 MethodInfo[] methods = new MethodInfo [members.Count];
1377 members.CopyTo (methods, 0);
1382 /// This method returns the members of this type just like Type.FindMembers would
1383 /// Only, we need to use this for types which are _being_ defined because MS'
1384 /// implementation can't take care of that.
1387 // FIXME: return an empty static array instead of null, that cleans up
1388 // some code and is consistent with some coding conventions I just found
1392 // Notice that in various cases we check if our field is non-null,
1393 // something that would normally mean that there was a bug elsewhere.
1395 // The problem happens while we are defining p-invoke methods, as those
1396 // will trigger a FindMembers, but this happens before things are defined
1398 // Since the whole process is a no-op, it is fine to check for null here.
1400 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1401 MemberFilter filter, object criteria)
1403 ArrayList members = null;
1406 if ((bf & BindingFlags.Public) != 0)
1407 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1409 if ((bf & BindingFlags.NonPublic) != 0)
1410 modflags |= Modifiers.PRIVATE;
1412 int static_mask = 0, static_flags = 0;
1413 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1414 case BindingFlags.Static:
1415 static_mask = static_flags = Modifiers.STATIC;
1418 case BindingFlags.Instance:
1419 static_mask = Modifiers.STATIC;
1424 static_mask = static_flags = 0;
1428 Timer.StartTimer (TimerType.TcFindMembers);
1431 filter = accepting_filter;
1433 if ((mt & MemberTypes.Field) != 0) {
1434 if (fields != null) {
1435 int len = fields.Count;
1436 for (int i = 0; i < len; i++) {
1437 Field f = (Field) fields [i];
1439 if ((f.ModFlags & modflags) == 0)
1441 if ((f.ModFlags & static_mask) != static_flags)
1444 FieldBuilder fb = f.FieldBuilder;
1445 if (fb != null && filter (fb, criteria) == true) {
1446 if (members == null)
1447 members = new ArrayList ();
1454 if (constants != null) {
1455 int len = constants.Count;
1456 for (int i = 0; i < len; i++) {
1457 Const con = (Const) constants [i];
1459 if ((con.ModFlags & modflags) == 0)
1461 if ((con.ModFlags & static_mask) != static_flags)
1464 FieldBuilder fb = con.FieldBuilder;
1465 if (fb != null && filter (fb, criteria) == true) {
1466 if (members == null)
1467 members = new ArrayList ();
1475 if ((mt & MemberTypes.Method) != 0) {
1476 if (methods != null) {
1477 int len = methods.Count;
1478 for (int i = 0; i < len; i++) {
1479 Method m = (Method) methods [i];
1481 if ((m.ModFlags & modflags) == 0)
1483 if ((m.ModFlags & static_mask) != static_flags)
1486 MethodBuilder mb = m.MethodBuilder;
1488 if (mb != null && filter (mb, criteria) == true) {
1489 if (members == null)
1490 members = new ArrayList ();
1497 if (operators != null) {
1498 int len = operators.Count;
1499 for (int i = 0; i < len; i++) {
1500 Operator o = (Operator) operators [i];
1502 if ((o.ModFlags & modflags) == 0)
1504 if ((o.ModFlags & static_mask) != static_flags)
1507 MethodBuilder ob = o.OperatorMethodBuilder;
1508 if (ob != null && filter (ob, criteria) == true) {
1509 if (members == null)
1510 members = new ArrayList ();
1517 if (properties != null) {
1518 int len = properties.Count;
1519 for (int i = 0; i < len; i++) {
1520 Property p = (Property) properties [i];
1522 if ((p.ModFlags & modflags) == 0)
1524 if ((p.ModFlags & static_mask) != static_flags)
1530 if (b != null && filter (b, criteria) == true) {
1531 if (members == null)
1532 members = new ArrayList ();
1538 if (b != null && filter (b, criteria) == true) {
1539 if (members == null)
1540 members = new ArrayList ();
1547 if (indexers != null) {
1548 int len = indexers.Count;
1549 for (int i = 0; i < len; i++) {
1550 Indexer ix = (Indexer) indexers [i];
1552 if ((ix.ModFlags & modflags) == 0)
1554 if ((ix.ModFlags & static_mask) != static_flags)
1560 if (b != null && filter (b, criteria) == true) {
1561 if (members == null)
1562 members = new ArrayList ();
1568 if (b != null && filter (b, criteria) == true) {
1569 if (members == null)
1570 members = new ArrayList ();
1578 if ((mt & MemberTypes.Event) != 0) {
1579 if (events != null) {
1580 int len = events.Count;
1581 for (int i = 0; i < len; i++) {
1582 Event e = (Event) events [i];
1584 if ((e.ModFlags & modflags) == 0)
1586 if ((e.ModFlags & static_mask) != static_flags)
1589 MemberInfo eb = e.EventBuilder;
1590 if (eb != null && filter (eb, criteria) == true) {
1591 if (members == null)
1592 members = new ArrayList ();
1594 members.Add (e.EventBuilder);
1600 if ((mt & MemberTypes.Property) != 0){
1601 if (properties != null) {
1602 int len = properties.Count;
1603 for (int i = 0; i < len; i++) {
1604 Property p = (Property) properties [i];
1606 if ((p.ModFlags & modflags) == 0)
1608 if ((p.ModFlags & static_mask) != static_flags)
1611 MemberInfo pb = p.PropertyBuilder;
1612 if (pb != null && filter (pb, criteria) == true) {
1613 if (members == null)
1614 members = new ArrayList ();
1616 members.Add (p.PropertyBuilder);
1621 if (indexers != null) {
1622 int len = indexers.Count;
1623 for (int i = 0; i < len; i++) {
1624 Indexer ix = (Indexer) indexers [i];
1626 if ((ix.ModFlags & modflags) == 0)
1628 if ((ix.ModFlags & static_mask) != static_flags)
1631 MemberInfo ib = ix.PropertyBuilder;
1632 if (ib != null && filter (ib, criteria) == true) {
1633 if (members == null)
1634 members = new ArrayList ();
1636 members.Add (ix.PropertyBuilder);
1642 if ((mt & MemberTypes.NestedType) != 0) {
1643 if (types != null) {
1644 int len = types.Count;
1645 for (int i = 0; i < len; i++) {
1646 TypeContainer t = (TypeContainer) types [i];
1648 if ((t.ModFlags & modflags) == 0)
1651 TypeBuilder tb = t.TypeBuilder;
1652 if (tb != null && (filter (tb, criteria) == true)) {
1653 if (members == null)
1654 members = new ArrayList ();
1661 if (enums != null) {
1662 int len = enums.Count;
1663 for (int i = 0; i < len; i++) {
1664 Enum en = (Enum) enums [i];
1666 if ((en.ModFlags & modflags) == 0)
1669 TypeBuilder tb = en.TypeBuilder;
1670 if (tb != null && (filter (tb, criteria) == true)) {
1671 if (members == null)
1672 members = new ArrayList ();
1679 if (delegates != null) {
1680 int len = delegates.Count;
1681 for (int i = 0; i < len; i++) {
1682 Delegate d = (Delegate) delegates [i];
1684 if ((d.ModFlags & modflags) == 0)
1687 TypeBuilder tb = d.TypeBuilder;
1688 if (tb != null && (filter (tb, criteria) == true)) {
1689 if (members == null)
1690 members = new ArrayList ();
1697 if (interfaces != null) {
1698 int len = interfaces.Count;
1699 for (int i = 0; i < len; i++) {
1700 Interface iface = (Interface) interfaces [i];
1702 if ((iface.ModFlags & modflags) == 0)
1705 TypeBuilder tb = iface.TypeBuilder;
1706 if (tb != null && (filter (tb, criteria) == true)) {
1707 if (members == null)
1708 members = new ArrayList ();
1716 if ((mt & MemberTypes.Constructor) != 0){
1717 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1718 int len = instance_constructors.Count;
1719 for (int i = 0; i < len; i++) {
1720 Constructor c = (Constructor) instance_constructors [i];
1722 ConstructorBuilder cb = c.ConstructorBuilder;
1723 if (cb != null && filter (cb, criteria) == true) {
1724 if (members == null)
1725 members = new ArrayList ();
1732 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1733 ConstructorBuilder cb =
1734 default_static_constructor.ConstructorBuilder;
1736 if (cb != null && filter (cb, criteria) == true) {
1737 if (members == null)
1738 members = new ArrayList ();
1746 // Lookup members in parent if requested.
1748 if (((bf & BindingFlags.DeclaredOnly) == 0) && (TypeBuilder.BaseType != null)) {
1749 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1750 if (list.Count > 0) {
1751 if (members == null)
1752 members = new ArrayList ();
1754 members.AddRange (list);
1758 Timer.StopTimer (TimerType.TcFindMembers);
1760 if (members == null)
1761 return MemberList.Empty;
1763 return new MemberList (members);
1766 public override MemberCache MemberCache {
1768 return member_cache;
1772 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1773 MemberFilter filter, object criteria)
1775 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1778 return ds.FindMembers (mt, bf, filter, criteria);
1780 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1784 // FindMethods will look for methods not only in the type `t', but in
1785 // any interfaces implemented by the type.
1787 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1788 MemberFilter filter, object criteria)
1794 /// Emits the values for the constants
1796 public void EmitConstants ()
1798 if (constants != null)
1799 foreach (Const con in constants)
1805 /// Emits the code, this step is performed after all
1806 /// the types, enumerations, constructors
1810 if (instance_constructors != null)
1811 foreach (Constructor c in instance_constructors)
1814 if (default_static_constructor != null)
1815 default_static_constructor.Emit (this);
1817 if (methods != null)
1818 foreach (Method m in methods)
1821 if (operators != null)
1822 foreach (Operator o in operators)
1825 if (properties != null)
1826 foreach (Property p in properties)
1829 if (indexers != null){
1830 foreach (Indexer ix in indexers)
1833 CustomAttributeBuilder cb = EmitDefaultMemberAttr ();
1834 TypeBuilder.SetCustomAttribute (cb);
1838 foreach (Field f in fields)
1841 if (events != null){
1842 foreach (Event e in Events)
1846 if (Pending != null)
1847 if (Pending.VerifyPendingMethods ())
1850 Attribute.ApplyAttributes (ec, TypeBuilder, this, OptAttributes);
1853 // Check for internal or private fields that were never assigned
1855 if (RootContext.WarningLevel >= 3) {
1856 if (fields != null){
1857 foreach (Field f in fields) {
1858 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1861 if ((f.status & Field.Status.USED) == 0){
1863 169, f.Location, "Private field " +
1864 MakeName (f.Name) + " is never used");
1869 // Only report 649 on level 4
1871 if (RootContext.WarningLevel < 4)
1874 if ((f.status & Field.Status.ASSIGNED) != 0)
1879 "Field " + MakeName (f.Name) + " is never assigned " +
1880 " to and will always have its default value");
1884 if (events != null){
1885 foreach (Event e in events){
1887 Report.Warning (67, "The event " + MakeName (e.Name) + " is never used");
1892 // if (types != null)
1893 // foreach (TypeContainer tc in types)
1897 CustomAttributeBuilder EmitDefaultMemberAttr ()
1899 EmitContext ec = new EmitContext (this, Location, null, null, ModFlags);
1901 Expression ml = Expression.MemberLookup (ec, TypeManager.default_member_type,
1902 ".ctor", MemberTypes.Constructor,
1903 BindingFlags.Public | BindingFlags.Instance,
1906 MethodGroupExpr mg = (MethodGroupExpr) ml;
1908 MethodBase constructor = mg.Methods [0];
1910 string [] vals = { IndexerName };
1912 CustomAttributeBuilder cb = null;
1914 cb = new CustomAttributeBuilder ((ConstructorInfo) constructor, vals);
1916 Report.Warning (-100, "Can not set the indexer default member attribute");
1922 public override void CloseType ()
1929 TypeBuilder.CreateType ();
1930 } catch (TypeLoadException){
1932 // This is fine, the code still created the type
1934 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1935 // Console.WriteLine (e.Message);
1937 Console.WriteLine ("In type: " + Name);
1942 foreach (Enum en in Enums)
1945 if (interface_order != null){
1946 foreach (Interface iface in interface_order)
1951 foreach (TypeContainer tc in Types)
1955 foreach (TypeContainer tc in Types)
1956 if (!(tc is Struct))
1960 if (Delegates != null)
1961 foreach (Delegate d in Delegates)
1969 initialized_fields = null;
1970 initialized_static_fields = null;
1973 interface_order = null;
1979 default_constructor = null;
1980 default_static_constructor = null;
1982 OptAttributes = null;
1984 parent_container = null;
1985 member_cache = null;
1988 public string MakeName (string n)
1990 return "`" + Name + "." + n + "'";
1993 public void Warning_KeywordNewRequired (Location l, MemberInfo mi)
1996 108, l, "The keyword new is required on " +
1997 MakeName (mi.Name) + " because it hides `" +
1998 mi.ReflectedType.Name + "." + mi.Name + "'");
2001 public void Warning_KeywordNewNotRequired (Location l, MemberCore mc)
2004 109, l, "The member " + MakeName (mc.Name) + " does not hide an " +
2005 "inherited member, the keyword new is not required");
2008 public void Error_EventCanOnlyOverrideEvent (Location l, MemberInfo mi)
2011 72, l, MakeName (mi.Name) + " : cannot override; `" +
2012 mi.ReflectedType.Name + "." + mi.Name + "' is not an event");
2015 public static int CheckMember (string name, MemberInfo mi, int ModFlags)
2021 // Performs the validation on a Method's modifiers (properties have
2022 // the same properties).
2024 public bool MethodModifiersValid (int flags, string n, Location loc)
2026 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2027 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2028 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2032 // At most one of static, virtual or override
2034 if ((flags & Modifiers.STATIC) != 0){
2035 if ((flags & vao) != 0){
2037 112, loc, "static method " + MakeName (n) + "can not be marked " +
2038 "as virtual, abstract or override");
2043 if (this is Struct){
2044 if ((flags & va) != 0){
2045 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
2050 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2052 113, loc, MakeName (n) +
2053 " marked as override cannot be marked as new or virtual");
2058 // If the declaration includes the abstract modifier, then the
2059 // declaration does not include static, virtual or extern
2061 if ((flags & Modifiers.ABSTRACT) != 0){
2062 if ((flags & Modifiers.EXTERN) != 0){
2064 180, loc, MakeName (n) + " can not be both abstract and extern");
2068 if ((flags & Modifiers.VIRTUAL) != 0){
2070 503, loc, MakeName (n) + " can not be both abstract and virtual");
2074 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2076 513, loc, MakeName (n) +
2077 " is abstract but its container class is not");
2083 if ((flags & Modifiers.PRIVATE) != 0){
2084 if ((flags & vao) != 0){
2086 621, loc, MakeName (n) +
2087 " virtual or abstract members can not be private");
2092 if ((flags & Modifiers.SEALED) != 0){
2093 if ((flags & Modifiers.OVERRIDE) == 0){
2095 238, loc, MakeName (n) +
2096 " cannot be sealed because it is not an override");
2104 Hashtable builder_and_args;
2106 public bool RegisterMethod (MethodBuilder mb, InternalParameters ip, Type [] args)
2108 if (builder_and_args == null)
2109 builder_and_args = new Hashtable ();
2114 /// Performs checks for an explicit interface implementation. First it
2115 /// checks whether the `interface_type' is a base inteface implementation.
2116 /// Then it checks whether `name' exists in the interface type.
2118 public bool VerifyImplements (Type interface_type, string full, string name, Location loc)
2122 if (ifaces != null){
2123 foreach (TypeExpr t in ifaces){
2124 if (t.Type == interface_type){
2132 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
2143 string IMemberContainer.Name {
2149 Type IMemberContainer.Type {
2155 IMemberContainer IMemberContainer.Parent {
2157 return parent_container;
2161 MemberCache IMemberContainer.MemberCache {
2163 return member_cache;
2167 bool IMemberContainer.IsInterface {
2169 return this is Interface;
2173 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2175 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2177 if (GenericType != null)
2178 return TypeManager.FindMembers (GenericType, mt, new_bf,
2181 return FindMembers (mt, new_bf, null, null);
2185 // Operator pair checking
2188 class OperatorEntry {
2190 public Type ret_type;
2191 public Type type1, type2;
2193 public Operator.OpType ot;
2195 public OperatorEntry (int f, Operator o)
2199 ret_type = o.OperatorMethod.GetReturnType ();
2200 Type [] pt = o.OperatorMethod.ParameterTypes;
2204 ot = o.OperatorType;
2207 public override int GetHashCode ()
2209 return ret_type.GetHashCode ();
2212 public override bool Equals (object o)
2214 OperatorEntry other = (OperatorEntry) o;
2216 if (other.ret_type != ret_type)
2218 if (other.type1 != type1)
2220 if (other.type2 != type2)
2227 // Checks that some operators come in pairs:
2233 // They are matched based on the return type and the argument types
2235 void CheckPairedOperators ()
2237 Hashtable pairs = new Hashtable (null, null);
2238 Operator true_op = null;
2239 Operator false_op = null;
2240 bool has_equality_or_inequality = false;
2242 // Register all the operators we care about.
2243 foreach (Operator op in operators){
2246 switch (op.OperatorType){
2247 case Operator.OpType.Equality:
2249 has_equality_or_inequality = true;
2251 case Operator.OpType.Inequality:
2253 has_equality_or_inequality = true;
2256 case Operator.OpType.True:
2259 case Operator.OpType.False:
2263 case Operator.OpType.GreaterThan:
2265 case Operator.OpType.LessThan:
2268 case Operator.OpType.GreaterThanOrEqual:
2270 case Operator.OpType.LessThanOrEqual:
2276 OperatorEntry oe = new OperatorEntry (reg, op);
2278 object o = pairs [oe];
2282 oe = (OperatorEntry) o;
2287 if (true_op != null){
2288 if (false_op == null)
2289 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
2290 } else if (false_op != null)
2291 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
2294 // Look for the mistakes.
2296 foreach (DictionaryEntry de in pairs){
2297 OperatorEntry oe = (OperatorEntry) de.Key;
2304 case Operator.OpType.Equality:
2307 case Operator.OpType.Inequality:
2310 case Operator.OpType.GreaterThan:
2313 case Operator.OpType.LessThan:
2316 case Operator.OpType.GreaterThanOrEqual:
2319 case Operator.OpType.LessThanOrEqual:
2323 Report.Error (216, oe.op.Location,
2324 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
2327 if ((has_equality_or_inequality) && (RootContext.WarningLevel >= 2)) {
2328 MethodSignature equals_ms = new MethodSignature (
2329 "Equals", TypeManager.bool_type, new Type [] { TypeManager.object_type });
2330 MethodSignature hash_ms = new MethodSignature (
2331 "GetHashCode", TypeManager.int32_type, new Type [0]);
2333 MemberList equals_ml = FindMembers (MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance |
2334 BindingFlags.DeclaredOnly, MethodSignature.method_signature_filter,
2336 MemberList hash_ml = FindMembers (MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance |
2337 BindingFlags.DeclaredOnly, MethodSignature.method_signature_filter,
2340 bool equals_ok = false;
2341 if ((equals_ml != null) && (equals_ml.Count == 1))
2342 equals_ok = equals_ml [0].DeclaringType == TypeBuilder;
2343 bool hash_ok = false;
2344 if ((hash_ml != null) && (hash_ml.Count == 1))
2345 hash_ok = hash_ml [0].DeclaringType == TypeBuilder;
2348 Report.Warning (660, Location, "`" + Name + "' defines operator == or operator != but does " +
2349 "not override Object.Equals (object o)");
2351 Report.Warning (661, Location, "`" + Name + "' defines operator == or operator != but does " +
2352 "not override Object.GetHashCode ()");
2358 public class Class : TypeContainer {
2360 // Modifiers allowed in a class declaration
2362 public const int AllowedModifiers =
2365 Modifiers.PROTECTED |
2366 Modifiers.INTERNAL |
2368 Modifiers.ABSTRACT |
2372 public Class (NamespaceEntry ns, TypeContainer parent, string name, int mod,
2373 Attributes attrs, Location l)
2374 : base (ns, parent, name, attrs, l)
2378 if (parent.Parent == null)
2379 accmods = Modifiers.INTERNAL;
2381 accmods = Modifiers.PRIVATE;
2383 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2387 // FIXME: How do we deal with the user specifying a different
2390 public override TypeAttributes TypeAttr {
2392 return base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2397 public class Struct : TypeContainer {
2399 // Modifiers allowed in a struct declaration
2401 public const int AllowedModifiers =
2404 Modifiers.PROTECTED |
2405 Modifiers.INTERNAL |
2409 public Struct (NamespaceEntry ns, TypeContainer parent, string name, int mod, Attributes attrs, Location l)
2410 : base (ns, parent, name, attrs, l)
2414 if (parent.Parent == null)
2415 accmods = Modifiers.INTERNAL;
2417 accmods = Modifiers.PRIVATE;
2419 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2421 this.ModFlags |= Modifiers.SEALED;
2425 // FIXME: Allow the user to specify a different set of attributes
2426 // in some cases (Sealed for example is mandatory for a class,
2427 // but what SequentialLayout can be changed
2429 public override TypeAttributes TypeAttr {
2431 return base.TypeAttr |
2432 TypeAttributes.SequentialLayout |
2433 TypeAttributes.Sealed |
2434 TypeAttributes.BeforeFieldInit;
2442 public class Interface : TypeContainer, IMemberContainer {
2444 /// Modifiers allowed in a class declaration
2446 public const int AllowedModifiers =
2449 Modifiers.PROTECTED |
2450 Modifiers.INTERNAL |
2454 public Interface (NamespaceEntry ns, TypeContainer parent, string name, int mod,
2455 Attributes attrs, Location l)
2456 : base (ns, parent, name, attrs, l)
2460 if (parent.Parent == null)
2461 accmods = Modifiers.INTERNAL;
2463 accmods = Modifiers.PRIVATE;
2465 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2468 public override TypeAttributes TypeAttr {
2470 return base.TypeAttr |
2471 TypeAttributes.AutoLayout |
2472 TypeAttributes.Abstract |
2473 TypeAttributes.Interface;
2478 public abstract class MethodCore : MemberBase {
2479 public readonly Parameters Parameters;
2480 protected Block block;
2481 protected DeclSpace ds;
2484 // Parameters, cached for semantic analysis.
2486 protected InternalParameters parameter_info;
2487 protected Type [] parameter_types;
2490 // This is set from TypeContainer.DefineMembers if this method overrides something.
2492 public bool OverridesSomething;
2494 // Whether this is an operator method.
2495 public bool IsOperator;
2497 public MethodCore (DeclSpace ds, Expression type, int mod, int allowed_mod,
2498 bool is_interface, MemberName name, Attributes attrs,
2499 Parameters parameters, Location loc)
2500 : base (type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
2502 Parameters = parameters;
2503 IsInterface = is_interface;
2508 // Returns the System.Type array for the parameters of this method
2510 public Type [] ParameterTypes {
2512 return parameter_types;
2516 public InternalParameters ParameterInfo
2519 return parameter_info;
2523 public Block Block {
2533 protected virtual bool DoDefineParameters ()
2535 // Check if arguments were correct
2536 parameter_types = Parameters.GetParameterInfo (ds);
2537 if ((parameter_types == null) || !CheckParameters (ds, parameter_types))
2540 parameter_info = new InternalParameters (ds, Parameters);
2542 Parameter array_param = Parameters.ArrayParameter;
2543 if ((array_param != null) &&
2544 (!array_param.ParameterType.IsArray ||
2545 (array_param.ParameterType.GetArrayRank () != 1))) {
2546 Report.Error (225, Location, "params parameter has to be a single dimensional array");
2553 protected bool IsDuplicateImplementation (TypeContainer tc, MethodCore method)
2555 if ((method == this) || (method.Name != Name))
2558 Type[] param_types = method.ParameterTypes;
2559 if (param_types == null)
2562 if (param_types.Length != ParameterTypes.Length)
2566 bool may_unify = true;
2568 for (int i = 0; i < param_types.Length; i++) {
2569 Type a = param_types [i];
2570 Type b = ParameterTypes [i];
2572 if (!TypeManager.MayBecomeEqualGenericTypes (a, b))
2579 Report.Error (111, Location,
2580 "Class `{0}' already defines a member called " +
2581 "`{1}' with the same parameter types",
2584 } else if (may_unify) {
2585 Report.Error (408, Location,
2586 "`{0}' cannot define overload members that " +
2587 "may unify for some type parameter substitutions",
2595 public CallingConventions GetCallingConvention (bool is_class)
2597 CallingConventions cc = 0;
2599 cc = Parameters.GetCallingConvention ();
2602 if ((ModFlags & Modifiers.STATIC) == 0)
2603 cc |= CallingConventions.HasThis;
2605 // FIXME: How is `ExplicitThis' used in C#?
2611 // The method's attributes are passed in because we need to extract
2612 // the "return:" attribute from there to apply on the return type
2614 static public void LabelParameters (EmitContext ec,
2616 Parameters parameters,
2617 Attributes method_attrs,
2621 // Define each type attribute (in/out/ref) and
2622 // the argument names.
2624 Parameter [] p = parameters.FixedParameters;
2627 MethodBuilder mb = null;
2628 ConstructorBuilder cb = null;
2630 if (builder is MethodBuilder)
2631 mb = (MethodBuilder) builder;
2633 cb = (ConstructorBuilder) builder;
2636 for (i = 0; i < p.Length; i++) {
2637 ParameterBuilder pb;
2638 ParameterAttributes par_attr = p [i].Attributes;
2641 pb = cb.DefineParameter (
2642 i + 1, par_attr, p [i].Name);
2644 pb = mb.DefineParameter (
2645 i + 1, par_attr, p [i].Name);
2647 Attributes attr = p [i].OptAttributes;
2649 Attribute.ApplyAttributes (ec, pb, pb, attr);
2651 if (par_attr == ParameterAttributes.Out){
2652 if (attr.Contains (TypeManager.in_attribute_type))
2653 Report.Error (36, loc,
2654 "Can not use [In] attribute on out parameter");
2660 if (parameters.ArrayParameter != null){
2661 ParameterBuilder pb;
2662 Parameter array_param = parameters.ArrayParameter;
2665 pb = cb.DefineParameter (
2666 i + 1, array_param.Attributes,
2669 pb = mb.DefineParameter (
2670 i + 1, array_param.Attributes,
2673 CustomAttributeBuilder a = new CustomAttributeBuilder (
2674 TypeManager.cons_param_array_attribute, new object [0]);
2676 pb.SetCustomAttribute (a);
2680 // And now for the return type attribute decoration
2682 ParameterBuilder ret_pb;
2683 Attributes ret_attrs = null;
2685 if (mb == null || method_attrs == null)
2688 foreach (AttributeSection asec in method_attrs.AttributeSections) {
2690 if (asec.Target != "return")
2693 if (ret_attrs == null)
2694 ret_attrs = new Attributes (asec);
2696 ret_attrs.AddAttributeSection (asec);
2699 if (ret_attrs != null) {
2701 ret_pb = mb.DefineParameter (0, ParameterAttributes.None, "");
2702 Attribute.ApplyAttributes (ec, ret_pb, ret_pb, ret_attrs);
2704 } catch (ArgumentOutOfRangeException) {
2707 ".NET SDK 1.0 does not permit setting custom attributes" +
2708 " on the return type of a method");
2714 public class Method : MethodCore, IIteratorContainer {
2715 public MethodBuilder MethodBuilder;
2716 public MethodData MethodData;
2717 public readonly GenericMethod GenericMethod;
2720 /// Modifiers allowed in a class declaration
2722 const int AllowedModifiers =
2725 Modifiers.PROTECTED |
2726 Modifiers.INTERNAL |
2731 Modifiers.OVERRIDE |
2732 Modifiers.ABSTRACT |
2734 Modifiers.METHOD_YIELDS |
2737 const int AllowedInterfaceModifiers =
2741 // return_type can be "null" for VOID values.
2743 public Method (DeclSpace ds, Expression return_type, int mod, bool is_iface,
2744 MemberName name, Parameters parameters, Attributes attrs,
2746 : base (ds, return_type, mod,
2747 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
2748 is_iface, name, attrs, parameters, l)
2753 // return_type can be "null" for VOID values.
2755 public Method (GenericMethod generic, Expression return_type, int mod,
2756 bool is_iface, MemberName name, Parameters parameters,
2757 Attributes attrs, Location l)
2758 : this ((DeclSpace) generic, return_type, mod, is_iface, name,
2759 parameters, attrs, l)
2761 GenericMethod = generic;
2765 // Returns the `System.Type' for the ReturnType of this
2766 // function. Provides a nice cache. (used between semantic analysis
2767 // and actual code generation
2769 public Type GetReturnType ()
2774 void DuplicateEntryPoint (MethodInfo b, Location location)
2778 "Program `" + CodeGen.FileName +
2779 "' has more than one entry point defined: `" +
2780 TypeManager.CSharpSignature(b) + "'");
2783 void Report28 (MethodInfo b)
2787 "`" + TypeManager.CSharpSignature(b) +
2788 "' has the wrong signature to be an entry point");
2791 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
2793 if (b.ReturnType != TypeManager.void_type &&
2794 b.ReturnType != TypeManager.int32_type)
2797 if (pinfo.Count == 0)
2800 if (pinfo.Count > 1)
2803 Type t = pinfo.ParameterType(0);
2805 (t.GetArrayRank() == 1) &&
2806 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
2807 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
2814 // Checks our base implementation if any
2816 protected override bool CheckBase (TypeContainer container)
2818 base.CheckBase (container);
2820 // Check whether arguments were correct.
2821 if (!DoDefineParameters ())
2824 MethodSignature ms = new MethodSignature (Name, null, ParameterTypes);
2826 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
2829 // Check in our class for dups
2831 ArrayList ar = container.Methods;
2833 int arLen = ar.Count;
2835 for (int i = 0; i < arLen; i++) {
2836 Method m = (Method) ar [i];
2837 if (IsDuplicateImplementation (container, m))
2845 // Verify if the parent has a type with the same name, and then
2846 // check whether we have to create a new slot for it or not.
2848 Type ptype = container.TypeBuilder.BaseType;
2850 // ptype is only null for System.Object while compiling corlib.
2851 if (ptype != null) {
2854 // Explicit implementations do not have `parent' methods, however,
2855 // the member cache stores them there. Without this check, we get
2856 // an incorrect warning in corlib.
2858 if (! IsExplicitImpl) {
2859 parent_method = (MethodInfo)((IMemberContainer)container).Parent.MemberCache.FindMemberToOverride (
2860 container.TypeBuilder, Name, ParameterTypes, false);
2863 if (parent_method != null) {
2864 string name = parent_method.DeclaringType.Name + "." +
2867 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
2870 if ((ModFlags & Modifiers.NEW) == 0) {
2871 Type parent_ret = TypeManager.TypeToCoreType (
2872 parent_method.ReturnType);
2874 if (!parent_ret.Equals (MemberType)) {
2876 508, Location, container.MakeName (Name) + ": cannot " +
2877 "change return type when overriding " +
2878 "inherited member " + name);
2883 if (!OverridesSomething && ((ModFlags & Modifiers.NEW) != 0))
2884 WarningNotHiding (container);
2886 if ((ModFlags & Modifiers.OVERRIDE) != 0){
2887 Report.Error (115, Location,
2888 container.MakeName (Name) +
2889 " no suitable methods found to override");
2892 } else if ((ModFlags & Modifiers.NEW) != 0)
2893 WarningNotHiding (container);
2901 public override bool Define (TypeContainer container)
2904 MethodBuilder mb = null;
2905 if (GenericMethod != null) {
2906 mb = container.TypeBuilder.DefineGenericMethod (Name, flags);
2907 if (!GenericMethod.Define (mb))
2909 decl = GenericMethod;
2913 if (!DoDefine (decl, container))
2916 if (!CheckBase (container))
2919 CallingConventions cc = GetCallingConvention (container is Class);
2921 MethodData = new MethodData (ds, this, null, MemberType,
2922 ParameterTypes, ParameterInfo, cc,
2923 OptAttributes, ModFlags, flags, true,
2926 if (!MethodData.Define (container))
2930 // Setup iterator if we are one
2932 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
2933 IteratorHandler ih = new IteratorHandler (
2934 Name, container, MemberType,
2935 ParameterTypes, ParameterInfo,
2936 ModFlags, Location);
2938 Block new_block = ih.Setup (block);
2939 if (new_block == null)
2944 MethodBuilder = MethodData.MethodBuilder;
2947 // This is used to track the Entry Point,
2949 if (Name == "Main" &&
2950 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
2951 (RootContext.MainClass == null ||
2952 RootContext.MainClass == container.TypeBuilder.FullName)){
2953 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
2954 if (RootContext.EntryPoint == null) {
2955 if (container.IsGeneric){
2956 Report.Error (-201, Location,
2957 "Entry point can not be defined in a generic class");
2960 RootContext.EntryPoint = MethodBuilder;
2961 RootContext.EntryPointLocation = Location;
2963 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
2964 DuplicateEntryPoint (MethodBuilder, Location);
2967 Report28(MethodBuilder);
2976 public void Emit (TypeContainer container)
2978 MethodData.Emit (container, Block, this);
2983 void IIteratorContainer.SetYields ()
2985 ModFlags |= Modifiers.METHOD_YIELDS;
2989 public abstract class ConstructorInitializer {
2990 ArrayList argument_list;
2991 ConstructorInfo parent_constructor;
2992 Parameters parameters;
2995 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
2998 this.argument_list = argument_list;
2999 this.parameters = parameters;
3003 public ArrayList Arguments {
3005 return argument_list;
3009 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
3011 Expression parent_constructor_group;
3014 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
3016 if (argument_list != null){
3017 foreach (Argument a in argument_list){
3018 if (!a.Resolve (ec, loc))
3022 ec.CurrentBlock = null;
3024 if (this is ConstructorBaseInitializer) {
3025 if (ec.ContainerType.BaseType == null)
3028 t = ec.ContainerType.BaseType;
3029 if (ec.ContainerType.IsValueType) {
3030 Report.Error (522, loc,
3031 "structs cannot call base class constructors");
3035 t = ec.ContainerType;
3037 parent_constructor_group = Expression.MemberLookup (
3038 ec, t, null, t, ".ctor", 0,
3039 MemberTypes.Constructor,
3040 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3043 if (parent_constructor_group == null){
3044 Report.Error (1501, loc,
3045 "Can not find a constructor for this argument list");
3049 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (ec,
3050 (MethodGroupExpr) parent_constructor_group, argument_list, loc);
3052 if (parent_constructor == null){
3053 Report.Error (1501, loc,
3054 "Can not find a constructor for this argument list");
3058 if (parent_constructor == caller_builder){
3059 Report.Error (515, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
3066 public void Emit (EmitContext ec)
3068 if (parent_constructor != null){
3069 ec.Mark (loc, false);
3071 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
3073 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
3078 public class ConstructorBaseInitializer : ConstructorInitializer {
3079 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
3080 base (argument_list, pars, l)
3085 public class ConstructorThisInitializer : ConstructorInitializer {
3086 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
3087 base (argument_list, pars, l)
3092 public class Constructor : MethodCore {
3093 public ConstructorBuilder ConstructorBuilder;
3094 public ConstructorInitializer Initializer;
3097 // Modifiers allowed for a constructor.
3099 public const int AllowedModifiers =
3101 Modifiers.PROTECTED |
3102 Modifiers.INTERNAL |
3109 // The spec claims that static is not permitted, but
3110 // my very own code has static constructors.
3112 public Constructor (DeclSpace ds, string name, int mod, Parameters args,
3113 ConstructorInitializer init, Location l)
3114 : base (ds, null, mod, AllowedModifiers, false,
3115 new MemberName (name), null, args, l)
3121 // Returns true if this is a default constructor
3123 public bool IsDefault ()
3125 if ((ModFlags & Modifiers.STATIC) != 0)
3126 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
3127 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
3130 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
3131 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
3132 (Initializer is ConstructorBaseInitializer) &&
3133 (Initializer.Arguments == null);
3136 protected override bool CheckBase (TypeContainer container)
3138 base.CheckBase (container);
3140 // Check whether arguments were correct.
3141 if (!DoDefineParameters ())
3144 if ((ModFlags & Modifiers.STATIC) != 0)
3147 if (container is Struct && ParameterTypes.Length == 0) {
3148 Report.Error (568, Location,
3149 "Structs can not contain explicit parameterless " +
3155 // Check in our class for dups
3157 ArrayList ar = container.InstanceConstructors;
3159 int arLen = ar.Count;
3161 for (int i = 0; i < arLen; i++) {
3162 Constructor m = (Constructor) ar [i];
3163 if (IsDuplicateImplementation (container, m))
3172 // Creates the ConstructorBuilder
3174 public override bool Define (TypeContainer container)
3176 MethodAttributes ca = (MethodAttributes.RTSpecialName |
3177 MethodAttributes.SpecialName);
3179 if ((ModFlags & Modifiers.STATIC) != 0){
3180 ca |= MethodAttributes.Static | MethodAttributes.Private;
3182 ca |= MethodAttributes.HideBySig;
3184 if ((ModFlags & Modifiers.PUBLIC) != 0)
3185 ca |= MethodAttributes.Public;
3186 else if ((ModFlags & Modifiers.PROTECTED) != 0){
3187 if ((ModFlags & Modifiers.INTERNAL) != 0)
3188 ca |= MethodAttributes.FamORAssem;
3190 ca |= MethodAttributes.Family;
3191 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
3192 ca |= MethodAttributes.Assembly;
3193 else if (IsDefault ())
3194 ca |= MethodAttributes.Public;
3196 ca |= MethodAttributes.Private;
3199 // Check if arguments were correct.
3200 if (!CheckBase (container))
3203 ConstructorBuilder = container.TypeBuilder.DefineConstructor (
3204 ca, GetCallingConvention (container is Class), ParameterTypes);
3206 if ((ModFlags & Modifiers.UNSAFE) != 0)
3207 ConstructorBuilder.InitLocals = false;
3210 // HACK because System.Reflection.Emit is lame
3212 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
3220 public void Emit (TypeContainer container)
3222 ILGenerator ig = ConstructorBuilder.GetILGenerator ();
3223 EmitContext ec = new EmitContext (container, Location, ig, null, ModFlags, true);
3226 // extern methods have no bodies
3228 if ((ModFlags & Modifiers.EXTERN) != 0) {
3229 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
3231 179, Location, "External constructor `" +
3232 TypeManager.CSharpSignature (ConstructorBuilder) +
3233 "' can not have a body");
3236 } else if (block == null) {
3238 501, Location, "Constructor `" +
3239 TypeManager.CSharpSignature (ConstructorBuilder) +
3240 "' must declare a body since it is not marked extern");
3244 if ((ModFlags & Modifiers.STATIC) == 0){
3245 if (container is Class && Initializer == null)
3246 Initializer = new ConstructorBaseInitializer (
3247 null, Parameters.EmptyReadOnlyParameters, Location);
3251 // Spec mandates that Initializers will not have
3255 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
3257 ec.IsStatic = false;
3260 MethodCore.LabelParameters (ec, ConstructorBuilder,
3261 Parameters, OptAttributes, Location);
3263 SymbolWriter sw = CodeGen.SymbolWriter;
3264 bool generate_debugging = false;
3266 if ((sw != null) && (block != null) &&
3267 !Location.IsNull (Location) &&
3268 !Location.IsNull (block.EndLocation) &&
3269 (Location.SymbolDocument != null)) {
3270 sw.OpenMethod (container, ConstructorBuilder, Location, block.EndLocation);
3272 generate_debugging = true;
3276 // Classes can have base initializers and instance field initializers.
3278 if (container is Class){
3279 if ((ModFlags & Modifiers.STATIC) == 0){
3282 // If we use a "this (...)" constructor initializer, then
3283 // do not emit field initializers, they are initialized in the other constructor
3285 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
3286 container.EmitFieldInitializers (ec);
3289 if (Initializer != null)
3290 Initializer.Emit (ec);
3292 if ((ModFlags & Modifiers.STATIC) != 0)
3293 container.EmitFieldInitializers (ec);
3295 Attribute.ApplyAttributes (ec, ConstructorBuilder, this, OptAttributes);
3297 // If this is a non-static `struct' constructor and doesn't have any
3298 // initializer, it must initialize all of the struct's fields.
3299 if ((container is Struct) && ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
3300 Block.AddThisVariable (container, Location);
3302 ec.EmitTopBlock (block, ParameterInfo, Location);
3304 if (generate_debugging)
3312 // Encapsulates most of the Method's state
3314 public class MethodData {
3316 // The return type of this method
3318 public readonly Type ReturnType;
3319 public readonly Type[] ParameterTypes;
3320 public readonly GenericMethod GenericMethod;
3321 public readonly InternalParameters ParameterInfo;
3322 public readonly CallingConventions CallingConventions;
3323 public readonly Attributes OptAttributes;
3324 public readonly Location Location;
3327 // Are we implementing an interface ?
3329 public bool IsImplementing = false;
3334 protected DeclSpace ds;
3335 protected MemberBase member;
3336 protected int modifiers;
3337 protected MethodAttributes flags;
3338 protected bool is_method;
3339 protected string accessor_name;
3340 protected Type declaring_type;
3343 // It can either hold a string with the condition, or an arraylist of conditions.
3344 object conditionals;
3347 MethodBuilder builder = null;
3348 public MethodBuilder MethodBuilder {
3354 public Type DeclaringType {
3356 return declaring_type;
3360 public MethodData (DeclSpace ds, MemberBase member, string name, Type return_type,
3361 Type [] parameter_types, InternalParameters parameters,
3362 CallingConventions cc, Attributes opt_attrs,
3363 int modifiers, MethodAttributes flags, bool is_method)
3366 this.member = member;
3367 this.accessor_name = name;
3368 this.ReturnType = return_type;
3369 this.ParameterTypes = parameter_types;
3370 this.ParameterInfo = parameters;
3371 this.CallingConventions = cc;
3372 this.OptAttributes = opt_attrs;
3373 this.modifiers = modifiers;
3375 this.is_method = is_method;
3376 this.Location = member.Location;
3377 this.conditionals = null;
3380 public MethodData (DeclSpace ds, MemberBase member, string name, Type return_type,
3381 Type [] parameter_types, InternalParameters parameters,
3382 CallingConventions cc, Attributes opt_attrs,
3383 int modifiers, MethodAttributes flags, bool is_method,
3384 MethodBuilder builder, GenericMethod generic)
3385 : this (ds, member, name, return_type, parameter_types, parameters,
3386 cc, opt_attrs, modifiers, flags, is_method)
3388 this.builder = builder;
3389 this.GenericMethod = generic;
3395 Attribute dllimport_attribute = null;
3396 string obsolete = null;
3397 bool obsolete_error = false;
3399 public virtual bool ApplyAttributes (Attributes opt_attrs, bool is_method)
3401 if ((opt_attrs == null) || (opt_attrs.AttributeSections == null))
3404 foreach (AttributeSection asec in opt_attrs.AttributeSections) {
3405 if (asec.Attributes == null)
3408 foreach (Attribute a in asec.Attributes) {
3409 if (a.Name == "Conditional") {
3410 if (!ApplyConditionalAttribute (a))
3412 } else if (a.Name == "Obsolete") {
3413 if (!ApplyObsoleteAttribute (a))
3415 } else if (a.Name.IndexOf ("DllImport") != -1) {
3417 a.Type = TypeManager.dllimport_type;
3418 Attribute.Error_AttributeNotValidForElement (a, Location);
3421 if (!ApplyDllImportAttribute (a))
3431 // Applies the `DllImport' attribute to the method.
3433 protected virtual bool ApplyDllImportAttribute (Attribute a)
3435 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3436 if ((modifiers & extern_static) != extern_static) {
3437 Report.Error (601, Location,
3438 "The DllImport attribute must be specified on a method " +
3439 "marked `static' and `extern'.");
3443 flags |= MethodAttributes.PinvokeImpl;
3444 dllimport_attribute = a;
3449 // Applies the `Obsolete' attribute to the method.
3451 protected virtual bool ApplyObsoleteAttribute (Attribute a)
3453 if (obsolete != null) {
3454 Report.Error (579, Location, "Duplicate `Obsolete' attribute");
3458 obsolete = a.Obsolete_GetObsoleteMessage (out obsolete_error);
3459 return obsolete != null;
3463 // Applies the `Conditional' attribute to the method.
3465 protected virtual bool ApplyConditionalAttribute (Attribute a)
3467 // The Conditional attribute is only valid on methods.
3469 Attribute.Error_AttributeNotValidForElement (a, Location);
3473 string condition = a.Conditional_GetConditionName ();
3475 if (condition == null)
3478 if (ReturnType != TypeManager.void_type) {
3479 Report.Error (578, Location,
3480 "Conditional not valid on `" + member.Name + "' " +
3481 "because its return type is not void");
3485 if ((modifiers & Modifiers.OVERRIDE) != 0) {
3486 Report.Error (243, Location,
3487 "Conditional not valid on `" + member.Name + "' " +
3488 "because it is an override method");
3492 if (member.IsExplicitImpl) {
3493 Report.Error (577, Location,
3494 "Conditional not valid on `" + member.Name + "' " +
3495 "because it is an explicit interface implementation");
3499 if (IsImplementing) {
3500 Report.Error (623, Location,
3501 "Conditional not valid on `" + member.Name + "' " +
3502 "because it is an interface method");
3507 // The likelyhood that the conditional will be more than 1 is very slim
3509 if (conditionals == null)
3510 conditionals = condition;
3511 else if (conditionals is string){
3512 string s = (string) conditionals;
3513 conditionals = new ArrayList ();
3514 ((ArrayList)conditionals).Add (s);
3516 ((ArrayList)conditionals).Add (condition);
3522 // Checks whether this method should be ignored due to its Conditional attributes.
3524 bool ShouldIgnore (Location loc)
3526 // When we're overriding a virtual method, we implicitly inherit the
3527 // Conditional attributes from our parent.
3528 if (member.ParentMethod != null) {
3529 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (
3530 member.ParentMethod, loc);
3532 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
3536 if (conditionals != null){
3537 if (conditionals is string){
3538 if (RootContext.AllDefines [conditionals] == null)
3541 foreach (string condition in (ArrayList) conditionals)
3542 if (RootContext.AllDefines [condition] == null)
3550 // Returns the TypeManager.MethodFlags for this method.
3551 // This emits an error 619 / warning 618 if the method is obsolete.
3552 // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
3554 public virtual TypeManager.MethodFlags GetMethodFlags (Location loc)
3556 TypeManager.MethodFlags flags = 0;
3558 if (obsolete != null) {
3559 if (obsolete_error) {
3560 Report.Error (619, loc, "Method `" + member.Name +
3561 "' is obsolete: `" + obsolete + "'");
3562 return TypeManager.MethodFlags.IsObsoleteError;
3564 Report.Warning (618, loc, "Method `" + member.Name +
3565 "' is obsolete: `" + obsolete + "'");
3567 flags |= TypeManager.MethodFlags.IsObsolete;
3570 if (ShouldIgnore (loc))
3571 flags |= TypeManager.MethodFlags.ShouldIgnore;
3576 public virtual bool Define (TypeContainer container)
3578 MethodInfo implementing = null;
3579 string method_name, name, prefix;
3581 if (OptAttributes != null)
3582 if (!ApplyAttributes (OptAttributes, is_method))
3585 if (member.IsExplicitImpl)
3586 prefix = member.InterfaceType.FullName + ".";
3590 if (accessor_name != null)
3591 name = accessor_name + "_" + member.ShortName;
3593 name = member.ShortName;
3594 method_name = prefix + name;
3596 if (container.Pending != null){
3597 if (member is Indexer)
3598 implementing = container.Pending.IsInterfaceIndexer (
3599 member.InterfaceType, ReturnType, ParameterTypes);
3601 implementing = container.Pending.IsInterfaceMethod (
3602 member.InterfaceType, name, ReturnType, ParameterTypes);
3604 if (member.InterfaceType != null && implementing == null){
3605 Report.Error (539, Location, "'{0}' in explicit interface declaration is not an interface", method_name);
3611 // For implicit implementations, make sure we are public, for
3612 // explicit implementations, make sure we are private.
3614 if (implementing != null){
3616 // Setting null inside this block will trigger a more
3617 // verbose error reporting for missing interface implementations
3619 // The "candidate" function has been flagged already
3620 // but it wont get cleared
3622 if (member.IsExplicitImpl){
3623 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
3624 Modifiers.Error_InvalidModifier (Location, "public, virtual or abstract");
3625 implementing = null;
3627 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
3628 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
3630 // If this is an interface method implementation,
3631 // check for public accessibility
3633 implementing = null;
3634 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
3635 // We may never be private.
3636 implementing = null;
3637 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
3639 // We may be protected if we're overriding something.
3641 implementing = null;
3646 // Static is not allowed
3648 if ((modifiers & Modifiers.STATIC) != 0){
3649 implementing = null;
3650 Modifiers.Error_InvalidModifier (Location, "static");
3655 // If implementing is still valid, set flags
3657 if (implementing != null){
3659 // When implementing interface methods, set NewSlot
3660 // unless, we are overwriting a method.
3662 if (implementing.DeclaringType.IsInterface){
3663 if ((modifiers & Modifiers.OVERRIDE) == 0)
3664 flags |= MethodAttributes.NewSlot;
3667 MethodAttributes.Virtual |
3668 MethodAttributes.HideBySig;
3670 // Set Final unless we're virtual, abstract or already overriding a method.
3671 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
3672 flags |= MethodAttributes.Final;
3674 // Get the method name from the explicit interface.
3675 if (member.InterfaceType != null) {
3676 name = implementing.Name;
3677 method_name = prefix + name;
3680 IsImplementing = true;
3683 ec = new EmitContext (
3684 container, ds, Location, null, ReturnType, modifiers, false);
3687 // Create the MethodBuilder for the method
3689 if ((flags & MethodAttributes.PinvokeImpl) != 0) {
3690 if ((modifiers & Modifiers.STATIC) == 0) {
3691 Report.Error (601, Location,
3692 "The DllImport attribute must be specified on " +
3693 "a method marked 'static' and 'extern'.");
3696 builder = dllimport_attribute.DefinePInvokeMethod (
3697 ec, container.TypeBuilder, method_name, flags,
3698 ReturnType, ParameterTypes);
3699 } else if (builder == null)
3700 builder = container.TypeBuilder.DefineMethod (
3701 method_name, flags, CallingConventions,
3702 ReturnType, ParameterTypes);
3704 builder.SetGenericMethodSignature (
3705 flags, CallingConventions,
3706 ReturnType, ParameterTypes);
3708 if (builder == null)
3711 if (GenericMethod != null) {
3712 if (!GenericMethod.DefineType (ec, builder))
3716 if (container.CurrentType != null)
3717 declaring_type = container.CurrentType.ResolveType (ec);
3719 declaring_type = container.TypeBuilder;
3721 if ((modifiers & Modifiers.UNSAFE) != 0)
3722 builder.InitLocals = false;
3724 if (IsImplementing){
3726 // clear the pending implemntation flag
3728 if (member is Indexer) {
3729 container.Pending.ImplementIndexer (
3730 member.InterfaceType, builder, ReturnType,
3731 ParameterTypes, true);
3733 container.Pending.ImplementMethod (
3734 member.InterfaceType, name, ReturnType,
3735 ParameterTypes, member.IsExplicitImpl);
3737 if (member.IsExplicitImpl)
3738 container.TypeBuilder.DefineMethodOverride (
3739 builder, implementing);
3743 if (!TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes)) {
3744 Report.Error (111, Location,
3745 "Class `" + container.Name +
3746 "' already contains a definition with the " +
3747 "same return value and parameter types as the " +
3748 "'get' method of property `" + member.Name + "'");
3752 TypeManager.AddMethod (builder, this);
3760 public virtual void Emit (TypeContainer container, Block block, object kind)
3765 if ((flags & MethodAttributes.PinvokeImpl) == 0)
3766 ig = builder.GetILGenerator ();
3770 ec = new EmitContext (container, ds, Location, ig, ReturnType, modifiers, false);
3772 if (OptAttributes != null)
3773 Attribute.ApplyAttributes (ec, builder, kind, OptAttributes);
3775 if (member is MethodCore)
3776 MethodCore.LabelParameters (ec, MethodBuilder,
3777 ((MethodCore) member).Parameters,
3781 SymbolWriter sw = CodeGen.SymbolWriter;
3784 // abstract or extern methods have no bodies
3786 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
3787 if (block == null) {
3788 if ((sw != null) && ((modifiers & Modifiers.EXTERN) != 0) &&
3789 !Location.IsNull (Location) &&
3790 (Location.SymbolDocument != null)) {
3791 sw.OpenMethod (container, MethodBuilder, Location, Location);
3799 // abstract or extern methods have no bodies.
3801 if ((modifiers & Modifiers.ABSTRACT) != 0)
3803 500, Location, "Abstract method `" +
3804 TypeManager.CSharpSignature (builder) +
3805 "' can not have a body");
3807 if ((modifiers & Modifiers.EXTERN) != 0)
3809 179, Location, "External method `" +
3810 TypeManager.CSharpSignature (builder) +
3811 "' can not have a body");
3817 // Methods must have a body unless they're extern or abstract
3819 if (block == null) {
3821 501, Location, "Method `" +
3822 TypeManager.CSharpSignature (builder) +
3823 "' must declare a body since it is not marked " +
3824 "abstract or extern");
3829 // Handle destructors specially
3831 // FIXME: This code generates buggy code
3833 if ((sw != null) && !Location.IsNull (Location) &&
3834 !Location.IsNull (block.EndLocation) &&
3835 (Location.SymbolDocument != null)) {
3836 sw.OpenMethod (container, MethodBuilder, Location, block.EndLocation);
3838 if (member is Destructor)
3839 EmitDestructor (ec, block);
3841 ec.EmitTopBlock (block, ParameterInfo, Location);
3845 if (member is Destructor)
3846 EmitDestructor (ec, block);
3848 ec.EmitTopBlock (block, ParameterInfo, Location);
3852 void EmitDestructor (EmitContext ec, Block block)
3854 ILGenerator ig = ec.ig;
3856 Label finish = ig.DefineLabel ();
3858 block.SetDestructor ();
3860 ig.BeginExceptionBlock ();
3861 ec.ReturnLabel = finish;
3862 ec.HasReturnLabel = true;
3863 ec.EmitTopBlock (block, null, Location);
3865 // ig.MarkLabel (finish);
3866 ig.BeginFinallyBlock ();
3868 if (ec.ContainerType.BaseType != null) {
3869 Expression member_lookup = Expression.MemberLookup (
3870 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
3871 "Finalize", 0, MemberTypes.Method, Expression.AllBindingFlags, Location);
3873 if (member_lookup != null){
3874 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
3876 ig.Emit (OpCodes.Ldarg_0);
3877 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
3881 ig.EndExceptionBlock ();
3882 //ig.MarkLabel (ec.ReturnLabel);
3883 ig.Emit (OpCodes.Ret);
3887 public class Destructor : Method {
3889 public Destructor (DeclSpace ds, Expression return_type, int mod, string name,
3890 Parameters parameters, Attributes attrs, Location l)
3891 : base (ds, return_type, mod, false, new MemberName (name),
3892 parameters, attrs, l)
3897 abstract public class MemberBase : MemberCore {
3898 public Expression Type;
3900 protected MethodAttributes flags;
3902 protected readonly int explicit_mod_flags;
3904 public readonly MemberName MemberName;
3907 // The "short" name of this property / indexer / event. This is the
3908 // name without the explicit interface.
3910 public string ShortName;
3913 // The type of this property / indexer / event
3915 public Type MemberType;
3918 // If true, this is an explicit interface implementation
3920 public bool IsExplicitImpl = false;
3923 // The name of the interface we are explicitly implementing
3925 public Expression ExplicitInterfaceName = null;
3928 // Whether this is an interface member.
3930 public bool IsInterface;
3933 // If true, the interface type we are explicitly implementing
3935 public Type InterfaceType = null;
3938 // The method we're overriding if this is an override method.
3940 protected MethodInfo parent_method = null;
3941 public MethodInfo ParentMethod {
3943 return parent_method;
3948 // The constructor is only exposed to our children
3950 protected MemberBase (Expression type, int mod, int allowed_mod, int def_mod,
3951 MemberName name, Attributes attrs, Location loc)
3952 : base (name.GetMemberName (), attrs, loc)
3954 explicit_mod_flags = mod;
3957 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
3960 protected virtual bool CheckBase (TypeContainer container)
3962 if ((container is Struct) || (RootContext.WarningLevel > 3)){
3963 if ((ModFlags & Modifiers.PROTECTED) != 0 && (container.ModFlags & Modifiers.SEALED) != 0){
3964 if (container is Struct){
3965 Report.Error (666, Location, "Protected member in struct declaration");
3968 Report.Warning (628, Location, "Member " + container.MakeName (Name) + " protected in sealed class");
3974 protected void WarningNotHiding (TypeContainer parent)
3978 "The member " + parent.MakeName (Name) + " does not hide an " +
3979 "inherited member. The keyword new is not required");
3983 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method,
3987 // FIXME: report the old/new permissions?
3990 507, Location, parent.MakeName (Name) +
3991 ": can't change the access modifiers when overriding inherited " +
3992 "member `" + name + "'");
3996 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3997 // that have been defined.
3999 // `name' is the user visible name for reporting errors (this is used to
4000 // provide the right name regarding method names and properties)
4002 protected bool CheckMethodAgainstBase (TypeContainer parent, MethodAttributes my_attrs,
4003 MethodInfo mb, string name)
4007 if ((ModFlags & Modifiers.OVERRIDE) != 0){
4008 if (!(mb.IsAbstract || mb.IsVirtual)){
4010 506, Location, parent.MakeName (Name) +
4011 ": cannot override inherited member `" +
4012 name + "' because it is not " +
4013 "virtual, abstract or override");
4017 // Now we check that the overriden method is not final
4020 // This happens when implementing interface methods.
4021 if (mb.IsHideBySig && mb.IsVirtual) {
4023 506, Location, parent.MakeName (Name) +
4024 ": cannot override inherited member `" +
4025 name + "' because it is not " +
4026 "virtual, abstract or override");
4028 Report.Error (239, Location, parent.MakeName (Name) + " : cannot " +
4029 "override inherited member `" + name +
4030 "' because it is sealed.");
4034 // Check that the permissions are not being changed
4036 MethodAttributes thisp = my_attrs & MethodAttributes.MemberAccessMask;
4037 MethodAttributes parentp = mb.Attributes & MethodAttributes.MemberAccessMask;
4040 // special case for "protected internal"
4043 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
4045 // when overriding protected internal, the method can be declared
4046 // protected internal only within the same assembly
4049 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
4050 if (parent.TypeBuilder.Assembly != mb.DeclaringType.Assembly){
4052 // assemblies differ - report an error
4055 Error_CannotChangeAccessModifiers (parent, mb, name);
4057 } else if (thisp != parentp) {
4059 // same assembly, but other attributes differ - report an error
4062 Error_CannotChangeAccessModifiers (parent, mb, name);
4065 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
4067 // if it's not "protected internal", it must be "protected"
4070 Error_CannotChangeAccessModifiers (parent, mb, name);
4072 } else if (parent.TypeBuilder.Assembly == mb.DeclaringType.Assembly) {
4074 // protected within the same assembly - an error
4076 Error_CannotChangeAccessModifiers (parent, mb, name);
4078 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
4079 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
4081 // protected ok, but other attributes differ - report an error
4083 Error_CannotChangeAccessModifiers (parent, mb, name);
4087 if (thisp != parentp){
4088 Error_CannotChangeAccessModifiers (parent, mb, name);
4094 if (mb.IsVirtual || mb.IsAbstract){
4095 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
4096 if (Name != "Finalize"){
4098 114, 2, Location, parent.MakeName (Name) +
4099 " hides inherited member `" + name +
4100 "'. To make the current member override that " +
4101 "implementation, add the override keyword, " +
4102 "otherwise use the new keyword");
4103 ModFlags |= Modifiers.NEW;
4107 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
4108 if (Name != "Finalize"){
4110 108, 1, Location, "The keyword new is required on " +
4111 parent.MakeName (Name) + " because it hides " +
4112 "inherited member `" + name + "'");
4113 ModFlags |= Modifiers.NEW;
4121 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4125 foreach (Type partype in parameters){
4126 if (partype.IsPointer){
4129 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4133 if (ds.AsAccessible (partype, ModFlags))
4136 if (this is Indexer)
4137 Report.Error (55, Location,
4138 "Inconsistent accessibility: parameter type `" +
4139 TypeManager.CSharpName (partype) + "' is less " +
4140 "accessible than indexer `" + Name + "'");
4141 else if ((this is Method) && ((Method) this).IsOperator)
4142 Report.Error (57, Location,
4143 "Inconsistent accessibility: parameter type `" +
4144 TypeManager.CSharpName (partype) + "' is less " +
4145 "accessible than operator `" + Name + "'");
4147 Report.Error (51, Location,
4148 "Inconsistent accessibility: parameter type `" +
4149 TypeManager.CSharpName (partype) + "' is less " +
4150 "accessible than method `" + Name + "'");
4157 protected virtual bool DoDefine (DeclSpace decl, TypeContainer container)
4163 ModFlags = Modifiers.PUBLIC |
4164 Modifiers.ABSTRACT |
4167 flags = MethodAttributes.Public |
4168 MethodAttributes.Abstract |
4169 MethodAttributes.HideBySig |
4170 MethodAttributes.NewSlot |
4171 MethodAttributes.Virtual;
4173 if (!container.MethodModifiersValid (ModFlags, Name, Location))
4176 flags = Modifiers.MethodAttr (ModFlags);
4179 // Lookup Type, verify validity
4180 MemberType = decl.ResolveType (Type, false, Location);
4181 if (MemberType == null)
4184 if ((container.ModFlags & Modifiers.SEALED) != 0){
4185 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
4186 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
4191 // verify accessibility
4192 if (!container.AsAccessible (MemberType, ModFlags)) {
4193 if (this is Property)
4194 Report.Error (53, Location,
4195 "Inconsistent accessibility: property type `" +
4196 TypeManager.CSharpName (MemberType) + "' is less " +
4197 "accessible than property `" + Name + "'");
4198 else if (this is Indexer)
4199 Report.Error (54, Location,
4200 "Inconsistent accessibility: indexer return type `" +
4201 TypeManager.CSharpName (MemberType) + "' is less " +
4202 "accessible than indexer `" + Name + "'");
4203 else if (this is Method) {
4204 if (((Method) this).IsOperator)
4205 Report.Error (56, Location,
4206 "Inconsistent accessibility: return type `" +
4207 TypeManager.CSharpName (MemberType) + "' is less " +
4208 "accessible than operator `" + Name + "'");
4210 Report.Error (50, Location,
4211 "Inconsistent accessibility: return type `" +
4212 TypeManager.CSharpName (MemberType) + "' is less " +
4213 "accessible than method `" + Name + "'");
4215 Report.Error (52, Location,
4216 "Inconsistent accessibility: field type `" +
4217 TypeManager.CSharpName (MemberType) + "' is less " +
4218 "accessible than field `" + Name + "'");
4222 if (MemberType.IsPointer && !UnsafeOK (container))
4226 // Check for explicit interface implementation
4228 if (MemberName.Left != null) {
4229 ExplicitInterfaceName = MemberName.Left.GetTypeExpression (Location);
4230 ShortName = MemberName.Name;
4234 if (ExplicitInterfaceName != null) {
4235 InterfaceType = container.ResolveType (
4236 ExplicitInterfaceName, false, Location);
4237 if (InterfaceType == null)
4240 if (InterfaceType.IsClass) {
4241 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", ExplicitInterfaceName);
4245 // Compute the full name that we need to export.
4246 Name = InterfaceType.FullName + "." + ShortName;
4248 if (!container.VerifyImplements (InterfaceType, ShortName, Name, Location))
4251 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
4253 IsExplicitImpl = true;
4255 IsExplicitImpl = false;
4262 // Fields and Events both generate FieldBuilders, we use this to share
4263 // their common bits. This is also used to flag usage of the field
4265 abstract public class FieldBase : MemberBase {
4266 public FieldBuilder FieldBuilder;
4267 public Status status;
4270 public enum Status : byte { ASSIGNED = 1, USED = 2 }
4273 // The constructor is only exposed to our children
4275 protected FieldBase (Expression type, int mod, int allowed_mod, MemberName name,
4276 object init, Attributes attrs, Location loc)
4277 : base (type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
4283 // Whether this field has an initializer.
4285 public bool HasInitializer {
4287 return init != null;
4291 protected readonly Object init;
4293 Expression init_expr;
4294 bool init_expr_initialized = false;
4297 // Resolves and returns the field initializer.
4299 public Expression GetInitializerExpression (EmitContext ec)
4301 if (init_expr_initialized)
4305 if (init is Expression)
4306 e = (Expression) init;
4308 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
4310 ec.IsFieldInitializer = true;
4311 e = e.DoResolve (ec);
4312 ec.IsFieldInitializer = false;
4315 init_expr_initialized = true;
4320 public void SetAssigned ()
4322 status |= Status.ASSIGNED;
4327 // The Field class is used to represents class/struct fields during parsing.
4329 public class Field : FieldBase {
4331 // Modifiers allowed in a class declaration
4333 const int AllowedModifiers =
4336 Modifiers.PROTECTED |
4337 Modifiers.INTERNAL |
4340 Modifiers.VOLATILE |
4344 public Field (Expression type, int mod, string name, Object expr_or_array_init,
4345 Attributes attrs, Location loc)
4346 : base (type, mod, AllowedModifiers, new MemberName (name),
4347 expr_or_array_init, attrs, loc)
4351 public override bool Define (TypeContainer container)
4353 Type t = container.ResolveType (Type, false, Location);
4358 CheckBase (container);
4360 if (!container.AsAccessible (t, ModFlags)) {
4361 Report.Error (52, Location,
4362 "Inconsistent accessibility: field type `" +
4363 TypeManager.CSharpName (t) + "' is less " +
4364 "accessible than field `" + Name + "'");
4368 if (t.IsPointer && !UnsafeOK (container))
4371 if (RootContext.WarningLevel > 1){
4372 Type ptype = container.TypeBuilder.BaseType;
4374 // ptype is only null for System.Object while compiling corlib.
4376 TypeContainer.FindMembers (
4377 ptype, MemberTypes.Method,
4378 BindingFlags.Public |
4379 BindingFlags.Static | BindingFlags.Instance,
4380 System.Type.FilterName, Name);
4384 if ((ModFlags & Modifiers.VOLATILE) != 0){
4388 if (TypeManager.IsEnumType (vt))
4389 vt = TypeManager.EnumToUnderlying (t);
4391 if (!((vt == TypeManager.bool_type) ||
4392 (vt == TypeManager.sbyte_type) ||
4393 (vt == TypeManager.byte_type) ||
4394 (vt == TypeManager.short_type) ||
4395 (vt == TypeManager.ushort_type) ||
4396 (vt == TypeManager.int32_type) ||
4397 (vt == TypeManager.uint32_type) ||
4398 (vt == TypeManager.char_type) ||
4399 (vt == TypeManager.float_type))){
4401 677, Location, container.MakeName (Name) +
4402 " A volatile field can not be of type `" +
4403 TypeManager.CSharpName (vt) + "'");
4408 if ((ModFlags & Modifiers.READONLY) != 0){
4411 "A field can not be both volatile and readonly");
4416 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
4418 if (container is Struct &&
4419 ((fa & FieldAttributes.Static) == 0) &&
4420 t == container.TypeBuilder &&
4421 !TypeManager.IsBuiltinType (t)){
4422 Report.Error (523, Location, "Struct member `" + container.Name + "." + Name +
4423 "' causes a cycle in the structure layout");
4428 FieldBuilder = container.TypeBuilder.DefineField (
4429 Name, t, Modifiers.FieldAttr (ModFlags));
4431 TypeManager.RegisterFieldBase (FieldBuilder, this);
4433 catch (ArgumentException) {
4434 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
4441 public void Emit (TypeContainer tc)
4443 EmitContext ec = new EmitContext (tc, Location, null,
4444 FieldBuilder.FieldType, ModFlags);
4446 Attribute.ApplyAttributes (ec, FieldBuilder, this, OptAttributes);
4451 // `set' and `get' accessors are represented with an Accessor.
4453 public class Accessor {
4455 // Null if the accessor is empty, or a Block if not
4458 public Attributes OptAttributes;
4460 public Accessor (Block b, Attributes attrs)
4463 OptAttributes = attrs;
4468 // Properties and Indexers both generate PropertyBuilders, we use this to share
4469 // their common bits.
4471 abstract public class PropertyBase : MethodCore {
4472 public Accessor Get, Set;
4473 public PropertyBuilder PropertyBuilder;
4474 public MethodBuilder GetBuilder, SetBuilder;
4475 public MethodData GetData, SetData;
4477 protected EmitContext ec;
4479 public PropertyBase (DeclSpace ds, Expression type, int mod_flags,
4480 int allowed_mod, bool is_iface, MemberName name,
4481 Parameters parameters, Attributes attrs,
4482 Accessor get_block, Accessor set_block,
4484 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
4485 attrs, parameters, loc)
4491 protected override bool DoDefine (DeclSpace decl, TypeContainer container)
4493 if (!base.DoDefine (decl, container))
4496 ec = new EmitContext (container, Location, null, MemberType, ModFlags);
4502 // Checks our base implementation if any
4504 protected override bool CheckBase (TypeContainer container)
4506 base.CheckBase (container);
4508 // Check whether arguments were correct.
4509 if (!DoDefineParameters ())
4516 // Check in our class for dups
4518 ArrayList ar = container.Properties;
4520 int arLen = ar.Count;
4522 for (int i = 0; i < arLen; i++) {
4523 Property m = (Property) ar [i];
4524 if (IsDuplicateImplementation (container, m))
4533 MethodSignature ms, base_ms;
4534 if (this is Indexer) {
4535 string name, base_name;
4537 report_name = "this";
4538 name = TypeManager.IndexerPropertyName (container.TypeBuilder);
4539 ms = new MethodSignature (name, null, ParameterTypes);
4540 base_name = TypeManager.IndexerPropertyName (container.TypeBuilder.BaseType);
4541 base_ms = new MethodSignature (base_name, null, ParameterTypes);
4544 ms = base_ms = new MethodSignature (Name, null, ParameterTypes);
4548 // Verify if the parent has a type with the same name, and then
4549 // check whether we have to create a new slot for it or not.
4551 Type ptype = container.TypeBuilder.BaseType;
4553 // ptype is only null for System.Object while compiling corlib.
4554 if (ptype == null) {
4555 if ((ModFlags & Modifiers.NEW) != 0)
4556 WarningNotHiding (container);
4561 PropertyInfo parent_property = null;
4564 // Explicit implementations do not have `parent' methods, however,
4565 // the member cache stores them there. Without this check, we get
4566 // an incorrect warning in corlib.
4568 if (! IsExplicitImpl) {
4569 parent_property = (PropertyInfo) ((IMemberContainer)container).Parent.MemberCache.FindMemberToOverride (
4570 container.TypeBuilder, Name, ParameterTypes, true);
4573 if (parent_property != null) {
4574 string name = parent_property.DeclaringType.Name + "." +
4575 parent_property.Name;
4577 MethodInfo get, set, parent_method;
4578 get = parent_property.GetGetMethod (true);
4579 set = parent_property.GetSetMethod (true);
4582 parent_method = get;
4583 else if (set != null)
4584 parent_method = set;
4586 throw new Exception ("Internal error!");
4588 if (!CheckMethodAgainstBase (container, flags, parent_method, name))
4591 if ((ModFlags & Modifiers.NEW) == 0) {
4592 Type parent_type = TypeManager.TypeToCoreType (
4593 parent_property.PropertyType);
4595 if (parent_type != MemberType) {
4597 508, Location, container.MakeName (Name) + ": cannot " +
4598 "change return type when overriding " +
4599 "inherited member " + name);
4604 if ((ModFlags & Modifiers.NEW) != 0)
4605 WarningNotHiding (container);
4607 if ((ModFlags & Modifiers.OVERRIDE) != 0){
4608 if (this is Indexer)
4609 Report.Error (115, Location,
4610 container.MakeName (Name) +
4611 " no suitable indexers found to override");
4613 Report.Error (115, Location,
4614 container.MakeName (Name) +
4615 " no suitable properties found to override");
4622 public void Emit (TypeContainer tc)
4625 // The PropertyBuilder can be null for explicit implementations, in that
4626 // case, we do not actually emit the ".property", so there is nowhere to
4627 // put the attribute
4629 if (PropertyBuilder != null)
4630 Attribute.ApplyAttributes (ec, PropertyBuilder, this, OptAttributes);
4632 if (GetData != null) {
4633 GetData.Emit (tc, Get.Block, Get);
4637 if (SetData != null) {
4638 SetData.Emit (tc, Set.Block, Set);
4644 public class Property : PropertyBase, IIteratorContainer {
4645 const int AllowedModifiers =
4648 Modifiers.PROTECTED |
4649 Modifiers.INTERNAL |
4653 Modifiers.OVERRIDE |
4654 Modifiers.ABSTRACT |
4657 Modifiers.METHOD_YIELDS |
4660 const int AllowedInterfaceModifiers =
4663 public Property (DeclSpace ds, Expression type, int mod_flags, bool is_iface,
4664 MemberName name, Attributes attrs, Accessor get_block,
4665 Accessor set_block, Location loc)
4666 : base (ds, type, mod_flags,
4667 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4668 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
4669 get_block, set_block, loc)
4673 public override bool Define (TypeContainer container)
4675 if (!DoDefine (container, container))
4678 if (!CheckBase (container))
4681 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
4684 Type [] parameters = TypeManager.NoTypes;
4686 InternalParameters ip = new InternalParameters (
4687 container, Parameters.EmptyReadOnlyParameters);
4689 GetData = new MethodData (container, this, "get", MemberType,
4690 parameters, ip, CallingConventions.Standard,
4691 Get.OptAttributes, ModFlags, flags, false);
4694 // Setup iterator if we are one
4696 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4697 IteratorHandler ih = new IteratorHandler (
4698 "get", container, MemberType,
4699 parameters, ip, ModFlags, Location);
4701 Block new_block = ih.Setup (block);
4702 if (new_block == null)
4707 if (!GetData.Define (container))
4710 GetBuilder = GetData.MethodBuilder;
4714 Type [] parameters = new Type [1];
4715 parameters [0] = MemberType;
4717 Parameter [] parms = new Parameter [1];
4718 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
4719 InternalParameters ip = new InternalParameters (
4720 container, new Parameters (parms, null, Location));
4722 SetData = new MethodData (container, this, "set", TypeManager.void_type,
4723 parameters, ip, CallingConventions.Standard,
4724 Set.OptAttributes, ModFlags, flags, false);
4726 if (!SetData.Define (container))
4729 SetBuilder = SetData.MethodBuilder;
4730 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4733 // FIXME - PropertyAttributes.HasDefault ?
4735 PropertyAttributes prop_attr = PropertyAttributes.None;
4737 prop_attr |= PropertyAttributes.RTSpecialName |
4738 PropertyAttributes.SpecialName;
4740 if (!IsExplicitImpl){
4741 PropertyBuilder = container.TypeBuilder.DefineProperty (
4742 Name, prop_attr, MemberType, null);
4745 PropertyBuilder.SetGetMethod (GetBuilder);
4748 PropertyBuilder.SetSetMethod (SetBuilder);
4751 // HACK for the reasons exposed above
4753 if (!TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder)) {
4756 "Class `" + container.Name +
4757 "' already contains a definition for the property `" +
4765 public void SetYields ()
4767 ModFlags |= Modifiers.METHOD_YIELDS;
4772 /// Gigantic workaround for lameness in SRE follows :
4773 /// This class derives from EventInfo and attempts to basically
4774 /// wrap around the EventBuilder so that FindMembers can quickly
4775 /// return this in it search for members
4777 public class MyEventBuilder : EventInfo {
4780 // We use this to "point" to our Builder which is
4781 // not really a MemberInfo
4783 EventBuilder MyBuilder;
4786 // We "catch" and wrap these methods
4788 MethodInfo raise, remove, add;
4790 EventAttributes attributes;
4791 Type declaring_type, reflected_type, event_type;
4796 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
4798 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
4800 // And now store the values in our own fields.
4802 declaring_type = type_builder;
4804 reflected_type = type_builder;
4806 attributes = event_attr;
4809 this.event_type = event_type;
4813 // Methods that you have to override. Note that you only need
4814 // to "implement" the variants that take the argument (those are
4815 // the "abstract" methods, the others (GetAddMethod()) are
4818 public override MethodInfo GetAddMethod (bool nonPublic)
4823 public override MethodInfo GetRemoveMethod (bool nonPublic)
4828 public override MethodInfo GetRaiseMethod (bool nonPublic)
4834 // These methods make "MyEventInfo" look like a Builder
4836 public void SetRaiseMethod (MethodBuilder raiseMethod)
4838 raise = raiseMethod;
4839 MyBuilder.SetRaiseMethod (raiseMethod);
4842 public void SetRemoveOnMethod (MethodBuilder removeMethod)
4844 remove = removeMethod;
4845 MyBuilder.SetRemoveOnMethod (removeMethod);
4848 public void SetAddOnMethod (MethodBuilder addMethod)
4851 MyBuilder.SetAddOnMethod (addMethod);
4854 public void SetCustomAttribute (CustomAttributeBuilder cb)
4856 MyBuilder.SetCustomAttribute (cb);
4859 public override object [] GetCustomAttributes (bool inherit)
4861 // FIXME : There's nothing which can be seemingly done here because
4862 // we have no way of getting at the custom attribute objects of the
4867 public override object [] GetCustomAttributes (Type t, bool inherit)
4869 // FIXME : Same here !
4873 public override bool IsDefined (Type t, bool b)
4878 public override EventAttributes Attributes {
4884 public override string Name {
4890 public override Type DeclaringType {
4892 return declaring_type;
4896 public override Type ReflectedType {
4898 return reflected_type;
4902 public Type EventType {
4908 public void SetUsed ()
4910 if (my_event != null)
4911 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
4915 public class Event : FieldBase {
4916 const int AllowedModifiers =
4919 Modifiers.PROTECTED |
4920 Modifiers.INTERNAL |
4925 Modifiers.OVERRIDE |
4929 const int AllowedInterfaceModifiers =
4932 public readonly Accessor Add;
4933 public readonly Accessor Remove;
4934 public MyEventBuilder EventBuilder;
4936 public MethodBuilder AddBuilder, RemoveBuilder;
4937 MethodData AddData, RemoveData;
4939 public Event (Expression type, int mod_flags, bool is_iface, MemberName name,
4940 Object init, Attributes attrs, Accessor add, Accessor remove,
4942 : base (type, mod_flags,
4943 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4944 name, init, attrs, loc)
4948 IsInterface = is_iface;
4951 public override bool Define (TypeContainer container)
4953 EventAttributes e_attr = EventAttributes.RTSpecialName | EventAttributes.SpecialName;
4954 MethodAttributes m_attr = MethodAttributes.HideBySig | MethodAttributes.SpecialName
4956 if (!DoDefine (container, container))
4959 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
4960 Report.Error (74, Location, "'" + container.Name + "." + Name +
4961 "': abstract event can not have an initializer");
4965 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
4966 Report.Error (66, Location, "'" + container.Name + "." + Name +
4967 "' : event must be of a delegate type");
4971 Type [] parameter_types = new Type [1];
4972 parameter_types [0] = MemberType;
4974 Parameter [] parms = new Parameter [1];
4975 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
4976 InternalParameters ip = new InternalParameters (
4977 container, new Parameters (parms, null, Location));
4979 if (!CheckBase (container))
4983 // Now define the accessors
4985 AddData = new MethodData (container, this, "add", TypeManager.void_type,
4986 parameter_types, ip, CallingConventions.Standard,
4987 (Add != null) ? Add.OptAttributes : null,
4988 ModFlags, flags | m_attr, false);
4990 if (!AddData.Define (container))
4993 AddBuilder = AddData.MethodBuilder;
4994 AddBuilder.DefineParameter (1, ParameterAttributes.None, "value");
4996 RemoveData = new MethodData (container, this, "remove", TypeManager.void_type,
4997 parameter_types, ip, CallingConventions.Standard,
4998 (Remove != null) ? Remove.OptAttributes : null,
4999 ModFlags, flags | m_attr, false);
5001 if (!RemoveData.Define (container))
5004 RemoveBuilder = RemoveData.MethodBuilder;
5005 RemoveBuilder.DefineParameter (1, ParameterAttributes.None, "value");
5007 if (!IsExplicitImpl){
5008 EventBuilder = new MyEventBuilder (this,
5009 container.TypeBuilder, Name, e_attr, MemberType);
5011 if (Add == null && Remove == null) {
5012 FieldBuilder = container.TypeBuilder.DefineField (
5014 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
5015 TypeManager.RegisterPrivateFieldOfEvent (
5016 (EventInfo) EventBuilder, FieldBuilder);
5017 TypeManager.RegisterFieldBase (FieldBuilder, this);
5020 EventBuilder.SetAddOnMethod (AddBuilder);
5021 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
5023 if (!TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder)) {
5024 Report.Error (111, Location,
5025 "Class `" + container.Name +
5026 "' already contains a definition for the event `" +
5035 void EmitDefaultMethod (EmitContext ec, bool is_add)
5037 ILGenerator ig = ec.ig;
5038 MethodInfo method = null;
5041 method = TypeManager.delegate_combine_delegate_delegate;
5043 method = TypeManager.delegate_remove_delegate_delegate;
5045 if ((ModFlags & Modifiers.STATIC) != 0) {
5046 ig.Emit (OpCodes.Ldsfld, (FieldInfo) FieldBuilder);
5047 ig.Emit (OpCodes.Ldarg_0);
5048 ig.Emit (OpCodes.Call, method);
5049 ig.Emit (OpCodes.Castclass, MemberType);
5050 ig.Emit (OpCodes.Stsfld, (FieldInfo) FieldBuilder);
5052 ig.Emit (OpCodes.Ldarg_0);
5053 ig.Emit (OpCodes.Ldarg_0);
5054 ig.Emit (OpCodes.Ldfld, (FieldInfo) FieldBuilder);
5055 ig.Emit (OpCodes.Ldarg_1);
5056 ig.Emit (OpCodes.Call, method);
5057 ig.Emit (OpCodes.Castclass, MemberType);
5058 ig.Emit (OpCodes.Stfld, (FieldInfo) FieldBuilder);
5060 ig.Emit (OpCodes.Ret);
5063 public void Emit (TypeContainer tc)
5067 ec = new EmitContext (tc, Location, null, MemberType, ModFlags);
5068 Attribute.ApplyAttributes (ec, EventBuilder, this, OptAttributes);
5071 AddData.Emit (tc, Add.Block, Add);
5074 ILGenerator ig = AddData.MethodBuilder.GetILGenerator ();
5075 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
5076 EmitDefaultMethod (ec, true);
5079 if (Remove != null) {
5080 RemoveData.Emit (tc, Remove.Block, Remove);
5081 Remove.Block = null;
5083 ILGenerator ig = RemoveData.MethodBuilder.GetILGenerator ();
5084 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
5085 EmitDefaultMethod (ec, false);
5092 // FIXME: This does not handle:
5094 // int INTERFACENAME [ args ]
5099 // int this [ args ]
5101 public class Indexer : PropertyBase {
5103 const int AllowedModifiers =
5106 Modifiers.PROTECTED |
5107 Modifiers.INTERNAL |
5111 Modifiers.OVERRIDE |
5116 const int AllowedInterfaceModifiers =
5119 public string IndexerName;
5120 public string InterfaceIndexerName;
5123 // Are we implementing an interface ?
5125 public Indexer (DeclSpace ds, Expression type, int mod_flags, bool is_iface,
5126 MemberName name, Parameters parameters, Attributes attrs,
5127 Accessor get_block, Accessor set_block, Location loc)
5128 : base (ds, type, mod_flags,
5129 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
5130 is_iface, name, parameters, attrs, get_block, set_block, loc)
5134 public override bool Define (TypeContainer container)
5136 PropertyAttributes prop_attr =
5137 PropertyAttributes.RTSpecialName |
5138 PropertyAttributes.SpecialName;
5140 if (!DoDefine (container, container))
5143 IndexerName = Attribute.ScanForIndexerName (ec, OptAttributes);
5144 if (IndexerName == null)
5145 IndexerName = "Item";
5146 else if (IsExplicitImpl)
5147 Report.Error (592, Location,
5148 "Attribute 'IndexerName' is not valid on this declaration " +
5149 "type. It is valid on `property' declarations only.");
5151 ShortName = IndexerName;
5152 if (IsExplicitImpl) {
5153 InterfaceIndexerName = TypeManager.IndexerPropertyName (InterfaceType);
5154 Name = InterfaceType.FullName + "." + IndexerName;
5156 InterfaceIndexerName = IndexerName;
5160 if (!CheckNameCollision (container))
5163 if (!CheckBase (container))
5166 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
5168 InternalParameters ip = new InternalParameters (container, Parameters);
5170 GetData = new MethodData (container, this, "get", MemberType,
5171 ParameterTypes, ip, CallingConventions.Standard,
5172 Get.OptAttributes, ModFlags, flags, false);
5174 if (!GetData.Define (container))
5177 GetBuilder = GetData.MethodBuilder;
5181 int top = ParameterTypes.Length;
5182 Type [] set_pars = new Type [top + 1];
5183 ParameterTypes.CopyTo (set_pars, 0);
5184 set_pars [top] = MemberType;
5186 Parameter [] fixed_parms = Parameters.FixedParameters;
5188 if (fixed_parms == null){
5189 throw new Exception ("We currently do not support only array arguments in an indexer at: " + Location);
5190 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
5191 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
5193 // Here is the problem: the `value' parameter has
5194 // to come *after* the array parameter in the declaration
5196 // X (object [] x, Type value)
5199 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
5200 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
5204 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
5207 fixed_parms.CopyTo (tmp, 0);
5208 tmp [fixed_parms.Length] = new Parameter (
5209 Type, "value", Parameter.Modifier.NONE, null);
5211 Parameters set_formal_params = new Parameters (tmp, null, Location);
5213 InternalParameters ip = new InternalParameters (container, set_formal_params);
5215 SetData = new MethodData (container, this, "set", TypeManager.void_type,
5216 set_pars, ip, CallingConventions.Standard,
5217 Set.OptAttributes, ModFlags, flags, false);
5219 if (!SetData.Define (container))
5222 SetBuilder = SetData.MethodBuilder;
5226 // Now name the parameters
5228 Parameter [] p = Parameters.FixedParameters;
5232 for (i = 0; i < p.Length; ++i) {
5234 GetBuilder.DefineParameter (
5235 i + 1, p [i].Attributes, p [i].Name);
5238 SetBuilder.DefineParameter (
5239 i + 1, p [i].Attributes, p [i].Name);
5243 SetBuilder.DefineParameter (
5244 i + 1, ParameterAttributes.None, "value");
5246 if (i != ParameterTypes.Length) {
5247 Parameter array_param = Parameters.ArrayParameter;
5249 SetBuilder.DefineParameter (
5250 i + 1, array_param.Attributes, array_param.Name);
5255 // Define the PropertyBuilder if one of the following conditions are met:
5256 // a) we're not implementing an interface indexer.
5257 // b) the indexer has a different IndexerName and this is no
5258 // explicit interface implementation.
5260 if (!IsExplicitImpl) {
5261 PropertyBuilder = container.TypeBuilder.DefineProperty (
5262 IndexerName, prop_attr, MemberType, ParameterTypes);
5264 if (GetData != null)
5265 PropertyBuilder.SetGetMethod (GetBuilder);
5267 if (SetData != null)
5268 PropertyBuilder.SetSetMethod (SetBuilder);
5270 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder,
5277 bool CheckNameCollision (TypeContainer container) {
5278 switch (VerifyName (container)){
5279 case DeclSpace.AdditionResult.NameExists:
5280 Report.Error (102, Location, "The container '{0}' already contains a definition for '{1}'", container.GetSignatureForError (), Name);
5283 case DeclSpace.AdditionResult.Success:
5286 throw new NotImplementedException ();
5289 DeclSpace.AdditionResult VerifyName (TypeContainer container) {
5290 if (!AddIndexer (container, container.Name + "." + Name))
5291 return DeclSpace.AdditionResult.NameExists;
5294 if (!AddIndexer (container, container.Name + ".get_" + Name))
5295 return DeclSpace.AdditionResult.NameExists;
5299 if (!AddIndexer (container, container.Name + ".set_" + Name))
5300 return DeclSpace.AdditionResult.NameExists;
5302 return DeclSpace.AdditionResult.Success;
5305 bool AddIndexer (TypeContainer container, string fullname)
5307 object value = container.GetDefinition (fullname);
5309 if (value != null) {
5310 return value.GetType () != GetType () ? false : true;
5313 container.DefineName (fullname, this);
5317 public override string GetSignatureForError () {
5318 return TypeManager.CSharpSignature (PropertyBuilder, true);
5322 public class Operator : MemberBase, IIteratorContainer {
5324 const int AllowedModifiers =
5330 const int RequiredModifiers =
5334 public enum OpType : byte {
5344 // Unary and Binary operators
5367 // Implicit and Explicit
5372 public readonly OpType OperatorType;
5373 public readonly Expression ReturnType;
5374 public readonly Expression FirstArgType, SecondArgType;
5375 public readonly string FirstArgName, SecondArgName;
5377 public MethodBuilder OperatorMethodBuilder;
5379 public string MethodName;
5380 public Method OperatorMethod;
5382 public Operator (OpType type, Expression ret_type, int mod_flags,
5383 Expression arg1type, string arg1name,
5384 Expression arg2type, string arg2name,
5385 Block block, Attributes attrs, Location loc)
5386 : base (ret_type, mod_flags, AllowedModifiers, Modifiers.PUBLIC,
5387 MemberName.Null, attrs, loc)
5389 OperatorType = type;
5390 Name = "op_" + OperatorType;
5391 ReturnType = ret_type;
5392 FirstArgType = arg1type;
5393 FirstArgName = arg1name;
5394 SecondArgType = arg2type;
5395 SecondArgName = arg2name;
5399 string Prototype (TypeContainer container)
5401 return container.Name + ".operator " + OperatorType + " (" + FirstArgType + "," +
5402 SecondArgType + ")";
5405 public override bool Define (TypeContainer container)
5408 MethodName = "op_" + OperatorType;
5410 if (SecondArgType != null)
5413 Parameter [] param_list = new Parameter [length];
5415 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
5418 "User defined operators `" +
5419 Prototype (container) +
5420 "' must be declared static and public");
5424 param_list[0] = new Parameter (FirstArgType, FirstArgName,
5425 Parameter.Modifier.NONE, null);
5426 if (SecondArgType != null)
5427 param_list[1] = new Parameter (SecondArgType, SecondArgName,
5428 Parameter.Modifier.NONE, null);
5430 OperatorMethod = new Method (
5431 container, ReturnType, ModFlags, false,
5432 new MemberName (MethodName),
5433 new Parameters (param_list, null, Location),
5434 OptAttributes, Location);
5436 OperatorMethod.Block = Block;
5437 OperatorMethod.IsOperator = true;
5438 OperatorMethod.Define (container);
5440 if (OperatorMethod.MethodBuilder == null)
5443 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
5445 Type [] param_types = OperatorMethod.ParameterTypes;
5446 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
5447 Type return_type = OperatorMethod.GetReturnType ();
5448 Type first_arg_type = param_types [0];
5450 // Rules for conversion operators
5452 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
5453 if (first_arg_type == return_type && first_arg_type == declaring_type){
5456 "User-defined conversion cannot take an object of the " +
5457 "enclosing type and convert to an object of the enclosing" +
5462 if (first_arg_type != declaring_type && return_type != declaring_type){
5465 "User-defined conversion must convert to or from the " +
5470 if (first_arg_type == TypeManager.object_type ||
5471 return_type == TypeManager.object_type){
5474 "User-defined conversion cannot convert to or from " +
5479 if (first_arg_type.IsInterface || return_type.IsInterface){
5482 "User-defined conversion cannot convert to or from an " +
5487 if (first_arg_type.IsSubclassOf (return_type) ||
5488 return_type.IsSubclassOf (first_arg_type)){
5491 "User-defined conversion cannot convert between types " +
5492 "that derive from each other");
5495 } else if (SecondArgType == null) {
5496 // Checks for Unary operators
5498 if (first_arg_type != declaring_type){
5501 "The parameter of a unary operator must be the " +
5506 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
5507 if (return_type != declaring_type){
5510 "The parameter and return type for ++ and -- " +
5511 "must be the containing type");
5517 if (OperatorType == OpType.True || OperatorType == OpType.False) {
5518 if (return_type != TypeManager.bool_type){
5521 "The return type of operator True or False " +
5528 // Checks for Binary operators
5530 if (first_arg_type != declaring_type &&
5531 param_types [1] != declaring_type){
5534 "One of the parameters of a binary operator must " +
5535 "be the containing type");
5543 public void Emit (TypeContainer container)
5546 // abstract or extern methods have no bodies
5548 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
5551 OperatorMethod.Emit (container);
5555 public static string GetName (OpType ot)
5558 case OpType.LogicalNot:
5560 case OpType.OnesComplement:
5562 case OpType.Increment:
5564 case OpType.Decrement:
5570 case OpType.Addition:
5572 case OpType.Subtraction:
5574 case OpType.UnaryPlus:
5576 case OpType.UnaryNegation:
5578 case OpType.Multiply:
5580 case OpType.Division:
5582 case OpType.Modulus:
5584 case OpType.BitwiseAnd:
5586 case OpType.BitwiseOr:
5588 case OpType.ExclusiveOr:
5590 case OpType.LeftShift:
5592 case OpType.RightShift:
5594 case OpType.Equality:
5596 case OpType.Inequality:
5598 case OpType.GreaterThan:
5600 case OpType.LessThan:
5602 case OpType.GreaterThanOrEqual:
5604 case OpType.LessThanOrEqual:
5606 case OpType.Implicit:
5608 case OpType.Explicit:
5614 public override string ToString ()
5616 Type return_type = OperatorMethod.GetReturnType();
5617 Type [] param_types = OperatorMethod.ParameterTypes;
5619 if (SecondArgType == null)
5620 return String.Format (
5621 "{0} operator {1}({2})",
5622 TypeManager.CSharpName (return_type),
5623 GetName (OperatorType),
5626 return String.Format (
5627 "{0} operator {1}({2}, {3})",
5628 TypeManager.CSharpName (return_type),
5629 GetName (OperatorType),
5630 param_types [0], param_types [1]);
5633 public void SetYields ()
5635 ModFlags |= Modifiers.METHOD_YIELDS;
5640 // This is used to compare method signatures
5642 struct MethodSignature {
5644 public Type RetType;
5645 public Type [] Parameters;
5648 /// This delegate is used to extract methods which have the
5649 /// same signature as the argument
5651 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
5653 public MethodSignature (string name, Type ret_type, Type [] parameters)
5658 if (parameters == null)
5659 Parameters = TypeManager.NoTypes;
5661 Parameters = parameters;
5664 public override string ToString ()
5667 if (Parameters.Length != 0){
5668 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
5669 for (int i = 0; i < Parameters.Length; i++){
5670 sb.Append (Parameters [i]);
5671 if (i+1 < Parameters.Length)
5674 pars = sb.ToString ();
5677 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
5680 public override int GetHashCode ()
5682 return Name.GetHashCode ();
5685 public override bool Equals (Object o)
5687 MethodSignature other = (MethodSignature) o;
5689 if (other.Name != Name)
5692 if (other.RetType != RetType)
5695 if (Parameters == null){
5696 if (other.Parameters == null)
5701 if (other.Parameters == null)
5704 int c = Parameters.Length;
5705 if (other.Parameters.Length != c)
5708 for (int i = 0; i < c; i++)
5709 if (other.Parameters [i] != Parameters [i])
5715 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
5717 MethodSignature sig = (MethodSignature) filter_criteria;
5719 if (m.Name != sig.Name)
5723 MethodInfo mi = m as MethodInfo;
5724 PropertyInfo pi = m as PropertyInfo;
5727 ReturnType = mi.ReturnType;
5728 else if (pi != null)
5729 ReturnType = pi.PropertyType;
5734 // we use sig.RetType == null to mean `do not check the
5735 // method return value.
5737 if (sig.RetType != null)
5738 if (ReturnType != sig.RetType)
5743 args = TypeManager.GetArgumentTypes (mi);
5745 args = TypeManager.GetArgumentTypes (pi);
5746 Type [] sigp = sig.Parameters;
5748 if (args.Length != sigp.Length)
5751 for (int i = args.Length; i > 0; ){
5753 if (args [i] != sigp [i])