2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 namespace Mono.CSharp {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
79 public virtual void Emit ()
81 foreach (MemberCore mc in this)
86 public class MethodArrayList: MemberCoreArrayList
94 CachedMethods cached_method;
95 TypeContainer container;
97 public MethodArrayList (TypeContainer container)
99 this.container = container;
103 /// Method container contains Equals method
105 public bool HasEquals {
107 cached_method |= CachedMethods.Equals;
111 return (cached_method & CachedMethods.Equals) != 0;
116 /// Method container contains GetHashCode method
118 public bool HasGetHashCode {
120 cached_method |= CachedMethods.GetHashCode;
124 return (cached_method & CachedMethods.GetHashCode) != 0;
128 public override void DefineContainerMembers ()
130 base.DefineContainerMembers ();
132 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
133 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
139 public sealed class IndexerArrayList: MemberCoreArrayList
142 /// The indexer name for this container
144 public string IndexerName = DefaultIndexerName;
146 bool seen_normal_indexers = false;
148 TypeContainer container;
150 public IndexerArrayList (TypeContainer container)
152 this.container = container;
156 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
157 /// class is consistent. Either it is `Item' or it is the name defined by all the
158 /// indexers with the `IndexerName' attribute.
160 /// Turns out that the IndexerNameAttribute is applied to each indexer,
161 /// but it is never emitted, instead a DefaultMember attribute is attached
164 public override void DefineContainerMembers()
166 base.DefineContainerMembers ();
168 string class_indexer_name = null;
171 // If there's both an explicit and an implicit interface implementation, the
172 // explicit one actually implements the interface while the other one is just
173 // a normal indexer. See bug #37714.
176 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
177 foreach (Indexer i in this) {
178 if (i.InterfaceType != null) {
179 if (seen_normal_indexers)
180 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
184 seen_normal_indexers = true;
186 if (class_indexer_name == null) {
187 class_indexer_name = i.ShortName;
191 if (i.ShortName != class_indexer_name)
192 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
195 if (class_indexer_name != null)
196 IndexerName = class_indexer_name;
199 public override void Emit ()
203 if (!seen_normal_indexers)
206 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
207 container.TypeBuilder.SetCustomAttribute (cb);
211 public class OperatorArrayList: MemberCoreArrayList
213 TypeContainer container;
215 public OperatorArrayList (TypeContainer container)
217 this.container = container;
221 // Operator pair checking
226 public Type ret_type;
227 public Type type1, type2;
229 public Operator.OpType ot;
231 public OperatorEntry (int f, Operator o)
235 ret_type = o.OperatorMethod.ReturnType;
236 Type [] pt = o.OperatorMethod.ParameterTypes;
243 public override int GetHashCode ()
245 return ret_type.GetHashCode ();
248 public override bool Equals (object o)
250 OperatorEntry other = (OperatorEntry) o;
252 if (other.ret_type != ret_type)
254 if (other.type1 != type1)
256 if (other.type2 != type2)
263 // Checks that some operators come in pairs:
269 // They are matched based on the return type and the argument types
271 void CheckPairedOperators ()
273 Hashtable pairs = new Hashtable (null, null);
274 Operator true_op = null;
275 Operator false_op = null;
276 bool has_equality_or_inequality = false;
278 // Register all the operators we care about.
279 foreach (Operator op in this){
282 switch (op.OperatorType){
283 case Operator.OpType.Equality:
285 has_equality_or_inequality = true;
287 case Operator.OpType.Inequality:
289 has_equality_or_inequality = true;
292 case Operator.OpType.True:
295 case Operator.OpType.False:
299 case Operator.OpType.GreaterThan:
301 case Operator.OpType.LessThan:
304 case Operator.OpType.GreaterThanOrEqual:
306 case Operator.OpType.LessThanOrEqual:
312 OperatorEntry oe = new OperatorEntry (reg, op);
314 object o = pairs [oe];
318 oe = (OperatorEntry) o;
323 if (true_op != null){
324 if (false_op == null)
325 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
326 } else if (false_op != null)
327 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
330 // Look for the mistakes.
332 foreach (DictionaryEntry de in pairs){
333 OperatorEntry oe = (OperatorEntry) de.Key;
340 case Operator.OpType.Equality:
343 case Operator.OpType.Inequality:
346 case Operator.OpType.GreaterThan:
349 case Operator.OpType.LessThan:
352 case Operator.OpType.GreaterThanOrEqual:
355 case Operator.OpType.LessThanOrEqual:
359 Report.Error (216, oe.op.Location,
360 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
363 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
364 if (container.Methods == null || !container.Methods.HasEquals)
365 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
367 if (container.Methods == null || !container.Methods.HasGetHashCode)
368 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
372 public override void DefineContainerMembers ()
374 base.DefineContainerMembers ();
375 CheckPairedOperators ();
380 // Whether this is a struct, class or interface
381 public readonly Kind Kind;
383 // Holds a list of classes and structures
386 // Holds the list of properties
387 MemberCoreArrayList properties;
389 // Holds the list of enumerations
390 MemberCoreArrayList enums;
392 // Holds the list of delegates
393 MemberCoreArrayList delegates;
395 // Holds the list of constructors
396 protected MemberCoreArrayList instance_constructors;
398 // Holds the list of fields
399 MemberCoreArrayList fields;
401 // Holds a list of fields that have initializers
402 protected ArrayList initialized_fields;
404 // Holds a list of static fields that have initializers
405 protected ArrayList initialized_static_fields;
407 // Holds the list of constants
408 MemberCoreArrayList constants;
411 MemberCoreArrayList interfaces;
413 // Holds the methods.
414 MethodArrayList methods;
417 protected MemberCoreArrayList events;
419 // Holds the indexers
420 IndexerArrayList indexers;
422 // Holds the operators
423 MemberCoreArrayList operators;
425 // Holds the iterators
428 // Holds the parts of a partial class;
432 // Pointers to the default constructor and the default static constructor
434 protected Constructor default_constructor;
435 protected Constructor default_static_constructor;
438 // Whether we have at least one non-static field
440 bool have_nonstatic_fields = false;
443 // This one is computed after we can distinguish interfaces
444 // from classes from the arraylist `type_bases'
446 string base_class_name;
447 TypeExpr parent_type;
449 ArrayList type_bases;
451 bool members_defined;
452 bool members_defined_ok;
454 // The interfaces we implement.
455 protected Type [] ifaces;
456 protected Type ptype;
458 // The parent member cache and our member cache
459 MemberCache parent_cache;
460 MemberCache member_cache;
462 public const string DefaultIndexerName = "Item";
464 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
465 Attributes attrs, Kind kind, Location l)
466 : base (ns, parent, name, attrs, l)
470 types = new ArrayList ();
472 base_class_name = null;
475 public bool AddToMemberContainer (MemberCore symbol, bool is_method)
477 return AddToContainer (symbol, is_method, String.Concat (Name, '.', symbol.Name), symbol.Name);
480 bool AddToTypeContainer (DeclSpace ds)
482 return AddToContainer (ds, false, ds.Name, ds.Basename);
485 public void AddConstant (Const constant)
487 if (!AddToMemberContainer (constant, false))
490 if (constants == null)
491 constants = new MemberCoreArrayList ();
493 constants.Add (constant);
496 public void AddEnum (Mono.CSharp.Enum e)
498 if (!AddToTypeContainer (e))
502 enums = new MemberCoreArrayList ();
507 public void AddClassOrStruct (TypeContainer c)
509 if (!AddToTypeContainer (c))
515 public void AddDelegate (Delegate d)
517 if (!AddToTypeContainer (d))
520 if (delegates == null)
521 delegates = new MemberCoreArrayList ();
526 public void AddMethod (Method method)
528 if (!AddToMemberContainer (method, true))
532 methods = new MethodArrayList (this);
534 if (method.Name.IndexOf ('.') != -1)
535 methods.Insert (0, method);
537 methods.Add (method);
540 public void AddConstructor (Constructor c)
542 if (c.Name != Basename) {
543 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
546 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
549 if (default_static_constructor != null) {
550 Report.SymbolRelatedToPreviousError (default_static_constructor);
551 Report.Error (111, c.Location, Error111, Name, c.Name);
555 default_static_constructor = c;
558 if (default_constructor != null) {
559 Report.SymbolRelatedToPreviousError (default_constructor);
560 Report.Error (111, c.Location, Error111, c.Location, Name, c.Name);
563 default_constructor = c;
566 if (instance_constructors == null)
567 instance_constructors = new MemberCoreArrayList ();
569 instance_constructors.Add (c);
573 internal static string Error111 {
575 return "Type '{0}' already defines a member called '{1}' with the same parameter types";
579 public void AddInterface (TypeContainer iface)
581 if (!AddToTypeContainer (iface))
584 if (interfaces == null) {
585 interfaces = new MemberCoreArrayList ();
588 interfaces.Add (iface);
591 public void AddField (Field field)
593 if (!AddToMemberContainer (field, false))
597 fields = new MemberCoreArrayList ();
601 if (field.HasInitializer){
602 if ((field.ModFlags & Modifiers.STATIC) != 0){
603 if (initialized_static_fields == null)
604 initialized_static_fields = new ArrayList ();
606 initialized_static_fields.Add (field);
608 if (initialized_fields == null)
609 initialized_fields = new ArrayList ();
611 initialized_fields.Add (field);
615 if ((field.ModFlags & Modifiers.STATIC) == 0)
616 have_nonstatic_fields = true;
619 public void AddProperty (Property prop)
621 if (!AddToMemberContainer (prop, false) ||
622 !AddToMemberContainer (prop.Get, true) || !AddToMemberContainer (prop.Set, true))
625 if (properties == null)
626 properties = new MemberCoreArrayList ();
628 if (prop.Name.IndexOf ('.') != -1)
629 properties.Insert (0, prop);
631 properties.Add (prop);
634 public void AddEvent (Event e)
636 if (!AddToMemberContainer (e, false))
639 if (e is EventProperty) {
640 if (!AddToMemberContainer (e.Add, true))
643 if (!AddToMemberContainer (e.Remove, true))
648 events = new MemberCoreArrayList ();
655 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
657 public void AddIndexer (Indexer i)
659 if (indexers == null)
660 indexers = new IndexerArrayList (this);
662 if (i.IsExplicitImpl)
663 indexers.Insert (0, i);
668 public void AddOperator (Operator op)
670 if (!AddToMemberContainer (op, true))
673 if (operators == null)
674 operators = new OperatorArrayList (this);
679 public void AddIterator (Iterator i)
681 if (iterators == null)
682 iterators = new ArrayList ();
687 public void AddType (TypeContainer tc)
692 public void AddPart (ClassPart part)
695 parts = new ArrayList ();
700 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
702 if (a.Type == TypeManager.default_member_type) {
703 if (Indexers != null) {
704 Report.Error (646, a.Location,
705 "Cannot specify the DefaultMember attribute on" +
706 " a type containing an indexer");
711 base.ApplyAttributeBuilder (a, cb);
714 public override AttributeTargets AttributeTargets {
716 throw new NotSupportedException ();
720 public ArrayList Types {
726 public MethodArrayList Methods {
732 public ArrayList Constants {
738 public ArrayList Interfaces {
744 public ArrayList Iterators {
752 return base_class_name;
756 public ArrayList Bases {
766 public ArrayList Fields {
772 public ArrayList InstanceConstructors {
774 return instance_constructors;
778 public ArrayList Properties {
784 public ArrayList Events {
790 public ArrayList Enums {
796 public ArrayList Indexers {
802 public ArrayList Operators {
808 public ArrayList Delegates {
814 public ArrayList Parts {
820 public virtual TypeAttributes TypeAttr {
822 return Modifiers.TypeAttr (ModFlags, this);
826 public string IndexerName {
828 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
833 // Emits the instance field initializers
835 public bool EmitFieldInitializers (EmitContext ec)
838 Expression instance_expr;
841 fields = initialized_static_fields;
842 instance_expr = null;
844 fields = initialized_fields;
845 instance_expr = new This (Location.Null).Resolve (ec);
851 foreach (Field f in fields){
852 Expression e = f.GetInitializerExpression (ec);
856 Location l = f.Location;
857 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
858 fe.InstanceExpression = instance_expr;
859 ExpressionStatement a = new Assign (fe, e, l);
861 a = a.ResolveStatement (ec);
865 a.EmitStatement (ec);
872 // Defines the default constructors
874 protected void DefineDefaultConstructor (bool is_static)
878 // The default constructor is public
879 // If the class is abstract, the default constructor is protected
880 // The default static constructor is private
882 int mods = Modifiers.PUBLIC;
884 mods = Modifiers.STATIC | Modifiers.PRIVATE;
885 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
886 mods = Modifiers.PROTECTED;
888 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
889 new ConstructorBaseInitializer (
890 null, Parameters.EmptyReadOnlyParameters,
896 c.Block = new ToplevelBlock (null, Location);
901 /// The pending methods that need to be implemented
902 // (interfaces or abstract methods)
904 public PendingImplementation Pending;
906 public abstract void Register ();
908 public abstract PendingImplementation GetPendingImplementations ();
910 TypeExpr[] GetPartialBases (out TypeExpr parent, out bool error)
912 ArrayList ifaces = new ArrayList ();
915 Location parent_loc = Location.Null;
917 foreach (ClassPart part in parts) {
919 TypeExpr[] new_ifaces;
921 new_ifaces = part.GetClassBases (out new_parent, out error);
925 if ((parent != null) && (new_parent != null) &&
926 !parent.Equals (new_parent)) {
927 Report.Error (263, part.Location,
928 "Partial declarations of `{0}' must " +
929 "not specify different base classes",
932 if (!Location.IsNull (parent_loc))
933 Report.LocationOfPreviousError (parent_loc);
939 if ((parent == null) && (new_parent != null)) {
941 parent_loc = part.Location;
944 if (new_ifaces == null)
947 foreach (TypeExpr iface in new_ifaces) {
949 foreach (TypeExpr old_iface in ifaces) {
950 if (old_iface.Equals (iface)) {
963 TypeExpr[] retval = new TypeExpr [ifaces.Count];
964 ifaces.CopyTo (retval, 0);
968 TypeExpr[] GetNormalBases (out TypeExpr parent, out bool error)
972 int count = Bases.Count;
975 if (Kind == Kind.Class){
976 TypeExpr name = ResolveTypeExpr (
977 (Expression) Bases [0], false, Location);
994 TypeExpr [] ifaces = new TypeExpr [count-start];
996 for (i = start, j = 0; i < count; i++, j++){
997 Expression name = (Expression) Bases [i];
998 TypeExpr resolved = ResolveTypeExpr (name, false, Location);
999 if (resolved == null) {
1004 ifaces [j] = resolved;
1012 /// This function computes the Base class and also the
1013 /// list of interfaces that the class or struct @c implements.
1015 /// The return value is an array (might be null) of
1016 /// interfaces implemented (as Types).
1018 /// The @parent argument is set to the parent object or null
1019 /// if this is `System.Object'.
1021 TypeExpr [] GetClassBases (out TypeExpr parent, out bool error)
1030 ifaces = GetPartialBases (out parent, out error);
1031 else if (Bases == null){
1035 ifaces = GetNormalBases (out parent, out error);
1040 if ((parent != null) && (Kind == Kind.Class)){
1042 if (parent.Type.IsArray || parent.Type.IsPointer) {
1043 Report.Error (1521, parent.Location, "Invalid base type");
1048 if (parent.IsSealed){
1050 Report.SymbolRelatedToPreviousError (parent.Type);
1051 if (parent.Type.IsAbstract) {
1052 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1054 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1059 if (!parent.CanInheritFrom ()){
1060 Report.Error (644, Location,
1061 "`{0}' cannot inherit from special class `{1}'",
1067 if (!parent.AsAccessible (this, ModFlags)) {
1068 Report.SymbolRelatedToPreviousError (parent.Type);
1069 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1070 TypeManager.CSharpName (parent.Type), GetSignatureForError ());
1075 base_class_name = parent.Name;
1080 int count = ifaces != null ? ifaces.Length : 0;
1082 for (i = 0; i < count; i++) {
1083 TypeExpr iface = (TypeExpr) ifaces [i];
1085 if ((Kind != Kind.Class) && !iface.IsInterface){
1086 string what = Kind == Kind.Struct ?
1087 "Struct" : "Interface";
1089 Report.Error (527, Location,
1090 "In {0} `{1}', type `{2}' is not "+
1091 "an interface", what, Name, iface.Name);
1095 if (iface.IsClass) {
1097 Report.Error (1721, Location,
1098 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1101 Report.Error (1722, Location,
1102 "In Class `{0}', `{1}' is not " +
1103 "an interface, a base class must be listed first", Name, iface.Name);
1109 for (int x = 0; x < i; x++) {
1110 if (iface.Equals (ifaces [x])) {
1111 Report.Error (528, Location,
1112 "`{0}' is already listed in " +
1113 "interface list", iface.Name);
1119 if ((Kind == Kind.Interface) &&
1120 !iface.AsAccessible (Parent, ModFlags))
1121 Report.Error (61, Location,
1122 "Inconsistent accessibility: base " +
1123 "interface `{0}' is less accessible " +
1124 "than interface `{1}'", iface.Name,
1134 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1136 public override TypeBuilder DefineType ()
1138 if (TypeBuilder != null)
1145 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
1152 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1154 TypeExpr[] iface_exprs = GetClassBases (out parent_type, out error);
1158 if (parent_type == null) {
1159 if (Kind == Kind.Class){
1160 if (RootContext.StdLib)
1161 parent_type = TypeManager.system_object_expr;
1162 else if (Name != "System.Object")
1163 parent_type = TypeManager.system_object_expr;
1164 } else if (Kind == Kind.Struct) {
1166 // If we are compiling our runtime,
1167 // and we are defining ValueType, then our
1168 // parent is `System.Object'.
1170 if (!RootContext.StdLib && Name == "System.ValueType")
1171 parent_type = TypeManager.system_object_expr;
1173 parent_type = TypeManager.system_valuetype_expr;
1177 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1178 throw new Exception ();
1180 TypeAttributes type_attributes = TypeAttr;
1182 if (parent_type != null) {
1183 ptype = parent_type.ResolveType (ec);
1184 if (ptype == null) {
1192 if (TypeManager.NamespaceClash (Name, Location)) {
1197 ModuleBuilder builder = CodeGen.Module.Builder;
1198 TypeBuilder = builder.DefineType (
1199 Name, type_attributes, ptype, null);
1202 TypeBuilder builder = Parent.DefineType ();
1203 if (builder == null)
1206 TypeBuilder = builder.DefineNestedType (
1207 Basename, type_attributes, ptype, null);
1210 catch (ArgumentException) {
1211 Report.RuntimeMissingSupport (Location, "static classes");
1216 // Structs with no fields need to have at least one byte.
1217 // The right thing would be to set the PackingSize in a DefineType
1218 // but there are no functions that allow interfaces *and* the size to
1222 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1223 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1224 FieldAttributes.Private);
1227 // add interfaces that were not added at type creation
1228 if (iface_exprs != null) {
1229 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1230 if (ifaces == null) {
1235 foreach (Type itype in ifaces)
1236 TypeBuilder.AddInterfaceImplementation (itype);
1238 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1242 // Finish the setup for the EmitContext
1244 ec.ContainerType = TypeBuilder;
1246 TypeManager.AddUserType (Name, TypeBuilder, this);
1248 if ((parent_type != null) && parent_type.IsAttribute) {
1249 RootContext.RegisterAttribute (this);
1250 } else if (!(this is Iterator))
1251 RootContext.RegisterOrder (this);
1253 if (!DefineNestedTypes ()) {
1262 protected virtual bool DefineNestedTypes ()
1264 if (Interfaces != null) {
1265 foreach (TypeContainer iface in Interfaces)
1266 if (iface.DefineType () == null)
1270 if (Types != null) {
1271 foreach (TypeContainer tc in Types)
1272 if (tc.DefineType () == null)
1276 if (Delegates != null) {
1277 foreach (Delegate d in Delegates)
1278 if (d.DefineType () == null)
1282 if (Enums != null) {
1283 foreach (Enum en in Enums)
1284 if (en.DefineType () == null)
1288 if (Parts != null) {
1289 foreach (ClassPart part in Parts) {
1290 part.TypeBuilder = TypeBuilder;
1292 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1299 static void Error_KeywordNotAllowed (Location loc)
1301 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1305 /// Populates our TypeBuilder with fields and methods
1307 public override bool DefineMembers (TypeContainer container)
1309 if (members_defined)
1310 return members_defined_ok;
1312 members_defined_ok = DoDefineMembers ();
1313 members_defined = true;
1315 return members_defined_ok;
1318 bool DoDefineMembers ()
1321 // We need to be able to use the member cache while we are checking/defining
1323 if (TypeBuilder.BaseType != null)
1324 parent_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
1326 if (TypeBuilder.IsInterface)
1327 parent_cache = TypeManager.LookupParentInterfacesCache (TypeBuilder);
1330 if ((ModFlags & Modifiers.NEW) != 0)
1331 Error_KeywordNotAllowed (Location);
1333 // HACK: missing implemenation
1334 // This is not fully functional. Better way how to handle this is to have recursive definition of containers
1335 // instead of flat as we have now.
1336 // Now we are not able to check inner attribute class because its parent had not been defined.
1338 // TODO: remove this if
1339 if (Parent.MemberCache != null) {
1340 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1341 if (conflict_symbol == null) {
1342 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1343 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1345 if ((ModFlags & Modifiers.NEW) == 0) {
1346 Report.SymbolRelatedToPreviousError (conflict_symbol);
1347 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1353 DefineContainerMembers (constants);
1354 DefineContainerMembers (fields);
1356 if ((Kind == Kind.Class) && !(this is ClassPart) && !(this is StaticClass)){
1357 if ((instance_constructors == null) &&
1358 !(this is StaticClass)) {
1359 if (default_constructor == null)
1360 DefineDefaultConstructor (false);
1363 if (initialized_static_fields != null &&
1364 default_static_constructor == null)
1365 DefineDefaultConstructor (true);
1368 if (Kind == Kind.Struct){
1370 // Structs can not have initialized instance
1373 if (initialized_static_fields != null &&
1374 default_static_constructor == null)
1375 DefineDefaultConstructor (true);
1377 if (initialized_fields != null)
1378 ReportStructInitializedInstanceError ();
1381 Pending = GetPendingImplementations ();
1383 if (parts != null) {
1384 foreach (ClassPart part in parts) {
1385 if (!part.DefineMembers (this))
1391 // Constructors are not in the defined_names array
1393 DefineContainerMembers (instance_constructors);
1395 if (default_static_constructor != null)
1396 default_static_constructor.Define ();
1398 DefineContainerMembers (properties);
1399 DefineContainerMembers (events);
1400 DefineContainerMembers (indexers);
1401 DefineContainerMembers (methods);
1402 DefineContainerMembers (operators);
1403 DefineContainerMembers (enums);
1404 DefineContainerMembers (delegates);
1407 if (!(this is ClassPart))
1408 member_cache = new MemberCache (this);
1411 if (parts != null) {
1412 foreach (ClassPart part in parts)
1413 part.member_cache = member_cache;
1416 if (iterators != null) {
1417 foreach (Iterator iterator in iterators) {
1418 if (iterator.DefineType () == null)
1422 foreach (Iterator iterator in iterators) {
1423 if (!iterator.DefineMembers (this))
1431 void ReportStructInitializedInstanceError ()
1433 string n = TypeBuilder.FullName;
1435 foreach (Field f in initialized_fields){
1438 "`" + n + "." + f.Name + "': can not have " +
1439 "instance field initializers in structs");
1443 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1446 mcal.DefineContainerMembers ();
1449 public override bool Define ()
1451 if (parts != null) {
1452 foreach (ClassPart part in parts) {
1453 if (!part.Define ())
1461 public MemberInfo FindMemberWithSameName (string name, bool ignore_methods)
1463 return ParentCache.FindMemberWithSameName (name, ignore_methods, null);
1467 /// This function is based by a delegate to the FindMembers routine
1469 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1475 /// This filter is used by FindMembers, and we just keep
1476 /// a global for the filter to `AlwaysAccept'
1478 static MemberFilter accepting_filter;
1481 static TypeContainer ()
1483 accepting_filter = new MemberFilter (AlwaysAccept);
1486 public MethodInfo[] GetMethods ()
1488 ArrayList members = new ArrayList ();
1490 DefineMembers (null);
1492 if (methods != null) {
1493 int len = methods.Count;
1494 for (int i = 0; i < len; i++) {
1495 Method m = (Method) methods [i];
1497 members.Add (m.MethodBuilder);
1501 if (operators != null) {
1502 int len = operators.Count;
1503 for (int i = 0; i < len; i++) {
1504 Operator o = (Operator) operators [i];
1506 members.Add (o.OperatorMethodBuilder);
1510 if (properties != null) {
1511 int len = properties.Count;
1512 for (int i = 0; i < len; i++) {
1513 Property p = (Property) properties [i];
1515 if (p.GetBuilder != null)
1516 members.Add (p.GetBuilder);
1517 if (p.SetBuilder != null)
1518 members.Add (p.SetBuilder);
1522 if (indexers != null) {
1523 int len = indexers.Count;
1524 for (int i = 0; i < len; i++) {
1525 Indexer ix = (Indexer) indexers [i];
1527 if (ix.GetBuilder != null)
1528 members.Add (ix.GetBuilder);
1529 if (ix.SetBuilder != null)
1530 members.Add (ix.SetBuilder);
1534 if (events != null) {
1535 int len = events.Count;
1536 for (int i = 0; i < len; i++) {
1537 Event e = (Event) events [i];
1539 if (e.AddBuilder != null)
1540 members.Add (e.AddBuilder);
1541 if (e.RemoveBuilder != null)
1542 members.Add (e.RemoveBuilder);
1546 MethodInfo[] retMethods = new MethodInfo [members.Count];
1547 members.CopyTo (retMethods, 0);
1551 // Indicated whether container has StructLayout attribute set Explicit
1552 public virtual bool HasExplicitLayout {
1559 /// This method returns the members of this type just like Type.FindMembers would
1560 /// Only, we need to use this for types which are _being_ defined because MS'
1561 /// implementation can't take care of that.
1564 // FIXME: return an empty static array instead of null, that cleans up
1565 // some code and is consistent with some coding conventions I just found
1569 // Notice that in various cases we check if our field is non-null,
1570 // something that would normally mean that there was a bug elsewhere.
1572 // The problem happens while we are defining p-invoke methods, as those
1573 // will trigger a FindMembers, but this happens before things are defined
1575 // Since the whole process is a no-op, it is fine to check for null here.
1577 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1578 MemberFilter filter, object criteria)
1580 ArrayList members = null;
1583 if ((bf & BindingFlags.Public) != 0)
1584 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1586 if ((bf & BindingFlags.NonPublic) != 0)
1587 modflags |= Modifiers.PRIVATE;
1589 int static_mask = 0, static_flags = 0;
1590 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1591 case BindingFlags.Static:
1592 static_mask = static_flags = Modifiers.STATIC;
1595 case BindingFlags.Instance:
1596 static_mask = Modifiers.STATIC;
1601 static_mask = static_flags = 0;
1605 Timer.StartTimer (TimerType.TcFindMembers);
1608 filter = accepting_filter;
1610 if ((mt & MemberTypes.Field) != 0) {
1611 if (fields != null) {
1612 int len = fields.Count;
1613 for (int i = 0; i < len; i++) {
1614 Field f = (Field) fields [i];
1616 if ((f.ModFlags & modflags) == 0)
1618 if ((f.ModFlags & static_mask) != static_flags)
1621 FieldBuilder fb = f.FieldBuilder;
1622 if (fb != null && filter (fb, criteria) == true) {
1623 if (members == null)
1624 members = new ArrayList ();
1631 if (constants != null) {
1632 int len = constants.Count;
1633 for (int i = 0; i < len; i++) {
1634 Const con = (Const) constants [i];
1636 if ((con.ModFlags & modflags) == 0)
1638 if ((con.ModFlags & static_mask) != static_flags)
1641 FieldBuilder fb = con.FieldBuilder;
1642 if (fb != null && filter (fb, criteria) == true) {
1643 if (members == null)
1644 members = new ArrayList ();
1652 if ((mt & MemberTypes.Method) != 0) {
1653 if (methods != null) {
1654 int len = methods.Count;
1655 for (int i = 0; i < len; i++) {
1656 Method m = (Method) methods [i];
1658 if ((m.ModFlags & modflags) == 0)
1660 if ((m.ModFlags & static_mask) != static_flags)
1663 MethodBuilder mb = m.MethodBuilder;
1665 if (mb != null && filter (mb, criteria) == true) {
1666 if (members == null)
1667 members = new ArrayList ();
1674 if (operators != null) {
1675 int len = operators.Count;
1676 for (int i = 0; i < len; i++) {
1677 Operator o = (Operator) operators [i];
1679 if ((o.ModFlags & modflags) == 0)
1681 if ((o.ModFlags & static_mask) != static_flags)
1684 MethodBuilder ob = o.OperatorMethodBuilder;
1685 if (ob != null && filter (ob, criteria) == true) {
1686 if (members == null)
1687 members = new ArrayList ();
1694 if (properties != null) {
1695 int len = properties.Count;
1696 for (int i = 0; i < len; i++) {
1697 Property p = (Property) properties [i];
1699 if ((p.ModFlags & modflags) == 0)
1701 if ((p.ModFlags & static_mask) != static_flags)
1707 if (b != null && filter (b, criteria) == true) {
1708 if (members == null)
1709 members = new ArrayList ();
1715 if (b != null && filter (b, criteria) == true) {
1716 if (members == null)
1717 members = new ArrayList ();
1724 if (indexers != null) {
1725 int len = indexers.Count;
1726 for (int i = 0; i < len; i++) {
1727 Indexer ix = (Indexer) indexers [i];
1729 if ((ix.ModFlags & modflags) == 0)
1731 if ((ix.ModFlags & static_mask) != static_flags)
1737 if (b != null && filter (b, criteria) == true) {
1738 if (members == null)
1739 members = new ArrayList ();
1745 if (b != null && filter (b, criteria) == true) {
1746 if (members == null)
1747 members = new ArrayList ();
1755 if ((mt & MemberTypes.Event) != 0) {
1756 if (events != null) {
1757 int len = events.Count;
1758 for (int i = 0; i < len; i++) {
1759 Event e = (Event) events [i];
1761 if ((e.ModFlags & modflags) == 0)
1763 if ((e.ModFlags & static_mask) != static_flags)
1766 MemberInfo eb = e.EventBuilder;
1767 if (eb != null && filter (eb, criteria) == true) {
1768 if (members == null)
1769 members = new ArrayList ();
1771 members.Add (e.EventBuilder);
1777 if ((mt & MemberTypes.Property) != 0){
1778 if (properties != null) {
1779 int len = properties.Count;
1780 for (int i = 0; i < len; i++) {
1781 Property p = (Property) properties [i];
1783 if ((p.ModFlags & modflags) == 0)
1785 if ((p.ModFlags & static_mask) != static_flags)
1788 MemberInfo pb = p.PropertyBuilder;
1789 if (pb != null && filter (pb, criteria) == true) {
1790 if (members == null)
1791 members = new ArrayList ();
1793 members.Add (p.PropertyBuilder);
1798 if (indexers != null) {
1799 int len = indexers.Count;
1800 for (int i = 0; i < len; i++) {
1801 Indexer ix = (Indexer) indexers [i];
1803 if ((ix.ModFlags & modflags) == 0)
1805 if ((ix.ModFlags & static_mask) != static_flags)
1808 MemberInfo ib = ix.PropertyBuilder;
1809 if (ib != null && filter (ib, criteria) == true) {
1810 if (members == null)
1811 members = new ArrayList ();
1813 members.Add (ix.PropertyBuilder);
1819 if ((mt & MemberTypes.NestedType) != 0) {
1820 if (types != null) {
1821 int len = types.Count;
1822 for (int i = 0; i < len; i++) {
1823 TypeContainer t = (TypeContainer) types [i];
1825 if ((t.ModFlags & modflags) == 0)
1828 TypeBuilder tb = t.TypeBuilder;
1829 if (tb != null && (filter (tb, criteria) == true)) {
1830 if (members == null)
1831 members = new ArrayList ();
1838 if (enums != null) {
1839 int len = enums.Count;
1840 for (int i = 0; i < len; i++) {
1841 Enum en = (Enum) enums [i];
1843 if ((en.ModFlags & modflags) == 0)
1846 TypeBuilder tb = en.TypeBuilder;
1847 if (tb != null && (filter (tb, criteria) == true)) {
1848 if (members == null)
1849 members = new ArrayList ();
1856 if (delegates != null) {
1857 int len = delegates.Count;
1858 for (int i = 0; i < len; i++) {
1859 Delegate d = (Delegate) delegates [i];
1861 if ((d.ModFlags & modflags) == 0)
1864 TypeBuilder tb = d.TypeBuilder;
1865 if (tb != null && (filter (tb, criteria) == true)) {
1866 if (members == null)
1867 members = new ArrayList ();
1874 if (interfaces != null) {
1875 int len = interfaces.Count;
1876 for (int i = 0; i < len; i++) {
1877 TypeContainer iface = (TypeContainer) interfaces [i];
1879 if ((iface.ModFlags & modflags) == 0)
1882 TypeBuilder tb = iface.TypeBuilder;
1883 if (tb != null && (filter (tb, criteria) == true)) {
1884 if (members == null)
1885 members = new ArrayList ();
1893 if ((mt & MemberTypes.Constructor) != 0){
1894 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1895 int len = instance_constructors.Count;
1896 for (int i = 0; i < len; i++) {
1897 Constructor c = (Constructor) instance_constructors [i];
1899 ConstructorBuilder cb = c.ConstructorBuilder;
1900 if (cb != null && filter (cb, criteria) == true) {
1901 if (members == null)
1902 members = new ArrayList ();
1909 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1910 ConstructorBuilder cb =
1911 default_static_constructor.ConstructorBuilder;
1913 if (cb != null && filter (cb, criteria) == true) {
1914 if (members == null)
1915 members = new ArrayList ();
1923 // Lookup members in parent if requested.
1925 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1926 if (TypeBuilder.BaseType != null) {
1927 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1928 if (list.Count > 0) {
1929 if (members == null)
1930 members = new ArrayList ();
1932 members.AddRange (list);
1935 if (ifaces != null) {
1936 foreach (Type base_type in ifaces) {
1937 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1939 if (list.Count > 0) {
1940 if (members == null)
1941 members = new ArrayList ();
1942 members.AddRange (list);
1948 Timer.StopTimer (TimerType.TcFindMembers);
1950 if (members == null)
1951 return MemberList.Empty;
1953 return new MemberList (members);
1956 public override MemberCache MemberCache {
1958 return member_cache;
1962 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1963 MemberFilter filter, object criteria)
1965 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1968 return ds.FindMembers (mt, bf, filter, criteria);
1970 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1975 // FindMethods will look for methods not only in the type `t', but in
1976 // any interfaces implemented by the type.
1978 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1979 MemberFilter filter, object criteria)
1985 /// Emits the values for the constants
1987 public void EmitConstants ()
1989 if (constants != null)
1990 foreach (Const con in constants)
1995 protected virtual void VerifyMembers (EmitContext ec)
1998 // Check for internal or private fields that were never assigned
2000 if (RootContext.WarningLevel >= 3) {
2001 if (fields != null){
2002 foreach (Field f in fields) {
2003 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2006 if ((f.status & Field.Status.USED) == 0){
2007 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2012 // Only report 649 on level 4
2014 if (RootContext.WarningLevel < 4)
2017 if ((f.status & Field.Status.ASSIGNED) != 0)
2020 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2027 /// Emits the code, this step is performed after all
2028 /// the types, enumerations, constructors
2030 public void EmitType ()
2032 if (OptAttributes != null)
2033 OptAttributes.Emit (ec, this);
2037 if (instance_constructors != null) {
2038 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2039 bool has_compliant_args = false;
2041 foreach (Constructor c in instance_constructors) {
2044 if (has_compliant_args)
2047 has_compliant_args = c.HasCompliantArgs;
2049 if (!has_compliant_args)
2050 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2052 foreach (Constructor c in instance_constructors)
2059 if (default_static_constructor != null)
2060 default_static_constructor.Emit ();
2062 if (methods != null)
2063 foreach (Method m in methods)
2066 if (operators != null)
2067 foreach (Operator o in operators)
2070 if (properties != null)
2071 foreach (Property p in properties)
2074 if (indexers != null){
2079 foreach (Field f in fields)
2082 if (events != null){
2083 foreach (Event e in Events)
2087 if (delegates != null) {
2088 foreach (Delegate d in Delegates) {
2093 if (enums != null) {
2094 foreach (Enum e in enums) {
2099 if (parts != null) {
2100 foreach (ClassPart part in parts)
2104 if ((Pending != null) && !(this is ClassPart))
2105 if (Pending.VerifyPendingMethods ())
2110 if (iterators != null)
2111 foreach (Iterator iterator in iterators)
2112 iterator.EmitType ();
2114 // if (types != null)
2115 // foreach (TypeContainer tc in types)
2119 public override void CloseType ()
2121 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2125 caching_flags |= Flags.CloseTypeCreated;
2126 TypeBuilder.CreateType ();
2127 } catch (TypeLoadException){
2129 // This is fine, the code still created the type
2131 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2132 // Console.WriteLine (e.Message);
2134 Console.WriteLine ("In type: " + Name);
2139 foreach (Enum en in Enums)
2143 foreach (TypeContainer tc in Types)
2144 if (tc.Kind == Kind.Struct)
2147 foreach (TypeContainer tc in Types)
2148 if (tc.Kind != Kind.Struct)
2152 if (Delegates != null)
2153 foreach (Delegate d in Delegates)
2156 if (Iterators != null)
2157 foreach (Iterator i in Iterators)
2165 initialized_fields = null;
2166 initialized_static_fields = null;
2175 default_constructor = null;
2176 default_static_constructor = null;
2178 OptAttributes = null;
2180 parent_cache = null;
2181 member_cache = null;
2184 // TODO: make it obsolete and use GetSignatureForError
2185 public string MakeName (string n)
2187 return "`" + Name + "." + n + "'";
2191 // Performs the validation on a Method's modifiers (properties have
2192 // the same properties).
2194 public bool MethodModifiersValid (MemberCore mc)
2196 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2197 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2198 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2200 int flags = mc.ModFlags;
2203 // At most one of static, virtual or override
2205 if ((flags & Modifiers.STATIC) != 0){
2206 if ((flags & vao) != 0){
2207 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2208 GetSignatureForError ());
2213 if (Kind == Kind.Struct){
2214 if ((flags & va) != 0){
2215 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2220 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2221 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2226 // If the declaration includes the abstract modifier, then the
2227 // declaration does not include static, virtual or extern
2229 if ((flags & Modifiers.ABSTRACT) != 0){
2230 if ((flags & Modifiers.EXTERN) != 0){
2232 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2236 if ((flags & Modifiers.SEALED) != 0) {
2237 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2241 if ((flags & Modifiers.VIRTUAL) != 0){
2242 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2246 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2247 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2252 if ((flags & Modifiers.PRIVATE) != 0){
2253 if ((flags & vao) != 0){
2254 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2259 if ((flags & Modifiers.SEALED) != 0){
2260 if ((flags & Modifiers.OVERRIDE) == 0){
2261 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2269 public bool UserDefinedStaticConstructor {
2271 return default_static_constructor != null;
2275 public Constructor DefaultStaticConstructor {
2276 get { return default_static_constructor; }
2279 protected override bool VerifyClsCompliance (DeclSpace ds)
2281 if (!base.VerifyClsCompliance (ds))
2286 Type base_type = TypeBuilder.BaseType;
2287 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2288 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2291 if (!Parent.IsClsCompliaceRequired (ds)) {
2292 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2293 GetSignatureForError (), Parent.GetSignatureForError ());
2300 /// Checks whether container name is CLS Compliant
2302 void VerifyClsName ()
2304 Hashtable parent_members = parent_cache == null ?
2306 parent_cache.GetPublicMembers ();
2307 Hashtable this_members = new Hashtable ();
2309 foreach (DictionaryEntry entry in defined_names) {
2310 MemberCore mc = (MemberCore)entry.Value;
2311 if (!mc.IsClsCompliaceRequired (this))
2314 string name = (string)entry.Key;
2315 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2317 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2318 object found = parent_members [lcase];
2319 if (found == null) {
2320 found = this_members [lcase];
2321 if (found == null) {
2322 this_members.Add (lcase, mc);
2327 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2330 if (found is MemberInfo) {
2331 if (basename == ((MemberInfo)found).Name)
2333 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2335 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2337 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2343 /// Performs checks for an explicit interface implementation. First it
2344 /// checks whether the `interface_type' is a base inteface implementation.
2345 /// Then it checks whether `name' exists in the interface type.
2347 public virtual bool VerifyImplements (Type interface_type, string full,
2348 string name, Location loc)
2352 if (ifaces != null){
2353 foreach (Type t in ifaces){
2354 if (t == interface_type){
2362 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2363 full, interface_type.FullName);
2370 protected override void VerifyObsoleteAttribute()
2372 CheckUsageOfObsoleteAttribute (ptype);
2377 foreach (Type iface in ifaces) {
2378 CheckUsageOfObsoleteAttribute (iface);
2387 string IMemberContainer.Name {
2393 Type IMemberContainer.Type {
2399 MemberCache IMemberContainer.MemberCache {
2401 return member_cache;
2405 bool IMemberContainer.IsInterface {
2407 return Kind == Kind.Interface;
2411 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2413 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2417 // Generates xml doc comments (if any), and if required,
2418 // handle warning report.
2420 internal override void GenerateDocComment (DeclSpace ds)
2422 DocUtil.GenerateTypeDocComment (this, ds);
2425 public override string DocCommentHeader {
2426 get { return "T:"; }
2429 public virtual MemberCache ParentCache {
2431 return parent_cache;
2436 public class PartialContainer : TypeContainer {
2438 public readonly Namespace Namespace;
2439 public readonly int OriginalModFlags;
2440 public readonly int AllowedModifiers;
2441 public readonly TypeAttributes DefaultTypeAttributes;
2443 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2444 MemberName member_name, int mod_flags, Kind kind,
2447 PartialContainer pc;
2448 string full_name = member_name.GetName (true);
2449 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2451 pc = ds as PartialContainer;
2455 260, ds.Location, "Missing partial modifier " +
2456 "on declaration of type `{0}'; another " +
2457 "partial implementation of this type exists",
2458 member_name.GetPartialName());
2460 Report.LocationOfPreviousError (loc);
2464 if (pc.Kind != kind) {
2466 261, loc, "Partial declarations of `{0}' " +
2467 "must be all classes, all structs or " +
2468 "all interfaces", member_name.GetPartialName ());
2472 if (pc.OriginalModFlags != mod_flags) {
2474 262, loc, "Partial declarations of `{0}' " +
2475 "have conflicting accessibility modifiers",
2476 member_name.GetPartialName ());
2483 pc = new PartialContainer (ns, parent, member_name, mod_flags, kind, loc);
2484 RootContext.Tree.RecordDecl (full_name, pc);
2485 parent.AddType (pc);
2490 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2491 MemberName name, int mod, Attributes attrs,
2492 Kind kind, Location loc)
2494 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2496 // An error occured; create a dummy container, but don't
2498 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2501 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2506 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2507 MemberName name, int mod, Kind kind, Location l)
2508 : base (ns, parent, name, null, kind, l)
2510 this.Namespace = ns.NS;
2514 AllowedModifiers = Class.AllowedModifiers;
2515 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2519 AllowedModifiers = Struct.AllowedModifiers;
2520 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2523 case Kind.Interface:
2524 AllowedModifiers = Interface.AllowedModifiers;
2525 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2529 throw new InvalidOperationException ();
2533 if (parent.Parent == null)
2534 accmods = Modifiers.INTERNAL;
2536 accmods = Modifiers.PRIVATE;
2538 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2539 this.OriginalModFlags = mod;
2542 public override void Register ()
2544 if (Kind == Kind.Interface)
2545 Parent.AddInterface (this);
2546 else if (Kind == Kind.Class || Kind == Kind.Struct)
2547 Parent.AddClassOrStruct (this);
2549 throw new InvalidOperationException ();
2552 public override PendingImplementation GetPendingImplementations ()
2554 return PendingImplementation.GetPendingImplementations (this);
2557 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2560 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2565 public override TypeAttributes TypeAttr {
2567 return base.TypeAttr | DefaultTypeAttributes;
2572 public class ClassPart : TypeContainer, IMemberContainer {
2573 public readonly PartialContainer PartialContainer;
2574 public readonly bool IsPartial;
2576 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2577 int mod, Attributes attrs, Kind kind, Location l)
2578 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2580 this.PartialContainer = parent;
2581 this.IsPartial = true;
2584 if (parent.Parent == null)
2585 accmods = Modifiers.INTERNAL;
2587 accmods = Modifiers.PRIVATE;
2589 this.ModFlags = Modifiers.Check (
2590 parent.AllowedModifiers, mod, accmods, l);
2593 public override void Register ()
2597 public override PendingImplementation GetPendingImplementations ()
2599 return PartialContainer.Pending;
2602 public override bool VerifyImplements (Type interface_type, string full,
2603 string name, Location loc)
2605 return PartialContainer.VerifyImplements (
2606 interface_type, full, name, loc);
2609 public override MemberCache ParentCache {
2611 return PartialContainer.ParentCache;
2616 public abstract class ClassOrStruct : TypeContainer {
2617 bool hasExplicitLayout = false;
2618 ListDictionary declarative_security;
2620 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2621 MemberName name, Attributes attrs, Kind kind,
2623 : base (ns, parent, name, attrs, kind, l)
2627 public override PendingImplementation GetPendingImplementations ()
2629 return PendingImplementation.GetPendingImplementations (this);
2632 public override bool HasExplicitLayout {
2634 return hasExplicitLayout;
2638 protected override void VerifyMembers (EmitContext ec)
2640 base.VerifyMembers (ec);
2642 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2643 foreach (Event e in events){
2645 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2650 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2652 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2653 if (declarative_security == null)
2654 declarative_security = new ListDictionary ();
2656 a.ExtractSecurityPermissionSet (declarative_security);
2660 if (a.Type == TypeManager.struct_layout_attribute_type
2661 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2662 hasExplicitLayout = true;
2664 base.ApplyAttributeBuilder (a, cb);
2667 public override void Emit()
2671 if (declarative_security != null) {
2672 foreach (DictionaryEntry de in declarative_security) {
2673 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2678 public override void Register ()
2680 Parent.AddClassOrStruct (this);
2685 /// Class handles static classes declaration
2687 public sealed class StaticClass: Class {
2688 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2689 Attributes attrs, Location l)
2690 : base (ns, parent, name, mod, attrs, l)
2692 if (RootContext.Version == LanguageVersion.ISO_1) {
2693 Report.FeatureIsNotStandardized (l, "static classes");
2694 Environment.Exit (1);
2698 protected override int AllowedModifiersProp {
2700 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2701 Modifiers.STATIC | Modifiers.UNSAFE;
2705 protected override void DefineContainerMembers (MemberCoreArrayList list)
2710 foreach (MemberCore m in list) {
2711 if (m is Operator) {
2712 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2716 if ((m.ModFlags & Modifiers.STATIC) != 0)
2719 if (m is Constructor) {
2720 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2724 if (m is Destructor) {
2725 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2729 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2732 base.DefineContainerMembers (list);
2735 public override TypeBuilder DefineType()
2737 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2738 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2742 TypeBuilder tb = base.DefineType ();
2746 if (ptype != TypeManager.object_type) {
2747 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2751 if (ifaces != null) {
2752 foreach (Type t in ifaces)
2753 Report.SymbolRelatedToPreviousError (t);
2754 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2759 public override TypeAttributes TypeAttr {
2761 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2766 public class Class : ClassOrStruct {
2767 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2768 public const int AllowedModifiers =
2771 Modifiers.PROTECTED |
2772 Modifiers.INTERNAL |
2774 Modifiers.ABSTRACT |
2778 // Information in the case we are an attribute type
2779 AttributeUsageAttribute attribute_usage;
2781 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2782 Attributes attrs, Location l)
2783 : base (ns, parent, name, attrs, Kind.Class, l)
2785 this.ModFlags = mod;
2786 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2789 virtual protected int AllowedModifiersProp {
2791 return AllowedModifiers;
2795 public override AttributeTargets AttributeTargets {
2797 return AttributeTargets.Class;
2801 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2803 if (a.UsageAttribute != null) {
2804 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2805 TypeBuilder.FullName != "System.Attribute") {
2806 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2808 attribute_usage = a.UsageAttribute;
2811 base.ApplyAttributeBuilder (a, cb);
2814 public AttributeUsageAttribute AttributeUsage {
2816 return attribute_usage;
2820 public const TypeAttributes DefaultTypeAttributes =
2821 TypeAttributes.AutoLayout | TypeAttributes.Class;
2823 public override TypeBuilder DefineType()
2825 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2826 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2830 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2831 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2833 return base.DefineType ();
2837 // FIXME: How do we deal with the user specifying a different
2840 public override TypeAttributes TypeAttr {
2842 return base.TypeAttr | DefaultTypeAttributes;
2847 public class Struct : ClassOrStruct {
2849 // Modifiers allowed in a struct declaration
2851 public const int AllowedModifiers =
2854 Modifiers.PROTECTED |
2855 Modifiers.INTERNAL |
2859 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2860 int mod, Attributes attrs, Location l)
2861 : base (ns, parent, name, attrs, Kind.Struct, l)
2865 if (parent.Parent == null)
2866 accmods = Modifiers.INTERNAL;
2868 accmods = Modifiers.PRIVATE;
2870 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2872 this.ModFlags |= Modifiers.SEALED;
2875 public override AttributeTargets AttributeTargets {
2877 return AttributeTargets.Struct;
2881 public const TypeAttributes DefaultTypeAttributes =
2882 TypeAttributes.SequentialLayout |
2883 TypeAttributes.Sealed |
2884 TypeAttributes.BeforeFieldInit;
2887 // FIXME: Allow the user to specify a different set of attributes
2888 // in some cases (Sealed for example is mandatory for a class,
2889 // but what SequentialLayout can be changed
2891 public override TypeAttributes TypeAttr {
2893 return base.TypeAttr | DefaultTypeAttributes;
2901 public class Interface : TypeContainer, IMemberContainer {
2903 /// Modifiers allowed in a class declaration
2905 public const int AllowedModifiers =
2908 Modifiers.PROTECTED |
2909 Modifiers.INTERNAL |
2913 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2914 Attributes attrs, Location l)
2915 : base (ns, parent, name, attrs, Kind.Interface, l)
2919 if (parent.Parent == null)
2920 accmods = Modifiers.INTERNAL;
2922 accmods = Modifiers.PRIVATE;
2924 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2927 public override void Register ()
2929 Parent.AddInterface (this);
2932 public override PendingImplementation GetPendingImplementations ()
2937 public override AttributeTargets AttributeTargets {
2939 return AttributeTargets.Interface;
2943 public const TypeAttributes DefaultTypeAttributes =
2944 TypeAttributes.AutoLayout |
2945 TypeAttributes.Abstract |
2946 TypeAttributes.Interface;
2948 public override TypeAttributes TypeAttr {
2950 return base.TypeAttr | DefaultTypeAttributes;
2955 public abstract class MethodCore : MemberBase {
2956 public readonly Parameters Parameters;
2957 protected ToplevelBlock block;
2960 // Parameters, cached for semantic analysis.
2962 protected InternalParameters parameter_info;
2963 protected Type [] parameter_types;
2965 // Whether this is an operator method.
2966 public bool IsOperator;
2969 // The method we're overriding if this is an override method.
2971 protected MethodInfo parent_method = null;
2973 static string[] attribute_targets = new string [] { "method", "return" };
2975 public MethodCore (TypeContainer parent, Expression type, int mod,
2976 int allowed_mod, bool is_interface, MemberName name,
2977 Attributes attrs, Parameters parameters, Location loc)
2978 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
2981 Parameters = parameters;
2982 IsInterface = is_interface;
2986 // Returns the System.Type array for the parameters of this method
2988 public Type [] ParameterTypes {
2990 return parameter_types;
2994 public InternalParameters ParameterInfo
2997 return parameter_info;
3001 public ToplevelBlock Block {
3011 protected override bool CheckBase ()
3013 if (!base.CheckBase ())
3016 // Check whether arguments were correct.
3017 if (!DoDefineParameters ())
3020 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3026 // Is null for System.Object while compiling corlib and base interfaces
3027 if (Parent.ParentCache == null) {
3028 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3029 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3034 Type parent_ret_type = null;
3035 parent_method = FindOutParentMethod (Parent, ref parent_ret_type);
3037 // method is override
3038 if (parent_method != null) {
3040 if (!CheckMethodAgainstBase ())
3043 if ((ModFlags & Modifiers.NEW) == 0) {
3044 if (MemberType != TypeManager.TypeToCoreType (parent_ret_type)) {
3045 Report.SymbolRelatedToPreviousError (parent_method);
3046 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3047 "change return type when overriding inherited member");
3051 if (parent_method.IsAbstract && !IsInterface) {
3052 Report.SymbolRelatedToPreviousError (parent_method);
3053 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3058 if (parent_method.IsSpecialName && !(this is PropertyBase)) {
3059 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (parent_method));
3063 if (RootContext.WarningLevel > 2) {
3064 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3065 Parent.Methods.HasEquals = true;
3066 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3067 Parent.Methods.HasGetHashCode = true;
3070 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (parent_method);
3072 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3073 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3074 Report.SymbolRelatedToPreviousError (parent_method);
3075 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3081 MemberInfo conflict_symbol = Parent.FindMemberWithSameName (Name, !(this is Property));
3082 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3083 if (conflict_symbol != null) {
3084 Report.SymbolRelatedToPreviousError (conflict_symbol);
3085 if (this is PropertyBase)
3086 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3088 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3090 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3094 if (conflict_symbol == null) {
3095 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3096 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3101 if ((ModFlags & Modifiers.NEW) == 0) {
3102 if (this is Method && conflict_symbol is MethodBase)
3105 Report.SymbolRelatedToPreviousError (conflict_symbol);
3106 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3114 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3115 // that have been defined.
3117 // `name' is the user visible name for reporting errors (this is used to
3118 // provide the right name regarding method names and properties)
3120 bool CheckMethodAgainstBase ()
3124 // TODO: replace with GetSignatureForError
3125 string name = parent_method.DeclaringType.Name + "." + parent_method.Name;
3127 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3128 if (!(parent_method.IsAbstract || parent_method.IsVirtual)){
3130 506, Location, Parent.MakeName (Name) +
3131 ": cannot override inherited member `" +
3132 name + "' because it is not " +
3133 "virtual, abstract or override");
3137 // Now we check that the overriden method is not final
3139 if (parent_method.IsFinal) {
3140 // This happens when implementing interface methods.
3141 if (parent_method.IsHideBySig && parent_method.IsVirtual) {
3143 506, Location, Parent.MakeName (Name) +
3144 ": cannot override inherited member `" +
3145 name + "' because it is not " +
3146 "virtual, abstract or override");
3148 Report.Error (239, Location, Parent.MakeName (Name) + " : cannot " +
3149 "override inherited member `" + name +
3150 "' because it is sealed.");
3154 // Check that the permissions are not being changed
3156 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3157 MethodAttributes parentp = parent_method.Attributes & MethodAttributes.MemberAccessMask;
3159 if (!CheckAccessModifiers (thisp, parentp, parent_method)) {
3160 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3165 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3166 ModFlags |= Modifiers.NEW;
3167 Report.SymbolRelatedToPreviousError (parent_method);
3168 if (!IsInterface && (parent_method.IsVirtual || parent_method.IsAbstract)) {
3169 if (RootContext.WarningLevel >= 2)
3170 Report.Warning (114, Location, "'{0}' hides inherited member '{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword", GetSignatureForError (Parent), TypeManager.CSharpSignature (parent_method));
3172 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3178 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes parentp, MethodInfo base_method)
3180 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3182 // when overriding protected internal, the method can be declared
3183 // protected internal only within the same assembly
3186 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3187 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3189 // assemblies differ - report an error
3193 } else if (thisp != parentp) {
3195 // same assembly, but other attributes differ - report an error
3200 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3202 // if it's not "protected internal", it must be "protected"
3206 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3208 // protected within the same assembly - an error
3211 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3212 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3214 // protected ok, but other attributes differ - report an error
3220 return (thisp == parentp);
3224 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method, string name)
3227 // FIXME: report the old/new permissions?
3230 507, Location, parent.MakeName (Name) +
3231 ": can't change the access modifiers when overriding inherited " +
3232 "member `" + name + "'");
3235 protected static string Error722 {
3237 return "'{0}': static types cannot be used as return types";
3242 /// For custom member duplication search in a container
3244 protected abstract bool CheckForDuplications ();
3247 /// Gets parent method and its return type
3249 protected abstract MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type);
3251 protected virtual bool DoDefineParameters ()
3253 EmitContext ec = Parent.EmitContext;
3255 throw new InternalErrorException ("DoDefineParameters invoked too early");
3257 bool old_unsafe = ec.InUnsafe;
3258 ec.InUnsafe = InUnsafe;
3259 // Check if arguments were correct
3260 parameter_types = Parameters.GetParameterInfo (ec);
3261 ec.InUnsafe = old_unsafe;
3263 if ((parameter_types == null) ||
3264 !CheckParameters (Parent, parameter_types))
3267 parameter_info = new InternalParameters (parameter_types, Parameters);
3269 Parameter array_param = Parameters.ArrayParameter;
3270 if ((array_param != null) &&
3271 (!array_param.ParameterType.IsArray ||
3272 (array_param.ParameterType.GetArrayRank () != 1))) {
3273 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3280 public override string[] ValidAttributeTargets {
3282 return attribute_targets;
3286 protected override bool VerifyClsCompliance (DeclSpace ds)
3288 if (!base.VerifyClsCompliance (ds)) {
3289 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3290 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3295 if (Parameters.HasArglist) {
3296 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3299 if (!AttributeTester.IsClsCompliant (MemberType)) {
3300 if (this is PropertyBase)
3301 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3302 GetSignatureForError ());
3304 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3305 GetSignatureForError ());
3308 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3313 protected bool IsDuplicateImplementation (MethodCore method)
3315 if ((method == this) || (method.Name != Name))
3318 Type[] param_types = method.ParameterTypes;
3319 if (param_types == null)
3322 if (param_types.Length != ParameterTypes.Length)
3325 for (int i = 0; i < param_types.Length; i++)
3326 if (param_types [i] != ParameterTypes [i])
3329 // TODO: make operator compatible with MethodCore to avoid this
3330 if (this is Operator && method is Operator) {
3331 if (MemberType != method.MemberType)
3336 // Try to report 663: method only differs on out/ref
3338 ParameterData info = ParameterInfo;
3339 ParameterData other_info = method.ParameterInfo;
3340 for (int i = 0; i < info.Count; i++){
3341 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3342 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3347 Report.SymbolRelatedToPreviousError (method);
3348 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3353 // Returns a string that represents the signature for this
3354 // member which should be used in XML documentation.
3356 public override string GetDocCommentName (DeclSpace ds)
3358 return DocUtil.GetMethodDocCommentName (this, ds);
3362 // Raised (and passed an XmlElement that contains the comment)
3363 // when GenerateDocComment is writing documentation expectedly.
3365 // FIXME: with a few effort, it could be done with XmlReader,
3366 // that means removal of DOM use.
3368 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3370 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3374 // Represents header string for documentation comment.
3376 public override string DocCommentHeader {
3377 get { return "M:"; }
3380 protected override void VerifyObsoleteAttribute()
3382 base.VerifyObsoleteAttribute ();
3384 if (parameter_types == null)
3387 foreach (Type type in parameter_types) {
3388 CheckUsageOfObsoleteAttribute (type);
3393 public class SourceMethod : ISourceMethod
3395 TypeContainer container;
3398 protected SourceMethod (TypeContainer container, MethodBase builder,
3399 ISourceFile file, Location start, Location end)
3401 this.container = container;
3402 this.builder = builder;
3404 CodeGen.SymbolWriter.OpenMethod (
3405 file, this, start.Row, 0, end.Row, 0);
3408 public string Name {
3409 get { return builder.Name; }
3412 public int NamespaceID {
3413 get { return container.NamespaceEntry.SymbolFileID; }
3418 if (builder is MethodBuilder)
3419 return ((MethodBuilder) builder).GetToken ().Token;
3420 else if (builder is ConstructorBuilder)
3421 return ((ConstructorBuilder) builder).GetToken ().Token;
3423 throw new NotSupportedException ();
3427 public void CloseMethod ()
3429 if (CodeGen.SymbolWriter != null)
3430 CodeGen.SymbolWriter.CloseMethod ();
3433 public static SourceMethod Create (TypeContainer parent,
3434 MethodBase builder, Block block)
3436 if (CodeGen.SymbolWriter == null)
3441 Location start_loc = block.StartLocation;
3442 if (Location.IsNull (start_loc))
3445 Location end_loc = block.EndLocation;
3446 if (Location.IsNull (end_loc))
3449 ISourceFile file = start_loc.SourceFile;
3453 return new SourceMethod (
3454 parent, builder, file, start_loc, end_loc);
3458 public class Method : MethodCore, IIteratorContainer, IMethodData {
3459 public MethodBuilder MethodBuilder;
3460 public MethodData MethodData;
3461 ReturnParameter return_attributes;
3462 ListDictionary declarative_security;
3465 /// Modifiers allowed in a class declaration
3467 const int AllowedModifiers =
3470 Modifiers.PROTECTED |
3471 Modifiers.INTERNAL |
3476 Modifiers.OVERRIDE |
3477 Modifiers.ABSTRACT |
3479 Modifiers.METHOD_YIELDS |
3482 const int AllowedInterfaceModifiers =
3483 Modifiers.NEW | Modifiers.UNSAFE;
3486 // return_type can be "null" for VOID values.
3488 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3489 MemberName name, Parameters parameters, Attributes attrs,
3491 : base (ds, return_type, mod,
3492 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3493 is_iface, name, attrs, parameters, l)
3497 public override AttributeTargets AttributeTargets {
3499 return AttributeTargets.Method;
3503 public override string GetSignatureForError()
3505 if (MethodBuilder == null) {
3506 return GetSignatureForError (Parent);
3508 return TypeManager.CSharpSignature (MethodBuilder);
3512 /// Use this method when MethodBuilder is null
3514 public override string GetSignatureForError (TypeContainer tc)
3516 // TODO: get params from somewhere
3517 if (parameter_info == null)
3518 return base.GetSignatureForError (tc);
3520 // TODO: move to parameters
3521 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3522 if (parameter_info.Parameters.FixedParameters != null) {
3523 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3524 Parameter p = parameter_info.Parameters.FixedParameters [i];
3525 args.Append (p.GetSignatureForError ());
3527 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3532 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3535 void DuplicateEntryPoint (MethodInfo b, Location location)
3539 "Program `" + CodeGen.FileName +
3540 "' has more than one entry point defined: `" +
3541 TypeManager.CSharpSignature(b) + "'");
3544 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3546 if (b.ReturnType != TypeManager.void_type &&
3547 b.ReturnType != TypeManager.int32_type)
3550 if (pinfo.Count == 0)
3553 if (pinfo.Count > 1)
3556 Type t = pinfo.ParameterType(0);
3558 (t.GetArrayRank() == 1) &&
3559 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3560 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3566 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3568 if (a.Target == AttributeTargets.ReturnValue) {
3569 if (return_attributes == null)
3570 return_attributes = new ReturnParameter (MethodBuilder, Location);
3572 return_attributes.ApplyAttributeBuilder (a, cb);
3576 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
3577 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3580 if (a.Type == TypeManager.dllimport_type) {
3581 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3582 if ((ModFlags & extern_static) != extern_static) {
3583 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3589 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3590 if (declarative_security == null)
3591 declarative_security = new ListDictionary ();
3592 a.ExtractSecurityPermissionSet (declarative_security);
3596 if (a.Type == TypeManager.conditional_attribute_type) {
3597 if (IsOperator || IsExplicitImpl) {
3598 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3602 if (ReturnType != TypeManager.void_type) {
3603 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3607 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3608 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3613 Report.Error (582, Location, "Conditional not valid on interface members");
3617 if (MethodData.IsImplementing) {
3618 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3622 for (int i = 0; i < parameter_info.Count; ++i) {
3623 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3624 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3630 MethodBuilder.SetCustomAttribute (cb);
3633 protected override bool CheckForDuplications ()
3635 ArrayList ar = Parent.Methods;
3637 int arLen = ar.Count;
3639 for (int i = 0; i < arLen; i++) {
3640 Method m = (Method) ar [i];
3641 if (IsDuplicateImplementation (m))
3646 ar = Parent.Properties;
3648 for (int i = 0; i < ar.Count; ++i) {
3649 PropertyBase pb = (PropertyBase) ar [i];
3650 if (pb.AreAccessorsDuplicateImplementation (this))
3655 ar = Parent.Indexers;
3657 for (int i = 0; i < ar.Count; ++i) {
3658 PropertyBase pb = (PropertyBase) ar [i];
3659 if (pb.AreAccessorsDuplicateImplementation (this))
3666 for (int i = 0; i < ar.Count; ++i) {
3667 Event ev = (Event) ar [i];
3668 if (ev.AreAccessorsDuplicateImplementation (this))
3679 public override bool Define ()
3688 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3690 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3692 if (!MethodData.Define (Parent))
3696 // Setup iterator if we are one
3698 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3699 Iterator iterator = new Iterator (
3700 Parent, Name, MemberType, ParameterTypes,
3701 ParameterInfo, ModFlags, block, Location);
3703 if (!iterator.DefineIterator ())
3706 block = iterator.Block;
3709 MethodBuilder = MethodData.MethodBuilder;
3712 // This is used to track the Entry Point,
3714 if (Name == "Main" &&
3715 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3716 (RootContext.MainClass == null ||
3717 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3718 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3719 if (RootContext.EntryPoint == null) {
3720 RootContext.EntryPoint = MethodBuilder;
3721 RootContext.EntryPointLocation = Location;
3723 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3724 DuplicateEntryPoint (MethodBuilder, Location);
3727 if (RootContext.WarningLevel >= 4)
3728 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3732 if (MemberType.IsAbstract && MemberType.IsSealed) {
3733 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3743 public override void Emit ()
3745 MethodData.Emit (Parent, this);
3748 if (declarative_security != null) {
3749 foreach (DictionaryEntry de in declarative_security) {
3750 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3758 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
3760 MethodInfo mi = (MethodInfo) container.ParentCache.FindMemberToOverride (
3761 container.TypeBuilder, Name, ParameterTypes, false);
3766 parent_ret_type = mi.ReturnType;
3770 protected override bool VerifyClsCompliance(DeclSpace ds)
3772 if (!base.VerifyClsCompliance (ds))
3775 if (parameter_types.Length > 0) {
3776 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3778 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3785 void IIteratorContainer.SetYields ()
3787 ModFlags |= Modifiers.METHOD_YIELDS;
3790 #region IMethodData Members
3792 public CallingConventions CallingConventions {
3794 CallingConventions cc = Parameters.GetCallingConvention ();
3795 if (Parameters.HasArglist)
3796 block.HasVarargs = true;
3799 if ((ModFlags & Modifiers.STATIC) == 0)
3800 cc |= CallingConventions.HasThis;
3802 // FIXME: How is `ExplicitThis' used in C#?
3808 public Type ReturnType {
3814 public MemberName MethodName {
3820 public new Location Location {
3822 return base.Location;
3826 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3828 return new EmitContext (
3829 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3832 public ObsoleteAttribute GetObsoleteAttribute ()
3834 return GetObsoleteAttribute (Parent);
3838 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3840 public bool IsExcluded (EmitContext ec)
3842 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3843 return (caching_flags & Flags.Excluded) != 0;
3845 caching_flags &= ~Flags.Excluded_Undetected;
3847 if (parent_method == null) {
3848 if (OptAttributes == null)
3851 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3856 foreach (Attribute a in attrs) {
3857 string condition = a.GetConditionalAttributeValue (
3859 if (RootContext.AllDefines.Contains (condition))
3863 caching_flags |= Flags.Excluded;
3867 IMethodData md = TypeManager.GetMethod (parent_method);
3869 if (AttributeTester.IsConditionalMethodExcluded (parent_method)) {
3870 caching_flags |= Flags.Excluded;
3876 if (md.IsExcluded (ec)) {
3877 caching_flags |= Flags.Excluded;
3886 public abstract class ConstructorInitializer {
3887 ArrayList argument_list;
3888 protected ConstructorInfo parent_constructor;
3889 Parameters parameters;
3892 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
3895 this.argument_list = argument_list;
3896 this.parameters = parameters;
3900 public ArrayList Arguments {
3902 return argument_list;
3906 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
3908 Expression parent_constructor_group;
3911 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
3913 if (argument_list != null){
3914 foreach (Argument a in argument_list){
3915 if (!a.Resolve (ec, loc))
3919 ec.CurrentBlock = null;
3921 if (this is ConstructorBaseInitializer) {
3922 if (ec.ContainerType.BaseType == null)
3925 t = ec.ContainerType.BaseType;
3926 if (ec.ContainerType.IsValueType) {
3927 Report.Error (522, loc,
3928 "structs cannot call base class constructors");
3932 t = ec.ContainerType;
3934 parent_constructor_group = Expression.MemberLookup (
3935 ec, t, ".ctor", MemberTypes.Constructor,
3936 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3939 if (parent_constructor_group == null){
3940 parent_constructor_group = Expression.MemberLookup (
3941 ec, t, ".ctor", MemberTypes.Constructor,
3942 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3945 if (parent_constructor_group != null)
3947 112, loc, "`{0}.{1}' is inaccessible due to " +
3948 "its protection level", t.FullName, t.Name);
3951 1501, loc, "Can not find a constructor for " +
3952 "this argument list");
3956 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (
3957 ec, (MethodGroupExpr) parent_constructor_group, argument_list,
3960 if (parent_constructor == null){
3961 Report.Error (1501, loc,
3962 "Can not find a constructor for this argument list");
3966 if (parent_constructor == caller_builder){
3967 Report.Error (516, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
3974 public void Emit (EmitContext ec)
3976 if (parent_constructor != null){
3977 ec.Mark (loc, false);
3979 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
3981 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
3986 /// Method search for base ctor. (We do not cache it).
3988 Constructor GetOverloadedConstructor (TypeContainer tc)
3990 if (tc.InstanceConstructors == null)
3993 foreach (Constructor c in tc.InstanceConstructors) {
3994 if (Arguments == null) {
3995 if (c.ParameterTypes.Length == 0)
4003 int count = c.ParameterInfo.Count;
4005 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4006 for (int i = 0; i < count-1; i++)
4007 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4012 if (c.ParameterTypes.Length != Arguments.Count)
4015 for (int i = 0; i < Arguments.Count; ++i)
4016 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4031 //TODO: implement caching when it will be necessary
4032 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4034 Constructor ctor = GetOverloadedConstructor (tc);
4038 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4042 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4046 public class ConstructorBaseInitializer : ConstructorInitializer {
4047 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4048 base (argument_list, pars, l)
4052 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4053 if (parent_constructor == null)
4056 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4057 if (type_ds == null) {
4058 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (parent_constructor);
4061 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (parent_constructor), loc);
4066 base.CheckObsoleteAttribute (type_ds, loc);
4071 public class ConstructorThisInitializer : ConstructorInitializer {
4072 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4073 base (argument_list, pars, l)
4078 public class Constructor : MethodCore, IMethodData {
4079 public ConstructorBuilder ConstructorBuilder;
4080 public ConstructorInitializer Initializer;
4081 ListDictionary declarative_security;
4084 // Modifiers allowed for a constructor.
4086 public const int AllowedModifiers =
4088 Modifiers.PROTECTED |
4089 Modifiers.INTERNAL |
4095 bool has_compliant_args = false;
4097 // The spec claims that static is not permitted, but
4098 // my very own code has static constructors.
4100 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4101 ConstructorInitializer init, Location l)
4102 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4108 public override string GetSignatureForError()
4110 if (ConstructorBuilder == null)
4111 return GetSignatureForError (Parent);
4113 return TypeManager.CSharpSignature (ConstructorBuilder);
4116 public bool HasCompliantArgs {
4118 return has_compliant_args;
4122 public override AttributeTargets AttributeTargets {
4124 return AttributeTargets.Constructor;
4130 // Returns true if this is a default constructor
4132 public bool IsDefault ()
4134 if ((ModFlags & Modifiers.STATIC) != 0)
4135 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4136 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4139 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4140 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4141 (Initializer is ConstructorBaseInitializer) &&
4142 (Initializer.Arguments == null);
4145 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4147 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4148 if (declarative_security == null) {
4149 declarative_security = new ListDictionary ();
4151 a.ExtractSecurityPermissionSet (declarative_security);
4155 ConstructorBuilder.SetCustomAttribute (cb);
4158 protected override bool CheckForDuplications ()
4160 ArrayList ar = Parent.InstanceConstructors;
4162 int arLen = ar.Count;
4164 for (int i = 0; i < arLen; i++) {
4165 Constructor m = (Constructor) ar [i];
4166 if (IsDuplicateImplementation (m))
4173 protected override bool CheckBase ()
4175 // Check whether arguments were correct.
4176 if (!DoDefineParameters ())
4179 // TODO: skip the rest for generated ctor
4180 if ((ModFlags & Modifiers.STATIC) != 0)
4183 if (!CheckForDuplications ())
4186 if (Parent.Kind == Kind.Struct) {
4187 if (ParameterTypes.Length == 0) {
4188 Report.Error (568, Location,
4189 "Structs can not contain explicit parameterless " +
4194 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4195 Report.Error (666, Location, "Protected member in struct declaration");
4200 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4201 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4208 // Creates the ConstructorBuilder
4210 public override bool Define ()
4212 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4213 MethodAttributes.SpecialName);
4215 if ((ModFlags & Modifiers.STATIC) != 0) {
4216 ca |= MethodAttributes.Static | MethodAttributes.Private;
4218 ca |= MethodAttributes.HideBySig;
4220 if ((ModFlags & Modifiers.PUBLIC) != 0)
4221 ca |= MethodAttributes.Public;
4222 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4223 if ((ModFlags & Modifiers.INTERNAL) != 0)
4224 ca |= MethodAttributes.FamORAssem;
4226 ca |= MethodAttributes.Family;
4227 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4228 ca |= MethodAttributes.Assembly;
4229 else if (IsDefault ())
4230 ca |= MethodAttributes.Public;
4232 ca |= MethodAttributes.Private;
4235 // Check if arguments were correct.
4239 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4240 ca, CallingConventions,
4243 if ((ModFlags & Modifiers.UNSAFE) != 0)
4244 ConstructorBuilder.InitLocals = false;
4246 TypeManager.AddMethod (ConstructorBuilder, this);
4249 // HACK because System.Reflection.Emit is lame
4251 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4259 public override void Emit ()
4261 EmitContext ec = CreateEmitContext (null, null);
4264 // extern methods have no bodies
4266 if ((ModFlags & Modifiers.EXTERN) != 0) {
4267 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4269 179, Location, "External constructor `" +
4270 TypeManager.CSharpSignature (ConstructorBuilder) +
4271 "' can not have a body");
4274 } else if (block == null) {
4276 501, Location, "Constructor `" +
4277 TypeManager.CSharpSignature (ConstructorBuilder) +
4278 "' must declare a body since it is not marked extern");
4282 if ((ModFlags & Modifiers.STATIC) == 0){
4283 if (Parent.Kind == Kind.Class && Initializer == null)
4284 Initializer = new ConstructorBaseInitializer (
4285 null, Parameters.EmptyReadOnlyParameters, Location);
4289 // Spec mandates that Initializers will not have
4293 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4295 ec.IsStatic = false;
4298 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4300 SourceMethod source = SourceMethod.Create (
4301 Parent, ConstructorBuilder, block);
4304 // Classes can have base initializers and instance field initializers.
4306 if (Parent.Kind == Kind.Class){
4307 if ((ModFlags & Modifiers.STATIC) == 0){
4310 // If we use a "this (...)" constructor initializer, then
4311 // do not emit field initializers, they are initialized in the other constructor
4313 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4314 Parent.EmitFieldInitializers (ec);
4317 if (Initializer != null) {
4318 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4319 Initializer.CheckObsoleteAttribute (Parent, Location);
4321 ec.TestObsoleteMethodUsage = false;
4322 Initializer.Emit (ec);
4325 if ((ModFlags & Modifiers.STATIC) != 0)
4326 Parent.EmitFieldInitializers (ec);
4328 if (OptAttributes != null)
4329 OptAttributes.Emit (ec, this);
4331 // If this is a non-static `struct' constructor and doesn't have any
4332 // initializer, it must initialize all of the struct's fields.
4333 if ((Parent.Kind == Kind.Struct) &&
4334 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4335 Block.AddThisVariable (Parent, Location);
4337 ec.EmitTopBlock (block, ParameterInfo, Location);
4340 source.CloseMethod ();
4344 if (declarative_security != null) {
4345 foreach (DictionaryEntry de in declarative_security) {
4346 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4353 // Is never override
4354 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
4359 protected override bool VerifyClsCompliance (DeclSpace ds)
4361 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4365 if (parameter_types.Length > 0) {
4366 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4368 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4370 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4371 foreach (Type param in parameter_types) {
4372 if (param.IsArray) {
4378 has_compliant_args = true;
4382 #region IMethodData Members
4384 public System.Reflection.CallingConventions CallingConventions {
4386 CallingConventions cc = Parameters.GetCallingConvention ();
4388 if (Parent.Kind == Kind.Class)
4389 if ((ModFlags & Modifiers.STATIC) == 0)
4390 cc |= CallingConventions.HasThis;
4392 // FIXME: How is `ExplicitThis' used in C#?
4398 public new Location Location {
4400 return base.Location;
4404 public MemberName MethodName {
4410 public Type ReturnType {
4416 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4418 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4419 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4422 public ObsoleteAttribute GetObsoleteAttribute ()
4427 public bool IsExcluded(EmitContext ec)
4436 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4438 public interface IMethodData
4440 CallingConventions CallingConventions { get; }
4441 Location Location { get; }
4442 MemberName MethodName { get; }
4443 Type[] ParameterTypes { get; }
4444 Type ReturnType { get; }
4446 Attributes OptAttributes { get; }
4447 ToplevelBlock Block { get; }
4449 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4450 ObsoleteAttribute GetObsoleteAttribute ();
4451 string GetSignatureForError (TypeContainer tc);
4452 bool IsExcluded (EmitContext ec);
4453 bool IsClsCompliaceRequired (DeclSpace ds);
4457 // Encapsulates most of the Method's state
4459 public class MethodData {
4461 readonly IMethodData method;
4464 // The return type of this method
4466 public readonly InternalParameters ParameterInfo;
4469 // Are we implementing an interface ?
4471 public bool IsImplementing = false;
4476 protected MemberBase member;
4477 protected int modifiers;
4478 protected MethodAttributes flags;
4480 MethodBuilder builder = null;
4481 public MethodBuilder MethodBuilder {
4487 public MethodData (MemberBase member, InternalParameters parameters,
4488 int modifiers, MethodAttributes flags, IMethodData method)
4490 this.member = member;
4491 this.ParameterInfo = parameters;
4492 this.modifiers = modifiers;
4495 this.method = method;
4498 public bool Define (TypeContainer container)
4500 MethodInfo implementing = null;
4502 string name = method.MethodName.Name;
4503 string method_name = name;
4505 Type[] ParameterTypes = method.ParameterTypes;
4507 if (container.Pending != null){
4508 if (member is Indexer)
4509 implementing = container.Pending.IsInterfaceIndexer (
4510 member.InterfaceType, method.ReturnType, ParameterTypes);
4512 implementing = container.Pending.IsInterfaceMethod (
4513 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4515 if (member.InterfaceType != null){
4516 if (implementing == null){
4517 Report.Error (539, method.Location,
4518 "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
4521 method_name = member.InterfaceType.FullName + "." + name;
4526 // For implicit implementations, make sure we are public, for
4527 // explicit implementations, make sure we are private.
4529 if (implementing != null){
4531 // Setting null inside this block will trigger a more
4532 // verbose error reporting for missing interface implementations
4534 // The "candidate" function has been flagged already
4535 // but it wont get cleared
4537 if (member.IsExplicitImpl){
4538 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4539 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4540 implementing = null;
4542 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4543 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4545 // If this is an interface method implementation,
4546 // check for public accessibility
4548 implementing = null;
4549 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4550 // We may never be private.
4551 implementing = null;
4552 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4554 // We may be protected if we're overriding something.
4556 implementing = null;
4561 // Static is not allowed
4563 if ((modifiers & Modifiers.STATIC) != 0){
4564 implementing = null;
4565 Modifiers.Error_InvalidModifier (method.Location, "static");
4570 // If implementing is still valid, set flags
4572 if (implementing != null){
4574 // When implementing interface methods, set NewSlot
4575 // unless, we are overwriting a method.
4577 if (implementing.DeclaringType.IsInterface){
4578 if ((modifiers & Modifiers.OVERRIDE) == 0)
4579 flags |= MethodAttributes.NewSlot;
4582 MethodAttributes.Virtual |
4583 MethodAttributes.HideBySig;
4585 // Set Final unless we're virtual, abstract or already overriding a method.
4586 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4587 flags |= MethodAttributes.Final;
4589 IsImplementing = true;
4592 EmitContext ec = method.CreateEmitContext (container, null);
4594 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4596 if (builder == null)
4599 if ((modifiers & Modifiers.UNSAFE) != 0)
4600 builder.InitLocals = false;
4602 if (IsImplementing){
4604 // clear the pending implemntation flag
4606 if (member is Indexer) {
4607 container.Pending.ImplementIndexer (
4608 member.InterfaceType, builder, method.ReturnType,
4609 ParameterTypes, member.IsExplicitImpl);
4611 container.Pending.ImplementMethod (
4612 member.InterfaceType, name, method.ReturnType,
4613 ParameterTypes, member.IsExplicitImpl);
4615 if (member.IsExplicitImpl)
4616 container.TypeBuilder.DefineMethodOverride (
4617 builder, implementing);
4621 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4622 TypeManager.AddMethod (builder, method);
4629 /// Create the MethodBuilder for the method
4631 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4633 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4635 if ((modifiers & extern_static) == extern_static) {
4637 if (method.OptAttributes != null) {
4638 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4639 if (dllimport_attribute != null) {
4640 flags |= MethodAttributes.PinvokeImpl;
4641 builder = dllimport_attribute.DefinePInvokeMethod (
4642 ec, container.TypeBuilder, method_name, flags,
4643 method.ReturnType, ParameterTypes);
4649 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4650 // We are more strict than Microsoft and report CS0626 like error
4651 if (method.OptAttributes == null ||
4652 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4653 Report.Error (626, method.Location, "Method, operator, or accessor '{0}' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation", method.GetSignatureForError (container));
4658 builder = container.TypeBuilder.DefineMethod (
4659 method_name, flags, method.CallingConventions,
4660 method.ReturnType, ParameterTypes);
4666 public void Emit (TypeContainer container, Attributable kind)
4669 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4670 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4672 ec = method.CreateEmitContext (container, null);
4674 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container.Parent) != null)
4675 ec.TestObsoleteMethodUsage = false;
4677 Location loc = method.Location;
4678 Attributes OptAttributes = method.OptAttributes;
4680 if (OptAttributes != null)
4681 OptAttributes.Emit (ec, kind);
4683 if (member is MethodCore)
4684 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4686 ToplevelBlock block = method.Block;
4689 // abstract or extern methods have no bodies
4691 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4696 // abstract or extern methods have no bodies.
4698 if ((modifiers & Modifiers.ABSTRACT) != 0)
4700 500, method.Location, "Abstract method `" +
4701 TypeManager.CSharpSignature (builder) +
4702 "' can not have a body");
4704 if ((modifiers & Modifiers.EXTERN) != 0)
4706 179, method.Location, "External method `" +
4707 TypeManager.CSharpSignature (builder) +
4708 "' can not have a body");
4714 // Methods must have a body unless they're extern or abstract
4716 if (block == null) {
4718 501, method.Location, "Method `" +
4719 TypeManager.CSharpSignature (builder) +
4720 "' must declare a body since it is not marked " +
4721 "abstract or extern");
4725 SourceMethod source = SourceMethod.Create (
4726 container, MethodBuilder, method.Block);
4729 // Handle destructors specially
4731 // FIXME: This code generates buggy code
4733 if (member is Destructor)
4734 EmitDestructor (ec, block);
4736 ec.EmitTopBlock (block, ParameterInfo, loc);
4739 source.CloseMethod ();
4742 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4744 ILGenerator ig = ec.ig;
4746 Label finish = ig.DefineLabel ();
4748 block.SetDestructor ();
4750 ig.BeginExceptionBlock ();
4751 ec.ReturnLabel = finish;
4752 ec.HasReturnLabel = true;
4753 ec.EmitTopBlock (block, null, method.Location);
4755 // ig.MarkLabel (finish);
4756 ig.BeginFinallyBlock ();
4758 if (ec.ContainerType.BaseType != null) {
4759 Expression member_lookup = Expression.MemberLookup (
4760 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4761 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4763 if (member_lookup != null){
4764 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
4766 ig.Emit (OpCodes.Ldarg_0);
4767 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
4771 ig.EndExceptionBlock ();
4772 //ig.MarkLabel (ec.ReturnLabel);
4773 ig.Emit (OpCodes.Ret);
4777 public class Destructor : Method {
4779 public Destructor (TypeContainer ds, Expression return_type, int mod,
4780 string name, Parameters parameters, Attributes attrs,
4782 : base (ds, return_type, mod, false, new MemberName (name),
4783 parameters, attrs, l)
4786 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4788 if (a.Type == TypeManager.conditional_attribute_type) {
4789 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4793 base.ApplyAttributeBuilder (a, cb);
4797 abstract public class MemberBase : MemberCore {
4798 public Expression Type;
4800 public MethodAttributes flags;
4802 protected readonly int explicit_mod_flags;
4805 // The "short" name of this property / indexer / event. This is the
4806 // name without the explicit interface.
4808 public string ShortName;
4811 // The type of this property / indexer / event
4813 public Type MemberType;
4816 // If true, this is an explicit interface implementation
4818 public bool IsExplicitImpl = false;
4821 // The name of the interface we are explicitly implementing
4823 public MemberName ExplicitInterfaceName = null;
4826 // Whether this is an interface member.
4828 public bool IsInterface;
4831 // If true, the interface type we are explicitly implementing
4833 public Type InterfaceType = null;
4836 // The constructor is only exposed to our children
4838 protected MemberBase (TypeContainer parent, Expression type, int mod,
4839 int allowed_mod, int def_mod, MemberName name,
4840 Attributes attrs, Location loc)
4841 : base (parent, name, attrs, loc)
4843 explicit_mod_flags = mod;
4845 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4847 // Check for explicit interface implementation
4848 if (MemberName.Left != null) {
4849 ExplicitInterfaceName = MemberName.Left;
4850 ShortName = MemberName.Name;
4851 IsExplicitImpl = true;
4856 protected virtual bool CheckBase ()
4858 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4859 Report.Error (666, Location, "Protected member in struct declaration");
4863 if ((RootContext.WarningLevel >= 4) &&
4864 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4865 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4866 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4867 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4872 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4876 foreach (Type partype in parameters){
4877 if (partype == TypeManager.void_type) {
4879 1547, Location, "Keyword 'void' cannot " +
4880 "be used in this context");
4884 if (partype.IsPointer){
4887 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4891 if (ds.AsAccessible (partype, ModFlags))
4894 if (this is Indexer)
4895 Report.Error (55, Location,
4896 "Inconsistent accessibility: parameter type `" +
4897 TypeManager.CSharpName (partype) + "' is less " +
4898 "accessible than indexer `" + Name + "'");
4899 else if ((this is Method) && ((Method) this).IsOperator)
4900 Report.Error (57, Location,
4901 "Inconsistent accessibility: parameter type `" +
4902 TypeManager.CSharpName (partype) + "' is less " +
4903 "accessible than operator `" + Name + "'");
4905 Report.Error (51, Location,
4906 "Inconsistent accessibility: parameter type `" +
4907 TypeManager.CSharpName (partype) + "' is less " +
4908 "accessible than method `" + Name + "'");
4915 protected virtual bool DoDefine ()
4917 EmitContext ec = Parent.EmitContext;
4919 throw new InternalErrorException ("MemberBase.DoDefine called too early");
4922 throw new InternalErrorException ();
4925 ModFlags = Modifiers.PUBLIC |
4926 Modifiers.ABSTRACT |
4927 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
4929 flags = MethodAttributes.Public |
4930 MethodAttributes.Abstract |
4931 MethodAttributes.HideBySig |
4932 MethodAttributes.NewSlot |
4933 MethodAttributes.Virtual;
4935 if (!Parent.MethodModifiersValid (this))
4938 flags = Modifiers.MethodAttr (ModFlags);
4941 // Lookup Type, verify validity
4942 bool old_unsafe = ec.InUnsafe;
4943 ec.InUnsafe = InUnsafe;
4944 Type = Type.ResolveAsTypeTerminal (ec, false);
4945 ec.InUnsafe = old_unsafe;
4950 MemberType = Type.Type;
4952 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
4953 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
4954 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
4959 // verify accessibility
4960 if (!Parent.AsAccessible (MemberType, ModFlags)) {
4961 Report.SymbolRelatedToPreviousError (MemberType);
4962 if (this is Property)
4963 Report.Error (53, Location,
4964 "Inconsistent accessibility: property type `" +
4965 TypeManager.CSharpName (MemberType) + "' is less " +
4966 "accessible than property `" + GetSignatureForError () + "'");
4967 else if (this is Indexer)
4968 Report.Error (54, Location,
4969 "Inconsistent accessibility: indexer return type `" +
4970 TypeManager.CSharpName (MemberType) + "' is less " +
4971 "accessible than indexer `" + Name + "'");
4972 else if (this is MethodCore) {
4973 if (this is Operator)
4974 Report.Error (56, Location,
4975 "Inconsistent accessibility: return type `" +
4976 TypeManager.CSharpName (MemberType) + "' is less " +
4977 "accessible than operator `" + Name + "'");
4979 Report.Error (50, Location,
4980 "Inconsistent accessibility: return type `" +
4981 TypeManager.CSharpName (MemberType) + "' is less " +
4982 "accessible than method `" + Name + "'");
4984 Report.Error (52, Location,
4985 "Inconsistent accessibility: field type `" +
4986 TypeManager.CSharpName (MemberType) + "' is less " +
4987 "accessible than field `" + Name + "'");
4992 if (MemberType.IsPointer && !UnsafeOK (Parent))
4995 if (IsExplicitImpl) {
4996 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
4997 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5001 InterfaceType = texpr.ResolveType (ec);
5003 if (!InterfaceType.IsInterface) {
5004 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5009 // Compute the full name that we need to export.
5010 if (InterfaceType.FullName != ExplicitInterfaceName) {
5011 ExplicitInterfaceName = InterfaceType.FullName;
5012 UpdateMemberName ();
5016 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5019 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5026 /// The name of the member can be changed during definition (see IndexerName attribute)
5028 protected virtual void UpdateMemberName ()
5030 MemberName.Name = ShortName;
5033 public override string GetSignatureForError (TypeContainer tc)
5035 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5038 protected bool IsTypePermitted ()
5040 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5041 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5047 protected override bool VerifyClsCompliance(DeclSpace ds)
5049 if (base.VerifyClsCompliance (ds)) {
5053 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5054 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5059 protected override void VerifyObsoleteAttribute()
5061 CheckUsageOfObsoleteAttribute (MemberType);
5066 // Fields and Events both generate FieldBuilders, we use this to share
5067 // their common bits. This is also used to flag usage of the field
5069 abstract public class FieldBase : MemberBase {
5070 public FieldBuilder FieldBuilder;
5071 public Status status;
5074 public enum Status : byte {
5077 HAS_OFFSET = 4 // Used by FieldMember.
5080 static string[] attribute_targets = new string [] { "field" };
5083 /// Symbol with same name in parent class/struct
5085 public MemberInfo conflict_symbol;
5088 // The constructor is only exposed to our children
5090 protected FieldBase (TypeContainer parent, Expression type, int mod,
5091 int allowed_mod, MemberName name, object init,
5092 Attributes attrs, Location loc)
5093 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5099 public override AttributeTargets AttributeTargets {
5101 return AttributeTargets.Field;
5105 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5107 if (a.Type == TypeManager.marshal_as_attr_type) {
5108 UnmanagedMarshal marshal = a.GetMarshal (this);
5109 if (marshal != null) {
5110 FieldBuilder.SetMarshal (marshal);
5115 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5116 a.Error_InvalidSecurityParent ();
5120 FieldBuilder.SetCustomAttribute (cb);
5124 // Whether this field has an initializer.
5126 public bool HasInitializer {
5128 return init != null;
5132 protected readonly Object init;
5135 Expression init_expr;
5136 bool init_expr_initialized = false;
5139 // Resolves and returns the field initializer.
5141 public Expression GetInitializerExpression (EmitContext ec)
5143 if (init_expr_initialized)
5147 if (init is Expression)
5148 e = (Expression) init;
5150 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5152 ec.IsFieldInitializer = true;
5153 e = e.DoResolve (ec);
5154 ec.IsFieldInitializer = false;
5157 init_expr_initialized = true;
5162 protected override bool CheckBase ()
5164 if (!base.CheckBase ())
5171 conflict_symbol = Parent.FindMemberWithSameName (Name, false);
5172 if (conflict_symbol == null) {
5173 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5174 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5179 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5180 Report.SymbolRelatedToPreviousError (conflict_symbol);
5181 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5187 public override string GetSignatureForError ()
5189 if (FieldBuilder == null) {
5190 return base.GetSignatureForError (Parent);
5192 return TypeManager.GetFullNameSignature (FieldBuilder);
5195 public override string[] ValidAttributeTargets {
5197 return attribute_targets;
5201 protected override bool VerifyClsCompliance (DeclSpace ds)
5203 if (!base.VerifyClsCompliance (ds))
5206 if (FieldBuilder == null) {
5210 if (!AttributeTester.IsClsCompliant (FieldBuilder.FieldType)) {
5211 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5217 public void SetAssigned ()
5219 status |= Status.ASSIGNED;
5223 public abstract class FieldMember: FieldBase
5227 protected FieldMember (TypeContainer parent, Expression type, int mod,
5228 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5229 : base (parent, type, mod, allowed_mod, name, init, attrs, loc)
5233 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5235 if (a.Type == TypeManager.field_offset_attribute_type)
5237 status |= Status.HAS_OFFSET;
5239 if (!Parent.HasExplicitLayout) {
5240 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5244 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5245 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5249 base.ApplyAttributeBuilder (a, cb);
5253 public override bool Define()
5255 EmitContext ec = Parent.EmitContext;
5257 throw new InternalErrorException ("FieldMember.Define called too early");
5259 bool old_unsafe = ec.InUnsafe;
5260 ec.InUnsafe = InUnsafe;
5261 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
5265 MemberType = texpr.ResolveType (ec);
5267 if (MemberType == TypeManager.void_type) {
5268 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5272 ec.InUnsafe = old_unsafe;
5277 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5278 Report.Error (52, Location,
5279 "Inconsistent accessibility: field type `" +
5280 TypeManager.CSharpName (MemberType) + "' is less " +
5281 "accessible than field `" + Name + "'");
5285 if (!IsTypePermitted ())
5288 if (MemberType.IsPointer && !UnsafeOK (Parent))
5294 public override void Emit ()
5296 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5297 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5304 // Represents header string for documentation comment.
5306 public override string DocCommentHeader {
5307 get { return "F:"; }
5312 // The Field class is used to represents class/struct fields during parsing.
5314 public class Field : FieldMember {
5316 // Modifiers allowed in a class declaration
5318 const int AllowedModifiers =
5321 Modifiers.PROTECTED |
5322 Modifiers.INTERNAL |
5325 Modifiers.VOLATILE |
5329 public Field (TypeContainer parent, Expression type, int mod, string name,
5330 Object expr_or_array_init, Attributes attrs, Location loc)
5331 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5332 expr_or_array_init, attrs, loc)
5336 public override bool Define ()
5338 if (!base.Define ())
5341 if (RootContext.WarningLevel > 1){
5342 Type ptype = Parent.TypeBuilder.BaseType;
5344 // ptype is only null for System.Object while compiling corlib.
5346 TypeContainer.FindMembers (
5347 ptype, MemberTypes.Method,
5348 BindingFlags.Public |
5349 BindingFlags.Static | BindingFlags.Instance,
5350 System.Type.FilterName, Name);
5354 if ((ModFlags & Modifiers.VOLATILE) != 0){
5355 if (!MemberType.IsClass){
5356 Type vt = MemberType;
5358 if (TypeManager.IsEnumType (vt))
5359 vt = TypeManager.EnumToUnderlying (MemberType);
5361 if (!((vt == TypeManager.bool_type) ||
5362 (vt == TypeManager.sbyte_type) ||
5363 (vt == TypeManager.byte_type) ||
5364 (vt == TypeManager.short_type) ||
5365 (vt == TypeManager.ushort_type) ||
5366 (vt == TypeManager.int32_type) ||
5367 (vt == TypeManager.uint32_type) ||
5368 (vt == TypeManager.char_type) ||
5369 (vt == TypeManager.float_type) ||
5370 (!vt.IsValueType))){
5372 677, Location, Parent.MakeName (Name) +
5373 " A volatile field can not be of type `" +
5374 TypeManager.CSharpName (vt) + "'");
5379 if ((ModFlags & Modifiers.READONLY) != 0){
5382 "A field can not be both volatile and readonly");
5387 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5389 if (Parent.Kind == Kind.Struct &&
5390 ((fa & FieldAttributes.Static) == 0) &&
5391 MemberType == Parent.TypeBuilder &&
5392 !TypeManager.IsBuiltinType (MemberType)){
5393 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5394 "' causes a cycle in the structure layout");
5399 FieldBuilder = Parent.TypeBuilder.DefineField (
5400 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5402 TypeManager.RegisterFieldBase (FieldBuilder, this);
5404 catch (ArgumentException) {
5405 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5412 public override void Emit ()
5414 if (OptAttributes != null) {
5415 EmitContext ec = new EmitContext (
5416 Parent, Location, null, FieldBuilder.FieldType,
5418 OptAttributes.Emit (ec, this);
5426 // `set' and `get' accessors are represented with an Accessor.
5428 public class Accessor {
5430 // Null if the accessor is empty, or a Block if not
5432 public const int AllowedModifiers =
5434 Modifiers.PROTECTED |
5435 Modifiers.INTERNAL |
5438 public ToplevelBlock Block;
5439 public Attributes Attributes;
5440 public Location Location;
5441 public int ModFlags;
5443 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5448 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5453 // Ooouh Martin, templates are missing here.
5454 // When it will be possible move here a lot of child code and template method type.
5455 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5456 protected MethodData method_data;
5457 protected ToplevelBlock block;
5458 protected ListDictionary declarative_security;
5460 // The accessor are created event if they are not wanted.
5461 // But we need them because their names are reserved.
5462 // Field says whether accessor will be emited or not
5463 public readonly bool IsDummy;
5465 protected readonly string prefix;
5467 ReturnParameter return_attributes;
5469 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5470 : base (null, SetupName (prefix, member), null, member.Location)
5472 this.prefix = prefix;
5476 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5478 : base (null, SetupName (prefix, member),
5479 accessor.Attributes, accessor.Location)
5481 this.prefix = prefix;
5482 this.block = accessor.Block;
5485 static MemberName SetupName (string prefix, MemberBase member)
5487 MemberName name = member.MemberName.Clone ();
5488 name.Name = prefix + member.ShortName;
5492 public void UpdateName (MemberBase member)
5494 MemberName.Name = prefix + member.ShortName;
5497 #region IMethodData Members
5499 public ToplevelBlock Block {
5509 public CallingConventions CallingConventions {
5511 return CallingConventions.Standard;
5515 public bool IsExcluded (EmitContext ec)
5520 public MemberName MethodName {
5526 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5527 public abstract Type[] ParameterTypes { get; }
5528 public abstract Type ReturnType { get; }
5529 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5533 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5535 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5536 a.Type == TypeManager.conditional_attribute_type) {
5537 Report.Error (1667, a.Location, "'{0}' is not valid on property or event accessors. It is valid on {1} declarations only", TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5541 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5542 if (declarative_security == null)
5543 declarative_security = new ListDictionary ();
5544 a.ExtractSecurityPermissionSet (declarative_security);
5548 if (a.Target == AttributeTargets.Method) {
5549 method_data.MethodBuilder.SetCustomAttribute (cb);
5553 if (a.Target == AttributeTargets.ReturnValue) {
5554 if (return_attributes == null)
5555 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5557 return_attributes.ApplyAttributeBuilder (a, cb);
5561 ApplyToExtraTarget (a, cb);
5564 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5566 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5569 public override bool Define()
5571 throw new NotSupportedException ();
5574 public virtual void Emit (TypeContainer container)
5576 method_data.Emit (container, this);
5578 if (declarative_security != null) {
5579 foreach (DictionaryEntry de in declarative_security) {
5580 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5587 public override bool IsClsCompliaceRequired(DeclSpace ds)
5592 public bool IsDuplicateImplementation (MethodCore method)
5594 if (Name != method.Name)
5597 Type[] param_types = method.ParameterTypes;
5599 if (param_types.Length != ParameterTypes.Length)
5602 for (int i = 0; i < param_types.Length; i++)
5603 if (param_types [i] != ParameterTypes [i])
5606 Report.SymbolRelatedToPreviousError (method);
5607 Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
5611 public new Location Location {
5613 return base.Location;
5618 // Represents header string for documentation comment.
5620 public override string DocCommentHeader {
5621 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5624 protected override void VerifyObsoleteAttribute()
5631 // Properties and Indexers both generate PropertyBuilders, we use this to share
5632 // their common bits.
5634 abstract public class PropertyBase : MethodCore {
5636 public class GetMethod: PropertyMethod
5638 static string[] attribute_targets = new string [] { "method", "return" };
5640 public GetMethod (MethodCore method):
5641 base (method, "get_")
5645 public GetMethod (MethodCore method, Accessor accessor):
5646 base (method, accessor, "get_")
5650 public override MethodBuilder Define(TypeContainer container)
5652 base.Define (container);
5654 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5656 if (!method_data.Define (container))
5659 return method_data.MethodBuilder;
5662 public override string GetSignatureForError (TypeContainer tc)
5664 return String.Concat (base.GetSignatureForError (tc), ".get");
5667 public override Type ReturnType {
5669 return method.MemberType;
5673 public override string[] ValidAttributeTargets {
5675 return attribute_targets;
5680 public class SetMethod: PropertyMethod {
5682 static string[] attribute_targets = new string [] { "method", "param", "return" };
5683 ImplicitParameter param_attr;
5685 public SetMethod (MethodCore method):
5686 base (method, "set_")
5690 public SetMethod (MethodCore method, Accessor accessor):
5691 base (method, accessor, "set_")
5695 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5697 if (a.Target == AttributeTargets.Parameter) {
5698 if (param_attr == null)
5699 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5701 param_attr.ApplyAttributeBuilder (a, cb);
5705 base.ApplyAttributeBuilder (a, cb);
5708 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5710 Parameter [] parms = new Parameter [1];
5711 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
5712 Parameters parameters = new Parameters (parms, null, method.Location);
5713 Type [] types = parameters.GetParameterInfo (ec);
5714 return new InternalParameters (types, parameters);
5717 public override MethodBuilder Define(TypeContainer container)
5719 if (container.EmitContext == null)
5720 throw new InternalErrorException ("SetMethod.Define called too early");
5722 base.Define (container);
5724 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5726 if (!method_data.Define (container))
5729 return method_data.MethodBuilder;
5732 public override string GetSignatureForError (TypeContainer tc)
5734 return String.Concat (base.GetSignatureForError (tc), ".set");
5737 public override Type[] ParameterTypes {
5739 return new Type[] { method.MemberType };
5743 public override Type ReturnType {
5745 return TypeManager.void_type;
5749 public override string[] ValidAttributeTargets {
5751 return attribute_targets;
5756 static string[] attribute_targets = new string [] { "property" };
5758 public abstract class PropertyMethod: AbstractPropertyEventMethod
5760 protected readonly MethodCore method;
5761 protected MethodAttributes flags;
5763 public PropertyMethod (MethodCore method, string prefix)
5764 : base (method, prefix)
5766 this.method = method;
5769 public PropertyMethod (MethodCore method, Accessor accessor,
5771 : base (method, accessor, prefix)
5773 this.method = method;
5774 this.ModFlags = accessor.ModFlags;
5776 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
5777 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
5778 Environment.Exit (1);
5782 public override AttributeTargets AttributeTargets {
5784 return AttributeTargets.Method;
5788 public override bool IsClsCompliaceRequired(DeclSpace ds)
5790 return method.IsClsCompliaceRequired (ds);
5793 public InternalParameters ParameterInfo
5796 return method_data.ParameterInfo;
5800 public virtual MethodBuilder Define (TypeContainer container)
5803 // Check for custom access modifier
5805 if (ModFlags == 0) {
5806 ModFlags = method.ModFlags;
5807 flags = method.flags;
5809 CheckModifiers (container, ModFlags);
5810 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
5811 flags = Modifiers.MethodAttr (ModFlags);
5812 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
5819 public override Type[] ParameterTypes {
5821 return TypeManager.NoTypes;
5825 public override EmitContext CreateEmitContext (TypeContainer tc,
5828 return new EmitContext (
5829 tc, method.Parent, method.Location, ig, ReturnType,
5830 method.ModFlags, false);
5833 public override ObsoleteAttribute GetObsoleteAttribute ()
5835 return method.GetObsoleteAttribute (method.Parent);
5838 public override string GetSignatureForError (TypeContainer tc)
5840 return String.Concat (tc.Name, '.', method.Name);
5843 void CheckModifiers (TypeContainer container, int modflags)
5846 int mflags = method.ModFlags & Modifiers.Accessibility;
5848 if ((mflags & Modifiers.PUBLIC) != 0) {
5849 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
5851 else if ((mflags & Modifiers.PROTECTED) != 0) {
5852 if ((mflags & Modifiers.INTERNAL) != 0)
5853 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
5855 flags |= Modifiers.PRIVATE;
5857 else if ((mflags & Modifiers.INTERNAL) != 0)
5858 flags |= Modifiers.PRIVATE;
5860 if ((mflags == modflags) || (modflags & (~flags)) != 0)
5861 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
5862 GetSignatureForError (container));
5867 public PropertyMethod Get, Set;
5868 public PropertyBuilder PropertyBuilder;
5869 public MethodBuilder GetBuilder, SetBuilder;
5871 protected EmitContext ec;
5873 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
5874 int allowed_mod, bool is_iface, MemberName name,
5875 Parameters parameters, Attributes attrs,
5877 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
5878 attrs, parameters, loc)
5882 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5884 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5885 a.Error_InvalidSecurityParent ();
5889 PropertyBuilder.SetCustomAttribute (cb);
5892 public override AttributeTargets AttributeTargets {
5894 return AttributeTargets.Property;
5898 public override bool Define ()
5903 if (!IsTypePermitted ())
5909 protected override bool DoDefine ()
5911 if (!base.DoDefine ())
5915 // Accessors modifiers check
5917 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
5918 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
5919 GetSignatureForError ());
5923 if ((Get.IsDummy || Set.IsDummy)
5924 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
5925 Report.Error (276, Location,
5926 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
5927 GetSignatureForError ());
5931 if (MemberType.IsAbstract && MemberType.IsSealed) {
5932 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
5936 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
5940 public override string GetSignatureForError()
5942 if (PropertyBuilder == null)
5943 return GetSignatureForError (Parent);
5945 return TypeManager.CSharpSignature (PropertyBuilder, false);
5949 protected override bool CheckForDuplications ()
5951 ArrayList ar = Parent.Indexers;
5953 int arLen = ar.Count;
5955 for (int i = 0; i < arLen; i++) {
5956 Indexer m = (Indexer) ar [i];
5957 if (IsDuplicateImplementation (m))
5962 ar = Parent.Properties;
5964 int arLen = ar.Count;
5966 for (int i = 0; i < arLen; i++) {
5967 Property m = (Property) ar [i];
5968 if (IsDuplicateImplementation (m))
5976 // TODO: rename to Resolve......
5977 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
5979 PropertyInfo parent_property = container.ParentCache.FindMemberToOverride (
5980 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
5982 if (parent_property == null)
5985 parent_ret_type = parent_property.PropertyType;
5986 MethodInfo get_accessor = parent_property.GetGetMethod (true);
5987 MethodInfo set_accessor = parent_property.GetSetMethod (true);
5988 MethodAttributes get_accessor_access, set_accessor_access;
5990 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
5991 if (Get != null && !Get.IsDummy && get_accessor == null) {
5992 Report.SymbolRelatedToPreviousError (parent_property);
5993 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
5996 if (Set != null && !Set.IsDummy && set_accessor == null) {
5997 Report.SymbolRelatedToPreviousError (parent_property);
5998 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
6003 // Check parent accessors access
6005 get_accessor_access = set_accessor_access = 0;
6006 if ((ModFlags & Modifiers.NEW) == 0) {
6007 if (get_accessor != null) {
6008 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6009 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6011 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6012 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6013 GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
6016 if (set_accessor != null) {
6017 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6018 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6020 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6021 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6022 GetSignatureForError (container), TypeManager.GetFullNameSignature (parent_property));
6027 // Get the less restrictive access
6029 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6032 public override void Emit ()
6035 // The PropertyBuilder can be null for explicit implementations, in that
6036 // case, we do not actually emit the ".property", so there is nowhere to
6037 // put the attribute
6039 if (PropertyBuilder != null && OptAttributes != null)
6040 OptAttributes.Emit (ec, this);
6052 /// Tests whether accessors are not in collision with some method (CS0111)
6054 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6056 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6059 protected override void UpdateMemberName ()
6061 base.UpdateMemberName ();
6063 Get.UpdateName (this);
6064 Set.UpdateName (this);
6067 protected override bool VerifyClsCompliance (DeclSpace ds)
6069 if (!base.VerifyClsCompliance (ds))
6072 if ((Get.ModFlags != ModFlags && !Get.IsDummy) || (Set.ModFlags != ModFlags && !Set.IsDummy)) {
6073 Report.Error (3025, Get.ModFlags != ModFlags ? Get.Location : Set.Location,
6074 "CLS-compliant accessors must have the same accessibility as their property");
6079 public override string[] ValidAttributeTargets {
6081 return attribute_targets;
6086 // Represents header string for documentation comment.
6088 public override string DocCommentHeader {
6089 get { return "P:"; }
6093 public class Property : PropertyBase, IIteratorContainer {
6094 const int AllowedModifiers =
6097 Modifiers.PROTECTED |
6098 Modifiers.INTERNAL |
6102 Modifiers.OVERRIDE |
6103 Modifiers.ABSTRACT |
6106 Modifiers.METHOD_YIELDS |
6109 const int AllowedInterfaceModifiers =
6112 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6113 MemberName name, Attributes attrs, Accessor get_block,
6114 Accessor set_block, Location loc)
6115 : base (ds, type, mod,
6116 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6117 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6120 if (get_block == null)
6121 Get = new GetMethod (this);
6123 Get = new GetMethod (this, get_block);
6125 if (set_block == null)
6126 Set = new SetMethod (this);
6128 Set = new SetMethod (this, set_block);
6131 public override bool Define ()
6133 if (!base.Define ())
6139 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6143 GetBuilder = Get.Define (Parent);
6144 if (GetBuilder == null)
6148 // Setup iterator if we are one
6150 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6151 Iterator iterator = new Iterator (
6152 Parent, "get", MemberType,
6153 TypeManager.NoTypes, Get.ParameterInfo,
6154 ModFlags, Get.Block, Location);
6156 if (!iterator.DefineIterator ())
6158 Get.Block = iterator.Block;
6163 SetBuilder = Set.Define (Parent);
6164 if (SetBuilder == null)
6167 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6170 // FIXME - PropertyAttributes.HasDefault ?
6172 PropertyAttributes prop_attr = PropertyAttributes.None;
6174 prop_attr |= PropertyAttributes.RTSpecialName |
6175 PropertyAttributes.SpecialName;
6177 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6178 Name, prop_attr, MemberType, null);
6181 PropertyBuilder.SetGetMethod (GetBuilder);
6184 PropertyBuilder.SetSetMethod (SetBuilder);
6186 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6190 public void SetYields ()
6192 ModFlags |= Modifiers.METHOD_YIELDS;
6197 /// Gigantic workaround for lameness in SRE follows :
6198 /// This class derives from EventInfo and attempts to basically
6199 /// wrap around the EventBuilder so that FindMembers can quickly
6200 /// return this in it search for members
6202 public class MyEventBuilder : EventInfo {
6205 // We use this to "point" to our Builder which is
6206 // not really a MemberInfo
6208 EventBuilder MyBuilder;
6211 // We "catch" and wrap these methods
6213 MethodInfo raise, remove, add;
6215 EventAttributes attributes;
6216 Type declaring_type, reflected_type, event_type;
6221 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6223 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6225 // And now store the values in our own fields.
6227 declaring_type = type_builder;
6229 reflected_type = type_builder;
6231 attributes = event_attr;
6234 this.event_type = event_type;
6238 // Methods that you have to override. Note that you only need
6239 // to "implement" the variants that take the argument (those are
6240 // the "abstract" methods, the others (GetAddMethod()) are
6243 public override MethodInfo GetAddMethod (bool nonPublic)
6248 public override MethodInfo GetRemoveMethod (bool nonPublic)
6253 public override MethodInfo GetRaiseMethod (bool nonPublic)
6259 // These methods make "MyEventInfo" look like a Builder
6261 public void SetRaiseMethod (MethodBuilder raiseMethod)
6263 raise = raiseMethod;
6264 MyBuilder.SetRaiseMethod (raiseMethod);
6267 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6269 remove = removeMethod;
6270 MyBuilder.SetRemoveOnMethod (removeMethod);
6273 public void SetAddOnMethod (MethodBuilder addMethod)
6276 MyBuilder.SetAddOnMethod (addMethod);
6279 public void SetCustomAttribute (CustomAttributeBuilder cb)
6281 MyBuilder.SetCustomAttribute (cb);
6284 public override object [] GetCustomAttributes (bool inherit)
6286 // FIXME : There's nothing which can be seemingly done here because
6287 // we have no way of getting at the custom attribute objects of the
6292 public override object [] GetCustomAttributes (Type t, bool inherit)
6294 // FIXME : Same here !
6298 public override bool IsDefined (Type t, bool b)
6303 public override EventAttributes Attributes {
6309 public override string Name {
6315 public override Type DeclaringType {
6317 return declaring_type;
6321 public override Type ReflectedType {
6323 return reflected_type;
6327 public Type EventType {
6333 public void SetUsed ()
6335 if (my_event != null)
6336 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6341 /// For case when event is declared like property (with add and remove accessors).
6343 public class EventProperty: Event {
6345 static string[] attribute_targets = new string [] { "event", "property" };
6347 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6348 bool is_iface, MemberName name, Object init,
6349 Attributes attrs, Accessor add, Accessor remove,
6351 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6353 Add = new AddDelegateMethod (this, add);
6354 Remove = new RemoveDelegateMethod (this, remove);
6356 // For this event syntax we don't report error CS0067
6357 // because it is hard to do it.
6361 public override string[] ValidAttributeTargets {
6363 return attribute_targets;
6369 /// Event is declared like field.
6371 public class EventField: Event {
6373 static string[] attribute_targets = new string [] { "event", "field", "method" };
6374 static string[] attribute_targets_interface = new string[] { "event", "method" };
6376 public EventField (TypeContainer parent, Expression type, int mod_flags,
6377 bool is_iface, MemberName name, Object init,
6378 Attributes attrs, Location loc)
6379 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6381 Add = new AddDelegateMethod (this);
6382 Remove = new RemoveDelegateMethod (this);
6385 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6387 if (a.Target == AttributeTargets.Field) {
6388 FieldBuilder.SetCustomAttribute (cb);
6392 if (a.Target == AttributeTargets.Method) {
6393 Add.ApplyAttributeBuilder (a, cb);
6394 Remove.ApplyAttributeBuilder (a, cb);
6398 base.ApplyAttributeBuilder (a, cb);
6401 public override string[] ValidAttributeTargets {
6403 return IsInterface ? attribute_targets_interface : attribute_targets;
6408 public abstract class Event : FieldBase {
6410 protected sealed class AddDelegateMethod: DelegateMethod
6413 public AddDelegateMethod (Event method):
6414 base (method, "add_")
6418 public AddDelegateMethod (Event method, Accessor accessor):
6419 base (method, accessor, "add_")
6423 protected override MethodInfo DelegateMethodInfo {
6425 return TypeManager.delegate_combine_delegate_delegate;
6431 protected sealed class RemoveDelegateMethod: DelegateMethod
6433 public RemoveDelegateMethod (Event method):
6434 base (method, "remove_")
6438 public RemoveDelegateMethod (Event method, Accessor accessor):
6439 base (method, accessor, "remove_")
6443 protected override MethodInfo DelegateMethodInfo {
6445 return TypeManager.delegate_remove_delegate_delegate;
6451 public abstract class DelegateMethod: AbstractPropertyEventMethod
6453 protected readonly Event method;
6454 ImplicitParameter param_attr;
6456 static string[] attribute_targets = new string [] { "method", "param", "return" };
6458 public DelegateMethod (Event method, string prefix)
6459 : base (method, prefix)
6461 this.method = method;
6464 public DelegateMethod (Event method, Accessor accessor, string prefix)
6465 : base (method, accessor, prefix)
6467 this.method = method;
6470 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6472 if (a.Target == AttributeTargets.Parameter) {
6473 if (param_attr == null)
6474 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6476 param_attr.ApplyAttributeBuilder (a, cb);
6480 base.ApplyAttributeBuilder (a, cb);
6483 public override AttributeTargets AttributeTargets {
6485 return AttributeTargets.Method;
6489 public override bool IsClsCompliaceRequired(DeclSpace ds)
6491 return method.IsClsCompliaceRequired (ds);
6494 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6496 method_data = new MethodData (method, ip, method.ModFlags,
6497 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6499 if (!method_data.Define (container))
6502 MethodBuilder mb = method_data.MethodBuilder;
6503 mb.DefineParameter (1, ParameterAttributes.None, "value");
6508 public override void Emit (TypeContainer tc)
6510 if (block != null) {
6515 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6516 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6518 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6519 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6520 ig.Emit (OpCodes.Ldsfld, field_info);
6521 ig.Emit (OpCodes.Ldarg_0);
6522 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6523 ig.Emit (OpCodes.Castclass, method.MemberType);
6524 ig.Emit (OpCodes.Stsfld, field_info);
6526 ig.Emit (OpCodes.Ldarg_0);
6527 ig.Emit (OpCodes.Ldarg_0);
6528 ig.Emit (OpCodes.Ldfld, field_info);
6529 ig.Emit (OpCodes.Ldarg_1);
6530 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6531 ig.Emit (OpCodes.Castclass, method.MemberType);
6532 ig.Emit (OpCodes.Stfld, field_info);
6534 ig.Emit (OpCodes.Ret);
6537 protected abstract MethodInfo DelegateMethodInfo { get; }
6539 public override Type[] ParameterTypes {
6541 return new Type[] { method.MemberType };
6545 public override Type ReturnType {
6547 return TypeManager.void_type;
6551 public override EmitContext CreateEmitContext (TypeContainer tc,
6554 return new EmitContext (
6555 tc, method.Parent, Location, ig, ReturnType,
6556 method.ModFlags, false);
6559 public override string GetSignatureForError (TypeContainer tc)
6561 return String.Concat (tc.Name, '.', method.Name);
6564 public override ObsoleteAttribute GetObsoleteAttribute ()
6566 return method.GetObsoleteAttribute (method.Parent);
6569 public override string[] ValidAttributeTargets {
6571 return attribute_targets;
6577 const int AllowedModifiers =
6580 Modifiers.PROTECTED |
6581 Modifiers.INTERNAL |
6586 Modifiers.OVERRIDE |
6590 const int AllowedInterfaceModifiers =
6593 public DelegateMethod Add, Remove;
6594 public MyEventBuilder EventBuilder;
6595 public MethodBuilder AddBuilder, RemoveBuilder;
6597 public Event (TypeContainer parent, Expression type, int mod_flags,
6598 bool is_iface, MemberName name, Object init, Attributes attrs,
6600 : base (parent, type, mod_flags,
6601 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6602 name, init, attrs, loc)
6604 IsInterface = is_iface;
6607 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6609 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6610 a.Error_InvalidSecurityParent ();
6614 EventBuilder.SetCustomAttribute (cb);
6617 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6619 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6622 public override AttributeTargets AttributeTargets {
6624 return AttributeTargets.Event;
6628 public override bool Define ()
6630 EventAttributes e_attr;
6631 e_attr = EventAttributes.None;
6636 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6637 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6638 "': abstract event can not have an initializer");
6642 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6643 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6644 "' : event must be of a delegate type");
6648 EmitContext ec = Parent.EmitContext;
6650 throw new InternalErrorException ("Event.Define called too early?");
6651 bool old_unsafe = ec.InUnsafe;
6652 ec.InUnsafe = InUnsafe;
6654 Parameter [] parms = new Parameter [1];
6655 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6656 Parameters parameters = new Parameters (parms, null, Location);
6657 Type [] types = parameters.GetParameterInfo (ec);
6658 InternalParameters ip = new InternalParameters (types, parameters);
6660 ec.InUnsafe = old_unsafe;
6666 // Now define the accessors
6669 AddBuilder = Add.Define (Parent, ip);
6670 if (AddBuilder == null)
6673 RemoveBuilder = Remove.Define (Parent, ip);
6674 if (RemoveBuilder == null)
6677 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6679 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6680 FieldBuilder = Parent.TypeBuilder.DefineField (
6682 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6683 TypeManager.RegisterPrivateFieldOfEvent (
6684 (EventInfo) EventBuilder, FieldBuilder);
6685 TypeManager.RegisterFieldBase (FieldBuilder, this);
6688 EventBuilder.SetAddOnMethod (AddBuilder);
6689 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6691 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6695 protected override bool CheckBase ()
6697 if (!base.CheckBase ())
6700 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6701 if (!(conflict_symbol is EventInfo)) {
6702 Report.SymbolRelatedToPreviousError (conflict_symbol);
6703 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6711 public override void Emit ()
6713 if (OptAttributes != null) {
6714 EmitContext ec = new EmitContext (
6715 Parent, Location, null, MemberType, ModFlags);
6716 OptAttributes.Emit (ec, this);
6721 Remove.Emit (Parent);
6727 public override string GetSignatureForError ()
6729 if (EventBuilder == null)
6730 return base.GetSignatureForError (Parent);
6732 return TypeManager.GetFullNameSignature (EventBuilder);
6736 // Represents header string for documentation comment.
6738 public override string DocCommentHeader {
6739 get { return "E:"; }
6744 public class Indexer : PropertyBase {
6746 class GetIndexerMethod: GetMethod
6748 public GetIndexerMethod (MethodCore method):
6753 public GetIndexerMethod (MethodCore method, Accessor accessor):
6754 base (method, accessor)
6758 public override Type[] ParameterTypes {
6760 return method.ParameterTypes;
6765 class SetIndexerMethod: SetMethod
6767 readonly Parameters parameters;
6769 public SetIndexerMethod (MethodCore method):
6774 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
6775 base (method, accessor)
6777 this.parameters = parameters;
6780 public override Type[] ParameterTypes {
6782 int top = method.ParameterTypes.Length;
6783 Type [] set_pars = new Type [top + 1];
6784 method.ParameterTypes.CopyTo (set_pars, 0);
6785 set_pars [top] = method.MemberType;
6790 protected override InternalParameters GetParameterInfo (EmitContext ec)
6792 Parameter [] fixed_parms = parameters.FixedParameters;
6794 if (fixed_parms == null){
6795 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
6796 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6797 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6799 // Here is the problem: the `value' parameter has
6800 // to come *after* the array parameter in the declaration
6802 // X (object [] x, Type value)
6805 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6806 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6810 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
6812 fixed_parms.CopyTo (tmp, 0);
6813 tmp [fixed_parms.Length] = new Parameter (
6814 method.Type, "value", Parameter.Modifier.NONE, null);
6816 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
6817 Type [] types = set_formal_params.GetParameterInfo (ec);
6819 return new InternalParameters (types, set_formal_params);
6824 const int AllowedModifiers =
6827 Modifiers.PROTECTED |
6828 Modifiers.INTERNAL |
6832 Modifiers.OVERRIDE |
6837 const int AllowedInterfaceModifiers =
6841 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
6842 bool is_iface, Parameters parameters, Attributes attrs,
6843 Accessor get_block, Accessor set_block, Location loc)
6844 : base (ds, type, mod,
6845 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6846 is_iface, name, parameters, attrs, loc)
6848 if (get_block == null)
6849 Get = new GetIndexerMethod (this);
6851 Get = new GetIndexerMethod (this, get_block);
6853 if (set_block == null)
6854 Set = new SetIndexerMethod (this);
6856 Set = new SetIndexerMethod (this, parameters, set_block);
6859 public override bool Define ()
6861 PropertyAttributes prop_attr =
6862 PropertyAttributes.RTSpecialName |
6863 PropertyAttributes.SpecialName;
6865 if (!base.Define ())
6868 if (MemberType == TypeManager.void_type) {
6869 Report.Error (620, Location, "Indexers cannot have void type");
6873 if (OptAttributes != null) {
6874 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
6875 if (indexer_attr != null) {
6876 // Remove the attribute from the list because it is not emitted
6877 OptAttributes.Attrs.Remove (indexer_attr);
6879 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
6881 if (IsExplicitImpl) {
6882 Report.Error (415, indexer_attr.Location,
6883 "The 'IndexerName' attribute is valid only on an" +
6884 "indexer that is not an explicit interface member declaration");
6888 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6889 Report.Error (609, indexer_attr.Location,
6890 "Cannot set the 'IndexerName' attribute on an indexer marked override");
6894 if (!Tokenizer.IsValidIdentifier (ShortName)) {
6895 Report.Error (633, indexer_attr.Location,
6896 "The argument to the 'IndexerName' attribute must be a valid identifier");
6900 UpdateMemberName ();
6904 if (InterfaceType != null) {
6905 string parent_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
6906 if (parent_IndexerName != Name)
6907 ShortName = parent_IndexerName;
6908 UpdateMemberName ();
6911 if (!Parent.AddToMemberContainer (this, true) ||
6912 !Parent.AddToMemberContainer (Get, true) || !Parent.AddToMemberContainer (Set, true))
6918 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6920 GetBuilder = Get.Define (Parent);
6921 if (GetBuilder == null)
6926 SetBuilder = Set.Define (Parent);
6927 if (SetBuilder == null)
6932 // Now name the parameters
6934 Parameter [] p = Parameters.FixedParameters;
6936 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
6937 Report.Error (631, Location, "ref and out are not valid in this context");
6943 for (i = 0; i < p.Length; ++i) {
6945 GetBuilder.DefineParameter (
6946 i + 1, p [i].Attributes, p [i].Name);
6949 SetBuilder.DefineParameter (
6950 i + 1, p [i].Attributes, p [i].Name);
6954 SetBuilder.DefineParameter (
6955 i + 1, ParameterAttributes.None, "value");
6957 if (i != ParameterTypes.Length) {
6958 Parameter array_param = Parameters.ArrayParameter;
6960 SetBuilder.DefineParameter (
6961 i + 1, array_param.Attributes, array_param.Name);
6965 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6966 Name, prop_attr, MemberType, ParameterTypes);
6969 PropertyBuilder.SetGetMethod (GetBuilder);
6972 PropertyBuilder.SetSetMethod (SetBuilder);
6974 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
6979 public override string GetSignatureForError ()
6981 if (PropertyBuilder == null)
6982 return GetSignatureForError (Parent);
6984 return TypeManager.CSharpSignature (PropertyBuilder, true);
6987 public override string GetSignatureForError(TypeContainer tc)
6989 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
6993 public class Operator : MethodCore, IIteratorContainer {
6995 const int AllowedModifiers =
7001 public enum OpType : byte {
7011 // Unary and Binary operators
7034 // Implicit and Explicit
7039 public readonly OpType OperatorType;
7040 public MethodBuilder OperatorMethodBuilder;
7042 public Method OperatorMethod;
7044 static string[] attribute_targets = new string [] { "method", "return" };
7046 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7047 int mod_flags, Parameters parameters,
7048 ToplevelBlock block, Attributes attrs, Location loc)
7049 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7050 new MemberName ("op_" + type), attrs, parameters, loc)
7052 OperatorType = type;
7056 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7058 OperatorMethod.ApplyAttributeBuilder (a, cb);
7061 public override AttributeTargets AttributeTargets {
7063 return AttributeTargets.Method;
7067 protected override bool CheckForDuplications()
7069 ArrayList ar = Parent.Operators;
7071 int arLen = ar.Count;
7073 for (int i = 0; i < arLen; i++) {
7074 Operator o = (Operator) ar [i];
7075 if (IsDuplicateImplementation (o))
7080 ar = Parent.Methods;
7082 int arLen = ar.Count;
7084 for (int i = 0; i < arLen; i++) {
7085 Method m = (Method) ar [i];
7086 if (IsDuplicateImplementation (m))
7094 public override bool Define ()
7097 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7098 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7099 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7106 if (MemberType == TypeManager.void_type) {
7107 Report.Error (590, Location, "User-defined operators cannot return void");
7111 OperatorMethod = new Method (
7112 Parent, Type, ModFlags, false, MemberName,
7113 Parameters, OptAttributes, Location);
7115 OperatorMethod.Block = Block;
7116 OperatorMethod.IsOperator = true;
7117 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7118 OperatorMethod.Define ();
7120 if (OperatorMethod.MethodBuilder == null)
7123 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7125 parameter_types = OperatorMethod.ParameterTypes;
7126 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7127 Type return_type = OperatorMethod.ReturnType;
7128 Type first_arg_type = parameter_types [0];
7133 // Rules for conversion operators
7135 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7136 if (first_arg_type == return_type && first_arg_type == declaring_type){
7139 "User-defined conversion cannot take an object of the " +
7140 "enclosing type and convert to an object of the enclosing" +
7145 if (first_arg_type != declaring_type && return_type != declaring_type){
7148 "User-defined conversion must convert to or from the " +
7153 if (first_arg_type == TypeManager.object_type ||
7154 return_type == TypeManager.object_type){
7157 "User-defined conversion cannot convert to or from " +
7162 if (first_arg_type.IsInterface || return_type.IsInterface){
7165 "User-defined conversion cannot convert to or from an " +
7170 if (first_arg_type.IsSubclassOf (return_type)
7171 || return_type.IsSubclassOf (first_arg_type)){
7172 if (declaring_type.IsSubclassOf (return_type)) {
7173 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7176 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7179 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7180 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7181 Report.Error (564, Location, "Overloaded shift operator must have the type of the first operand be the containing type, and the type of the second operand must be int");
7184 } else if (Parameters.FixedParameters.Length == 1) {
7185 // Checks for Unary operators
7187 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7188 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7189 Report.Error (448, Location,
7190 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7193 if (first_arg_type != declaring_type) {
7195 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7200 if (first_arg_type != declaring_type){
7203 "The parameter of a unary operator must be the " +
7208 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7209 if (return_type != TypeManager.bool_type){
7212 "The return type of operator True or False " +
7219 // Checks for Binary operators
7221 if (first_arg_type != declaring_type &&
7222 parameter_types [1] != declaring_type){
7225 "One of the parameters of a binary operator must " +
7226 "be the containing type");
7234 public override void Emit ()
7237 // abstract or extern methods have no bodies
7239 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7242 OperatorMethod.Emit ();
7246 // Operator cannot be override
7247 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
7252 public static string GetName (OpType ot)
7255 case OpType.LogicalNot:
7257 case OpType.OnesComplement:
7259 case OpType.Increment:
7261 case OpType.Decrement:
7267 case OpType.Addition:
7269 case OpType.Subtraction:
7271 case OpType.UnaryPlus:
7273 case OpType.UnaryNegation:
7275 case OpType.Multiply:
7277 case OpType.Division:
7279 case OpType.Modulus:
7281 case OpType.BitwiseAnd:
7283 case OpType.BitwiseOr:
7285 case OpType.ExclusiveOr:
7287 case OpType.LeftShift:
7289 case OpType.RightShift:
7291 case OpType.Equality:
7293 case OpType.Inequality:
7295 case OpType.GreaterThan:
7297 case OpType.LessThan:
7299 case OpType.GreaterThanOrEqual:
7301 case OpType.LessThanOrEqual:
7303 case OpType.Implicit:
7305 case OpType.Explicit:
7311 public override string GetSignatureForError (TypeContainer tc)
7313 StringBuilder sb = new StringBuilder ();
7314 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7315 Parameters.FixedParameters [0].GetSignatureForError ());
7317 if (Parameters.FixedParameters.Length > 1) {
7319 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7322 return sb.ToString ();
7325 public override string GetSignatureForError ()
7330 public override string ToString ()
7332 if (OperatorMethod == null)
7335 Type return_type = OperatorMethod.ReturnType;
7336 Type [] param_types = OperatorMethod.ParameterTypes;
7338 if (Parameters.FixedParameters.Length == 1)
7339 return String.Format (
7340 "{0} operator {1}({2})",
7341 TypeManager.CSharpName (return_type),
7342 GetName (OperatorType),
7345 return String.Format (
7346 "{0} operator {1}({2}, {3})",
7347 TypeManager.CSharpName (return_type),
7348 GetName (OperatorType),
7349 param_types [0], param_types [1]);
7352 public override string[] ValidAttributeTargets {
7354 return attribute_targets;
7358 public void SetYields ()
7360 ModFlags |= Modifiers.METHOD_YIELDS;
7365 // This is used to compare method signatures
7367 struct MethodSignature {
7369 public Type RetType;
7370 public Type [] Parameters;
7373 /// This delegate is used to extract methods which have the
7374 /// same signature as the argument
7376 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7378 public MethodSignature (string name, Type ret_type, Type [] parameters)
7383 if (parameters == null)
7384 Parameters = TypeManager.NoTypes;
7386 Parameters = parameters;
7389 public override string ToString ()
7392 if (Parameters.Length != 0){
7393 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7394 for (int i = 0; i < Parameters.Length; i++){
7395 sb.Append (Parameters [i]);
7396 if (i+1 < Parameters.Length)
7399 pars = sb.ToString ();
7402 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7405 public override int GetHashCode ()
7407 return Name.GetHashCode ();
7410 public override bool Equals (Object o)
7412 MethodSignature other = (MethodSignature) o;
7414 if (other.Name != Name)
7417 if (other.RetType != RetType)
7420 if (Parameters == null){
7421 if (other.Parameters == null)
7426 if (other.Parameters == null)
7429 int c = Parameters.Length;
7430 if (other.Parameters.Length != c)
7433 for (int i = 0; i < c; i++)
7434 if (other.Parameters [i] != Parameters [i])
7440 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7442 MethodSignature sig = (MethodSignature) filter_criteria;
7444 if (m.Name != sig.Name)
7448 MethodInfo mi = m as MethodInfo;
7449 PropertyInfo pi = m as PropertyInfo;
7452 ReturnType = mi.ReturnType;
7453 else if (pi != null)
7454 ReturnType = pi.PropertyType;
7459 // we use sig.RetType == null to mean `do not check the
7460 // method return value.
7462 if (sig.RetType != null)
7463 if (ReturnType != sig.RetType)
7468 args = TypeManager.GetArgumentTypes (mi);
7470 args = TypeManager.GetArgumentTypes (pi);
7471 Type [] sigp = sig.Parameters;
7473 if (args.Length != sigp.Length)
7476 for (int i = args.Length; i > 0; ){
7478 if (args [i] != sigp [i])