2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 namespace Mono.CSharp {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
79 public virtual void Emit ()
81 foreach (MemberCore mc in this)
86 public class MethodArrayList: MemberCoreArrayList
94 CachedMethods cached_method;
95 TypeContainer container;
97 public MethodArrayList (TypeContainer container)
99 this.container = container;
103 /// Method container contains Equals method
105 public bool HasEquals {
107 cached_method |= CachedMethods.Equals;
111 return (cached_method & CachedMethods.Equals) != 0;
116 /// Method container contains GetHashCode method
118 public bool HasGetHashCode {
120 cached_method |= CachedMethods.GetHashCode;
124 return (cached_method & CachedMethods.GetHashCode) != 0;
128 public override void DefineContainerMembers ()
130 base.DefineContainerMembers ();
132 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
133 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
139 public sealed class IndexerArrayList: MemberCoreArrayList
142 /// The indexer name for this container
144 public string IndexerName = DefaultIndexerName;
146 bool seen_normal_indexers = false;
148 TypeContainer container;
150 public IndexerArrayList (TypeContainer container)
152 this.container = container;
156 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
157 /// class is consistent. Either it is `Item' or it is the name defined by all the
158 /// indexers with the `IndexerName' attribute.
160 /// Turns out that the IndexerNameAttribute is applied to each indexer,
161 /// but it is never emitted, instead a DefaultMember attribute is attached
164 public override void DefineContainerMembers()
166 base.DefineContainerMembers ();
168 string class_indexer_name = null;
171 // If there's both an explicit and an implicit interface implementation, the
172 // explicit one actually implements the interface while the other one is just
173 // a normal indexer. See bug #37714.
176 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
177 foreach (Indexer i in this) {
178 if (i.InterfaceType != null) {
179 if (seen_normal_indexers)
180 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
184 seen_normal_indexers = true;
186 if (class_indexer_name == null) {
187 class_indexer_name = i.ShortName;
191 if (i.ShortName != class_indexer_name)
192 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
195 if (class_indexer_name != null)
196 IndexerName = class_indexer_name;
199 public override void Emit ()
203 if (!seen_normal_indexers)
206 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
207 container.TypeBuilder.SetCustomAttribute (cb);
211 public class OperatorArrayList: MemberCoreArrayList
213 TypeContainer container;
215 public OperatorArrayList (TypeContainer container)
217 this.container = container;
221 // Operator pair checking
226 public Type ret_type;
227 public Type type1, type2;
229 public Operator.OpType ot;
231 public OperatorEntry (int f, Operator o)
235 ret_type = o.OperatorMethod.ReturnType;
236 Type [] pt = o.OperatorMethod.ParameterTypes;
243 public override int GetHashCode ()
245 return ret_type.GetHashCode ();
248 public override bool Equals (object o)
250 OperatorEntry other = (OperatorEntry) o;
252 if (other.ret_type != ret_type)
254 if (other.type1 != type1)
256 if (other.type2 != type2)
263 // Checks that some operators come in pairs:
269 // They are matched based on the return type and the argument types
271 void CheckPairedOperators ()
273 Hashtable pairs = new Hashtable (null, null);
274 Operator true_op = null;
275 Operator false_op = null;
276 bool has_equality_or_inequality = false;
278 // Register all the operators we care about.
279 foreach (Operator op in this){
282 switch (op.OperatorType){
283 case Operator.OpType.Equality:
285 has_equality_or_inequality = true;
287 case Operator.OpType.Inequality:
289 has_equality_or_inequality = true;
292 case Operator.OpType.True:
295 case Operator.OpType.False:
299 case Operator.OpType.GreaterThan:
301 case Operator.OpType.LessThan:
304 case Operator.OpType.GreaterThanOrEqual:
306 case Operator.OpType.LessThanOrEqual:
312 OperatorEntry oe = new OperatorEntry (reg, op);
314 object o = pairs [oe];
318 oe = (OperatorEntry) o;
323 if (true_op != null){
324 if (false_op == null)
325 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
326 } else if (false_op != null)
327 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
330 // Look for the mistakes.
332 foreach (DictionaryEntry de in pairs){
333 OperatorEntry oe = (OperatorEntry) de.Key;
340 case Operator.OpType.Equality:
343 case Operator.OpType.Inequality:
346 case Operator.OpType.GreaterThan:
349 case Operator.OpType.LessThan:
352 case Operator.OpType.GreaterThanOrEqual:
355 case Operator.OpType.LessThanOrEqual:
359 Report.Error (216, oe.op.Location,
360 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
363 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
364 if (container.Methods == null || !container.Methods.HasEquals)
365 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
367 if (container.Methods == null || !container.Methods.HasGetHashCode)
368 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
372 public override void DefineContainerMembers ()
374 base.DefineContainerMembers ();
375 CheckPairedOperators ();
380 // Whether this is a struct, class or interface
381 public readonly Kind Kind;
383 // Holds a list of classes and structures
386 // Holds the list of properties
387 MemberCoreArrayList properties;
389 // Holds the list of enumerations
390 MemberCoreArrayList enums;
392 // Holds the list of delegates
393 MemberCoreArrayList delegates;
395 // Holds the list of constructors
396 protected MemberCoreArrayList instance_constructors;
398 // Holds the list of fields
399 MemberCoreArrayList fields;
401 // Holds a list of fields that have initializers
402 protected ArrayList initialized_fields;
404 // Holds a list of static fields that have initializers
405 protected ArrayList initialized_static_fields;
407 // Holds the list of constants
408 MemberCoreArrayList constants;
411 MemberCoreArrayList interfaces;
413 // Holds the methods.
414 MethodArrayList methods;
417 protected MemberCoreArrayList events;
419 // Holds the indexers
420 IndexerArrayList indexers;
422 // Holds the operators
423 MemberCoreArrayList operators;
425 // Holds the iterators
428 // Holds the parts of a partial class;
432 // Pointers to the default constructor and the default static constructor
434 protected Constructor default_constructor;
435 protected Constructor default_static_constructor;
438 // Whether we have at least one non-static field
440 bool have_nonstatic_fields = false;
443 // This one is computed after we can distinguish interfaces
444 // from classes from the arraylist `type_bases'
446 string base_class_name;
447 TypeExpr parent_type;
449 ArrayList type_bases;
451 bool members_defined;
452 bool members_defined_ok;
454 // The interfaces we implement.
455 protected Type [] ifaces;
456 protected Type ptype;
458 // The parent member cache and our member cache
459 MemberCache parent_cache;
460 MemberCache member_cache;
462 public const string DefaultIndexerName = "Item";
464 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
465 Attributes attrs, Kind kind, Location l)
466 : base (ns, parent, name, attrs, l)
470 types = new ArrayList ();
472 base_class_name = null;
475 public bool AddToMemberContainer (MemberCore symbol, bool is_method)
477 return AddToContainer (symbol, is_method, String.Concat (Name, '.', symbol.Name), symbol.Name);
480 bool AddToTypeContainer (DeclSpace ds)
482 return AddToContainer (ds, false, ds.Name, ds.Basename);
485 public void AddConstant (Const constant)
487 if (!AddToMemberContainer (constant, false))
490 if (constants == null)
491 constants = new MemberCoreArrayList ();
493 constants.Add (constant);
496 public void AddEnum (Mono.CSharp.Enum e)
498 if (!AddToTypeContainer (e))
502 enums = new MemberCoreArrayList ();
507 public void AddClassOrStruct (TypeContainer c)
509 if (!AddToTypeContainer (c))
515 public void AddDelegate (Delegate d)
517 if (!AddToTypeContainer (d))
520 if (delegates == null)
521 delegates = new MemberCoreArrayList ();
526 public void AddMethod (Method method)
528 if (!AddToMemberContainer (method, true))
532 methods = new MethodArrayList (this);
534 if (method.Name.IndexOf ('.') != -1)
535 methods.Insert (0, method);
537 methods.Add (method);
540 public void AddConstructor (Constructor c)
542 if (c.Name != Basename) {
543 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
546 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
549 if (default_static_constructor != null) {
550 Report.SymbolRelatedToPreviousError (default_static_constructor);
551 Report.Error (111, c.Location, Error111, Name, c.Name);
555 default_static_constructor = c;
558 if (default_constructor != null) {
559 Report.SymbolRelatedToPreviousError (default_constructor);
560 Report.Error (111, c.Location, Error111, c.Location, Name, c.Name);
563 default_constructor = c;
566 if (instance_constructors == null)
567 instance_constructors = new MemberCoreArrayList ();
569 instance_constructors.Add (c);
573 internal static string Error111 {
575 return "Type '{0}' already defines a member called '{1}' with the same parameter types";
579 public void AddInterface (TypeContainer iface)
581 if (!AddToTypeContainer (iface))
584 if (interfaces == null) {
585 interfaces = new MemberCoreArrayList ();
588 interfaces.Add (iface);
591 public void AddField (Field field)
593 if (!AddToMemberContainer (field, false))
597 fields = new MemberCoreArrayList ();
601 if (field.HasInitializer){
602 if ((field.ModFlags & Modifiers.STATIC) != 0){
603 if (initialized_static_fields == null)
604 initialized_static_fields = new ArrayList ();
606 initialized_static_fields.Add (field);
608 if (initialized_fields == null)
609 initialized_fields = new ArrayList ();
611 initialized_fields.Add (field);
615 if ((field.ModFlags & Modifiers.STATIC) == 0)
616 have_nonstatic_fields = true;
619 public void AddProperty (Property prop)
621 if (!AddToMemberContainer (prop, false) ||
622 !AddToMemberContainer (prop.Get, true) || !AddToMemberContainer (prop.Set, true))
625 if (properties == null)
626 properties = new MemberCoreArrayList ();
628 if (prop.Name.IndexOf ('.') != -1)
629 properties.Insert (0, prop);
631 properties.Add (prop);
634 public void AddEvent (Event e)
636 if (!AddToMemberContainer (e, false))
639 if (e is EventProperty) {
640 if (!AddToMemberContainer (e.Add, true))
643 if (!AddToMemberContainer (e.Remove, true))
648 events = new MemberCoreArrayList ();
655 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
657 public void AddIndexer (Indexer i)
659 if (indexers == null)
660 indexers = new IndexerArrayList (this);
662 if (i.IsExplicitImpl)
663 indexers.Insert (0, i);
668 public void AddOperator (Operator op)
670 if (!AddToMemberContainer (op, true))
673 if (operators == null)
674 operators = new OperatorArrayList (this);
679 public void AddIterator (Iterator i)
681 if (iterators == null)
682 iterators = new ArrayList ();
687 public void AddType (TypeContainer tc)
692 public void AddPart (ClassPart part)
695 parts = new ArrayList ();
700 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
702 if (a.Type == TypeManager.default_member_type) {
703 if (Indexers != null) {
704 Report.Error (646, a.Location,
705 "Cannot specify the DefaultMember attribute on" +
706 " a type containing an indexer");
711 base.ApplyAttributeBuilder (a, cb);
714 public override AttributeTargets AttributeTargets {
716 throw new NotSupportedException ();
720 public ArrayList Types {
726 public MethodArrayList Methods {
732 public ArrayList Constants {
738 public ArrayList Interfaces {
744 public ArrayList Iterators {
752 return base_class_name;
756 public ArrayList Bases {
766 public ArrayList Fields {
772 public ArrayList InstanceConstructors {
774 return instance_constructors;
778 public ArrayList Properties {
784 public ArrayList Events {
790 public ArrayList Enums {
796 public ArrayList Indexers {
802 public ArrayList Operators {
808 public ArrayList Delegates {
814 public ArrayList Parts {
820 public virtual TypeAttributes TypeAttr {
822 return Modifiers.TypeAttr (ModFlags, this);
826 public string IndexerName {
828 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
833 // Emits the instance field initializers
835 public bool EmitFieldInitializers (EmitContext ec)
838 Expression instance_expr;
841 fields = initialized_static_fields;
842 instance_expr = null;
844 fields = initialized_fields;
845 instance_expr = new This (Location.Null).Resolve (ec);
851 foreach (Field f in fields){
852 Expression e = f.GetInitializerExpression (ec);
856 Location l = f.Location;
857 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
858 fe.InstanceExpression = instance_expr;
859 ExpressionStatement a = new Assign (fe, e, l);
861 a = a.ResolveStatement (ec);
865 a.EmitStatement (ec);
872 // Defines the default constructors
874 protected void DefineDefaultConstructor (bool is_static)
878 // The default constructor is public
879 // If the class is abstract, the default constructor is protected
880 // The default static constructor is private
882 int mods = Modifiers.PUBLIC;
884 mods = Modifiers.STATIC | Modifiers.PRIVATE;
885 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
886 mods = Modifiers.PROTECTED;
888 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
889 new ConstructorBaseInitializer (
890 null, Parameters.EmptyReadOnlyParameters,
896 c.Block = new ToplevelBlock (null, Location);
901 /// The pending methods that need to be implemented
902 // (interfaces or abstract methods)
904 public PendingImplementation Pending;
906 public abstract void Register ();
908 public abstract PendingImplementation GetPendingImplementations ();
910 TypeExpr[] GetPartialBases (out TypeExpr parent, out bool error)
912 ArrayList ifaces = new ArrayList ();
915 Location parent_loc = Location.Null;
917 foreach (ClassPart part in parts) {
919 TypeExpr[] new_ifaces;
921 new_ifaces = part.GetClassBases (out new_parent, out error);
925 if ((parent != null) && (new_parent != null) &&
926 !parent.Equals (new_parent)) {
927 Report.Error (263, part.Location,
928 "Partial declarations of `{0}' must " +
929 "not specify different base classes",
932 if (!Location.IsNull (parent_loc))
933 Report.LocationOfPreviousError (parent_loc);
939 if ((parent == null) && (new_parent != null)) {
941 parent_loc = part.Location;
944 if (new_ifaces == null)
947 foreach (TypeExpr iface in new_ifaces) {
949 foreach (TypeExpr old_iface in ifaces) {
950 if (old_iface.Equals (iface)) {
963 TypeExpr[] retval = new TypeExpr [ifaces.Count];
964 ifaces.CopyTo (retval, 0);
968 TypeExpr[] GetNormalBases (out TypeExpr parent, out bool error)
972 int count = Bases.Count;
975 if (Kind == Kind.Class){
976 TypeExpr name = ResolveTypeExpr (
977 (Expression) Bases [0], false, Location);
994 TypeExpr [] ifaces = new TypeExpr [count-start];
996 for (i = start, j = 0; i < count; i++, j++){
997 Expression name = (Expression) Bases [i];
998 TypeExpr resolved = ResolveTypeExpr (name, false, Location);
999 if (resolved == null) {
1004 ifaces [j] = resolved;
1012 /// This function computes the Base class and also the
1013 /// list of interfaces that the class or struct @c implements.
1015 /// The return value is an array (might be null) of
1016 /// interfaces implemented (as Types).
1018 /// The @parent argument is set to the parent object or null
1019 /// if this is `System.Object'.
1021 TypeExpr [] GetClassBases (out TypeExpr parent, out bool error)
1030 ifaces = GetPartialBases (out parent, out error);
1031 else if (Bases == null){
1035 ifaces = GetNormalBases (out parent, out error);
1040 if ((parent != null) && (Kind == Kind.Class)){
1041 if (parent.IsSealed){
1043 Report.SymbolRelatedToPreviousError (parent.Type);
1044 if (parent.Type.IsAbstract) {
1045 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1047 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1052 if (!parent.CanInheritFrom ()){
1053 Report.Error (644, Location,
1054 "`{0}' cannot inherit from special class `{1}'",
1060 if (!parent.AsAccessible (this, ModFlags)) {
1061 Report.SymbolRelatedToPreviousError (parent.Type);
1062 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1063 TypeManager.CSharpName (parent.Type), GetSignatureForError ());
1068 base_class_name = parent.Name;
1073 int count = ifaces != null ? ifaces.Length : 0;
1075 for (i = 0; i < count; i++) {
1076 TypeExpr iface = (TypeExpr) ifaces [i];
1078 if ((Kind != Kind.Class) && !iface.IsInterface){
1079 string what = Kind == Kind.Struct ?
1080 "Struct" : "Interface";
1082 Report.Error (527, Location,
1083 "In {0} `{1}', type `{2}' is not "+
1084 "an interface", what, Name, iface.Name);
1088 if (iface.IsClass) {
1090 Report.Error (1721, Location,
1091 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1094 Report.Error (1722, Location,
1095 "In Class `{0}', `{1}' is not " +
1096 "an interface, a base class must be listed first", Name, iface.Name);
1102 for (int x = 0; x < i; x++) {
1103 if (iface.Equals (ifaces [x])) {
1104 Report.Error (528, Location,
1105 "`{0}' is already listed in " +
1106 "interface list", iface.Name);
1112 if ((Kind == Kind.Interface) &&
1113 !iface.AsAccessible (Parent, ModFlags))
1114 Report.Error (61, Location,
1115 "Inconsistent accessibility: base " +
1116 "interface `{0}' is less accessible " +
1117 "than interface `{1}'", iface.Name,
1127 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1129 public override TypeBuilder DefineType ()
1131 if (TypeBuilder != null)
1138 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
1145 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1147 TypeExpr[] iface_exprs = GetClassBases (out parent_type, out error);
1151 if (parent_type == null) {
1152 if (Kind == Kind.Class){
1153 if (RootContext.StdLib)
1154 parent_type = TypeManager.system_object_expr;
1155 else if (Name != "System.Object")
1156 parent_type = TypeManager.system_object_expr;
1157 } else if (Kind == Kind.Struct) {
1159 // If we are compiling our runtime,
1160 // and we are defining ValueType, then our
1161 // parent is `System.Object'.
1163 if (!RootContext.StdLib && Name == "System.ValueType")
1164 parent_type = TypeManager.system_object_expr;
1166 parent_type = TypeManager.system_valuetype_expr;
1170 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1171 throw new Exception ();
1173 TypeAttributes type_attributes = TypeAttr;
1175 if (parent_type != null) {
1176 ptype = parent_type.ResolveType (ec);
1177 if (ptype == null) {
1185 if (TypeManager.NamespaceClash (Name, Location)) {
1190 ModuleBuilder builder = CodeGen.Module.Builder;
1191 TypeBuilder = builder.DefineType (
1192 Name, type_attributes, ptype, null);
1195 TypeBuilder builder = Parent.DefineType ();
1196 if (builder == null)
1199 TypeBuilder = builder.DefineNestedType (
1200 Basename, type_attributes, ptype, null);
1203 catch (ArgumentException) {
1204 Report.RuntimeMissingSupport (Location, "static classes");
1209 // Structs with no fields need to have at least one byte.
1210 // The right thing would be to set the PackingSize in a DefineType
1211 // but there are no functions that allow interfaces *and* the size to
1215 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1216 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1217 FieldAttributes.Private);
1220 // add interfaces that were not added at type creation
1221 if (iface_exprs != null) {
1222 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1223 if (ifaces == null) {
1228 foreach (Type itype in ifaces)
1229 TypeBuilder.AddInterfaceImplementation (itype);
1231 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1235 // Finish the setup for the EmitContext
1237 ec.ContainerType = TypeBuilder;
1239 TypeManager.AddUserType (Name, TypeBuilder, this);
1241 if ((parent_type != null) && parent_type.IsAttribute) {
1242 RootContext.RegisterAttribute (this);
1243 } else if (!(this is Iterator))
1244 RootContext.RegisterOrder (this);
1246 if (!DefineNestedTypes ()) {
1255 protected virtual bool DefineNestedTypes ()
1257 if (Interfaces != null) {
1258 foreach (TypeContainer iface in Interfaces)
1259 if (iface.DefineType () == null)
1263 if (Types != null) {
1264 foreach (TypeContainer tc in Types)
1265 if (tc.DefineType () == null)
1269 if (Delegates != null) {
1270 foreach (Delegate d in Delegates)
1271 if (d.DefineType () == null)
1275 if (Enums != null) {
1276 foreach (Enum en in Enums)
1277 if (en.DefineType () == null)
1281 if (Parts != null) {
1282 foreach (ClassPart part in Parts) {
1283 part.TypeBuilder = TypeBuilder;
1285 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1292 static void Error_KeywordNotAllowed (Location loc)
1294 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1298 /// Populates our TypeBuilder with fields and methods
1300 public override bool DefineMembers (TypeContainer container)
1302 if (members_defined)
1303 return members_defined_ok;
1305 members_defined_ok = DoDefineMembers ();
1306 members_defined = true;
1308 return members_defined_ok;
1311 bool DoDefineMembers ()
1314 // We need to be able to use the member cache while we are checking/defining
1316 if (TypeBuilder.BaseType != null)
1317 parent_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
1319 if (TypeBuilder.IsInterface)
1320 parent_cache = TypeManager.LookupParentInterfacesCache (TypeBuilder);
1323 if ((ModFlags & Modifiers.NEW) != 0)
1324 Error_KeywordNotAllowed (Location);
1326 // HACK: missing implemenation
1327 // This is not fully functional. Better way how to handle this is to have recursive definition of containers
1328 // instead of flat as we have now.
1329 // Now we are not able to check inner attribute class because its parent had not been defined.
1331 // TODO: remove this if
1332 if (Parent.MemberCache != null) {
1333 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1334 if (conflict_symbol == null) {
1335 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1336 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1338 if ((ModFlags & Modifiers.NEW) == 0) {
1339 Report.SymbolRelatedToPreviousError (conflict_symbol);
1340 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1346 DefineContainerMembers (constants);
1347 DefineContainerMembers (fields);
1349 if ((Kind == Kind.Class) && !(this is ClassPart) && !(this is StaticClass)){
1350 if ((instance_constructors == null) &&
1351 !(this is StaticClass)) {
1352 if (default_constructor == null)
1353 DefineDefaultConstructor (false);
1356 if (initialized_static_fields != null &&
1357 default_static_constructor == null)
1358 DefineDefaultConstructor (true);
1361 if (Kind == Kind.Struct){
1363 // Structs can not have initialized instance
1366 if (initialized_static_fields != null &&
1367 default_static_constructor == null)
1368 DefineDefaultConstructor (true);
1370 if (initialized_fields != null)
1371 ReportStructInitializedInstanceError ();
1374 Pending = GetPendingImplementations ();
1376 if (parts != null) {
1377 foreach (ClassPart part in parts) {
1378 if (!part.DefineMembers (this))
1384 // Constructors are not in the defined_names array
1386 DefineContainerMembers (instance_constructors);
1388 if (default_static_constructor != null)
1389 default_static_constructor.Define ();
1391 DefineContainerMembers (properties);
1392 DefineContainerMembers (events);
1393 DefineContainerMembers (indexers);
1394 DefineContainerMembers (methods);
1395 DefineContainerMembers (operators);
1396 DefineContainerMembers (enums);
1397 DefineContainerMembers (delegates);
1400 if (!(this is ClassPart))
1401 member_cache = new MemberCache (this);
1404 if (parts != null) {
1405 foreach (ClassPart part in parts)
1406 part.member_cache = member_cache;
1409 if (iterators != null) {
1410 foreach (Iterator iterator in iterators) {
1411 if (iterator.DefineType () == null)
1415 foreach (Iterator iterator in iterators) {
1416 if (!iterator.DefineMembers (this))
1424 void ReportStructInitializedInstanceError ()
1426 string n = TypeBuilder.FullName;
1428 foreach (Field f in initialized_fields){
1431 "`" + n + "." + f.Name + "': can not have " +
1432 "instance field initializers in structs");
1436 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1439 mcal.DefineContainerMembers ();
1442 public override bool Define ()
1444 if (parts != null) {
1445 foreach (ClassPart part in parts) {
1446 if (!part.Define ())
1454 public MemberInfo FindMemberWithSameName (string name, bool ignore_methods)
1456 return ParentCache.FindMemberWithSameName (name, ignore_methods, null);
1460 /// This function is based by a delegate to the FindMembers routine
1462 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1468 /// This filter is used by FindMembers, and we just keep
1469 /// a global for the filter to `AlwaysAccept'
1471 static MemberFilter accepting_filter;
1474 static TypeContainer ()
1476 accepting_filter = new MemberFilter (AlwaysAccept);
1479 public MethodInfo[] GetMethods ()
1481 ArrayList members = new ArrayList ();
1483 DefineMembers (null);
1485 if (methods != null) {
1486 int len = methods.Count;
1487 for (int i = 0; i < len; i++) {
1488 Method m = (Method) methods [i];
1490 members.Add (m.MethodBuilder);
1494 if (operators != null) {
1495 int len = operators.Count;
1496 for (int i = 0; i < len; i++) {
1497 Operator o = (Operator) operators [i];
1499 members.Add (o.OperatorMethodBuilder);
1503 if (properties != null) {
1504 int len = properties.Count;
1505 for (int i = 0; i < len; i++) {
1506 Property p = (Property) properties [i];
1508 if (p.GetBuilder != null)
1509 members.Add (p.GetBuilder);
1510 if (p.SetBuilder != null)
1511 members.Add (p.SetBuilder);
1515 if (indexers != null) {
1516 int len = indexers.Count;
1517 for (int i = 0; i < len; i++) {
1518 Indexer ix = (Indexer) indexers [i];
1520 if (ix.GetBuilder != null)
1521 members.Add (ix.GetBuilder);
1522 if (ix.SetBuilder != null)
1523 members.Add (ix.SetBuilder);
1527 if (events != null) {
1528 int len = events.Count;
1529 for (int i = 0; i < len; i++) {
1530 Event e = (Event) events [i];
1532 if (e.AddBuilder != null)
1533 members.Add (e.AddBuilder);
1534 if (e.RemoveBuilder != null)
1535 members.Add (e.RemoveBuilder);
1539 MethodInfo[] retMethods = new MethodInfo [members.Count];
1540 members.CopyTo (retMethods, 0);
1544 // Indicated whether container has StructLayout attribute set Explicit
1545 public virtual bool HasExplicitLayout {
1552 /// This method returns the members of this type just like Type.FindMembers would
1553 /// Only, we need to use this for types which are _being_ defined because MS'
1554 /// implementation can't take care of that.
1557 // FIXME: return an empty static array instead of null, that cleans up
1558 // some code and is consistent with some coding conventions I just found
1562 // Notice that in various cases we check if our field is non-null,
1563 // something that would normally mean that there was a bug elsewhere.
1565 // The problem happens while we are defining p-invoke methods, as those
1566 // will trigger a FindMembers, but this happens before things are defined
1568 // Since the whole process is a no-op, it is fine to check for null here.
1570 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1571 MemberFilter filter, object criteria)
1573 ArrayList members = null;
1576 if ((bf & BindingFlags.Public) != 0)
1577 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1579 if ((bf & BindingFlags.NonPublic) != 0)
1580 modflags |= Modifiers.PRIVATE;
1582 int static_mask = 0, static_flags = 0;
1583 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1584 case BindingFlags.Static:
1585 static_mask = static_flags = Modifiers.STATIC;
1588 case BindingFlags.Instance:
1589 static_mask = Modifiers.STATIC;
1594 static_mask = static_flags = 0;
1598 Timer.StartTimer (TimerType.TcFindMembers);
1601 filter = accepting_filter;
1603 if ((mt & MemberTypes.Field) != 0) {
1604 if (fields != null) {
1605 int len = fields.Count;
1606 for (int i = 0; i < len; i++) {
1607 Field f = (Field) fields [i];
1609 if ((f.ModFlags & modflags) == 0)
1611 if ((f.ModFlags & static_mask) != static_flags)
1614 FieldBuilder fb = f.FieldBuilder;
1615 if (fb != null && filter (fb, criteria) == true) {
1616 if (members == null)
1617 members = new ArrayList ();
1624 if (constants != null) {
1625 int len = constants.Count;
1626 for (int i = 0; i < len; i++) {
1627 Const con = (Const) constants [i];
1629 if ((con.ModFlags & modflags) == 0)
1631 if ((con.ModFlags & static_mask) != static_flags)
1634 FieldBuilder fb = con.FieldBuilder;
1635 if (fb != null && filter (fb, criteria) == true) {
1636 if (members == null)
1637 members = new ArrayList ();
1645 if ((mt & MemberTypes.Method) != 0) {
1646 if (methods != null) {
1647 int len = methods.Count;
1648 for (int i = 0; i < len; i++) {
1649 Method m = (Method) methods [i];
1651 if ((m.ModFlags & modflags) == 0)
1653 if ((m.ModFlags & static_mask) != static_flags)
1656 MethodBuilder mb = m.MethodBuilder;
1658 if (mb != null && filter (mb, criteria) == true) {
1659 if (members == null)
1660 members = new ArrayList ();
1667 if (operators != null) {
1668 int len = operators.Count;
1669 for (int i = 0; i < len; i++) {
1670 Operator o = (Operator) operators [i];
1672 if ((o.ModFlags & modflags) == 0)
1674 if ((o.ModFlags & static_mask) != static_flags)
1677 MethodBuilder ob = o.OperatorMethodBuilder;
1678 if (ob != null && filter (ob, criteria) == true) {
1679 if (members == null)
1680 members = new ArrayList ();
1687 if (properties != null) {
1688 int len = properties.Count;
1689 for (int i = 0; i < len; i++) {
1690 Property p = (Property) properties [i];
1692 if ((p.ModFlags & modflags) == 0)
1694 if ((p.ModFlags & static_mask) != static_flags)
1700 if (b != null && filter (b, criteria) == true) {
1701 if (members == null)
1702 members = new ArrayList ();
1708 if (b != null && filter (b, criteria) == true) {
1709 if (members == null)
1710 members = new ArrayList ();
1717 if (indexers != null) {
1718 int len = indexers.Count;
1719 for (int i = 0; i < len; i++) {
1720 Indexer ix = (Indexer) indexers [i];
1722 if ((ix.ModFlags & modflags) == 0)
1724 if ((ix.ModFlags & static_mask) != static_flags)
1730 if (b != null && filter (b, criteria) == true) {
1731 if (members == null)
1732 members = new ArrayList ();
1738 if (b != null && filter (b, criteria) == true) {
1739 if (members == null)
1740 members = new ArrayList ();
1748 if ((mt & MemberTypes.Event) != 0) {
1749 if (events != null) {
1750 int len = events.Count;
1751 for (int i = 0; i < len; i++) {
1752 Event e = (Event) events [i];
1754 if ((e.ModFlags & modflags) == 0)
1756 if ((e.ModFlags & static_mask) != static_flags)
1759 MemberInfo eb = e.EventBuilder;
1760 if (eb != null && filter (eb, criteria) == true) {
1761 if (members == null)
1762 members = new ArrayList ();
1764 members.Add (e.EventBuilder);
1770 if ((mt & MemberTypes.Property) != 0){
1771 if (properties != null) {
1772 int len = properties.Count;
1773 for (int i = 0; i < len; i++) {
1774 Property p = (Property) properties [i];
1776 if ((p.ModFlags & modflags) == 0)
1778 if ((p.ModFlags & static_mask) != static_flags)
1781 MemberInfo pb = p.PropertyBuilder;
1782 if (pb != null && filter (pb, criteria) == true) {
1783 if (members == null)
1784 members = new ArrayList ();
1786 members.Add (p.PropertyBuilder);
1791 if (indexers != null) {
1792 int len = indexers.Count;
1793 for (int i = 0; i < len; i++) {
1794 Indexer ix = (Indexer) indexers [i];
1796 if ((ix.ModFlags & modflags) == 0)
1798 if ((ix.ModFlags & static_mask) != static_flags)
1801 MemberInfo ib = ix.PropertyBuilder;
1802 if (ib != null && filter (ib, criteria) == true) {
1803 if (members == null)
1804 members = new ArrayList ();
1806 members.Add (ix.PropertyBuilder);
1812 if ((mt & MemberTypes.NestedType) != 0) {
1813 if (types != null) {
1814 int len = types.Count;
1815 for (int i = 0; i < len; i++) {
1816 TypeContainer t = (TypeContainer) types [i];
1818 if ((t.ModFlags & modflags) == 0)
1821 TypeBuilder tb = t.TypeBuilder;
1822 if (tb != null && (filter (tb, criteria) == true)) {
1823 if (members == null)
1824 members = new ArrayList ();
1831 if (enums != null) {
1832 int len = enums.Count;
1833 for (int i = 0; i < len; i++) {
1834 Enum en = (Enum) enums [i];
1836 if ((en.ModFlags & modflags) == 0)
1839 TypeBuilder tb = en.TypeBuilder;
1840 if (tb != null && (filter (tb, criteria) == true)) {
1841 if (members == null)
1842 members = new ArrayList ();
1849 if (delegates != null) {
1850 int len = delegates.Count;
1851 for (int i = 0; i < len; i++) {
1852 Delegate d = (Delegate) delegates [i];
1854 if ((d.ModFlags & modflags) == 0)
1857 TypeBuilder tb = d.TypeBuilder;
1858 if (tb != null && (filter (tb, criteria) == true)) {
1859 if (members == null)
1860 members = new ArrayList ();
1867 if (interfaces != null) {
1868 int len = interfaces.Count;
1869 for (int i = 0; i < len; i++) {
1870 TypeContainer iface = (TypeContainer) interfaces [i];
1872 if ((iface.ModFlags & modflags) == 0)
1875 TypeBuilder tb = iface.TypeBuilder;
1876 if (tb != null && (filter (tb, criteria) == true)) {
1877 if (members == null)
1878 members = new ArrayList ();
1886 if ((mt & MemberTypes.Constructor) != 0){
1887 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1888 int len = instance_constructors.Count;
1889 for (int i = 0; i < len; i++) {
1890 Constructor c = (Constructor) instance_constructors [i];
1892 ConstructorBuilder cb = c.ConstructorBuilder;
1893 if (cb != null && filter (cb, criteria) == true) {
1894 if (members == null)
1895 members = new ArrayList ();
1902 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1903 ConstructorBuilder cb =
1904 default_static_constructor.ConstructorBuilder;
1906 if (cb != null && filter (cb, criteria) == true) {
1907 if (members == null)
1908 members = new ArrayList ();
1916 // Lookup members in parent if requested.
1918 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1919 if (TypeBuilder.BaseType != null) {
1920 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1921 if (list.Count > 0) {
1922 if (members == null)
1923 members = new ArrayList ();
1925 members.AddRange (list);
1928 if (ifaces != null) {
1929 foreach (Type base_type in ifaces) {
1930 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1932 if (list.Count > 0) {
1933 if (members == null)
1934 members = new ArrayList ();
1935 members.AddRange (list);
1941 Timer.StopTimer (TimerType.TcFindMembers);
1943 if (members == null)
1944 return MemberList.Empty;
1946 return new MemberList (members);
1949 public override MemberCache MemberCache {
1951 return member_cache;
1955 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1956 MemberFilter filter, object criteria)
1958 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1961 return ds.FindMembers (mt, bf, filter, criteria);
1963 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1968 // FindMethods will look for methods not only in the type `t', but in
1969 // any interfaces implemented by the type.
1971 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1972 MemberFilter filter, object criteria)
1978 /// Emits the values for the constants
1980 public void EmitConstants ()
1982 if (constants != null)
1983 foreach (Const con in constants)
1988 protected virtual void VerifyMembers (EmitContext ec)
1991 // Check for internal or private fields that were never assigned
1993 if (RootContext.WarningLevel >= 3) {
1994 if (fields != null){
1995 foreach (Field f in fields) {
1996 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1999 if ((f.status & Field.Status.USED) == 0){
2000 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2005 // Only report 649 on level 4
2007 if (RootContext.WarningLevel < 4)
2010 if ((f.status & Field.Status.ASSIGNED) != 0)
2013 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2020 /// Emits the code, this step is performed after all
2021 /// the types, enumerations, constructors
2023 public void EmitType ()
2025 if (OptAttributes != null)
2026 OptAttributes.Emit (ec, this);
2030 if (instance_constructors != null) {
2031 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2032 bool has_compliant_args = false;
2034 foreach (Constructor c in instance_constructors) {
2037 if (has_compliant_args)
2040 has_compliant_args = c.HasCompliantArgs;
2042 if (!has_compliant_args)
2043 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2045 foreach (Constructor c in instance_constructors)
2052 if (default_static_constructor != null)
2053 default_static_constructor.Emit ();
2055 if (methods != null)
2056 foreach (Method m in methods)
2059 if (operators != null)
2060 foreach (Operator o in operators)
2063 if (properties != null)
2064 foreach (Property p in properties)
2067 if (indexers != null){
2072 foreach (Field f in fields)
2075 if (events != null){
2076 foreach (Event e in Events)
2080 if (delegates != null) {
2081 foreach (Delegate d in Delegates) {
2086 if (enums != null) {
2087 foreach (Enum e in enums) {
2092 if (parts != null) {
2093 foreach (ClassPart part in parts)
2097 if ((Pending != null) && !(this is ClassPart))
2098 if (Pending.VerifyPendingMethods ())
2103 if (iterators != null)
2104 foreach (Iterator iterator in iterators)
2105 iterator.EmitType ();
2107 // if (types != null)
2108 // foreach (TypeContainer tc in types)
2112 public override void CloseType ()
2114 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2118 caching_flags |= Flags.CloseTypeCreated;
2119 TypeBuilder.CreateType ();
2120 } catch (TypeLoadException){
2122 // This is fine, the code still created the type
2124 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2125 // Console.WriteLine (e.Message);
2127 Console.WriteLine ("In type: " + Name);
2132 foreach (Enum en in Enums)
2136 foreach (TypeContainer tc in Types)
2137 if (tc.Kind == Kind.Struct)
2140 foreach (TypeContainer tc in Types)
2141 if (tc.Kind != Kind.Struct)
2145 if (Delegates != null)
2146 foreach (Delegate d in Delegates)
2149 if (Iterators != null)
2150 foreach (Iterator i in Iterators)
2158 initialized_fields = null;
2159 initialized_static_fields = null;
2168 default_constructor = null;
2169 default_static_constructor = null;
2171 OptAttributes = null;
2173 parent_cache = null;
2174 member_cache = null;
2177 // TODO: make it obsolete and use GetSignatureForError
2178 public string MakeName (string n)
2180 return "`" + Name + "." + n + "'";
2184 // Performs the validation on a Method's modifiers (properties have
2185 // the same properties).
2187 public bool MethodModifiersValid (int flags, string n, Location loc)
2189 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2190 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2191 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2195 // At most one of static, virtual or override
2197 if ((flags & Modifiers.STATIC) != 0){
2198 if ((flags & vao) != 0){
2200 112, loc, "static method " + MakeName (n) + "can not be marked " +
2201 "as virtual, abstract or override");
2206 if (Kind == Kind.Struct){
2207 if ((flags & va) != 0){
2208 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
2213 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2215 113, loc, MakeName (n) +
2216 " marked as override cannot be marked as new or virtual");
2221 // If the declaration includes the abstract modifier, then the
2222 // declaration does not include static, virtual or extern
2224 if ((flags & Modifiers.ABSTRACT) != 0){
2225 if ((flags & Modifiers.EXTERN) != 0){
2227 180, loc, MakeName (n) + " can not be both abstract and extern");
2231 if ((flags & Modifiers.VIRTUAL) != 0){
2233 503, loc, MakeName (n) + " can not be both abstract and virtual");
2237 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2239 513, loc, MakeName (n) +
2240 " is abstract but its container class is not");
2246 if ((flags & Modifiers.PRIVATE) != 0){
2247 if ((flags & vao) != 0){
2249 621, loc, MakeName (n) +
2250 " virtual or abstract members can not be private");
2255 if ((flags & Modifiers.SEALED) != 0){
2256 if ((flags & Modifiers.OVERRIDE) == 0){
2258 238, loc, MakeName (n) +
2259 " cannot be sealed because it is not an override");
2267 public bool UserDefinedStaticConstructor {
2269 return default_static_constructor != null;
2273 public Constructor DefaultStaticConstructor {
2274 get { return default_static_constructor; }
2277 protected override bool VerifyClsCompliance (DeclSpace ds)
2279 if (!base.VerifyClsCompliance (ds))
2284 Type base_type = TypeBuilder.BaseType;
2285 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2286 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2293 /// Checks whether container name is CLS Compliant
2295 void VerifyClsName ()
2297 Hashtable parent_members = parent_cache == null ?
2299 parent_cache.GetPublicMembers ();
2300 Hashtable this_members = new Hashtable ();
2302 foreach (DictionaryEntry entry in defined_names) {
2303 MemberCore mc = (MemberCore)entry.Value;
2304 if (!mc.IsClsCompliaceRequired (this))
2307 string name = (string)entry.Key;
2308 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2310 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2311 object found = parent_members [lcase];
2312 if (found == null) {
2313 found = this_members [lcase];
2314 if (found == null) {
2315 this_members.Add (lcase, mc);
2320 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2323 if (found is MemberInfo) {
2324 if (basename == ((MemberInfo)found).Name)
2326 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2328 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2330 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2336 /// Performs checks for an explicit interface implementation. First it
2337 /// checks whether the `interface_type' is a base inteface implementation.
2338 /// Then it checks whether `name' exists in the interface type.
2340 public virtual bool VerifyImplements (Type interface_type, string full,
2341 string name, Location loc)
2345 if (ifaces != null){
2346 foreach (Type t in ifaces){
2347 if (t == interface_type){
2355 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2356 full, interface_type.FullName);
2363 protected override void VerifyObsoleteAttribute()
2365 CheckUsageOfObsoleteAttribute (ptype);
2370 foreach (Type iface in ifaces) {
2371 CheckUsageOfObsoleteAttribute (iface);
2380 string IMemberContainer.Name {
2386 Type IMemberContainer.Type {
2392 MemberCache IMemberContainer.MemberCache {
2394 return member_cache;
2398 bool IMemberContainer.IsInterface {
2400 return Kind == Kind.Interface;
2404 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2406 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2410 // Generates xml doc comments (if any), and if required,
2411 // handle warning report.
2413 internal override void GenerateDocComment (DeclSpace ds)
2415 DocUtil.GenerateTypeDocComment (this, ds);
2418 public override string DocCommentHeader {
2419 get { return "T:"; }
2422 public virtual MemberCache ParentCache {
2424 return parent_cache;
2429 public class PartialContainer : TypeContainer {
2431 public readonly Namespace Namespace;
2432 public readonly int OriginalModFlags;
2433 public readonly int AllowedModifiers;
2434 public readonly TypeAttributes DefaultTypeAttributes;
2436 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2437 MemberName member_name, int mod_flags, Kind kind,
2440 PartialContainer pc;
2441 string full_name = member_name.GetName (true);
2442 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2444 pc = ds as PartialContainer;
2448 260, ds.Location, "Missing partial modifier " +
2449 "on declaration of type `{0}'; another " +
2450 "partial implementation of this type exists",
2451 member_name.GetPartialName());
2453 Report.LocationOfPreviousError (loc);
2457 if (pc.Kind != kind) {
2459 261, loc, "Partial declarations of `{0}' " +
2460 "must be all classes, all structs or " +
2461 "all interfaces", member_name.GetPartialName ());
2465 if (pc.OriginalModFlags != mod_flags) {
2467 262, loc, "Partial declarations of `{0}' " +
2468 "have conflicting accessibility modifiers",
2469 member_name.GetPartialName ());
2476 pc = new PartialContainer (ns, parent, member_name, mod_flags, kind, loc);
2477 RootContext.Tree.RecordDecl (full_name, pc);
2478 parent.AddType (pc);
2483 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2484 MemberName name, int mod, Attributes attrs,
2485 Kind kind, Location loc)
2487 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2489 // An error occured; create a dummy container, but don't
2491 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2494 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2499 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2500 MemberName name, int mod, Kind kind, Location l)
2501 : base (ns, parent, name, null, kind, l)
2503 this.Namespace = ns.NS;
2507 AllowedModifiers = Class.AllowedModifiers;
2508 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2512 AllowedModifiers = Struct.AllowedModifiers;
2513 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2516 case Kind.Interface:
2517 AllowedModifiers = Interface.AllowedModifiers;
2518 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2522 throw new InvalidOperationException ();
2526 if (parent.Parent == null)
2527 accmods = Modifiers.INTERNAL;
2529 accmods = Modifiers.PRIVATE;
2531 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2532 this.OriginalModFlags = mod;
2535 public override void Register ()
2537 if (Kind == Kind.Interface)
2538 Parent.AddInterface (this);
2539 else if (Kind == Kind.Class || Kind == Kind.Struct)
2540 Parent.AddClassOrStruct (this);
2542 throw new InvalidOperationException ();
2545 public override PendingImplementation GetPendingImplementations ()
2547 return PendingImplementation.GetPendingImplementations (this);
2550 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2553 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2558 public override TypeAttributes TypeAttr {
2560 return base.TypeAttr | DefaultTypeAttributes;
2565 public class ClassPart : TypeContainer, IMemberContainer {
2566 public readonly PartialContainer PartialContainer;
2567 public readonly bool IsPartial;
2569 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2570 int mod, Attributes attrs, Kind kind, Location l)
2571 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2573 this.PartialContainer = parent;
2574 this.IsPartial = true;
2577 if (parent.Parent == null)
2578 accmods = Modifiers.INTERNAL;
2580 accmods = Modifiers.PRIVATE;
2582 this.ModFlags = Modifiers.Check (
2583 parent.AllowedModifiers, mod, accmods, l);
2586 public override void Register ()
2590 public override PendingImplementation GetPendingImplementations ()
2592 return PartialContainer.Pending;
2595 public override bool VerifyImplements (Type interface_type, string full,
2596 string name, Location loc)
2598 return PartialContainer.VerifyImplements (
2599 interface_type, full, name, loc);
2602 public override MemberCache ParentCache {
2604 return PartialContainer.ParentCache;
2609 public abstract class ClassOrStruct : TypeContainer {
2610 bool hasExplicitLayout = false;
2611 ListDictionary declarative_security;
2613 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2614 MemberName name, Attributes attrs, Kind kind,
2616 : base (ns, parent, name, attrs, kind, l)
2620 public override PendingImplementation GetPendingImplementations ()
2622 return PendingImplementation.GetPendingImplementations (this);
2625 public override bool HasExplicitLayout {
2627 return hasExplicitLayout;
2631 protected override void VerifyMembers (EmitContext ec)
2633 base.VerifyMembers (ec);
2635 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2636 foreach (Event e in events){
2638 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2643 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2645 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2646 if (declarative_security == null)
2647 declarative_security = new ListDictionary ();
2649 a.ExtractSecurityPermissionSet (declarative_security);
2653 if (a.Type == TypeManager.struct_layout_attribute_type
2654 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2655 hasExplicitLayout = true;
2657 base.ApplyAttributeBuilder (a, cb);
2660 public override void Emit()
2664 if (declarative_security != null) {
2665 foreach (DictionaryEntry de in declarative_security) {
2666 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2671 public override void Register ()
2673 Parent.AddClassOrStruct (this);
2678 /// Class handles static classes declaration
2680 public sealed class StaticClass: Class {
2681 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2682 Attributes attrs, Location l)
2683 : base (ns, parent, name, mod & ~Modifiers.STATIC, attrs, l)
2685 if (RootContext.Version == LanguageVersion.ISO_1) {
2686 Report.FeatureIsNotStandardized (l, "static classes");
2687 Environment.Exit (1);
2691 protected override void DefineContainerMembers (MemberCoreArrayList list)
2696 foreach (MemberCore m in list) {
2697 if (m is Operator) {
2698 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2702 if ((m.ModFlags & Modifiers.STATIC) != 0)
2705 if (m is Constructor) {
2706 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2710 if (m is Destructor) {
2711 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2715 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2718 base.DefineContainerMembers (list);
2721 public override TypeBuilder DefineType()
2723 TypeBuilder tb = base.DefineType ();
2727 if (ptype != TypeManager.object_type) {
2728 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2732 if (ifaces != null) {
2733 foreach (Type t in ifaces)
2734 Report.SymbolRelatedToPreviousError (t);
2735 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2740 public override TypeAttributes TypeAttr {
2742 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2747 public class Class : ClassOrStruct {
2749 // Modifiers allowed in a class declaration
2751 public const int AllowedModifiers =
2754 Modifiers.PROTECTED |
2755 Modifiers.INTERNAL |
2757 Modifiers.ABSTRACT |
2761 // Information in the case we are an attribute type
2762 AttributeUsageAttribute attribute_usage;
2764 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2765 Attributes attrs, Location l)
2766 : base (ns, parent, name, attrs, Kind.Class, l)
2770 if (parent.Parent == null)
2771 accmods = Modifiers.INTERNAL;
2773 accmods = Modifiers.PRIVATE;
2775 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2776 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.SEALED)) == (Modifiers.ABSTRACT | Modifiers.SEALED)) {
2777 Report.Error (502, Location, "'{0}' cannot be both abstract and sealed", GetSignatureForError ());
2780 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2783 public override AttributeTargets AttributeTargets {
2785 return AttributeTargets.Class;
2789 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2791 if (a.UsageAttribute != null) {
2792 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2793 TypeBuilder.FullName != "System.Attribute") {
2794 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2796 attribute_usage = a.UsageAttribute;
2799 base.ApplyAttributeBuilder (a, cb);
2802 public AttributeUsageAttribute AttributeUsage {
2804 return attribute_usage;
2808 public const TypeAttributes DefaultTypeAttributes =
2809 TypeAttributes.AutoLayout | TypeAttributes.Class;
2812 // FIXME: How do we deal with the user specifying a different
2815 public override TypeAttributes TypeAttr {
2817 return base.TypeAttr | DefaultTypeAttributes;
2822 public class Struct : ClassOrStruct {
2824 // Modifiers allowed in a struct declaration
2826 public const int AllowedModifiers =
2829 Modifiers.PROTECTED |
2830 Modifiers.INTERNAL |
2834 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2835 int mod, Attributes attrs, Location l)
2836 : base (ns, parent, name, attrs, Kind.Struct, l)
2840 if (parent.Parent == null)
2841 accmods = Modifiers.INTERNAL;
2843 accmods = Modifiers.PRIVATE;
2845 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2847 this.ModFlags |= Modifiers.SEALED;
2850 public override AttributeTargets AttributeTargets {
2852 return AttributeTargets.Struct;
2856 public const TypeAttributes DefaultTypeAttributes =
2857 TypeAttributes.SequentialLayout |
2858 TypeAttributes.Sealed |
2859 TypeAttributes.BeforeFieldInit;
2862 // FIXME: Allow the user to specify a different set of attributes
2863 // in some cases (Sealed for example is mandatory for a class,
2864 // but what SequentialLayout can be changed
2866 public override TypeAttributes TypeAttr {
2868 return base.TypeAttr | DefaultTypeAttributes;
2876 public class Interface : TypeContainer, IMemberContainer {
2878 /// Modifiers allowed in a class declaration
2880 public const int AllowedModifiers =
2883 Modifiers.PROTECTED |
2884 Modifiers.INTERNAL |
2888 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2889 Attributes attrs, Location l)
2890 : base (ns, parent, name, attrs, Kind.Interface, l)
2894 if (parent.Parent == null)
2895 accmods = Modifiers.INTERNAL;
2897 accmods = Modifiers.PRIVATE;
2899 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2902 public override void Register ()
2904 Parent.AddInterface (this);
2907 public override PendingImplementation GetPendingImplementations ()
2912 public override AttributeTargets AttributeTargets {
2914 return AttributeTargets.Interface;
2918 public const TypeAttributes DefaultTypeAttributes =
2919 TypeAttributes.AutoLayout |
2920 TypeAttributes.Abstract |
2921 TypeAttributes.Interface;
2923 public override TypeAttributes TypeAttr {
2925 return base.TypeAttr | DefaultTypeAttributes;
2930 public abstract class MethodCore : MemberBase {
2931 public readonly Parameters Parameters;
2932 protected ToplevelBlock block;
2935 // Parameters, cached for semantic analysis.
2937 protected InternalParameters parameter_info;
2938 protected Type [] parameter_types;
2940 // Whether this is an operator method.
2941 public bool IsOperator;
2944 // The method we're overriding if this is an override method.
2946 protected MethodInfo parent_method = null;
2948 static string[] attribute_targets = new string [] { "method", "return" };
2950 public MethodCore (TypeContainer parent, Expression type, int mod,
2951 int allowed_mod, bool is_interface, MemberName name,
2952 Attributes attrs, Parameters parameters, Location loc)
2953 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
2956 Parameters = parameters;
2957 IsInterface = is_interface;
2961 // Returns the System.Type array for the parameters of this method
2963 public Type [] ParameterTypes {
2965 return parameter_types;
2969 public InternalParameters ParameterInfo
2972 return parameter_info;
2976 public ToplevelBlock Block {
2986 protected override bool CheckBase ()
2988 if (!base.CheckBase ())
2991 // Check whether arguments were correct.
2992 if (!DoDefineParameters ())
2995 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3001 // Is null for System.Object while compiling corlib and base interfaces
3002 if (Parent.ParentCache == null) {
3003 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3004 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3009 Type parent_ret_type = null;
3010 parent_method = FindOutParentMethod (Parent, ref parent_ret_type);
3012 // method is override
3013 if (parent_method != null) {
3015 if (!CheckMethodAgainstBase ())
3018 if ((ModFlags & Modifiers.NEW) == 0) {
3019 if (MemberType != TypeManager.TypeToCoreType (parent_ret_type)) {
3020 Report.SymbolRelatedToPreviousError (parent_method);
3021 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3022 "change return type when overriding inherited member");
3026 if (parent_method.IsAbstract && !IsInterface) {
3027 Report.SymbolRelatedToPreviousError (parent_method);
3028 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3033 if (parent_method.IsSpecialName && !(this is PropertyBase)) {
3034 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (parent_method));
3038 if (RootContext.WarningLevel > 2) {
3039 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3040 Parent.Methods.HasEquals = true;
3041 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3042 Parent.Methods.HasGetHashCode = true;
3045 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (parent_method);
3047 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3048 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3049 Report.SymbolRelatedToPreviousError (parent_method);
3050 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3056 MemberInfo conflict_symbol = Parent.FindMemberWithSameName (Name, !(this is Property));
3057 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3058 if (conflict_symbol != null) {
3059 Report.SymbolRelatedToPreviousError (conflict_symbol);
3060 if (this is PropertyBase)
3061 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3063 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3065 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3069 if (conflict_symbol == null) {
3070 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3071 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3076 if ((ModFlags & Modifiers.NEW) == 0) {
3077 if (this is Method && conflict_symbol is MethodBase)
3080 Report.SymbolRelatedToPreviousError (conflict_symbol);
3081 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3089 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3090 // that have been defined.
3092 // `name' is the user visible name for reporting errors (this is used to
3093 // provide the right name regarding method names and properties)
3095 bool CheckMethodAgainstBase ()
3099 // TODO: replace with GetSignatureForError
3100 string name = parent_method.DeclaringType.Name + "." + parent_method.Name;
3102 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3103 if (!(parent_method.IsAbstract || parent_method.IsVirtual)){
3105 506, Location, Parent.MakeName (Name) +
3106 ": cannot override inherited member `" +
3107 name + "' because it is not " +
3108 "virtual, abstract or override");
3112 // Now we check that the overriden method is not final
3114 if (parent_method.IsFinal) {
3115 // This happens when implementing interface methods.
3116 if (parent_method.IsHideBySig && parent_method.IsVirtual) {
3118 506, Location, Parent.MakeName (Name) +
3119 ": cannot override inherited member `" +
3120 name + "' because it is not " +
3121 "virtual, abstract or override");
3123 Report.Error (239, Location, Parent.MakeName (Name) + " : cannot " +
3124 "override inherited member `" + name +
3125 "' because it is sealed.");
3129 // Check that the permissions are not being changed
3131 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3132 MethodAttributes parentp = parent_method.Attributes & MethodAttributes.MemberAccessMask;
3134 if (!CheckAccessModifiers (thisp, parentp, parent_method)) {
3135 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3140 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3141 ModFlags |= Modifiers.NEW;
3142 Report.SymbolRelatedToPreviousError (parent_method);
3143 if (!IsInterface && (parent_method.IsVirtual || parent_method.IsAbstract)) {
3144 if (RootContext.WarningLevel >= 2)
3145 Report.Warning (114, Location, "'{0}' hides inherited member '{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword", GetSignatureForError (Parent), TypeManager.CSharpSignature (parent_method));
3147 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3153 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes parentp, MethodInfo base_method)
3155 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3157 // when overriding protected internal, the method can be declared
3158 // protected internal only within the same assembly
3161 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3162 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3164 // assemblies differ - report an error
3168 } else if (thisp != parentp) {
3170 // same assembly, but other attributes differ - report an error
3175 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3177 // if it's not "protected internal", it must be "protected"
3181 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3183 // protected within the same assembly - an error
3186 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3187 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3189 // protected ok, but other attributes differ - report an error
3195 return (thisp == parentp);
3199 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method, string name)
3202 // FIXME: report the old/new permissions?
3205 507, Location, parent.MakeName (Name) +
3206 ": can't change the access modifiers when overriding inherited " +
3207 "member `" + name + "'");
3210 protected static string Error722 {
3212 return "'{0}': static types cannot be used as return types";
3217 /// For custom member duplication search in a container
3219 protected abstract bool CheckForDuplications ();
3222 /// Gets parent method and its return type
3224 protected abstract MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type);
3226 protected virtual bool DoDefineParameters ()
3228 EmitContext ec = Parent.EmitContext;
3230 throw new InternalErrorException ("DoDefineParameters invoked too early");
3232 bool old_unsafe = ec.InUnsafe;
3233 ec.InUnsafe = InUnsafe;
3234 // Check if arguments were correct
3235 parameter_types = Parameters.GetParameterInfo (ec);
3236 ec.InUnsafe = old_unsafe;
3238 if ((parameter_types == null) ||
3239 !CheckParameters (Parent, parameter_types))
3242 parameter_info = new InternalParameters (parameter_types, Parameters);
3244 Parameter array_param = Parameters.ArrayParameter;
3245 if ((array_param != null) &&
3246 (!array_param.ParameterType.IsArray ||
3247 (array_param.ParameterType.GetArrayRank () != 1))) {
3248 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3255 public override string[] ValidAttributeTargets {
3257 return attribute_targets;
3261 protected override bool VerifyClsCompliance (DeclSpace ds)
3263 if (!base.VerifyClsCompliance (ds)) {
3264 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3265 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3270 if (Parameters.HasArglist) {
3271 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3274 if (!AttributeTester.IsClsCompliant (MemberType)) {
3275 if ((this is Property) || (this is Indexer))
3276 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3277 GetSignatureForError ());
3279 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3280 GetSignatureForError ());
3283 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3288 protected bool IsDuplicateImplementation (MethodCore method)
3290 if ((method == this) || (method.Name != Name))
3293 Type[] param_types = method.ParameterTypes;
3294 if (param_types == null)
3297 if (param_types.Length != ParameterTypes.Length)
3300 for (int i = 0; i < param_types.Length; i++)
3301 if (param_types [i] != ParameterTypes [i])
3304 // TODO: make operator compatible with MethodCore to avoid this
3305 if (this is Operator && method is Operator) {
3306 if (MemberType != method.MemberType)
3311 // Try to report 663: method only differs on out/ref
3313 ParameterData info = ParameterInfo;
3314 ParameterData other_info = method.ParameterInfo;
3315 for (int i = 0; i < info.Count; i++){
3316 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3317 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3322 Report.SymbolRelatedToPreviousError (method);
3323 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3328 // Returns a string that represents the signature for this
3329 // member which should be used in XML documentation.
3331 public override string GetDocCommentName (DeclSpace ds)
3333 return DocUtil.GetMethodDocCommentName (this, ds);
3337 // Raised (and passed an XmlElement that contains the comment)
3338 // when GenerateDocComment is writing documentation expectedly.
3340 // FIXME: with a few effort, it could be done with XmlReader,
3341 // that means removal of DOM use.
3343 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3345 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3349 // Represents header string for documentation comment.
3351 public override string DocCommentHeader {
3352 get { return "M:"; }
3355 protected override void VerifyObsoleteAttribute()
3357 base.VerifyObsoleteAttribute ();
3359 if (parameter_types == null)
3362 foreach (Type type in parameter_types) {
3363 CheckUsageOfObsoleteAttribute (type);
3368 public class SourceMethod : ISourceMethod
3370 TypeContainer container;
3373 protected SourceMethod (TypeContainer container, MethodBase builder,
3374 ISourceFile file, Location start, Location end)
3376 this.container = container;
3377 this.builder = builder;
3379 CodeGen.SymbolWriter.OpenMethod (
3380 file, this, start.Row, 0, end.Row, 0);
3383 public string Name {
3384 get { return builder.Name; }
3387 public int NamespaceID {
3388 get { return container.NamespaceEntry.SymbolFileID; }
3393 if (builder is MethodBuilder)
3394 return ((MethodBuilder) builder).GetToken ().Token;
3395 else if (builder is ConstructorBuilder)
3396 return ((ConstructorBuilder) builder).GetToken ().Token;
3398 throw new NotSupportedException ();
3402 public void CloseMethod ()
3404 if (CodeGen.SymbolWriter != null)
3405 CodeGen.SymbolWriter.CloseMethod ();
3408 public static SourceMethod Create (TypeContainer parent,
3409 MethodBase builder, Block block)
3411 if (CodeGen.SymbolWriter == null)
3416 Location start_loc = block.StartLocation;
3417 if (Location.IsNull (start_loc))
3420 Location end_loc = block.EndLocation;
3421 if (Location.IsNull (end_loc))
3424 ISourceFile file = start_loc.SourceFile;
3428 return new SourceMethod (
3429 parent, builder, file, start_loc, end_loc);
3433 public class Method : MethodCore, IIteratorContainer, IMethodData {
3434 public MethodBuilder MethodBuilder;
3435 public MethodData MethodData;
3436 ReturnParameter return_attributes;
3437 ListDictionary declarative_security;
3440 /// Modifiers allowed in a class declaration
3442 const int AllowedModifiers =
3445 Modifiers.PROTECTED |
3446 Modifiers.INTERNAL |
3451 Modifiers.OVERRIDE |
3452 Modifiers.ABSTRACT |
3454 Modifiers.METHOD_YIELDS |
3457 const int AllowedInterfaceModifiers =
3458 Modifiers.NEW | Modifiers.UNSAFE;
3461 // return_type can be "null" for VOID values.
3463 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3464 MemberName name, Parameters parameters, Attributes attrs,
3466 : base (ds, return_type, mod,
3467 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3468 is_iface, name, attrs, parameters, l)
3472 public override AttributeTargets AttributeTargets {
3474 return AttributeTargets.Method;
3478 public override string GetSignatureForError()
3480 if (MethodBuilder == null) {
3481 return GetSignatureForError (Parent);
3483 return TypeManager.CSharpSignature (MethodBuilder);
3487 /// Use this method when MethodBuilder is null
3489 public override string GetSignatureForError (TypeContainer tc)
3491 // TODO: get params from somewhere
3492 if (parameter_info == null)
3493 return base.GetSignatureForError (tc);
3495 // TODO: move to parameters
3496 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3497 if (parameter_info.Parameters.FixedParameters != null) {
3498 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3499 Parameter p = parameter_info.Parameters.FixedParameters [i];
3500 args.Append (p.GetSignatureForError ());
3502 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3507 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3510 void DuplicateEntryPoint (MethodInfo b, Location location)
3514 "Program `" + CodeGen.FileName +
3515 "' has more than one entry point defined: `" +
3516 TypeManager.CSharpSignature(b) + "'");
3519 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3521 if (b.ReturnType != TypeManager.void_type &&
3522 b.ReturnType != TypeManager.int32_type)
3525 if (pinfo.Count == 0)
3528 if (pinfo.Count > 1)
3531 Type t = pinfo.ParameterType(0);
3533 (t.GetArrayRank() == 1) &&
3534 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3535 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3541 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3543 if (a.Target == AttributeTargets.ReturnValue) {
3544 if (return_attributes == null)
3545 return_attributes = new ReturnParameter (MethodBuilder, Location);
3547 return_attributes.ApplyAttributeBuilder (a, cb);
3551 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
3552 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3555 if (a.Type == TypeManager.dllimport_type) {
3556 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3557 if ((ModFlags & extern_static) != extern_static) {
3558 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3564 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3565 if (declarative_security == null)
3566 declarative_security = new ListDictionary ();
3567 a.ExtractSecurityPermissionSet (declarative_security);
3571 if (a.Type == TypeManager.conditional_attribute_type) {
3572 if (IsOperator || IsExplicitImpl) {
3573 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3577 if (ReturnType != TypeManager.void_type) {
3578 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3582 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3583 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3588 Report.Error (582, Location, "Conditional not valid on interface members");
3592 if (MethodData.IsImplementing) {
3593 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3597 for (int i = 0; i < parameter_info.Count; ++i) {
3598 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3599 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3605 MethodBuilder.SetCustomAttribute (cb);
3608 protected override bool CheckForDuplications ()
3610 ArrayList ar = Parent.Methods;
3612 int arLen = ar.Count;
3614 for (int i = 0; i < arLen; i++) {
3615 Method m = (Method) ar [i];
3616 if (IsDuplicateImplementation (m))
3621 ar = Parent.Properties;
3623 for (int i = 0; i < ar.Count; ++i) {
3624 PropertyBase pb = (PropertyBase) ar [i];
3625 if (pb.AreAccessorsDuplicateImplementation (this))
3630 ar = Parent.Indexers;
3632 for (int i = 0; i < ar.Count; ++i) {
3633 PropertyBase pb = (PropertyBase) ar [i];
3634 if (pb.AreAccessorsDuplicateImplementation (this))
3641 for (int i = 0; i < ar.Count; ++i) {
3642 Event ev = (Event) ar [i];
3643 if (ev.AreAccessorsDuplicateImplementation (this))
3654 public override bool Define ()
3663 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3665 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3667 if (!MethodData.Define (Parent))
3671 // Setup iterator if we are one
3673 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3674 Iterator iterator = new Iterator (
3675 Parent, Name, MemberType, ParameterTypes,
3676 ParameterInfo, ModFlags, block, Location);
3678 if (!iterator.DefineIterator ())
3681 block = iterator.Block;
3684 MethodBuilder = MethodData.MethodBuilder;
3687 // This is used to track the Entry Point,
3689 if (Name == "Main" &&
3690 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3691 (RootContext.MainClass == null ||
3692 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3693 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3694 if (RootContext.EntryPoint == null) {
3695 RootContext.EntryPoint = MethodBuilder;
3696 RootContext.EntryPointLocation = Location;
3698 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3699 DuplicateEntryPoint (MethodBuilder, Location);
3702 if (RootContext.WarningLevel >= 4)
3703 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3707 if (MemberType.IsAbstract && MemberType.IsSealed) {
3708 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3718 public override void Emit ()
3720 MethodData.Emit (Parent, this);
3723 if (declarative_security != null) {
3724 foreach (DictionaryEntry de in declarative_security) {
3725 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3733 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
3735 MethodInfo mi = (MethodInfo) container.ParentCache.FindMemberToOverride (
3736 container.TypeBuilder, Name, ParameterTypes, false);
3741 parent_ret_type = mi.ReturnType;
3745 protected override bool VerifyClsCompliance(DeclSpace ds)
3747 if (!base.VerifyClsCompliance (ds))
3750 if (parameter_types.Length > 0) {
3751 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3753 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3760 void IIteratorContainer.SetYields ()
3762 ModFlags |= Modifiers.METHOD_YIELDS;
3765 #region IMethodData Members
3767 public CallingConventions CallingConventions {
3769 CallingConventions cc = Parameters.GetCallingConvention ();
3770 if (Parameters.HasArglist)
3771 block.HasVarargs = true;
3774 if ((ModFlags & Modifiers.STATIC) == 0)
3775 cc |= CallingConventions.HasThis;
3777 // FIXME: How is `ExplicitThis' used in C#?
3783 public Type ReturnType {
3789 public MemberName MethodName {
3795 public new Location Location {
3797 return base.Location;
3801 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3803 return new EmitContext (
3804 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3807 public ObsoleteAttribute GetObsoleteAttribute ()
3809 return GetObsoleteAttribute (Parent);
3813 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3815 public bool IsExcluded (EmitContext ec)
3817 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3818 return (caching_flags & Flags.Excluded) != 0;
3820 caching_flags &= ~Flags.Excluded_Undetected;
3822 if (parent_method == null) {
3823 if (OptAttributes == null)
3826 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3831 foreach (Attribute a in attrs) {
3832 string condition = a.GetConditionalAttributeValue (
3834 if (RootContext.AllDefines.Contains (condition))
3838 caching_flags |= Flags.Excluded;
3842 IMethodData md = TypeManager.GetMethod (parent_method);
3844 if (AttributeTester.IsConditionalMethodExcluded (parent_method)) {
3845 caching_flags |= Flags.Excluded;
3851 if (md.IsExcluded (ec)) {
3852 caching_flags |= Flags.Excluded;
3861 public abstract class ConstructorInitializer {
3862 ArrayList argument_list;
3863 protected ConstructorInfo parent_constructor;
3864 Parameters parameters;
3867 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
3870 this.argument_list = argument_list;
3871 this.parameters = parameters;
3875 public ArrayList Arguments {
3877 return argument_list;
3881 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
3883 Expression parent_constructor_group;
3886 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
3888 if (argument_list != null){
3889 foreach (Argument a in argument_list){
3890 if (!a.Resolve (ec, loc))
3894 ec.CurrentBlock = null;
3896 if (this is ConstructorBaseInitializer) {
3897 if (ec.ContainerType.BaseType == null)
3900 t = ec.ContainerType.BaseType;
3901 if (ec.ContainerType.IsValueType) {
3902 Report.Error (522, loc,
3903 "structs cannot call base class constructors");
3907 t = ec.ContainerType;
3909 parent_constructor_group = Expression.MemberLookup (
3910 ec, t, ".ctor", MemberTypes.Constructor,
3911 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3914 if (parent_constructor_group == null){
3915 parent_constructor_group = Expression.MemberLookup (
3916 ec, t, ".ctor", MemberTypes.Constructor,
3917 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3920 if (parent_constructor_group != null)
3922 112, loc, "`{0}.{1}' is inaccessible due to " +
3923 "its protection level", t.FullName, t.Name);
3926 1501, loc, "Can not find a constructor for " +
3927 "this argument list");
3931 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (
3932 ec, (MethodGroupExpr) parent_constructor_group, argument_list,
3935 if (parent_constructor == null){
3936 Report.Error (1501, loc,
3937 "Can not find a constructor for this argument list");
3941 if (parent_constructor == caller_builder){
3942 Report.Error (516, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
3949 public void Emit (EmitContext ec)
3951 if (parent_constructor != null){
3952 ec.Mark (loc, false);
3954 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
3956 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
3961 /// Method search for base ctor. (We do not cache it).
3963 Constructor GetOverloadedConstructor (TypeContainer tc)
3965 if (tc.InstanceConstructors == null)
3968 foreach (Constructor c in tc.InstanceConstructors) {
3969 if (Arguments == null) {
3970 if (c.ParameterTypes.Length == 0)
3978 int count = c.ParameterInfo.Count;
3980 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
3981 for (int i = 0; i < count-1; i++)
3982 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
3987 if (c.ParameterTypes.Length != Arguments.Count)
3990 for (int i = 0; i < Arguments.Count; ++i)
3991 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4006 //TODO: implement caching when it will be necessary
4007 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4009 Constructor ctor = GetOverloadedConstructor (tc);
4013 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4017 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4021 public class ConstructorBaseInitializer : ConstructorInitializer {
4022 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4023 base (argument_list, pars, l)
4027 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4028 if (parent_constructor == null)
4031 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4032 if (type_ds == null) {
4033 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (parent_constructor);
4036 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (parent_constructor), loc);
4041 base.CheckObsoleteAttribute (type_ds, loc);
4046 public class ConstructorThisInitializer : ConstructorInitializer {
4047 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4048 base (argument_list, pars, l)
4053 public class Constructor : MethodCore, IMethodData {
4054 public ConstructorBuilder ConstructorBuilder;
4055 public ConstructorInitializer Initializer;
4056 ListDictionary declarative_security;
4059 // Modifiers allowed for a constructor.
4061 public const int AllowedModifiers =
4063 Modifiers.PROTECTED |
4064 Modifiers.INTERNAL |
4070 bool has_compliant_args = false;
4072 // The spec claims that static is not permitted, but
4073 // my very own code has static constructors.
4075 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4076 ConstructorInitializer init, Location l)
4077 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4083 public override string GetSignatureForError()
4085 if (ConstructorBuilder == null)
4086 return GetSignatureForError (Parent);
4088 return TypeManager.CSharpSignature (ConstructorBuilder);
4091 public bool HasCompliantArgs {
4093 return has_compliant_args;
4097 public override AttributeTargets AttributeTargets {
4099 return AttributeTargets.Constructor;
4105 // Returns true if this is a default constructor
4107 public bool IsDefault ()
4109 if ((ModFlags & Modifiers.STATIC) != 0)
4110 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4111 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4114 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4115 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4116 (Initializer is ConstructorBaseInitializer) &&
4117 (Initializer.Arguments == null);
4120 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4122 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4123 if (declarative_security == null) {
4124 declarative_security = new ListDictionary ();
4126 a.ExtractSecurityPermissionSet (declarative_security);
4130 ConstructorBuilder.SetCustomAttribute (cb);
4133 protected override bool CheckForDuplications ()
4135 ArrayList ar = Parent.InstanceConstructors;
4137 int arLen = ar.Count;
4139 for (int i = 0; i < arLen; i++) {
4140 Constructor m = (Constructor) ar [i];
4141 if (IsDuplicateImplementation (m))
4148 protected override bool CheckBase ()
4150 // Check whether arguments were correct.
4151 if (!DoDefineParameters ())
4154 // TODO: skip the rest for generated ctor
4155 if ((ModFlags & Modifiers.STATIC) != 0)
4158 if (!CheckForDuplications ())
4161 if (Parent.Kind == Kind.Struct) {
4162 if (ParameterTypes.Length == 0) {
4163 Report.Error (568, Location,
4164 "Structs can not contain explicit parameterless " +
4169 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4170 Report.Error (666, Location, "Protected member in struct declaration");
4175 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4176 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4183 // Creates the ConstructorBuilder
4185 public override bool Define ()
4187 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4188 MethodAttributes.SpecialName);
4190 if ((ModFlags & Modifiers.STATIC) != 0) {
4191 ca |= MethodAttributes.Static | MethodAttributes.Private;
4193 ca |= MethodAttributes.HideBySig;
4195 if ((ModFlags & Modifiers.PUBLIC) != 0)
4196 ca |= MethodAttributes.Public;
4197 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4198 if ((ModFlags & Modifiers.INTERNAL) != 0)
4199 ca |= MethodAttributes.FamORAssem;
4201 ca |= MethodAttributes.Family;
4202 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4203 ca |= MethodAttributes.Assembly;
4204 else if (IsDefault ())
4205 ca |= MethodAttributes.Public;
4207 ca |= MethodAttributes.Private;
4210 // Check if arguments were correct.
4214 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4215 ca, CallingConventions,
4218 if ((ModFlags & Modifiers.UNSAFE) != 0)
4219 ConstructorBuilder.InitLocals = false;
4221 TypeManager.AddMethod (ConstructorBuilder, this);
4224 // HACK because System.Reflection.Emit is lame
4226 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4234 public override void Emit ()
4236 EmitContext ec = CreateEmitContext (null, null);
4239 // extern methods have no bodies
4241 if ((ModFlags & Modifiers.EXTERN) != 0) {
4242 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4244 179, Location, "External constructor `" +
4245 TypeManager.CSharpSignature (ConstructorBuilder) +
4246 "' can not have a body");
4249 } else if (block == null) {
4251 501, Location, "Constructor `" +
4252 TypeManager.CSharpSignature (ConstructorBuilder) +
4253 "' must declare a body since it is not marked extern");
4257 if ((ModFlags & Modifiers.STATIC) == 0){
4258 if (Parent.Kind == Kind.Class && Initializer == null)
4259 Initializer = new ConstructorBaseInitializer (
4260 null, Parameters.EmptyReadOnlyParameters, Location);
4264 // Spec mandates that Initializers will not have
4268 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4270 ec.IsStatic = false;
4273 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4275 SourceMethod source = SourceMethod.Create (
4276 Parent, ConstructorBuilder, block);
4279 // Classes can have base initializers and instance field initializers.
4281 if (Parent.Kind == Kind.Class){
4282 if ((ModFlags & Modifiers.STATIC) == 0){
4285 // If we use a "this (...)" constructor initializer, then
4286 // do not emit field initializers, they are initialized in the other constructor
4288 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4289 Parent.EmitFieldInitializers (ec);
4292 if (Initializer != null) {
4293 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4294 Initializer.CheckObsoleteAttribute (Parent, Location);
4296 ec.TestObsoleteMethodUsage = false;
4297 Initializer.Emit (ec);
4300 if ((ModFlags & Modifiers.STATIC) != 0)
4301 Parent.EmitFieldInitializers (ec);
4303 if (OptAttributes != null)
4304 OptAttributes.Emit (ec, this);
4306 // If this is a non-static `struct' constructor and doesn't have any
4307 // initializer, it must initialize all of the struct's fields.
4308 if ((Parent.Kind == Kind.Struct) &&
4309 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4310 Block.AddThisVariable (Parent, Location);
4312 ec.EmitTopBlock (block, ParameterInfo, Location);
4315 source.CloseMethod ();
4319 if (declarative_security != null) {
4320 foreach (DictionaryEntry de in declarative_security) {
4321 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4328 // Is never override
4329 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
4334 protected override bool VerifyClsCompliance (DeclSpace ds)
4336 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4340 if (parameter_types.Length > 0) {
4341 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4343 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4345 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4346 foreach (Type param in parameter_types) {
4347 if (param.IsArray) {
4353 has_compliant_args = true;
4357 #region IMethodData Members
4359 public System.Reflection.CallingConventions CallingConventions {
4361 CallingConventions cc = Parameters.GetCallingConvention ();
4363 if (Parent.Kind == Kind.Class)
4364 if ((ModFlags & Modifiers.STATIC) == 0)
4365 cc |= CallingConventions.HasThis;
4367 // FIXME: How is `ExplicitThis' used in C#?
4373 public new Location Location {
4375 return base.Location;
4379 public MemberName MethodName {
4385 public Type ReturnType {
4391 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4393 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4394 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4397 public ObsoleteAttribute GetObsoleteAttribute ()
4402 public bool IsExcluded(EmitContext ec)
4411 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4413 public interface IMethodData
4415 CallingConventions CallingConventions { get; }
4416 Location Location { get; }
4417 MemberName MethodName { get; }
4418 Type[] ParameterTypes { get; }
4419 Type ReturnType { get; }
4421 Attributes OptAttributes { get; }
4422 ToplevelBlock Block { get; }
4424 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4425 ObsoleteAttribute GetObsoleteAttribute ();
4426 string GetSignatureForError (TypeContainer tc);
4427 bool IsExcluded (EmitContext ec);
4428 bool IsClsCompliaceRequired (DeclSpace ds);
4432 // Encapsulates most of the Method's state
4434 public class MethodData {
4436 readonly IMethodData method;
4439 // The return type of this method
4441 public readonly InternalParameters ParameterInfo;
4444 // Are we implementing an interface ?
4446 public bool IsImplementing = false;
4451 protected MemberBase member;
4452 protected int modifiers;
4453 protected MethodAttributes flags;
4455 MethodBuilder builder = null;
4456 public MethodBuilder MethodBuilder {
4462 public MethodData (MemberBase member, InternalParameters parameters,
4463 int modifiers, MethodAttributes flags, IMethodData method)
4465 this.member = member;
4466 this.ParameterInfo = parameters;
4467 this.modifiers = modifiers;
4470 this.method = method;
4473 public bool Define (TypeContainer container)
4475 MethodInfo implementing = null;
4477 string name = method.MethodName.Name;
4478 string method_name = name;
4480 Type[] ParameterTypes = method.ParameterTypes;
4482 if (container.Pending != null){
4483 if (member is Indexer)
4484 implementing = container.Pending.IsInterfaceIndexer (
4485 member.InterfaceType, method.ReturnType, ParameterTypes);
4487 implementing = container.Pending.IsInterfaceMethod (
4488 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4490 if (member.InterfaceType != null){
4491 if (implementing == null){
4492 Report.Error (539, method.Location,
4493 "'{0}' in explicit interface declaration is not an interface", method_name);
4496 method_name = member.InterfaceType.FullName + "." + name;
4501 // For implicit implementations, make sure we are public, for
4502 // explicit implementations, make sure we are private.
4504 if (implementing != null){
4506 // Setting null inside this block will trigger a more
4507 // verbose error reporting for missing interface implementations
4509 // The "candidate" function has been flagged already
4510 // but it wont get cleared
4512 if (member.IsExplicitImpl){
4513 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4514 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4515 implementing = null;
4517 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4518 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4520 // If this is an interface method implementation,
4521 // check for public accessibility
4523 implementing = null;
4524 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4525 // We may never be private.
4526 implementing = null;
4527 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4529 // We may be protected if we're overriding something.
4531 implementing = null;
4536 // Static is not allowed
4538 if ((modifiers & Modifiers.STATIC) != 0){
4539 implementing = null;
4540 Modifiers.Error_InvalidModifier (method.Location, "static");
4545 // If implementing is still valid, set flags
4547 if (implementing != null){
4549 // When implementing interface methods, set NewSlot
4550 // unless, we are overwriting a method.
4552 if (implementing.DeclaringType.IsInterface){
4553 if ((modifiers & Modifiers.OVERRIDE) == 0)
4554 flags |= MethodAttributes.NewSlot;
4557 MethodAttributes.Virtual |
4558 MethodAttributes.HideBySig;
4560 // Set Final unless we're virtual, abstract or already overriding a method.
4561 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4562 flags |= MethodAttributes.Final;
4564 IsImplementing = true;
4567 EmitContext ec = method.CreateEmitContext (container, null);
4569 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4571 if (builder == null)
4574 if ((modifiers & Modifiers.UNSAFE) != 0)
4575 builder.InitLocals = false;
4577 if (IsImplementing){
4579 // clear the pending implemntation flag
4581 if (member is Indexer) {
4582 container.Pending.ImplementIndexer (
4583 member.InterfaceType, builder, method.ReturnType,
4584 ParameterTypes, member.IsExplicitImpl);
4586 container.Pending.ImplementMethod (
4587 member.InterfaceType, name, method.ReturnType,
4588 ParameterTypes, member.IsExplicitImpl);
4590 if (member.IsExplicitImpl)
4591 container.TypeBuilder.DefineMethodOverride (
4592 builder, implementing);
4596 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4597 TypeManager.AddMethod (builder, method);
4604 /// Create the MethodBuilder for the method
4606 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4608 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4610 if ((modifiers & extern_static) == extern_static) {
4612 if (method.OptAttributes != null) {
4613 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4614 if (dllimport_attribute != null) {
4615 flags |= MethodAttributes.PinvokeImpl;
4616 builder = dllimport_attribute.DefinePInvokeMethod (
4617 ec, container.TypeBuilder, method_name, flags,
4618 method.ReturnType, ParameterTypes);
4624 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4625 // We are more strict than Microsoft and report CS0626 like error
4626 if (method.OptAttributes == null ||
4627 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4628 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));
4633 builder = container.TypeBuilder.DefineMethod (
4634 method_name, flags, method.CallingConventions,
4635 method.ReturnType, ParameterTypes);
4641 public void Emit (TypeContainer container, Attributable kind)
4644 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4645 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4647 ec = method.CreateEmitContext (container, null);
4649 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container.Parent) != null)
4650 ec.TestObsoleteMethodUsage = false;
4652 Location loc = method.Location;
4653 Attributes OptAttributes = method.OptAttributes;
4655 if (OptAttributes != null)
4656 OptAttributes.Emit (ec, kind);
4658 if (member is MethodCore)
4659 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4661 SymbolWriter sw = CodeGen.SymbolWriter;
4662 ToplevelBlock block = method.Block;
4665 // abstract or extern methods have no bodies
4667 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4672 // abstract or extern methods have no bodies.
4674 if ((modifiers & Modifiers.ABSTRACT) != 0)
4676 500, method.Location, "Abstract method `" +
4677 TypeManager.CSharpSignature (builder) +
4678 "' can not have a body");
4680 if ((modifiers & Modifiers.EXTERN) != 0)
4682 179, method.Location, "External method `" +
4683 TypeManager.CSharpSignature (builder) +
4684 "' can not have a body");
4690 // Methods must have a body unless they're extern or abstract
4692 if (block == null) {
4694 501, method.Location, "Method `" +
4695 TypeManager.CSharpSignature (builder) +
4696 "' must declare a body since it is not marked " +
4697 "abstract or extern");
4701 SourceMethod source = SourceMethod.Create (
4702 container, MethodBuilder, method.Block);
4705 // Handle destructors specially
4707 // FIXME: This code generates buggy code
4709 if (member is Destructor)
4710 EmitDestructor (ec, block);
4712 ec.EmitTopBlock (block, ParameterInfo, loc);
4715 source.CloseMethod ();
4718 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4720 ILGenerator ig = ec.ig;
4722 Label finish = ig.DefineLabel ();
4724 block.SetDestructor ();
4726 ig.BeginExceptionBlock ();
4727 ec.ReturnLabel = finish;
4728 ec.HasReturnLabel = true;
4729 ec.EmitTopBlock (block, null, method.Location);
4731 // ig.MarkLabel (finish);
4732 ig.BeginFinallyBlock ();
4734 if (ec.ContainerType.BaseType != null) {
4735 Expression member_lookup = Expression.MemberLookup (
4736 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4737 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4739 if (member_lookup != null){
4740 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
4742 ig.Emit (OpCodes.Ldarg_0);
4743 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
4747 ig.EndExceptionBlock ();
4748 //ig.MarkLabel (ec.ReturnLabel);
4749 ig.Emit (OpCodes.Ret);
4753 public class Destructor : Method {
4755 public Destructor (TypeContainer ds, Expression return_type, int mod,
4756 string name, Parameters parameters, Attributes attrs,
4758 : base (ds, return_type, mod, false, new MemberName (name),
4759 parameters, attrs, l)
4762 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4764 if (a.Type == TypeManager.conditional_attribute_type) {
4765 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4769 base.ApplyAttributeBuilder (a, cb);
4773 abstract public class MemberBase : MemberCore {
4774 public Expression Type;
4776 public MethodAttributes flags;
4778 protected readonly int explicit_mod_flags;
4781 // The "short" name of this property / indexer / event. This is the
4782 // name without the explicit interface.
4784 public string ShortName;
4787 // The type of this property / indexer / event
4789 public Type MemberType;
4792 // If true, this is an explicit interface implementation
4794 public bool IsExplicitImpl = false;
4797 // The name of the interface we are explicitly implementing
4799 public MemberName ExplicitInterfaceName = null;
4802 // Whether this is an interface member.
4804 public bool IsInterface;
4807 // If true, the interface type we are explicitly implementing
4809 public Type InterfaceType = null;
4812 // The constructor is only exposed to our children
4814 protected MemberBase (TypeContainer parent, Expression type, int mod,
4815 int allowed_mod, int def_mod, MemberName name,
4816 Attributes attrs, Location loc)
4817 : base (parent, name, attrs, loc)
4819 explicit_mod_flags = mod;
4821 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4823 // Check for explicit interface implementation
4824 if (MemberName.Left != null) {
4825 ExplicitInterfaceName = MemberName.Left;
4826 ShortName = MemberName.Name;
4827 IsExplicitImpl = true;
4832 protected virtual bool CheckBase ()
4834 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4835 Report.Error (666, Location, "Protected member in struct declaration");
4839 if ((RootContext.WarningLevel >= 4) &&
4840 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4841 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4842 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4843 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4848 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4852 foreach (Type partype in parameters){
4853 if (partype == TypeManager.void_type) {
4855 1547, Location, "Keyword 'void' cannot " +
4856 "be used in this context");
4860 if (partype.IsPointer){
4863 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4867 if (ds.AsAccessible (partype, ModFlags))
4870 if (this is Indexer)
4871 Report.Error (55, Location,
4872 "Inconsistent accessibility: parameter type `" +
4873 TypeManager.CSharpName (partype) + "' is less " +
4874 "accessible than indexer `" + Name + "'");
4875 else if ((this is Method) && ((Method) this).IsOperator)
4876 Report.Error (57, Location,
4877 "Inconsistent accessibility: parameter type `" +
4878 TypeManager.CSharpName (partype) + "' is less " +
4879 "accessible than operator `" + Name + "'");
4881 Report.Error (51, Location,
4882 "Inconsistent accessibility: parameter type `" +
4883 TypeManager.CSharpName (partype) + "' is less " +
4884 "accessible than method `" + Name + "'");
4891 protected virtual bool DoDefine ()
4893 EmitContext ec = Parent.EmitContext;
4895 throw new InternalErrorException ("MemberBase.DoDefine called too early");
4898 throw new InternalErrorException ();
4901 ModFlags = Modifiers.PUBLIC |
4902 Modifiers.ABSTRACT |
4903 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
4905 flags = MethodAttributes.Public |
4906 MethodAttributes.Abstract |
4907 MethodAttributes.HideBySig |
4908 MethodAttributes.NewSlot |
4909 MethodAttributes.Virtual;
4911 if (!Parent.MethodModifiersValid (ModFlags, Name, Location))
4914 flags = Modifiers.MethodAttr (ModFlags);
4917 // Lookup Type, verify validity
4918 bool old_unsafe = ec.InUnsafe;
4919 ec.InUnsafe = InUnsafe;
4920 Type = Type.ResolveAsTypeTerminal (ec, false);
4921 ec.InUnsafe = old_unsafe;
4926 MemberType = Type.Type;
4928 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
4929 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
4930 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
4935 // verify accessibility
4936 if (!Parent.AsAccessible (MemberType, ModFlags)) {
4937 if (this is Property)
4938 Report.Error (53, Location,
4939 "Inconsistent accessibility: property type `" +
4940 TypeManager.CSharpName (MemberType) + "' is less " +
4941 "accessible than property `" + Name + "'");
4942 else if (this is Indexer)
4943 Report.Error (54, Location,
4944 "Inconsistent accessibility: indexer return type `" +
4945 TypeManager.CSharpName (MemberType) + "' is less " +
4946 "accessible than indexer `" + Name + "'");
4947 else if (this is MethodCore) {
4948 if (this is Operator)
4949 Report.Error (56, Location,
4950 "Inconsistent accessibility: return type `" +
4951 TypeManager.CSharpName (MemberType) + "' is less " +
4952 "accessible than operator `" + Name + "'");
4954 Report.Error (50, Location,
4955 "Inconsistent accessibility: return type `" +
4956 TypeManager.CSharpName (MemberType) + "' is less " +
4957 "accessible than method `" + Name + "'");
4959 Report.Error (52, Location,
4960 "Inconsistent accessibility: field type `" +
4961 TypeManager.CSharpName (MemberType) + "' is less " +
4962 "accessible than field `" + Name + "'");
4967 if (MemberType.IsPointer && !UnsafeOK (Parent))
4970 if (IsExplicitImpl) {
4971 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
4972 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
4976 InterfaceType = texpr.ResolveType (ec);
4978 if (!InterfaceType.IsInterface) {
4979 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
4984 // Compute the full name that we need to export.
4985 if (InterfaceType.FullName != ExplicitInterfaceName) {
4986 ExplicitInterfaceName = InterfaceType.FullName;
4987 UpdateMemberName ();
4991 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
4994 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5001 /// The name of the member can be changed during definition (see IndexerName attribute)
5003 protected virtual void UpdateMemberName ()
5005 MemberName.Name = ShortName;
5008 public override string GetSignatureForError (TypeContainer tc)
5010 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5013 protected bool IsTypePermitted ()
5015 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5016 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5022 protected override bool VerifyClsCompliance(DeclSpace ds)
5024 if (base.VerifyClsCompliance (ds)) {
5028 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5029 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5034 protected override void VerifyObsoleteAttribute()
5036 CheckUsageOfObsoleteAttribute (MemberType);
5041 // Fields and Events both generate FieldBuilders, we use this to share
5042 // their common bits. This is also used to flag usage of the field
5044 abstract public class FieldBase : MemberBase {
5045 public FieldBuilder FieldBuilder;
5046 public Status status;
5049 public enum Status : byte {
5052 HAS_OFFSET = 4 // Used by FieldMember.
5055 static string[] attribute_targets = new string [] { "field" };
5058 /// Symbol with same name in parent class/struct
5060 public MemberInfo conflict_symbol;
5063 // The constructor is only exposed to our children
5065 protected FieldBase (TypeContainer parent, Expression type, int mod,
5066 int allowed_mod, MemberName name, object init,
5067 Attributes attrs, Location loc)
5068 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5074 public override AttributeTargets AttributeTargets {
5076 return AttributeTargets.Field;
5080 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5082 if (a.Type == TypeManager.marshal_as_attr_type) {
5083 UnmanagedMarshal marshal = a.GetMarshal (this);
5084 if (marshal != null) {
5085 FieldBuilder.SetMarshal (marshal);
5090 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5091 a.Error_InvalidSecurityParent ();
5095 FieldBuilder.SetCustomAttribute (cb);
5099 // Whether this field has an initializer.
5101 public bool HasInitializer {
5103 return init != null;
5107 protected readonly Object init;
5110 Expression init_expr;
5111 bool init_expr_initialized = false;
5114 // Resolves and returns the field initializer.
5116 public Expression GetInitializerExpression (EmitContext ec)
5118 if (init_expr_initialized)
5122 if (init is Expression)
5123 e = (Expression) init;
5125 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5127 ec.IsFieldInitializer = true;
5128 e = e.DoResolve (ec);
5129 ec.IsFieldInitializer = false;
5132 init_expr_initialized = true;
5137 protected override bool CheckBase ()
5139 if (!base.CheckBase ())
5146 conflict_symbol = Parent.FindMemberWithSameName (Name, false);
5147 if (conflict_symbol == null) {
5148 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5149 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5154 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5155 Report.SymbolRelatedToPreviousError (conflict_symbol);
5156 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5162 public override string GetSignatureForError ()
5164 if (FieldBuilder == null) {
5165 return base.GetSignatureForError (Parent);
5167 return TypeManager.GetFullNameSignature (FieldBuilder);
5170 public override string[] ValidAttributeTargets {
5172 return attribute_targets;
5176 protected override bool VerifyClsCompliance (DeclSpace ds)
5178 if (!base.VerifyClsCompliance (ds))
5181 if (FieldBuilder == null) {
5185 if (!AttributeTester.IsClsCompliant (FieldBuilder.FieldType)) {
5186 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5192 public void SetAssigned ()
5194 status |= Status.ASSIGNED;
5198 public abstract class FieldMember: FieldBase
5202 protected FieldMember (TypeContainer parent, Expression type, int mod,
5203 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5204 : base (parent, type, mod, allowed_mod, name, init, attrs, loc)
5208 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5210 if (a.Type == TypeManager.field_offset_attribute_type)
5212 status |= Status.HAS_OFFSET;
5214 if (!Parent.HasExplicitLayout) {
5215 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5219 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5220 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5224 base.ApplyAttributeBuilder (a, cb);
5228 public override bool Define()
5230 EmitContext ec = Parent.EmitContext;
5232 throw new InternalErrorException ("FieldMember.Define called too early");
5234 bool old_unsafe = ec.InUnsafe;
5235 ec.InUnsafe = InUnsafe;
5236 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
5240 MemberType = texpr.ResolveType (ec);
5242 if (MemberType == TypeManager.void_type) {
5243 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5247 ec.InUnsafe = old_unsafe;
5252 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5253 Report.Error (52, Location,
5254 "Inconsistent accessibility: field type `" +
5255 TypeManager.CSharpName (MemberType) + "' is less " +
5256 "accessible than field `" + Name + "'");
5260 if (!IsTypePermitted ())
5263 if (MemberType.IsPointer && !UnsafeOK (Parent))
5269 public override void Emit ()
5271 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5272 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5279 // Represents header string for documentation comment.
5281 public override string DocCommentHeader {
5282 get { return "F:"; }
5287 // The Field class is used to represents class/struct fields during parsing.
5289 public class Field : FieldMember {
5291 // Modifiers allowed in a class declaration
5293 const int AllowedModifiers =
5296 Modifiers.PROTECTED |
5297 Modifiers.INTERNAL |
5300 Modifiers.VOLATILE |
5304 public Field (TypeContainer parent, Expression type, int mod, string name,
5305 Object expr_or_array_init, Attributes attrs, Location loc)
5306 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5307 expr_or_array_init, attrs, loc)
5311 public override bool Define ()
5313 if (!base.Define ())
5316 if (RootContext.WarningLevel > 1){
5317 Type ptype = Parent.TypeBuilder.BaseType;
5319 // ptype is only null for System.Object while compiling corlib.
5321 TypeContainer.FindMembers (
5322 ptype, MemberTypes.Method,
5323 BindingFlags.Public |
5324 BindingFlags.Static | BindingFlags.Instance,
5325 System.Type.FilterName, Name);
5329 if ((ModFlags & Modifiers.VOLATILE) != 0){
5330 if (!MemberType.IsClass){
5331 Type vt = MemberType;
5333 if (TypeManager.IsEnumType (vt))
5334 vt = TypeManager.EnumToUnderlying (MemberType);
5336 if (!((vt == TypeManager.bool_type) ||
5337 (vt == TypeManager.sbyte_type) ||
5338 (vt == TypeManager.byte_type) ||
5339 (vt == TypeManager.short_type) ||
5340 (vt == TypeManager.ushort_type) ||
5341 (vt == TypeManager.int32_type) ||
5342 (vt == TypeManager.uint32_type) ||
5343 (vt == TypeManager.char_type) ||
5344 (vt == TypeManager.float_type) ||
5345 (!vt.IsValueType))){
5347 677, Location, Parent.MakeName (Name) +
5348 " A volatile field can not be of type `" +
5349 TypeManager.CSharpName (vt) + "'");
5354 if ((ModFlags & Modifiers.READONLY) != 0){
5357 "A field can not be both volatile and readonly");
5362 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5364 if (Parent.Kind == Kind.Struct &&
5365 ((fa & FieldAttributes.Static) == 0) &&
5366 MemberType == Parent.TypeBuilder &&
5367 !TypeManager.IsBuiltinType (MemberType)){
5368 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5369 "' causes a cycle in the structure layout");
5374 FieldBuilder = Parent.TypeBuilder.DefineField (
5375 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5377 TypeManager.RegisterFieldBase (FieldBuilder, this);
5379 catch (ArgumentException) {
5380 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5387 public override void Emit ()
5389 if (OptAttributes != null) {
5390 EmitContext ec = new EmitContext (
5391 Parent, Location, null, FieldBuilder.FieldType,
5393 OptAttributes.Emit (ec, this);
5401 // `set' and `get' accessors are represented with an Accessor.
5403 public class Accessor {
5405 // Null if the accessor is empty, or a Block if not
5407 public const int AllowedModifiers =
5409 Modifiers.PROTECTED |
5410 Modifiers.INTERNAL |
5413 public ToplevelBlock Block;
5414 public Attributes Attributes;
5415 public Location Location;
5416 public int ModFlags;
5418 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5423 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5428 // Ooouh Martin, templates are missing here.
5429 // When it will be possible move here a lot of child code and template method type.
5430 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5431 protected MethodData method_data;
5432 protected ToplevelBlock block;
5433 protected ListDictionary declarative_security;
5435 // The accessor are created event if they are not wanted.
5436 // But we need them because their names are reserved.
5437 // Field says whether accessor will be emited or not
5438 public readonly bool IsDummy;
5440 protected readonly string prefix;
5442 ReturnParameter return_attributes;
5444 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5445 : base (null, SetupName (prefix, member), null, member.Location)
5447 this.prefix = prefix;
5451 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5453 : base (null, SetupName (prefix, member),
5454 accessor.Attributes, accessor.Location)
5456 this.prefix = prefix;
5457 this.block = accessor.Block;
5460 static MemberName SetupName (string prefix, MemberBase member)
5462 MemberName name = member.MemberName.Clone ();
5463 name.Name = prefix + member.ShortName;
5467 public void UpdateName (MemberBase member)
5469 MemberName.Name = prefix + member.ShortName;
5472 #region IMethodData Members
5474 public ToplevelBlock Block {
5484 public CallingConventions CallingConventions {
5486 return CallingConventions.Standard;
5490 public bool IsExcluded (EmitContext ec)
5495 public MemberName MethodName {
5501 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5502 public abstract Type[] ParameterTypes { get; }
5503 public abstract Type ReturnType { get; }
5504 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5508 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5510 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5511 a.Type == TypeManager.conditional_attribute_type) {
5512 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 ());
5516 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5517 if (declarative_security == null)
5518 declarative_security = new ListDictionary ();
5519 a.ExtractSecurityPermissionSet (declarative_security);
5523 if (a.Target == AttributeTargets.Method) {
5524 method_data.MethodBuilder.SetCustomAttribute (cb);
5528 if (a.Target == AttributeTargets.ReturnValue) {
5529 if (return_attributes == null)
5530 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5532 return_attributes.ApplyAttributeBuilder (a, cb);
5536 ApplyToExtraTarget (a, cb);
5539 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5541 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5544 public override bool Define()
5546 throw new NotSupportedException ();
5549 public virtual void Emit (TypeContainer container)
5551 method_data.Emit (container, this);
5553 if (declarative_security != null) {
5554 foreach (DictionaryEntry de in declarative_security) {
5555 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5562 public override bool IsClsCompliaceRequired(DeclSpace ds)
5567 public bool IsDuplicateImplementation (MethodCore method)
5569 if (Name != method.Name)
5572 Type[] param_types = method.ParameterTypes;
5574 if (param_types.Length != ParameterTypes.Length)
5577 for (int i = 0; i < param_types.Length; i++)
5578 if (param_types [i] != ParameterTypes [i])
5581 Report.SymbolRelatedToPreviousError (method);
5582 Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
5586 public new Location Location {
5588 return base.Location;
5593 // Represents header string for documentation comment.
5595 public override string DocCommentHeader {
5596 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5599 protected override void VerifyObsoleteAttribute()
5606 // Properties and Indexers both generate PropertyBuilders, we use this to share
5607 // their common bits.
5609 abstract public class PropertyBase : MethodCore {
5611 public class GetMethod: PropertyMethod
5613 static string[] attribute_targets = new string [] { "method", "return" };
5615 public GetMethod (MethodCore method):
5616 base (method, "get_")
5620 public GetMethod (MethodCore method, Accessor accessor):
5621 base (method, accessor, "get_")
5625 public override MethodBuilder Define(TypeContainer container)
5627 base.Define (container);
5629 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5631 if (!method_data.Define (container))
5634 return method_data.MethodBuilder;
5637 public override string GetSignatureForError (TypeContainer tc)
5639 return String.Concat (base.GetSignatureForError (tc), ".get");
5642 public override Type ReturnType {
5644 return method.MemberType;
5648 public override string[] ValidAttributeTargets {
5650 return attribute_targets;
5655 public class SetMethod: PropertyMethod {
5657 static string[] attribute_targets = new string [] { "method", "param", "return" };
5658 ImplicitParameter param_attr;
5660 public SetMethod (MethodCore method):
5661 base (method, "set_")
5665 public SetMethod (MethodCore method, Accessor accessor):
5666 base (method, accessor, "set_")
5670 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5672 if (a.Target == AttributeTargets.Parameter) {
5673 if (param_attr == null)
5674 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5676 param_attr.ApplyAttributeBuilder (a, cb);
5680 base.ApplyAttributeBuilder (a, cb);
5683 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5685 Parameter [] parms = new Parameter [1];
5686 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
5687 Parameters parameters = new Parameters (parms, null, method.Location);
5688 Type [] types = parameters.GetParameterInfo (ec);
5689 return new InternalParameters (types, parameters);
5692 public override MethodBuilder Define(TypeContainer container)
5694 if (container.EmitContext == null)
5695 throw new InternalErrorException ("SetMethod.Define called too early");
5697 base.Define (container);
5699 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5701 if (!method_data.Define (container))
5704 return method_data.MethodBuilder;
5707 public override string GetSignatureForError (TypeContainer tc)
5709 return String.Concat (base.GetSignatureForError (tc), ".set");
5712 public override Type[] ParameterTypes {
5714 return new Type[] { method.MemberType };
5718 public override Type ReturnType {
5720 return TypeManager.void_type;
5724 public override string[] ValidAttributeTargets {
5726 return attribute_targets;
5731 static string[] attribute_targets = new string [] { "property" };
5733 public abstract class PropertyMethod: AbstractPropertyEventMethod
5735 protected readonly MethodCore method;
5736 protected MethodAttributes flags;
5738 public PropertyMethod (MethodCore method, string prefix)
5739 : base (method, prefix)
5741 this.method = method;
5744 public PropertyMethod (MethodCore method, Accessor accessor,
5746 : base (method, accessor, prefix)
5748 this.method = method;
5749 this.ModFlags = accessor.ModFlags;
5751 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
5752 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
5753 Environment.Exit (1);
5757 public override AttributeTargets AttributeTargets {
5759 return AttributeTargets.Method;
5763 public override bool IsClsCompliaceRequired(DeclSpace ds)
5765 return method.IsClsCompliaceRequired (ds);
5768 public InternalParameters ParameterInfo
5771 return method_data.ParameterInfo;
5775 public virtual MethodBuilder Define (TypeContainer container)
5778 // Check for custom access modifier
5780 if (ModFlags == 0) {
5781 ModFlags = method.ModFlags;
5782 flags = method.flags;
5784 CheckModifiers (container, ModFlags);
5785 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
5786 flags = Modifiers.MethodAttr (ModFlags);
5787 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
5794 public override Type[] ParameterTypes {
5796 return TypeManager.NoTypes;
5800 public override EmitContext CreateEmitContext (TypeContainer tc,
5803 return new EmitContext (
5804 tc, method.Parent, method.Location, ig, ReturnType,
5805 method.ModFlags, false);
5808 public override ObsoleteAttribute GetObsoleteAttribute ()
5810 return method.GetObsoleteAttribute (method.Parent);
5813 public override string GetSignatureForError (TypeContainer tc)
5815 return String.Concat (tc.Name, '.', method.Name);
5818 void CheckModifiers (TypeContainer container, int modflags)
5821 int mflags = method.ModFlags & Modifiers.Accessibility;
5823 if ((mflags & Modifiers.PUBLIC) != 0) {
5824 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
5826 else if ((mflags & Modifiers.PROTECTED) != 0) {
5827 if ((mflags & Modifiers.INTERNAL) != 0)
5828 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
5830 flags |= Modifiers.PRIVATE;
5832 else if ((mflags & Modifiers.INTERNAL) != 0)
5833 flags |= Modifiers.PRIVATE;
5835 if ((mflags == modflags) || (modflags & (~flags)) != 0)
5836 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
5837 GetSignatureForError (container));
5843 public PropertyMethod Get, Set;
5844 public PropertyBuilder PropertyBuilder;
5845 public MethodBuilder GetBuilder, SetBuilder;
5847 protected EmitContext ec;
5849 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
5850 int allowed_mod, bool is_iface, MemberName name,
5851 Parameters parameters, Attributes attrs,
5853 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
5854 attrs, parameters, loc)
5858 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5860 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5861 a.Error_InvalidSecurityParent ();
5865 PropertyBuilder.SetCustomAttribute (cb);
5868 public override AttributeTargets AttributeTargets {
5870 return AttributeTargets.Property;
5874 public override bool Define ()
5879 if (!IsTypePermitted ())
5885 protected override bool DoDefine ()
5887 if (!base.DoDefine ())
5891 // Accessors modifiers check
5893 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
5894 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
5895 GetSignatureForError ());
5899 if ((Get.IsDummy || Set.IsDummy)
5900 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
5901 Report.Error (276, Location,
5902 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
5903 GetSignatureForError ());
5907 if (MemberType.IsAbstract && MemberType.IsSealed) {
5908 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
5912 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
5916 public override string GetSignatureForError()
5918 if (PropertyBuilder == null)
5919 return GetSignatureForError (Parent);
5921 return TypeManager.CSharpSignature (PropertyBuilder, false);
5925 protected override bool CheckForDuplications ()
5927 ArrayList ar = Parent.Indexers;
5929 int arLen = ar.Count;
5931 for (int i = 0; i < arLen; i++) {
5932 Indexer m = (Indexer) ar [i];
5933 if (IsDuplicateImplementation (m))
5938 ar = Parent.Properties;
5940 int arLen = ar.Count;
5942 for (int i = 0; i < arLen; i++) {
5943 Property m = (Property) ar [i];
5944 if (IsDuplicateImplementation (m))
5952 // TODO: rename to Resolve......
5953 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
5955 PropertyInfo parent_property = container.ParentCache.FindMemberToOverride (
5956 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
5958 if (parent_property == null)
5961 parent_ret_type = parent_property.PropertyType;
5962 MethodInfo get_accessor = parent_property.GetGetMethod (true);
5963 MethodInfo set_accessor = parent_property.GetSetMethod (true);
5964 MethodAttributes get_accessor_access, set_accessor_access;
5966 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
5967 if (Get != null && !Get.IsDummy && get_accessor == null) {
5968 Report.SymbolRelatedToPreviousError (parent_property);
5969 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
5972 if (Set != null && !Set.IsDummy && set_accessor == null) {
5973 Report.SymbolRelatedToPreviousError (parent_property);
5974 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
5979 // Check parent accessors access
5981 get_accessor_access = set_accessor_access = 0;
5982 if ((ModFlags & Modifiers.NEW) == 0) {
5983 if (get_accessor != null) {
5984 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
5985 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
5987 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
5988 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
5989 GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
5992 if (set_accessor != null) {
5993 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
5994 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
5996 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
5997 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
5998 GetSignatureForError (container), TypeManager.GetFullNameSignature (parent_property));
6003 // Get the less restrictive access
6005 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6008 public override void Emit ()
6011 // The PropertyBuilder can be null for explicit implementations, in that
6012 // case, we do not actually emit the ".property", so there is nowhere to
6013 // put the attribute
6015 if (PropertyBuilder != null && OptAttributes != null)
6016 OptAttributes.Emit (ec, this);
6028 /// Tests whether accessors are not in collision with some method (CS0111)
6030 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6032 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6035 protected override void UpdateMemberName ()
6037 base.UpdateMemberName ();
6039 Get.UpdateName (this);
6040 Set.UpdateName (this);
6044 public override string[] ValidAttributeTargets {
6046 return attribute_targets;
6051 // Represents header string for documentation comment.
6053 public override string DocCommentHeader {
6054 get { return "P:"; }
6058 public class Property : PropertyBase, IIteratorContainer {
6059 const int AllowedModifiers =
6062 Modifiers.PROTECTED |
6063 Modifiers.INTERNAL |
6067 Modifiers.OVERRIDE |
6068 Modifiers.ABSTRACT |
6071 Modifiers.METHOD_YIELDS |
6074 const int AllowedInterfaceModifiers =
6077 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6078 MemberName name, Attributes attrs, Accessor get_block,
6079 Accessor set_block, Location loc)
6080 : base (ds, type, mod,
6081 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6082 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6085 if (get_block == null)
6086 Get = new GetMethod (this);
6088 Get = new GetMethod (this, get_block);
6090 if (set_block == null)
6091 Set = new SetMethod (this);
6093 Set = new SetMethod (this, set_block);
6096 public override bool Define ()
6098 if (!base.Define ())
6104 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6108 GetBuilder = Get.Define (Parent);
6109 if (GetBuilder == null)
6113 // Setup iterator if we are one
6115 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6116 Iterator iterator = new Iterator (
6117 Parent, "get", MemberType,
6118 TypeManager.NoTypes, Get.ParameterInfo,
6119 ModFlags, Get.Block, Location);
6121 if (!iterator.DefineIterator ())
6123 Get.Block = iterator.Block;
6128 SetBuilder = Set.Define (Parent);
6129 if (SetBuilder == null)
6132 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6135 // FIXME - PropertyAttributes.HasDefault ?
6137 PropertyAttributes prop_attr = PropertyAttributes.None;
6139 prop_attr |= PropertyAttributes.RTSpecialName |
6140 PropertyAttributes.SpecialName;
6142 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6143 Name, prop_attr, MemberType, null);
6146 PropertyBuilder.SetGetMethod (GetBuilder);
6149 PropertyBuilder.SetSetMethod (SetBuilder);
6151 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6155 public void SetYields ()
6157 ModFlags |= Modifiers.METHOD_YIELDS;
6162 /// Gigantic workaround for lameness in SRE follows :
6163 /// This class derives from EventInfo and attempts to basically
6164 /// wrap around the EventBuilder so that FindMembers can quickly
6165 /// return this in it search for members
6167 public class MyEventBuilder : EventInfo {
6170 // We use this to "point" to our Builder which is
6171 // not really a MemberInfo
6173 EventBuilder MyBuilder;
6176 // We "catch" and wrap these methods
6178 MethodInfo raise, remove, add;
6180 EventAttributes attributes;
6181 Type declaring_type, reflected_type, event_type;
6186 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6188 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6190 // And now store the values in our own fields.
6192 declaring_type = type_builder;
6194 reflected_type = type_builder;
6196 attributes = event_attr;
6199 this.event_type = event_type;
6203 // Methods that you have to override. Note that you only need
6204 // to "implement" the variants that take the argument (those are
6205 // the "abstract" methods, the others (GetAddMethod()) are
6208 public override MethodInfo GetAddMethod (bool nonPublic)
6213 public override MethodInfo GetRemoveMethod (bool nonPublic)
6218 public override MethodInfo GetRaiseMethod (bool nonPublic)
6224 // These methods make "MyEventInfo" look like a Builder
6226 public void SetRaiseMethod (MethodBuilder raiseMethod)
6228 raise = raiseMethod;
6229 MyBuilder.SetRaiseMethod (raiseMethod);
6232 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6234 remove = removeMethod;
6235 MyBuilder.SetRemoveOnMethod (removeMethod);
6238 public void SetAddOnMethod (MethodBuilder addMethod)
6241 MyBuilder.SetAddOnMethod (addMethod);
6244 public void SetCustomAttribute (CustomAttributeBuilder cb)
6246 MyBuilder.SetCustomAttribute (cb);
6249 public override object [] GetCustomAttributes (bool inherit)
6251 // FIXME : There's nothing which can be seemingly done here because
6252 // we have no way of getting at the custom attribute objects of the
6257 public override object [] GetCustomAttributes (Type t, bool inherit)
6259 // FIXME : Same here !
6263 public override bool IsDefined (Type t, bool b)
6268 public override EventAttributes Attributes {
6274 public override string Name {
6280 public override Type DeclaringType {
6282 return declaring_type;
6286 public override Type ReflectedType {
6288 return reflected_type;
6292 public Type EventType {
6298 public void SetUsed ()
6300 if (my_event != null)
6301 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6306 /// For case when event is declared like property (with add and remove accessors).
6308 public class EventProperty: Event {
6310 static string[] attribute_targets = new string [] { "event", "property" };
6312 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6313 bool is_iface, MemberName name, Object init,
6314 Attributes attrs, Accessor add, Accessor remove,
6316 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6318 Add = new AddDelegateMethod (this, add);
6319 Remove = new RemoveDelegateMethod (this, remove);
6321 // For this event syntax we don't report error CS0067
6322 // because it is hard to do it.
6326 public override string[] ValidAttributeTargets {
6328 return attribute_targets;
6334 /// Event is declared like field.
6336 public class EventField: Event {
6338 static string[] attribute_targets = new string [] { "event", "field", "method" };
6339 static string[] attribute_targets_interface = new string[] { "event", "method" };
6341 public EventField (TypeContainer parent, Expression type, int mod_flags,
6342 bool is_iface, MemberName name, Object init,
6343 Attributes attrs, Location loc)
6344 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6346 Add = new AddDelegateMethod (this);
6347 Remove = new RemoveDelegateMethod (this);
6350 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6352 if (a.Target == AttributeTargets.Field) {
6353 FieldBuilder.SetCustomAttribute (cb);
6357 if (a.Target == AttributeTargets.Method) {
6358 Add.ApplyAttributeBuilder (a, cb);
6359 Remove.ApplyAttributeBuilder (a, cb);
6363 base.ApplyAttributeBuilder (a, cb);
6366 public override string[] ValidAttributeTargets {
6368 return IsInterface ? attribute_targets_interface : attribute_targets;
6373 public abstract class Event : FieldBase {
6375 protected sealed class AddDelegateMethod: DelegateMethod
6378 public AddDelegateMethod (Event method):
6379 base (method, "add_")
6383 public AddDelegateMethod (Event method, Accessor accessor):
6384 base (method, accessor, "add_")
6388 protected override MethodInfo DelegateMethodInfo {
6390 return TypeManager.delegate_combine_delegate_delegate;
6396 protected sealed class RemoveDelegateMethod: DelegateMethod
6398 public RemoveDelegateMethod (Event method):
6399 base (method, "remove_")
6403 public RemoveDelegateMethod (Event method, Accessor accessor):
6404 base (method, accessor, "remove_")
6408 protected override MethodInfo DelegateMethodInfo {
6410 return TypeManager.delegate_remove_delegate_delegate;
6416 public abstract class DelegateMethod: AbstractPropertyEventMethod
6418 protected readonly Event method;
6419 ImplicitParameter param_attr;
6421 static string[] attribute_targets = new string [] { "method", "param", "return" };
6423 public DelegateMethod (Event method, string prefix)
6424 : base (method, prefix)
6426 this.method = method;
6429 public DelegateMethod (Event method, Accessor accessor, string prefix)
6430 : base (method, accessor, prefix)
6432 this.method = method;
6435 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6437 if (a.Target == AttributeTargets.Parameter) {
6438 if (param_attr == null)
6439 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6441 param_attr.ApplyAttributeBuilder (a, cb);
6445 base.ApplyAttributeBuilder (a, cb);
6448 public override AttributeTargets AttributeTargets {
6450 return AttributeTargets.Method;
6454 public override bool IsClsCompliaceRequired(DeclSpace ds)
6456 return method.IsClsCompliaceRequired (ds);
6459 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6461 method_data = new MethodData (method, ip, method.ModFlags,
6462 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6464 if (!method_data.Define (container))
6467 MethodBuilder mb = method_data.MethodBuilder;
6468 mb.DefineParameter (1, ParameterAttributes.None, "value");
6473 public override void Emit (TypeContainer tc)
6475 if (block != null) {
6480 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6481 EmitContext ec = CreateEmitContext (tc, ig);
6482 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6484 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6485 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6486 ig.Emit (OpCodes.Ldsfld, field_info);
6487 ig.Emit (OpCodes.Ldarg_0);
6488 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6489 ig.Emit (OpCodes.Castclass, method.MemberType);
6490 ig.Emit (OpCodes.Stsfld, field_info);
6492 ig.Emit (OpCodes.Ldarg_0);
6493 ig.Emit (OpCodes.Ldarg_0);
6494 ig.Emit (OpCodes.Ldfld, field_info);
6495 ig.Emit (OpCodes.Ldarg_1);
6496 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6497 ig.Emit (OpCodes.Castclass, method.MemberType);
6498 ig.Emit (OpCodes.Stfld, field_info);
6500 ig.Emit (OpCodes.Ret);
6503 protected abstract MethodInfo DelegateMethodInfo { get; }
6505 public override Type[] ParameterTypes {
6507 return new Type[] { method.MemberType };
6511 public override Type ReturnType {
6513 return TypeManager.void_type;
6517 public override EmitContext CreateEmitContext (TypeContainer tc,
6520 return new EmitContext (
6521 tc, method.Parent, Location, ig, ReturnType,
6522 method.ModFlags, false);
6525 public override string GetSignatureForError (TypeContainer tc)
6527 return String.Concat (tc.Name, '.', method.Name);
6530 public override ObsoleteAttribute GetObsoleteAttribute ()
6532 return method.GetObsoleteAttribute (method.Parent);
6535 public override string[] ValidAttributeTargets {
6537 return attribute_targets;
6543 const int AllowedModifiers =
6546 Modifiers.PROTECTED |
6547 Modifiers.INTERNAL |
6552 Modifiers.OVERRIDE |
6556 const int AllowedInterfaceModifiers =
6559 public DelegateMethod Add, Remove;
6560 public MyEventBuilder EventBuilder;
6561 public MethodBuilder AddBuilder, RemoveBuilder;
6563 public Event (TypeContainer parent, Expression type, int mod_flags,
6564 bool is_iface, MemberName name, Object init, Attributes attrs,
6566 : base (parent, type, mod_flags,
6567 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6568 name, init, attrs, loc)
6570 IsInterface = is_iface;
6573 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6575 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6576 a.Error_InvalidSecurityParent ();
6580 EventBuilder.SetCustomAttribute (cb);
6583 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6585 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6588 public override AttributeTargets AttributeTargets {
6590 return AttributeTargets.Event;
6594 public override bool Define ()
6596 EventAttributes e_attr;
6597 e_attr = EventAttributes.None;
6602 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6603 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6604 "': abstract event can not have an initializer");
6608 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6609 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6610 "' : event must be of a delegate type");
6614 EmitContext ec = Parent.EmitContext;
6616 throw new InternalErrorException ("Event.Define called too early?");
6617 bool old_unsafe = ec.InUnsafe;
6618 ec.InUnsafe = InUnsafe;
6620 Parameter [] parms = new Parameter [1];
6621 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6622 Parameters parameters = new Parameters (parms, null, Location);
6623 Type [] types = parameters.GetParameterInfo (ec);
6624 InternalParameters ip = new InternalParameters (types, parameters);
6626 ec.InUnsafe = old_unsafe;
6632 // Now define the accessors
6635 AddBuilder = Add.Define (Parent, ip);
6636 if (AddBuilder == null)
6639 RemoveBuilder = Remove.Define (Parent, ip);
6640 if (RemoveBuilder == null)
6643 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6645 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6646 FieldBuilder = Parent.TypeBuilder.DefineField (
6648 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6649 TypeManager.RegisterPrivateFieldOfEvent (
6650 (EventInfo) EventBuilder, FieldBuilder);
6651 TypeManager.RegisterFieldBase (FieldBuilder, this);
6654 EventBuilder.SetAddOnMethod (AddBuilder);
6655 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6657 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6661 protected override bool CheckBase ()
6663 if (!base.CheckBase ())
6666 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6667 if (!(conflict_symbol is EventInfo)) {
6668 Report.SymbolRelatedToPreviousError (conflict_symbol);
6669 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6677 public override void Emit ()
6679 if (OptAttributes != null) {
6680 EmitContext ec = new EmitContext (
6681 Parent, Location, null, MemberType, ModFlags);
6682 OptAttributes.Emit (ec, this);
6687 Remove.Emit (Parent);
6693 public override string GetSignatureForError ()
6695 if (EventBuilder == null)
6696 return base.GetSignatureForError (Parent);
6698 return TypeManager.GetFullNameSignature (EventBuilder);
6702 // Represents header string for documentation comment.
6704 public override string DocCommentHeader {
6705 get { return "E:"; }
6710 public class Indexer : PropertyBase {
6712 class GetIndexerMethod: GetMethod
6714 public GetIndexerMethod (MethodCore method):
6719 public GetIndexerMethod (MethodCore method, Accessor accessor):
6720 base (method, accessor)
6724 public override Type[] ParameterTypes {
6726 return method.ParameterTypes;
6731 class SetIndexerMethod: SetMethod
6733 readonly Parameters parameters;
6735 public SetIndexerMethod (MethodCore method):
6740 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
6741 base (method, accessor)
6743 this.parameters = parameters;
6746 public override Type[] ParameterTypes {
6748 int top = method.ParameterTypes.Length;
6749 Type [] set_pars = new Type [top + 1];
6750 method.ParameterTypes.CopyTo (set_pars, 0);
6751 set_pars [top] = method.MemberType;
6756 protected override InternalParameters GetParameterInfo (EmitContext ec)
6758 Parameter [] fixed_parms = parameters.FixedParameters;
6760 if (fixed_parms == null){
6761 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
6762 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6763 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6765 // Here is the problem: the `value' parameter has
6766 // to come *after* the array parameter in the declaration
6768 // X (object [] x, Type value)
6771 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6772 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6776 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
6778 fixed_parms.CopyTo (tmp, 0);
6779 tmp [fixed_parms.Length] = new Parameter (
6780 method.Type, "value", Parameter.Modifier.NONE, null);
6782 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
6783 Type [] types = set_formal_params.GetParameterInfo (ec);
6785 return new InternalParameters (types, set_formal_params);
6790 const int AllowedModifiers =
6793 Modifiers.PROTECTED |
6794 Modifiers.INTERNAL |
6798 Modifiers.OVERRIDE |
6803 const int AllowedInterfaceModifiers =
6807 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
6808 bool is_iface, Parameters parameters, Attributes attrs,
6809 Accessor get_block, Accessor set_block, Location loc)
6810 : base (ds, type, mod,
6811 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6812 is_iface, name, parameters, attrs, loc)
6814 if (get_block == null)
6815 Get = new GetIndexerMethod (this);
6817 Get = new GetIndexerMethod (this, get_block);
6819 if (set_block == null)
6820 Set = new SetIndexerMethod (this);
6822 Set = new SetIndexerMethod (this, parameters, set_block);
6825 public override bool Define ()
6827 PropertyAttributes prop_attr =
6828 PropertyAttributes.RTSpecialName |
6829 PropertyAttributes.SpecialName;
6831 if (!base.Define ())
6834 if (MemberType == TypeManager.void_type) {
6835 Report.Error (620, Location, "Indexers cannot have void type");
6839 if (OptAttributes != null) {
6840 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
6841 if (indexer_attr != null) {
6842 // Remove the attribute from the list because it is not emitted
6843 OptAttributes.Attrs.Remove (indexer_attr);
6845 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
6847 if (IsExplicitImpl) {
6848 Report.Error (415, indexer_attr.Location,
6849 "The 'IndexerName' attribute is valid only on an" +
6850 "indexer that is not an explicit interface member declaration");
6854 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6855 Report.Error (609, indexer_attr.Location,
6856 "Cannot set the 'IndexerName' attribute on an indexer marked override");
6860 if (!Tokenizer.IsValidIdentifier (ShortName)) {
6861 Report.Error (633, indexer_attr.Location,
6862 "The argument to the 'IndexerName' attribute must be a valid identifier");
6866 UpdateMemberName ();
6870 if (InterfaceType != null) {
6871 string parent_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
6872 if (parent_IndexerName != Name)
6873 ShortName = parent_IndexerName;
6874 UpdateMemberName ();
6877 if (!Parent.AddToMemberContainer (this, true) ||
6878 !Parent.AddToMemberContainer (Get, true) || !Parent.AddToMemberContainer (Set, true))
6884 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6886 GetBuilder = Get.Define (Parent);
6887 if (GetBuilder == null)
6892 SetBuilder = Set.Define (Parent);
6893 if (SetBuilder == null)
6898 // Now name the parameters
6900 Parameter [] p = Parameters.FixedParameters;
6902 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
6903 Report.Error (631, Location, "ref and out are not valid in this context");
6909 for (i = 0; i < p.Length; ++i) {
6911 GetBuilder.DefineParameter (
6912 i + 1, p [i].Attributes, p [i].Name);
6915 SetBuilder.DefineParameter (
6916 i + 1, p [i].Attributes, p [i].Name);
6920 SetBuilder.DefineParameter (
6921 i + 1, ParameterAttributes.None, "value");
6923 if (i != ParameterTypes.Length) {
6924 Parameter array_param = Parameters.ArrayParameter;
6926 SetBuilder.DefineParameter (
6927 i + 1, array_param.Attributes, array_param.Name);
6931 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6932 Name, prop_attr, MemberType, ParameterTypes);
6935 PropertyBuilder.SetGetMethod (GetBuilder);
6938 PropertyBuilder.SetSetMethod (SetBuilder);
6940 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
6945 public override string GetSignatureForError ()
6947 if (PropertyBuilder == null)
6948 return GetSignatureForError (Parent);
6950 return TypeManager.CSharpSignature (PropertyBuilder, true);
6953 public override string GetSignatureForError(TypeContainer tc)
6955 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
6959 public class Operator : MethodCore, IIteratorContainer {
6961 const int AllowedModifiers =
6967 public enum OpType : byte {
6977 // Unary and Binary operators
7000 // Implicit and Explicit
7005 public readonly OpType OperatorType;
7006 public MethodBuilder OperatorMethodBuilder;
7008 public Method OperatorMethod;
7010 static string[] attribute_targets = new string [] { "method", "return" };
7012 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7013 int mod_flags, Parameters parameters,
7014 ToplevelBlock block, Attributes attrs, Location loc)
7015 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7016 new MemberName ("op_" + type), attrs, parameters, loc)
7018 OperatorType = type;
7022 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7024 OperatorMethod.ApplyAttributeBuilder (a, cb);
7027 public override AttributeTargets AttributeTargets {
7029 return AttributeTargets.Method;
7033 protected override bool CheckForDuplications()
7035 ArrayList ar = Parent.Operators;
7037 int arLen = ar.Count;
7039 for (int i = 0; i < arLen; i++) {
7040 Operator o = (Operator) ar [i];
7041 if (IsDuplicateImplementation (o))
7046 ar = Parent.Methods;
7048 int arLen = ar.Count;
7050 for (int i = 0; i < arLen; i++) {
7051 Method m = (Method) ar [i];
7052 if (IsDuplicateImplementation (m))
7060 public override bool Define ()
7063 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7064 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7065 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7072 if (MemberType == TypeManager.void_type) {
7073 Report.Error (590, Location, "User-defined operators cannot return void");
7077 OperatorMethod = new Method (
7078 Parent, Type, ModFlags, false, MemberName,
7079 Parameters, OptAttributes, Location);
7081 OperatorMethod.Block = Block;
7082 OperatorMethod.IsOperator = true;
7083 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7084 OperatorMethod.Define ();
7086 if (OperatorMethod.MethodBuilder == null)
7089 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7091 parameter_types = OperatorMethod.ParameterTypes;
7092 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7093 Type return_type = OperatorMethod.ReturnType;
7094 Type first_arg_type = parameter_types [0];
7099 // Rules for conversion operators
7101 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7102 if (first_arg_type == return_type && first_arg_type == declaring_type){
7105 "User-defined conversion cannot take an object of the " +
7106 "enclosing type and convert to an object of the enclosing" +
7111 if (first_arg_type != declaring_type && return_type != declaring_type){
7114 "User-defined conversion must convert to or from the " +
7119 if (first_arg_type == TypeManager.object_type ||
7120 return_type == TypeManager.object_type){
7123 "User-defined conversion cannot convert to or from " +
7128 if (first_arg_type.IsInterface || return_type.IsInterface){
7131 "User-defined conversion cannot convert to or from an " +
7136 if (first_arg_type.IsSubclassOf (return_type)
7137 || return_type.IsSubclassOf (first_arg_type)){
7138 if (declaring_type.IsSubclassOf (return_type)) {
7139 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7142 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7145 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7146 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7147 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");
7150 } else if (Parameters.FixedParameters.Length == 1) {
7151 // Checks for Unary operators
7153 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7154 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7155 Report.Error (448, Location,
7156 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7159 if (first_arg_type != declaring_type) {
7161 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7166 if (first_arg_type != declaring_type){
7169 "The parameter of a unary operator must be the " +
7174 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7175 if (return_type != TypeManager.bool_type){
7178 "The return type of operator True or False " +
7185 // Checks for Binary operators
7187 if (first_arg_type != declaring_type &&
7188 parameter_types [1] != declaring_type){
7191 "One of the parameters of a binary operator must " +
7192 "be the containing type");
7200 public override void Emit ()
7203 // abstract or extern methods have no bodies
7205 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7208 OperatorMethod.Emit ();
7212 // Operator cannot be override
7213 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
7218 public static string GetName (OpType ot)
7221 case OpType.LogicalNot:
7223 case OpType.OnesComplement:
7225 case OpType.Increment:
7227 case OpType.Decrement:
7233 case OpType.Addition:
7235 case OpType.Subtraction:
7237 case OpType.UnaryPlus:
7239 case OpType.UnaryNegation:
7241 case OpType.Multiply:
7243 case OpType.Division:
7245 case OpType.Modulus:
7247 case OpType.BitwiseAnd:
7249 case OpType.BitwiseOr:
7251 case OpType.ExclusiveOr:
7253 case OpType.LeftShift:
7255 case OpType.RightShift:
7257 case OpType.Equality:
7259 case OpType.Inequality:
7261 case OpType.GreaterThan:
7263 case OpType.LessThan:
7265 case OpType.GreaterThanOrEqual:
7267 case OpType.LessThanOrEqual:
7269 case OpType.Implicit:
7271 case OpType.Explicit:
7277 public override string GetSignatureForError (TypeContainer tc)
7279 StringBuilder sb = new StringBuilder ();
7280 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7281 Parameters.FixedParameters [0].GetSignatureForError ());
7283 if (Parameters.FixedParameters.Length > 1) {
7285 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7288 return sb.ToString ();
7291 public override string GetSignatureForError ()
7296 public override string ToString ()
7298 if (OperatorMethod == null)
7301 Type return_type = OperatorMethod.ReturnType;
7302 Type [] param_types = OperatorMethod.ParameterTypes;
7304 if (Parameters.FixedParameters.Length == 1)
7305 return String.Format (
7306 "{0} operator {1}({2})",
7307 TypeManager.CSharpName (return_type),
7308 GetName (OperatorType),
7311 return String.Format (
7312 "{0} operator {1}({2}, {3})",
7313 TypeManager.CSharpName (return_type),
7314 GetName (OperatorType),
7315 param_types [0], param_types [1]);
7318 public override string[] ValidAttributeTargets {
7320 return attribute_targets;
7324 public void SetYields ()
7326 ModFlags |= Modifiers.METHOD_YIELDS;
7331 // This is used to compare method signatures
7333 struct MethodSignature {
7335 public Type RetType;
7336 public Type [] Parameters;
7339 /// This delegate is used to extract methods which have the
7340 /// same signature as the argument
7342 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7344 public MethodSignature (string name, Type ret_type, Type [] parameters)
7349 if (parameters == null)
7350 Parameters = TypeManager.NoTypes;
7352 Parameters = parameters;
7355 public override string ToString ()
7358 if (Parameters.Length != 0){
7359 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7360 for (int i = 0; i < Parameters.Length; i++){
7361 sb.Append (Parameters [i]);
7362 if (i+1 < Parameters.Length)
7365 pars = sb.ToString ();
7368 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7371 public override int GetHashCode ()
7373 return Name.GetHashCode ();
7376 public override bool Equals (Object o)
7378 MethodSignature other = (MethodSignature) o;
7380 if (other.Name != Name)
7383 if (other.RetType != RetType)
7386 if (Parameters == null){
7387 if (other.Parameters == null)
7392 if (other.Parameters == null)
7395 int c = Parameters.Length;
7396 if (other.Parameters.Length != c)
7399 for (int i = 0; i < c; i++)
7400 if (other.Parameters [i] != Parameters [i])
7406 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7408 MethodSignature sig = (MethodSignature) filter_criteria;
7410 if (m.Name != sig.Name)
7414 MethodInfo mi = m as MethodInfo;
7415 PropertyInfo pi = m as PropertyInfo;
7418 ReturnType = mi.ReturnType;
7419 else if (pi != null)
7420 ReturnType = pi.PropertyType;
7425 // we use sig.RetType == null to mean `do not check the
7426 // method return value.
7428 if (sig.RetType != null)
7429 if (ReturnType != sig.RetType)
7434 args = TypeManager.GetArgumentTypes (mi);
7436 args = TypeManager.GetArgumentTypes (pi);
7437 Type [] sigp = sig.Parameters;
7439 if (args.Length != sigp.Length)
7442 for (int i = args.Length; i > 0; ){
7444 if (args [i] != sigp [i])