2 // class.cs: Class and Struct handlers
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
19 public class TypeContainer : DeclSpace {
20 protected int mod_flags;
22 // Holds a list of classes and structures
25 // Holds the list of properties
28 // Holds the list of enumerations
31 // Holds the list of delegates
34 // Holds the list of constructors
35 ArrayList constructors;
37 // Holds the list of fields
40 // Holds a list of fields that have initializers
41 ArrayList initialized_fields;
43 // Holds a list of static fields that have initializers
44 ArrayList initialized_static_fields;
46 // Holds the list of constants
61 // Holds the operators
64 // Maps MethodBuilders to Methods
65 static Hashtable method_builders_to_parameters;
68 // Pointers to the default constructor and the default static constructor
70 Constructor default_constructor;
71 Constructor default_static_constructor;
74 // Whether we have seen a static constructor for this class or not
76 bool have_static_constructor = false;
79 // This is the namespace in which this typecontainer
80 // was declared. We use this to resolve names.
82 Namespace my_namespace;
85 // This one is computed after we can distinguish interfaces
86 // from classes from the arraylist `type_bases'
88 string base_class_name;
94 // This behaves like a property ;-)
96 public readonly RootContext RootContext;
98 // Attributes for this type
99 protected Attributes attributes;
101 public TypeContainer (RootContext rc, TypeContainer parent, string name, Location l)
105 types = new ArrayList ();
106 this.parent = parent;
114 base_class_name = null;
116 //Console.WriteLine ("New class " + name + " inside " + n);
119 public AdditionResult AddConstant (Constant constant)
122 string name = constant.Name;
124 if ((res = IsValid (name)) != AdditionResult.Success)
127 if (constants == null)
128 constants = new ArrayList ();
130 constants.Add (constant);
131 DefineName (name, constant);
133 return AdditionResult.Success;
136 public AdditionResult AddEnum (CIR.Enum e)
139 string name = e.Name;
141 if ((res = IsValid (name)) != AdditionResult.Success)
145 enums = new ArrayList ();
148 DefineName (name, e);
150 return AdditionResult.Success;
153 public AdditionResult AddClass (Class c)
156 string name = c.Name;
159 if ((res = IsValid (name)) != AdditionResult.Success)
162 DefineName (name, c);
165 return AdditionResult.Success;
168 public AdditionResult AddStruct (Struct s)
171 string name = s.Name;
173 if ((res = IsValid (name)) != AdditionResult.Success)
176 DefineName (name, s);
179 return AdditionResult.Success;
182 public AdditionResult AddDelegate (Delegate d)
185 string name = d.Name;
187 if ((res = IsValid (name)) != AdditionResult.Success)
190 if (delegates == null)
191 delegates = new ArrayList ();
193 DefineName (name, d);
196 return AdditionResult.Success;
199 public AdditionResult AddMethod (Method method)
201 string name = method.Name;
202 Object value = defined_names [name];
204 if (value != null && (!(value is Method)))
205 return AdditionResult.NameExists;
208 methods = new ArrayList ();
210 methods.Add (method);
212 DefineName (name, method);
214 return AdditionResult.Success;
217 public AdditionResult AddConstructor (Constructor c)
219 if (c.Name != Basename)
220 return AdditionResult.NotAConstructor;
222 if (constructors == null)
223 constructors = new ArrayList ();
225 constructors.Add (c);
227 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
230 have_static_constructor = true;
232 if (c.IsDefault ()) {
234 default_static_constructor = c;
236 default_constructor = c;
239 return AdditionResult.Success;
242 public AdditionResult AddInterface (Interface iface)
245 string name = iface.Name;
247 if ((res = IsValid (name)) != AdditionResult.Success)
250 if (interfaces == null)
251 interfaces = new ArrayList ();
252 interfaces.Add (iface);
253 DefineName (name, iface);
255 return AdditionResult.Success;
258 public AdditionResult AddField (Field field)
261 string name = field.Name;
263 if ((res = IsValid (name)) != AdditionResult.Success)
267 fields = new ArrayList ();
270 if (field.Initializer != null){
271 if ((field.ModFlags & Modifiers.STATIC) != 0){
272 if (initialized_static_fields == null)
273 initialized_static_fields = new ArrayList ();
275 initialized_static_fields.Add (field);
278 // We have not seen a static constructor,
279 // but we will provide static initialization of fields
281 have_static_constructor = true;
283 if (initialized_fields == null)
284 initialized_fields = new ArrayList ();
286 initialized_fields.Add (field);
290 DefineName (name, field);
291 return AdditionResult.Success;
294 public AdditionResult AddProperty (Property prop)
297 string name = prop.Name;
299 if ((res = IsValid (name)) != AdditionResult.Success)
302 if (properties == null)
303 properties = new ArrayList ();
305 properties.Add (prop);
306 DefineName (name, prop);
308 return AdditionResult.Success;
311 public AdditionResult AddEvent (Event e)
314 string name = e.Name;
316 if ((res = IsValid (name)) != AdditionResult.Success)
320 events = new ArrayList ();
323 DefineName (name, e);
325 return AdditionResult.Success;
328 public AdditionResult AddIndexer (Indexer i)
330 if (indexers == null)
331 indexers = new ArrayList ();
335 return AdditionResult.Success;
338 public AdditionResult AddOperator (Operator op)
340 if (operators == null)
341 operators = new ArrayList ();
345 return AdditionResult.Success;
348 public TypeContainer Parent {
354 public ArrayList Types {
360 public ArrayList Methods {
366 public ArrayList Constants {
372 public ArrayList Interfaces {
378 public int ModFlags {
386 return base_class_name;
390 public ArrayList Bases {
400 public ArrayList Fields {
406 public ArrayList Constructors {
412 public ArrayList Properties {
418 public ArrayList Events {
424 public ArrayList Enums {
430 public ArrayList Indexers {
436 public ArrayList Operators {
442 public ArrayList Delegates {
448 public Attributes OptAttributes {
454 public Namespace Namespace {
460 my_namespace = value;
465 // root_types contains all the types. All TopLevel types
466 // hence have a parent that points to `root_types', that is
467 // why there is a non-obvious test down here.
469 public bool IsTopLevel {
472 if (parent.Parent == null)
479 public bool HaveStaticConstructor {
481 return have_static_constructor;
485 public virtual TypeAttributes TypeAttr {
487 return Modifiers.TypeAttr (mod_flags, this);
492 // Emits the instance field initializers
494 public bool EmitFieldInitializers (EmitContext ec, bool is_static)
497 ILGenerator ig = ec.ig;
500 fields = initialized_static_fields;
502 fields = initialized_fields;
507 foreach (Field f in fields){
508 Object init = f.Initializer;
510 if (init is Expression){
511 Expression e = (Expression) init;
518 ig.Emit (OpCodes.Ldarg_0);
523 ig.Emit (OpCodes.Stsfld, f.FieldBuilder);
525 ig.Emit (OpCodes.Stfld, f.FieldBuilder);
533 // Defines the default constructors
535 void DefineDefaultConstructor (bool is_static)
540 c = new Constructor (Basename, new Parameters (null, null),
541 new ConstructorBaseInitializer (null, new Location (-1)),
546 c.Block = new Block (null);
549 mods = Modifiers.STATIC;
555 public void ReportStructInitializedInstanceError ()
557 string n = TypeBuilder.FullName;
559 foreach (Field f in initialized_fields){
562 "`" + n + "." + f.Name + "': can not have " +
563 "instance field initializers in structs");
567 public void RegisterRequiredImplementations ()
569 Type [] ifaces = TypeBuilder.GetInterfaces ();
570 Type b = TypeBuilder.BaseType;
573 SetRequiredInterfaces (ifaces);
576 MemberInfo [] abstract_methods;
578 abstract_methods = FindMembers (
579 TypeBuilder.BaseType,
580 MemberTypes.Method, BindingFlags.Public,
581 abstract_method_filter, null);
583 if (abstract_methods != null){
584 MethodInfo [] mi = new MethodInfo [abstract_methods.Length];
586 abstract_methods.CopyTo (mi, 0);
587 RequireMethods (mi, b);
593 static object MakeKey (MethodBase mb)
595 if (mb is MethodBuilder || mb is ConstructorBuilder)
596 return mb.ReflectedType.FullName + ":" + mb;
598 return mb.MethodHandle.ToString ();
602 public static string MakeFQN (string nsn, string name)
604 string prefix = (nsn == "" ? "" : nsn + ".");
606 return prefix + name;
609 Type LookupInterfaceOrClass (object builder, string ns, string name, bool is_class, out bool error)
611 TypeContainer parent;
615 name = MakeFQN (ns, name);
617 t = RootContext.TypeManager.LookupType (name);
622 parent = (Class) RootContext.Tree.Classes [name];
624 parent = (Struct) RootContext.Tree.Structs [name];
628 t = parent.DefineType (builder);
630 Report.Error (146, "Class definition is circular: `"+name+"'");
642 // returns the type for an interface or a class, this will recursively
643 // try to define the types that it depends on.
645 Type GetInterfaceOrClass (object builder, string name, bool is_class)
651 // Attempt to lookup the class on our namespace
653 t = LookupInterfaceOrClass (builder, Namespace.Name, name, is_class, out error);
661 // Attempt to do a direct unqualified lookup
663 t = LookupInterfaceOrClass (builder, "", name, is_class, out error);
671 // Attempt to lookup the class on any of the `using'
675 for (Namespace ns = Namespace; ns != null; ns = ns.Parent){
676 ArrayList using_list = ns.UsingTable;
678 if (using_list == null)
681 foreach (string n in using_list){
682 t = LookupInterfaceOrClass (builder, n, name, is_class, out error);
691 Report.Error (246, "Can not find type `"+name+"'");
696 // This function computes the Base class and also the
697 // list of interfaces that the class or struct @c implements.
699 // The return value is an array (might be null) of
700 // interfaces implemented (as Types).
702 // The @parent argument is set to the parent object or null
703 // if this is `System.Object'.
705 Type [] GetClassBases (object builder, bool is_class, out Type parent, out bool error)
707 ArrayList bases = Bases;
716 parent = TypeManager.value_type;
720 if (RootContext.StdLib)
721 parent = TypeManager.object_type;
722 else if (Name != "System.Object")
723 parent = TypeManager.object_type;
726 // If we are compiling our runtime,
727 // and we are defining ValueType, then our
728 // parent is `System.Object'.
730 if (!RootContext.StdLib && Name == "System.ValueType")
731 parent = TypeManager.object_type;
738 // Bases should be null if there are no bases at all
743 string name = (string) bases [0];
744 Type first = GetInterfaceOrClass (builder, name, is_class);
755 parent = TypeManager.object_type;
762 Type [] ifaces = new Type [count-start];
764 for (i = start, j = 0; i < count; i++, j++){
765 string name = (string) bases [i];
766 Type t = GetInterfaceOrClass (builder, name, is_class);
773 if (is_class == false && !t.IsInterface){
774 Report.Error (527, "In Struct `" + Name + "', type `"+
775 name +"' is not an interface");
784 detail = " (a class can not inherit from a struct)";
786 Report.Error (509, "class `"+ Name +
787 "': Cannot inherit from sealed class `"+
788 bases [i]+"'"+detail);
795 Report.Error (527, "In Class `" + Name + "', type `"+
796 name+"' is not an interface");
809 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
811 public TypeBuilder DefineType (object parent_builder)
828 ifaces = GetClassBases (parent_builder, is_class, out parent, out error);
833 if (parent_builder is ModuleBuilder) {
834 ModuleBuilder builder = (ModuleBuilder) parent_builder;
837 // Structs with no fields need to have a ".size 1"
840 if (!is_class && Fields == null)
841 TypeBuilder = builder.DefineType (Name,
844 PackingSize.Unspecified, 1);
847 // classes or structs with fields
849 TypeBuilder = builder.DefineType (Name,
855 TypeBuilder builder = (TypeBuilder) parent_builder;
858 // Structs with no fields need to have a ".size 1"
861 if (!is_class && Fields == null)
862 TypeBuilder = builder.DefineNestedType (Name,
865 PackingSize.Unspecified);
868 // classes or structs with fields
870 TypeBuilder = builder.DefineNestedType (Name,
876 RootContext.TypeManager.AddUserType (Name, TypeBuilder, this);
879 foreach (TypeContainer tc in Types)
880 tc.DefineType (TypeBuilder);
883 if (Delegates != null) {
884 foreach (Delegate d in Delegates)
885 d.DefineDelegate (TypeBuilder);
893 // Populates our TypeBuilder with fields and methods
895 public void Populate ()
897 if (Constants != null){
898 foreach (Constant c in Constants)
899 c.EmitConstant (RootContext, this);
903 foreach (Field f in Fields)
907 if (this is Class && constructors == null){
908 if (default_constructor == null)
909 DefineDefaultConstructor (false);
911 if (initialized_static_fields != null &&
912 default_static_constructor == null)
913 DefineDefaultConstructor (true);
918 // Structs can not have initialized instance
921 if (initialized_static_fields != null &&
922 default_static_constructor == null)
923 DefineDefaultConstructor (true);
925 if (initialized_fields != null)
926 ReportStructInitializedInstanceError ();
929 RegisterRequiredImplementations ();
931 ArrayList remove_list = new ArrayList ();
933 if (constructors != null || methods != null ||
934 properties != null || operators != null){
935 if (method_builders_to_parameters == null)
936 method_builders_to_parameters = new Hashtable ();
939 if (constructors != null){
940 foreach (Constructor c in constructors){
941 MethodBase builder = c.Define (this);
946 InternalParameters ip = c.ParameterInfo;
948 method_builders_to_parameters.Add (MakeKey (builder), ip);
952 foreach (object o in remove_list)
953 constructors.Remove (o);
955 remove_list.Clear ();
958 if (Methods != null){
959 foreach (Method m in methods){
960 MethodBase key = m.Define (this);
964 // The following key is not enoug
965 // class x { public void X () {} }
966 // class y : x { public void X () {}}
972 InternalParameters ip = m.ParameterInfo;
973 method_builders_to_parameters.Add (MakeKey (key), ip);
976 foreach (object o in remove_list)
979 remove_list.Clear ();
982 if (Properties != null) {
983 foreach (Property p in Properties)
988 foreach (Enum e in Enums)
992 if (Events != null) {
993 foreach (Event e in Events)
997 if (Indexers != null) {
998 foreach (Indexer i in Indexers)
1002 if (Operators != null) {
1003 foreach (Operator o in Operators) {
1006 InternalParameters ip = o.OperatorMethod.ParameterInfo;
1008 method_builders_to_parameters.Add (
1009 MakeKey (o.OperatorMethodBuilder), ip);
1013 if (Delegates != null) {
1014 foreach (Delegate d in Delegates)
1018 if (Types != null) {
1019 foreach (TypeContainer tc in Types)
1027 // Since System.Reflection.Emit can not retrieve parameter information
1028 // from methods that are dynamically defined, we have to look those
1029 // up ourselves using this
1031 static public ParameterData LookupParametersByBuilder (MethodBase mb)
1033 return (ParameterData) method_builders_to_parameters [MakeKey (mb)];
1037 // Indexers and properties can register more than one method at once,
1038 // so we need to provide a mechanism for those to register their
1039 // various methods to parameter info mappers.
1041 static public void RegisterParameterForBuilder (MethodBase mb, InternalParameters pi)
1043 method_builders_to_parameters.Add (MakeKey (mb), pi);
1046 public Type LookupType (string name, bool silent)
1048 return RootContext.LookupType (this, name, silent);
1051 public string LookupAlias (string Name)
1054 // Read the comments on `mcs/mcs/TODO' for details
1060 // This function is based by a delegate to the FindMembers routine
1062 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1068 static bool IsAbstractMethod (MemberInfo m, object filter_criteria)
1070 MethodInfo mi = (MethodInfo) m;
1072 return mi.IsAbstract;
1075 // This filter is used by FindMembers, and we just keep
1076 // a global for the filter to `AlwaysAccept'
1078 static MemberFilter accepting_filter;
1081 // This delegate is a MemberFilter used to extract the
1082 // abstact methods from a type.
1084 static MemberFilter abstract_method_filter;
1086 static TypeContainer ()
1088 abstract_method_filter = new MemberFilter (IsAbstractMethod);
1089 accepting_filter = new MemberFilter (AlwaysAccept);
1093 // This method returns the members of this type just like Type.FindMembers would
1094 // Only, we need to use this for types which are _being_ defined because MS'
1095 // implementation can't take care of that.
1097 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf,
1098 MemberFilter filter, object criteria)
1100 ArrayList members = new ArrayList ();
1103 filter = accepting_filter;
1105 if ((mt & MemberTypes.Field) != 0 && Fields != null) {
1106 foreach (Field f in Fields) {
1107 if (filter (f.FieldBuilder, criteria) == true)
1108 members.Add (f.FieldBuilder);
1112 if ((mt & MemberTypes.Method) != 0) {
1113 if (Methods != null){
1114 foreach (Method m in Methods) {
1115 MethodBuilder mb = m.MethodBuilder;
1117 if (filter (mb, criteria) == true)
1122 if (Operators != null){
1123 foreach (Operator o in Operators) {
1124 MethodBuilder ob = o.OperatorMethodBuilder;
1126 if (filter (ob, criteria) == true)
1132 // FIXME : This ain't right because EventBuilder is not a
1133 // MemberInfo. What do we do ?
1135 if ((mt & MemberTypes.Event) != 0 && Events != null) {
1136 //foreach (Event e in Events) {
1137 // if (filter (e.EventBuilder, criteria) == true)
1138 // mi [i++] = e.EventBuilder;
1142 if ((mt & MemberTypes.Property) != 0){
1143 if (Properties != null)
1144 foreach (Property p in Properties) {
1145 if (filter (p.PropertyBuilder, criteria) == true)
1146 members.Add (p.PropertyBuilder);
1149 if (Indexers != null)
1150 foreach (Indexer ix in Indexers){
1151 if (filter (ix.PropertyBuilder, criteria) == true)
1152 members.Add (ix.PropertyBuilder);
1156 if ((mt & MemberTypes.NestedType) != 0 && Types != null) {
1157 foreach (TypeContainer t in Types) {
1158 if (filter (t.TypeBuilder, criteria) == true)
1159 members.Add (t.TypeBuilder);
1163 if ((mt & MemberTypes.Constructor) != 0){
1164 if (Constructors != null){
1165 foreach (Constructor c in Constructors){
1166 ConstructorBuilder cb = c.ConstructorBuilder;
1168 if (filter (cb, criteria) == true)
1175 // Lookup members in parent if requested.
1177 if ((bf & BindingFlags.DeclaredOnly) == 0){
1180 mi = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1182 members.AddRange (mi);
1185 int count = members.Count;
1187 MemberInfo [] mi = new MemberInfo [count];
1188 members.CopyTo (mi);
1195 public static MemberInfo [] FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1196 MemberFilter filter, object criteria)
1198 TypeContainer tc = TypeManager.LookupTypeContainer (t);
1201 return tc.FindMembers (mt, bf, filter, criteria);
1203 return t.FindMembers (mt, bf, filter, criteria);
1207 Hashtable pending_implementations;
1210 // Requires that the methods in `mi' be implemented for this
1213 public void RequireMethods (MethodInfo [] mi, object data)
1215 if (pending_implementations == null)
1216 pending_implementations = new Hashtable ();
1218 foreach (MethodInfo m in mi){
1219 Type [] types = TypeManager.GetArgumentTypes (m);
1221 pending_implementations.Add (
1223 (m.Name, m.ReturnType, types), data);
1228 // Used to set the list of interfaces that this typecontainer
1233 // For each element exposed by the type, we create a MethodSignature
1234 // struct that we will label as `implemented' as we define the various
1237 public void SetRequiredInterfaces (Type [] ifaces)
1239 foreach (Type t in ifaces){
1242 if (t is TypeBuilder){
1243 Interface iface = RootContext.TypeManager.LookupInterface (t);
1245 mi = iface.GetMethods ();
1247 mi = t.GetMethods ();
1249 RequireMethods (mi, t);
1254 // If a method with name `Name', return type `ret_type' and
1255 // arguments `args' implements an interface, this method will
1258 // This will remove the method from the list of "pending" methods
1259 // that are required to be implemented for this class as a side effect.
1262 public bool IsInterfaceMethod (string Name, Type ret_type, Type [] args)
1264 MethodSignature query;
1266 if (pending_implementations == null)
1269 query = new MethodSignature (Name, ret_type, args);
1271 if (pending_implementations.Contains (query)){
1272 pending_implementations.Remove (query);
1280 // Verifies that any pending abstract methods or interface methods
1281 // were implemented.
1283 void VerifyPendingMethods ()
1287 foreach (object m in pending_implementations){
1288 DictionaryEntry de = (DictionaryEntry) m;
1289 Type t = (Type) de.Value;
1292 MethodSignature method = (MethodSignature) de.Key;
1297 "`" + Name + "' does not implement interface member `" +
1298 t.FullName + "." + method.Name + "'");
1302 "`" + Name + "' does not implement inherited abstract " +
1303 "member `" + t.FullName + "." + method.Name + "'");
1308 // Emits the code, this step is performed after all
1309 // the types, enumerations, constructors
1313 if (Constructors != null)
1314 foreach (Constructor c in Constructors)
1317 if (methods != null)
1318 foreach (Method m in methods)
1321 if (operators != null)
1322 foreach (Operator o in operators)
1325 if (properties != null)
1326 foreach (Property p in properties)
1329 if (indexers != null)
1330 foreach (Indexer ix in indexers)
1333 if (pending_implementations != null)
1334 VerifyPendingMethods ();
1336 if (OptAttributes != null) {
1337 if (OptAttributes.AttributeSections != null) {
1338 foreach (AttributeSection asec in OptAttributes.AttributeSections) {
1339 if (asec.Attributes != null) {
1340 foreach (Attribute a in asec.Attributes) {
1341 EmitContext ec = new EmitContext (this, null,
1342 null, ModFlags, false);
1344 CustomAttributeBuilder cb = a.Resolve (ec);
1346 TypeBuilder.SetCustomAttribute (cb);
1354 foreach (TypeContainer tc in types)
1358 public void CloseType ()
1361 TypeBuilder.CreateType ();
1362 } catch (InvalidOperationException e){
1363 Console.WriteLine ("Exception while creating class: " + TypeBuilder.Name);
1364 Console.WriteLine ("Message:" + e.Message);
1367 foreach (TypeContainer tc in Types)
1370 if (Delegates != null)
1371 foreach (Delegate d in Delegates)
1375 string MakeName (string n)
1377 return "`" + Name + "." + n + "'";
1380 public static int CheckMember (string name, MemberInfo mi, int ModFlags)
1386 public class Class : TypeContainer {
1388 // Modifiers allowed in a class declaration
1390 public const int AllowedModifiers =
1393 Modifiers.PROTECTED |
1394 Modifiers.INTERNAL |
1396 Modifiers.ABSTRACT |
1399 public Class (RootContext rc, TypeContainer parent, string name, int mod,
1400 Attributes attrs, Location l)
1401 : base (rc, parent, name, l)
1405 if (parent.Parent == null)
1406 accmods = Modifiers.INTERNAL;
1408 accmods = Modifiers.PRIVATE;
1410 this.mod_flags = Modifiers.Check (AllowedModifiers, mod, accmods);
1411 this.attributes = attrs;
1415 // FIXME: How do we deal with the user specifying a different
1418 public override TypeAttributes TypeAttr {
1420 return base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
1425 public class Struct : TypeContainer {
1427 // Modifiers allowed in a struct declaration
1429 public const int AllowedModifiers =
1432 Modifiers.PROTECTED |
1433 Modifiers.INTERNAL |
1436 public Struct (RootContext rc, TypeContainer parent, string name, int mod,
1437 Attributes attrs, Location l)
1438 : base (rc, parent, name, l)
1442 if (parent.Parent == null)
1443 accmods = Modifiers.INTERNAL;
1445 accmods = Modifiers.PRIVATE;
1447 this.mod_flags = Modifiers.Check (AllowedModifiers, mod, accmods);
1449 this.mod_flags |= Modifiers.SEALED;
1450 this.attributes = attrs;
1455 // FIXME: Allow the user to specify a different set of attributes
1456 // in some cases (Sealed for example is mandatory for a class,
1457 // but what SequentialLayout can be changed
1459 public override TypeAttributes TypeAttr {
1461 return base.TypeAttr |
1462 TypeAttributes.SequentialLayout |
1463 TypeAttributes.Sealed |
1464 TypeAttributes.BeforeFieldInit;
1469 public class MethodCore {
1470 public readonly Parameters Parameters;
1471 public readonly string Name;
1472 public int ModFlags;
1474 public readonly Location Location;
1477 // Parameters, cached for semantic analysis.
1479 InternalParameters parameter_info;
1481 public MethodCore (string name, Parameters parameters, Location l)
1484 Parameters = parameters;
1489 // Returns the System.Type array for the parameters of this method
1491 Type [] parameter_types;
1492 public Type [] ParameterTypes (TypeContainer parent)
1494 if (Parameters == null)
1497 if (parameter_types == null)
1498 parameter_types = Parameters.GetParameterInfo (parent);
1500 return parameter_types;
1503 public InternalParameters ParameterInfo
1506 return parameter_info;
1510 parameter_info = value;
1514 public Block Block {
1524 public CallingConventions GetCallingConvention (bool is_class)
1526 CallingConventions cc = 0;
1528 cc = Parameters.GetCallingConvention ();
1531 if ((ModFlags & Modifiers.STATIC) == 0)
1532 cc |= CallingConventions.HasThis;
1534 // FIXME: How is `ExplicitThis' used in C#?
1540 public class Method : MethodCore {
1541 public readonly string ReturnType;
1542 public MethodBuilder MethodBuilder;
1543 public readonly Attributes OptAttributes;
1546 // Modifiers allowed in a class declaration
1548 const int AllowedModifiers =
1551 Modifiers.PROTECTED |
1552 Modifiers.INTERNAL |
1557 Modifiers.OVERRIDE |
1558 Modifiers.ABSTRACT |
1561 // return_type can be "null" for VOID values.
1562 public Method (string return_type, int mod, string name, Parameters parameters,
1563 Attributes attrs, Location l)
1564 : base (name, parameters, l)
1566 ReturnType = return_type;
1567 ModFlags = Modifiers.Check (AllowedModifiers, mod, Modifiers.PRIVATE);
1568 OptAttributes = attrs;
1571 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
1575 if (! (m is MethodInfo))
1578 MethodSignature sig = (MethodSignature) filter_criteria;
1580 if (m.Name != sig.Name)
1583 mi = (MethodInfo) m;
1585 if (mi.ReturnType != sig.RetType)
1588 Type [] args = TypeManager.GetArgumentTypes (mi);
1589 Type [] sigp = sig.Parameters;
1592 // FIXME: remove this assumption if we manage to
1593 // not enter a null as a the Parameters in TypeManager's
1594 // MethodBase to Type argument mapper.
1601 } else if (sigp == null)
1604 if (args.Length != sigp.Length)
1607 for (int i = args.Length; i > 0; ){
1609 if (args [i] != sigp [i])
1616 // This delegate is used to extract methods which have the
1617 // same signature as the argument
1619 static MemberFilter method_signature_filter;
1623 method_signature_filter = new MemberFilter (MemberSignatureCompare);
1627 // Returns the `System.Type' for the ReturnType of this
1628 // function. Provides a nice cache. (used between semantic analysis
1629 // and actual code generation
1631 Type type_return_type;
1632 public Type GetReturnType (TypeContainer parent)
1634 if (type_return_type == null)
1635 type_return_type = parent.LookupType (ReturnType, false);
1637 return type_return_type;
1640 void WarningNotHiding (TypeContainer parent)
1644 "The member `" + parent.Name + "." + Name + "' does not hide an " +
1645 "inherited member. The keyword new is not required");
1649 string MakeName (TypeContainer parent)
1651 return "`" + parent.Name + "." + Name + "'";
1654 string MethodBaseName (MethodBase mb)
1656 return "`" + mb.ReflectedType.Name + "." + mb.Name + "'";
1659 bool CheckMethod (TypeContainer parent, MemberInfo [] mi)
1661 MethodInfo mb = (MethodInfo) mi [0];
1663 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
1665 108, Location, "The keyword new is required on " +
1666 MakeName (parent) + " because it hides `" +
1667 mb.ReflectedType.Name + "." +
1671 if (mb.IsVirtual || mb.IsAbstract){
1672 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
1674 114, Location, MakeName (parent) +
1675 "hides inherited member " + MethodBaseName (mb) +
1676 ". To make the current member override that " +
1677 "implementation, add the override keyword, " +
1678 "otherwise use the new keyword");
1689 public MethodBuilder Define (TypeContainer parent)
1691 Type ret_type = GetReturnType (parent);
1692 Type [] parameters = ParameterTypes (parent);
1693 MethodAttributes flags;
1697 // Verify if the parent has a type with the same name, and then
1698 // check whether we have to create a new slot for it or not.
1700 Type ptype = parent.TypeBuilder.BaseType;
1702 // ptype is only null for System.Object while compiling corlib.
1704 MethodSignature ms = new MethodSignature (Name, ret_type, parameters);
1707 mi = TypeContainer.FindMembers (
1708 ptype, MemberTypes.Method,
1709 BindingFlags.Public, method_signature_filter,
1712 if (mi != null && mi.Length > 0){
1713 CheckMethod (parent, mi);
1715 if ((ModFlags & Modifiers.NEW) != 0)
1716 WarningNotHiding (parent);
1718 if ((ModFlags & Modifiers.OVERRIDE) != 0)
1719 Report.Error (115, Location,
1721 " no suitable methods found to override");
1723 } else if ((ModFlags & Modifiers.NEW) != 0)
1724 WarningNotHiding (parent);
1727 // If we implement an interface, then set the proper flags.
1729 flags = Modifiers.MethodAttr (ModFlags);
1731 if (parent.IsInterfaceMethod (Name, ret_type, parameters))
1732 flags |= MethodAttributes.Virtual | MethodAttributes.Final |
1733 MethodAttributes.NewSlot | MethodAttributes.HideBySig;
1736 // Catch invalid uses of virtual and abtract modifiers
1738 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1739 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1740 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1742 if ((ModFlags & va) == va){
1743 if ((ModFlags & va) == va){
1745 503, Location, "The abstract method " +
1746 MakeName (parent) + "can not be marked virtual");
1751 if ((ModFlags & Modifiers.ABSTRACT) != 0){
1752 if ((parent.ModFlags & Modifiers.ABSTRACT) == 0){
1754 513, Location, MakeName (parent) +
1755 " is abstract but its container class is not");
1760 if ((ModFlags & va) != 0 && ((ModFlags & Modifiers.PRIVATE) != 0)){
1762 621, Location, MakeName (parent) +
1763 " virtual or abstract members can not be private");
1767 if ((ModFlags & Modifiers.STATIC) != 0){
1768 if ((ModFlags & vao) != 0){
1770 112, Location, "static method " + MakeName (parent) +
1771 " can not be marked as virtual, abstract or override");
1777 if ((ModFlags & Modifiers.OVERRIDE) != 0 && ((ModFlags & nv) != 0)){
1779 113, Location, MakeName (parent) +
1780 "marked as override cannot be marked as new or virtual");
1788 // Finally, define the method
1791 MethodBuilder = parent.TypeBuilder.DefineMethod (
1793 GetCallingConvention (parent is Class),
1794 ret_type, parameters);
1797 // HACK because System.Reflection.Emit is lame
1799 if (!TypeManager.RegisterMethod (MethodBuilder, parameters)) {
1800 Report.Error (111, Location,
1801 "Class `" + parent.Name + "' already contains a definition with the " +
1802 "same return value and parameter types for method `" + Name + "'");
1806 ParameterInfo = new InternalParameters (parent, Parameters);
1809 // This is used to track the Entry Point,
1811 // FIXME: Allow pluggable entry point, check arguments, etc.
1813 if (Name == "Main"){
1814 if ((ModFlags & Modifiers.STATIC) != 0){
1815 parent.RootContext.EntryPoint = MethodBuilder;
1820 // Define each type attribute (in/out/ref) and
1821 // the argument names.
1823 Parameter [] p = Parameters.FixedParameters;
1827 for (i = 0; i < p.Length; i++)
1828 MethodBuilder.DefineParameter (
1829 i + 1, p [i].Attributes, p [i].Name);
1831 if (i != parameters.Length) {
1832 Parameter array_param = Parameters.ArrayParameter;
1833 MethodBuilder.DefineParameter (i + 1, array_param.Attributes,
1838 return MethodBuilder;
1844 public void Emit (TypeContainer parent)
1846 ILGenerator ig = MethodBuilder.GetILGenerator ();
1847 EmitContext ec = new EmitContext (parent, ig, GetReturnType (parent), ModFlags);
1849 if (OptAttributes != null) {
1850 if (OptAttributes.AttributeSections != null) {
1851 foreach (AttributeSection asec in OptAttributes.AttributeSections) {
1852 if (asec.Attributes != null) {
1853 foreach (Attribute a in asec.Attributes) {
1854 CustomAttributeBuilder cb = a.Resolve (ec);
1856 MethodBuilder.SetCustomAttribute (cb);
1863 ec.EmitTopBlock (Block);
1867 public abstract class ConstructorInitializer {
1868 ArrayList argument_list;
1869 ConstructorInfo parent_constructor;
1872 public ConstructorInitializer (ArrayList argument_list, Location location)
1874 this.argument_list = argument_list;
1875 this.location = location;
1878 public ArrayList Arguments {
1880 return argument_list;
1884 public bool Resolve (EmitContext ec)
1886 Expression parent_constructor_group;
1888 if (argument_list != null){
1889 for (int i = argument_list.Count; i > 0; ){
1892 Argument a = (Argument) argument_list [i];
1893 if (!a.Resolve (ec))
1898 parent_constructor_group = Expression.MemberLookup (
1900 ec.TypeContainer.TypeBuilder.BaseType, ".ctor", true,
1901 MemberTypes.Constructor,
1902 BindingFlags.Public | BindingFlags.Instance, location);
1904 if (parent_constructor_group == null){
1905 Console.WriteLine ("Could not find a constructor in our parent");
1909 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (ec,
1910 (MethodGroupExpr) parent_constructor_group, argument_list, location);
1912 if (parent_constructor == null)
1918 public void Emit (EmitContext ec)
1920 ec.ig.Emit (OpCodes.Ldarg_0);
1921 if (argument_list != null)
1922 Invocation.EmitArguments (ec, argument_list);
1923 ec.ig.Emit (OpCodes.Call, parent_constructor);
1927 public class ConstructorBaseInitializer : ConstructorInitializer {
1928 public ConstructorBaseInitializer (ArrayList argument_list, Location l) : base (argument_list, l)
1933 public class ConstructorThisInitializer : ConstructorInitializer {
1934 public ConstructorThisInitializer (ArrayList argument_list, Location l) : base (argument_list, l)
1939 public class Constructor : MethodCore {
1940 public ConstructorBuilder ConstructorBuilder;
1941 public ConstructorInitializer Initializer;
1942 public Attributes OptAttributes;
1945 // Modifiers allowed for a constructor.
1947 const int AllowedModifiers =
1949 Modifiers.PROTECTED |
1950 Modifiers.INTERNAL |
1955 // The spec claims that static is not permitted, but
1956 // my very own code has static constructors.
1958 public Constructor (string name, Parameters args, ConstructorInitializer init, Location l)
1959 : base (name, args, l)
1965 // Returns true if this is a default constructor
1967 public bool IsDefault ()
1969 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
1970 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
1971 (Initializer is ConstructorBaseInitializer) &&
1972 (Initializer.Arguments == null);
1976 // Creates the ConstructorBuilder
1978 public ConstructorBuilder Define (TypeContainer parent)
1980 MethodAttributes ca = (MethodAttributes.RTSpecialName |
1981 MethodAttributes.SpecialName);
1983 Type [] parameters = ParameterTypes (parent);
1985 if ((ModFlags & Modifiers.STATIC) != 0)
1986 ca |= MethodAttributes.Static;
1988 if (parent is Struct && parameters == null){
1991 "Structs can not contain explicit parameterless " +
1997 ConstructorBuilder = parent.TypeBuilder.DefineConstructor (
1998 ca, GetCallingConvention (parent is Class),
2001 // HACK because System.Reflection.Emit is lame
2003 if (!TypeManager.RegisterMethod (ConstructorBuilder, parameters)) {
2004 Report.Error (111, Location,
2005 "Class `" + parent.Name + "' already contains a definition with the " +
2006 "same return value and parameter types for constructor `" + Name + "'");
2011 ParameterInfo = new InternalParameters (parent, Parameters);
2013 return ConstructorBuilder;
2019 public void Emit (TypeContainer parent)
2021 ILGenerator ig = ConstructorBuilder.GetILGenerator ();
2022 EmitContext ec = new EmitContext (parent, ig, null, ModFlags, true);
2024 if (parent is Class){
2025 if (Initializer == null)
2026 Initializer = new ConstructorBaseInitializer (null, parent.Location);
2028 if (!Initializer.Resolve (ec))
2033 // Classes can have base initializers and instance field initializers.
2035 if (parent is Class){
2036 if ((ModFlags & Modifiers.STATIC) == 0)
2037 Initializer.Emit (ec);
2038 parent.EmitFieldInitializers (ec, false);
2041 if ((ModFlags & Modifiers.STATIC) != 0)
2042 parent.EmitFieldInitializers (ec, true);
2044 if (OptAttributes != null) {
2045 if (OptAttributes.AttributeSections != null) {
2046 foreach (AttributeSection asec in OptAttributes.AttributeSections) {
2047 if (asec.Attributes != null) {
2048 foreach (Attribute a in asec.Attributes) {
2049 CustomAttributeBuilder cb = a.Resolve (ec);
2051 ConstructorBuilder.SetCustomAttribute (cb);
2058 ec.EmitTopBlock (Block);
2062 public class Field {
2063 public readonly string Type;
2064 public readonly Object Initializer;
2065 public readonly string Name;
2066 public readonly int ModFlags;
2067 public readonly Attributes OptAttributes;
2068 public FieldBuilder FieldBuilder;
2072 // Modifiers allowed in a class declaration
2074 const int AllowedModifiers =
2077 Modifiers.PROTECTED |
2078 Modifiers.INTERNAL |
2083 public Field (string type, int mod, string name, Object expr_or_array_init, Attributes attrs)
2086 ModFlags = Modifiers.Check (AllowedModifiers, mod, Modifiers.PRIVATE);
2088 Initializer = expr_or_array_init;
2089 OptAttributes = attrs;
2092 public void Define (TypeContainer parent)
2094 Type t = parent.LookupType (Type, false);
2099 FieldBuilder = parent.TypeBuilder.DefineField (
2100 Name, t, Modifiers.FieldAttr (ModFlags));
2104 public class Property {
2106 public readonly string Type;
2107 public readonly string Name;
2108 public readonly int ModFlags;
2109 public Block Get, Set;
2110 public PropertyBuilder PropertyBuilder;
2111 public Attributes OptAttributes;
2112 MethodBuilder GetBuilder, SetBuilder;
2117 // The type, once we compute it.
2121 const int AllowedModifiers =
2124 Modifiers.PROTECTED |
2125 Modifiers.INTERNAL |
2129 Modifiers.OVERRIDE |
2130 Modifiers.ABSTRACT |
2133 public Property (string type, string name, int mod_flags, Block get_block, Block set_block,
2134 Attributes attrs, Location loc)
2138 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PRIVATE);
2141 OptAttributes = attrs;
2145 public void Define (TypeContainer parent)
2148 MethodAttributes method_attr = Modifiers.MethodAttr(ModFlags);
2150 // FIXME - PropertyAttributes.HasDefault ?
2152 PropertyAttributes prop_attr = PropertyAttributes.RTSpecialName |
2153 PropertyAttributes.SpecialName;
2156 PropertyType = parent.LookupType (Type, false);
2157 Type [] parameters = new Type [1];
2158 parameters [0] = PropertyType;
2160 PropertyBuilder = parent.TypeBuilder.DefineProperty (
2161 Name, prop_attr, PropertyType, null);
2165 GetBuilder = parent.TypeBuilder.DefineMethod (
2166 "get_" + Name, method_attr, PropertyType, null);
2167 PropertyBuilder.SetGetMethod (GetBuilder);
2169 // HACK because System.Reflection.Emit is lame
2171 if (!TypeManager.RegisterMethod (GetBuilder, null)) {
2172 Report.Error (111, Location,
2173 "Class `" + parent.Name + "' already contains a definition with the " +
2174 "same return value and parameter types as the " +
2175 "'get' method of property `" + Name + "'");
2184 SetBuilder = parent.TypeBuilder.DefineMethod (
2185 "set_" + Name, method_attr, null, parameters);
2186 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
2187 PropertyBuilder.SetSetMethod (SetBuilder);
2189 // HACK because System.Reflection.Emit is lame
2191 if (!TypeManager.RegisterMethod (SetBuilder, parameters)) {
2192 Report.Error (111, Location,
2193 "Class `" + parent.Name + "' already contains a definition with the " +
2194 "same return value and parameter types as the " +
2195 "'set' method of property `" + Name + "'");
2200 // HACK for the reasons exposed above
2202 if (!TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder)) {
2203 Report.Error (111, Location,
2204 "Class `" + parent.Name + "' already contains a definition for the " +
2205 " property `" + Name + "'");
2213 public void Emit (TypeContainer tc)
2219 ig = GetBuilder.GetILGenerator ();
2220 ec = new EmitContext (tc, ig, PropertyType, ModFlags);
2222 ec.EmitTopBlock (Get);
2226 ig = SetBuilder.GetILGenerator ();
2227 ec = new EmitContext (tc, ig, null, ModFlags);
2229 ec.EmitTopBlock (Set);
2234 public class Event {
2236 const int AllowedModifiers =
2239 Modifiers.PROTECTED |
2240 Modifiers.INTERNAL |
2245 Modifiers.OVERRIDE |
2248 public readonly string Type;
2249 public readonly string Name;
2250 public readonly Object Initializer;
2251 public readonly int ModFlags;
2252 public readonly Block Add;
2253 public readonly Block Remove;
2254 public EventBuilder EventBuilder;
2255 public Attributes OptAttributes;
2259 public Event (string type, string name, Object init, int flags, Block add_block, Block rem_block,
2260 Attributes attrs, Location loc)
2265 ModFlags = Modifiers.Check (AllowedModifiers, flags, Modifiers.PRIVATE);
2268 OptAttributes = attrs;
2272 public void Define (TypeContainer parent)
2274 MethodAttributes m_attr = Modifiers.MethodAttr (ModFlags);
2276 EventAttributes e_attr = EventAttributes.RTSpecialName | EventAttributes.SpecialName;
2280 Type t = parent.LookupType (Type, false);
2281 Type [] parameters = new Type [1];
2284 EventBuilder = parent.TypeBuilder.DefineEvent (Name, e_attr, t);
2287 mb = parent.TypeBuilder.DefineMethod ("add_" + Name, m_attr, null,
2289 mb.DefineParameter (1, ParameterAttributes.None, "value");
2290 EventBuilder.SetAddOnMethod (mb);
2292 // HACK because System.Reflection.Emit is lame
2294 if (!TypeManager.RegisterMethod (mb, parameters)) {
2295 Report.Error (111, Location,
2296 "Class `" + parent.Name + "' already contains a definition with the " +
2297 "same return value and parameter types for the " +
2298 "'add' method of event `" + Name + "'");
2303 if (Remove != null) {
2304 mb = parent.TypeBuilder.DefineMethod ("remove_" + Name, m_attr, null,
2306 mb.DefineParameter (1, ParameterAttributes.None, "value");
2307 EventBuilder.SetRemoveOnMethod (mb);
2310 // HACK because System.Reflection.Emit is lame
2312 if (!TypeManager.RegisterMethod (mb, parameters)) {
2313 Report.Error (111, Location,
2314 "Class `" + parent.Name + "' already contains a definition with the " +
2315 "same return value and parameter types for the " +
2316 "'remove' method of event `" + Name + "'");
2325 // FIXME: This does not handle:
2327 // int INTERFACENAME [ args ]
2331 // int this [ args ]
2333 public class Indexer {
2335 const int AllowedModifiers =
2338 Modifiers.PROTECTED |
2339 Modifiers.INTERNAL |
2343 Modifiers.OVERRIDE |
2346 public readonly string Type;
2347 public readonly string InterfaceType;
2348 public readonly Parameters FormalParameters;
2349 public readonly int ModFlags;
2350 public readonly Block Get;
2351 public readonly Block Set;
2352 public Attributes OptAttributes;
2353 public MethodBuilder GetBuilder;
2354 public MethodBuilder SetBuilder;
2355 public PropertyBuilder PropertyBuilder;
2356 public Type IndexerType;
2360 public Indexer (string type, string int_type, int flags, Parameters parms,
2361 Block get_block, Block set_block, Attributes attrs, Location loc)
2365 InterfaceType = int_type;
2366 ModFlags = Modifiers.Check (AllowedModifiers, flags, Modifiers.PRIVATE);
2367 FormalParameters = parms;
2370 OptAttributes = attrs;
2374 public void Define (TypeContainer parent)
2376 MethodAttributes attr = Modifiers.MethodAttr (ModFlags);
2377 PropertyAttributes prop_attr =
2378 PropertyAttributes.RTSpecialName |
2379 PropertyAttributes.SpecialName;
2381 IndexerType = parent.LookupType (Type, false);
2382 Type [] parameters = FormalParameters.GetParameterInfo (parent);
2384 PropertyBuilder = parent.TypeBuilder.DefineProperty (
2385 TypeManager.IndexerPropertyName (parent.TypeBuilder),
2386 prop_attr, IndexerType, parameters);
2389 GetBuilder = parent.TypeBuilder.DefineMethod (
2390 "get_Item", attr, IndexerType, parameters);
2392 if (!TypeManager.RegisterMethod (GetBuilder, parameters)) {
2393 Report.Error (111, Location,
2394 "Class `" + parent.Name + "' already contains a definition with the " +
2395 "same return value and parameter types for the " +
2400 TypeContainer.RegisterParameterForBuilder (
2401 GetBuilder, new InternalParameters (parent, FormalParameters));
2405 int top = parameters.Length;
2406 Type [] set_pars = new Type [top + 1];
2407 parameters.CopyTo (set_pars, 0);
2408 set_pars [top] = IndexerType;
2410 Parameter [] fixed_parms = FormalParameters.FixedParameters;
2412 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
2414 fixed_parms.CopyTo (tmp, 0);
2415 tmp [fixed_parms.Length] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
2417 Parameters set_formal_params = new Parameters (tmp, null);
2419 SetBuilder = parent.TypeBuilder.DefineMethod (
2420 "set_Item", attr, null, set_pars);
2422 if (!TypeManager.RegisterMethod (SetBuilder, set_pars)) {
2423 Report.Error (111, Location,
2424 "Class `" + parent.Name + "' already contains a definition with the " +
2425 "same return value and parameter types for the " +
2430 TypeContainer.RegisterParameterForBuilder (
2431 SetBuilder, new InternalParameters (parent, set_formal_params));
2434 PropertyBuilder.SetGetMethod (GetBuilder);
2435 PropertyBuilder.SetSetMethod (SetBuilder);
2437 Parameter [] p = FormalParameters.FixedParameters;
2442 for (i = 0; i < p.Length; ++i) {
2444 GetBuilder.DefineParameter (
2445 i + 1, p [i].Attributes, p [i].Name);
2448 SetBuilder.DefineParameter (
2449 i + 1, p [i].Attributes, p [i].Name);
2453 SetBuilder.DefineParameter (
2454 i + 1, ParameterAttributes.None, "value");
2456 if (i != parameters.Length) {
2457 Parameter array_param = FormalParameters.ArrayParameter;
2458 SetBuilder.DefineParameter (i + 1, array_param.Attributes,
2463 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
2466 public void Emit (TypeContainer tc)
2472 ig = GetBuilder.GetILGenerator ();
2473 ec = new EmitContext (tc, ig, IndexerType, ModFlags);
2475 ec.EmitTopBlock (Get);
2479 ig = SetBuilder.GetILGenerator ();
2480 ec = new EmitContext (tc, ig, null, ModFlags);
2482 ec.EmitTopBlock (Set);
2487 public class Operator {
2489 const int AllowedModifiers =
2493 const int RequiredModifiers =
2497 public enum OpType {
2507 // Unary and Binary operators
2530 // Implicit and Explicit
2535 public readonly OpType OperatorType;
2536 public readonly string ReturnType;
2537 public readonly string FirstArgType;
2538 public readonly string FirstArgName;
2539 public readonly string SecondArgType;
2540 public readonly string SecondArgName;
2541 public readonly int ModFlags;
2542 public readonly Block Block;
2543 public Attributes OptAttributes;
2544 public MethodBuilder OperatorMethodBuilder;
2545 public Location Location;
2547 public string MethodName;
2548 public Method OperatorMethod;
2550 public Operator (OpType type, string ret_type, int flags, string arg1type, string arg1name,
2551 string arg2type, string arg2name, Block block, Attributes attrs, Location loc)
2553 OperatorType = type;
2554 ReturnType = ret_type;
2555 ModFlags = Modifiers.Check (AllowedModifiers, flags, Modifiers.PUBLIC);
2556 FirstArgType = arg1type;
2557 FirstArgName = arg1name;
2558 SecondArgType = arg2type;
2559 SecondArgName = arg2name;
2561 OptAttributes = attrs;
2565 string Prototype (TypeContainer parent)
2567 return parent.Name + ".operator " + OperatorType + " (" + FirstArgType + "," +
2568 SecondArgType + ")";
2571 public void Define (TypeContainer parent)
2574 MethodName = "op_" + OperatorType;
2576 if (SecondArgType != null)
2579 Parameter [] param_list = new Parameter [length];
2581 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2584 "User defined operators `" +
2585 Prototype (parent) +
2586 "' must be declared static and public");
2589 param_list[0] = new Parameter (FirstArgType, FirstArgName,
2590 Parameter.Modifier.NONE, null);
2591 if (SecondArgType != null)
2592 param_list[1] = new Parameter (SecondArgType, SecondArgName,
2593 Parameter.Modifier.NONE, null);
2595 OperatorMethod = new Method (ReturnType, ModFlags, MethodName,
2596 new Parameters (param_list, null),
2597 OptAttributes, Location.Null);
2599 OperatorMethod.Define (parent);
2600 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
2602 Type [] param_types = OperatorMethod.ParameterTypes (parent);
2603 Type declaring_type = OperatorMethodBuilder.DeclaringType;
2604 Type return_type = OperatorMethod.GetReturnType (parent);
2605 Type first_arg_type = param_types [0];
2607 // Rules for conversion operators
2609 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2611 if (first_arg_type == return_type && first_arg_type == declaring_type)
2612 Report.Error (555, Location,
2613 "User-defined conversion cannot take an object of the enclosing type " +
2614 "and convert to an object of the enclosing type");
2616 if (first_arg_type != declaring_type && return_type != declaring_type)
2617 Report.Error (556, Location,
2618 "User-defined conversion must convert to or from the enclosing type");
2620 if (first_arg_type == TypeManager.object_type || return_type == TypeManager.object_type)
2621 Report.Error (-8, Location,
2622 "User-defined conversion cannot convert to or from object type");
2624 if (first_arg_type.IsInterface || return_type.IsInterface)
2625 Report.Error (-9, Location,
2626 "User-defined conversion cannot convert to or from an interface type");
2628 if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type))
2629 Report.Error (-10, Location,
2630 "User-defined conversion cannot convert between types that " +
2631 "derive from each other");
2633 } else if (SecondArgType == null) {
2634 // Checks for Unary operators
2636 if (first_arg_type != declaring_type)
2637 Report.Error (562, Location,
2638 "The parameter of a unary operator must be the containing type");
2641 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2642 if (return_type != declaring_type)
2643 Report.Error (559, Location,
2644 "The parameter and return type for ++ and -- " +
2645 "must be the containing type");
2649 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2650 if (return_type != TypeManager.bool_type)
2651 Report.Error (215, Location,
2652 "The return type of operator True or False " +
2657 // Checks for Binary operators
2659 if (first_arg_type != declaring_type &&
2660 param_types [1] != declaring_type)
2661 Report.Error (563, Location,
2662 "One of the parameters of a binary operator must be the containing type");
2669 public void Emit (TypeContainer parent)
2671 OperatorMethod.Block = Block;
2672 OperatorMethod.Emit (parent);
2679 // This is used to compare method signatures
2681 struct MethodSignature {
2683 public Type RetType;
2684 public Type [] Parameters;
2686 public MethodSignature (string name, Type ret_type, Type [] parameters)
2690 Parameters = parameters;
2692 if (parameters != null){
2693 if (parameters.Length == 0)
2698 public override int GetHashCode ()
2700 return Name.GetHashCode ();
2703 public override bool Equals (Object o)
2705 MethodSignature other = (MethodSignature) o;
2707 if (other.Name != Name)
2710 if (other.RetType != RetType)
2713 if (Parameters == null){
2714 if (other.Parameters == null)
2719 if (other.Parameters == null)
2722 int c = Parameters.Length;
2723 if (other.Parameters.Length != c)
2726 for (int i = 0; i < c; i++)
2727 if (other.Parameters [i] != Parameters [i])