3 // class.cs: Class and Struct handlers
5 // Authors: Miguel de Icaza (miguel@gnu.org)
6 // Martin Baulig (martin@gnome.org)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002 Ximian, Inc (http://www.ximian.com)
13 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
15 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
16 // have fixed a remaining problem: not every AddXXXX was adding a
17 // fully qualified name.
19 // Now everyone registers a fully qualified name in the DeclSpace as
20 // being defined instead of the partial name.
22 // Downsides: we are slower than we need to be due to the excess
23 // copies and the names being registered this way.
25 // The reason for this is that we currently depend (on the corlib
26 // bootstrap for instance) that types are fully qualified, because
27 // we dump all the types in the namespace, and we should really have
28 // types inserted into the proper namespace, so we can only store the
29 // basenames in the defined_names array.
34 using System.Collections;
35 using System.Reflection;
36 using System.Reflection.Emit;
37 using System.Runtime.CompilerServices;
38 using System.Diagnostics.SymbolStore;
40 namespace Mono.CSharp {
43 /// This is the base class for structs and classes.
45 public class TypeContainer : DeclSpace, IMemberContainer {
46 // Holds a list of classes and structures
49 // Holds the list of properties
52 // Holds the list of enumerations
55 // Holds the list of delegates
58 // Holds the list of constructors
59 ArrayList instance_constructors;
61 // Holds the list of fields
64 // Holds a list of fields that have initializers
65 ArrayList initialized_fields;
67 // Holds a list of static fields that have initializers
68 ArrayList initialized_static_fields;
70 // Holds the list of constants
76 // Holds order in which interfaces must be closed
77 ArrayList interface_order;
88 // Holds the operators
91 // The emit context for toplevel objects.
95 // Pointers to the default constructor and the default static constructor
97 Constructor default_constructor;
98 Constructor default_static_constructor;
101 // Whether we have seen a static constructor for this class or not
103 bool have_static_constructor = false;
106 // Whether we have at least one non-static field
108 bool have_nonstatic_fields = false;
111 // This one is computed after we can distinguish interfaces
112 // from classes from the arraylist `type_bases'
114 string base_class_name;
116 ArrayList type_bases;
118 // Attributes for this type
119 protected Attributes attributes;
121 // Information in the case we are an attribute type
123 public AttributeTargets Targets = AttributeTargets.All;
124 public bool AllowMultiple = false;
125 public bool Inherited;
127 // The interfaces we implement.
130 // The parent member container and our member cache
131 IMemberContainer parent_container;
132 MemberCache member_cache;
135 // The indexer name for this class
137 public string IndexerName;
139 public TypeContainer (TypeContainer parent, string name, Location l)
140 : base (parent, name, l)
143 types = new ArrayList ();
150 base_class_name = null;
152 //Console.WriteLine ("New class " + name + " inside " + n);
155 public AdditionResult AddConstant (Const constant)
158 string basename = constant.Name;
160 if ((res = IsValid (basename)) != AdditionResult.Success)
163 if (constants == null)
164 constants = new ArrayList ();
166 constants.Add (constant);
167 DefineName (Name + "." + basename, constant);
169 return AdditionResult.Success;
172 public AdditionResult AddEnum (Mono.CSharp.Enum e)
176 if ((res = IsValid (e.Basename)) != AdditionResult.Success)
180 enums = new ArrayList ();
183 DefineName (e.Name, e);
185 return AdditionResult.Success;
188 public AdditionResult AddClass (Class c)
192 if ((res = IsValid (c.Basename)) != AdditionResult.Success)
197 DefineName (c.Name, c);
200 // FIXME: Do we really need to explicitly add an empty default static constructor?
201 if (c.default_static_constructor == null)
203 bool isModule = c is Mono.MonoBASIC.Module;
204 Constructor dc = new Constructor ("New", Parameters.EmptyReadOnlyParameters, null, c.Location);
205 dc.ModFlags = isModule ? Modifiers.PUBLIC | Modifiers.STATIC : Modifiers.PUBLIC;
206 c.AddConstructor (dc);
208 // --------------------------------------------------------------
210 return AdditionResult.Success;
213 public AdditionResult AddStruct (Struct s)
217 if ((res = IsValid (s.Basename)) != AdditionResult.Success)
220 DefineName (s.Name, s);
223 return AdditionResult.Success;
226 public AdditionResult AddDelegate (Delegate d)
230 if ((res = IsValid (d.Basename)) != AdditionResult.Success)
233 if (delegates == null)
234 delegates = new ArrayList ();
236 DefineName (d.Name, d);
239 return AdditionResult.Success;
242 public AdditionResult AddMethod (Method method)
244 string basename = method.Name;
245 string fullname = Name + "." + basename;
247 Object value = defined_names [fullname];
249 if (value != null && (!(value is Method)))
250 return AdditionResult.NameExists;
252 if (basename == Basename)
253 return AdditionResult.EnclosingClash;
256 methods = new ArrayList ();
258 if (method.Name.IndexOf (".") != -1)
259 methods.Insert (0, method);
261 methods.Add (method);
264 DefineName (fullname, method);
266 return AdditionResult.Success;
269 public AdditionResult AddConstructor (Constructor c)
272 return AdditionResult.NotAConstructor;
274 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
277 have_static_constructor = true;
278 if (default_static_constructor != null){
279 Console.WriteLine ("I have a static constructor already");
280 Console.WriteLine (" " + default_static_constructor);
281 return AdditionResult.MethodExists;
284 default_static_constructor = c;
287 if (default_constructor != null)
288 return AdditionResult.MethodExists;
289 default_constructor = c;
292 if (instance_constructors == null)
293 instance_constructors = new ArrayList ();
295 instance_constructors.Add (c);
298 return AdditionResult.Success;
301 public AdditionResult AddInterface (Interface iface)
305 if ((res = IsValid (iface.Basename)) != AdditionResult.Success)
308 if (interfaces == null)
309 interfaces = new ArrayList ();
310 interfaces.Add (iface);
311 DefineName (iface.Name, iface);
313 return AdditionResult.Success;
316 public AdditionResult AddField (Field field)
319 string basename = field.Name;
321 if ((res = IsValid (basename)) != AdditionResult.Success)
325 fields = new ArrayList ();
329 if (field.HasInitializer){
330 if ((field.ModFlags & Modifiers.STATIC) != 0) {
331 if (initialized_static_fields == null)
332 initialized_static_fields = new ArrayList ();
334 initialized_static_fields.Add (field);
337 // We have not seen a static constructor,
338 // but we will provide static initialization of fields
340 have_static_constructor = true;
342 if (initialized_fields == null)
343 initialized_fields = new ArrayList ();
345 initialized_fields.Add (field);
349 if ((field.ModFlags & Modifiers.STATIC) == 0)
350 have_nonstatic_fields = true;
352 DefineName (Name + "." + basename, field);
353 return AdditionResult.Success;
356 public AdditionResult AddProperty (Property prop)
359 string basename = prop.Name;
361 if ((res = IsValid (basename)) != AdditionResult.Success)
364 if (properties == null)
365 properties = new ArrayList ();
367 if (prop.Name.IndexOf (".") != -1)
368 properties.Insert (0, prop);
370 properties.Add (prop);
371 DefineName (Name + "." + basename, prop);
373 return AdditionResult.Success;
376 public AdditionResult AddEvent (Event e)
379 string basename = e.Name;
381 if ((res = IsValid (basename)) != AdditionResult.Success)
385 events = new ArrayList ();
388 DefineName (Name + "." + basename, e);
390 return AdditionResult.Success;
393 public AdditionResult AddIndexer (Indexer i)
395 if (indexers == null)
396 indexers = new ArrayList ();
398 if (i.InterfaceType != null)
399 indexers.Insert (0, i);
403 return AdditionResult.Success;
406 public AdditionResult AddOperator (Operator op)
408 if (operators == null)
409 operators = new ArrayList ();
413 return AdditionResult.Success;
416 public void RegisterOrder (Interface iface)
418 if (interface_order == null)
419 interface_order = new ArrayList ();
421 interface_order.Add (iface);
424 public ArrayList Types {
430 public ArrayList Methods {
436 public ArrayList Constants {
442 public ArrayList Interfaces {
450 return base_class_name;
454 public ArrayList Bases {
464 public ArrayList Fields {
474 public ArrayList InstanceConstructors {
476 return instance_constructors;
480 public ArrayList Properties {
486 public ArrayList Events {
492 public ArrayList Enums {
498 public ArrayList Indexers {
504 public ArrayList Operators {
510 public ArrayList Delegates {
516 public Attributes OptAttributes {
522 public bool HaveStaticConstructor {
524 return have_static_constructor;
528 public virtual TypeAttributes TypeAttr {
530 return Modifiers.TypeAttr (ModFlags, this);
535 // Emits the instance field initializers
537 public bool EmitFieldInitializers (EmitContext ec)
540 ILGenerator ig = ec.ig;
541 Expression instance_expr;
544 fields = initialized_static_fields;
545 instance_expr = null;
547 fields = initialized_fields;
548 instance_expr = new This (Location.Null).Resolve (ec);
554 foreach (Field f in fields){
555 Expression e = f.GetInitializerExpression (ec);
559 Location l = f.Location;
560 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
561 fe.InstanceExpression = instance_expr;
562 Expression a = new Assign (fe, e, l);
568 if (a is ExpressionStatement)
569 ((ExpressionStatement) a).EmitStatement (ec);
571 throw new Exception ("Assign.Resolve returned a non ExpressionStatement");
579 // Defines the default constructors
581 void DefineDefaultConstructor (bool is_static)
586 c = new Constructor (Basename, Parameters.EmptyReadOnlyParameters,
587 new ConstructorBaseInitializer (
588 null, Parameters.EmptyReadOnlyParameters,
593 mods = Modifiers.STATIC;
599 c.Block = new Block (null);
603 public void ReportStructInitializedInstanceError ()
605 string n = TypeBuilder.FullName;
607 foreach (Field f in initialized_fields){
610 "`" + n + "." + f.Name + "': can not have " +
611 "instance field initializers in structs");
616 /// The pending methods that need to be implemented (interfaces or abstract methods)
618 public PendingImplementation Pending;
621 /// This function computes the Base class and also the
622 /// list of interfaces that the class or struct @c implements.
624 /// The return value is an array (might be null) of
625 /// interfaces implemented (as Types).
627 /// The @parent argument is set to the parent object or null
628 /// if this is `System.Object'.
630 Type [] GetClassBases (bool is_class, out Type parent, out bool error)
632 ArrayList bases = Bases;
641 parent = TypeManager.value_type;
645 if (RootContext.StdLib)
646 parent = TypeManager.object_type;
647 else if (Name != "System.Object")
648 parent = TypeManager.object_type;
651 // If we are compiling our runtime,
652 // and we are defining ValueType, then our
653 // parent is `System.Object'.
655 if (!RootContext.StdLib && Name == "System.ValueType")
656 parent = TypeManager.object_type;
663 // Bases should be null if there are no bases at all
668 Expression name = (Expression) bases [0];
669 name = ResolveTypeExpr (name, false, Location);
676 Type first = name.Type;
682 parent = TypeManager.object_type;
686 if (!AsAccessible (parent, ModFlags))
687 Report.Error (60, Location,
688 "Inconsistent accessibility: base class `" +
689 TypeManager.CSharpName (parent) + "' is less " +
690 "accessible than class `" +
697 Type [] ifaces = new Type [count-start];
699 for (i = start, j = 0; i < count; i++, j++){
700 Expression name = (Expression) bases [i];
701 Expression resolved = ResolveTypeExpr (name, false, Location);
702 bases [i] = resolved;
703 Type t = resolved.Type;
710 if (is_class == false && !t.IsInterface){
711 Report.Error (527, "In Struct `" + Name + "', type `"+
712 name +"' is not an interface");
721 detail = " (a class can not inherit from a struct/enum)";
723 Report.Error (509, "class `"+ Name +
724 "': Cannot inherit from sealed class `"+
725 bases [i]+"'"+detail);
732 Report.Error (527, "In Class `" + Name + "', type `"+
733 name+"' is not an interface");
739 for (int x = 0; x < j; x++) {
740 if (t == ifaces [x]) {
741 Report.Error (528, "`" + name + "' is already listed in interface list");
750 return TypeManager.ExpandInterfaces (ifaces);
754 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
756 public override TypeBuilder DefineType ()
762 if (TypeBuilder != null)
775 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
777 ifaces = GetClassBases (is_class, out parent, out error);
782 if (is_class && parent != null){
783 if (parent == TypeManager.enum_type ||
784 (parent == TypeManager.value_type && RootContext.StdLib) ||
785 parent == TypeManager.delegate_type ||
786 parent == TypeManager.array_type){
788 644, Location, "`" + Name + "' cannot inherit from " +
789 "special class `" + TypeManager.CSharpName (parent) + "'");
794 if (!is_class && TypeManager.value_type == null)
795 throw new Exception ();
797 TypeAttributes type_attributes = TypeAttr;
799 // if (parent_builder is ModuleBuilder) {
801 ModuleBuilder builder = CodeGen.ModuleBuilder;
802 TypeBuilder = builder.DefineType (
803 Name, type_attributes, parent, ifaces);
806 TypeBuilder builder = Parent.TypeBuilder;
807 TypeBuilder = builder.DefineNestedType (
808 Basename, type_attributes, parent, ifaces);
812 // Structs with no fields need to have at least one byte.
813 // The right thing would be to set the PackingSize in a DefineType
814 // but there are no functions that allow interfaces *and* the size to
818 if (!is_class && !have_nonstatic_fields){
819 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
820 FieldAttributes.Private);
823 // add interfaces that were not added at type creation (weird API issue)
824 if (!is_class && !have_nonstatic_fields && (ifaces != null)) {
825 foreach (Type i in ifaces)
826 TypeBuilder.AddInterfaceImplementation (i);
830 // Finish the setup for the EmitContext
832 ec.ContainerType = TypeBuilder;
834 TypeManager.AddUserType (Name, TypeBuilder, this, ifaces);
836 if ((parent != null) &&
837 (parent == TypeManager.attribute_type ||
838 parent.IsSubclassOf (TypeManager.attribute_type))) {
839 RootContext.RegisterAttribute (this);
840 TypeManager.RegisterAttrType (TypeBuilder, this);
842 RootContext.RegisterOrder (this);
844 if (Interfaces != null) {
845 foreach (Interface iface in Interfaces)
850 foreach (TypeContainer tc in Types)
854 if (Delegates != null) {
855 foreach (Delegate d in Delegates)
860 foreach (Enum en in Enums)
870 /// Defines the MemberCore objects that are in the `list' Arraylist
872 /// The `defined_names' array contains a list of members defined in
875 static ArrayList remove_list = new ArrayList ();
876 void DefineMembers (ArrayList list, MemberInfo [] defined_names)
880 remove_list.Clear ();
882 foreach (MemberCore mc in list){
883 if (!mc.Define (this)){
884 remove_list.Add (mc);
888 if (defined_names == null)
891 idx = Array.BinarySearch (defined_names, mc.Name, mif_compare);
893 if (RootContext.WarningLevel >= 4){
894 if ((mc.ModFlags & Modifiers.NEW) != 0)
895 Warning_KewywordNewNotRequired (mc.Location, mc);
900 MemberInfo match = defined_names [idx];
902 if (match is PropertyInfo && ((mc.ModFlags & Modifiers.OVERRIDE) != 0))
906 // If we are both methods, let the method resolution emit warnings
908 if (match is MethodBase && mc is MethodCore)
911 if ((mc.ModFlags & Modifiers.NEW) == 0)
912 Warning_KeywordNewRequired (mc.Location, defined_names [idx]);
915 foreach (object o in remove_list)
918 remove_list.Clear ();
922 // Defines the indexers, and also verifies that the IndexerNameAttribute in the
923 // class is consisten. Either it is `Item' or it is the name defined by all the
924 // indexers with the `IndexerName' attribute.
926 // Turns out that the IndexerNameAttribute is applied to each indexer,
927 // but it is never emitted, instead a DefaultName attribute is attached
930 void DefineIndexers ()
932 string class_indexer_name = null;
934 foreach (Indexer i in Indexers){
939 name = i.IndexerName;
941 if (i.InterfaceType != null)
944 if (class_indexer_name == null){
945 class_indexer_name = name;
949 if (name == class_indexer_name)
953 668, "Two indexers have different names, " +
954 " you should use the same name for all your indexers");
956 if (class_indexer_name == null)
957 class_indexer_name = "Item";
958 IndexerName = class_indexer_name;
961 static void Error_KeywordNotAllowed (Location loc)
963 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
967 /// Populates our TypeBuilder with fields and methods
969 public override bool DefineMembers (TypeContainer parent)
971 MemberInfo [] defined_names = null;
973 if (interface_order != null){
974 foreach (Interface iface in interface_order)
975 if ((iface.ModFlags & Modifiers.NEW) == 0)
976 iface.DefineMembers (this);
978 Error_KeywordNotAllowed (iface.Location);
981 if (RootContext.WarningLevel > 1){
985 // This code throws an exception in the comparer
986 // I guess the string is not an object?
988 ptype = TypeBuilder.BaseType;
990 defined_names = (MemberInfo []) FindMembers (
991 ptype, MemberTypes.All & ~MemberTypes.Constructor,
992 BindingFlags.Public | BindingFlags.Instance |
993 BindingFlags.Static, null, null);
995 Array.Sort (defined_names, mif_compare);
999 if (constants != null)
1000 DefineMembers (constants, defined_names);
1003 DefineMembers (fields, defined_names);
1006 if (instance_constructors == null){
1007 if (default_constructor == null)
1008 DefineDefaultConstructor (false);
1011 if (initialized_static_fields != null &&
1012 default_static_constructor == null)
1013 DefineDefaultConstructor (true);
1016 if (this is Struct){
1018 // Structs can not have initialized instance
1021 if (initialized_static_fields != null &&
1022 default_static_constructor == null)
1023 DefineDefaultConstructor (true);
1025 if (initialized_fields != null)
1026 ReportStructInitializedInstanceError ();
1029 Pending = PendingImplementation.GetPendingImplementations (this);
1032 // Constructors are not in the defined_names array
1034 if (instance_constructors != null)
1035 DefineMembers (instance_constructors, null);
1037 if (default_static_constructor != null)
1038 default_static_constructor.Define (this);
1040 if (methods != null)
1041 DefineMembers (methods, defined_names);
1043 if (properties != null)
1044 DefineMembers (properties, defined_names);
1047 DefineMembers (events, defined_names);
1049 if (indexers != null) {
1052 IndexerName = "Item";
1054 if (operators != null){
1055 DefineMembers (operators, null);
1057 CheckPairedOperators ();
1061 DefineMembers (enums, defined_names);
1063 if (delegates != null)
1064 DefineMembers (delegates, defined_names);
1067 if (TypeBuilder.BaseType != null)
1068 parent_container = TypeManager.LookupMemberContainer (TypeBuilder.BaseType);
1070 member_cache = new MemberCache (this);
1076 public override bool Define (TypeContainer parent)
1078 if (interface_order != null){
1079 foreach (Interface iface in interface_order)
1080 if ((iface.ModFlags & Modifiers.NEW) == 0)
1081 iface.Define (this);
1088 /// This function is based by a delegate to the FindMembers routine
1090 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1096 /// This filter is used by FindMembers, and we just keep
1097 /// a global for the filter to `AlwaysAccept'
1099 static MemberFilter accepting_filter;
1103 /// A member comparission method based on name only
1105 static IComparer mif_compare;
1107 static TypeContainer ()
1109 accepting_filter = new MemberFilter (AlwaysAccept);
1110 mif_compare = new MemberInfoCompare ();
1114 /// This method returns the members of this type just like Type.FindMembers would
1115 /// Only, we need to use this for types which are _being_ defined because MS'
1116 /// implementation can't take care of that.
1119 // FIXME: return an empty static array instead of null, that cleans up
1120 // some code and is consistent with some coding conventions I just found
1124 // Notice that in various cases we check if our field is non-null,
1125 // something that would normally mean that there was a bug elsewhere.
1127 // The problem happens while we are defining p-invoke methods, as those
1128 // will trigger a FindMembers, but this happens before things are defined
1130 // Since the whole process is a no-op, it is fine to check for null here.
1132 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1133 MemberFilter filter, object criteria)
1135 ArrayList members = new ArrayList ();
1138 if ((bf & BindingFlags.Public) != 0)
1139 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1141 if ((bf & BindingFlags.NonPublic) != 0)
1142 modflags |= Modifiers.PRIVATE;
1144 int static_mask = 0, static_flags = 0;
1145 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1146 case BindingFlags.Static:
1147 static_mask = static_flags = Modifiers.STATIC;
1150 case BindingFlags.Instance:
1151 static_mask = Modifiers.STATIC;
1156 static_mask = static_flags = 0;
1160 Timer.StartTimer (TimerType.TcFindMembers);
1163 filter = accepting_filter;
1165 if ((mt & MemberTypes.Field) != 0) {
1166 if (fields != null) {
1167 foreach (Field f in fields) {
1168 if ((f.ModFlags & modflags) == 0)
1170 if ((f.ModFlags & static_mask) != static_flags)
1173 FieldBuilder fb = f.FieldBuilder;
1174 if (fb != null && filter (fb, criteria) == true)
1179 if (constants != null) {
1180 foreach (Const con in constants) {
1181 if ((con.ModFlags & modflags) == 0)
1183 if ((con.ModFlags & static_mask) != static_flags)
1186 FieldBuilder fb = con.FieldBuilder;
1187 if (fb != null && filter (fb, criteria) == true)
1193 if ((mt & MemberTypes.Method) != 0) {
1194 if (methods != null) {
1195 foreach (Method m in methods) {
1196 if ((m.ModFlags & modflags) == 0)
1198 if ((m.ModFlags & static_mask) != static_flags)
1201 MethodBuilder mb = m.MethodBuilder;
1203 if (mb != null && filter (mb, criteria) == true)
1208 if (operators != null){
1209 foreach (Operator o in operators) {
1210 if ((o.ModFlags & modflags) == 0)
1212 if ((o.ModFlags & static_mask) != static_flags)
1215 MethodBuilder ob = o.OperatorMethodBuilder;
1216 if (ob != null && filter (ob, criteria) == true)
1221 if (properties != null){
1222 foreach (Property p in properties){
1223 if ((p.ModFlags & modflags) == 0)
1225 if ((p.ModFlags & static_mask) != static_flags)
1231 if (b != null && filter (b, criteria) == true)
1235 if (b != null && filter (b, criteria) == true)
1240 if (indexers != null){
1241 foreach (Indexer ix in indexers){
1242 if ((ix.ModFlags & modflags) == 0)
1244 if ((ix.ModFlags & static_mask) != static_flags)
1250 if (b != null && filter (b, criteria) == true)
1254 if (b != null && filter (b, criteria) == true)
1260 if ((mt & MemberTypes.Event) != 0) {
1262 foreach (Event e in events) {
1263 if ((e.ModFlags & modflags) == 0)
1265 if ((e.ModFlags & static_mask) != static_flags)
1268 MemberInfo eb = e.EventBuilder;
1269 if (eb != null && filter (eb, criteria) == true)
1270 members.Add (e.EventBuilder);
1274 if ((mt & MemberTypes.Property) != 0){
1275 if (properties != null)
1276 foreach (Property p in properties) {
1277 if ((p.ModFlags & modflags) == 0)
1279 if ((p.ModFlags & static_mask) != static_flags)
1282 MemberInfo pb = p.PropertyBuilder;
1283 if (pb != null && filter (pb, criteria) == true) {
1284 members.Add (p.PropertyBuilder);
1288 if (indexers != null)
1289 foreach (Indexer ix in indexers) {
1290 if ((ix.ModFlags & modflags) == 0)
1292 if ((ix.ModFlags & static_mask) != static_flags)
1295 MemberInfo ib = ix.PropertyBuilder;
1296 if (ib != null && filter (ib, criteria) == true) {
1297 members.Add (ix.PropertyBuilder);
1302 if ((mt & MemberTypes.NestedType) != 0) {
1304 foreach (TypeContainer t in types) {
1305 if ((t.ModFlags & modflags) == 0)
1308 TypeBuilder tb = t.TypeBuilder;
1309 if (tb != null && (filter (tb, criteria) == true))
1315 foreach (Enum en in enums){
1316 if ((en.ModFlags & modflags) == 0)
1319 TypeBuilder tb = en.TypeBuilder;
1320 if (tb != null && (filter (tb, criteria) == true))
1325 if (delegates != null){
1326 foreach (Delegate d in delegates){
1327 if ((d.ModFlags & modflags) == 0)
1330 TypeBuilder tb = d.TypeBuilder;
1331 if (tb != null && (filter (tb, criteria) == true))
1336 if (interfaces != null){
1337 foreach (Interface iface in interfaces){
1338 if ((iface.ModFlags & modflags) == 0)
1341 TypeBuilder tb = iface.TypeBuilder;
1342 if (tb != null && (filter (tb, criteria) == true))
1348 if ((mt & MemberTypes.Constructor) != 0){
1349 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1350 foreach (Constructor c in instance_constructors){
1351 ConstructorBuilder cb = c.ConstructorBuilder;
1353 if (filter (cb, criteria) == true)
1358 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1359 ConstructorBuilder cb =
1360 default_static_constructor.ConstructorBuilder;
1363 if (filter (cb, criteria) == true)
1369 // Lookup members in parent if requested.
1371 if (((bf & BindingFlags.DeclaredOnly) == 0) && (TypeBuilder.BaseType != null)) {
1372 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1373 members.AddRange (list);
1376 Timer.StopTimer (TimerType.TcFindMembers);
1378 return new MemberList (members);
1381 public override MemberCache MemberCache {
1383 return member_cache;
1387 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1388 MemberFilter filter, object criteria)
1390 TypeContainer tc = TypeManager.LookupTypeContainer (t);
1393 return tc.FindMembers (mt, bf, filter, criteria);
1395 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1399 // FindMethods will look for methods not only in the type `t', but in
1400 // any interfaces implemented by the type.
1402 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1403 MemberFilter filter, object criteria)
1409 /// Emits the values for the constants
1411 public void EmitConstants ()
1413 if (constants != null)
1414 foreach (Const con in constants)
1415 con.EmitConstant (this);
1420 /// Emits the code, this step is performed after all
1421 /// the types, enumerations, constructors
1425 if (instance_constructors != null)
1426 foreach (Constructor c in instance_constructors)
1429 if (default_static_constructor != null)
1430 default_static_constructor.Emit (this);
1432 if (methods != null)
1433 foreach (Method m in methods)
1436 if (operators != null)
1437 foreach (Operator o in operators)
1440 if (properties != null)
1441 foreach (Property p in properties)
1444 if (indexers != null){
1445 foreach (Indexer ix in indexers)
1448 CustomAttributeBuilder cb = Interface.EmitDefaultMemberAttr (
1449 this, IndexerName, ModFlags, Location);
1450 TypeBuilder.SetCustomAttribute (cb);
1454 foreach (Field f in fields)
1457 if (events != null){
1458 foreach (Event e in Events)
1462 if (Pending != null)
1463 if (Pending.VerifyPendingMethods ())
1466 Attribute.ApplyAttributes (ec, TypeBuilder, this, OptAttributes, Location);
1469 // Check for internal or private fields that were never assigned
1471 if (fields != null && RootContext.WarningLevel >= 3) {
1472 foreach (Field f in fields) {
1473 if ((f.ModFlags & Modifiers.PUBLIC) != 0)
1478 169, f.Location, "Private field " +
1479 MakeName (f.Name) + " is never used");
1484 // Only report 649 on level 4
1486 if (RootContext.WarningLevel < 4)
1489 if ((f.status & Field.Status.ASSIGNED) != 0)
1494 "Field " + MakeName (f.Name) + " is never assigned " +
1495 " to and will always have its default value");
1499 // if (types != null)
1500 // foreach (TypeContainer tc in types)
1504 public override void CloseType ()
1509 TypeBuilder.CreateType ();
1511 } catch (TypeLoadException){
1513 // This is fine, the code still created the type
1515 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1516 // Console.WriteLine (e.Message);
1518 Console.WriteLine ("In type: " + Name);
1523 foreach (Enum en in Enums)
1526 if (interface_order != null){
1527 foreach (Interface iface in interface_order)
1532 foreach (TypeContainer tc in Types)
1536 foreach (TypeContainer tc in Types)
1537 if (!(tc is Struct))
1541 if (Delegates != null)
1542 foreach (Delegate d in Delegates)
1546 public string MakeName (string n)
1548 return "`" + Name + "." + n + "'";
1551 public void Warning_KeywordNewRequired (Location l, MemberInfo mi)
1554 108, l, "The keyword new is required on " +
1555 MakeName (mi.Name) + " because it hides `" +
1556 mi.ReflectedType.Name + "." + mi.Name + "'");
1559 public void Warning_KewywordNewNotRequired (Location l, MemberCore mc)
1562 109, l, "The member " + MakeName (mc.Name) + " does not hide an " +
1563 "inherited member, the keyword new is not required");
1566 public static int CheckMember (string name, MemberInfo mi, int ModFlags)
1572 // Performs the validation on a Method's modifiers (properties have
1573 // the same properties).
1575 public bool MethodModifiersValid (int flags, string n, Location loc)
1577 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1578 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1579 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1581 string name = MakeName (n);
1584 // At most one of static, virtual or override
1586 if ((flags & Modifiers.STATIC) != 0){
1587 if ((flags & vao) != 0){
1589 112, loc, "static method " + name + "can not be marked " +
1590 "as virtual, abstract or override");
1595 if (this is Struct){
1596 if ((flags & va) != 0){
1597 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
1602 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1605 " marked as override cannot be marked as new or virtual");
1610 // If the declaration includes the abstract modifier, then the
1611 // declaration does not include static, virtual or extern
1613 if ((flags & Modifiers.ABSTRACT) != 0){
1614 if ((flags & Modifiers.EXTERN) != 0){
1616 180, loc, name + " can not be both abstract and extern");
1620 if ((flags & Modifiers.VIRTUAL) != 0){
1622 503, loc, name + " can not be both abstract and virtual");
1626 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1629 " is abstract but its container class is not");
1635 if ((flags & Modifiers.PRIVATE) != 0){
1636 if ((flags & vao) != 0){
1639 " virtual or abstract members can not be private");
1644 if ((flags & Modifiers.SEALED) != 0){
1645 if ((flags & Modifiers.OVERRIDE) == 0){
1648 " cannot be sealed because it is not an override");
1656 // Access level of a type.
1659 ProtectedInternal = 1,
1665 // Check whether `flags' denotes a more restricted access than `level'
1666 // and return the new level.
1667 static AccessLevel CheckAccessLevel (AccessLevel level, int flags)
1669 AccessLevel old_level = level;
1671 if ((flags & Modifiers.INTERNAL) != 0) {
1672 if ((flags & Modifiers.PROTECTED) != 0) {
1673 if ((int) level < (int) AccessLevel.ProtectedInternal)
1674 level = AccessLevel.ProtectedInternal;
1676 if ((int) level < (int) AccessLevel.Internal)
1677 level = AccessLevel.Internal;
1679 } else if ((flags & Modifiers.PROTECTED) != 0) {
1680 if ((int) level < (int) AccessLevel.Protected)
1681 level = AccessLevel.Protected;
1682 } else if ((flags & Modifiers.PRIVATE) != 0)
1683 level = AccessLevel.Private;
1688 // Return the access level for a new member which is defined in the current
1689 // TypeContainer with access modifiers `flags'.
1690 AccessLevel GetAccessLevel (int flags)
1692 if ((flags & Modifiers.PRIVATE) != 0)
1693 return AccessLevel.Private;
1696 if (!IsTopLevel && (Parent != null))
1697 level = Parent.GetAccessLevel (flags);
1699 level = AccessLevel.Public;
1701 return CheckAccessLevel (CheckAccessLevel (level, flags), ModFlags);
1704 // Return the access level for type `t', but don't give more access than `flags'.
1705 static AccessLevel GetAccessLevel (Type t, int flags)
1707 if (((flags & Modifiers.PRIVATE) != 0) || t.IsNestedPrivate)
1708 return AccessLevel.Private;
1711 if (TypeManager.IsBuiltinType (t))
1712 return AccessLevel.Public;
1713 else if ((t.DeclaringType != null) && (t != t.DeclaringType))
1714 level = GetAccessLevel (t.DeclaringType, flags);
1716 level = CheckAccessLevel (AccessLevel.Public, flags);
1719 if (t.IsNestedPublic)
1722 if (t.IsNestedAssembly || t.IsNotPublic) {
1723 if ((int) level < (int) AccessLevel.Internal)
1724 level = AccessLevel.Internal;
1727 if (t.IsNestedFamily) {
1728 if ((int) level < (int) AccessLevel.Protected)
1729 level = AccessLevel.Protected;
1732 if (t.IsNestedFamORAssem) {
1733 if ((int) level < (int) AccessLevel.ProtectedInternal)
1734 level = AccessLevel.ProtectedInternal;
1741 // Returns true if `parent' is as accessible as the flags `flags'
1742 // given for this member.
1744 public bool AsAccessible (Type parent, int flags)
1746 while (parent.IsArray || parent.IsPointer || parent.IsByRef)
1747 parent = parent.GetElementType ();
1749 AccessLevel level = GetAccessLevel (flags);
1750 AccessLevel level2 = GetAccessLevel (parent, flags);
1752 return (int) level >= (int) level2;
1755 Hashtable builder_and_args;
1757 public bool RegisterMethod (MethodBuilder mb, InternalParameters ip, Type [] args)
1759 if (builder_and_args == null)
1760 builder_and_args = new Hashtable ();
1765 /// Performs checks for an explicit interface implementation. First it
1766 /// checks whether the `interface_type' is a base inteface implementation.
1767 /// Then it checks whether `name' exists in the interface type.
1769 public bool VerifyImplements (Type interface_type, string full, string name, Location loc)
1773 if (ifaces != null){
1774 foreach (Type t in ifaces){
1775 if (t == interface_type){
1783 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
1790 public static void Error_ExplicitInterfaceNotMemberInterface (Location loc, string name)
1792 Report.Error (539, loc, "Explicit implementation: `" + name + "' is not a member of the interface");
1799 string IMemberContainer.Name {
1805 Type IMemberContainer.Type {
1811 IMemberContainer IMemberContainer.Parent {
1813 return parent_container;
1817 MemberCache IMemberContainer.MemberCache {
1819 return member_cache;
1823 bool IMemberContainer.IsInterface {
1829 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
1831 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
1835 // Operator pair checking
1838 class OperatorEntry {
1840 public Type ret_type;
1841 public Type type1, type2;
1843 public Operator.OpType ot;
1845 public OperatorEntry (int f, Operator o)
1849 ret_type = o.OperatorMethod.GetReturnType ();
1850 Type [] pt = o.OperatorMethod.ParameterTypes;
1854 ot = o.OperatorType;
1857 public override int GetHashCode ()
1859 return ret_type.GetHashCode ();
1862 public override bool Equals (object o)
1864 OperatorEntry other = (OperatorEntry) o;
1866 if (other.ret_type != ret_type)
1868 if (other.type1 != type1)
1870 if (other.type2 != type2)
1877 // Checks that some operators come in pairs:
1882 // They are matched based on the return type and the argument types
1884 void CheckPairedOperators ()
1886 Hashtable pairs = new Hashtable (null, null);
1888 // Register all the operators we care about.
1889 foreach (Operator op in operators){
1892 switch (op.OperatorType){
1893 case Operator.OpType.Equality:
1895 case Operator.OpType.Inequality:
1898 case Operator.OpType.GreaterThan:
1900 case Operator.OpType.LessThan:
1903 case Operator.OpType.GreaterThanOrEqual:
1905 case Operator.OpType.LessThanOrEqual:
1911 OperatorEntry oe = new OperatorEntry (reg, op);
1913 object o = pairs [oe];
1917 oe = (OperatorEntry) o;
1923 // Look for the mistakes.
1925 foreach (DictionaryEntry de in pairs){
1926 OperatorEntry oe = (OperatorEntry) de.Key;
1933 case Operator.OpType.Equality:
1936 case Operator.OpType.Inequality:
1939 case Operator.OpType.GreaterThan:
1942 case Operator.OpType.LessThan:
1945 case Operator.OpType.GreaterThanOrEqual:
1948 case Operator.OpType.LessThanOrEqual:
1952 Report.Error (216, oe.op.Location,
1953 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
1960 public class Class : TypeContainer {
1962 // Modifiers allowed in a class declaration
1964 public const int AllowedModifiers =
1967 Modifiers.PROTECTED |
1968 Modifiers.INTERNAL |
1970 Modifiers.ABSTRACT |
1974 public Class (TypeContainer parent, string name, int mod, Attributes attrs, Location l)
1975 : base (parent, name, l)
1979 if (parent.Parent == null)
1980 accmods = Modifiers.INTERNAL;
1982 accmods = Modifiers.PRIVATE;
1984 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
1985 this.attributes = attrs;
1989 // FIXME: How do we deal with the user specifying a different
1992 public override TypeAttributes TypeAttr {
1994 return base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
1999 public class Struct : TypeContainer {
2001 // Modifiers allowed in a struct declaration
2003 public const int AllowedModifiers =
2006 Modifiers.PROTECTED |
2007 Modifiers.INTERNAL |
2011 public Struct (TypeContainer parent, string name, int mod, Attributes attrs, Location l)
2012 : base (parent, name, l)
2016 if (parent.Parent == null)
2017 accmods = Modifiers.INTERNAL;
2019 accmods = Modifiers.PRIVATE;
2021 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2023 this.ModFlags |= Modifiers.SEALED;
2024 this.attributes = attrs;
2029 // FIXME: Allow the user to specify a different set of attributes
2030 // in some cases (Sealed for example is mandatory for a class,
2031 // but what SequentialLayout can be changed
2033 public override TypeAttributes TypeAttr {
2035 return base.TypeAttr |
2036 TypeAttributes.SequentialLayout |
2037 TypeAttributes.Sealed |
2038 TypeAttributes.BeforeFieldInit;
2043 public abstract class MethodCore : MemberBase {
2044 public /* readonly */ Parameters Parameters;
2048 // Parameters, cached for semantic analysis.
2050 protected InternalParameters parameter_info;
2051 protected Type [] parameter_types;
2053 public MethodCore (Expression type, int mod, int allowed_mod, string name,
2054 Attributes attrs, Parameters parameters, Location loc)
2055 : base (type, mod, allowed_mod, name, attrs, loc)
2057 Parameters = parameters;
2061 // Returns the System.Type array for the parameters of this method
2063 public Type [] ParameterTypes {
2065 return parameter_types;
2069 public InternalParameters ParameterInfo
2072 return parameter_info;
2076 public Block Block {
2086 protected virtual bool DoDefineParameters (TypeContainer parent)
2088 // Check if arguments were correct
2089 parameter_types = Parameters.GetParameterInfo (parent);
2090 if ((parameter_types == null) || !CheckParameters (parent, parameter_types))
2093 parameter_info = new InternalParameters (parent, Parameters);
2098 public CallingConventions GetCallingConvention (bool is_class)
2100 CallingConventions cc = 0;
2102 cc = Parameters.GetCallingConvention ();
2105 if ((ModFlags & Modifiers.STATIC) == 0)
2106 cc |= CallingConventions.HasThis;
2108 // FIXME: How is `ExplicitThis' used in C#?
2113 public void LabelParameters (EmitContext ec, Type [] parameters, MethodBase builder)
2115 LabelParameters (ec, parameters, builder, null);
2118 public void LabelParameters (EmitContext ec, Type [] parameters, MethodBase builder, Parameters p_params)
2121 // Define each type attribute (in/out/ref) and
2122 // the argument names.
2124 Parameter [] p = p_params == null ? Parameters.FixedParameters : p_params.FixedParameters;
2127 MethodBuilder mb = null;
2128 ConstructorBuilder cb = null;
2130 if (builder is MethodBuilder)
2131 mb = (MethodBuilder) builder;
2133 cb = (ConstructorBuilder) builder;
2136 for (i = 0; i < p.Length; i++) {
2137 ParameterBuilder pb;
2140 pb = cb.DefineParameter (
2141 i + 1, p [i].Attributes, p [i].Name);
2143 pb = mb.DefineParameter (
2144 i + 1, p [i].Attributes, p [i].Name);
2146 Attributes attr = p [i].OptAttributes;
2148 Attribute.ApplyAttributes (ec, pb, pb, attr, Location);
2152 if (Parameters.ArrayParameter != null){
2153 ParameterBuilder pb;
2154 Parameter array_param = Parameters.ArrayParameter;
2157 pb = cb.DefineParameter (
2158 i + 1, array_param.Attributes,
2161 pb = mb.DefineParameter (
2162 i + 1, array_param.Attributes,
2165 CustomAttributeBuilder a = new CustomAttributeBuilder (
2166 TypeManager.cons_param_array_attribute, new object [0]);
2168 pb.SetCustomAttribute (a);
2173 public class Method : MethodCore {
2174 public MethodBuilder MethodBuilder;
2175 public MethodData MethodData;
2178 /// Modifiers allowed in a class declaration
2180 const int AllowedModifiers =
2183 Modifiers.PROTECTED |
2184 Modifiers.INTERNAL |
2189 Modifiers.OVERRIDE |
2190 Modifiers.ABSTRACT |
2195 // return_type can be "null" for VOID values.
2197 public Method (Expression return_type, int mod, string name, Parameters parameters,
2198 Attributes attrs, Location l)
2199 : base (return_type, mod, AllowedModifiers, name, attrs, parameters, l)
2204 public Method (Expression return_type, int mod, string name, Parameters parameters,
2205 Attributes attrs, Expression impl_what, Location l)
2206 : base (return_type, mod, AllowedModifiers, name, attrs, parameters, l)
2208 Implements = impl_what;
2212 // Returns the `System.Type' for the ReturnType of this
2213 // function. Provides a nice cache. (used between semantic analysis
2214 // and actual code generation
2216 public Type GetReturnType ()
2221 // Whether this is an operator method.
2222 public bool IsOperator;
2224 void DuplicateEntryPoint (MethodInfo b, Location location)
2228 "Program `" + CodeGen.FileName +
2229 "' has more than one entry point defined: `" +
2230 TypeManager.CSharpSignature(b) + "'");
2233 void Report28 (MethodInfo b)
2235 if (RootContext.WarningLevel < 4)
2240 "`" + TypeManager.CSharpSignature(b) +
2241 "' has the wrong signature to be an entry point");
2244 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
2246 if (b.ReturnType != TypeManager.void_type &&
2247 b.ReturnType != TypeManager.int32_type)
2250 if (pinfo.Count == 0)
2253 if (pinfo.Count > 1)
2256 Type t = pinfo.ParameterType(0);
2258 (t.GetArrayRank() == 1) &&
2259 (t.GetElementType() == TypeManager.string_type) &&
2260 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
2267 // Checks our base implementation if any
2269 protected override bool CheckBase (TypeContainer parent)
2271 // Check whether arguments were correct.
2272 if (!DoDefineParameters (parent))
2275 MethodSignature ms = new MethodSignature (Name, null, ParameterTypes);
2279 mi_this = TypeContainer.FindMembers (
2280 parent.TypeBuilder, MemberTypes.Method,
2281 BindingFlags.NonPublic | BindingFlags.Public |
2282 BindingFlags.Static | BindingFlags.Instance |
2283 BindingFlags.DeclaredOnly,
2284 MethodSignature.method_signature_filter, ms);
2286 if (mi_this.Count > 0) {
2287 Report.Error (111, Location, "Class `" + parent.Name + "' " +
2288 "already defines a member called `" + Name + "' " +
2289 "with the same parameter types");
2295 // Verify if the parent has a type with the same name, and then
2296 // check whether we have to create a new slot for it or not.
2298 Type ptype = parent.TypeBuilder.BaseType;
2300 // ptype is only null for System.Object while compiling corlib.
2302 MemberList mi, mi_static, mi_instance;
2304 mi_static = TypeContainer.FindMembers (
2305 ptype, MemberTypes.Method,
2306 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static,
2307 MethodSignature.inheritable_method_signature_filter, ms);
2309 mi_instance = TypeContainer.FindMembers (
2310 ptype, MemberTypes.Method,
2311 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
2312 MethodSignature.inheritable_method_signature_filter,
2315 if (mi_instance.Count > 0){
2317 } else if (mi_static.Count > 0)
2322 if (mi != null && mi.Count > 0){
2323 parent_method = (MethodInfo) mi [0];
2324 string name = parent_method.DeclaringType.Name + "." +
2327 if (!CheckMethodAgainstBase (parent, flags, parent_method, name))
2330 if ((ModFlags & Modifiers.NEW) == 0) {
2331 Type parent_ret = TypeManager.TypeToCoreType (
2332 parent_method.ReturnType);
2334 if (parent_ret != MemberType) {
2336 508, parent.MakeName (Name) + ": cannot " +
2337 "change return type when overriding " +
2338 "inherited member " + name);
2343 if ((ModFlags & Modifiers.NEW) != 0)
2344 WarningNotHiding (parent);
2346 if ((ModFlags & Modifiers.OVERRIDE) != 0){
2347 Report.Error (115, Location,
2348 parent.MakeName (Name) +
2349 " no suitable methods found to override");
2352 } else if ((ModFlags & Modifiers.NEW) != 0)
2353 WarningNotHiding (parent);
2361 public override bool Define (TypeContainer parent)
2363 if (!DoDefine (parent))
2366 if (!CheckBase (parent))
2369 CallingConventions cc = GetCallingConvention (parent is Class);
2371 MethodData = new MethodData (this, null, MemberType, ParameterTypes,
2372 ParameterInfo, cc, OptAttributes,
2373 ModFlags, flags, true);
2375 if (!MethodData.Define (parent))
2378 MethodBuilder = MethodData.MethodBuilder;
2381 // This is used to track the Entry Point,
2383 if (Name == "Main" &&
2384 ((ModFlags & Modifiers.STATIC) != 0) &&
2385 (RootContext.MainClass == null ||
2386 RootContext.MainClass == parent.TypeBuilder.FullName)){
2387 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
2388 if (RootContext.EntryPoint == null) {
2389 RootContext.EntryPoint = MethodBuilder;
2390 RootContext.EntryPointLocation = Location;
2392 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
2393 DuplicateEntryPoint (MethodBuilder, Location);
2396 Report28(MethodBuilder);
2405 public void Emit (TypeContainer parent)
2407 MethodData.Emit (parent, Block, this);
2411 public abstract class ConstructorInitializer {
2412 ArrayList argument_list;
2413 ConstructorInfo parent_constructor;
2414 Parameters parameters;
2417 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
2420 this.argument_list = argument_list;
2421 this.parameters = parameters;
2425 public ArrayList Arguments {
2427 return argument_list;
2431 public bool Resolve (EmitContext ec)
2433 Expression parent_constructor_group;
2436 ec.CurrentBlock = new Block (null, true, parameters);
2438 if (argument_list != null){
2439 foreach (Argument a in argument_list){
2440 if (!a.Resolve (ec, loc))
2445 ec.CurrentBlock = null;
2447 if (this is ConstructorBaseInitializer) {
2448 if (ec.ContainerType.BaseType == null)
2451 t = ec.ContainerType.BaseType;
2452 if (ec.ContainerType.IsValueType) {
2453 Report.Error (522, loc,
2454 "structs cannot call base class constructors");
2458 t = ec.ContainerType;
2460 parent_constructor_group = Expression.MemberLookup (
2462 MemberTypes.Constructor,
2463 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
2466 if (parent_constructor_group == null){
2467 Report.Error (1501, loc,
2468 "Can not find a constructor for this argument list");
2472 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (ec,
2473 (MethodGroupExpr) parent_constructor_group, argument_list, loc);
2475 if (parent_constructor == null){
2476 Report.Error (1501, loc,
2477 "Can not find a constructor for this argument list");
2484 public void Emit (EmitContext ec)
2486 if (parent_constructor != null){
2488 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
2490 Invocation.EmitCall (ec, true, false, ec.This, parent_constructor, argument_list, loc);
2495 public class ConstructorBaseInitializer : ConstructorInitializer {
2496 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
2497 base (argument_list, pars, l)
2502 public class ConstructorThisInitializer : ConstructorInitializer {
2503 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
2504 base (argument_list, pars, l)
2509 public class Constructor : MethodCore {
2510 public ConstructorBuilder ConstructorBuilder;
2511 public ConstructorInitializer Initializer;
2512 new public Attributes OptAttributes;
2515 // Modifiers allowed for a constructor.
2517 public const int AllowedModifiers =
2519 Modifiers.PROTECTED |
2520 Modifiers.INTERNAL |
2527 // The spec claims that static is not permitted, but
2528 // my very own code has static constructors.
2530 public Constructor (string name, Parameters args, ConstructorInitializer init, Location l)
2531 : base (null, 0, AllowedModifiers, name, null, args, l)
2537 // Returns true if this is a default constructor
2539 public bool IsDefault ()
2541 if ((ModFlags & Modifiers.STATIC) != 0)
2542 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
2543 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
2546 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
2547 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
2548 (Initializer is ConstructorBaseInitializer) &&
2549 (Initializer.Arguments == null);
2553 // Creates the ConstructorBuilder
2555 public override bool Define (TypeContainer parent)
2557 MethodAttributes ca = (MethodAttributes.RTSpecialName |
2558 MethodAttributes.SpecialName);
2560 // Check if arguments were correct.
2561 if (!DoDefineParameters (parent))
2564 if ((ModFlags & Modifiers.STATIC) != 0)
2565 ca |= MethodAttributes.Static;
2567 if (parent is Struct && ParameterTypes.Length == 0){
2570 "Structs can not contain explicit parameterless " +
2574 ca |= MethodAttributes.HideBySig;
2576 if ((ModFlags & Modifiers.PUBLIC) != 0)
2577 ca |= MethodAttributes.Public;
2578 else if ((ModFlags & Modifiers.PROTECTED) != 0){
2579 if ((ModFlags & Modifiers.INTERNAL) != 0)
2580 ca |= MethodAttributes.FamORAssem;
2582 ca |= MethodAttributes.Family;
2583 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
2584 ca |= MethodAttributes.Assembly;
2585 else if (IsDefault ())
2586 ca |= MethodAttributes.Public;
2588 ca |= MethodAttributes.Private;
2591 ConstructorBuilder = parent.TypeBuilder.DefineConstructor (
2592 ca, GetCallingConvention (parent is Class), ParameterTypes);
2595 // HACK because System.Reflection.Emit is lame
2597 if (!TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes)) {
2600 "Class `" +parent.Name+ "' already contains a definition with the " +
2601 "same return value and parameter types for constructor `" + Name
2612 public void Emit (TypeContainer parent)
2614 ILGenerator ig = ConstructorBuilder.GetILGenerator ();
2615 EmitContext ec = new EmitContext (parent, Location, ig, null, ModFlags, true);
2617 if ((ModFlags & Modifiers.STATIC) == 0){
2618 if (parent is Class && Initializer == null)
2619 Initializer = new ConstructorBaseInitializer (
2620 null, Parameters.EmptyReadOnlyParameters, parent.Location);
2624 // Spec mandates that Initializers will not have
2628 if (Initializer != null && !Initializer.Resolve (ec))
2630 ec.IsStatic = false;
2633 LabelParameters (ec, ParameterTypes, ConstructorBuilder);
2636 // Classes can have base initializers and instance field initializers.
2638 if (parent is Class){
2639 if ((ModFlags & Modifiers.STATIC) == 0)
2640 parent.EmitFieldInitializers (ec);
2642 if (Initializer != null)
2643 Initializer.Emit (ec);
2645 if ((ModFlags & Modifiers.STATIC) != 0)
2646 parent.EmitFieldInitializers (ec);
2648 Attribute.ApplyAttributes (ec, ConstructorBuilder, this, OptAttributes, Location);
2650 // If this is a non-static `struct' constructor and doesn't have any
2651 // initializer, it must initialize all of the struct's fields.
2652 if ((parent is Struct) && ((ModFlags & Modifiers.STATIC) == 0) &&
2653 (Initializer == null))
2654 Block.AddThisVariable (parent, Location);
2656 ec.EmitTopBlock (Block, ParameterInfo, Location);
2660 public class MethodData {
2662 // The return type of this method
2664 public readonly Type ReturnType;
2665 public readonly Type[] ParameterTypes;
2666 public readonly InternalParameters ParameterInfo;
2667 public readonly CallingConventions CallingConventions;
2668 public readonly Attributes OptAttributes;
2669 public readonly Location Location;
2672 // Are we implementing an interface ?
2674 public bool IsImplementing = false;
2679 protected MemberBase member;
2680 protected int modifiers;
2681 protected MethodAttributes flags;
2682 protected bool is_method;
2683 protected string accessor_name;
2684 ArrayList conditionals;
2686 MethodBuilder builder = null;
2687 public MethodBuilder MethodBuilder {
2693 public MethodData (MemberBase member, string name, Type return_type,
2694 Type [] parameter_types, InternalParameters parameters,
2695 CallingConventions cc, Attributes opt_attrs,
2696 int modifiers, MethodAttributes flags, bool is_method)
2698 this.member = member;
2699 this.accessor_name = name;
2700 this.ReturnType = return_type;
2701 this.ParameterTypes = parameter_types;
2702 this.ParameterInfo = parameters;
2703 this.CallingConventions = cc;
2704 this.OptAttributes = opt_attrs;
2705 this.modifiers = modifiers;
2707 this.is_method = is_method;
2708 this.Location = member.Location;
2709 this.conditionals = new ArrayList ();
2715 Attribute dllimport_attribute = null;
2716 string obsolete = null;
2717 bool obsolete_error = false;
2719 public virtual bool ApplyAttributes (Attributes opt_attrs, bool is_method)
2721 if ((opt_attrs == null) || (opt_attrs.AttributeSections == null))
2724 foreach (AttributeSection asec in opt_attrs.AttributeSections) {
2725 if (asec.Attributes == null)
2728 foreach (Attribute a in asec.Attributes) {
2729 if (a.Name == "Conditional") {
2730 if (!ApplyConditionalAttribute (a))
2732 } else if (a.Name == "Obsolete") {
2733 if (!ApplyObsoleteAttribute (a))
2735 } else if (a.Name.IndexOf ("DllImport") != -1) {
2737 a.Type = TypeManager.dllimport_type;
2738 Attribute.Error_AttributeNotValidForElement (a, Location);
2741 if (!ApplyDllImportAttribute (a))
2751 // Applies the `DllImport' attribute to the method.
2753 protected virtual bool ApplyDllImportAttribute (Attribute a)
2755 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
2756 if ((modifiers & extern_static) != extern_static) {
2757 Report.Error (601, Location,
2758 "The DllImport attribute must be specified on a method " +
2759 "marked `static' and `extern'.");
2763 flags |= MethodAttributes.PinvokeImpl;
2764 dllimport_attribute = a;
2769 // Applies the `Obsolete' attribute to the method.
2771 protected virtual bool ApplyObsoleteAttribute (Attribute a)
2773 if (obsolete != null) {
2774 Report.Error (579, Location, "Duplicate `Obsolete' attribute");
2778 obsolete = a.Obsolete_GetObsoleteMessage (out obsolete_error);
2779 return obsolete != null;
2783 // Applies the `Conditional' attribute to the method.
2785 protected virtual bool ApplyConditionalAttribute (Attribute a)
2787 // The Conditional attribute is only valid on methods.
2789 Attribute.Error_AttributeNotValidForElement (a, Location);
2793 string condition = a.Conditional_GetConditionName ();
2795 if (condition == null)
2798 if (ReturnType != TypeManager.void_type) {
2799 Report.Error (578, Location,
2800 "Conditional not valid on `" + member.Name + "' " +
2801 "because its return type is not void");
2805 if ((modifiers & Modifiers.OVERRIDE) != 0) {
2806 Report.Error (243, Location,
2807 "Conditional not valid on `" + member.Name + "' " +
2808 "because it is an override method");
2812 if (member.IsExplicitImpl) {
2813 Report.Error (577, Location,
2814 "Conditional not valid on `" + member.Name + "' " +
2815 "because it is an explicit interface implementation");
2819 if (IsImplementing) {
2820 Report.Error (623, Location,
2821 "Conditional not valid on `" + member.Name + "' " +
2822 "because it is an interface method");
2826 conditionals.Add (condition);
2832 // Checks whether this method should be ignored due to its Conditional attributes.
2834 bool ShouldIgnore (Location loc)
2836 // When we're overriding a virtual method, we implicitly inherit the
2837 // Conditional attributes from our parent.
2838 if (member.ParentMethod != null) {
2839 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (
2840 member.ParentMethod, loc);
2842 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
2846 foreach (string condition in conditionals)
2847 if (RootContext.AllDefines [condition] == null)
2854 // Returns the TypeManager.MethodFlags for this method.
2855 // This emits an error 619 / warning 618 if the method is obsolete.
2856 // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
2858 public virtual TypeManager.MethodFlags GetMethodFlags (Location loc)
2860 TypeManager.MethodFlags flags = 0;
2862 if (obsolete != null) {
2863 if (obsolete_error) {
2864 Report.Error (619, loc, "Method `" + member.Name +
2865 "' is obsolete: `" + obsolete + "'");
2866 return TypeManager.MethodFlags.IsObsoleteError;
2868 Report.Warning (618, loc, "Method `" + member.Name +
2869 "' is obsolete: `" + obsolete + "'");
2871 flags |= TypeManager.MethodFlags.IsObsolete;
2874 if (ShouldIgnore (loc))
2875 flags |= TypeManager.MethodFlags.ShouldIgnore;
2880 public virtual bool Define (TypeContainer parent)
2882 MethodInfo implementing = null;
2883 string method_name, name, prefix;
2885 if (OptAttributes != null)
2886 if (!ApplyAttributes (OptAttributes, is_method))
2889 if (member.IsExplicitImpl)
2890 prefix = member.InterfaceType.FullName + ".";
2894 if (accessor_name != null)
2895 name = accessor_name + "_" + member.ShortName;
2897 name = member.ShortName;
2898 method_name = prefix + name;
2900 if (parent.Pending != null){
2901 if (member is Indexer)
2902 implementing = parent.Pending.IsInterfaceIndexer (
2903 member.InterfaceType, ReturnType, ParameterTypes);
2905 implementing = parent.Pending.IsInterfaceMethod (
2906 member.InterfaceType, name, ReturnType, ParameterTypes);
2908 if (member.InterfaceType != null && implementing == null){
2909 TypeContainer.Error_ExplicitInterfaceNotMemberInterface (
2916 // For implicit implementations, make sure we are public, for
2917 // explicit implementations, make sure we are private.
2919 if (implementing != null){
2921 // Setting null inside this block will trigger a more
2922 // verbose error reporting for missing interface implementations
2924 // The "candidate" function has been flagged already
2925 // but it wont get cleared
2927 if (!member.IsExplicitImpl){
2929 // We already catch different accessibility settings
2930 // so we just need to check that we are not private
2932 if ((modifiers & Modifiers.PRIVATE) != 0)
2933 implementing = null;
2936 // Static is not allowed
2938 if ((modifiers & Modifiers.STATIC) != 0)
2939 implementing = null;
2941 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
2942 Modifiers.Error_InvalidModifier (Location, "public, virtual or abstract");
2943 implementing = null;
2949 // If implementing is still valid, set flags
2951 if (implementing != null){
2953 // When implementing interface methods, set NewSlot.
2955 if (implementing.DeclaringType.IsInterface)
2956 flags |= MethodAttributes.NewSlot;
2959 MethodAttributes.Virtual |
2960 MethodAttributes.HideBySig;
2962 // Get the method name from the explicit interface.
2963 if (member.InterfaceType != null) {
2964 name = implementing.Name;
2965 method_name = prefix + name;
2968 IsImplementing = true;
2972 // Create the MethodBuilder for the method
2974 if ((flags & MethodAttributes.PinvokeImpl) != 0) {
2975 if ((modifiers & Modifiers.STATIC) == 0) {
2976 Report.Error (601, Location,
2977 "The DllImport attribute must be specified on " +
2978 "a method marked 'static' and 'extern'.");
2982 EmitContext ec = new EmitContext (
2983 parent, Location, null, ReturnType, modifiers);
2985 builder = dllimport_attribute.DefinePInvokeMethod (
2986 ec, parent.TypeBuilder, method_name, flags,
2987 ReturnType, ParameterTypes);
2989 builder = parent.TypeBuilder.DefineMethod (
2990 method_name, flags, CallingConventions,
2991 ReturnType, ParameterTypes);
2993 if (builder == null)
2996 if (IsImplementing) {
2998 // clear the pending implemntation flag
3000 if (member is Indexer) {
3001 parent.Pending.ImplementIndexer (
3002 member.InterfaceType, builder, ReturnType,
3003 ParameterTypes, true);
3005 parent.Pending.ImplementMethod (
3006 member.InterfaceType, name, ReturnType,
3007 ParameterTypes, member.IsExplicitImpl);
3009 if (member.IsExplicitImpl)
3010 parent.TypeBuilder.DefineMethodOverride (
3011 builder, implementing);
3014 if (!TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes)) {
3015 Report.Error (111, Location,
3016 "Class `" + parent.Name +
3017 "' already contains a definition with the " +
3018 "same return value and parameter types as the " +
3019 "'get' method of property `" + member.Name + "'");
3023 TypeManager.AddMethod (builder, this);
3031 public virtual void Emit (TypeContainer parent, Block block, object kind)
3036 if ((flags & MethodAttributes.PinvokeImpl) == 0)
3037 ig = builder.GetILGenerator ();
3041 ec = new EmitContext (parent, Location, ig, ReturnType, modifiers);
3043 if (OptAttributes != null)
3044 Attribute.ApplyAttributes (ec, builder, kind, OptAttributes, Location);
3046 if (member is MethodCore)
3047 ((MethodCore) member).LabelParameters (ec, ParameterTypes, MethodBuilder);
3050 // abstract or extern methods have no bodies
3052 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
3057 // abstract or extern methods have no bodies.
3059 if ((modifiers & Modifiers.ABSTRACT) != 0)
3061 500, Location, "Abstract method `" +
3062 TypeManager.CSharpSignature (builder) +
3063 "' can not have a body");
3065 if ((modifiers & Modifiers.EXTERN) != 0)
3067 179, Location, "External method `" +
3068 TypeManager.CSharpSignature (builder) +
3069 "' can not have a body");
3075 // Methods must have a body unless they're extern or abstract
3077 if (block == null) {
3079 501, Location, "Method `" +
3080 TypeManager.CSharpSignature (builder) +
3081 "' must declare a body since it is not marked " +
3082 "abstract or extern");
3087 // Handle destructors specially
3089 // FIXME: This code generates buggy code
3091 if (member.Name == "Finalize" && ReturnType == TypeManager.void_type)
3092 EmitDestructor (ec, block);
3094 ISymbolWriter sw = CodeGen.SymbolWriter;
3096 if ((sw != null) && !Location.IsNull (Location) &&
3097 !Location.IsNull (block.EndLocation)) {
3098 Location end = block.EndLocation;
3099 MethodToken token = MethodBuilder.GetToken ();
3100 sw.OpenMethod (new SymbolToken (token.Token));
3101 // Avoid error if we don't support debugging for the platform
3103 sw.SetMethodSourceRange (Location.SymbolDocument,
3107 } catch (Exception) {
3110 ec.EmitTopBlock (block, member.Name, ParameterInfo, Location);
3114 ec.EmitTopBlock (block, member.Name, ParameterInfo, Location);
3118 void EmitDestructor (EmitContext ec, Block block)
3120 ILGenerator ig = ec.ig;
3122 Label finish = ig.DefineLabel ();
3123 bool old_in_try = ec.InTry;
3125 ig.BeginExceptionBlock ();
3127 ec.ReturnLabel = finish;
3128 ec.HasReturnLabel = true;
3129 ec.EmitTopBlock (block, null, Location);
3130 ec.InTry = old_in_try;
3132 // ig.MarkLabel (finish);
3133 bool old_in_finally = ec.InFinally;
3134 ec.InFinally = true;
3135 ig.BeginFinallyBlock ();
3137 if (ec.ContainerType.BaseType != null) {
3138 Expression member_lookup = Expression.MemberLookup (
3139 ec, ec.ContainerType.BaseType, ec.ContainerType.BaseType, "Finalize",
3140 MemberTypes.Method, Expression.AllBindingFlags, Location);
3142 if (member_lookup != null){
3143 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
3145 ig.Emit (OpCodes.Ldarg_0);
3146 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
3149 ec.InFinally = old_in_finally;
3151 ig.EndExceptionBlock ();
3152 //ig.MarkLabel (ec.ReturnLabel);
3153 ig.Emit (OpCodes.Ret);
3157 abstract public class MemberBase : MemberCore {
3158 public Expression Type;
3159 public readonly Attributes OptAttributes;
3160 public Expression Implements;
3162 protected MethodAttributes flags;
3165 // The "short" name of this property / indexer / event. This is the
3166 // name without the explicit interface.
3168 public string ShortName;
3171 // The type of this property / indexer / event
3173 public Type MemberType;
3176 // If true, this is an explicit interface implementation
3178 public bool IsExplicitImpl = false;
3181 // The name of the interface we are explicitly implementing
3183 public string ExplicitInterfaceName = null;
3186 // If true, the interface type we are explicitly implementing
3188 public Type InterfaceType = null;
3191 // The method we're overriding if this is an override method.
3193 protected MethodInfo parent_method = null;
3194 public MethodInfo ParentMethod {
3196 return parent_method;
3201 // The constructor is only exposed to our children
3203 protected MemberBase (Expression type, int mod, int allowed_mod, string name,
3204 Attributes attrs, Location loc)
3208 ModFlags = Modifiers.Check (allowed_mod, mod, Modifiers.PRIVATE, loc);
3209 OptAttributes = attrs;
3212 protected virtual bool CheckBase (TypeContainer parent)
3217 protected virtual bool CheckParameters (TypeContainer parent, Type [] parameters)
3221 foreach (Type partype in parameters){
3222 if (partype.IsPointer && !UnsafeOK (parent))
3225 if (parent.AsAccessible (partype, ModFlags))
3228 if (this is Indexer)
3229 Report.Error (55, Location,
3230 "Inconsistent accessibility: parameter type `" +
3231 TypeManager.CSharpName (partype) + "' is less " +
3232 "accessible than indexer `" + Name + "'");
3234 Report.Error (51, Location,
3235 "Inconsistent accessibility: parameter type `" +
3236 TypeManager.CSharpName (partype) + "' is less " +
3237 "accessible than method `" + Name + "'");
3244 protected virtual bool DoDefine (TypeContainer parent)
3249 if (!parent.MethodModifiersValid (ModFlags, Name, Location))
3252 flags = Modifiers.MethodAttr (ModFlags);
3254 // Lookup Type, verify validity
3255 MemberType = parent.ResolveType (Type, false, Location);
3256 if (MemberType == null)
3259 // verify accessibility
3260 if (!parent.AsAccessible (MemberType, ModFlags)) {
3261 if (this is Property)
3262 Report.Error (53, Location,
3263 "Inconsistent accessibility: property type `" +
3264 TypeManager.CSharpName (MemberType) + "' is less " +
3265 "accessible than property `" + Name + "'");
3266 else if (this is Indexer)
3267 Report.Error (54, Location,
3268 "Inconsistent accessibility: indexer return type `" +
3269 TypeManager.CSharpName (MemberType) + "' is less " +
3270 "accessible than indexer `" + Name + "'");
3271 else if (this is Method)
3272 Report.Error (50, Location,
3273 "Inconsistent accessibility: return type `" +
3274 TypeManager.CSharpName (MemberType) + "' is less " +
3275 "accessible than method `" + Name + "'");
3277 Report.Error (52, Location,
3278 "Inconsistent accessibility: field type `" +
3279 TypeManager.CSharpName (MemberType) + "' is less " +
3280 "accessible than field `" + Name + "'");
3284 if (MemberType.IsPointer && !UnsafeOK (parent))
3288 // Check for explicit interface implementation
3290 if ((ExplicitInterfaceName == null) && (Name.IndexOf (".") != -1)){
3291 int pos = Name.LastIndexOf (".");
3293 ExplicitInterfaceName = Name.Substring (0, pos);
3294 ShortName = Name.Substring (pos + 1);
3298 if (ExplicitInterfaceName != null) {
3299 InterfaceType = RootContext.LookupType (
3300 parent, ExplicitInterfaceName, false, Location);
3301 if (InterfaceType == null)
3304 // Compute the full name that we need to export.
3305 Name = InterfaceType.FullName + "." + ShortName;
3307 if (!parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
3310 IsExplicitImpl = true;
3312 IsExplicitImpl = false;
3319 // Fields and Events both generate FieldBuilders, we use this to share
3320 // their common bits. This is also used to flag usage of the field
3322 abstract public class FieldBase : MemberBase {
3323 public FieldBuilder FieldBuilder;
3324 public Status status;
3327 public enum Status : byte { ASSIGNED = 1, USED = 2 }
3330 // The constructor is only exposed to our children
3332 protected FieldBase (Expression type, int mod, int allowed_mod, string name,
3333 object init, Attributes attrs, Location loc)
3334 : base (type, mod, allowed_mod, name, attrs, loc)
3340 // Whether this field has an initializer.
3342 public bool HasInitializer {
3344 return init != null;
3349 readonly Object init;
3350 Expression init_expr;
3351 bool init_expr_initialized = false;
3354 // Resolves and returns the field initializer.
3356 public Expression GetInitializerExpression (EmitContext ec)
3358 if (init_expr_initialized)
3362 if (init is Expression)
3363 e = (Expression) init;
3365 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
3367 ec.IsFieldInitializer = true;
3368 e = e.DoResolve (ec);
3369 ec.IsFieldInitializer = false;
3372 init_expr_initialized = true;
3379 // The Field class is used to represents class/struct fields during parsing.
3381 public class Field : FieldBase {
3383 // Modifiers allowed in a class declaration
3385 const int AllowedModifiers =
3388 Modifiers.PROTECTED |
3389 Modifiers.INTERNAL |
3392 Modifiers.VOLATILE |
3396 public Field (Expression type, int mod, string name, Object expr_or_array_init,
3397 Attributes attrs, Location loc)
3398 : base (type, mod, AllowedModifiers, name, expr_or_array_init, attrs, loc)
3402 public override bool Define (TypeContainer parent)
3404 Type t = parent.ResolveType (Type, false, Location);
3409 if (!parent.AsAccessible (t, ModFlags)) {
3410 Report.Error (52, Location,
3411 "Inconsistent accessibility: field type `" +
3412 TypeManager.CSharpName (t) + "' is less " +
3413 "accessible than field `" + Name + "'");
3417 if (t.IsPointer && !UnsafeOK (parent))
3420 if (RootContext.WarningLevel > 1){
3421 Type ptype = parent.TypeBuilder.BaseType;
3423 // ptype is only null for System.Object while compiling corlib.
3425 TypeContainer.FindMembers (
3426 ptype, MemberTypes.Method,
3427 BindingFlags.Public |
3428 BindingFlags.Static | BindingFlags.Instance,
3429 System.Type.FilterName, Name);
3433 if ((ModFlags & Modifiers.VOLATILE) != 0){
3435 if (TypeManager.IsEnumType (t))
3436 t = TypeManager.EnumToUnderlying (t);
3438 if (!((t == TypeManager.bool_type) ||
3439 (t == TypeManager.sbyte_type) ||
3440 (t == TypeManager.byte_type) ||
3441 (t == TypeManager.short_type) ||
3442 (t == TypeManager.ushort_type) ||
3443 (t == TypeManager.int32_type) ||
3444 (t == TypeManager.uint32_type) ||
3445 (t == TypeManager.char_type) ||
3446 (t == TypeManager.float_type))){
3448 677, Location, parent.MakeName (Name) +
3449 " A volatile field can not be of type `" +
3450 TypeManager.CSharpName (t) + "'");
3456 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
3458 if (parent is Struct &&
3459 ((fa & FieldAttributes.Static) == 0) &&
3460 t == parent.TypeBuilder &&
3461 !TypeManager.IsBuiltinType (t)){
3462 Report.Error (523, Location, "Struct member `" + parent.Name + "." + Name +
3463 "' causes a cycle in the structure layout");
3466 FieldBuilder = parent.TypeBuilder.DefineField (
3467 Name, t, Modifiers.FieldAttr (ModFlags));
3469 TypeManager.RegisterFieldBase (FieldBuilder, this);
3473 public void Emit (TypeContainer tc)
3475 EmitContext ec = new EmitContext (tc, Location, null,
3476 FieldBuilder.FieldType, ModFlags);
3478 Attribute.ApplyAttributes (ec, FieldBuilder, this, OptAttributes, Location);
3483 // `set' and `get' accessors are represented with an Accessor.
3485 public class Accessor {
3487 // Null if the accessor is empty, or a Block if not
3490 public Attributes OptAttributes;
3492 public Accessor (Block b, Attributes attrs)
3495 OptAttributes = attrs;
3500 // Properties and Indexers both generate PropertyBuilders, we use this to share
3501 // their common bits.
3503 abstract public class PropertyBase : MethodCore {
3504 public Accessor Get, Set;
3505 public PropertyBuilder PropertyBuilder;
3506 public MethodBuilder GetBuilder, SetBuilder;
3507 public MethodData GetData, SetData;
3509 protected EmitContext ec;
3511 public PropertyBase (Expression type, string name, int mod_flags, int allowed_mod,
3512 Parameters parameters, Accessor get_block, Accessor set_block,
3513 Attributes attrs, Location loc)
3514 : base (type, mod_flags, allowed_mod, name, attrs, parameters, loc)
3520 protected override bool DoDefine (TypeContainer parent)
3522 if (!base.DoDefine (parent))
3525 ec = new EmitContext (parent, Location, null, MemberType, ModFlags);
3531 // Checks our base implementation if any
3533 protected override bool CheckBase (TypeContainer parent)
3535 // Check whether arguments were correct.
3536 if (!DoDefineParameters (parent))
3543 MethodSignature ms, base_ms;
3544 if (this is Indexer) {
3545 string name, base_name;
3547 report_name = "this";
3548 name = TypeManager.IndexerPropertyName (parent.TypeBuilder);
3549 ms = new MethodSignature (name, null, ParameterTypes);
3550 base_name = TypeManager.IndexerPropertyName (parent.TypeBuilder.BaseType);
3551 base_ms = new MethodSignature (base_name, null, ParameterTypes);
3554 ms = base_ms = new MethodSignature (Name, null, ParameterTypes);
3557 MemberList props_this;
3559 props_this = TypeContainer.FindMembers (
3560 parent.TypeBuilder, MemberTypes.Property,
3561 BindingFlags.NonPublic | BindingFlags.Public |
3562 BindingFlags.Static | BindingFlags.Instance |
3563 BindingFlags.DeclaredOnly,
3564 MethodSignature.method_signature_filter, ms);
3566 if (props_this.Count > 0) {
3567 Report.Error (111, Location, "Class `" + parent.Name + "' " +
3568 "already defines a member called `" + report_name + "' " +
3569 "with the same parameter types");
3574 // Find properties with the same name on the base class
3577 MemberList props_static = TypeContainer.FindMembers (
3578 parent.TypeBuilder.BaseType, MemberTypes.Property,
3579 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static,
3580 MethodSignature.inheritable_property_signature_filter, base_ms);
3582 MemberList props_instance = TypeContainer.FindMembers (
3583 parent.TypeBuilder.BaseType, MemberTypes.Property,
3584 BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
3585 MethodSignature.inheritable_property_signature_filter,
3589 // Find if we have anything
3591 if (props_static.Count > 0)
3592 props = props_static;
3593 else if (props_instance.Count > 0)
3594 props = props_instance;
3599 // If we have something on the base.
3600 if (props != null && props.Count > 0){
3601 PropertyInfo pi = (PropertyInfo) props [0];
3603 MethodInfo inherited_get = TypeManager.GetPropertyGetter (pi);
3604 MethodInfo inherited_set = TypeManager.GetPropertySetter (pi);
3606 MethodInfo reference = inherited_get == null ?
3607 inherited_set : inherited_get;
3609 if (reference != null) {
3610 string name = reference.DeclaringType.Name + "." + report_name;
3612 if (!CheckMethodAgainstBase (parent, flags, reference, name))
3616 if (((ModFlags & Modifiers.NEW) == 0) && (pi.PropertyType != MemberType)) {
3617 Report.Error (508, parent.MakeName (Name) + ": cannot " +
3618 "change return type when overriding inherited " +
3619 "member `" + pi.DeclaringType + "." + pi.Name + "'");
3623 if ((ModFlags & Modifiers.NEW) != 0)
3624 WarningNotHiding (parent);
3626 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3627 if (this is Indexer)
3628 Report.Error (115, Location,
3629 parent.MakeName (Name) +
3630 " no suitable indexers found to override");
3632 Report.Error (115, Location,
3633 parent.MakeName (Name) +
3634 " no suitable properties found to override");
3641 public void Emit (TypeContainer tc)
3644 // The PropertyBuilder can be null for explicit implementations, in that
3645 // case, we do not actually emit the ".property", so there is nowhere to
3646 // put the attribute
3648 if (PropertyBuilder != null)
3649 Attribute.ApplyAttributes (ec, PropertyBuilder, this, OptAttributes, Location);
3651 if (GetData != null)
3652 GetData.Emit (tc, Get.Block, Get);
3654 if (SetData != null)
3655 SetData.Emit (tc, Set.Block, Set);
3660 public class Property : PropertyBase {
3661 const int AllowedModifiers =
3664 Modifiers.PROTECTED |
3665 Modifiers.INTERNAL |
3669 Modifiers.OVERRIDE |
3670 Modifiers.ABSTRACT |
3675 string set_parameter_name;
3676 Parameters get_params;
3677 Parameters set_params;
3679 public Property (Expression type, string name, int mod_flags,
3680 Accessor get_block, Accessor set_block,
3681 Attributes attrs, Location loc, string set_name,
3682 Parameters p_get, Parameters p_set)
3683 : base (type, name, mod_flags, AllowedModifiers,
3685 get_block, set_block, attrs, loc)
3687 set_parameter_name = set_name;
3693 public Property (Expression type, string name, int mod_flags,
3694 Accessor get_block, Accessor set_block,
3695 Attributes attrs, Location loc, string set_name,
3696 Parameters p_get, Parameters p_set, Expression impl_what)
3697 : base (type, name, mod_flags, AllowedModifiers,
3699 get_block, set_block, attrs, loc)
3701 set_parameter_name = set_name;
3704 Implements = impl_what;
3707 public Property (Expression type, string name, int mod_flags,
3708 Accessor get_block, Accessor set_block,
3709 Attributes attrs, Location loc)
3710 : base (type, name, mod_flags, AllowedModifiers,
3711 Parameters.EmptyReadOnlyParameters,
3712 get_block, set_block, attrs, loc)
3714 set_parameter_name = "Value";
3715 get_params = Parameters.EmptyReadOnlyParameters;
3716 set_params = Parameters.EmptyReadOnlyParameters;
3719 public override bool Define (TypeContainer parent)
3721 Type [] g_parameters=null, s_parameters=null;
3722 Parameter [] g_parms, s_parms;
3723 InternalParameters g_ip=null, s_ip=null;
3725 if (!DoDefine (parent))
3728 if (!CheckBase (parent))
3731 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
3734 if (get_params == Parameters.EmptyReadOnlyParameters)
3736 g_parameters = TypeManager.NoTypes;
3737 g_ip = new InternalParameters (
3738 parent, Parameters.EmptyReadOnlyParameters);
3742 g_parameters = new Type [get_params.FixedParameters.Length];
3743 for (int i = 0; i < get_params.FixedParameters.Length; i ++)
3745 g_parameters[i] = get_params.FixedParameters[i].ParameterType;
3747 g_parms = new Parameter [get_params.FixedParameters.Length];
3748 for (int i = 0; i < get_params.FixedParameters.Length; i ++)
3750 Parameter tp = get_params.FixedParameters[i];
3751 g_parms[i] = new Parameter (tp.TypeName, tp.Name,
3752 Parameter.Modifier.NONE, null);
3754 g_ip = new InternalParameters (
3755 parent, new Parameters (g_parms, null, Location));
3758 GetData = new MethodData (this, "get", MemberType,
3759 g_parameters, g_ip, CallingConventions.Standard,
3760 Get.OptAttributes, ModFlags, flags, false);
3762 if (!GetData.Define (parent))
3765 GetBuilder = GetData.MethodBuilder;
3769 if (set_params == Parameters.EmptyReadOnlyParameters)
3771 s_parameters = new Type [1];
3772 s_parameters [0] = MemberType;
3774 s_parms = new Parameter [1];
3775 s_parms [0] = new Parameter (Type, /* was "value" */ set_parameter_name,
3776 Parameter.Modifier.NONE, null);
3780 s_parameters = new Type [set_params.FixedParameters.Length];
3781 for (int i = 0; i < set_params.FixedParameters.Length; i ++)
3783 s_parameters[i] = set_params.FixedParameters[i].ParameterType;
3786 s_parms = new Parameter [set_params.FixedParameters.Length];
3787 for (int i = 0; i < set_params.FixedParameters.Length; i ++)
3789 Parameter tp = set_params.FixedParameters[i];
3790 s_parms[i] = new Parameter (tp.TypeName, tp.Name,
3791 Parameter.Modifier.NONE, null);
3795 s_ip = new InternalParameters (
3796 parent, new Parameters (s_parms, null, Location));
3799 SetData = new MethodData (this, "set", TypeManager.void_type,
3800 s_parameters, s_ip, CallingConventions.Standard,
3801 Set.OptAttributes, ModFlags, flags, false);
3803 if (!SetData.Define (parent))
3806 SetBuilder = SetData.MethodBuilder;
3807 SetBuilder.DefineParameter (1, ParameterAttributes.None,
3808 /* was "value" */ set_parameter_name);
3811 // FIXME - PropertyAttributes.HasDefault ?
3813 PropertyAttributes prop_attr =
3814 PropertyAttributes.RTSpecialName |
3815 PropertyAttributes.SpecialName;
3817 if (!IsExplicitImpl){
3818 PropertyBuilder = parent.TypeBuilder.DefineProperty (
3819 Name, prop_attr, MemberType, null);
3822 PropertyBuilder.SetGetMethod (GetBuilder);
3825 PropertyBuilder.SetSetMethod (SetBuilder);
3828 // HACK for the reasons exposed above
3830 if (!TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder)) {
3833 "Class `" + parent.Name +
3834 "' already contains a definition for the property `" +
3842 public void Emit (TypeContainer tc)
3846 if (GetData != null)
3848 Parameters = get_params;
3849 GetData.Emit (tc, Get.Block, Get);
3852 if (SetData != null)
3854 Parameters = set_params;
3855 SetData.Emit (tc, Set.Block, Set);
3862 /// Gigantic workaround for lameness in SRE follows :
3863 /// This class derives from EventInfo and attempts to basically
3864 /// wrap around the EventBuilder so that FindMembers can quickly
3865 /// return this in it search for members
3867 public class MyEventBuilder : EventInfo {
3870 // We use this to "point" to our Builder which is
3871 // not really a MemberInfo
3873 EventBuilder MyBuilder;
3876 // We "catch" and wrap these methods
3878 MethodInfo raise, remove, add;
3880 EventAttributes attributes;
3881 Type declaring_type, reflected_type, event_type;
3884 public MyEventBuilder (TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
3886 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
3888 // And now store the values in our own fields.
3890 declaring_type = type_builder;
3892 reflected_type = type_builder;
3894 attributes = event_attr;
3896 this.event_type = event_type;
3900 // Methods that you have to override. Note that you only need
3901 // to "implement" the variants that take the argument (those are
3902 // the "abstract" methods, the others (GetAddMethod()) are
3905 public override MethodInfo GetAddMethod (bool nonPublic)
3910 public override MethodInfo GetRemoveMethod (bool nonPublic)
3915 public override MethodInfo GetRaiseMethod (bool nonPublic)
3921 // These methods make "MyEventInfo" look like a Builder
3923 public void SetRaiseMethod (MethodBuilder raiseMethod)
3925 raise = raiseMethod;
3926 MyBuilder.SetRaiseMethod (raiseMethod);
3929 public void SetRemoveOnMethod (MethodBuilder removeMethod)
3931 remove = removeMethod;
3932 MyBuilder.SetRemoveOnMethod (removeMethod);
3935 public void SetAddOnMethod (MethodBuilder addMethod)
3938 MyBuilder.SetAddOnMethod (addMethod);
3941 public void SetCustomAttribute (CustomAttributeBuilder cb)
3943 MyBuilder.SetCustomAttribute (cb);
3946 public override object [] GetCustomAttributes (bool inherit)
3948 // FIXME : There's nothing which can be seemingly done here because
3949 // we have no way of getting at the custom attribute objects of the
3954 public override object [] GetCustomAttributes (Type t, bool inherit)
3956 // FIXME : Same here !
3960 public override bool IsDefined (Type t, bool b)
3965 public override EventAttributes Attributes {
3971 public override string Name {
3977 public override Type DeclaringType {
3979 return declaring_type;
3983 public override Type ReflectedType {
3985 return reflected_type;
3989 public Type EventType {
3996 public class Event : FieldBase {
3997 const int AllowedModifiers =
4000 Modifiers.PROTECTED |
4001 Modifiers.INTERNAL |
4006 Modifiers.OVERRIDE |
4010 public readonly Accessor Add;
4011 public readonly Accessor Remove;
4012 public MyEventBuilder EventBuilder;
4014 MethodBuilder AddBuilder, RemoveBuilder;
4015 MethodData AddData, RemoveData;
4017 public Event (Expression type, string name, Object init, int mod, Accessor add,
4018 Accessor remove, Attributes attrs, Location loc)
4019 : base (type, mod, AllowedModifiers, name, init, attrs, loc)
4025 public override bool Define (TypeContainer parent)
4027 EventAttributes e_attr = EventAttributes.RTSpecialName | EventAttributes.SpecialName;
4029 if (!DoDefine (parent))
4032 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
4033 Report.Error (66, Location, "'" + parent.Name + "." + Name +
4034 "' : event must be of a delegate type");
4038 Type [] parameter_types = new Type [1];
4039 parameter_types [0] = MemberType;
4041 Parameter [] parms = new Parameter [1];
4042 parms [0] = new Parameter (Type, /* was "value" */ this.Name, Parameter.Modifier.NONE, null);
4043 InternalParameters ip = new InternalParameters (
4044 parent, new Parameters (parms, null, Location));
4046 if (!CheckBase (parent))
4050 // Now define the accessors
4052 AddData = new MethodData (this, "add", TypeManager.void_type,
4053 parameter_types, ip, CallingConventions.Standard,
4054 (Add != null) ? Add.OptAttributes : null,
4055 ModFlags, flags, false);
4057 if (!AddData.Define (parent))
4060 AddBuilder = AddData.MethodBuilder;
4061 AddBuilder.DefineParameter (1, ParameterAttributes.None, /* was "value" */ this.Name);
4063 RemoveData = new MethodData (this, "remove", TypeManager.void_type,
4064 parameter_types, ip, CallingConventions.Standard,
4065 (Remove != null) ? Remove.OptAttributes : null,
4066 ModFlags, flags, false);
4068 if (!RemoveData.Define (parent))
4071 RemoveBuilder = RemoveData.MethodBuilder;
4072 RemoveBuilder.DefineParameter (1, ParameterAttributes.None, /* was "value" */ this.Name);
4074 if (!IsExplicitImpl){
4075 EventBuilder = new MyEventBuilder (
4076 parent.TypeBuilder, Name, e_attr, MemberType);
4078 if (Add == null && Remove == null) {
4079 FieldBuilder = parent.TypeBuilder.DefineField (
4081 FieldAttributes.FamANDAssem | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
4082 TypeManager.RegisterPrivateFieldOfEvent (
4083 (EventInfo) EventBuilder, FieldBuilder);
4084 TypeManager.RegisterFieldBase (FieldBuilder, this);
4087 EventBuilder.SetAddOnMethod (AddBuilder);
4088 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
4090 if (!TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder)) {
4091 Report.Error (111, Location,
4092 "Class `" + parent.Name +
4093 "' already contains a definition for the event `" +
4102 void EmitDefaultMethod (EmitContext ec, bool is_add)
4104 ILGenerator ig = ec.ig;
4105 MethodInfo method = null;
4108 method = TypeManager.delegate_combine_delegate_delegate;
4110 method = TypeManager.delegate_remove_delegate_delegate;
4112 if ((ModFlags & Modifiers.STATIC) != 0) {
4113 ig.Emit (OpCodes.Ldsfld, (FieldInfo) FieldBuilder);
4114 ig.Emit (OpCodes.Ldarg_0);
4115 ig.Emit (OpCodes.Call, method);
4116 ig.Emit (OpCodes.Castclass, MemberType);
4117 ig.Emit (OpCodes.Stsfld, (FieldInfo) FieldBuilder);
4119 ig.Emit (OpCodes.Ldarg_0);
4120 ig.Emit (OpCodes.Ldarg_0);
4121 ig.Emit (OpCodes.Ldfld, (FieldInfo) FieldBuilder);
4122 ig.Emit (OpCodes.Ldarg_1);
4123 ig.Emit (OpCodes.Call, method);
4124 ig.Emit (OpCodes.Castclass, MemberType);
4125 ig.Emit (OpCodes.Stfld, (FieldInfo) FieldBuilder);
4127 ig.Emit (OpCodes.Ret);
4130 public void Emit (TypeContainer tc)
4134 ec = new EmitContext (tc, Location, null, MemberType, ModFlags);
4135 Attribute.ApplyAttributes (ec, EventBuilder, this, OptAttributes, Location);
4138 AddData.Emit (tc, Add.Block, Add);
4140 ILGenerator ig = AddData.MethodBuilder.GetILGenerator ();
4141 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
4142 EmitDefaultMethod (ec, true);
4146 RemoveData.Emit (tc, Remove.Block, Remove);
4148 ILGenerator ig = RemoveData.MethodBuilder.GetILGenerator ();
4149 ec = new EmitContext (tc, Location, ig, TypeManager.void_type, ModFlags);
4150 EmitDefaultMethod (ec, false);
4157 // FIXME: This does not handle:
4159 // int INTERFACENAME [ args ]
4164 // int this [ args ]
4166 public class Indexer : PropertyBase {
4168 const int AllowedModifiers =
4171 Modifiers.PROTECTED |
4172 Modifiers.INTERNAL |
4176 Modifiers.OVERRIDE |
4181 public string IndexerName;
4182 public string InterfaceIndexerName;
4185 // Are we implementing an interface ?
4187 bool IsImplementing = false;
4189 public Indexer (Expression type, string int_type, int flags, Parameters parameters,
4190 Accessor get_block, Accessor set_block, Attributes attrs, Location loc)
4191 : base (type, "", flags, AllowedModifiers, parameters, get_block, set_block,
4194 ExplicitInterfaceName = int_type;
4197 public override bool Define (TypeContainer parent)
4199 PropertyAttributes prop_attr =
4200 PropertyAttributes.RTSpecialName |
4201 PropertyAttributes.SpecialName;
4203 if (!DoDefine (parent))
4206 IndexerName = Attribute.ScanForIndexerName (ec, OptAttributes);
4207 if (IndexerName == null)
4208 IndexerName = "Item";
4209 else if (IsExplicitImpl)
4210 Report.Error (592, Location,
4211 "Attribute 'IndexerName' is not valid on this declaration " +
4212 "type. It is valid on `property' declarations only.");
4214 ShortName = IndexerName;
4215 if (IsExplicitImpl) {
4216 InterfaceIndexerName = TypeManager.IndexerPropertyName (InterfaceType);
4217 Name = InterfaceType.FullName + "." + IndexerName;
4219 InterfaceIndexerName = IndexerName;
4223 if (!CheckBase (parent))
4227 InternalParameters ip = new InternalParameters (parent, Parameters);
4229 GetData = new MethodData (this, "get", MemberType,
4230 ParameterTypes, ip, CallingConventions.Standard,
4231 Get.OptAttributes, ModFlags, flags, false);
4233 if (!GetData.Define (parent))
4236 GetBuilder = GetData.MethodBuilder;
4240 int top = ParameterTypes.Length;
4241 Type [] set_pars = new Type [top + 1];
4242 ParameterTypes.CopyTo (set_pars, 0);
4243 set_pars [top] = MemberType;
4245 Parameter [] fixed_parms = Parameters.FixedParameters;
4247 if (fixed_parms == null){
4248 throw new Exception ("We currently do not support only array arguments in an indexer");
4249 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4250 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4252 // Here is the problem: the `value' parameter has
4253 // to come *after* the array parameter in the declaration
4255 // X (object [] x, Type value)
4258 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4259 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
4263 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
4266 fixed_parms.CopyTo (tmp, 0);
4267 tmp [fixed_parms.Length] = new Parameter (
4268 Type, /* was "value" */ this.Name, Parameter.Modifier.NONE, null);
4270 Parameters set_formal_params = new Parameters (tmp, null, Location);
4272 InternalParameters ip = new InternalParameters (parent, set_formal_params);
4274 SetData = new MethodData (this, "set", TypeManager.void_type,
4275 set_pars, ip, CallingConventions.Standard,
4276 Set.OptAttributes, ModFlags, flags, false);
4278 if (!SetData.Define (parent))
4281 SetBuilder = SetData.MethodBuilder;
4285 // Now name the parameters
4287 Parameter [] p = Parameters.FixedParameters;
4291 for (i = 0; i < p.Length; ++i) {
4293 GetBuilder.DefineParameter (
4294 i + 1, p [i].Attributes, p [i].Name);
4297 SetBuilder.DefineParameter (
4298 i + 1, p [i].Attributes, p [i].Name);
4303 SetBuilder.DefineParameter (
4304 i + 1, ParameterAttributes.None, /* was "value" */ this.Name);
4306 if (i != ParameterTypes.Length) {
4307 Parameter array_param = Parameters.ArrayParameter;
4308 SetBuilder.DefineParameter (
4309 i + 1, array_param.Attributes, array_param.Name);
4313 if (GetData != null)
4314 IsImplementing = GetData.IsImplementing;
4315 else if (SetData != null)
4316 IsImplementing = SetData.IsImplementing;
4319 // Define the PropertyBuilder if one of the following conditions are met:
4320 // a) we're not implementing an interface indexer.
4321 // b) the indexer has a different IndexerName and this is no
4322 // explicit interface implementation.
4324 if (!IsExplicitImpl) {
4325 PropertyBuilder = parent.TypeBuilder.DefineProperty (
4326 IndexerName, prop_attr, MemberType, ParameterTypes);
4328 if (GetData != null)
4329 PropertyBuilder.SetGetMethod (GetBuilder);
4331 if (SetData != null)
4332 PropertyBuilder.SetSetMethod (SetBuilder);
4334 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder,
4342 public class Operator : MemberCore {
4344 const int AllowedModifiers =
4350 const int RequiredModifiers =
4354 public enum OpType : byte {
4364 // Unary and Binary operators
4387 // Implicit and Explicit
4392 public readonly OpType OperatorType;
4393 public readonly Expression ReturnType;
4394 public readonly Expression FirstArgType, SecondArgType;
4395 public readonly string FirstArgName, SecondArgName;
4396 public readonly Block Block;
4397 public Attributes OptAttributes;
4398 public MethodBuilder OperatorMethodBuilder;
4400 public string MethodName;
4401 public Method OperatorMethod;
4403 public Operator (OpType type, Expression ret_type, int flags,
4404 Expression arg1type, string arg1name,
4405 Expression arg2type, string arg2name,
4406 Block block, Attributes attrs, Location loc)
4409 OperatorType = type;
4410 ReturnType = ret_type;
4411 ModFlags = Modifiers.Check (AllowedModifiers, flags, Modifiers.PUBLIC, loc);
4412 FirstArgType = arg1type;
4413 FirstArgName = arg1name;
4414 SecondArgType = arg2type;
4415 SecondArgName = arg2name;
4417 OptAttributes = attrs;
4420 string Prototype (TypeContainer parent)
4422 return parent.Name + ".operator " + OperatorType + " (" + FirstArgType + "," +
4423 SecondArgType + ")";
4426 public override bool Define (TypeContainer parent)
4429 MethodName = "op_" + OperatorType;
4431 if (SecondArgType != null)
4434 Parameter [] param_list = new Parameter [length];
4436 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
4439 "User defined operators `" +
4440 Prototype (parent) +
4441 "' must be declared static and public");
4445 param_list[0] = new Parameter (FirstArgType, FirstArgName,
4446 Parameter.Modifier.NONE, null);
4447 if (SecondArgType != null)
4448 param_list[1] = new Parameter (SecondArgType, SecondArgName,
4449 Parameter.Modifier.NONE, null);
4451 OperatorMethod = new Method (ReturnType, ModFlags, MethodName,
4452 new Parameters (param_list, null, Location),
4453 OptAttributes, Mono.CSharp.Location.Null);
4455 OperatorMethod.IsOperator = true;
4456 OperatorMethod.Define (parent);
4458 if (OperatorMethod.MethodBuilder == null)
4461 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
4463 Type [] param_types = OperatorMethod.ParameterTypes;
4464 Type declaring_type = OperatorMethodBuilder.DeclaringType;
4465 Type return_type = OperatorMethod.GetReturnType ();
4466 Type first_arg_type = param_types [0];
4468 // Rules for conversion operators
4470 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
4471 if (first_arg_type == return_type && first_arg_type == declaring_type){
4474 "User-defined conversion cannot take an object of the " +
4475 "enclosing type and convert to an object of the enclosing" +
4480 if (first_arg_type != declaring_type && return_type != declaring_type){
4483 "User-defined conversion must convert to or from the " +
4488 if (first_arg_type == TypeManager.object_type ||
4489 return_type == TypeManager.object_type){
4492 "User-defined conversion cannot convert to or from " +
4497 if (first_arg_type.IsInterface || return_type.IsInterface){
4500 "User-defined conversion cannot convert to or from an " +
4505 if (first_arg_type.IsSubclassOf (return_type) ||
4506 return_type.IsSubclassOf (first_arg_type)){
4509 "User-defined conversion cannot convert between types " +
4510 "that derive from each other");
4513 } else if (SecondArgType == null) {
4514 // Checks for Unary operators
4516 if (first_arg_type != declaring_type){
4519 "The parameter of a unary operator must be the " +
4524 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
4525 if (return_type != declaring_type){
4528 "The parameter and return type for ++ and -- " +
4529 "must be the containing type");
4535 if (OperatorType == OpType.True || OperatorType == OpType.False) {
4536 if (return_type != TypeManager.bool_type){
4539 "The return type of operator True or False " +
4546 // Checks for Binary operators
4548 if (first_arg_type != declaring_type &&
4549 param_types [1] != declaring_type){
4552 "One of the parameters of a binary operator must " +
4553 "be the containing type");
4561 public void Emit (TypeContainer parent)
4563 EmitContext ec = new EmitContext (parent, Location, null, null, ModFlags);
4564 Attribute.ApplyAttributes (ec, OperatorMethodBuilder, this, OptAttributes, Location);
4567 // abstract or extern methods have no bodies
4569 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
4572 OperatorMethod.Block = Block;
4573 OperatorMethod.Emit (parent);
4576 public static string GetName (OpType ot)
4579 case OpType.LogicalNot:
4581 case OpType.OnesComplement:
4583 case OpType.Increment:
4585 case OpType.Decrement:
4591 case OpType.Addition:
4593 case OpType.Subtraction:
4595 case OpType.UnaryPlus:
4597 case OpType.UnaryNegation:
4599 case OpType.Multiply:
4601 case OpType.Division:
4603 case OpType.Modulus:
4605 case OpType.BitwiseAnd:
4607 case OpType.BitwiseOr:
4609 case OpType.ExclusiveOr:
4611 case OpType.LeftShift:
4613 case OpType.RightShift:
4615 case OpType.Equality:
4617 case OpType.Inequality:
4619 case OpType.GreaterThan:
4621 case OpType.LessThan:
4623 case OpType.GreaterThanOrEqual:
4625 case OpType.LessThanOrEqual:
4627 case OpType.Implicit:
4629 case OpType.Explicit:
4635 public override string ToString ()
4637 Type return_type = OperatorMethod.GetReturnType();
4638 Type [] param_types = OperatorMethod.ParameterTypes;
4640 if (SecondArgType == null)
4641 return String.Format (
4642 "{0} operator {1}({2})",
4643 TypeManager.CSharpName (return_type),
4644 GetName (OperatorType),
4647 return String.Format (
4648 "{0} operator {1}({2}, {3})",
4649 TypeManager.CSharpName (return_type),
4650 GetName (OperatorType),
4651 param_types [0], param_types [1]);
4656 // This is used to compare method signatures
4658 struct MethodSignature {
4660 public Type RetType;
4661 public Type [] Parameters;
4664 /// This delegate is used to extract methods which have the
4665 /// same signature as the argument
4667 public static MemberFilter method_signature_filter;
4670 /// This delegate is used to extract methods which have the
4671 /// same signature as the argument except for the name
4673 public static MemberFilter method_signature_noname_filter;
4676 /// This delegate is used to extract inheritable methods which
4677 /// have the same signature as the argument. By inheritable,
4678 /// this means that we have permissions to override the method
4679 /// from the current assembly and class
4681 public static MemberFilter inheritable_method_signature_filter;
4684 /// This delegate is used to extract inheritable methods which
4685 /// have the same signature as the argument. By inheritable,
4686 /// this means that we have permissions to override the method
4687 /// from the current assembly and class
4689 public static MemberFilter inheritable_property_signature_filter;
4691 static MethodSignature ()
4693 method_signature_filter = new MemberFilter (MemberSignatureCompare);
4694 method_signature_noname_filter = new MemberFilter (MemberSignatureCompareNoName);
4695 inheritable_method_signature_filter = new MemberFilter (
4696 InheritableMemberSignatureCompare);
4697 inheritable_property_signature_filter = new MemberFilter (
4698 InheritablePropertySignatureCompare);
4701 public MethodSignature (string name, Type ret_type, Type [] parameters)
4706 if (parameters == null)
4707 Parameters = TypeManager.NoTypes;
4709 Parameters = parameters;
4712 public override int GetHashCode ()
4714 return Name.GetHashCode ();
4717 public override bool Equals (Object o)
4719 MethodSignature other = (MethodSignature) o;
4721 if (other.Name != Name)
4724 if (other.RetType != RetType)
4727 if (Parameters == null){
4728 if (other.Parameters == null)
4733 if (other.Parameters == null)
4736 int c = Parameters.Length;
4737 if (other.Parameters.Length != c)
4740 for (int i = 0; i < c; i++)
4741 if (other.Parameters [i] != Parameters [i])
4747 static bool MemberSignatureCompareNoName (MemberInfo m, object filter_criteria)
4749 return MemberSignatureCompare (m, filter_criteria, false);
4752 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
4754 return MemberSignatureCompare (m, filter_criteria, true);
4757 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria, bool use_name)
4759 MethodSignature sig = (MethodSignature) filter_criteria;
4761 if (use_name && (m.Name != sig.Name))
4765 MethodInfo mi = m as MethodInfo;
4766 PropertyInfo pi = m as PropertyInfo;
4769 ReturnType = mi.ReturnType;
4770 else if (pi != null)
4771 ReturnType = pi.PropertyType;
4776 // we use sig.RetType == null to mean `do not check the
4777 // method return value.
4779 if (sig.RetType != null)
4780 if (ReturnType != sig.RetType)
4785 args = TypeManager.GetArgumentTypes (mi);
4787 args = TypeManager.GetArgumentTypes (pi);
4788 Type [] sigp = sig.Parameters;
4790 if (args.Length != sigp.Length)
4793 for (int i = args.Length; i > 0; ){
4795 if (args [i] != sigp [i])
4802 // This filter should be used when we are requesting methods that
4803 // we want to override.
4805 // This makes a number of assumptions, for example
4806 // that the methods being extracted are of a parent
4807 // class (this means we know implicitly that we are
4808 // being called to find out about members by a derived
4811 static bool InheritableMemberSignatureCompare (MemberInfo m, object filter_criteria)
4813 if (MemberSignatureCompare (m, filter_criteria)){
4814 MethodInfo mi = (MethodInfo) m;
4815 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4817 // If only accessible to the current class.
4818 if (prot == MethodAttributes.Private)
4821 // If only accessible to the defining assembly or
4822 if (prot == MethodAttributes.FamANDAssem ||
4823 prot == MethodAttributes.Assembly){
4824 if (m.DeclaringType.Assembly == CodeGen.AssemblyBuilder)
4830 // Anything else (FamOrAssembly and Public) is fine
4837 // This filter should be used when we are requesting properties that
4838 // we want to override.
4840 // This makes a number of assumptions, for example
4841 // that the methods being extracted are of a parent
4842 // class (this means we know implicitly that we are
4843 // being called to find out about members by a derived
4846 static bool InheritablePropertySignatureCompare (MemberInfo m, object filter_criteria)
4848 if (MemberSignatureCompare (m, filter_criteria)){
4849 PropertyInfo pi = (PropertyInfo) m;
4851 MethodInfo inherited_get = TypeManager.GetPropertyGetter (pi);
4852 MethodInfo inherited_set = TypeManager.GetPropertySetter (pi);
4854 MethodInfo mi = inherited_get == null ? inherited_set : inherited_get;
4856 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4858 // If only accessible to the current class.
4859 if (prot == MethodAttributes.Private)
4862 // If only accessible to the defining assembly or
4863 if (prot == MethodAttributes.FamANDAssem ||
4864 prot == MethodAttributes.Assembly){
4865 if (m.DeclaringType.Assembly == CodeGen.AssemblyBuilder)
4871 // Anything else (FamOrAssembly and Public) is fine