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;
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 base member cache and our member cache
459 MemberCache base_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)
477 return AddToContainer (symbol, String.Concat (Name, '.', symbol.Name), symbol.Name);
480 bool AddToTypeContainer (DeclSpace ds)
482 return AddToContainer (ds, ds.Name, ds.Basename);
485 public void AddConstant (Const constant)
487 if (!AddToMemberContainer (constant))
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))
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))
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) ||
622 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
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))
639 if (e is EventProperty) {
640 if (!AddToMemberContainer (e.Add))
643 if (!AddToMemberContainer (e.Remove))
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))
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 {
718 return AttributeTargets.Class;
720 return AttributeTargets.Struct;
722 return AttributeTargets.Interface;
724 throw new NotSupportedException ();
729 public ArrayList Types {
735 public MethodArrayList Methods {
741 public ArrayList Constants {
747 public ArrayList Interfaces {
753 public ArrayList Iterators {
761 return base_class_name;
765 public ArrayList Bases {
775 public ArrayList Fields {
781 public ArrayList InstanceConstructors {
783 return instance_constructors;
787 public ArrayList Properties {
793 public ArrayList Events {
799 public ArrayList Enums {
805 public ArrayList Indexers {
811 public ArrayList Operators {
817 public ArrayList Delegates {
823 public ArrayList Parts {
829 public virtual TypeAttributes TypeAttr {
831 return Modifiers.TypeAttr (ModFlags, this);
835 public string IndexerName {
837 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
842 // Emits the instance field initializers
844 public bool EmitFieldInitializers (EmitContext ec)
847 Expression instance_expr;
850 fields = initialized_static_fields;
851 instance_expr = null;
853 fields = initialized_fields;
854 instance_expr = new This (Location.Null).Resolve (ec);
860 foreach (Field f in fields){
861 Expression e = f.GetInitializerExpression (ec);
865 Location l = f.Location;
866 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
867 fe.InstanceExpression = instance_expr;
868 ExpressionStatement a = new Assign (fe, e, l);
870 a = a.ResolveStatement (ec);
874 a.EmitStatement (ec);
881 // Defines the default constructors
883 protected void DefineDefaultConstructor (bool is_static)
887 // The default constructor is public
888 // If the class is abstract, the default constructor is protected
889 // The default static constructor is private
891 int mods = Modifiers.PUBLIC;
893 mods = Modifiers.STATIC | Modifiers.PRIVATE;
894 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
895 mods = Modifiers.PROTECTED;
897 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
898 new ConstructorBaseInitializer (
899 null, Parameters.EmptyReadOnlyParameters,
905 c.Block = new ToplevelBlock (null, Location);
910 /// The pending methods that need to be implemented
911 // (interfaces or abstract methods)
913 public PendingImplementation Pending;
915 public abstract void Register ();
917 public abstract PendingImplementation GetPendingImplementations ();
919 TypeExpr[] GetPartialBases (out TypeExpr base_class, out bool error)
921 ArrayList ifaces = new ArrayList ();
924 Location base_loc = Location.Null;
926 foreach (ClassPart part in parts) {
927 TypeExpr new_base_class;
928 TypeExpr[] new_ifaces;
930 new_ifaces = part.GetClassBases (out new_base_class, out error);
934 if ((base_class != null) && (new_base_class != null) &&
935 !base_class.Equals (new_base_class)) {
936 Report.Error (263, part.Location,
937 "Partial declarations of `{0}' must " +
938 "not specify different base classes",
941 if (!Location.IsNull (base_loc))
942 Report.LocationOfPreviousError (base_loc);
948 if ((base_class == null) && (new_base_class != null)) {
949 base_class = new_base_class;
950 base_loc = part.Location;
953 if (new_ifaces == null)
956 foreach (TypeExpr iface in new_ifaces) {
958 foreach (TypeExpr old_iface in ifaces) {
959 if (old_iface.Equals (iface)) {
972 TypeExpr[] retval = new TypeExpr [ifaces.Count];
973 ifaces.CopyTo (retval, 0);
977 TypeExpr[] GetNormalBases (out TypeExpr base_class, out bool error)
981 int count = Bases.Count;
984 if (Kind == Kind.Class){
985 TypeExpr name = ResolveBaseTypeExpr (
986 (Expression) Bases [0], false, Location);
993 if (!name.IsInterface) {
994 // base_class could be a class, struct, enum, delegate.
995 // This is validated in GetClassBases.
1001 TypeExpr [] ifaces = new TypeExpr [count-start];
1003 for (i = start, j = 0; i < count; i++, j++){
1004 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1005 if (resolved == null) {
1010 ifaces [j] = resolved;
1018 /// This function computes the Base class and also the
1019 /// list of interfaces that the class or struct @c implements.
1021 /// The return value is an array (might be null) of
1022 /// interfaces implemented (as Types).
1024 /// The @base_class argument is set to the base object or null
1025 /// if this is `System.Object'.
1027 TypeExpr [] GetClassBases (out TypeExpr base_class, out bool error)
1036 ifaces = GetPartialBases (out base_class, out error);
1037 else if (Bases == null){
1041 ifaces = GetNormalBases (out base_class, out error);
1046 if ((base_class != null) && (Kind == Kind.Class)){
1048 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1049 Report.Error (1521, base_class.Location, "Invalid base type");
1054 if (base_class.IsSealed){
1056 Report.SymbolRelatedToPreviousError (base_class.Type);
1057 if (base_class.Type.IsAbstract) {
1058 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1060 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1065 if (!base_class.CanInheritFrom ()){
1066 Report.Error (644, Location,
1067 "`{0}' cannot inherit from special class `{1}'",
1068 Name, base_class.Name);
1073 if (!base_class.AsAccessible (this, ModFlags)) {
1074 Report.SymbolRelatedToPreviousError (base_class.Type);
1075 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1076 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1080 if (base_class != null)
1081 base_class_name = base_class.Name;
1086 int count = ifaces != null ? ifaces.Length : 0;
1088 for (i = 0; i < count; i++) {
1089 TypeExpr iface = (TypeExpr) ifaces [i];
1091 if (!iface.IsInterface) {
1093 if (Kind != Kind.Class) {
1094 string what = Kind == Kind.Struct ? "Struct" : "Interface";
1096 Report.Error (527, Location,
1097 "In {0} `{1}', type `{2}' is not "+
1098 "an interface", what, Name, iface.Name);
1100 else if (base_class != null)
1101 Report.Error (1721, Location,
1102 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1105 Report.Error (1722, Location,
1106 "In Class `{0}', `{1}' is not " +
1107 "an interface, a base class must be listed first", Name, iface.Name);
1112 for (int x = 0; x < i; x++) {
1113 if (iface.Equals (ifaces [x])) {
1114 Report.Error (528, Location,
1115 "`{0}' is already listed in " +
1116 "interface list", iface.Name);
1121 if ((Kind == Kind.Interface) &&
1122 !iface.AsAccessible (Parent, ModFlags)) {
1123 Report.Error (61, Location,
1124 "Inconsistent accessibility: base " +
1125 "interface `{0}' is less accessible " +
1126 "than interface `{1}'", iface.Name,
1141 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1143 public override TypeBuilder DefineType ()
1145 if (TypeBuilder != null)
1152 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
1159 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1161 TypeExpr[] iface_exprs = GetClassBases (out base_type, out error);
1165 if (base_type == null) {
1166 if (Kind == Kind.Class){
1167 if (RootContext.StdLib)
1168 base_type = TypeManager.system_object_expr;
1169 else if (Name != "System.Object")
1170 base_type = TypeManager.system_object_expr;
1171 } else if (Kind == Kind.Struct) {
1173 // If we are compiling our runtime,
1174 // and we are defining ValueType, then our
1175 // base is `System.Object'.
1177 if (!RootContext.StdLib && Name == "System.ValueType")
1178 base_type = TypeManager.system_object_expr;
1180 base_type = TypeManager.system_valuetype_expr;
1184 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1185 throw new Exception ();
1187 TypeAttributes type_attributes = TypeAttr;
1189 if (base_type != null) {
1190 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1191 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1192 ptype = base_type.ResolveType (ec);
1193 if (ptype == null) {
1201 if (TypeManager.NamespaceClash (Name, Location)) {
1206 ModuleBuilder builder = CodeGen.Module.Builder;
1207 TypeBuilder = builder.DefineType (
1208 Name, type_attributes, ptype, null);
1211 TypeBuilder builder = Parent.DefineType ();
1212 if (builder == null)
1215 TypeBuilder = builder.DefineNestedType (
1216 Basename, type_attributes, ptype, null);
1219 catch (ArgumentException) {
1220 Report.RuntimeMissingSupport (Location, "static classes");
1225 // Structs with no fields need to have at least one byte.
1226 // The right thing would be to set the PackingSize in a DefineType
1227 // but there are no functions that allow interfaces *and* the size to
1231 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1232 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1233 FieldAttributes.Private);
1236 // add interfaces that were not added at type creation
1237 if (iface_exprs != null) {
1238 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1239 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1240 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1241 if (ifaces == null) {
1246 foreach (Type itype in ifaces)
1247 TypeBuilder.AddInterfaceImplementation (itype);
1249 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1253 // Finish the setup for the EmitContext
1255 ec.ContainerType = TypeBuilder;
1257 TypeManager.AddUserType (Name, TypeBuilder, this);
1259 if ((base_type != null) && base_type.IsAttribute) {
1260 RootContext.RegisterAttribute (this);
1261 } else if (!(this is Iterator))
1262 RootContext.RegisterOrder (this);
1264 if (!DefineNestedTypes ()) {
1273 protected virtual bool DefineNestedTypes ()
1275 if (Interfaces != null) {
1276 foreach (TypeContainer iface in Interfaces)
1277 if (iface.DefineType () == null)
1281 if (Types != null) {
1282 foreach (TypeContainer tc in Types)
1283 if (tc.DefineType () == null)
1287 if (Delegates != null) {
1288 foreach (Delegate d in Delegates)
1289 if (d.DefineType () == null)
1293 if (Enums != null) {
1294 foreach (Enum en in Enums)
1295 if (en.DefineType () == null)
1299 if (Parts != null) {
1300 foreach (ClassPart part in Parts) {
1301 part.TypeBuilder = TypeBuilder;
1303 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1310 static void Error_KeywordNotAllowed (Location loc)
1312 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1316 /// Populates our TypeBuilder with fields and methods
1318 public override bool DefineMembers (TypeContainer container)
1320 if (members_defined)
1321 return members_defined_ok;
1323 members_defined_ok = DoDefineMembers ();
1324 members_defined = true;
1326 return members_defined_ok;
1329 bool DoDefineMembers ()
1332 // We need to be able to use the member cache while we are checking/defining
1334 if (TypeBuilder.BaseType != null)
1335 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
1337 if (TypeBuilder.IsInterface)
1338 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
1341 if ((ModFlags & Modifiers.NEW) != 0)
1342 Error_KeywordNotAllowed (Location);
1344 // HACK: missing implemenation
1345 // This is not fully functional. Better way how to handle this is to have recursive definition of containers
1346 // instead of flat as we have now.
1347 // Now we are not able to check inner attribute class because its parent had not been defined.
1349 // TODO: remove this if
1350 if (Parent.MemberCache != null) {
1351 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1352 if (conflict_symbol == null) {
1353 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1354 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1356 if ((ModFlags & Modifiers.NEW) == 0) {
1357 Report.SymbolRelatedToPreviousError (conflict_symbol);
1358 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1364 DefineContainerMembers (constants);
1365 DefineContainerMembers (fields);
1367 if ((Kind == Kind.Class) && !(this is ClassPart) && !(this is StaticClass)){
1368 if ((instance_constructors == null) &&
1369 !(this is StaticClass)) {
1370 if (default_constructor == null)
1371 DefineDefaultConstructor (false);
1374 if (initialized_static_fields != null &&
1375 default_static_constructor == null)
1376 DefineDefaultConstructor (true);
1379 if (Kind == Kind.Struct){
1381 // Structs can not have initialized instance
1384 if (initialized_static_fields != null &&
1385 default_static_constructor == null)
1386 DefineDefaultConstructor (true);
1388 if (initialized_fields != null)
1389 ReportStructInitializedInstanceError ();
1392 Pending = GetPendingImplementations ();
1394 if (parts != null) {
1395 foreach (ClassPart part in parts) {
1396 if (!part.DefineMembers (this))
1402 // Constructors are not in the defined_names array
1404 DefineContainerMembers (instance_constructors);
1406 if (default_static_constructor != null)
1407 default_static_constructor.Define ();
1409 DefineContainerMembers (properties);
1410 DefineContainerMembers (events);
1411 DefineContainerMembers (indexers);
1412 DefineContainerMembers (methods);
1413 DefineContainerMembers (operators);
1414 DefineContainerMembers (enums);
1415 DefineContainerMembers (delegates);
1418 if (!(this is ClassPart))
1419 member_cache = new MemberCache (this);
1422 if (parts != null) {
1423 foreach (ClassPart part in parts)
1424 part.member_cache = member_cache;
1427 if (iterators != null) {
1428 foreach (Iterator iterator in iterators) {
1429 if (iterator.DefineType () == null)
1433 foreach (Iterator iterator in iterators) {
1434 if (!iterator.DefineMembers (this))
1442 void ReportStructInitializedInstanceError ()
1444 string n = TypeBuilder.FullName;
1446 foreach (Field f in initialized_fields){
1449 "`" + n + "." + f.Name + "': can not have " +
1450 "instance field initializers in structs");
1454 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1457 mcal.DefineContainerMembers ();
1460 public override bool Define ()
1462 if (parts != null) {
1463 foreach (ClassPart part in parts) {
1464 if (!part.Define ())
1472 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1474 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1478 /// This function is based by a delegate to the FindMembers routine
1480 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1486 /// This filter is used by FindMembers, and we just keep
1487 /// a global for the filter to `AlwaysAccept'
1489 static MemberFilter accepting_filter;
1492 static TypeContainer ()
1494 accepting_filter = new MemberFilter (AlwaysAccept);
1497 public MethodInfo[] GetMethods ()
1499 ArrayList members = new ArrayList ();
1501 DefineMembers (null);
1503 if (methods != null) {
1504 int len = methods.Count;
1505 for (int i = 0; i < len; i++) {
1506 Method m = (Method) methods [i];
1508 members.Add (m.MethodBuilder);
1512 if (operators != null) {
1513 int len = operators.Count;
1514 for (int i = 0; i < len; i++) {
1515 Operator o = (Operator) operators [i];
1517 members.Add (o.OperatorMethodBuilder);
1521 if (properties != null) {
1522 int len = properties.Count;
1523 for (int i = 0; i < len; i++) {
1524 Property p = (Property) properties [i];
1526 if (p.GetBuilder != null)
1527 members.Add (p.GetBuilder);
1528 if (p.SetBuilder != null)
1529 members.Add (p.SetBuilder);
1533 if (indexers != null) {
1534 int len = indexers.Count;
1535 for (int i = 0; i < len; i++) {
1536 Indexer ix = (Indexer) indexers [i];
1538 if (ix.GetBuilder != null)
1539 members.Add (ix.GetBuilder);
1540 if (ix.SetBuilder != null)
1541 members.Add (ix.SetBuilder);
1545 if (events != null) {
1546 int len = events.Count;
1547 for (int i = 0; i < len; i++) {
1548 Event e = (Event) events [i];
1550 if (e.AddBuilder != null)
1551 members.Add (e.AddBuilder);
1552 if (e.RemoveBuilder != null)
1553 members.Add (e.RemoveBuilder);
1557 MethodInfo[] retMethods = new MethodInfo [members.Count];
1558 members.CopyTo (retMethods, 0);
1562 // Indicated whether container has StructLayout attribute set Explicit
1563 public virtual bool HasExplicitLayout {
1570 /// This method returns the members of this type just like Type.FindMembers would
1571 /// Only, we need to use this for types which are _being_ defined because MS'
1572 /// implementation can't take care of that.
1575 // FIXME: return an empty static array instead of null, that cleans up
1576 // some code and is consistent with some coding conventions I just found
1580 // Notice that in various cases we check if our field is non-null,
1581 // something that would normally mean that there was a bug elsewhere.
1583 // The problem happens while we are defining p-invoke methods, as those
1584 // will trigger a FindMembers, but this happens before things are defined
1586 // Since the whole process is a no-op, it is fine to check for null here.
1588 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1589 MemberFilter filter, object criteria)
1591 ArrayList members = null;
1594 if ((bf & BindingFlags.Public) != 0)
1595 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1597 if ((bf & BindingFlags.NonPublic) != 0)
1598 modflags |= Modifiers.PRIVATE;
1600 int static_mask = 0, static_flags = 0;
1601 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1602 case BindingFlags.Static:
1603 static_mask = static_flags = Modifiers.STATIC;
1606 case BindingFlags.Instance:
1607 static_mask = Modifiers.STATIC;
1612 static_mask = static_flags = 0;
1616 Timer.StartTimer (TimerType.TcFindMembers);
1619 filter = accepting_filter;
1621 if ((mt & MemberTypes.Field) != 0) {
1622 if (fields != null) {
1623 int len = fields.Count;
1624 for (int i = 0; i < len; i++) {
1625 Field f = (Field) fields [i];
1627 if ((f.ModFlags & modflags) == 0)
1629 if ((f.ModFlags & static_mask) != static_flags)
1632 FieldBuilder fb = f.FieldBuilder;
1633 if (fb != null && filter (fb, criteria) == true) {
1634 if (members == null)
1635 members = new ArrayList ();
1642 if (constants != null) {
1643 int len = constants.Count;
1644 for (int i = 0; i < len; i++) {
1645 Const con = (Const) constants [i];
1647 if ((con.ModFlags & modflags) == 0)
1649 if ((con.ModFlags & static_mask) != static_flags)
1652 FieldBuilder fb = con.FieldBuilder;
1653 if (fb != null && filter (fb, criteria) == true) {
1654 if (members == null)
1655 members = new ArrayList ();
1663 if ((mt & MemberTypes.Method) != 0) {
1664 if (methods != null) {
1665 int len = methods.Count;
1666 for (int i = 0; i < len; i++) {
1667 Method m = (Method) methods [i];
1669 if ((m.ModFlags & modflags) == 0)
1671 if ((m.ModFlags & static_mask) != static_flags)
1674 MethodBuilder mb = m.MethodBuilder;
1676 if (mb != null && filter (mb, criteria) == true) {
1677 if (members == null)
1678 members = new ArrayList ();
1685 if (operators != null) {
1686 int len = operators.Count;
1687 for (int i = 0; i < len; i++) {
1688 Operator o = (Operator) operators [i];
1690 if ((o.ModFlags & modflags) == 0)
1692 if ((o.ModFlags & static_mask) != static_flags)
1695 MethodBuilder ob = o.OperatorMethodBuilder;
1696 if (ob != null && filter (ob, criteria) == true) {
1697 if (members == null)
1698 members = new ArrayList ();
1705 if (properties != null) {
1706 int len = properties.Count;
1707 for (int i = 0; i < len; i++) {
1708 Property p = (Property) properties [i];
1710 if ((p.ModFlags & modflags) == 0)
1712 if ((p.ModFlags & static_mask) != static_flags)
1718 if (b != null && filter (b, criteria) == true) {
1719 if (members == null)
1720 members = new ArrayList ();
1726 if (b != null && filter (b, criteria) == true) {
1727 if (members == null)
1728 members = new ArrayList ();
1735 if (indexers != null) {
1736 int len = indexers.Count;
1737 for (int i = 0; i < len; i++) {
1738 Indexer ix = (Indexer) indexers [i];
1740 if ((ix.ModFlags & modflags) == 0)
1742 if ((ix.ModFlags & static_mask) != static_flags)
1748 if (b != null && filter (b, criteria) == true) {
1749 if (members == null)
1750 members = new ArrayList ();
1756 if (b != null && filter (b, criteria) == true) {
1757 if (members == null)
1758 members = new ArrayList ();
1766 if ((mt & MemberTypes.Event) != 0) {
1767 if (events != null) {
1768 int len = events.Count;
1769 for (int i = 0; i < len; i++) {
1770 Event e = (Event) events [i];
1772 if ((e.ModFlags & modflags) == 0)
1774 if ((e.ModFlags & static_mask) != static_flags)
1777 MemberInfo eb = e.EventBuilder;
1778 if (eb != null && filter (eb, criteria) == true) {
1779 if (members == null)
1780 members = new ArrayList ();
1782 members.Add (e.EventBuilder);
1788 if ((mt & MemberTypes.Property) != 0){
1789 if (properties != null) {
1790 int len = properties.Count;
1791 for (int i = 0; i < len; i++) {
1792 Property p = (Property) properties [i];
1794 if ((p.ModFlags & modflags) == 0)
1796 if ((p.ModFlags & static_mask) != static_flags)
1799 MemberInfo pb = p.PropertyBuilder;
1800 if (pb != null && filter (pb, criteria) == true) {
1801 if (members == null)
1802 members = new ArrayList ();
1804 members.Add (p.PropertyBuilder);
1809 if (indexers != null) {
1810 int len = indexers.Count;
1811 for (int i = 0; i < len; i++) {
1812 Indexer ix = (Indexer) indexers [i];
1814 if ((ix.ModFlags & modflags) == 0)
1816 if ((ix.ModFlags & static_mask) != static_flags)
1819 MemberInfo ib = ix.PropertyBuilder;
1820 if (ib != null && filter (ib, criteria) == true) {
1821 if (members == null)
1822 members = new ArrayList ();
1824 members.Add (ix.PropertyBuilder);
1830 if ((mt & MemberTypes.NestedType) != 0) {
1831 if (types != null) {
1832 int len = types.Count;
1833 for (int i = 0; i < len; i++) {
1834 TypeContainer t = (TypeContainer) types [i];
1836 if ((t.ModFlags & modflags) == 0)
1839 TypeBuilder tb = t.TypeBuilder;
1840 if (tb != null && (filter (tb, criteria) == true)) {
1841 if (members == null)
1842 members = new ArrayList ();
1849 if (enums != null) {
1850 int len = enums.Count;
1851 for (int i = 0; i < len; i++) {
1852 Enum en = (Enum) enums [i];
1854 if ((en.ModFlags & modflags) == 0)
1857 TypeBuilder tb = en.TypeBuilder;
1858 if (tb != null && (filter (tb, criteria) == true)) {
1859 if (members == null)
1860 members = new ArrayList ();
1867 if (delegates != null) {
1868 int len = delegates.Count;
1869 for (int i = 0; i < len; i++) {
1870 Delegate d = (Delegate) delegates [i];
1872 if ((d.ModFlags & modflags) == 0)
1875 TypeBuilder tb = d.TypeBuilder;
1876 if (tb != null && (filter (tb, criteria) == true)) {
1877 if (members == null)
1878 members = new ArrayList ();
1885 if (interfaces != null) {
1886 int len = interfaces.Count;
1887 for (int i = 0; i < len; i++) {
1888 TypeContainer iface = (TypeContainer) interfaces [i];
1890 if ((iface.ModFlags & modflags) == 0)
1893 TypeBuilder tb = iface.TypeBuilder;
1894 if (tb != null && (filter (tb, criteria) == true)) {
1895 if (members == null)
1896 members = new ArrayList ();
1904 if ((mt & MemberTypes.Constructor) != 0){
1905 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1906 int len = instance_constructors.Count;
1907 for (int i = 0; i < len; i++) {
1908 Constructor c = (Constructor) instance_constructors [i];
1910 ConstructorBuilder cb = c.ConstructorBuilder;
1911 if (cb != null && filter (cb, criteria) == true) {
1912 if (members == null)
1913 members = new ArrayList ();
1920 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1921 ConstructorBuilder cb =
1922 default_static_constructor.ConstructorBuilder;
1924 if (cb != null && filter (cb, criteria) == true) {
1925 if (members == null)
1926 members = new ArrayList ();
1934 // Lookup members in base if requested.
1936 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1937 if (TypeBuilder.BaseType != null) {
1938 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1939 if (list.Count > 0) {
1940 if (members == null)
1941 members = new ArrayList ();
1943 members.AddRange (list);
1946 if (ifaces != null) {
1947 foreach (Type base_type in ifaces) {
1948 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1950 if (list.Count > 0) {
1951 if (members == null)
1952 members = new ArrayList ();
1953 members.AddRange (list);
1959 Timer.StopTimer (TimerType.TcFindMembers);
1961 if (members == null)
1962 return MemberList.Empty;
1964 return new MemberList (members);
1967 public override MemberCache MemberCache {
1969 return member_cache;
1973 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1974 MemberFilter filter, object criteria)
1976 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1979 return ds.FindMembers (mt, bf, filter, criteria);
1981 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1986 // FindMethods will look for methods not only in the type `t', but in
1987 // any interfaces implemented by the type.
1989 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1990 MemberFilter filter, object criteria)
1996 /// Emits the values for the constants
1998 public void EmitConstants ()
2000 if (constants != null)
2001 foreach (Const con in constants)
2006 protected virtual void VerifyMembers (EmitContext ec)
2009 // Check for internal or private fields that were never assigned
2011 if (RootContext.WarningLevel >= 4) {
2012 if (fields != null){
2013 foreach (Field f in fields) {
2014 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2017 if ((f.status & Field.Status.USED) == 0){
2018 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2023 // Only report 649 on level 4
2025 if (RootContext.WarningLevel < 4)
2028 if ((f.status & Field.Status.ASSIGNED) != 0)
2031 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2038 /// Emits the code, this step is performed after all
2039 /// the types, enumerations, constructors
2041 public void EmitType ()
2043 if (OptAttributes != null)
2044 OptAttributes.Emit (ec, this);
2048 if (instance_constructors != null) {
2049 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2050 bool has_compliant_args = false;
2052 foreach (Constructor c in instance_constructors) {
2055 if (has_compliant_args)
2058 has_compliant_args = c.HasCompliantArgs;
2060 if (!has_compliant_args)
2061 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2063 foreach (Constructor c in instance_constructors)
2070 if (default_static_constructor != null)
2071 default_static_constructor.Emit ();
2073 if (methods != null)
2074 foreach (Method m in methods)
2077 if (operators != null)
2078 foreach (Operator o in operators)
2081 if (properties != null)
2082 foreach (Property p in properties)
2085 if (indexers != null){
2090 foreach (Field f in fields)
2093 if (events != null){
2094 foreach (Event e in Events)
2098 if (delegates != null) {
2099 foreach (Delegate d in Delegates) {
2104 if (enums != null) {
2105 foreach (Enum e in enums) {
2110 if (parts != null) {
2111 foreach (ClassPart part in parts)
2115 if ((Pending != null) && !(this is ClassPart))
2116 if (Pending.VerifyPendingMethods ())
2121 if (iterators != null)
2122 foreach (Iterator iterator in iterators)
2123 iterator.EmitType ();
2125 // if (types != null)
2126 // foreach (TypeContainer tc in types)
2130 public override void CloseType ()
2132 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2136 caching_flags |= Flags.CloseTypeCreated;
2137 TypeBuilder.CreateType ();
2138 } catch (TypeLoadException){
2140 // This is fine, the code still created the type
2142 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2143 // Console.WriteLine (e.Message);
2145 Console.WriteLine ("In type: " + Name);
2150 foreach (Enum en in Enums)
2154 foreach (TypeContainer tc in Types)
2155 if (tc.Kind == Kind.Struct)
2158 foreach (TypeContainer tc in Types)
2159 if (tc.Kind != Kind.Struct)
2163 if (Delegates != null)
2164 foreach (Delegate d in Delegates)
2167 if (Iterators != null)
2168 foreach (Iterator i in Iterators)
2176 initialized_fields = null;
2177 initialized_static_fields = null;
2186 default_constructor = null;
2187 default_static_constructor = null;
2189 OptAttributes = null;
2192 member_cache = null;
2195 // TODO: make it obsolete and use GetSignatureForError
2196 public string MakeName (string n)
2198 return "`" + Name + "." + n + "'";
2202 // Performs the validation on a Method's modifiers (properties have
2203 // the same properties).
2205 public bool MethodModifiersValid (MemberCore mc)
2207 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2208 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2209 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2211 int flags = mc.ModFlags;
2214 // At most one of static, virtual or override
2216 if ((flags & Modifiers.STATIC) != 0){
2217 if ((flags & vao) != 0){
2218 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2219 GetSignatureForError ());
2224 if (Kind == Kind.Struct){
2225 if ((flags & va) != 0){
2226 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2231 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2232 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2237 // If the declaration includes the abstract modifier, then the
2238 // declaration does not include static, virtual or extern
2240 if ((flags & Modifiers.ABSTRACT) != 0){
2241 if ((flags & Modifiers.EXTERN) != 0){
2243 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2247 if ((flags & Modifiers.SEALED) != 0) {
2248 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2252 if ((flags & Modifiers.VIRTUAL) != 0){
2253 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2257 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2258 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2263 if ((flags & Modifiers.PRIVATE) != 0){
2264 if ((flags & vao) != 0){
2265 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2270 if ((flags & Modifiers.SEALED) != 0){
2271 if ((flags & Modifiers.OVERRIDE) == 0){
2272 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2280 public bool UserDefinedStaticConstructor {
2282 return default_static_constructor != null;
2286 public Constructor DefaultStaticConstructor {
2287 get { return default_static_constructor; }
2290 protected override bool VerifyClsCompliance (DeclSpace ds)
2292 if (!base.VerifyClsCompliance (ds))
2297 Type base_type = TypeBuilder.BaseType;
2298 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2299 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2302 if (!Parent.IsClsCompliaceRequired (ds)) {
2303 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2304 GetSignatureForError (), Parent.GetSignatureForError ());
2311 /// Checks whether container name is CLS Compliant
2313 void VerifyClsName ()
2315 Hashtable base_members = base_cache == null ?
2317 base_cache.GetPublicMembers ();
2318 Hashtable this_members = new Hashtable ();
2320 foreach (DictionaryEntry entry in defined_names) {
2321 MemberCore mc = (MemberCore)entry.Value;
2322 if (!mc.IsClsCompliaceRequired (this))
2325 string name = (string)entry.Key;
2326 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2328 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2329 object found = base_members [lcase];
2330 if (found == null) {
2331 found = this_members [lcase];
2332 if (found == null) {
2333 this_members.Add (lcase, mc);
2338 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2341 if (found is MemberInfo) {
2342 if (basename == ((MemberInfo)found).Name)
2344 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2346 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2348 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2354 /// Performs checks for an explicit interface implementation. First it
2355 /// checks whether the `interface_type' is a base inteface implementation.
2356 /// Then it checks whether `name' exists in the interface type.
2358 public virtual bool VerifyImplements (Type interface_type, string full,
2359 string name, Location loc)
2363 if (ifaces != null){
2364 foreach (Type t in ifaces){
2365 if (t == interface_type){
2373 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2374 full, interface_type.FullName);
2381 protected override void VerifyObsoleteAttribute()
2383 CheckUsageOfObsoleteAttribute (ptype);
2388 foreach (Type iface in ifaces) {
2389 CheckUsageOfObsoleteAttribute (iface);
2398 string IMemberContainer.Name {
2404 Type IMemberContainer.Type {
2410 MemberCache IMemberContainer.MemberCache {
2412 return member_cache;
2416 bool IMemberContainer.IsInterface {
2418 return Kind == Kind.Interface;
2422 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2424 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2428 // Generates xml doc comments (if any), and if required,
2429 // handle warning report.
2431 internal override void GenerateDocComment (DeclSpace ds)
2433 DocUtil.GenerateTypeDocComment (this, ds);
2436 public override string DocCommentHeader {
2437 get { return "T:"; }
2440 public virtual MemberCache BaseCache {
2447 public class PartialContainer : TypeContainer {
2449 public readonly Namespace Namespace;
2450 public readonly int OriginalModFlags;
2451 public readonly int AllowedModifiers;
2452 public readonly TypeAttributes DefaultTypeAttributes;
2454 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2455 MemberName member_name, int mod_flags, Kind kind,
2458 PartialContainer pc;
2459 string full_name = member_name.GetName (true);
2460 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2462 pc = ds as PartialContainer;
2466 260, ds.Location, "Missing partial modifier " +
2467 "on declaration of type `{0}'; another " +
2468 "partial implementation of this type exists",
2469 member_name.GetPartialName());
2471 Report.LocationOfPreviousError (loc);
2475 if (pc.Kind != kind) {
2477 261, loc, "Partial declarations of `{0}' " +
2478 "must be all classes, all structs or " +
2479 "all interfaces", member_name.GetPartialName ());
2483 if (pc.OriginalModFlags != mod_flags) {
2485 262, loc, "Partial declarations of `{0}' " +
2486 "have conflicting accessibility modifiers",
2487 member_name.GetPartialName ());
2494 pc = new PartialContainer (ns, parent, member_name, mod_flags, kind, loc);
2495 RootContext.Tree.RecordDecl (full_name, pc);
2496 parent.AddType (pc);
2501 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2502 MemberName name, int mod, Attributes attrs,
2503 Kind kind, Location loc)
2505 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2507 // An error occured; create a dummy container, but don't
2509 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2512 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2517 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2518 MemberName name, int mod, Kind kind, Location l)
2519 : base (ns, parent, name, null, kind, l)
2521 this.Namespace = ns.NS;
2525 AllowedModifiers = Class.AllowedModifiers;
2526 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2530 AllowedModifiers = Struct.AllowedModifiers;
2531 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2534 case Kind.Interface:
2535 AllowedModifiers = Interface.AllowedModifiers;
2536 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2540 throw new InvalidOperationException ();
2544 if (parent.Parent == null)
2545 accmods = Modifiers.INTERNAL;
2547 accmods = Modifiers.PRIVATE;
2549 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2550 this.OriginalModFlags = mod;
2553 public override void Register ()
2555 if (Kind == Kind.Interface)
2556 Parent.AddInterface (this);
2557 else if (Kind == Kind.Class || Kind == Kind.Struct)
2558 Parent.AddClassOrStruct (this);
2560 throw new InvalidOperationException ();
2563 public override PendingImplementation GetPendingImplementations ()
2565 return PendingImplementation.GetPendingImplementations (this);
2568 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2571 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2576 public override TypeAttributes TypeAttr {
2578 return base.TypeAttr | DefaultTypeAttributes;
2583 public class ClassPart : TypeContainer, IMemberContainer {
2584 public readonly PartialContainer PartialContainer;
2585 public readonly bool IsPartial;
2587 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2588 int mod, Attributes attrs, Kind kind, Location l)
2589 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2591 this.PartialContainer = parent;
2592 this.IsPartial = true;
2595 if (parent.Parent == null)
2596 accmods = Modifiers.INTERNAL;
2598 accmods = Modifiers.PRIVATE;
2600 this.ModFlags = Modifiers.Check (
2601 parent.AllowedModifiers, mod, accmods, l);
2604 public override void Register ()
2608 public override PendingImplementation GetPendingImplementations ()
2610 return PartialContainer.Pending;
2613 public override bool VerifyImplements (Type interface_type, string full,
2614 string name, Location loc)
2616 return PartialContainer.VerifyImplements (
2617 interface_type, full, name, loc);
2620 public override MemberCache BaseCache {
2622 return PartialContainer.BaseCache;
2627 public abstract class ClassOrStruct : TypeContainer {
2628 bool hasExplicitLayout = false;
2629 ListDictionary declarative_security;
2631 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2632 MemberName name, Attributes attrs, Kind kind,
2634 : base (ns, parent, name, attrs, kind, l)
2638 public override PendingImplementation GetPendingImplementations ()
2640 return PendingImplementation.GetPendingImplementations (this);
2643 public override bool HasExplicitLayout {
2645 return hasExplicitLayout;
2649 protected override void VerifyMembers (EmitContext ec)
2651 base.VerifyMembers (ec);
2653 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2654 foreach (Event e in events){
2656 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2661 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2663 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2664 if (declarative_security == null)
2665 declarative_security = new ListDictionary ();
2667 a.ExtractSecurityPermissionSet (declarative_security);
2671 if (a.Type == TypeManager.struct_layout_attribute_type
2672 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2673 hasExplicitLayout = true;
2675 base.ApplyAttributeBuilder (a, cb);
2678 public override void Emit()
2682 if (declarative_security != null) {
2683 foreach (DictionaryEntry de in declarative_security) {
2684 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2689 public override void Register ()
2691 Parent.AddClassOrStruct (this);
2696 /// Class handles static classes declaration
2698 public sealed class StaticClass: Class {
2699 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2700 Attributes attrs, Location l)
2701 : base (ns, parent, name, mod, attrs, l)
2703 if (RootContext.Version == LanguageVersion.ISO_1) {
2704 Report.FeatureIsNotStandardized (l, "static classes");
2705 Environment.Exit (1);
2709 protected override int AllowedModifiersProp {
2711 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2712 Modifiers.STATIC | Modifiers.UNSAFE;
2716 protected override void DefineContainerMembers (MemberCoreArrayList list)
2721 foreach (MemberCore m in list) {
2722 if (m is Operator) {
2723 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2727 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2730 if (m is Constructor) {
2731 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2735 if (m is Destructor) {
2736 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2740 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2743 base.DefineContainerMembers (list);
2746 public override TypeBuilder DefineType()
2748 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2749 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2753 TypeBuilder tb = base.DefineType ();
2757 if (ptype != TypeManager.object_type) {
2758 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2762 if (ifaces != null) {
2763 foreach (Type t in ifaces)
2764 Report.SymbolRelatedToPreviousError (t);
2765 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2770 public override TypeAttributes TypeAttr {
2772 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2777 public class Class : ClassOrStruct {
2778 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2779 public const int AllowedModifiers =
2782 Modifiers.PROTECTED |
2783 Modifiers.INTERNAL |
2785 Modifiers.ABSTRACT |
2789 // Information in the case we are an attribute type
2790 AttributeUsageAttribute attribute_usage;
2792 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2793 Attributes attrs, Location l)
2794 : base (ns, parent, name, attrs, Kind.Class, l)
2796 this.ModFlags = mod;
2797 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2800 virtual protected int AllowedModifiersProp {
2802 return AllowedModifiers;
2806 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2808 if (a.UsageAttribute != null) {
2809 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2810 TypeBuilder.FullName != "System.Attribute") {
2811 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2813 attribute_usage = a.UsageAttribute;
2816 base.ApplyAttributeBuilder (a, cb);
2819 public AttributeUsageAttribute AttributeUsage {
2821 return attribute_usage;
2825 public const TypeAttributes DefaultTypeAttributes =
2826 TypeAttributes.AutoLayout | TypeAttributes.Class;
2828 public override TypeBuilder DefineType()
2830 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2831 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2835 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2836 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2838 return base.DefineType ();
2842 // FIXME: How do we deal with the user specifying a different
2845 public override TypeAttributes TypeAttr {
2847 return base.TypeAttr | DefaultTypeAttributes;
2852 public class Struct : ClassOrStruct {
2854 // Modifiers allowed in a struct declaration
2856 public const int AllowedModifiers =
2859 Modifiers.PROTECTED |
2860 Modifiers.INTERNAL |
2864 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2865 int mod, Attributes attrs, Location l)
2866 : base (ns, parent, name, attrs, Kind.Struct, l)
2870 if (parent.Parent == null)
2871 accmods = Modifiers.INTERNAL;
2873 accmods = Modifiers.PRIVATE;
2875 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2877 this.ModFlags |= Modifiers.SEALED;
2880 public const TypeAttributes DefaultTypeAttributes =
2881 TypeAttributes.SequentialLayout |
2882 TypeAttributes.Sealed |
2883 TypeAttributes.BeforeFieldInit;
2886 // FIXME: Allow the user to specify a different set of attributes
2887 // in some cases (Sealed for example is mandatory for a class,
2888 // but what SequentialLayout can be changed
2890 public override TypeAttributes TypeAttr {
2892 return base.TypeAttr | DefaultTypeAttributes;
2900 public class Interface : TypeContainer, IMemberContainer {
2902 /// Modifiers allowed in a class declaration
2904 public const int AllowedModifiers =
2907 Modifiers.PROTECTED |
2908 Modifiers.INTERNAL |
2912 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2913 Attributes attrs, Location l)
2914 : base (ns, parent, name, attrs, Kind.Interface, l)
2918 if (parent.Parent == null)
2919 accmods = Modifiers.INTERNAL;
2921 accmods = Modifiers.PRIVATE;
2923 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2926 public override void Register ()
2928 Parent.AddInterface (this);
2931 public override PendingImplementation GetPendingImplementations ()
2936 public const TypeAttributes DefaultTypeAttributes =
2937 TypeAttributes.AutoLayout |
2938 TypeAttributes.Abstract |
2939 TypeAttributes.Interface;
2941 public override TypeAttributes TypeAttr {
2943 return base.TypeAttr | DefaultTypeAttributes;
2948 public abstract class MethodCore : MemberBase {
2949 public readonly Parameters Parameters;
2950 protected ToplevelBlock block;
2953 // Parameters, cached for semantic analysis.
2955 protected InternalParameters parameter_info;
2956 protected Type [] parameter_types;
2958 // Whether this is an operator method.
2959 public bool IsOperator;
2962 // The method we're overriding if this is an override method.
2964 protected MethodInfo base_method = null;
2966 static string[] attribute_targets = new string [] { "method", "return" };
2968 public MethodCore (TypeContainer parent, Expression type, int mod,
2969 int allowed_mod, bool is_interface, MemberName name,
2970 Attributes attrs, Parameters parameters, Location loc)
2971 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
2974 Parameters = parameters;
2975 IsInterface = is_interface;
2979 // Returns the System.Type array for the parameters of this method
2981 public Type [] ParameterTypes {
2983 return parameter_types;
2987 public InternalParameters ParameterInfo
2990 return parameter_info;
2994 public ToplevelBlock Block {
3004 protected override bool CheckBase ()
3006 if (!base.CheckBase ())
3009 // Check whether arguments were correct.
3010 if (!DoDefineParameters ())
3013 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3019 // Is null for System.Object while compiling corlib and base interfaces
3020 if (Parent.BaseCache == null) {
3021 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3022 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3027 Type base_ret_type = null;
3028 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3030 // method is override
3031 if (base_method != null) {
3033 if (!CheckMethodAgainstBase ())
3036 if ((ModFlags & Modifiers.NEW) == 0) {
3037 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3038 Report.SymbolRelatedToPreviousError (base_method);
3039 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3040 "change return type when overriding inherited member");
3044 if (base_method.IsAbstract && !IsInterface) {
3045 Report.SymbolRelatedToPreviousError (base_method);
3046 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3051 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3052 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3056 if (RootContext.WarningLevel > 2) {
3057 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3058 Parent.Methods.HasEquals = true;
3059 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3060 Parent.Methods.HasGetHashCode = true;
3063 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3064 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3066 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3067 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3068 Report.SymbolRelatedToPreviousError (base_method);
3069 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3076 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3077 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3078 if (conflict_symbol != null) {
3079 Report.SymbolRelatedToPreviousError (conflict_symbol);
3080 if (this is PropertyBase)
3081 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3083 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3085 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3089 if (conflict_symbol == null) {
3090 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3091 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3096 if ((ModFlags & Modifiers.NEW) == 0) {
3097 if (this is Method && conflict_symbol is MethodBase)
3100 Report.SymbolRelatedToPreviousError (conflict_symbol);
3101 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3109 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3110 // that have been defined.
3112 // `name' is the user visible name for reporting errors (this is used to
3113 // provide the right name regarding method names and properties)
3115 bool CheckMethodAgainstBase ()
3119 // TODO: replace with GetSignatureForError
3120 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3122 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3123 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3125 506, Location, Parent.MakeName (Name) +
3126 ": cannot override inherited member `" +
3127 name + "' because it is not " +
3128 "virtual, abstract or override");
3132 // Now we check that the overriden method is not final
3134 if (base_method.IsFinal) {
3135 // This happens when implementing interface methods.
3136 if (base_method.IsHideBySig && base_method.IsVirtual) {
3138 506, Location, Parent.MakeName (Name) +
3139 ": cannot override inherited member `" +
3140 name + "' because it is not " +
3141 "virtual, abstract or override");
3143 Report.Error (239, Location, Parent.MakeName (Name) + " : cannot " +
3144 "override inherited member `" + name +
3145 "' because it is sealed.");
3149 // Check that the permissions are not being changed
3151 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3152 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3154 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3155 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3160 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3161 ModFlags |= Modifiers.NEW;
3162 Report.SymbolRelatedToPreviousError (base_method);
3163 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3164 if (RootContext.WarningLevel >= 2)
3165 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 (base_method));
3167 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3173 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3175 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3177 // when overriding protected internal, the method can be declared
3178 // protected internal only within the same assembly
3181 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3182 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3184 // assemblies differ - report an error
3188 } else if (thisp != base_classp) {
3190 // same assembly, but other attributes differ - report an error
3195 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3197 // if it's not "protected internal", it must be "protected"
3201 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3203 // protected within the same assembly - an error
3206 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3207 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3209 // protected ok, but other attributes differ - report an error
3215 return (thisp == base_classp);
3219 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3222 // FIXME: report the old/new permissions?
3225 507, Location, parent.MakeName (Name) +
3226 ": can't change the access modifiers when overriding inherited " +
3227 "member `" + name + "'");
3230 protected static string Error722 {
3232 return "'{0}': static types cannot be used as return types";
3237 /// For custom member duplication search in a container
3239 protected abstract bool CheckForDuplications ();
3242 /// Gets base method and its return type
3244 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3246 protected virtual bool DoDefineParameters ()
3248 EmitContext ec = Parent.EmitContext;
3250 throw new InternalErrorException ("DoDefineParameters invoked too early");
3252 bool old_unsafe = ec.InUnsafe;
3253 ec.InUnsafe = InUnsafe;
3254 // Check if arguments were correct
3255 parameter_types = Parameters.GetParameterInfo (ec);
3256 ec.InUnsafe = old_unsafe;
3258 if ((parameter_types == null) ||
3259 !CheckParameters (Parent, parameter_types))
3262 parameter_info = new InternalParameters (parameter_types, Parameters);
3264 Parameter array_param = Parameters.ArrayParameter;
3265 if ((array_param != null) &&
3266 (!array_param.ParameterType.IsArray ||
3267 (array_param.ParameterType.GetArrayRank () != 1))) {
3268 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3275 public override string[] ValidAttributeTargets {
3277 return attribute_targets;
3281 protected override bool VerifyClsCompliance (DeclSpace ds)
3283 if (!base.VerifyClsCompliance (ds)) {
3284 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3285 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3290 if (Parameters.HasArglist) {
3291 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3294 if (!AttributeTester.IsClsCompliant (MemberType)) {
3295 if (this is PropertyBase)
3296 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3297 GetSignatureForError ());
3299 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3300 GetSignatureForError ());
3303 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3308 protected bool IsDuplicateImplementation (MethodCore method)
3310 if ((method == this) || (method.Name != Name))
3313 Type[] param_types = method.ParameterTypes;
3314 if (param_types == null)
3317 if (param_types.Length != ParameterTypes.Length)
3320 for (int i = 0; i < param_types.Length; i++)
3321 if (param_types [i] != ParameterTypes [i])
3324 // TODO: make operator compatible with MethodCore to avoid this
3325 if (this is Operator && method is Operator) {
3326 if (MemberType != method.MemberType)
3331 // Try to report 663: method only differs on out/ref
3333 ParameterData info = ParameterInfo;
3334 ParameterData other_info = method.ParameterInfo;
3335 for (int i = 0; i < info.Count; i++){
3336 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3337 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3342 Report.SymbolRelatedToPreviousError (method);
3343 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3348 // Returns a string that represents the signature for this
3349 // member which should be used in XML documentation.
3351 public override string GetDocCommentName (DeclSpace ds)
3353 return DocUtil.GetMethodDocCommentName (this, ds);
3357 // Raised (and passed an XmlElement that contains the comment)
3358 // when GenerateDocComment is writing documentation expectedly.
3360 // FIXME: with a few effort, it could be done with XmlReader,
3361 // that means removal of DOM use.
3363 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3365 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3369 // Represents header string for documentation comment.
3371 public override string DocCommentHeader {
3372 get { return "M:"; }
3375 protected override void VerifyObsoleteAttribute()
3377 base.VerifyObsoleteAttribute ();
3379 if (parameter_types == null)
3382 foreach (Type type in parameter_types) {
3383 CheckUsageOfObsoleteAttribute (type);
3388 public class SourceMethod : ISourceMethod
3390 TypeContainer container;
3393 protected SourceMethod (TypeContainer container, MethodBase builder,
3394 ISourceFile file, Location start, Location end)
3396 this.container = container;
3397 this.builder = builder;
3399 CodeGen.SymbolWriter.OpenMethod (
3400 file, this, start.Row, 0, end.Row, 0);
3403 public string Name {
3404 get { return builder.Name; }
3407 public int NamespaceID {
3408 get { return container.NamespaceEntry.SymbolFileID; }
3413 if (builder is MethodBuilder)
3414 return ((MethodBuilder) builder).GetToken ().Token;
3415 else if (builder is ConstructorBuilder)
3416 return ((ConstructorBuilder) builder).GetToken ().Token;
3418 throw new NotSupportedException ();
3422 public void CloseMethod ()
3424 if (CodeGen.SymbolWriter != null)
3425 CodeGen.SymbolWriter.CloseMethod ();
3428 public static SourceMethod Create (TypeContainer parent,
3429 MethodBase builder, Block block)
3431 if (CodeGen.SymbolWriter == null)
3436 Location start_loc = block.StartLocation;
3437 if (Location.IsNull (start_loc))
3440 Location end_loc = block.EndLocation;
3441 if (Location.IsNull (end_loc))
3444 ISourceFile file = start_loc.SourceFile;
3448 return new SourceMethod (
3449 parent, builder, file, start_loc, end_loc);
3453 public class Method : MethodCore, IIteratorContainer, IMethodData {
3454 public MethodBuilder MethodBuilder;
3455 public MethodData MethodData;
3456 ReturnParameter return_attributes;
3457 ListDictionary declarative_security;
3460 /// Modifiers allowed in a class declaration
3462 const int AllowedModifiers =
3465 Modifiers.PROTECTED |
3466 Modifiers.INTERNAL |
3471 Modifiers.OVERRIDE |
3472 Modifiers.ABSTRACT |
3474 Modifiers.METHOD_YIELDS |
3477 const int AllowedInterfaceModifiers =
3478 Modifiers.NEW | Modifiers.UNSAFE;
3481 // return_type can be "null" for VOID values.
3483 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3484 MemberName name, Parameters parameters, Attributes attrs,
3486 : base (ds, return_type, mod,
3487 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3488 is_iface, name, attrs, parameters, l)
3492 public override AttributeTargets AttributeTargets {
3494 return AttributeTargets.Method;
3498 public override string GetSignatureForError()
3500 if (MethodBuilder == null) {
3501 return GetSignatureForError (Parent);
3503 return TypeManager.CSharpSignature (MethodBuilder);
3507 /// Use this method when MethodBuilder is null
3509 public override string GetSignatureForError (TypeContainer tc)
3511 // TODO: get params from somewhere
3512 if (parameter_info == null)
3513 return base.GetSignatureForError (tc);
3515 // TODO: move to parameters
3516 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3517 if (parameter_info.Parameters.FixedParameters != null) {
3518 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3519 Parameter p = parameter_info.Parameters.FixedParameters [i];
3520 args.Append (p.GetSignatureForError ());
3522 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3527 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3530 void DuplicateEntryPoint (MethodInfo b, Location location)
3534 "Program `" + CodeGen.FileName +
3535 "' has more than one entry point defined: `" +
3536 TypeManager.CSharpSignature(b) + "'");
3539 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3541 if (b.ReturnType != TypeManager.void_type &&
3542 b.ReturnType != TypeManager.int32_type)
3545 if (pinfo.Count == 0)
3548 if (pinfo.Count > 1)
3551 Type t = pinfo.ParameterType(0);
3553 (t.GetArrayRank() == 1) &&
3554 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3555 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3561 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3563 if (a.Target == AttributeTargets.ReturnValue) {
3564 if (return_attributes == null)
3565 return_attributes = new ReturnParameter (MethodBuilder, Location);
3567 return_attributes.ApplyAttributeBuilder (a, cb);
3571 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
3572 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3575 if (a.Type == TypeManager.dllimport_type) {
3576 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3577 if ((ModFlags & extern_static) != extern_static) {
3578 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3584 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3585 if (declarative_security == null)
3586 declarative_security = new ListDictionary ();
3587 a.ExtractSecurityPermissionSet (declarative_security);
3591 if (a.Type == TypeManager.conditional_attribute_type) {
3592 if (IsOperator || IsExplicitImpl) {
3593 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3597 if (ReturnType != TypeManager.void_type) {
3598 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3602 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3603 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3608 Report.Error (582, Location, "Conditional not valid on interface members");
3612 if (MethodData.IsImplementing) {
3613 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3617 for (int i = 0; i < parameter_info.Count; ++i) {
3618 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3619 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3625 MethodBuilder.SetCustomAttribute (cb);
3628 protected override bool CheckForDuplications ()
3630 ArrayList ar = Parent.Methods;
3632 int arLen = ar.Count;
3634 for (int i = 0; i < arLen; i++) {
3635 Method m = (Method) ar [i];
3636 if (IsDuplicateImplementation (m))
3641 ar = Parent.Properties;
3643 for (int i = 0; i < ar.Count; ++i) {
3644 PropertyBase pb = (PropertyBase) ar [i];
3645 if (pb.AreAccessorsDuplicateImplementation (this))
3650 ar = Parent.Indexers;
3652 for (int i = 0; i < ar.Count; ++i) {
3653 PropertyBase pb = (PropertyBase) ar [i];
3654 if (pb.AreAccessorsDuplicateImplementation (this))
3661 for (int i = 0; i < ar.Count; ++i) {
3662 Event ev = (Event) ar [i];
3663 if (ev.AreAccessorsDuplicateImplementation (this))
3674 public override bool Define ()
3683 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3685 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3687 if (!MethodData.Define (Parent))
3691 // Setup iterator if we are one
3693 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3694 Iterator iterator = new Iterator (
3695 Parent, Name, MemberType, ParameterTypes,
3696 ParameterInfo, ModFlags, block, Location);
3698 if (!iterator.DefineIterator ())
3701 block = iterator.Block;
3704 MethodBuilder = MethodData.MethodBuilder;
3707 // This is used to track the Entry Point,
3709 if (Name == "Main" &&
3710 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3711 (RootContext.MainClass == null ||
3712 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3713 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3714 if (RootContext.EntryPoint == null) {
3715 RootContext.EntryPoint = MethodBuilder;
3716 RootContext.EntryPointLocation = Location;
3718 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3719 DuplicateEntryPoint (MethodBuilder, Location);
3722 if (RootContext.WarningLevel >= 4)
3723 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3727 if (MemberType.IsAbstract && MemberType.IsSealed) {
3728 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3738 public override void Emit ()
3740 MethodData.Emit (Parent, this);
3743 if (declarative_security != null) {
3744 foreach (DictionaryEntry de in declarative_security) {
3745 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3753 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3755 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3756 container.TypeBuilder, Name, ParameterTypes, false);
3761 base_ret_type = mi.ReturnType;
3765 public override bool MarkForDuplicationCheck ()
3767 caching_flags |= Flags.TestMethodDuplication;
3771 protected override bool VerifyClsCompliance(DeclSpace ds)
3773 if (!base.VerifyClsCompliance (ds))
3776 if (parameter_types.Length > 0) {
3777 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3779 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3786 void IIteratorContainer.SetYields ()
3788 ModFlags |= Modifiers.METHOD_YIELDS;
3791 #region IMethodData Members
3793 public CallingConventions CallingConventions {
3795 CallingConventions cc = Parameters.GetCallingConvention ();
3796 if (Parameters.HasArglist)
3797 block.HasVarargs = true;
3800 if ((ModFlags & Modifiers.STATIC) == 0)
3801 cc |= CallingConventions.HasThis;
3803 // FIXME: How is `ExplicitThis' used in C#?
3809 public Type ReturnType {
3815 public MemberName MethodName {
3821 public new Location Location {
3823 return base.Location;
3827 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3829 return new EmitContext (
3830 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3833 public ObsoleteAttribute GetObsoleteAttribute ()
3835 return GetObsoleteAttribute (Parent);
3839 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3841 public bool IsExcluded (EmitContext ec)
3843 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3844 return (caching_flags & Flags.Excluded) != 0;
3846 caching_flags &= ~Flags.Excluded_Undetected;
3848 if (base_method == null) {
3849 if (OptAttributes == null)
3852 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3857 foreach (Attribute a in attrs) {
3858 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3859 if (RootContext.AllDefines.Contains (condition))
3863 caching_flags |= Flags.Excluded;
3867 IMethodData md = TypeManager.GetMethod (base_method);
3869 if (AttributeTester.IsConditionalMethodExcluded (base_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 base_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 base_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 base_constructor_group = Expression.MemberLookup (
3935 ec, t, ".ctor", MemberTypes.Constructor,
3936 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3939 if (base_constructor_group == null){
3940 base_constructor_group = Expression.MemberLookup (
3941 ec, t, ".ctor", MemberTypes.Constructor,
3942 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3945 if (base_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 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
3957 ec, (MethodGroupExpr) base_constructor_group, argument_list,
3960 if (base_constructor == null){
3961 Report.Error (1501, loc,
3962 "Can not find a constructor for this argument list");
3966 if (base_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 (base_constructor != null){
3977 ec.Mark (loc, false);
3979 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
3981 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_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 (base_constructor == null)
4056 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4057 if (type_ds == null) {
4058 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (base_constructor);
4061 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (base_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 FindOutBaseMethod (TypeContainer container, ref Type base_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 base_destructor = ((MethodGroupExpr) member_lookup);
4766 ig.Emit (OpCodes.Ldarg_0);
4767 ig.Emit (OpCodes.Call, (MethodInfo) base_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 base 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.FindBaseMemberWithSameName (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);
5714 bool old_unsafe = ec.InUnsafe;
5715 ec.InUnsafe = InUnsafe;
5716 Type [] types = parameters.GetParameterInfo (ec);
5717 ec.InUnsafe = old_unsafe;
5719 return new InternalParameters (types, parameters);
5722 public override MethodBuilder Define (TypeContainer container)
5724 if (container.EmitContext == null)
5725 throw new InternalErrorException ("SetMethod.Define called too early");
5727 base.Define (container);
5729 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5731 if (!method_data.Define (container))
5734 return method_data.MethodBuilder;
5737 public override string GetSignatureForError (TypeContainer tc)
5739 return String.Concat (base.GetSignatureForError (tc), ".set");
5742 public override Type[] ParameterTypes {
5744 return new Type[] { method.MemberType };
5748 public override Type ReturnType {
5750 return TypeManager.void_type;
5754 public override string[] ValidAttributeTargets {
5756 return attribute_targets;
5761 static string[] attribute_targets = new string [] { "property" };
5763 public abstract class PropertyMethod: AbstractPropertyEventMethod
5765 protected readonly MethodCore method;
5766 protected MethodAttributes flags;
5768 public PropertyMethod (MethodCore method, string prefix)
5769 : base (method, prefix)
5771 this.method = method;
5772 Parent = method.Parent;
5775 public PropertyMethod (MethodCore method, Accessor accessor,
5777 : base (method, accessor, prefix)
5779 this.method = method;
5780 Parent = method.Parent;
5781 this.ModFlags = accessor.ModFlags;
5783 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
5784 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
5785 Environment.Exit (1);
5789 public override AttributeTargets AttributeTargets {
5791 return AttributeTargets.Method;
5795 public override bool IsClsCompliaceRequired(DeclSpace ds)
5797 return method.IsClsCompliaceRequired (ds);
5800 public InternalParameters ParameterInfo
5803 return method_data.ParameterInfo;
5807 public virtual MethodBuilder Define (TypeContainer container)
5810 // Check for custom access modifier
5812 if (ModFlags == 0) {
5813 ModFlags = method.ModFlags;
5814 flags = method.flags;
5816 CheckModifiers (container, ModFlags);
5817 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
5818 flags = Modifiers.MethodAttr (ModFlags);
5819 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
5826 public override Type[] ParameterTypes {
5828 return TypeManager.NoTypes;
5832 public override EmitContext CreateEmitContext (TypeContainer tc,
5835 return new EmitContext (
5836 tc, method.Parent, method.Location, ig, ReturnType,
5837 method.ModFlags, false);
5840 public override ObsoleteAttribute GetObsoleteAttribute ()
5842 return method.GetObsoleteAttribute (method.Parent);
5845 public override string GetSignatureForError (TypeContainer tc)
5847 return String.Concat (tc.Name, '.', method.Name);
5850 void CheckModifiers (TypeContainer container, int modflags)
5853 int mflags = method.ModFlags & Modifiers.Accessibility;
5855 if ((mflags & Modifiers.PUBLIC) != 0) {
5856 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
5858 else if ((mflags & Modifiers.PROTECTED) != 0) {
5859 if ((mflags & Modifiers.INTERNAL) != 0)
5860 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
5862 flags |= Modifiers.PRIVATE;
5864 else if ((mflags & Modifiers.INTERNAL) != 0)
5865 flags |= Modifiers.PRIVATE;
5867 if ((mflags == modflags) || (modflags & (~flags)) != 0)
5868 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
5869 GetSignatureForError (container));
5872 public override bool MarkForDuplicationCheck ()
5874 caching_flags |= Flags.TestMethodDuplication;
5880 public PropertyMethod Get, Set;
5881 public PropertyBuilder PropertyBuilder;
5882 public MethodBuilder GetBuilder, SetBuilder;
5884 protected EmitContext ec;
5886 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
5887 int allowed_mod, bool is_iface, MemberName name,
5888 Parameters parameters, Attributes attrs,
5890 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
5891 attrs, parameters, loc)
5895 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5897 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5898 a.Error_InvalidSecurityParent ();
5902 PropertyBuilder.SetCustomAttribute (cb);
5905 public override AttributeTargets AttributeTargets {
5907 return AttributeTargets.Property;
5911 public override bool Define ()
5916 if (!IsTypePermitted ())
5922 protected override bool DoDefine ()
5924 if (!base.DoDefine ())
5928 // Accessors modifiers check
5930 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
5931 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
5932 GetSignatureForError ());
5936 if ((Get.IsDummy || Set.IsDummy)
5937 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
5938 Report.Error (276, Location,
5939 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
5940 GetSignatureForError ());
5944 if (MemberType.IsAbstract && MemberType.IsSealed) {
5945 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
5949 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
5953 public override string GetSignatureForError()
5955 if (PropertyBuilder == null)
5956 return GetSignatureForError (Parent);
5958 return TypeManager.CSharpSignature (PropertyBuilder, false);
5961 protected override bool CheckForDuplications ()
5963 ArrayList ar = Parent.Indexers;
5965 int arLen = ar.Count;
5967 for (int i = 0; i < arLen; i++) {
5968 Indexer m = (Indexer) ar [i];
5969 if (IsDuplicateImplementation (m))
5974 ar = Parent.Properties;
5976 int arLen = ar.Count;
5978 for (int i = 0; i < arLen; i++) {
5979 Property m = (Property) ar [i];
5980 if (IsDuplicateImplementation (m))
5988 // TODO: rename to Resolve......
5989 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
5991 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
5992 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
5994 if (base_property == null)
5997 base_ret_type = base_property.PropertyType;
5998 MethodInfo get_accessor = base_property.GetGetMethod (true);
5999 MethodInfo set_accessor = base_property.GetSetMethod (true);
6000 MethodAttributes get_accessor_access, set_accessor_access;
6002 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6003 if (Get != null && !Get.IsDummy && get_accessor == null) {
6004 Report.SymbolRelatedToPreviousError (base_property);
6005 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6008 if (Set != null && !Set.IsDummy && set_accessor == null) {
6009 Report.SymbolRelatedToPreviousError (base_property);
6010 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6015 // Check base class accessors access
6017 get_accessor_access = set_accessor_access = 0;
6018 if ((ModFlags & Modifiers.NEW) == 0) {
6019 if (get_accessor != null) {
6020 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6021 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6023 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6024 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6025 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6028 if (set_accessor != null) {
6029 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6030 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6032 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6033 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6034 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6039 // Get the less restrictive access
6041 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6044 public override void Emit ()
6047 // The PropertyBuilder can be null for explicit implementations, in that
6048 // case, we do not actually emit the ".property", so there is nowhere to
6049 // put the attribute
6051 if (PropertyBuilder != null && OptAttributes != null)
6052 OptAttributes.Emit (ec, this);
6064 /// Tests whether accessors are not in collision with some method (CS0111)
6066 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6068 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6071 protected override void UpdateMemberName ()
6073 base.UpdateMemberName ();
6075 Get.UpdateName (this);
6076 Set.UpdateName (this);
6079 protected override bool VerifyClsCompliance (DeclSpace ds)
6081 if (!base.VerifyClsCompliance (ds))
6084 if ((Get.ModFlags != ModFlags && !Get.IsDummy) || (Set.ModFlags != ModFlags && !Set.IsDummy)) {
6085 Report.Error (3025, Get.ModFlags != ModFlags ? Get.Location : Set.Location,
6086 "CLS-compliant accessors must have the same accessibility as their property");
6091 public override string[] ValidAttributeTargets {
6093 return attribute_targets;
6098 // Represents header string for documentation comment.
6100 public override string DocCommentHeader {
6101 get { return "P:"; }
6105 public class Property : PropertyBase, IIteratorContainer {
6106 const int AllowedModifiers =
6109 Modifiers.PROTECTED |
6110 Modifiers.INTERNAL |
6114 Modifiers.OVERRIDE |
6115 Modifiers.ABSTRACT |
6118 Modifiers.METHOD_YIELDS |
6121 const int AllowedInterfaceModifiers =
6124 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6125 MemberName name, Attributes attrs, Accessor get_block,
6126 Accessor set_block, Location loc)
6127 : base (ds, type, mod,
6128 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6129 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6132 if (get_block == null)
6133 Get = new GetMethod (this);
6135 Get = new GetMethod (this, get_block);
6137 if (set_block == null)
6138 Set = new SetMethod (this);
6140 Set = new SetMethod (this, set_block);
6143 public override bool Define ()
6145 if (!base.Define ())
6151 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6155 GetBuilder = Get.Define (Parent);
6156 if (GetBuilder == null)
6160 // Setup iterator if we are one
6162 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6163 Iterator iterator = new Iterator (
6164 Parent, "get", MemberType,
6165 TypeManager.NoTypes, Get.ParameterInfo,
6166 ModFlags, Get.Block, Location);
6168 if (!iterator.DefineIterator ())
6170 Get.Block = iterator.Block;
6175 SetBuilder = Set.Define (Parent);
6176 if (SetBuilder == null)
6179 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6182 // FIXME - PropertyAttributes.HasDefault ?
6184 PropertyAttributes prop_attr = PropertyAttributes.None;
6186 prop_attr |= PropertyAttributes.RTSpecialName |
6187 PropertyAttributes.SpecialName;
6189 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6190 Name, prop_attr, MemberType, null);
6193 PropertyBuilder.SetGetMethod (GetBuilder);
6196 PropertyBuilder.SetSetMethod (SetBuilder);
6198 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6202 public void SetYields ()
6204 ModFlags |= Modifiers.METHOD_YIELDS;
6209 /// Gigantic workaround for lameness in SRE follows :
6210 /// This class derives from EventInfo and attempts to basically
6211 /// wrap around the EventBuilder so that FindMembers can quickly
6212 /// return this in it search for members
6214 public class MyEventBuilder : EventInfo {
6217 // We use this to "point" to our Builder which is
6218 // not really a MemberInfo
6220 EventBuilder MyBuilder;
6223 // We "catch" and wrap these methods
6225 MethodInfo raise, remove, add;
6227 EventAttributes attributes;
6228 Type declaring_type, reflected_type, event_type;
6233 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6235 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6237 // And now store the values in our own fields.
6239 declaring_type = type_builder;
6241 reflected_type = type_builder;
6243 attributes = event_attr;
6246 this.event_type = event_type;
6250 // Methods that you have to override. Note that you only need
6251 // to "implement" the variants that take the argument (those are
6252 // the "abstract" methods, the others (GetAddMethod()) are
6255 public override MethodInfo GetAddMethod (bool nonPublic)
6260 public override MethodInfo GetRemoveMethod (bool nonPublic)
6265 public override MethodInfo GetRaiseMethod (bool nonPublic)
6271 // These methods make "MyEventInfo" look like a Builder
6273 public void SetRaiseMethod (MethodBuilder raiseMethod)
6275 raise = raiseMethod;
6276 MyBuilder.SetRaiseMethod (raiseMethod);
6279 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6281 remove = removeMethod;
6282 MyBuilder.SetRemoveOnMethod (removeMethod);
6285 public void SetAddOnMethod (MethodBuilder addMethod)
6288 MyBuilder.SetAddOnMethod (addMethod);
6291 public void SetCustomAttribute (CustomAttributeBuilder cb)
6293 MyBuilder.SetCustomAttribute (cb);
6296 public override object [] GetCustomAttributes (bool inherit)
6298 // FIXME : There's nothing which can be seemingly done here because
6299 // we have no way of getting at the custom attribute objects of the
6304 public override object [] GetCustomAttributes (Type t, bool inherit)
6306 // FIXME : Same here !
6310 public override bool IsDefined (Type t, bool b)
6315 public override EventAttributes Attributes {
6321 public override string Name {
6327 public override Type DeclaringType {
6329 return declaring_type;
6333 public override Type ReflectedType {
6335 return reflected_type;
6339 public Type EventType {
6345 public void SetUsed ()
6347 if (my_event != null)
6348 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6353 /// For case when event is declared like property (with add and remove accessors).
6355 public class EventProperty: Event {
6357 static string[] attribute_targets = new string [] { "event", "property" };
6359 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6360 bool is_iface, MemberName name, Object init,
6361 Attributes attrs, Accessor add, Accessor remove,
6363 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6365 Add = new AddDelegateMethod (this, add);
6366 Remove = new RemoveDelegateMethod (this, remove);
6368 // For this event syntax we don't report error CS0067
6369 // because it is hard to do it.
6373 public override string[] ValidAttributeTargets {
6375 return attribute_targets;
6381 /// Event is declared like field.
6383 public class EventField: Event {
6385 static string[] attribute_targets = new string [] { "event", "field", "method" };
6386 static string[] attribute_targets_interface = new string[] { "event", "method" };
6388 public EventField (TypeContainer parent, Expression type, int mod_flags,
6389 bool is_iface, MemberName name, Object init,
6390 Attributes attrs, Location loc)
6391 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6393 Add = new AddDelegateMethod (this);
6394 Remove = new RemoveDelegateMethod (this);
6397 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6399 if (a.Target == AttributeTargets.Field) {
6400 FieldBuilder.SetCustomAttribute (cb);
6404 if (a.Target == AttributeTargets.Method) {
6405 Add.ApplyAttributeBuilder (a, cb);
6406 Remove.ApplyAttributeBuilder (a, cb);
6410 base.ApplyAttributeBuilder (a, cb);
6413 public override string[] ValidAttributeTargets {
6415 return IsInterface ? attribute_targets_interface : attribute_targets;
6420 public abstract class Event : FieldBase {
6422 protected sealed class AddDelegateMethod: DelegateMethod
6425 public AddDelegateMethod (Event method):
6426 base (method, "add_")
6430 public AddDelegateMethod (Event method, Accessor accessor):
6431 base (method, accessor, "add_")
6435 protected override MethodInfo DelegateMethodInfo {
6437 return TypeManager.delegate_combine_delegate_delegate;
6443 protected sealed class RemoveDelegateMethod: DelegateMethod
6445 public RemoveDelegateMethod (Event method):
6446 base (method, "remove_")
6450 public RemoveDelegateMethod (Event method, Accessor accessor):
6451 base (method, accessor, "remove_")
6455 protected override MethodInfo DelegateMethodInfo {
6457 return TypeManager.delegate_remove_delegate_delegate;
6463 public abstract class DelegateMethod: AbstractPropertyEventMethod
6465 protected readonly Event method;
6466 ImplicitParameter param_attr;
6468 static string[] attribute_targets = new string [] { "method", "param", "return" };
6470 public DelegateMethod (Event method, string prefix)
6471 : base (method, prefix)
6473 this.method = method;
6476 public DelegateMethod (Event method, Accessor accessor, string prefix)
6477 : base (method, accessor, prefix)
6479 this.method = method;
6482 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6484 if (a.Target == AttributeTargets.Parameter) {
6485 if (param_attr == null)
6486 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6488 param_attr.ApplyAttributeBuilder (a, cb);
6492 base.ApplyAttributeBuilder (a, cb);
6495 public override AttributeTargets AttributeTargets {
6497 return AttributeTargets.Method;
6501 public override bool IsClsCompliaceRequired(DeclSpace ds)
6503 return method.IsClsCompliaceRequired (ds);
6506 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6508 method_data = new MethodData (method, ip, method.ModFlags,
6509 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6511 if (!method_data.Define (container))
6514 MethodBuilder mb = method_data.MethodBuilder;
6515 mb.DefineParameter (1, ParameterAttributes.None, "value");
6520 public override void Emit (TypeContainer tc)
6522 if (block != null) {
6527 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6528 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6530 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6531 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6532 ig.Emit (OpCodes.Ldsfld, field_info);
6533 ig.Emit (OpCodes.Ldarg_0);
6534 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6535 ig.Emit (OpCodes.Castclass, method.MemberType);
6536 ig.Emit (OpCodes.Stsfld, field_info);
6538 ig.Emit (OpCodes.Ldarg_0);
6539 ig.Emit (OpCodes.Ldarg_0);
6540 ig.Emit (OpCodes.Ldfld, field_info);
6541 ig.Emit (OpCodes.Ldarg_1);
6542 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6543 ig.Emit (OpCodes.Castclass, method.MemberType);
6544 ig.Emit (OpCodes.Stfld, field_info);
6546 ig.Emit (OpCodes.Ret);
6549 protected abstract MethodInfo DelegateMethodInfo { get; }
6551 public override Type[] ParameterTypes {
6553 return new Type[] { method.MemberType };
6557 public override Type ReturnType {
6559 return TypeManager.void_type;
6563 public override EmitContext CreateEmitContext (TypeContainer tc,
6566 return new EmitContext (
6567 tc, method.Parent, Location, ig, ReturnType,
6568 method.ModFlags, false);
6571 public override string GetSignatureForError (TypeContainer tc)
6573 return String.Concat (tc.Name, '.', method.Name);
6576 public override ObsoleteAttribute GetObsoleteAttribute ()
6578 return method.GetObsoleteAttribute (method.Parent);
6581 public override string[] ValidAttributeTargets {
6583 return attribute_targets;
6589 const int AllowedModifiers =
6592 Modifiers.PROTECTED |
6593 Modifiers.INTERNAL |
6598 Modifiers.OVERRIDE |
6602 const int AllowedInterfaceModifiers =
6605 public DelegateMethod Add, Remove;
6606 public MyEventBuilder EventBuilder;
6607 public MethodBuilder AddBuilder, RemoveBuilder;
6609 public Event (TypeContainer parent, Expression type, int mod_flags,
6610 bool is_iface, MemberName name, Object init, Attributes attrs,
6612 : base (parent, type, mod_flags,
6613 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6614 name, init, attrs, loc)
6616 IsInterface = is_iface;
6619 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6621 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6622 a.Error_InvalidSecurityParent ();
6626 EventBuilder.SetCustomAttribute (cb);
6629 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6631 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6634 public override AttributeTargets AttributeTargets {
6636 return AttributeTargets.Event;
6640 public override bool Define ()
6642 EventAttributes e_attr;
6643 e_attr = EventAttributes.None;
6648 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6649 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6650 "': abstract event can not have an initializer");
6654 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6655 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6656 "' : event must be of a delegate type");
6660 EmitContext ec = Parent.EmitContext;
6662 throw new InternalErrorException ("Event.Define called too early?");
6663 bool old_unsafe = ec.InUnsafe;
6664 ec.InUnsafe = InUnsafe;
6666 Parameter [] parms = new Parameter [1];
6667 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6668 Parameters parameters = new Parameters (parms, null, Location);
6669 Type [] types = parameters.GetParameterInfo (ec);
6670 InternalParameters ip = new InternalParameters (types, parameters);
6672 ec.InUnsafe = old_unsafe;
6678 // Now define the accessors
6681 AddBuilder = Add.Define (Parent, ip);
6682 if (AddBuilder == null)
6685 RemoveBuilder = Remove.Define (Parent, ip);
6686 if (RemoveBuilder == null)
6689 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6691 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6692 FieldBuilder = Parent.TypeBuilder.DefineField (
6694 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6695 TypeManager.RegisterPrivateFieldOfEvent (
6696 (EventInfo) EventBuilder, FieldBuilder);
6697 TypeManager.RegisterFieldBase (FieldBuilder, this);
6700 EventBuilder.SetAddOnMethod (AddBuilder);
6701 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6703 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6707 protected override bool CheckBase ()
6709 if (!base.CheckBase ())
6712 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6713 if (!(conflict_symbol is EventInfo)) {
6714 Report.SymbolRelatedToPreviousError (conflict_symbol);
6715 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6723 public override void Emit ()
6725 if (OptAttributes != null) {
6726 EmitContext ec = new EmitContext (
6727 Parent, Location, null, MemberType, ModFlags);
6728 OptAttributes.Emit (ec, this);
6733 Remove.Emit (Parent);
6739 public override string GetSignatureForError ()
6741 if (EventBuilder == null)
6742 return base.GetSignatureForError (Parent);
6744 return TypeManager.GetFullNameSignature (EventBuilder);
6748 // Represents header string for documentation comment.
6750 public override string DocCommentHeader {
6751 get { return "E:"; }
6756 public class Indexer : PropertyBase {
6758 class GetIndexerMethod: GetMethod
6760 public GetIndexerMethod (MethodCore method):
6765 public GetIndexerMethod (MethodCore method, Accessor accessor):
6766 base (method, accessor)
6770 public override Type[] ParameterTypes {
6772 return method.ParameterTypes;
6777 class SetIndexerMethod: SetMethod
6779 readonly Parameters parameters;
6781 public SetIndexerMethod (MethodCore method):
6786 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
6787 base (method, accessor)
6789 this.parameters = parameters;
6792 public override Type[] ParameterTypes {
6794 int top = method.ParameterTypes.Length;
6795 Type [] set_pars = new Type [top + 1];
6796 method.ParameterTypes.CopyTo (set_pars, 0);
6797 set_pars [top] = method.MemberType;
6802 protected override InternalParameters GetParameterInfo (EmitContext ec)
6804 Parameter [] fixed_parms = parameters.FixedParameters;
6806 if (fixed_parms == null){
6807 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
6808 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6809 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6811 // Here is the problem: the `value' parameter has
6812 // to come *after* the array parameter in the declaration
6814 // X (object [] x, Type value)
6817 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6818 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6822 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
6824 fixed_parms.CopyTo (tmp, 0);
6825 tmp [fixed_parms.Length] = new Parameter (
6826 method.Type, "value", Parameter.Modifier.NONE, null);
6828 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
6829 Type [] types = set_formal_params.GetParameterInfo (ec);
6831 return new InternalParameters (types, set_formal_params);
6836 const int AllowedModifiers =
6839 Modifiers.PROTECTED |
6840 Modifiers.INTERNAL |
6844 Modifiers.OVERRIDE |
6849 const int AllowedInterfaceModifiers =
6853 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
6854 bool is_iface, Parameters parameters, Attributes attrs,
6855 Accessor get_block, Accessor set_block, Location loc)
6856 : base (ds, type, mod,
6857 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6858 is_iface, name, parameters, attrs, loc)
6860 if (get_block == null)
6861 Get = new GetIndexerMethod (this);
6863 Get = new GetIndexerMethod (this, get_block);
6865 if (set_block == null)
6866 Set = new SetIndexerMethod (this);
6868 Set = new SetIndexerMethod (this, parameters, set_block);
6871 public override bool Define ()
6873 PropertyAttributes prop_attr =
6874 PropertyAttributes.RTSpecialName |
6875 PropertyAttributes.SpecialName;
6877 if (!base.Define ())
6880 if (MemberType == TypeManager.void_type) {
6881 Report.Error (620, Location, "Indexers cannot have void type");
6885 if (OptAttributes != null) {
6886 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
6887 if (indexer_attr != null) {
6888 // Remove the attribute from the list because it is not emitted
6889 OptAttributes.Attrs.Remove (indexer_attr);
6891 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
6893 if (IsExplicitImpl) {
6894 Report.Error (415, indexer_attr.Location,
6895 "The 'IndexerName' attribute is valid only on an" +
6896 "indexer that is not an explicit interface member declaration");
6900 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6901 Report.Error (609, indexer_attr.Location,
6902 "Cannot set the 'IndexerName' attribute on an indexer marked override");
6906 if (!Tokenizer.IsValidIdentifier (ShortName)) {
6907 Report.Error (633, indexer_attr.Location,
6908 "The argument to the 'IndexerName' attribute must be a valid identifier");
6912 UpdateMemberName ();
6916 if (InterfaceType != null) {
6917 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
6918 if (base_IndexerName != Name)
6919 ShortName = base_IndexerName;
6920 UpdateMemberName ();
6923 if (!Parent.AddToMemberContainer (this) ||
6924 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
6930 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6932 GetBuilder = Get.Define (Parent);
6933 if (GetBuilder == null)
6938 SetBuilder = Set.Define (Parent);
6939 if (SetBuilder == null)
6944 // Now name the parameters
6946 Parameter [] p = Parameters.FixedParameters;
6948 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
6949 Report.Error (631, Location, "ref and out are not valid in this context");
6955 for (i = 0; i < p.Length; ++i) {
6957 GetBuilder.DefineParameter (
6958 i + 1, p [i].Attributes, p [i].Name);
6961 SetBuilder.DefineParameter (
6962 i + 1, p [i].Attributes, p [i].Name);
6966 SetBuilder.DefineParameter (
6967 i + 1, ParameterAttributes.None, "value");
6969 if (i != ParameterTypes.Length) {
6970 Parameter array_param = Parameters.ArrayParameter;
6972 SetBuilder.DefineParameter (
6973 i + 1, array_param.Attributes, array_param.Name);
6977 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6978 Name, prop_attr, MemberType, ParameterTypes);
6981 PropertyBuilder.SetGetMethod (GetBuilder);
6984 PropertyBuilder.SetSetMethod (SetBuilder);
6986 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
6991 public override string GetSignatureForError ()
6993 if (PropertyBuilder == null)
6994 return GetSignatureForError (Parent);
6996 return TypeManager.CSharpSignature (PropertyBuilder, true);
6999 public override string GetSignatureForError(TypeContainer tc)
7001 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7004 public override bool MarkForDuplicationCheck ()
7006 caching_flags |= Flags.TestMethodDuplication;
7012 public class Operator : MethodCore, IIteratorContainer {
7014 const int AllowedModifiers =
7020 public enum OpType : byte {
7030 // Unary and Binary operators
7053 // Implicit and Explicit
7058 public readonly OpType OperatorType;
7059 public MethodBuilder OperatorMethodBuilder;
7061 public Method OperatorMethod;
7063 static string[] attribute_targets = new string [] { "method", "return" };
7065 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7066 int mod_flags, Parameters parameters,
7067 ToplevelBlock block, Attributes attrs, Location loc)
7068 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7069 new MemberName ("op_" + type), attrs, parameters, loc)
7071 OperatorType = type;
7075 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7077 OperatorMethod.ApplyAttributeBuilder (a, cb);
7080 public override AttributeTargets AttributeTargets {
7082 return AttributeTargets.Method;
7086 protected override bool CheckForDuplications()
7088 ArrayList ar = Parent.Operators;
7090 int arLen = ar.Count;
7092 for (int i = 0; i < arLen; i++) {
7093 Operator o = (Operator) ar [i];
7094 if (IsDuplicateImplementation (o))
7099 ar = Parent.Methods;
7101 int arLen = ar.Count;
7103 for (int i = 0; i < arLen; i++) {
7104 Method m = (Method) ar [i];
7105 if (IsDuplicateImplementation (m))
7113 public override bool Define ()
7116 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7117 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7118 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7125 if (MemberType == TypeManager.void_type) {
7126 Report.Error (590, Location, "User-defined operators cannot return void");
7130 OperatorMethod = new Method (
7131 Parent, Type, ModFlags, false, MemberName,
7132 Parameters, OptAttributes, Location);
7134 OperatorMethod.Block = Block;
7135 OperatorMethod.IsOperator = true;
7136 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7137 OperatorMethod.Define ();
7139 if (OperatorMethod.MethodBuilder == null)
7142 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7144 parameter_types = OperatorMethod.ParameterTypes;
7145 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7146 Type return_type = OperatorMethod.ReturnType;
7147 Type first_arg_type = parameter_types [0];
7152 // Rules for conversion operators
7154 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7155 if (first_arg_type == return_type && first_arg_type == declaring_type){
7158 "User-defined conversion cannot take an object of the " +
7159 "enclosing type and convert to an object of the enclosing" +
7164 if (first_arg_type != declaring_type && return_type != declaring_type){
7167 "User-defined conversion must convert to or from the " +
7172 if (first_arg_type == TypeManager.object_type ||
7173 return_type == TypeManager.object_type){
7176 "User-defined conversion cannot convert to or from " +
7181 if (first_arg_type.IsInterface || return_type.IsInterface){
7184 "User-defined conversion cannot convert to or from an " +
7189 if (first_arg_type.IsSubclassOf (return_type)
7190 || return_type.IsSubclassOf (first_arg_type)){
7191 if (declaring_type.IsSubclassOf (return_type)) {
7192 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7195 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7198 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7199 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7200 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");
7203 } else if (Parameters.FixedParameters.Length == 1) {
7204 // Checks for Unary operators
7206 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7207 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7208 Report.Error (448, Location,
7209 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7212 if (first_arg_type != declaring_type) {
7214 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7219 if (first_arg_type != declaring_type){
7222 "The parameter of a unary operator must be the " +
7227 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7228 if (return_type != TypeManager.bool_type){
7231 "The return type of operator True or False " +
7238 // Checks for Binary operators
7240 if (first_arg_type != declaring_type &&
7241 parameter_types [1] != declaring_type){
7244 "One of the parameters of a binary operator must " +
7245 "be the containing type");
7253 public override void Emit ()
7256 // abstract or extern methods have no bodies
7258 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7261 OperatorMethod.Emit ();
7265 // Operator cannot be override
7266 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7271 public static string GetName (OpType ot)
7274 case OpType.LogicalNot:
7276 case OpType.OnesComplement:
7278 case OpType.Increment:
7280 case OpType.Decrement:
7286 case OpType.Addition:
7288 case OpType.Subtraction:
7290 case OpType.UnaryPlus:
7292 case OpType.UnaryNegation:
7294 case OpType.Multiply:
7296 case OpType.Division:
7298 case OpType.Modulus:
7300 case OpType.BitwiseAnd:
7302 case OpType.BitwiseOr:
7304 case OpType.ExclusiveOr:
7306 case OpType.LeftShift:
7308 case OpType.RightShift:
7310 case OpType.Equality:
7312 case OpType.Inequality:
7314 case OpType.GreaterThan:
7316 case OpType.LessThan:
7318 case OpType.GreaterThanOrEqual:
7320 case OpType.LessThanOrEqual:
7322 case OpType.Implicit:
7324 case OpType.Explicit:
7330 public override string GetSignatureForError (TypeContainer tc)
7332 StringBuilder sb = new StringBuilder ();
7333 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7334 Parameters.FixedParameters [0].GetSignatureForError ());
7336 if (Parameters.FixedParameters.Length > 1) {
7338 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7341 return sb.ToString ();
7344 public override string GetSignatureForError ()
7349 public override bool MarkForDuplicationCheck ()
7351 caching_flags |= Flags.TestMethodDuplication;
7355 public override string ToString ()
7357 if (OperatorMethod == null)
7360 Type return_type = OperatorMethod.ReturnType;
7361 Type [] param_types = OperatorMethod.ParameterTypes;
7363 if (Parameters.FixedParameters.Length == 1)
7364 return String.Format (
7365 "{0} operator {1}({2})",
7366 TypeManager.CSharpName (return_type),
7367 GetName (OperatorType),
7370 return String.Format (
7371 "{0} operator {1}({2}, {3})",
7372 TypeManager.CSharpName (return_type),
7373 GetName (OperatorType),
7374 param_types [0], param_types [1]);
7377 public override string[] ValidAttributeTargets {
7379 return attribute_targets;
7383 public void SetYields ()
7385 ModFlags |= Modifiers.METHOD_YIELDS;
7390 // This is used to compare method signatures
7392 struct MethodSignature {
7394 public Type RetType;
7395 public Type [] Parameters;
7398 /// This delegate is used to extract methods which have the
7399 /// same signature as the argument
7401 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7403 public MethodSignature (string name, Type ret_type, Type [] parameters)
7408 if (parameters == null)
7409 Parameters = TypeManager.NoTypes;
7411 Parameters = parameters;
7414 public override string ToString ()
7417 if (Parameters.Length != 0){
7418 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7419 for (int i = 0; i < Parameters.Length; i++){
7420 sb.Append (Parameters [i]);
7421 if (i+1 < Parameters.Length)
7424 pars = sb.ToString ();
7427 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7430 public override int GetHashCode ()
7432 return Name.GetHashCode ();
7435 public override bool Equals (Object o)
7437 MethodSignature other = (MethodSignature) o;
7439 if (other.Name != Name)
7442 if (other.RetType != RetType)
7445 if (Parameters == null){
7446 if (other.Parameters == null)
7451 if (other.Parameters == null)
7454 int c = Parameters.Length;
7455 if (other.Parameters.Length != c)
7458 for (int i = 0; i < c; i++)
7459 if (other.Parameters [i] != Parameters [i])
7465 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7467 MethodSignature sig = (MethodSignature) filter_criteria;
7469 if (m.Name != sig.Name)
7473 MethodInfo mi = m as MethodInfo;
7474 PropertyInfo pi = m as PropertyInfo;
7477 ReturnType = mi.ReturnType;
7478 else if (pi != null)
7479 ReturnType = pi.PropertyType;
7484 // we use sig.RetType == null to mean `do not check the
7485 // method return value.
7487 if (sig.RetType != null)
7488 if (ReturnType != sig.RetType)
7493 args = TypeManager.GetArgumentTypes (mi);
7495 args = TypeManager.GetArgumentTypes (pi);
7496 Type [] sigp = sig.Parameters;
7498 if (args.Length != sigp.Length)
7501 for (int i = args.Length; i > 0; ){
7503 if (args [i] != sigp [i])