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_methods;
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 lookup the class on any of the `using'
665 for (Namespace ns = Namespace; ns != null; ns = ns.Parent){
666 ArrayList using_list = ns.UsingTable;
668 if (using_list == null)
671 foreach (string n in using_list){
672 t = LookupInterfaceOrClass (builder, n, name, is_class, out error);
681 Report.Error (246, "Can not find type `"+name+"'");
686 // This function computes the Base class and also the
687 // list of interfaces that the class or struct @c implements.
689 // The return value is an array (might be null) of
690 // interfaces implemented (as Types).
692 // The @parent argument is set to the parent object or null
693 // if this is `System.Object'.
695 Type [] GetClassBases (object builder, bool is_class, out Type parent, out bool error)
697 ArrayList bases = Bases;
706 parent = TypeManager.value_type;
710 if (RootContext.StdLib)
711 parent = TypeManager.object_type;
712 else if (Name != "System.Object")
713 parent = TypeManager.object_type;
716 // If we are compiling our runtime,
717 // and we are defining ValueType, then our
718 // parent is `System.Object'.
720 if (!RootContext.StdLib && Name == "System.ValueType")
721 parent = TypeManager.object_type;
728 // Bases should be null if there are no bases at all
733 string name = (string) bases [0];
734 Type first = GetInterfaceOrClass (builder, name, is_class);
745 parent = TypeManager.object_type;
752 Type [] ifaces = new Type [count-start];
754 for (i = start, j = 0; i < count; i++, j++){
755 string name = (string) bases [i];
756 Type t = GetInterfaceOrClass (builder, name, is_class);
763 if (is_class == false && !t.IsInterface){
764 Report.Error (527, "In Struct `" + Name + "', type `"+
765 name +"' is not an interface");
774 detail = " (a class can not inherit from a struct)";
776 Report.Error (509, "class `"+ Name +
777 "': Cannot inherit from sealed class `"+
778 bases [i]+"'"+detail);
785 Report.Error (527, "In Class `" + Name + "', type `"+
786 name+"' is not an interface");
799 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
801 public TypeBuilder DefineType (object parent_builder)
818 ifaces = GetClassBases (parent_builder, is_class, out parent, out error);
823 if (parent_builder is ModuleBuilder) {
824 ModuleBuilder builder = (ModuleBuilder) parent_builder;
827 // Structs with no fields need to have a ".size 1"
830 if (!is_class && Fields == null)
831 TypeBuilder = builder.DefineType (Name,
834 PackingSize.Unspecified, 1);
837 // classes or structs with fields
839 TypeBuilder = builder.DefineType (Name,
845 TypeBuilder builder = (TypeBuilder) parent_builder;
848 // Structs with no fields need to have a ".size 1"
851 if (!is_class && Fields == null)
852 TypeBuilder = builder.DefineNestedType (Name,
855 PackingSize.Unspecified);
858 // classes or structs with fields
860 TypeBuilder = builder.DefineNestedType (Name,
866 RootContext.TypeManager.AddUserType (Name, TypeBuilder, this);
869 foreach (TypeContainer tc in Types)
870 tc.DefineType (TypeBuilder);
873 if (Delegates != null) {
874 foreach (Delegate d in Delegates)
875 d.DefineDelegate (TypeBuilder);
883 // Populates our TypeBuilder with fields and methods
885 public void Populate ()
887 if (Constants != null){
888 foreach (Constant c in Constants)
889 c.EmitConstant (RootContext, this);
893 foreach (Field f in Fields)
897 if (this is Class && constructors == null){
898 if (default_constructor == null)
899 DefineDefaultConstructor (false);
901 if (initialized_static_fields != null &&
902 default_static_constructor == null)
903 DefineDefaultConstructor (true);
908 // Structs can not have initialized instance
911 if (initialized_static_fields != null &&
912 default_static_constructor == null)
913 DefineDefaultConstructor (true);
915 if (initialized_fields != null)
916 ReportStructInitializedInstanceError ();
919 RegisterRequiredImplementations ();
921 ArrayList remove_list = new ArrayList ();
923 if (constructors != null || methods != null ||
924 properties != null || operators != null){
925 if (method_builders_to_methods == null)
926 method_builders_to_methods = new Hashtable ();
929 if (constructors != null){
930 foreach (Constructor c in constructors){
931 MethodBase builder = c.Define (this);
936 method_builders_to_methods.Add (MakeKey (builder), c);
939 foreach (object o in remove_list)
940 constructors.Remove (o);
942 remove_list.Clear ();
945 if (Methods != null){
946 foreach (Method m in methods){
947 MethodBase key = m.Define (this);
951 // The following key is not enoug
952 // class x { public void X () {} }
953 // class y : x { public void X () {}}
959 method_builders_to_methods.Add (MakeKey (key), m);
961 foreach (object o in remove_list)
964 remove_list.Clear ();
967 if (Properties != null) {
968 foreach (Property p in Properties)
973 foreach (Enum e in Enums)
977 if (Events != null) {
978 foreach (Event e in Events)
982 if (Indexers != null) {
983 foreach (Indexer i in Indexers)
987 if (Operators != null) {
988 foreach (Operator o in Operators) {
991 method_builders_to_methods.Add (
992 MakeKey (o.OperatorMethodBuilder), o.OperatorMethod);
996 if (Delegates != null) {
997 foreach (Delegate d in Delegates)
1001 if (Types != null) {
1002 foreach (TypeContainer tc in Types)
1009 // the `mb' must be a MethodBuilder or a
1010 // ConstructorBuilder, we return the method that
1013 static public MethodCore LookupMethodByBuilder (MethodBase mb)
1015 return (MethodCore) method_builders_to_methods [MakeKey (mb)];
1018 public Type LookupType (string name, bool silent)
1020 return RootContext.LookupType (this, name, silent);
1023 public string LookupAlias (string Name)
1026 // Read the comments on `mcs/mcs/TODO' for details
1032 // This function is based by a delegate to the FindMembers routine
1034 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1040 static bool IsAbstractMethod (MemberInfo m, object filter_criteria)
1042 MethodInfo mi = (MethodInfo) m;
1044 return mi.IsAbstract;
1047 // This filter is used by FindMembers, and we just keep
1048 // a global for the filter to `AlwaysAccept'
1050 static MemberFilter accepting_filter;
1053 // This delegate is a MemberFilter used to extract the
1054 // abstact methods from a type.
1056 static MemberFilter abstract_method_filter;
1058 static TypeContainer ()
1060 abstract_method_filter = new MemberFilter (IsAbstractMethod);
1061 accepting_filter = new MemberFilter (AlwaysAccept);
1065 // This method returns the members of this type just like Type.FindMembers would
1066 // Only, we need to use this for types which are _being_ defined because MS'
1067 // implementation can't take care of that.
1069 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf,
1070 MemberFilter filter, object criteria)
1072 ArrayList members = new ArrayList ();
1075 filter = accepting_filter;
1077 if ((mt & MemberTypes.Field) != 0 && Fields != null) {
1078 foreach (Field f in Fields) {
1079 if (filter (f.FieldBuilder, criteria) == true)
1080 members.Add (f.FieldBuilder);
1084 if ((mt & MemberTypes.Method) != 0) {
1085 if (Methods != null){
1086 foreach (Method m in Methods) {
1087 MethodBuilder mb = m.MethodBuilder;
1089 if (filter (mb, criteria) == true)
1094 if (Operators != null){
1095 foreach (Operator o in Operators) {
1096 MethodBuilder ob = o.OperatorMethodBuilder;
1098 if (filter (ob, criteria) == true)
1104 // FIXME : This ain't right because EventBuilder is not a
1105 // MemberInfo. What do we do ?
1107 if ((mt & MemberTypes.Event) != 0 && Events != null) {
1108 //foreach (Event e in Events) {
1109 // if (filter (e.EventBuilder, criteria) == true)
1110 // mi [i++] = e.EventBuilder;
1114 if ((mt & MemberTypes.Property) != 0 && Properties != null) {
1115 foreach (Property p in Properties) {
1116 if (filter (p.PropertyBuilder, criteria) == true)
1117 members.Add (p.PropertyBuilder);
1121 if ((mt & MemberTypes.NestedType) != 0 && Types != null) {
1122 foreach (TypeContainer t in Types) {
1123 if (filter (t.TypeBuilder, criteria) == true)
1124 members.Add (t.TypeBuilder);
1128 if ((mt & MemberTypes.Constructor) != 0){
1129 if (Constructors != null){
1130 foreach (Constructor c in Constructors){
1131 ConstructorBuilder cb = c.ConstructorBuilder;
1133 if (filter (cb, criteria) == true)
1140 // Lookup members in parent if requested.
1142 if ((bf & BindingFlags.DeclaredOnly) == 0){
1145 mi = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1147 members.AddRange (mi);
1150 int count = members.Count;
1152 MemberInfo [] mi = new MemberInfo [count];
1153 members.CopyTo (mi);
1160 public static MemberInfo [] FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1161 MemberFilter filter, object criteria)
1163 TypeContainer tc = TypeManager.LookupTypeContainer (t);
1166 return tc.FindMembers (mt, bf, filter, criteria);
1168 return t.FindMembers (mt, bf, filter, criteria);
1172 Hashtable pending_implementations;
1175 // Requires that the methods in `mi' be implemented for this
1178 public void RequireMethods (MethodInfo [] mi, object data)
1180 if (pending_implementations == null)
1181 pending_implementations = new Hashtable ();
1183 foreach (MethodInfo m in mi){
1184 Type [] types = TypeManager.GetArgumentTypes (m);
1186 pending_implementations.Add (
1188 (m.Name, m.ReturnType, types), data);
1193 // Used to set the list of interfaces that this typecontainer
1198 // For each element exposed by the type, we create a MethodSignature
1199 // struct that we will label as `implemented' as we define the various
1202 public void SetRequiredInterfaces (Type [] ifaces)
1204 foreach (Type t in ifaces){
1207 if (t is TypeBuilder){
1208 Interface iface = RootContext.TypeManager.LookupInterface (t);
1210 mi = iface.GetMethods ();
1212 mi = t.GetMethods ();
1214 RequireMethods (mi, t);
1219 // If a method with name `Name', return type `ret_type' and
1220 // arguments `args' implements an interface, this method will
1223 // This will remove the method from the list of "pending" methods
1224 // that are required to be implemented for this class as a side effect.
1227 public bool IsInterfaceMethod (string Name, Type ret_type, Type [] args)
1229 MethodSignature query;
1231 if (pending_implementations == null)
1234 query = new MethodSignature (Name, ret_type, args);
1236 if (pending_implementations.Contains (query)){
1237 pending_implementations.Remove (query);
1245 // Verifies that any pending abstract methods or interface methods
1246 // were implemented.
1248 void VerifyPendingMethods ()
1252 foreach (object m in pending_implementations){
1253 DictionaryEntry de = (DictionaryEntry) m;
1254 Type t = (Type) de.Value;
1257 MethodSignature method = (MethodSignature) de.Key;
1262 "`" + Name + "' does not implement interface member `" +
1263 t.FullName + "." + method.Name + "'");
1267 "`" + Name + "' does not implement inherited abstract " +
1268 "member `" + t.FullName + "." + method.Name + "'");
1273 // Emits the code, this step is performed after all
1274 // the types, enumerations, constructors
1278 if (Constructors != null)
1279 foreach (Constructor c in Constructors)
1282 if (methods != null)
1283 foreach (Method m in methods)
1286 if (operators != null)
1287 foreach (Operator o in operators)
1290 if (properties != null)
1291 foreach (Property p in properties)
1294 if (pending_implementations != null)
1295 VerifyPendingMethods ();
1298 foreach (TypeContainer tc in types)
1303 public void CloseType ()
1305 TypeBuilder.CreateType ();
1307 foreach (TypeContainer tc in Types)
1310 if (Delegates != null)
1311 foreach (Delegate d in Delegates)
1315 string MakeName (string n)
1317 return "`" + Name + "." + n + "'";
1320 public static int CheckMember (string name, MemberInfo mi, int ModFlags)
1326 public class Class : TypeContainer {
1328 // Modifiers allowed in a class declaration
1330 public const int AllowedModifiers =
1333 Modifiers.PROTECTED |
1334 Modifiers.INTERNAL |
1336 Modifiers.ABSTRACT |
1339 public Class (RootContext rc, TypeContainer parent, string name, int mod,
1340 Attributes attrs, Location l)
1341 : base (rc, parent, name, l)
1345 if (parent.Parent == null)
1346 accmods = Modifiers.INTERNAL;
1348 accmods = Modifiers.PRIVATE;
1350 this.mod_flags = Modifiers.Check (AllowedModifiers, mod, accmods);
1351 this.attributes = attrs;
1355 // FIXME: How do we deal with the user specifying a different
1358 public override TypeAttributes TypeAttr {
1360 return base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
1365 public class Struct : TypeContainer {
1367 // Modifiers allowed in a struct declaration
1369 public const int AllowedModifiers =
1372 Modifiers.PROTECTED |
1373 Modifiers.INTERNAL |
1376 public Struct (RootContext rc, TypeContainer parent, string name, int mod,
1377 Attributes attrs, Location l)
1378 : base (rc, parent, name, l)
1382 if (parent.Parent == null)
1383 accmods = Modifiers.INTERNAL;
1385 accmods = Modifiers.PRIVATE;
1387 this.mod_flags = Modifiers.Check (AllowedModifiers, mod, accmods);
1389 this.mod_flags |= Modifiers.SEALED;
1390 this.attributes = attrs;
1395 // FIXME: Allow the user to specify a different set of attributes
1396 // in some cases (Sealed for example is mandatory for a class,
1397 // but what SequentialLayout can be changed
1399 public override TypeAttributes TypeAttr {
1401 return base.TypeAttr |
1402 TypeAttributes.SequentialLayout |
1403 TypeAttributes.Sealed |
1404 TypeAttributes.BeforeFieldInit;
1409 public class MethodCore {
1410 public readonly Parameters Parameters;
1411 public readonly string Name;
1412 public int ModFlags;
1414 public readonly Location Location;
1417 // Parameters, cached for semantic analysis.
1419 InternalParameters parameter_info;
1421 public MethodCore (string name, Parameters parameters, Location l)
1424 Parameters = parameters;
1429 // Returns the System.Type array for the parameters of this method
1431 Type [] parameter_types;
1432 public Type [] ParameterTypes (TypeContainer parent)
1434 if (Parameters == null)
1437 if (parameter_types == null)
1438 parameter_types = Parameters.GetParameterInfo (parent);
1440 return parameter_types;
1443 public InternalParameters ParameterInfo
1446 return parameter_info;
1450 parameter_info = value;
1454 public Block Block {
1464 public CallingConventions GetCallingConvention (bool is_class)
1466 CallingConventions cc = 0;
1468 cc = Parameters.GetCallingConvention ();
1471 if ((ModFlags & Modifiers.STATIC) == 0)
1472 cc |= CallingConventions.HasThis;
1474 // FIXME: How is `ExplicitThis' used in C#?
1480 public class Method : MethodCore {
1481 public readonly string ReturnType;
1482 public MethodBuilder MethodBuilder;
1483 public readonly Attributes OptAttributes;
1486 // Modifiers allowed in a class declaration
1488 const int AllowedModifiers =
1491 Modifiers.PROTECTED |
1492 Modifiers.INTERNAL |
1497 Modifiers.OVERRIDE |
1498 Modifiers.ABSTRACT |
1501 // return_type can be "null" for VOID values.
1502 public Method (string return_type, int mod, string name, Parameters parameters,
1503 Attributes attrs, Location l)
1504 : base (name, parameters, l)
1506 ReturnType = return_type;
1507 ModFlags = Modifiers.Check (AllowedModifiers, mod, Modifiers.PRIVATE);
1508 OptAttributes = attrs;
1511 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
1515 if (! (m is MethodInfo))
1518 MethodSignature sig = (MethodSignature) filter_criteria;
1520 if (m.Name != sig.Name)
1523 mi = (MethodInfo) m;
1525 if (mi.ReturnType != sig.RetType)
1528 Type [] args = TypeManager.GetArgumentTypes (mi);
1529 Type [] sigp = sig.Parameters;
1532 // FIXME: remove this assumption if we manage to
1533 // not enter a null as a the Parameters in TypeManager's
1534 // MethodBase to Type argument mapper.
1541 } else if (sigp == null)
1544 if (args.Length != sigp.Length)
1547 for (int i = args.Length; i > 0; ){
1549 if (args [i] != sigp [i])
1556 // This delegate is used to extract methods which have the
1557 // same signature as the argument
1559 static MemberFilter method_signature_filter;
1563 method_signature_filter = new MemberFilter (MemberSignatureCompare);
1567 // Returns the `System.Type' for the ReturnType of this
1568 // function. Provides a nice cache. (used between semantic analysis
1569 // and actual code generation
1571 Type type_return_type;
1572 public Type GetReturnType (TypeContainer parent)
1574 if (type_return_type == null)
1575 type_return_type = parent.LookupType (ReturnType, false);
1577 return type_return_type;
1580 void WarningNotHiding (TypeContainer parent)
1584 "The member `" + parent.Name + "." + Name + "' does not hide an " +
1585 "inherited member. The keyword new is not required");
1589 string MakeName (TypeContainer parent)
1591 return "`" + parent.Name + "." + Name + "'";
1594 string MethodBaseName (MethodBase mb)
1596 return "`" + mb.ReflectedType.Name + "." + mb.Name + "'";
1599 bool CheckMethod (TypeContainer parent, MemberInfo [] mi)
1601 MethodInfo mb = (MethodInfo) mi [0];
1603 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
1605 108, Location, "The keyword new is required on " +
1606 MakeName (parent) + " because it hides `" +
1607 mb.ReflectedType.Name + "." +
1611 if (mb.IsVirtual || mb.IsAbstract){
1612 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0){
1614 114, Location, MakeName (parent) +
1615 "hides inherited member " + MethodBaseName (mb) +
1616 ". To make the current member override that " +
1617 "implementation, add the override keyword, " +
1618 "otherwise use the new keyword");
1629 public MethodBuilder Define (TypeContainer parent)
1631 Type ret_type = GetReturnType (parent);
1632 Type [] parameters = ParameterTypes (parent);
1633 MethodAttributes flags;
1637 // Verify if the parent has a type with the same name, and then
1638 // check whether we have to create a new slot for it or not.
1640 Type ptype = parent.TypeBuilder.BaseType;
1642 // ptype is only null for System.Object while compiling corlib.
1644 MethodSignature ms = new MethodSignature (Name, ret_type, parameters);
1647 mi = TypeContainer.FindMembers (
1648 ptype, MemberTypes.Method,
1649 BindingFlags.Public, method_signature_filter,
1652 if (mi != null && mi.Length > 0){
1653 CheckMethod (parent, mi);
1655 if ((ModFlags & Modifiers.NEW) != 0)
1656 WarningNotHiding (parent);
1658 if ((ModFlags & Modifiers.OVERRIDE) != 0)
1659 Report.Error (115, Location,
1661 " no suitable methods found to override");
1663 } else if ((ModFlags & Modifiers.NEW) != 0)
1664 WarningNotHiding (parent);
1667 // If we implement an interface, then set the proper flags.
1669 flags = Modifiers.MethodAttr (ModFlags);
1671 if (parent.IsInterfaceMethod (Name, ret_type, parameters))
1672 flags |= MethodAttributes.Virtual;
1675 // Catch invalid uses of virtual and abtract modifiers
1677 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1678 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1679 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1681 if ((ModFlags & va) == va){
1682 if ((ModFlags & va) == va){
1684 503, Location, "The abstract method " +
1685 MakeName (parent) + "can not be marked virtual");
1690 if ((ModFlags & Modifiers.ABSTRACT) != 0){
1691 if ((parent.ModFlags & Modifiers.ABSTRACT) == 0){
1693 513, Location, MakeName (parent) +
1694 " is abstract but its container class is not");
1699 if ((ModFlags & va) != 0 && ((ModFlags & Modifiers.PRIVATE) != 0)){
1701 621, Location, MakeName (parent) +
1702 " virtual or abstract members can not be private");
1706 if ((ModFlags & Modifiers.STATIC) != 0){
1707 if ((ModFlags & vao) != 0){
1709 112, Location, "static method " + MakeName (parent) +
1710 " can not be marked as virtual, abstract or override");
1716 if ((ModFlags & Modifiers.OVERRIDE) != 0 && ((ModFlags & nv) != 0)){
1718 113, Location, MakeName (parent) +
1719 "marked as override cannot be marked as new or virtual");
1727 // Finally, define the method
1730 MethodBuilder = parent.TypeBuilder.DefineMethod (
1732 GetCallingConvention (parent is Class),
1733 ret_type, parameters);
1736 // HACK because System.Reflection.Emit is lame
1738 TypeManager.RegisterMethod (MethodBuilder, parameters);
1740 ParameterInfo = new InternalParameters (parameters);
1743 // This is used to track the Entry Point,
1745 // FIXME: Allow pluggable entry point, check arguments, etc.
1747 if (Name == "Main"){
1748 if ((ModFlags & Modifiers.STATIC) != 0){
1749 parent.RootContext.EntryPoint = MethodBuilder;
1754 // Define each type attribute (in/out/ref) and
1755 // the argument names.
1757 Parameter [] p = Parameters.FixedParameters;
1761 for (i = 0; i < p.Length; i++)
1762 MethodBuilder.DefineParameter (
1763 i + 1, p [i].Attributes, p [i].Name);
1765 if (i != parameters.Length)
1766 Console.WriteLine ("Implement the type definition for params");
1769 return MethodBuilder;
1775 public void Emit (TypeContainer parent)
1777 ILGenerator ig = MethodBuilder.GetILGenerator ();
1778 EmitContext ec = new EmitContext (parent, ig, GetReturnType (parent), ModFlags);
1780 ec.EmitTopBlock (Block);
1784 public abstract class ConstructorInitializer {
1785 ArrayList argument_list;
1786 ConstructorInfo parent_constructor;
1789 public ConstructorInitializer (ArrayList argument_list, Location location)
1791 this.argument_list = argument_list;
1792 this.location = location;
1795 public ArrayList Arguments {
1797 return argument_list;
1801 public bool Resolve (EmitContext ec)
1803 Expression parent_constructor_group;
1805 if (argument_list != null){
1806 for (int i = argument_list.Count; i > 0; ){
1809 Argument a = (Argument) argument_list [i];
1810 if (!a.Resolve (ec))
1815 parent_constructor_group = Expression.MemberLookup (
1817 ec.TypeContainer.TypeBuilder.BaseType, ".ctor", false,
1818 MemberTypes.Constructor,
1819 BindingFlags.Public | BindingFlags.Instance, location);
1821 if (parent_constructor_group == null){
1822 Console.WriteLine ("Could not find a constructor in our parent");
1826 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (ec,
1827 (MethodGroupExpr) parent_constructor_group, argument_list, location);
1829 if (parent_constructor == null)
1835 public void Emit (EmitContext ec)
1837 ec.ig.Emit (OpCodes.Ldarg_0);
1838 if (argument_list != null)
1839 Invocation.EmitArguments (ec, parent_constructor, argument_list);
1840 ec.ig.Emit (OpCodes.Call, parent_constructor);
1844 public class ConstructorBaseInitializer : ConstructorInitializer {
1845 public ConstructorBaseInitializer (ArrayList argument_list, Location l) : base (argument_list, l)
1850 public class ConstructorThisInitializer : ConstructorInitializer {
1851 public ConstructorThisInitializer (ArrayList argument_list, Location l) : base (argument_list, l)
1856 public class Constructor : MethodCore {
1857 public ConstructorBuilder ConstructorBuilder;
1858 public ConstructorInitializer Initializer;
1861 // Modifiers allowed for a constructor.
1863 const int AllowedModifiers =
1865 Modifiers.PROTECTED |
1866 Modifiers.INTERNAL |
1871 // The spec claims that static is not permitted, but
1872 // my very own code has static constructors.
1874 public Constructor (string name, Parameters args, ConstructorInitializer init, Location l)
1875 : base (name, args, l)
1881 // Returns true if this is a default constructor
1883 public bool IsDefault ()
1885 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
1886 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
1887 (Initializer is ConstructorBaseInitializer) &&
1888 (Initializer.Arguments == null);
1892 // Creates the ConstructorBuilder
1894 public ConstructorBuilder Define (TypeContainer parent)
1896 MethodAttributes ca = (MethodAttributes.RTSpecialName |
1897 MethodAttributes.SpecialName);
1899 Type [] parameters = ParameterTypes (parent);
1901 if ((ModFlags & Modifiers.STATIC) != 0)
1902 ca |= MethodAttributes.Static;
1904 if (parent is Struct && parameters == null){
1907 "Structs can not contain explicit parameterless " +
1913 ConstructorBuilder = parent.TypeBuilder.DefineConstructor (
1914 ca, GetCallingConvention (parent is Class),
1917 // HACK because System.Reflection.Emit is lame
1919 TypeManager.RegisterMethod (ConstructorBuilder, parameters);
1921 ParameterInfo = new InternalParameters (parameters);
1923 return ConstructorBuilder;
1929 public void Emit (TypeContainer parent)
1931 ILGenerator ig = ConstructorBuilder.GetILGenerator ();
1932 EmitContext ec = new EmitContext (parent, ig, null, ModFlags, true);
1934 if (parent is Class){
1935 if (Initializer == null)
1936 Initializer = new ConstructorBaseInitializer (null, parent.Location);
1938 if (!Initializer.Resolve (ec))
1943 // Classes can have base initializers and instance field initializers.
1945 if (parent is Class){
1946 if ((ModFlags & Modifiers.STATIC) == 0)
1947 Initializer.Emit (ec);
1948 parent.EmitFieldInitializers (ec, false);
1951 if ((ModFlags & Modifiers.STATIC) != 0)
1952 parent.EmitFieldInitializers (ec, true);
1954 ec.EmitTopBlock (Block);
1958 public class Field {
1959 public readonly string Type;
1960 public readonly Object Initializer;
1961 public readonly string Name;
1962 public readonly int ModFlags;
1963 public readonly Attributes OptAttributes;
1964 public FieldBuilder FieldBuilder;
1968 // Modifiers allowed in a class declaration
1970 const int AllowedModifiers =
1973 Modifiers.PROTECTED |
1974 Modifiers.INTERNAL |
1979 public Field (string type, int mod, string name, Object expr_or_array_init, Attributes attrs)
1982 ModFlags = Modifiers.Check (AllowedModifiers, mod, Modifiers.PRIVATE);
1984 Initializer = expr_or_array_init;
1985 OptAttributes = attrs;
1988 public void Define (TypeContainer parent)
1990 Type t = parent.LookupType (Type, false);
1995 FieldBuilder = parent.TypeBuilder.DefineField (
1996 Name, t, Modifiers.FieldAttr (ModFlags));
2000 public class Property {
2002 public readonly string Type;
2003 public readonly string Name;
2004 public readonly int ModFlags;
2005 public Block Get, Set;
2006 public PropertyBuilder PropertyBuilder;
2007 public Attributes OptAttributes;
2008 MethodBuilder GetBuilder, SetBuilder;
2011 // The type, once we compute it.
2015 const int AllowedModifiers =
2018 Modifiers.PROTECTED |
2019 Modifiers.INTERNAL |
2023 Modifiers.OVERRIDE |
2024 Modifiers.ABSTRACT |
2027 public Property (string type, string name, int mod_flags, Block get_block, Block set_block, Attributes attrs)
2031 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PRIVATE);
2034 OptAttributes = attrs;
2037 public void Define (TypeContainer parent)
2040 MethodAttributes method_attr = Modifiers.MethodAttr(ModFlags);
2042 // FIXME - PropertyAttributes.HasDefault ?
2044 PropertyAttributes prop_attr = PropertyAttributes.RTSpecialName |
2045 PropertyAttributes.SpecialName;
2048 PropertyType = parent.LookupType (Type, false);
2049 Type [] parameters = new Type [1];
2050 parameters [0] = PropertyType;
2052 PropertyBuilder = parent.TypeBuilder.DefineProperty (
2053 Name, prop_attr, PropertyType, null);
2057 GetBuilder = parent.TypeBuilder.DefineMethod (
2058 "get_" + Name, method_attr, PropertyType, null);
2059 PropertyBuilder.SetGetMethod (GetBuilder);
2061 // HACK because System.Reflection.Emit is lame
2063 TypeManager.RegisterMethod (GetBuilder, null);
2068 SetBuilder = parent.TypeBuilder.DefineMethod (
2069 "set_" + Name, method_attr, null, parameters);
2070 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
2071 PropertyBuilder.SetSetMethod (SetBuilder);
2073 // HACK because System.Reflection.Emit is lame
2075 TypeManager.RegisterMethod (SetBuilder, parameters);
2079 // HACK for the reasons exposed above
2081 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
2084 public void Emit (TypeContainer tc)
2090 ig = GetBuilder.GetILGenerator ();
2091 ec = new EmitContext (tc, ig, PropertyType, ModFlags);
2093 ec.EmitTopBlock (Get);
2097 ig = SetBuilder.GetILGenerator ();
2098 ec = new EmitContext (tc, ig, null, ModFlags);
2100 ec.EmitTopBlock (Set);
2105 public class Event {
2107 const int AllowedModifiers =
2110 Modifiers.PROTECTED |
2111 Modifiers.INTERNAL |
2116 Modifiers.OVERRIDE |
2119 public readonly string Type;
2120 public readonly string Name;
2121 public readonly Object Initializer;
2122 public readonly int ModFlags;
2123 public readonly Block Add;
2124 public readonly Block Remove;
2125 public EventBuilder EventBuilder;
2126 public Attributes OptAttributes;
2128 public Event (string type, string name, Object init, int flags, Block add_block, Block rem_block,
2134 ModFlags = Modifiers.Check (AllowedModifiers, flags, Modifiers.PRIVATE);
2137 OptAttributes = attrs;
2140 public void Define (TypeContainer parent)
2142 MethodAttributes m_attr = Modifiers.MethodAttr (ModFlags);
2144 EventAttributes e_attr = EventAttributes.RTSpecialName | EventAttributes.SpecialName;
2148 Type t = parent.LookupType (Type, false);
2149 Type [] parameters = new Type [1];
2152 EventBuilder = parent.TypeBuilder.DefineEvent (Name, e_attr, t);
2155 mb = parent.TypeBuilder.DefineMethod ("add_" + Name, m_attr, null,
2157 mb.DefineParameter (1, ParameterAttributes.None, "value");
2158 EventBuilder.SetAddOnMethod (mb);
2160 // HACK because System.Reflection.Emit is lame
2162 TypeManager.RegisterMethod (mb, parameters);
2165 if (Remove != null) {
2166 mb = parent.TypeBuilder.DefineMethod ("remove_" + Name, m_attr, null,
2168 mb.DefineParameter (1, ParameterAttributes.None, "value");
2169 EventBuilder.SetRemoveOnMethod (mb);
2172 // HACK because System.Reflection.Emit is lame
2174 TypeManager.RegisterMethod (mb, parameters);
2180 public class Indexer {
2182 const int AllowedModifiers =
2185 Modifiers.PROTECTED |
2186 Modifiers.INTERNAL |
2190 Modifiers.OVERRIDE |
2193 public readonly string Type;
2194 public readonly string InterfaceType;
2195 public readonly Parameters FormalParameters;
2196 public readonly int ModFlags;
2197 public readonly Block Get;
2198 public readonly Block Set;
2199 public Attributes OptAttributes;
2200 public MethodBuilder GetMethodBuilder;
2201 public MethodBuilder SetMethodBuilder;
2204 public Indexer (string type, string int_type, int flags, Parameters parms,
2205 Block get_block, Block set_block, Attributes attrs)
2209 InterfaceType = int_type;
2210 ModFlags = Modifiers.Check (AllowedModifiers, flags, Modifiers.PRIVATE);
2211 FormalParameters = parms;
2214 OptAttributes = attrs;
2217 public void Define (TypeContainer parent)
2219 MethodAttributes attr = Modifiers.MethodAttr (ModFlags);
2221 Type ret_type = parent.LookupType (Type, false);
2222 Type [] parameters = FormalParameters.GetParameterInfo (parent);
2224 GetMethodBuilder = parent.TypeBuilder.DefineMethod (
2225 "get_Item", attr, ret_type, parameters);
2226 SetMethodBuilder = parent.TypeBuilder.DefineMethod (
2227 "set_Item", attr, ret_type, parameters);
2230 // HACK because System.Reflection.Emit is lame
2232 TypeManager.RegisterMethod (GetMethodBuilder, parameters);
2233 TypeManager.RegisterMethod (SetMethodBuilder, parameters);
2235 Parameter [] p = FormalParameters.FixedParameters;
2240 for (i = 0; i < p.Length; ++i) {
2241 GetMethodBuilder.DefineParameter (i + 1, p [i].Attributes, p [i].Name);
2242 SetMethodBuilder.DefineParameter (i + 1, p [i].Attributes, p [i].Name);
2245 if (i != parameters.Length)
2246 Console.WriteLine ("Implement type definition for params");
2253 public class Operator {
2255 const int AllowedModifiers =
2259 const int RequiredModifiers =
2263 public enum OpType {
2273 // Unary and Binary operators
2293 // Implicit and Explicit
2298 public readonly OpType OperatorType;
2299 public readonly string ReturnType;
2300 public readonly string FirstArgType;
2301 public readonly string FirstArgName;
2302 public readonly string SecondArgType;
2303 public readonly string SecondArgName;
2304 public readonly int ModFlags;
2305 public readonly Block Block;
2306 public Attributes OptAttributes;
2307 public MethodBuilder OperatorMethodBuilder;
2308 public Location Location;
2310 public string MethodName;
2311 public Method OperatorMethod;
2313 public Operator (OpType type, string ret_type, int flags, string arg1type, string arg1name,
2314 string arg2type, string arg2name, Block block, Attributes attrs, Location loc)
2316 OperatorType = type;
2317 ReturnType = ret_type;
2318 ModFlags = Modifiers.Check (AllowedModifiers, flags, Modifiers.PUBLIC);
2319 FirstArgType = arg1type;
2320 FirstArgName = arg1name;
2321 SecondArgType = arg2type;
2322 SecondArgName = arg2name;
2324 OptAttributes = attrs;
2328 string Prototype (TypeContainer parent)
2330 return parent.Name + ".operator " + OperatorType + " (" + FirstArgType + "," +
2331 SecondArgType + ")";
2334 public void Define (TypeContainer parent)
2337 MethodName = "op_" + OperatorType;
2339 if (SecondArgType != null)
2342 Parameter [] param_list = new Parameter [length];
2344 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
2347 "User defined operators `" +
2348 Prototype (parent) +
2349 "' must be declared static and public");
2352 param_list[0] = new Parameter (FirstArgType, FirstArgName,
2353 Parameter.Modifier.NONE, null);
2354 if (SecondArgType != null)
2355 param_list[1] = new Parameter (SecondArgType, SecondArgName,
2356 Parameter.Modifier.NONE, null);
2358 OperatorMethod = new Method (ReturnType, ModFlags, MethodName,
2359 new Parameters (param_list, null),
2360 OptAttributes, Location.Null);
2362 OperatorMethod.Define (parent);
2363 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
2365 Type [] param_types = OperatorMethod.ParameterTypes (parent);
2366 Type declaring_type = OperatorMethodBuilder.DeclaringType;
2367 Type return_type = OperatorMethod.GetReturnType (parent);
2368 Type first_arg_type = param_types [0];
2370 // Rules for conversion operators
2372 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
2374 if (first_arg_type == return_type && first_arg_type == declaring_type)
2375 Report.Error (555, Location,
2376 "User-defined conversion cannot take an object of the enclosing type " +
2377 "and convert to an object of the enclosing type");
2379 if (first_arg_type != declaring_type && return_type != declaring_type)
2380 Report.Error (556, Location,
2381 "User-defined conversion must convert to or from the enclosing type");
2383 if (first_arg_type == TypeManager.object_type || return_type == TypeManager.object_type)
2384 Report.Error (-8, Location,
2385 "User-defined conversion cannot convert to or from object type");
2387 if (first_arg_type.IsInterface || return_type.IsInterface)
2388 Report.Error (-9, Location,
2389 "User-defined conversion cannot convert to or from an interface type");
2391 if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type))
2392 Report.Error (-10, Location,
2393 "User-defined conversion cannot convert between types that " +
2394 "derive from each other");
2396 } else if (SecondArgType == null) {
2397 // Checks for Unary operators
2399 if (first_arg_type != declaring_type)
2400 Report.Error (562, Location,
2401 "The parameter of a unary operator must be the containing type");
2404 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
2405 if (return_type != declaring_type)
2406 Report.Error (559, Location,
2407 "The parameter and return type for ++ and -- " +
2408 "must be the containing type");
2412 if (OperatorType == OpType.True || OperatorType == OpType.False) {
2413 if (return_type != TypeManager.bool_type)
2414 Report.Error (215, Location,
2415 "The return type of operator True or False " +
2420 // Checks for Binary operators
2422 if (first_arg_type != declaring_type &&
2423 param_types [1] != declaring_type)
2424 Report.Error (563, Location,
2425 "One of the parameters of a binary operator must be the containing type");
2432 public void Emit (TypeContainer parent)
2434 OperatorMethod.Block = Block;
2435 OperatorMethod.Emit (parent);
2442 // This is used to compare method signatures
2444 struct MethodSignature {
2446 public Type RetType;
2447 public Type [] Parameters;
2449 public MethodSignature (string name, Type ret_type, Type [] parameters)
2453 Parameters = parameters;
2455 if (parameters != null){
2456 if (parameters.Length == 0)
2461 public override int GetHashCode ()
2463 return Name.GetHashCode ();
2466 public override bool Equals (Object o)
2468 MethodSignature other = (MethodSignature) o;
2470 if (other.Name != Name)
2473 if (other.RetType != RetType)
2476 if (Parameters == null){
2477 if (other.Parameters == null)
2482 if (other.Parameters == null)
2485 int c = Parameters.Length;
2486 if (other.Parameters.Length != c)
2489 for (int i = 0; i < c; i++)
2490 if (other.Parameters [i] != Parameters [i])