2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 namespace Mono.CSharp {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
79 public virtual void Emit ()
81 foreach (MemberCore mc in this)
86 public class MethodArrayList: MemberCoreArrayList
94 CachedMethods cached_method;
95 TypeContainer container;
97 public MethodArrayList (TypeContainer container)
99 this.container = container;
103 /// Method container contains Equals method
105 public bool HasEquals {
107 cached_method |= CachedMethods.Equals;
111 return (cached_method & CachedMethods.Equals) != 0;
116 /// Method container contains GetHashCode method
118 public bool HasGetHashCode {
120 cached_method |= CachedMethods.GetHashCode;
124 return (cached_method & CachedMethods.GetHashCode) != 0;
128 public override void DefineContainerMembers ()
130 base.DefineContainerMembers ();
132 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
133 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
139 public sealed class IndexerArrayList: MemberCoreArrayList
142 /// The indexer name for this container
144 public string IndexerName = DefaultIndexerName;
146 bool seen_normal_indexers = false;
148 TypeContainer container;
150 public IndexerArrayList (TypeContainer container)
152 this.container = container;
156 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
157 /// class is consistent. Either it is `Item' or it is the name defined by all the
158 /// indexers with the `IndexerName' attribute.
160 /// Turns out that the IndexerNameAttribute is applied to each indexer,
161 /// but it is never emitted, instead a DefaultMember attribute is attached
164 public override void DefineContainerMembers()
166 base.DefineContainerMembers ();
168 string class_indexer_name = null;
171 // If there's both an explicit and an implicit interface implementation, the
172 // explicit one actually implements the interface while the other one is just
173 // a normal indexer. See bug #37714.
176 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
177 foreach (Indexer i in this) {
178 if (i.InterfaceType != null) {
179 if (seen_normal_indexers)
180 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
184 seen_normal_indexers = true;
186 if (class_indexer_name == null) {
187 class_indexer_name = i.ShortName;
191 if (i.ShortName != class_indexer_name)
192 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
195 if (class_indexer_name != null)
196 IndexerName = class_indexer_name;
199 public override void Emit ()
203 if (!seen_normal_indexers)
206 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
207 container.TypeBuilder.SetCustomAttribute (cb);
211 public class OperatorArrayList: MemberCoreArrayList
213 TypeContainer container;
215 public OperatorArrayList (TypeContainer container)
217 this.container = container;
221 // Operator pair checking
226 public Type ret_type;
227 public Type type1, type2;
229 public Operator.OpType ot;
231 public OperatorEntry (int f, Operator o)
235 ret_type = o.OperatorMethod.ReturnType;
236 Type [] pt = o.OperatorMethod.ParameterTypes;
243 public override int GetHashCode ()
245 return ret_type.GetHashCode ();
248 public override bool Equals (object o)
250 OperatorEntry other = (OperatorEntry) o;
252 if (other.ret_type != ret_type)
254 if (other.type1 != type1)
256 if (other.type2 != type2)
263 // Checks that some operators come in pairs:
269 // They are matched based on the return type and the argument types
271 void CheckPairedOperators ()
273 Hashtable pairs = new Hashtable (null, null);
274 Operator true_op = null;
275 Operator false_op = null;
276 bool has_equality_or_inequality = false;
278 // Register all the operators we care about.
279 foreach (Operator op in this){
282 switch (op.OperatorType){
283 case Operator.OpType.Equality:
285 has_equality_or_inequality = true;
287 case Operator.OpType.Inequality:
289 has_equality_or_inequality = true;
292 case Operator.OpType.True:
295 case Operator.OpType.False:
299 case Operator.OpType.GreaterThan:
301 case Operator.OpType.LessThan:
304 case Operator.OpType.GreaterThanOrEqual:
306 case Operator.OpType.LessThanOrEqual:
312 OperatorEntry oe = new OperatorEntry (reg, op);
314 object o = pairs [oe];
318 oe = (OperatorEntry) o;
323 if (true_op != null){
324 if (false_op == null)
325 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
326 } else if (false_op != null)
327 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
330 // Look for the mistakes.
332 foreach (DictionaryEntry de in pairs){
333 OperatorEntry oe = (OperatorEntry) de.Key;
340 case Operator.OpType.Equality:
343 case Operator.OpType.Inequality:
346 case Operator.OpType.GreaterThan:
349 case Operator.OpType.LessThan:
352 case Operator.OpType.GreaterThanOrEqual:
355 case Operator.OpType.LessThanOrEqual:
359 Report.Error (216, oe.op.Location,
360 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
363 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
364 if (container.Methods == null || !container.Methods.HasEquals)
365 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
367 if (container.Methods == null || !container.Methods.HasGetHashCode)
368 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
372 public override void DefineContainerMembers ()
374 base.DefineContainerMembers ();
375 CheckPairedOperators ();
380 // Whether this is a struct, class or interface
381 public readonly Kind Kind;
383 // Holds a list of classes and structures
386 // Holds the list of properties
387 MemberCoreArrayList properties;
389 // Holds the list of enumerations
390 MemberCoreArrayList enums;
392 // Holds the list of delegates
393 MemberCoreArrayList delegates;
395 // Holds the list of constructors
396 protected MemberCoreArrayList instance_constructors;
398 // Holds the list of fields
399 MemberCoreArrayList fields;
401 // Holds a list of fields that have initializers
402 protected ArrayList initialized_fields;
404 // Holds a list of static fields that have initializers
405 protected ArrayList initialized_static_fields;
407 // Holds the list of constants
408 MemberCoreArrayList constants;
411 MemberCoreArrayList interfaces;
413 // Holds the methods.
414 MethodArrayList methods;
417 protected MemberCoreArrayList events;
419 // Holds the indexers
420 IndexerArrayList indexers;
422 // Holds the operators
423 MemberCoreArrayList operators;
425 // Holds the iterators
428 // Holds the parts of a partial class;
432 // Pointers to the default constructor and the default static constructor
434 protected Constructor default_constructor;
435 protected Constructor default_static_constructor;
438 // Whether we have at least one non-static field
440 bool have_nonstatic_fields = false;
443 // This one is computed after we can distinguish interfaces
444 // from classes from the arraylist `type_bases'
446 string base_class_name;
449 ArrayList type_bases;
451 bool members_defined;
452 bool members_defined_ok;
454 // The interfaces we implement.
455 protected Type [] ifaces;
456 protected Type ptype;
458 // The base member cache and our member cache
459 MemberCache base_cache;
460 MemberCache member_cache;
462 public const string DefaultIndexerName = "Item";
464 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
465 Attributes attrs, Kind kind, Location l)
466 : base (ns, parent, name, attrs, l)
470 types = new ArrayList ();
472 base_class_name = null;
475 public bool AddToMemberContainer (MemberCore symbol, 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 base_class, out bool error)
912 ArrayList ifaces = new ArrayList ();
915 Location base_loc = Location.Null;
917 foreach (ClassPart part in parts) {
918 TypeExpr new_base_class;
919 TypeExpr[] new_ifaces;
921 new_ifaces = part.GetClassBases (out new_base_class, out error);
925 if ((base_class != null) && (new_base_class != null) &&
926 !base_class.Equals (new_base_class)) {
927 Report.Error (263, part.Location,
928 "Partial declarations of `{0}' must " +
929 "not specify different base classes",
932 if (!Location.IsNull (base_loc))
933 Report.LocationOfPreviousError (base_loc);
939 if ((base_class == null) && (new_base_class != null)) {
940 base_class = new_base_class;
941 base_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 base_class, out bool error)
972 int count = Bases.Count;
975 if (Kind == Kind.Class){
976 TypeExpr name = ResolveBaseTypeExpr (
977 (Expression) Bases [0], false, Location);
994 TypeExpr [] ifaces = new TypeExpr [count-start];
996 for (i = start, j = 0; i < count; i++, j++){
997 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
998 if (resolved == null) {
1003 ifaces [j] = resolved;
1011 /// This function computes the Base class and also the
1012 /// list of interfaces that the class or struct @c implements.
1014 /// The return value is an array (might be null) of
1015 /// interfaces implemented (as Types).
1017 /// The @base_class argument is set to the base object or null
1018 /// if this is `System.Object'.
1020 TypeExpr [] GetClassBases (out TypeExpr base_class, out bool error)
1029 ifaces = GetPartialBases (out base_class, out error);
1030 else if (Bases == null){
1034 ifaces = GetNormalBases (out base_class, out error);
1039 if ((base_class != null) && (Kind == Kind.Class)){
1041 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1042 Report.Error (1521, base_class.Location, "Invalid base type");
1047 if (base_class.IsSealed){
1049 Report.SymbolRelatedToPreviousError (base_class.Type);
1050 if (base_class.Type.IsAbstract) {
1051 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1053 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1058 if (!base_class.CanInheritFrom ()){
1059 Report.Error (644, Location,
1060 "`{0}' cannot inherit from special class `{1}'",
1061 Name, base_class.Name);
1066 if (!base_class.AsAccessible (this, ModFlags)) {
1067 Report.SymbolRelatedToPreviousError (base_class.Type);
1068 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1069 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1073 if (base_class != null)
1074 base_class_name = base_class.Name;
1079 int count = ifaces != null ? ifaces.Length : 0;
1081 for (i = 0; i < count; i++) {
1082 TypeExpr iface = (TypeExpr) ifaces [i];
1084 if ((Kind != Kind.Class) && !iface.IsInterface){
1085 string what = Kind == Kind.Struct ?
1086 "Struct" : "Interface";
1088 Report.Error (527, Location,
1089 "In {0} `{1}', type `{2}' is not "+
1090 "an interface", what, Name, iface.Name);
1094 if (iface.IsClass) {
1095 if (base_class != null)
1096 Report.Error (1721, Location,
1097 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1100 Report.Error (1722, Location,
1101 "In Class `{0}', `{1}' is not " +
1102 "an interface, a base class must be listed first", Name, iface.Name);
1108 for (int x = 0; x < i; x++) {
1109 if (iface.Equals (ifaces [x])) {
1110 Report.Error (528, Location,
1111 "`{0}' is already listed in " +
1112 "interface list", iface.Name);
1118 if ((Kind == Kind.Interface) &&
1119 !iface.AsAccessible (Parent, ModFlags))
1120 Report.Error (61, Location,
1121 "Inconsistent accessibility: base " +
1122 "interface `{0}' is less accessible " +
1123 "than interface `{1}'", iface.Name,
1133 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1135 public override TypeBuilder DefineType ()
1137 if (TypeBuilder != null)
1144 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
1151 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1153 TypeExpr[] iface_exprs = GetClassBases (out base_type, out error);
1157 if (base_type == null) {
1158 if (Kind == Kind.Class){
1159 if (RootContext.StdLib)
1160 base_type = TypeManager.system_object_expr;
1161 else if (Name != "System.Object")
1162 base_type = TypeManager.system_object_expr;
1163 } else if (Kind == Kind.Struct) {
1165 // If we are compiling our runtime,
1166 // and we are defining ValueType, then our
1167 // base is `System.Object'.
1169 if (!RootContext.StdLib && Name == "System.ValueType")
1170 base_type = TypeManager.system_object_expr;
1172 base_type = TypeManager.system_valuetype_expr;
1176 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1177 throw new Exception ();
1179 TypeAttributes type_attributes = TypeAttr;
1181 if (base_type != null) {
1182 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1183 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1184 ptype = base_type.ResolveType (ec);
1185 if (ptype == null) {
1193 if (TypeManager.NamespaceClash (Name, Location)) {
1198 ModuleBuilder builder = CodeGen.Module.Builder;
1199 TypeBuilder = builder.DefineType (
1200 Name, type_attributes, ptype, null);
1203 TypeBuilder builder = Parent.DefineType ();
1204 if (builder == null)
1207 TypeBuilder = builder.DefineNestedType (
1208 Basename, type_attributes, ptype, null);
1211 catch (ArgumentException) {
1212 Report.RuntimeMissingSupport (Location, "static classes");
1217 // Structs with no fields need to have at least one byte.
1218 // The right thing would be to set the PackingSize in a DefineType
1219 // but there are no functions that allow interfaces *and* the size to
1223 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1224 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1225 FieldAttributes.Private);
1228 // add interfaces that were not added at type creation
1229 if (iface_exprs != null) {
1230 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1231 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1232 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1233 if (ifaces == null) {
1238 foreach (Type itype in ifaces)
1239 TypeBuilder.AddInterfaceImplementation (itype);
1241 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1245 // Finish the setup for the EmitContext
1247 ec.ContainerType = TypeBuilder;
1249 TypeManager.AddUserType (Name, TypeBuilder, this);
1251 if ((base_type != null) && base_type.IsAttribute) {
1252 RootContext.RegisterAttribute (this);
1253 } else if (!(this is Iterator))
1254 RootContext.RegisterOrder (this);
1256 if (!DefineNestedTypes ()) {
1265 protected virtual bool DefineNestedTypes ()
1267 if (Interfaces != null) {
1268 foreach (TypeContainer iface in Interfaces)
1269 if (iface.DefineType () == null)
1273 if (Types != null) {
1274 foreach (TypeContainer tc in Types)
1275 if (tc.DefineType () == null)
1279 if (Delegates != null) {
1280 foreach (Delegate d in Delegates)
1281 if (d.DefineType () == null)
1285 if (Enums != null) {
1286 foreach (Enum en in Enums)
1287 if (en.DefineType () == null)
1291 if (Parts != null) {
1292 foreach (ClassPart part in Parts) {
1293 part.TypeBuilder = TypeBuilder;
1295 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1302 static void Error_KeywordNotAllowed (Location loc)
1304 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1308 /// Populates our TypeBuilder with fields and methods
1310 public override bool DefineMembers (TypeContainer container)
1312 if (members_defined)
1313 return members_defined_ok;
1315 members_defined_ok = DoDefineMembers ();
1316 members_defined = true;
1318 return members_defined_ok;
1321 bool DoDefineMembers ()
1324 // We need to be able to use the member cache while we are checking/defining
1326 if (TypeBuilder.BaseType != null)
1327 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
1329 if (TypeBuilder.IsInterface)
1330 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
1333 if ((ModFlags & Modifiers.NEW) != 0)
1334 Error_KeywordNotAllowed (Location);
1336 // HACK: missing implemenation
1337 // This is not fully functional. Better way how to handle this is to have recursive definition of containers
1338 // instead of flat as we have now.
1339 // Now we are not able to check inner attribute class because its parent had not been defined.
1341 // TODO: remove this if
1342 if (Parent.MemberCache != null) {
1343 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1344 if (conflict_symbol == null) {
1345 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1346 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1348 if ((ModFlags & Modifiers.NEW) == 0) {
1349 Report.SymbolRelatedToPreviousError (conflict_symbol);
1350 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1356 DefineContainerMembers (constants);
1357 DefineContainerMembers (fields);
1359 if ((Kind == Kind.Class) && !(this is ClassPart) && !(this is StaticClass)){
1360 if ((instance_constructors == null) &&
1361 !(this is StaticClass)) {
1362 if (default_constructor == null)
1363 DefineDefaultConstructor (false);
1366 if (initialized_static_fields != null &&
1367 default_static_constructor == null)
1368 DefineDefaultConstructor (true);
1371 if (Kind == Kind.Struct){
1373 // Structs can not have initialized instance
1376 if (initialized_static_fields != null &&
1377 default_static_constructor == null)
1378 DefineDefaultConstructor (true);
1380 if (initialized_fields != null)
1381 ReportStructInitializedInstanceError ();
1384 Pending = GetPendingImplementations ();
1386 if (parts != null) {
1387 foreach (ClassPart part in parts) {
1388 if (!part.DefineMembers (this))
1394 // Constructors are not in the defined_names array
1396 DefineContainerMembers (instance_constructors);
1398 if (default_static_constructor != null)
1399 default_static_constructor.Define ();
1401 DefineContainerMembers (properties);
1402 DefineContainerMembers (events);
1403 DefineContainerMembers (indexers);
1404 DefineContainerMembers (methods);
1405 DefineContainerMembers (operators);
1406 DefineContainerMembers (enums);
1407 DefineContainerMembers (delegates);
1410 if (!(this is ClassPart))
1411 member_cache = new MemberCache (this);
1414 if (parts != null) {
1415 foreach (ClassPart part in parts)
1416 part.member_cache = member_cache;
1419 if (iterators != null) {
1420 foreach (Iterator iterator in iterators) {
1421 if (iterator.DefineType () == null)
1425 foreach (Iterator iterator in iterators) {
1426 if (!iterator.DefineMembers (this))
1434 void ReportStructInitializedInstanceError ()
1436 string n = TypeBuilder.FullName;
1438 foreach (Field f in initialized_fields){
1441 "`" + n + "." + f.Name + "': can not have " +
1442 "instance field initializers in structs");
1446 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1449 mcal.DefineContainerMembers ();
1452 public override bool Define ()
1454 if (parts != null) {
1455 foreach (ClassPart part in parts) {
1456 if (!part.Define ())
1464 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1466 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1470 /// This function is based by a delegate to the FindMembers routine
1472 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1478 /// This filter is used by FindMembers, and we just keep
1479 /// a global for the filter to `AlwaysAccept'
1481 static MemberFilter accepting_filter;
1484 static TypeContainer ()
1486 accepting_filter = new MemberFilter (AlwaysAccept);
1489 public MethodInfo[] GetMethods ()
1491 ArrayList members = new ArrayList ();
1493 DefineMembers (null);
1495 if (methods != null) {
1496 int len = methods.Count;
1497 for (int i = 0; i < len; i++) {
1498 Method m = (Method) methods [i];
1500 members.Add (m.MethodBuilder);
1504 if (operators != null) {
1505 int len = operators.Count;
1506 for (int i = 0; i < len; i++) {
1507 Operator o = (Operator) operators [i];
1509 members.Add (o.OperatorMethodBuilder);
1513 if (properties != null) {
1514 int len = properties.Count;
1515 for (int i = 0; i < len; i++) {
1516 Property p = (Property) properties [i];
1518 if (p.GetBuilder != null)
1519 members.Add (p.GetBuilder);
1520 if (p.SetBuilder != null)
1521 members.Add (p.SetBuilder);
1525 if (indexers != null) {
1526 int len = indexers.Count;
1527 for (int i = 0; i < len; i++) {
1528 Indexer ix = (Indexer) indexers [i];
1530 if (ix.GetBuilder != null)
1531 members.Add (ix.GetBuilder);
1532 if (ix.SetBuilder != null)
1533 members.Add (ix.SetBuilder);
1537 if (events != null) {
1538 int len = events.Count;
1539 for (int i = 0; i < len; i++) {
1540 Event e = (Event) events [i];
1542 if (e.AddBuilder != null)
1543 members.Add (e.AddBuilder);
1544 if (e.RemoveBuilder != null)
1545 members.Add (e.RemoveBuilder);
1549 MethodInfo[] retMethods = new MethodInfo [members.Count];
1550 members.CopyTo (retMethods, 0);
1554 // Indicated whether container has StructLayout attribute set Explicit
1555 public virtual bool HasExplicitLayout {
1562 /// This method returns the members of this type just like Type.FindMembers would
1563 /// Only, we need to use this for types which are _being_ defined because MS'
1564 /// implementation can't take care of that.
1567 // FIXME: return an empty static array instead of null, that cleans up
1568 // some code and is consistent with some coding conventions I just found
1572 // Notice that in various cases we check if our field is non-null,
1573 // something that would normally mean that there was a bug elsewhere.
1575 // The problem happens while we are defining p-invoke methods, as those
1576 // will trigger a FindMembers, but this happens before things are defined
1578 // Since the whole process is a no-op, it is fine to check for null here.
1580 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1581 MemberFilter filter, object criteria)
1583 ArrayList members = null;
1586 if ((bf & BindingFlags.Public) != 0)
1587 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1589 if ((bf & BindingFlags.NonPublic) != 0)
1590 modflags |= Modifiers.PRIVATE;
1592 int static_mask = 0, static_flags = 0;
1593 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1594 case BindingFlags.Static:
1595 static_mask = static_flags = Modifiers.STATIC;
1598 case BindingFlags.Instance:
1599 static_mask = Modifiers.STATIC;
1604 static_mask = static_flags = 0;
1608 Timer.StartTimer (TimerType.TcFindMembers);
1611 filter = accepting_filter;
1613 if ((mt & MemberTypes.Field) != 0) {
1614 if (fields != null) {
1615 int len = fields.Count;
1616 for (int i = 0; i < len; i++) {
1617 Field f = (Field) fields [i];
1619 if ((f.ModFlags & modflags) == 0)
1621 if ((f.ModFlags & static_mask) != static_flags)
1624 FieldBuilder fb = f.FieldBuilder;
1625 if (fb != null && filter (fb, criteria) == true) {
1626 if (members == null)
1627 members = new ArrayList ();
1634 if (constants != null) {
1635 int len = constants.Count;
1636 for (int i = 0; i < len; i++) {
1637 Const con = (Const) constants [i];
1639 if ((con.ModFlags & modflags) == 0)
1641 if ((con.ModFlags & static_mask) != static_flags)
1644 FieldBuilder fb = con.FieldBuilder;
1645 if (fb != null && filter (fb, criteria) == true) {
1646 if (members == null)
1647 members = new ArrayList ();
1655 if ((mt & MemberTypes.Method) != 0) {
1656 if (methods != null) {
1657 int len = methods.Count;
1658 for (int i = 0; i < len; i++) {
1659 Method m = (Method) methods [i];
1661 if ((m.ModFlags & modflags) == 0)
1663 if ((m.ModFlags & static_mask) != static_flags)
1666 MethodBuilder mb = m.MethodBuilder;
1668 if (mb != null && filter (mb, criteria) == true) {
1669 if (members == null)
1670 members = new ArrayList ();
1677 if (operators != null) {
1678 int len = operators.Count;
1679 for (int i = 0; i < len; i++) {
1680 Operator o = (Operator) operators [i];
1682 if ((o.ModFlags & modflags) == 0)
1684 if ((o.ModFlags & static_mask) != static_flags)
1687 MethodBuilder ob = o.OperatorMethodBuilder;
1688 if (ob != null && filter (ob, criteria) == true) {
1689 if (members == null)
1690 members = new ArrayList ();
1697 if (properties != null) {
1698 int len = properties.Count;
1699 for (int i = 0; i < len; i++) {
1700 Property p = (Property) properties [i];
1702 if ((p.ModFlags & modflags) == 0)
1704 if ((p.ModFlags & static_mask) != static_flags)
1710 if (b != null && filter (b, criteria) == true) {
1711 if (members == null)
1712 members = new ArrayList ();
1718 if (b != null && filter (b, criteria) == true) {
1719 if (members == null)
1720 members = new ArrayList ();
1727 if (indexers != null) {
1728 int len = indexers.Count;
1729 for (int i = 0; i < len; i++) {
1730 Indexer ix = (Indexer) indexers [i];
1732 if ((ix.ModFlags & modflags) == 0)
1734 if ((ix.ModFlags & static_mask) != static_flags)
1740 if (b != null && filter (b, criteria) == true) {
1741 if (members == null)
1742 members = new ArrayList ();
1748 if (b != null && filter (b, criteria) == true) {
1749 if (members == null)
1750 members = new ArrayList ();
1758 if ((mt & MemberTypes.Event) != 0) {
1759 if (events != null) {
1760 int len = events.Count;
1761 for (int i = 0; i < len; i++) {
1762 Event e = (Event) events [i];
1764 if ((e.ModFlags & modflags) == 0)
1766 if ((e.ModFlags & static_mask) != static_flags)
1769 MemberInfo eb = e.EventBuilder;
1770 if (eb != null && filter (eb, criteria) == true) {
1771 if (members == null)
1772 members = new ArrayList ();
1774 members.Add (e.EventBuilder);
1780 if ((mt & MemberTypes.Property) != 0){
1781 if (properties != null) {
1782 int len = properties.Count;
1783 for (int i = 0; i < len; i++) {
1784 Property p = (Property) properties [i];
1786 if ((p.ModFlags & modflags) == 0)
1788 if ((p.ModFlags & static_mask) != static_flags)
1791 MemberInfo pb = p.PropertyBuilder;
1792 if (pb != null && filter (pb, criteria) == true) {
1793 if (members == null)
1794 members = new ArrayList ();
1796 members.Add (p.PropertyBuilder);
1801 if (indexers != null) {
1802 int len = indexers.Count;
1803 for (int i = 0; i < len; i++) {
1804 Indexer ix = (Indexer) indexers [i];
1806 if ((ix.ModFlags & modflags) == 0)
1808 if ((ix.ModFlags & static_mask) != static_flags)
1811 MemberInfo ib = ix.PropertyBuilder;
1812 if (ib != null && filter (ib, criteria) == true) {
1813 if (members == null)
1814 members = new ArrayList ();
1816 members.Add (ix.PropertyBuilder);
1822 if ((mt & MemberTypes.NestedType) != 0) {
1823 if (types != null) {
1824 int len = types.Count;
1825 for (int i = 0; i < len; i++) {
1826 TypeContainer t = (TypeContainer) types [i];
1828 if ((t.ModFlags & modflags) == 0)
1831 TypeBuilder tb = t.TypeBuilder;
1832 if (tb != null && (filter (tb, criteria) == true)) {
1833 if (members == null)
1834 members = new ArrayList ();
1841 if (enums != null) {
1842 int len = enums.Count;
1843 for (int i = 0; i < len; i++) {
1844 Enum en = (Enum) enums [i];
1846 if ((en.ModFlags & modflags) == 0)
1849 TypeBuilder tb = en.TypeBuilder;
1850 if (tb != null && (filter (tb, criteria) == true)) {
1851 if (members == null)
1852 members = new ArrayList ();
1859 if (delegates != null) {
1860 int len = delegates.Count;
1861 for (int i = 0; i < len; i++) {
1862 Delegate d = (Delegate) delegates [i];
1864 if ((d.ModFlags & modflags) == 0)
1867 TypeBuilder tb = d.TypeBuilder;
1868 if (tb != null && (filter (tb, criteria) == true)) {
1869 if (members == null)
1870 members = new ArrayList ();
1877 if (interfaces != null) {
1878 int len = interfaces.Count;
1879 for (int i = 0; i < len; i++) {
1880 TypeContainer iface = (TypeContainer) interfaces [i];
1882 if ((iface.ModFlags & modflags) == 0)
1885 TypeBuilder tb = iface.TypeBuilder;
1886 if (tb != null && (filter (tb, criteria) == true)) {
1887 if (members == null)
1888 members = new ArrayList ();
1896 if ((mt & MemberTypes.Constructor) != 0){
1897 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1898 int len = instance_constructors.Count;
1899 for (int i = 0; i < len; i++) {
1900 Constructor c = (Constructor) instance_constructors [i];
1902 ConstructorBuilder cb = c.ConstructorBuilder;
1903 if (cb != null && filter (cb, criteria) == true) {
1904 if (members == null)
1905 members = new ArrayList ();
1912 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1913 ConstructorBuilder cb =
1914 default_static_constructor.ConstructorBuilder;
1916 if (cb != null && filter (cb, criteria) == true) {
1917 if (members == null)
1918 members = new ArrayList ();
1926 // Lookup members in base if requested.
1928 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1929 if (TypeBuilder.BaseType != null) {
1930 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1931 if (list.Count > 0) {
1932 if (members == null)
1933 members = new ArrayList ();
1935 members.AddRange (list);
1938 if (ifaces != null) {
1939 foreach (Type base_type in ifaces) {
1940 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1942 if (list.Count > 0) {
1943 if (members == null)
1944 members = new ArrayList ();
1945 members.AddRange (list);
1951 Timer.StopTimer (TimerType.TcFindMembers);
1953 if (members == null)
1954 return MemberList.Empty;
1956 return new MemberList (members);
1959 public override MemberCache MemberCache {
1961 return member_cache;
1965 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1966 MemberFilter filter, object criteria)
1968 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1971 return ds.FindMembers (mt, bf, filter, criteria);
1973 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1978 // FindMethods will look for methods not only in the type `t', but in
1979 // any interfaces implemented by the type.
1981 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1982 MemberFilter filter, object criteria)
1988 /// Emits the values for the constants
1990 public void EmitConstants ()
1992 if (constants != null)
1993 foreach (Const con in constants)
1998 protected virtual void VerifyMembers (EmitContext ec)
2001 // Check for internal or private fields that were never assigned
2003 if (RootContext.WarningLevel >= 4) {
2004 if (fields != null){
2005 foreach (Field f in fields) {
2006 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2009 if ((f.status & Field.Status.USED) == 0){
2010 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2015 // Only report 649 on level 4
2017 if (RootContext.WarningLevel < 4)
2020 if ((f.status & Field.Status.ASSIGNED) != 0)
2023 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2030 /// Emits the code, this step is performed after all
2031 /// the types, enumerations, constructors
2033 public void EmitType ()
2035 if (OptAttributes != null)
2036 OptAttributes.Emit (ec, this);
2040 if (instance_constructors != null) {
2041 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2042 bool has_compliant_args = false;
2044 foreach (Constructor c in instance_constructors) {
2047 if (has_compliant_args)
2050 has_compliant_args = c.HasCompliantArgs;
2052 if (!has_compliant_args)
2053 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2055 foreach (Constructor c in instance_constructors)
2062 if (default_static_constructor != null)
2063 default_static_constructor.Emit ();
2065 if (methods != null)
2066 foreach (Method m in methods)
2069 if (operators != null)
2070 foreach (Operator o in operators)
2073 if (properties != null)
2074 foreach (Property p in properties)
2077 if (indexers != null){
2082 foreach (Field f in fields)
2085 if (events != null){
2086 foreach (Event e in Events)
2090 if (delegates != null) {
2091 foreach (Delegate d in Delegates) {
2096 if (enums != null) {
2097 foreach (Enum e in enums) {
2102 if (parts != null) {
2103 foreach (ClassPart part in parts)
2107 if ((Pending != null) && !(this is ClassPart))
2108 if (Pending.VerifyPendingMethods ())
2113 if (iterators != null)
2114 foreach (Iterator iterator in iterators)
2115 iterator.EmitType ();
2117 // if (types != null)
2118 // foreach (TypeContainer tc in types)
2122 public override void CloseType ()
2124 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2128 caching_flags |= Flags.CloseTypeCreated;
2129 TypeBuilder.CreateType ();
2130 } catch (TypeLoadException){
2132 // This is fine, the code still created the type
2134 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2135 // Console.WriteLine (e.Message);
2137 Console.WriteLine ("In type: " + Name);
2142 foreach (Enum en in Enums)
2146 foreach (TypeContainer tc in Types)
2147 if (tc.Kind == Kind.Struct)
2150 foreach (TypeContainer tc in Types)
2151 if (tc.Kind != Kind.Struct)
2155 if (Delegates != null)
2156 foreach (Delegate d in Delegates)
2159 if (Iterators != null)
2160 foreach (Iterator i in Iterators)
2168 initialized_fields = null;
2169 initialized_static_fields = null;
2178 default_constructor = null;
2179 default_static_constructor = null;
2181 OptAttributes = null;
2184 member_cache = null;
2187 // TODO: make it obsolete and use GetSignatureForError
2188 public string MakeName (string n)
2190 return "`" + Name + "." + n + "'";
2194 // Performs the validation on a Method's modifiers (properties have
2195 // the same properties).
2197 public bool MethodModifiersValid (MemberCore mc)
2199 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2200 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2201 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2203 int flags = mc.ModFlags;
2206 // At most one of static, virtual or override
2208 if ((flags & Modifiers.STATIC) != 0){
2209 if ((flags & vao) != 0){
2210 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2211 GetSignatureForError ());
2216 if (Kind == Kind.Struct){
2217 if ((flags & va) != 0){
2218 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2223 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2224 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2229 // If the declaration includes the abstract modifier, then the
2230 // declaration does not include static, virtual or extern
2232 if ((flags & Modifiers.ABSTRACT) != 0){
2233 if ((flags & Modifiers.EXTERN) != 0){
2235 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2239 if ((flags & Modifiers.SEALED) != 0) {
2240 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2244 if ((flags & Modifiers.VIRTUAL) != 0){
2245 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2249 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2250 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2255 if ((flags & Modifiers.PRIVATE) != 0){
2256 if ((flags & vao) != 0){
2257 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2262 if ((flags & Modifiers.SEALED) != 0){
2263 if ((flags & Modifiers.OVERRIDE) == 0){
2264 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2272 public bool UserDefinedStaticConstructor {
2274 return default_static_constructor != null;
2278 public Constructor DefaultStaticConstructor {
2279 get { return default_static_constructor; }
2282 protected override bool VerifyClsCompliance (DeclSpace ds)
2284 if (!base.VerifyClsCompliance (ds))
2289 Type base_type = TypeBuilder.BaseType;
2290 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2291 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2294 if (!Parent.IsClsCompliaceRequired (ds)) {
2295 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2296 GetSignatureForError (), Parent.GetSignatureForError ());
2303 /// Checks whether container name is CLS Compliant
2305 void VerifyClsName ()
2307 Hashtable base_members = base_cache == null ?
2309 base_cache.GetPublicMembers ();
2310 Hashtable this_members = new Hashtable ();
2312 foreach (DictionaryEntry entry in defined_names) {
2313 MemberCore mc = (MemberCore)entry.Value;
2314 if (!mc.IsClsCompliaceRequired (this))
2317 string name = (string)entry.Key;
2318 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2320 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2321 object found = base_members [lcase];
2322 if (found == null) {
2323 found = this_members [lcase];
2324 if (found == null) {
2325 this_members.Add (lcase, mc);
2330 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2333 if (found is MemberInfo) {
2334 if (basename == ((MemberInfo)found).Name)
2336 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2338 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2340 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2346 /// Performs checks for an explicit interface implementation. First it
2347 /// checks whether the `interface_type' is a base inteface implementation.
2348 /// Then it checks whether `name' exists in the interface type.
2350 public virtual bool VerifyImplements (Type interface_type, string full,
2351 string name, Location loc)
2355 if (ifaces != null){
2356 foreach (Type t in ifaces){
2357 if (t == interface_type){
2365 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2366 full, interface_type.FullName);
2373 protected override void VerifyObsoleteAttribute()
2375 CheckUsageOfObsoleteAttribute (ptype);
2380 foreach (Type iface in ifaces) {
2381 CheckUsageOfObsoleteAttribute (iface);
2390 string IMemberContainer.Name {
2396 Type IMemberContainer.Type {
2402 MemberCache IMemberContainer.MemberCache {
2404 return member_cache;
2408 bool IMemberContainer.IsInterface {
2410 return Kind == Kind.Interface;
2414 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2416 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2420 // Generates xml doc comments (if any), and if required,
2421 // handle warning report.
2423 internal override void GenerateDocComment (DeclSpace ds)
2425 DocUtil.GenerateTypeDocComment (this, ds);
2428 public override string DocCommentHeader {
2429 get { return "T:"; }
2432 public virtual MemberCache BaseCache {
2439 public class PartialContainer : TypeContainer {
2441 public readonly Namespace Namespace;
2442 public readonly int OriginalModFlags;
2443 public readonly int AllowedModifiers;
2444 public readonly TypeAttributes DefaultTypeAttributes;
2446 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2447 MemberName member_name, int mod_flags, Kind kind,
2450 PartialContainer pc;
2451 string full_name = member_name.GetName (true);
2452 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2454 pc = ds as PartialContainer;
2458 260, ds.Location, "Missing partial modifier " +
2459 "on declaration of type `{0}'; another " +
2460 "partial implementation of this type exists",
2461 member_name.GetPartialName());
2463 Report.LocationOfPreviousError (loc);
2467 if (pc.Kind != kind) {
2469 261, loc, "Partial declarations of `{0}' " +
2470 "must be all classes, all structs or " +
2471 "all interfaces", member_name.GetPartialName ());
2475 if (pc.OriginalModFlags != mod_flags) {
2477 262, loc, "Partial declarations of `{0}' " +
2478 "have conflicting accessibility modifiers",
2479 member_name.GetPartialName ());
2486 pc = new PartialContainer (ns, parent, member_name, mod_flags, kind, loc);
2487 RootContext.Tree.RecordDecl (full_name, pc);
2488 parent.AddType (pc);
2493 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2494 MemberName name, int mod, Attributes attrs,
2495 Kind kind, Location loc)
2497 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2499 // An error occured; create a dummy container, but don't
2501 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2504 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2509 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2510 MemberName name, int mod, Kind kind, Location l)
2511 : base (ns, parent, name, null, kind, l)
2513 this.Namespace = ns.NS;
2517 AllowedModifiers = Class.AllowedModifiers;
2518 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2522 AllowedModifiers = Struct.AllowedModifiers;
2523 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2526 case Kind.Interface:
2527 AllowedModifiers = Interface.AllowedModifiers;
2528 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2532 throw new InvalidOperationException ();
2536 if (parent.Parent == null)
2537 accmods = Modifiers.INTERNAL;
2539 accmods = Modifiers.PRIVATE;
2541 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2542 this.OriginalModFlags = mod;
2545 public override void Register ()
2547 if (Kind == Kind.Interface)
2548 Parent.AddInterface (this);
2549 else if (Kind == Kind.Class || Kind == Kind.Struct)
2550 Parent.AddClassOrStruct (this);
2552 throw new InvalidOperationException ();
2555 public override PendingImplementation GetPendingImplementations ()
2557 return PendingImplementation.GetPendingImplementations (this);
2560 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2563 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2568 public override TypeAttributes TypeAttr {
2570 return base.TypeAttr | DefaultTypeAttributes;
2575 public class ClassPart : TypeContainer, IMemberContainer {
2576 public readonly PartialContainer PartialContainer;
2577 public readonly bool IsPartial;
2579 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2580 int mod, Attributes attrs, Kind kind, Location l)
2581 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2583 this.PartialContainer = parent;
2584 this.IsPartial = true;
2587 if (parent.Parent == null)
2588 accmods = Modifiers.INTERNAL;
2590 accmods = Modifiers.PRIVATE;
2592 this.ModFlags = Modifiers.Check (
2593 parent.AllowedModifiers, mod, accmods, l);
2596 public override void Register ()
2600 public override PendingImplementation GetPendingImplementations ()
2602 return PartialContainer.Pending;
2605 public override bool VerifyImplements (Type interface_type, string full,
2606 string name, Location loc)
2608 return PartialContainer.VerifyImplements (
2609 interface_type, full, name, loc);
2612 public override MemberCache BaseCache {
2614 return PartialContainer.BaseCache;
2619 public abstract class ClassOrStruct : TypeContainer {
2620 bool hasExplicitLayout = false;
2621 ListDictionary declarative_security;
2623 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2624 MemberName name, Attributes attrs, Kind kind,
2626 : base (ns, parent, name, attrs, kind, l)
2630 public override PendingImplementation GetPendingImplementations ()
2632 return PendingImplementation.GetPendingImplementations (this);
2635 public override bool HasExplicitLayout {
2637 return hasExplicitLayout;
2641 protected override void VerifyMembers (EmitContext ec)
2643 base.VerifyMembers (ec);
2645 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2646 foreach (Event e in events){
2648 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2653 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2655 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2656 if (declarative_security == null)
2657 declarative_security = new ListDictionary ();
2659 a.ExtractSecurityPermissionSet (declarative_security);
2663 if (a.Type == TypeManager.struct_layout_attribute_type
2664 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2665 hasExplicitLayout = true;
2667 base.ApplyAttributeBuilder (a, cb);
2670 public override void Emit()
2674 if (declarative_security != null) {
2675 foreach (DictionaryEntry de in declarative_security) {
2676 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2681 public override void Register ()
2683 Parent.AddClassOrStruct (this);
2688 /// Class handles static classes declaration
2690 public sealed class StaticClass: Class {
2691 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2692 Attributes attrs, Location l)
2693 : base (ns, parent, name, mod, attrs, l)
2695 if (RootContext.Version == LanguageVersion.ISO_1) {
2696 Report.FeatureIsNotStandardized (l, "static classes");
2697 Environment.Exit (1);
2701 protected override int AllowedModifiersProp {
2703 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2704 Modifiers.STATIC | Modifiers.UNSAFE;
2708 protected override void DefineContainerMembers (MemberCoreArrayList list)
2713 foreach (MemberCore m in list) {
2714 if (m is Operator) {
2715 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2719 if ((m.ModFlags & Modifiers.STATIC) != 0)
2722 if (m is Constructor) {
2723 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2727 if (m is Destructor) {
2728 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2732 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2735 base.DefineContainerMembers (list);
2738 public override TypeBuilder DefineType()
2740 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2741 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2745 TypeBuilder tb = base.DefineType ();
2749 if (ptype != TypeManager.object_type) {
2750 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2754 if (ifaces != null) {
2755 foreach (Type t in ifaces)
2756 Report.SymbolRelatedToPreviousError (t);
2757 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2762 public override TypeAttributes TypeAttr {
2764 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2769 public class Class : ClassOrStruct {
2770 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2771 public const int AllowedModifiers =
2774 Modifiers.PROTECTED |
2775 Modifiers.INTERNAL |
2777 Modifiers.ABSTRACT |
2781 // Information in the case we are an attribute type
2782 AttributeUsageAttribute attribute_usage;
2784 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2785 Attributes attrs, Location l)
2786 : base (ns, parent, name, attrs, Kind.Class, l)
2788 this.ModFlags = mod;
2789 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2792 virtual protected int AllowedModifiersProp {
2794 return AllowedModifiers;
2798 public override AttributeTargets AttributeTargets {
2800 return AttributeTargets.Class;
2804 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2806 if (a.UsageAttribute != null) {
2807 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2808 TypeBuilder.FullName != "System.Attribute") {
2809 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2811 attribute_usage = a.UsageAttribute;
2814 base.ApplyAttributeBuilder (a, cb);
2817 public AttributeUsageAttribute AttributeUsage {
2819 return attribute_usage;
2823 public const TypeAttributes DefaultTypeAttributes =
2824 TypeAttributes.AutoLayout | TypeAttributes.Class;
2826 public override TypeBuilder DefineType()
2828 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2829 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2833 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2834 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2836 return base.DefineType ();
2840 // FIXME: How do we deal with the user specifying a different
2843 public override TypeAttributes TypeAttr {
2845 return base.TypeAttr | DefaultTypeAttributes;
2850 public class Struct : ClassOrStruct {
2852 // Modifiers allowed in a struct declaration
2854 public const int AllowedModifiers =
2857 Modifiers.PROTECTED |
2858 Modifiers.INTERNAL |
2862 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2863 int mod, Attributes attrs, Location l)
2864 : base (ns, parent, name, attrs, Kind.Struct, l)
2868 if (parent.Parent == null)
2869 accmods = Modifiers.INTERNAL;
2871 accmods = Modifiers.PRIVATE;
2873 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2875 this.ModFlags |= Modifiers.SEALED;
2878 public override AttributeTargets AttributeTargets {
2880 return AttributeTargets.Struct;
2884 public const TypeAttributes DefaultTypeAttributes =
2885 TypeAttributes.SequentialLayout |
2886 TypeAttributes.Sealed |
2887 TypeAttributes.BeforeFieldInit;
2890 // FIXME: Allow the user to specify a different set of attributes
2891 // in some cases (Sealed for example is mandatory for a class,
2892 // but what SequentialLayout can be changed
2894 public override TypeAttributes TypeAttr {
2896 return base.TypeAttr | DefaultTypeAttributes;
2904 public class Interface : TypeContainer, IMemberContainer {
2906 /// Modifiers allowed in a class declaration
2908 public const int AllowedModifiers =
2911 Modifiers.PROTECTED |
2912 Modifiers.INTERNAL |
2916 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2917 Attributes attrs, Location l)
2918 : base (ns, parent, name, attrs, Kind.Interface, l)
2922 if (parent.Parent == null)
2923 accmods = Modifiers.INTERNAL;
2925 accmods = Modifiers.PRIVATE;
2927 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2930 public override void Register ()
2932 Parent.AddInterface (this);
2935 public override PendingImplementation GetPendingImplementations ()
2940 public override AttributeTargets AttributeTargets {
2942 return AttributeTargets.Interface;
2946 public const TypeAttributes DefaultTypeAttributes =
2947 TypeAttributes.AutoLayout |
2948 TypeAttributes.Abstract |
2949 TypeAttributes.Interface;
2951 public override TypeAttributes TypeAttr {
2953 return base.TypeAttr | DefaultTypeAttributes;
2958 public abstract class MethodCore : MemberBase {
2959 public readonly Parameters Parameters;
2960 protected ToplevelBlock block;
2963 // Parameters, cached for semantic analysis.
2965 protected InternalParameters parameter_info;
2966 protected Type [] parameter_types;
2968 // Whether this is an operator method.
2969 public bool IsOperator;
2972 // The method we're overriding if this is an override method.
2974 protected MethodInfo base_method = null;
2976 static string[] attribute_targets = new string [] { "method", "return" };
2978 public MethodCore (TypeContainer parent, Expression type, int mod,
2979 int allowed_mod, bool is_interface, MemberName name,
2980 Attributes attrs, Parameters parameters, Location loc)
2981 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
2984 Parameters = parameters;
2985 IsInterface = is_interface;
2989 // Returns the System.Type array for the parameters of this method
2991 public Type [] ParameterTypes {
2993 return parameter_types;
2997 public InternalParameters ParameterInfo
3000 return parameter_info;
3004 public ToplevelBlock Block {
3014 protected override bool CheckBase ()
3016 if (!base.CheckBase ())
3019 // Check whether arguments were correct.
3020 if (!DoDefineParameters ())
3023 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3029 // Is null for System.Object while compiling corlib and base interfaces
3030 if (Parent.BaseCache == null) {
3031 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3032 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3037 Type base_ret_type = null;
3038 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3040 // method is override
3041 if (base_method != null) {
3043 if (!CheckMethodAgainstBase ())
3046 if ((ModFlags & Modifiers.NEW) == 0) {
3047 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3048 Report.SymbolRelatedToPreviousError (base_method);
3049 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3050 "change return type when overriding inherited member");
3054 if (base_method.IsAbstract && !IsInterface) {
3055 Report.SymbolRelatedToPreviousError (base_method);
3056 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3061 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3062 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3066 if (RootContext.WarningLevel > 2) {
3067 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3068 Parent.Methods.HasEquals = true;
3069 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3070 Parent.Methods.HasGetHashCode = true;
3073 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3075 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3076 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3077 Report.SymbolRelatedToPreviousError (base_method);
3078 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3084 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3085 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3086 if (conflict_symbol != null) {
3087 Report.SymbolRelatedToPreviousError (conflict_symbol);
3088 if (this is PropertyBase)
3089 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3091 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3093 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3097 if (conflict_symbol == null) {
3098 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3099 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3104 if ((ModFlags & Modifiers.NEW) == 0) {
3105 if (this is Method && conflict_symbol is MethodBase)
3108 Report.SymbolRelatedToPreviousError (conflict_symbol);
3109 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3117 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3118 // that have been defined.
3120 // `name' is the user visible name for reporting errors (this is used to
3121 // provide the right name regarding method names and properties)
3123 bool CheckMethodAgainstBase ()
3127 // TODO: replace with GetSignatureForError
3128 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3130 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3131 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3133 506, Location, Parent.MakeName (Name) +
3134 ": cannot override inherited member `" +
3135 name + "' because it is not " +
3136 "virtual, abstract or override");
3140 // Now we check that the overriden method is not final
3142 if (base_method.IsFinal) {
3143 // This happens when implementing interface methods.
3144 if (base_method.IsHideBySig && base_method.IsVirtual) {
3146 506, Location, Parent.MakeName (Name) +
3147 ": cannot override inherited member `" +
3148 name + "' because it is not " +
3149 "virtual, abstract or override");
3151 Report.Error (239, Location, Parent.MakeName (Name) + " : cannot " +
3152 "override inherited member `" + name +
3153 "' because it is sealed.");
3157 // Check that the permissions are not being changed
3159 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3160 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3162 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3163 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3168 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3169 ModFlags |= Modifiers.NEW;
3170 Report.SymbolRelatedToPreviousError (base_method);
3171 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3172 if (RootContext.WarningLevel >= 2)
3173 Report.Warning (114, Location, "'{0}' hides inherited member '{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword", GetSignatureForError (Parent), TypeManager.CSharpSignature (base_method));
3175 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3181 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3183 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3185 // when overriding protected internal, the method can be declared
3186 // protected internal only within the same assembly
3189 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3190 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3192 // assemblies differ - report an error
3196 } else if (thisp != base_classp) {
3198 // same assembly, but other attributes differ - report an error
3203 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3205 // if it's not "protected internal", it must be "protected"
3209 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3211 // protected within the same assembly - an error
3214 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3215 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3217 // protected ok, but other attributes differ - report an error
3223 return (thisp == base_classp);
3227 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3230 // FIXME: report the old/new permissions?
3233 507, Location, parent.MakeName (Name) +
3234 ": can't change the access modifiers when overriding inherited " +
3235 "member `" + name + "'");
3238 protected static string Error722 {
3240 return "'{0}': static types cannot be used as return types";
3245 /// For custom member duplication search in a container
3247 protected abstract bool CheckForDuplications ();
3250 /// Gets base method and its return type
3252 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3254 protected virtual bool DoDefineParameters ()
3256 EmitContext ec = Parent.EmitContext;
3258 throw new InternalErrorException ("DoDefineParameters invoked too early");
3260 bool old_unsafe = ec.InUnsafe;
3261 ec.InUnsafe = InUnsafe;
3262 // Check if arguments were correct
3263 parameter_types = Parameters.GetParameterInfo (ec);
3264 ec.InUnsafe = old_unsafe;
3266 if ((parameter_types == null) ||
3267 !CheckParameters (Parent, parameter_types))
3270 parameter_info = new InternalParameters (parameter_types, Parameters);
3272 Parameter array_param = Parameters.ArrayParameter;
3273 if ((array_param != null) &&
3274 (!array_param.ParameterType.IsArray ||
3275 (array_param.ParameterType.GetArrayRank () != 1))) {
3276 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3283 public override string[] ValidAttributeTargets {
3285 return attribute_targets;
3289 protected override bool VerifyClsCompliance (DeclSpace ds)
3291 if (!base.VerifyClsCompliance (ds)) {
3292 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3293 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3298 if (Parameters.HasArglist) {
3299 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3302 if (!AttributeTester.IsClsCompliant (MemberType)) {
3303 if (this is PropertyBase)
3304 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3305 GetSignatureForError ());
3307 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3308 GetSignatureForError ());
3311 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3316 protected bool IsDuplicateImplementation (MethodCore method)
3318 if ((method == this) || (method.Name != Name))
3321 Type[] param_types = method.ParameterTypes;
3322 if (param_types == null)
3325 if (param_types.Length != ParameterTypes.Length)
3328 for (int i = 0; i < param_types.Length; i++)
3329 if (param_types [i] != ParameterTypes [i])
3332 // TODO: make operator compatible with MethodCore to avoid this
3333 if (this is Operator && method is Operator) {
3334 if (MemberType != method.MemberType)
3339 // Try to report 663: method only differs on out/ref
3341 ParameterData info = ParameterInfo;
3342 ParameterData other_info = method.ParameterInfo;
3343 for (int i = 0; i < info.Count; i++){
3344 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3345 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3350 Report.SymbolRelatedToPreviousError (method);
3351 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3356 // Returns a string that represents the signature for this
3357 // member which should be used in XML documentation.
3359 public override string GetDocCommentName (DeclSpace ds)
3361 return DocUtil.GetMethodDocCommentName (this, ds);
3365 // Raised (and passed an XmlElement that contains the comment)
3366 // when GenerateDocComment is writing documentation expectedly.
3368 // FIXME: with a few effort, it could be done with XmlReader,
3369 // that means removal of DOM use.
3371 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3373 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3377 // Represents header string for documentation comment.
3379 public override string DocCommentHeader {
3380 get { return "M:"; }
3383 protected override void VerifyObsoleteAttribute()
3385 base.VerifyObsoleteAttribute ();
3387 if (parameter_types == null)
3390 foreach (Type type in parameter_types) {
3391 CheckUsageOfObsoleteAttribute (type);
3396 public class SourceMethod : ISourceMethod
3398 TypeContainer container;
3401 protected SourceMethod (TypeContainer container, MethodBase builder,
3402 ISourceFile file, Location start, Location end)
3404 this.container = container;
3405 this.builder = builder;
3407 CodeGen.SymbolWriter.OpenMethod (
3408 file, this, start.Row, 0, end.Row, 0);
3411 public string Name {
3412 get { return builder.Name; }
3415 public int NamespaceID {
3416 get { return container.NamespaceEntry.SymbolFileID; }
3421 if (builder is MethodBuilder)
3422 return ((MethodBuilder) builder).GetToken ().Token;
3423 else if (builder is ConstructorBuilder)
3424 return ((ConstructorBuilder) builder).GetToken ().Token;
3426 throw new NotSupportedException ();
3430 public void CloseMethod ()
3432 if (CodeGen.SymbolWriter != null)
3433 CodeGen.SymbolWriter.CloseMethod ();
3436 public static SourceMethod Create (TypeContainer parent,
3437 MethodBase builder, Block block)
3439 if (CodeGen.SymbolWriter == null)
3444 Location start_loc = block.StartLocation;
3445 if (Location.IsNull (start_loc))
3448 Location end_loc = block.EndLocation;
3449 if (Location.IsNull (end_loc))
3452 ISourceFile file = start_loc.SourceFile;
3456 return new SourceMethod (
3457 parent, builder, file, start_loc, end_loc);
3461 public class Method : MethodCore, IIteratorContainer, IMethodData {
3462 public MethodBuilder MethodBuilder;
3463 public MethodData MethodData;
3464 ReturnParameter return_attributes;
3465 ListDictionary declarative_security;
3468 /// Modifiers allowed in a class declaration
3470 const int AllowedModifiers =
3473 Modifiers.PROTECTED |
3474 Modifiers.INTERNAL |
3479 Modifiers.OVERRIDE |
3480 Modifiers.ABSTRACT |
3482 Modifiers.METHOD_YIELDS |
3485 const int AllowedInterfaceModifiers =
3486 Modifiers.NEW | Modifiers.UNSAFE;
3489 // return_type can be "null" for VOID values.
3491 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3492 MemberName name, Parameters parameters, Attributes attrs,
3494 : base (ds, return_type, mod,
3495 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3496 is_iface, name, attrs, parameters, l)
3500 public override AttributeTargets AttributeTargets {
3502 return AttributeTargets.Method;
3506 public override string GetSignatureForError()
3508 if (MethodBuilder == null) {
3509 return GetSignatureForError (Parent);
3511 return TypeManager.CSharpSignature (MethodBuilder);
3515 /// Use this method when MethodBuilder is null
3517 public override string GetSignatureForError (TypeContainer tc)
3519 // TODO: get params from somewhere
3520 if (parameter_info == null)
3521 return base.GetSignatureForError (tc);
3523 // TODO: move to parameters
3524 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3525 if (parameter_info.Parameters.FixedParameters != null) {
3526 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3527 Parameter p = parameter_info.Parameters.FixedParameters [i];
3528 args.Append (p.GetSignatureForError ());
3530 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3535 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3538 void DuplicateEntryPoint (MethodInfo b, Location location)
3542 "Program `" + CodeGen.FileName +
3543 "' has more than one entry point defined: `" +
3544 TypeManager.CSharpSignature(b) + "'");
3547 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3549 if (b.ReturnType != TypeManager.void_type &&
3550 b.ReturnType != TypeManager.int32_type)
3553 if (pinfo.Count == 0)
3556 if (pinfo.Count > 1)
3559 Type t = pinfo.ParameterType(0);
3561 (t.GetArrayRank() == 1) &&
3562 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3563 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3569 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3571 if (a.Target == AttributeTargets.ReturnValue) {
3572 if (return_attributes == null)
3573 return_attributes = new ReturnParameter (MethodBuilder, Location);
3575 return_attributes.ApplyAttributeBuilder (a, cb);
3579 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
3580 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3583 if (a.Type == TypeManager.dllimport_type) {
3584 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3585 if ((ModFlags & extern_static) != extern_static) {
3586 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3592 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3593 if (declarative_security == null)
3594 declarative_security = new ListDictionary ();
3595 a.ExtractSecurityPermissionSet (declarative_security);
3599 if (a.Type == TypeManager.conditional_attribute_type) {
3600 if (IsOperator || IsExplicitImpl) {
3601 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3605 if (ReturnType != TypeManager.void_type) {
3606 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3610 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3611 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3616 Report.Error (582, Location, "Conditional not valid on interface members");
3620 if (MethodData.IsImplementing) {
3621 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3625 for (int i = 0; i < parameter_info.Count; ++i) {
3626 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3627 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3633 MethodBuilder.SetCustomAttribute (cb);
3636 protected override bool CheckForDuplications ()
3638 ArrayList ar = Parent.Methods;
3640 int arLen = ar.Count;
3642 for (int i = 0; i < arLen; i++) {
3643 Method m = (Method) ar [i];
3644 if (IsDuplicateImplementation (m))
3649 ar = Parent.Properties;
3651 for (int i = 0; i < ar.Count; ++i) {
3652 PropertyBase pb = (PropertyBase) ar [i];
3653 if (pb.AreAccessorsDuplicateImplementation (this))
3658 ar = Parent.Indexers;
3660 for (int i = 0; i < ar.Count; ++i) {
3661 PropertyBase pb = (PropertyBase) ar [i];
3662 if (pb.AreAccessorsDuplicateImplementation (this))
3669 for (int i = 0; i < ar.Count; ++i) {
3670 Event ev = (Event) ar [i];
3671 if (ev.AreAccessorsDuplicateImplementation (this))
3682 public override bool Define ()
3691 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3693 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3695 if (!MethodData.Define (Parent))
3699 // Setup iterator if we are one
3701 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3702 Iterator iterator = new Iterator (
3703 Parent, Name, MemberType, ParameterTypes,
3704 ParameterInfo, ModFlags, block, Location);
3706 if (!iterator.DefineIterator ())
3709 block = iterator.Block;
3712 MethodBuilder = MethodData.MethodBuilder;
3715 // This is used to track the Entry Point,
3717 if (Name == "Main" &&
3718 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3719 (RootContext.MainClass == null ||
3720 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3721 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3722 if (RootContext.EntryPoint == null) {
3723 RootContext.EntryPoint = MethodBuilder;
3724 RootContext.EntryPointLocation = Location;
3726 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3727 DuplicateEntryPoint (MethodBuilder, Location);
3730 if (RootContext.WarningLevel >= 4)
3731 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3735 if (MemberType.IsAbstract && MemberType.IsSealed) {
3736 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3746 public override void Emit ()
3748 MethodData.Emit (Parent, this);
3751 if (declarative_security != null) {
3752 foreach (DictionaryEntry de in declarative_security) {
3753 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3761 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3763 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3764 container.TypeBuilder, Name, ParameterTypes, false);
3769 base_ret_type = mi.ReturnType;
3773 protected override bool VerifyClsCompliance(DeclSpace ds)
3775 if (!base.VerifyClsCompliance (ds))
3778 if (parameter_types.Length > 0) {
3779 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3781 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3788 void IIteratorContainer.SetYields ()
3790 ModFlags |= Modifiers.METHOD_YIELDS;
3793 #region IMethodData Members
3795 public CallingConventions CallingConventions {
3797 CallingConventions cc = Parameters.GetCallingConvention ();
3798 if (Parameters.HasArglist)
3799 block.HasVarargs = true;
3802 if ((ModFlags & Modifiers.STATIC) == 0)
3803 cc |= CallingConventions.HasThis;
3805 // FIXME: How is `ExplicitThis' used in C#?
3811 public Type ReturnType {
3817 public MemberName MethodName {
3823 public new Location Location {
3825 return base.Location;
3829 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3831 return new EmitContext (
3832 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3835 public ObsoleteAttribute GetObsoleteAttribute ()
3837 return GetObsoleteAttribute (Parent);
3841 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3843 public bool IsExcluded (EmitContext ec)
3845 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3846 return (caching_flags & Flags.Excluded) != 0;
3848 caching_flags &= ~Flags.Excluded_Undetected;
3850 if (base_method == null) {
3851 if (OptAttributes == null)
3854 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3859 foreach (Attribute a in attrs) {
3860 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3861 if (RootContext.AllDefines.Contains (condition))
3865 caching_flags |= Flags.Excluded;
3869 IMethodData md = TypeManager.GetMethod (base_method);
3871 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
3872 caching_flags |= Flags.Excluded;
3878 if (md.IsExcluded (ec)) {
3879 caching_flags |= Flags.Excluded;
3888 public abstract class ConstructorInitializer {
3889 ArrayList argument_list;
3890 protected ConstructorInfo base_constructor;
3891 Parameters parameters;
3894 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
3897 this.argument_list = argument_list;
3898 this.parameters = parameters;
3902 public ArrayList Arguments {
3904 return argument_list;
3908 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
3910 Expression base_constructor_group;
3913 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
3915 if (argument_list != null){
3916 foreach (Argument a in argument_list){
3917 if (!a.Resolve (ec, loc))
3921 ec.CurrentBlock = null;
3923 if (this is ConstructorBaseInitializer) {
3924 if (ec.ContainerType.BaseType == null)
3927 t = ec.ContainerType.BaseType;
3928 if (ec.ContainerType.IsValueType) {
3929 Report.Error (522, loc,
3930 "structs cannot call base class constructors");
3934 t = ec.ContainerType;
3936 base_constructor_group = Expression.MemberLookup (
3937 ec, t, ".ctor", MemberTypes.Constructor,
3938 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3941 if (base_constructor_group == null){
3942 base_constructor_group = Expression.MemberLookup (
3943 ec, t, ".ctor", MemberTypes.Constructor,
3944 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3947 if (base_constructor_group != null)
3949 112, loc, "`{0}.{1}' is inaccessible due to " +
3950 "its protection level", t.FullName, t.Name);
3953 1501, loc, "Can not find a constructor for " +
3954 "this argument list");
3958 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
3959 ec, (MethodGroupExpr) base_constructor_group, argument_list,
3962 if (base_constructor == null){
3963 Report.Error (1501, loc,
3964 "Can not find a constructor for this argument list");
3968 if (base_constructor == caller_builder){
3969 Report.Error (516, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
3976 public void Emit (EmitContext ec)
3978 if (base_constructor != null){
3979 ec.Mark (loc, false);
3981 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
3983 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
3988 /// Method search for base ctor. (We do not cache it).
3990 Constructor GetOverloadedConstructor (TypeContainer tc)
3992 if (tc.InstanceConstructors == null)
3995 foreach (Constructor c in tc.InstanceConstructors) {
3996 if (Arguments == null) {
3997 if (c.ParameterTypes.Length == 0)
4005 int count = c.ParameterInfo.Count;
4007 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4008 for (int i = 0; i < count-1; i++)
4009 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4014 if (c.ParameterTypes.Length != Arguments.Count)
4017 for (int i = 0; i < Arguments.Count; ++i)
4018 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4033 //TODO: implement caching when it will be necessary
4034 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4036 Constructor ctor = GetOverloadedConstructor (tc);
4040 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4044 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4048 public class ConstructorBaseInitializer : ConstructorInitializer {
4049 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4050 base (argument_list, pars, l)
4054 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4055 if (base_constructor == null)
4058 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4059 if (type_ds == null) {
4060 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (base_constructor);
4063 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (base_constructor), loc);
4068 base.CheckObsoleteAttribute (type_ds, loc);
4073 public class ConstructorThisInitializer : ConstructorInitializer {
4074 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4075 base (argument_list, pars, l)
4080 public class Constructor : MethodCore, IMethodData {
4081 public ConstructorBuilder ConstructorBuilder;
4082 public ConstructorInitializer Initializer;
4083 ListDictionary declarative_security;
4086 // Modifiers allowed for a constructor.
4088 public const int AllowedModifiers =
4090 Modifiers.PROTECTED |
4091 Modifiers.INTERNAL |
4097 bool has_compliant_args = false;
4099 // The spec claims that static is not permitted, but
4100 // my very own code has static constructors.
4102 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4103 ConstructorInitializer init, Location l)
4104 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4110 public override string GetSignatureForError()
4112 if (ConstructorBuilder == null)
4113 return GetSignatureForError (Parent);
4115 return TypeManager.CSharpSignature (ConstructorBuilder);
4118 public bool HasCompliantArgs {
4120 return has_compliant_args;
4124 public override AttributeTargets AttributeTargets {
4126 return AttributeTargets.Constructor;
4132 // Returns true if this is a default constructor
4134 public bool IsDefault ()
4136 if ((ModFlags & Modifiers.STATIC) != 0)
4137 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4138 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4141 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4142 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4143 (Initializer is ConstructorBaseInitializer) &&
4144 (Initializer.Arguments == null);
4147 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4149 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4150 if (declarative_security == null) {
4151 declarative_security = new ListDictionary ();
4153 a.ExtractSecurityPermissionSet (declarative_security);
4157 ConstructorBuilder.SetCustomAttribute (cb);
4160 protected override bool CheckForDuplications ()
4162 ArrayList ar = Parent.InstanceConstructors;
4164 int arLen = ar.Count;
4166 for (int i = 0; i < arLen; i++) {
4167 Constructor m = (Constructor) ar [i];
4168 if (IsDuplicateImplementation (m))
4175 protected override bool CheckBase ()
4177 // Check whether arguments were correct.
4178 if (!DoDefineParameters ())
4181 // TODO: skip the rest for generated ctor
4182 if ((ModFlags & Modifiers.STATIC) != 0)
4185 if (!CheckForDuplications ())
4188 if (Parent.Kind == Kind.Struct) {
4189 if (ParameterTypes.Length == 0) {
4190 Report.Error (568, Location,
4191 "Structs can not contain explicit parameterless " +
4196 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4197 Report.Error (666, Location, "Protected member in struct declaration");
4202 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4203 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4210 // Creates the ConstructorBuilder
4212 public override bool Define ()
4214 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4215 MethodAttributes.SpecialName);
4217 if ((ModFlags & Modifiers.STATIC) != 0) {
4218 ca |= MethodAttributes.Static | MethodAttributes.Private;
4220 ca |= MethodAttributes.HideBySig;
4222 if ((ModFlags & Modifiers.PUBLIC) != 0)
4223 ca |= MethodAttributes.Public;
4224 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4225 if ((ModFlags & Modifiers.INTERNAL) != 0)
4226 ca |= MethodAttributes.FamORAssem;
4228 ca |= MethodAttributes.Family;
4229 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4230 ca |= MethodAttributes.Assembly;
4231 else if (IsDefault ())
4232 ca |= MethodAttributes.Public;
4234 ca |= MethodAttributes.Private;
4237 // Check if arguments were correct.
4241 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4242 ca, CallingConventions,
4245 if ((ModFlags & Modifiers.UNSAFE) != 0)
4246 ConstructorBuilder.InitLocals = false;
4248 TypeManager.AddMethod (ConstructorBuilder, this);
4251 // HACK because System.Reflection.Emit is lame
4253 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4261 public override void Emit ()
4263 EmitContext ec = CreateEmitContext (null, null);
4266 // extern methods have no bodies
4268 if ((ModFlags & Modifiers.EXTERN) != 0) {
4269 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4271 179, Location, "External constructor `" +
4272 TypeManager.CSharpSignature (ConstructorBuilder) +
4273 "' can not have a body");
4276 } else if (block == null) {
4278 501, Location, "Constructor `" +
4279 TypeManager.CSharpSignature (ConstructorBuilder) +
4280 "' must declare a body since it is not marked extern");
4284 if ((ModFlags & Modifiers.STATIC) == 0){
4285 if (Parent.Kind == Kind.Class && Initializer == null)
4286 Initializer = new ConstructorBaseInitializer (
4287 null, Parameters.EmptyReadOnlyParameters, Location);
4291 // Spec mandates that Initializers will not have
4295 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4297 ec.IsStatic = false;
4300 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4302 SourceMethod source = SourceMethod.Create (
4303 Parent, ConstructorBuilder, block);
4306 // Classes can have base initializers and instance field initializers.
4308 if (Parent.Kind == Kind.Class){
4309 if ((ModFlags & Modifiers.STATIC) == 0){
4312 // If we use a "this (...)" constructor initializer, then
4313 // do not emit field initializers, they are initialized in the other constructor
4315 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4316 Parent.EmitFieldInitializers (ec);
4319 if (Initializer != null) {
4320 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4321 Initializer.CheckObsoleteAttribute (Parent, Location);
4323 ec.TestObsoleteMethodUsage = false;
4324 Initializer.Emit (ec);
4327 if ((ModFlags & Modifiers.STATIC) != 0)
4328 Parent.EmitFieldInitializers (ec);
4330 if (OptAttributes != null)
4331 OptAttributes.Emit (ec, this);
4333 // If this is a non-static `struct' constructor and doesn't have any
4334 // initializer, it must initialize all of the struct's fields.
4335 if ((Parent.Kind == Kind.Struct) &&
4336 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4337 Block.AddThisVariable (Parent, Location);
4339 ec.EmitTopBlock (block, ParameterInfo, Location);
4342 source.CloseMethod ();
4346 if (declarative_security != null) {
4347 foreach (DictionaryEntry de in declarative_security) {
4348 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4355 // Is never override
4356 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4361 protected override bool VerifyClsCompliance (DeclSpace ds)
4363 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4367 if (parameter_types.Length > 0) {
4368 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4370 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4372 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4373 foreach (Type param in parameter_types) {
4374 if (param.IsArray) {
4380 has_compliant_args = true;
4384 #region IMethodData Members
4386 public System.Reflection.CallingConventions CallingConventions {
4388 CallingConventions cc = Parameters.GetCallingConvention ();
4390 if (Parent.Kind == Kind.Class)
4391 if ((ModFlags & Modifiers.STATIC) == 0)
4392 cc |= CallingConventions.HasThis;
4394 // FIXME: How is `ExplicitThis' used in C#?
4400 public new Location Location {
4402 return base.Location;
4406 public MemberName MethodName {
4412 public Type ReturnType {
4418 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4420 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4421 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4424 public ObsoleteAttribute GetObsoleteAttribute ()
4429 public bool IsExcluded(EmitContext ec)
4438 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4440 public interface IMethodData
4442 CallingConventions CallingConventions { get; }
4443 Location Location { get; }
4444 MemberName MethodName { get; }
4445 Type[] ParameterTypes { get; }
4446 Type ReturnType { get; }
4448 Attributes OptAttributes { get; }
4449 ToplevelBlock Block { get; }
4451 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4452 ObsoleteAttribute GetObsoleteAttribute ();
4453 string GetSignatureForError (TypeContainer tc);
4454 bool IsExcluded (EmitContext ec);
4455 bool IsClsCompliaceRequired (DeclSpace ds);
4459 // Encapsulates most of the Method's state
4461 public class MethodData {
4463 readonly IMethodData method;
4466 // The return type of this method
4468 public readonly InternalParameters ParameterInfo;
4471 // Are we implementing an interface ?
4473 public bool IsImplementing = false;
4478 protected MemberBase member;
4479 protected int modifiers;
4480 protected MethodAttributes flags;
4482 MethodBuilder builder = null;
4483 public MethodBuilder MethodBuilder {
4489 public MethodData (MemberBase member, InternalParameters parameters,
4490 int modifiers, MethodAttributes flags, IMethodData method)
4492 this.member = member;
4493 this.ParameterInfo = parameters;
4494 this.modifiers = modifiers;
4497 this.method = method;
4500 public bool Define (TypeContainer container)
4502 MethodInfo implementing = null;
4504 string name = method.MethodName.Name;
4505 string method_name = name;
4507 Type[] ParameterTypes = method.ParameterTypes;
4509 if (container.Pending != null){
4510 if (member is Indexer)
4511 implementing = container.Pending.IsInterfaceIndexer (
4512 member.InterfaceType, method.ReturnType, ParameterTypes);
4514 implementing = container.Pending.IsInterfaceMethod (
4515 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4517 if (member.InterfaceType != null){
4518 if (implementing == null){
4519 Report.Error (539, method.Location,
4520 "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
4523 method_name = member.InterfaceType.FullName + "." + name;
4528 // For implicit implementations, make sure we are public, for
4529 // explicit implementations, make sure we are private.
4531 if (implementing != null){
4533 // Setting null inside this block will trigger a more
4534 // verbose error reporting for missing interface implementations
4536 // The "candidate" function has been flagged already
4537 // but it wont get cleared
4539 if (member.IsExplicitImpl){
4540 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4541 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4542 implementing = null;
4544 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4545 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4547 // If this is an interface method implementation,
4548 // check for public accessibility
4550 implementing = null;
4551 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4552 // We may never be private.
4553 implementing = null;
4554 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4556 // We may be protected if we're overriding something.
4558 implementing = null;
4563 // Static is not allowed
4565 if ((modifiers & Modifiers.STATIC) != 0){
4566 implementing = null;
4567 Modifiers.Error_InvalidModifier (method.Location, "static");
4572 // If implementing is still valid, set flags
4574 if (implementing != null){
4576 // When implementing interface methods, set NewSlot
4577 // unless, we are overwriting a method.
4579 if (implementing.DeclaringType.IsInterface){
4580 if ((modifiers & Modifiers.OVERRIDE) == 0)
4581 flags |= MethodAttributes.NewSlot;
4584 MethodAttributes.Virtual |
4585 MethodAttributes.HideBySig;
4587 // Set Final unless we're virtual, abstract or already overriding a method.
4588 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4589 flags |= MethodAttributes.Final;
4591 IsImplementing = true;
4594 EmitContext ec = method.CreateEmitContext (container, null);
4596 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4598 if (builder == null)
4601 if ((modifiers & Modifiers.UNSAFE) != 0)
4602 builder.InitLocals = false;
4604 if (IsImplementing){
4606 // clear the pending implemntation flag
4608 if (member is Indexer) {
4609 container.Pending.ImplementIndexer (
4610 member.InterfaceType, builder, method.ReturnType,
4611 ParameterTypes, member.IsExplicitImpl);
4613 container.Pending.ImplementMethod (
4614 member.InterfaceType, name, method.ReturnType,
4615 ParameterTypes, member.IsExplicitImpl);
4617 if (member.IsExplicitImpl)
4618 container.TypeBuilder.DefineMethodOverride (
4619 builder, implementing);
4623 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4624 TypeManager.AddMethod (builder, method);
4631 /// Create the MethodBuilder for the method
4633 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4635 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4637 if ((modifiers & extern_static) == extern_static) {
4639 if (method.OptAttributes != null) {
4640 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4641 if (dllimport_attribute != null) {
4642 flags |= MethodAttributes.PinvokeImpl;
4643 builder = dllimport_attribute.DefinePInvokeMethod (
4644 ec, container.TypeBuilder, method_name, flags,
4645 method.ReturnType, ParameterTypes);
4651 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4652 // We are more strict than Microsoft and report CS0626 like error
4653 if (method.OptAttributes == null ||
4654 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4655 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));
4660 builder = container.TypeBuilder.DefineMethod (
4661 method_name, flags, method.CallingConventions,
4662 method.ReturnType, ParameterTypes);
4668 public void Emit (TypeContainer container, Attributable kind)
4671 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4672 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4674 ec = method.CreateEmitContext (container, null);
4676 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container.Parent) != null)
4677 ec.TestObsoleteMethodUsage = false;
4679 Location loc = method.Location;
4680 Attributes OptAttributes = method.OptAttributes;
4682 if (OptAttributes != null)
4683 OptAttributes.Emit (ec, kind);
4685 if (member is MethodCore)
4686 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4688 ToplevelBlock block = method.Block;
4691 // abstract or extern methods have no bodies
4693 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4698 // abstract or extern methods have no bodies.
4700 if ((modifiers & Modifiers.ABSTRACT) != 0)
4702 500, method.Location, "Abstract method `" +
4703 TypeManager.CSharpSignature (builder) +
4704 "' can not have a body");
4706 if ((modifiers & Modifiers.EXTERN) != 0)
4708 179, method.Location, "External method `" +
4709 TypeManager.CSharpSignature (builder) +
4710 "' can not have a body");
4716 // Methods must have a body unless they're extern or abstract
4718 if (block == null) {
4720 501, method.Location, "Method `" +
4721 TypeManager.CSharpSignature (builder) +
4722 "' must declare a body since it is not marked " +
4723 "abstract or extern");
4727 SourceMethod source = SourceMethod.Create (
4728 container, MethodBuilder, method.Block);
4731 // Handle destructors specially
4733 // FIXME: This code generates buggy code
4735 if (member is Destructor)
4736 EmitDestructor (ec, block);
4738 ec.EmitTopBlock (block, ParameterInfo, loc);
4741 source.CloseMethod ();
4744 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4746 ILGenerator ig = ec.ig;
4748 Label finish = ig.DefineLabel ();
4750 block.SetDestructor ();
4752 ig.BeginExceptionBlock ();
4753 ec.ReturnLabel = finish;
4754 ec.HasReturnLabel = true;
4755 ec.EmitTopBlock (block, null, method.Location);
4757 // ig.MarkLabel (finish);
4758 ig.BeginFinallyBlock ();
4760 if (ec.ContainerType.BaseType != null) {
4761 Expression member_lookup = Expression.MemberLookup (
4762 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4763 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4765 if (member_lookup != null){
4766 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4768 ig.Emit (OpCodes.Ldarg_0);
4769 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4773 ig.EndExceptionBlock ();
4774 //ig.MarkLabel (ec.ReturnLabel);
4775 ig.Emit (OpCodes.Ret);
4779 public class Destructor : Method {
4781 public Destructor (TypeContainer ds, Expression return_type, int mod,
4782 string name, Parameters parameters, Attributes attrs,
4784 : base (ds, return_type, mod, false, new MemberName (name),
4785 parameters, attrs, l)
4788 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4790 if (a.Type == TypeManager.conditional_attribute_type) {
4791 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4795 base.ApplyAttributeBuilder (a, cb);
4799 abstract public class MemberBase : MemberCore {
4800 public Expression Type;
4802 public MethodAttributes flags;
4804 protected readonly int explicit_mod_flags;
4807 // The "short" name of this property / indexer / event. This is the
4808 // name without the explicit interface.
4810 public string ShortName;
4813 // The type of this property / indexer / event
4815 public Type MemberType;
4818 // If true, this is an explicit interface implementation
4820 public bool IsExplicitImpl = false;
4823 // The name of the interface we are explicitly implementing
4825 public MemberName ExplicitInterfaceName = null;
4828 // Whether this is an interface member.
4830 public bool IsInterface;
4833 // If true, the interface type we are explicitly implementing
4835 public Type InterfaceType = null;
4838 // The constructor is only exposed to our children
4840 protected MemberBase (TypeContainer parent, Expression type, int mod,
4841 int allowed_mod, int def_mod, MemberName name,
4842 Attributes attrs, Location loc)
4843 : base (parent, name, attrs, loc)
4845 explicit_mod_flags = mod;
4847 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4849 // Check for explicit interface implementation
4850 if (MemberName.Left != null) {
4851 ExplicitInterfaceName = MemberName.Left;
4852 ShortName = MemberName.Name;
4853 IsExplicitImpl = true;
4858 protected virtual bool CheckBase ()
4860 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4861 Report.Error (666, Location, "Protected member in struct declaration");
4865 if ((RootContext.WarningLevel >= 4) &&
4866 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4867 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4868 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4869 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4874 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4878 foreach (Type partype in parameters){
4879 if (partype == TypeManager.void_type) {
4881 1547, Location, "Keyword 'void' cannot " +
4882 "be used in this context");
4886 if (partype.IsPointer){
4889 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4893 if (ds.AsAccessible (partype, ModFlags))
4896 if (this is Indexer)
4897 Report.Error (55, Location,
4898 "Inconsistent accessibility: parameter type `" +
4899 TypeManager.CSharpName (partype) + "' is less " +
4900 "accessible than indexer `" + Name + "'");
4901 else if ((this is Method) && ((Method) this).IsOperator)
4902 Report.Error (57, Location,
4903 "Inconsistent accessibility: parameter type `" +
4904 TypeManager.CSharpName (partype) + "' is less " +
4905 "accessible than operator `" + Name + "'");
4907 Report.Error (51, Location,
4908 "Inconsistent accessibility: parameter type `" +
4909 TypeManager.CSharpName (partype) + "' is less " +
4910 "accessible than method `" + Name + "'");
4917 protected virtual bool DoDefine ()
4919 EmitContext ec = Parent.EmitContext;
4921 throw new InternalErrorException ("MemberBase.DoDefine called too early");
4924 throw new InternalErrorException ();
4927 ModFlags = Modifiers.PUBLIC |
4928 Modifiers.ABSTRACT |
4929 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
4931 flags = MethodAttributes.Public |
4932 MethodAttributes.Abstract |
4933 MethodAttributes.HideBySig |
4934 MethodAttributes.NewSlot |
4935 MethodAttributes.Virtual;
4937 if (!Parent.MethodModifiersValid (this))
4940 flags = Modifiers.MethodAttr (ModFlags);
4943 // Lookup Type, verify validity
4944 bool old_unsafe = ec.InUnsafe;
4945 ec.InUnsafe = InUnsafe;
4946 Type = Type.ResolveAsTypeTerminal (ec, false);
4947 ec.InUnsafe = old_unsafe;
4952 MemberType = Type.Type;
4954 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
4955 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
4956 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
4961 // verify accessibility
4962 if (!Parent.AsAccessible (MemberType, ModFlags)) {
4963 Report.SymbolRelatedToPreviousError (MemberType);
4964 if (this is Property)
4965 Report.Error (53, Location,
4966 "Inconsistent accessibility: property type `" +
4967 TypeManager.CSharpName (MemberType) + "' is less " +
4968 "accessible than property `" + GetSignatureForError () + "'");
4969 else if (this is Indexer)
4970 Report.Error (54, Location,
4971 "Inconsistent accessibility: indexer return type `" +
4972 TypeManager.CSharpName (MemberType) + "' is less " +
4973 "accessible than indexer `" + Name + "'");
4974 else if (this is MethodCore) {
4975 if (this is Operator)
4976 Report.Error (56, Location,
4977 "Inconsistent accessibility: return type `" +
4978 TypeManager.CSharpName (MemberType) + "' is less " +
4979 "accessible than operator `" + Name + "'");
4981 Report.Error (50, Location,
4982 "Inconsistent accessibility: return type `" +
4983 TypeManager.CSharpName (MemberType) + "' is less " +
4984 "accessible than method `" + Name + "'");
4986 Report.Error (52, Location,
4987 "Inconsistent accessibility: field type `" +
4988 TypeManager.CSharpName (MemberType) + "' is less " +
4989 "accessible than field `" + Name + "'");
4994 if (MemberType.IsPointer && !UnsafeOK (Parent))
4997 if (IsExplicitImpl) {
4998 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
4999 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5003 InterfaceType = texpr.ResolveType (ec);
5005 if (!InterfaceType.IsInterface) {
5006 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5011 // Compute the full name that we need to export.
5012 if (InterfaceType.FullName != ExplicitInterfaceName) {
5013 ExplicitInterfaceName = InterfaceType.FullName;
5014 UpdateMemberName ();
5018 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5021 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5028 /// The name of the member can be changed during definition (see IndexerName attribute)
5030 protected virtual void UpdateMemberName ()
5032 MemberName.Name = ShortName;
5035 public override string GetSignatureForError (TypeContainer tc)
5037 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5040 protected bool IsTypePermitted ()
5042 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5043 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5049 protected override bool VerifyClsCompliance(DeclSpace ds)
5051 if (base.VerifyClsCompliance (ds)) {
5055 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5056 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5061 protected override void VerifyObsoleteAttribute()
5063 CheckUsageOfObsoleteAttribute (MemberType);
5068 // Fields and Events both generate FieldBuilders, we use this to share
5069 // their common bits. This is also used to flag usage of the field
5071 abstract public class FieldBase : MemberBase {
5072 public FieldBuilder FieldBuilder;
5073 public Status status;
5076 public enum Status : byte {
5079 HAS_OFFSET = 4 // Used by FieldMember.
5082 static string[] attribute_targets = new string [] { "field" };
5085 /// Symbol with same name in base class/struct
5087 public MemberInfo conflict_symbol;
5090 // The constructor is only exposed to our children
5092 protected FieldBase (TypeContainer parent, Expression type, int mod,
5093 int allowed_mod, MemberName name, object init,
5094 Attributes attrs, Location loc)
5095 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5101 public override AttributeTargets AttributeTargets {
5103 return AttributeTargets.Field;
5107 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5109 if (a.Type == TypeManager.marshal_as_attr_type) {
5110 UnmanagedMarshal marshal = a.GetMarshal (this);
5111 if (marshal != null) {
5112 FieldBuilder.SetMarshal (marshal);
5117 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5118 a.Error_InvalidSecurityParent ();
5122 FieldBuilder.SetCustomAttribute (cb);
5126 // Whether this field has an initializer.
5128 public bool HasInitializer {
5130 return init != null;
5134 protected readonly Object init;
5137 Expression init_expr;
5138 bool init_expr_initialized = false;
5141 // Resolves and returns the field initializer.
5143 public Expression GetInitializerExpression (EmitContext ec)
5145 if (init_expr_initialized)
5149 if (init is Expression)
5150 e = (Expression) init;
5152 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5154 ec.IsFieldInitializer = true;
5155 e = e.DoResolve (ec);
5156 ec.IsFieldInitializer = false;
5159 init_expr_initialized = true;
5164 protected override bool CheckBase ()
5166 if (!base.CheckBase ())
5173 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5174 if (conflict_symbol == null) {
5175 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5176 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5181 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5182 Report.SymbolRelatedToPreviousError (conflict_symbol);
5183 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5189 public override string GetSignatureForError ()
5191 if (FieldBuilder == null) {
5192 return base.GetSignatureForError (Parent);
5194 return TypeManager.GetFullNameSignature (FieldBuilder);
5197 public override string[] ValidAttributeTargets {
5199 return attribute_targets;
5203 protected override bool VerifyClsCompliance (DeclSpace ds)
5205 if (!base.VerifyClsCompliance (ds))
5208 if (FieldBuilder == null) {
5212 if (!AttributeTester.IsClsCompliant (FieldBuilder.FieldType)) {
5213 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5219 public void SetAssigned ()
5221 status |= Status.ASSIGNED;
5225 public abstract class FieldMember: FieldBase
5229 protected FieldMember (TypeContainer parent, Expression type, int mod,
5230 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5231 : base (parent, type, mod, allowed_mod, name, init, attrs, loc)
5235 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5237 if (a.Type == TypeManager.field_offset_attribute_type)
5239 status |= Status.HAS_OFFSET;
5241 if (!Parent.HasExplicitLayout) {
5242 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5246 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5247 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5251 base.ApplyAttributeBuilder (a, cb);
5255 public override bool Define()
5257 EmitContext ec = Parent.EmitContext;
5259 throw new InternalErrorException ("FieldMember.Define called too early");
5261 bool old_unsafe = ec.InUnsafe;
5262 ec.InUnsafe = InUnsafe;
5263 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
5267 MemberType = texpr.ResolveType (ec);
5269 if (MemberType == TypeManager.void_type) {
5270 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5274 ec.InUnsafe = old_unsafe;
5279 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5280 Report.Error (52, Location,
5281 "Inconsistent accessibility: field type `" +
5282 TypeManager.CSharpName (MemberType) + "' is less " +
5283 "accessible than field `" + Name + "'");
5287 if (!IsTypePermitted ())
5290 if (MemberType.IsPointer && !UnsafeOK (Parent))
5296 public override void Emit ()
5298 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5299 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5306 // Represents header string for documentation comment.
5308 public override string DocCommentHeader {
5309 get { return "F:"; }
5314 // The Field class is used to represents class/struct fields during parsing.
5316 public class Field : FieldMember {
5318 // Modifiers allowed in a class declaration
5320 const int AllowedModifiers =
5323 Modifiers.PROTECTED |
5324 Modifiers.INTERNAL |
5327 Modifiers.VOLATILE |
5331 public Field (TypeContainer parent, Expression type, int mod, string name,
5332 Object expr_or_array_init, Attributes attrs, Location loc)
5333 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5334 expr_or_array_init, attrs, loc)
5338 public override bool Define ()
5340 if (!base.Define ())
5343 if (RootContext.WarningLevel > 1){
5344 Type ptype = Parent.TypeBuilder.BaseType;
5346 // ptype is only null for System.Object while compiling corlib.
5348 TypeContainer.FindMembers (
5349 ptype, MemberTypes.Method,
5350 BindingFlags.Public |
5351 BindingFlags.Static | BindingFlags.Instance,
5352 System.Type.FilterName, Name);
5356 if ((ModFlags & Modifiers.VOLATILE) != 0){
5357 if (!MemberType.IsClass){
5358 Type vt = MemberType;
5360 if (TypeManager.IsEnumType (vt))
5361 vt = TypeManager.EnumToUnderlying (MemberType);
5363 if (!((vt == TypeManager.bool_type) ||
5364 (vt == TypeManager.sbyte_type) ||
5365 (vt == TypeManager.byte_type) ||
5366 (vt == TypeManager.short_type) ||
5367 (vt == TypeManager.ushort_type) ||
5368 (vt == TypeManager.int32_type) ||
5369 (vt == TypeManager.uint32_type) ||
5370 (vt == TypeManager.char_type) ||
5371 (vt == TypeManager.float_type) ||
5372 (!vt.IsValueType))){
5374 677, Location, Parent.MakeName (Name) +
5375 " A volatile field can not be of type `" +
5376 TypeManager.CSharpName (vt) + "'");
5381 if ((ModFlags & Modifiers.READONLY) != 0){
5384 "A field can not be both volatile and readonly");
5389 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5391 if (Parent.Kind == Kind.Struct &&
5392 ((fa & FieldAttributes.Static) == 0) &&
5393 MemberType == Parent.TypeBuilder &&
5394 !TypeManager.IsBuiltinType (MemberType)){
5395 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5396 "' causes a cycle in the structure layout");
5401 FieldBuilder = Parent.TypeBuilder.DefineField (
5402 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5404 TypeManager.RegisterFieldBase (FieldBuilder, this);
5406 catch (ArgumentException) {
5407 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5414 public override void Emit ()
5416 if (OptAttributes != null) {
5417 EmitContext ec = new EmitContext (
5418 Parent, Location, null, FieldBuilder.FieldType,
5420 OptAttributes.Emit (ec, this);
5428 // `set' and `get' accessors are represented with an Accessor.
5430 public class Accessor {
5432 // Null if the accessor is empty, or a Block if not
5434 public const int AllowedModifiers =
5436 Modifiers.PROTECTED |
5437 Modifiers.INTERNAL |
5440 public ToplevelBlock Block;
5441 public Attributes Attributes;
5442 public Location Location;
5443 public int ModFlags;
5445 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5450 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5455 // Ooouh Martin, templates are missing here.
5456 // When it will be possible move here a lot of child code and template method type.
5457 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5458 protected MethodData method_data;
5459 protected ToplevelBlock block;
5460 protected ListDictionary declarative_security;
5462 // The accessor are created event if they are not wanted.
5463 // But we need them because their names are reserved.
5464 // Field says whether accessor will be emited or not
5465 public readonly bool IsDummy;
5467 protected readonly string prefix;
5469 ReturnParameter return_attributes;
5471 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5472 : base (null, SetupName (prefix, member), null, member.Location)
5474 this.prefix = prefix;
5478 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5480 : base (null, SetupName (prefix, member),
5481 accessor.Attributes, accessor.Location)
5483 this.prefix = prefix;
5484 this.block = accessor.Block;
5487 static MemberName SetupName (string prefix, MemberBase member)
5489 MemberName name = member.MemberName.Clone ();
5490 name.Name = prefix + member.ShortName;
5494 public void UpdateName (MemberBase member)
5496 MemberName.Name = prefix + member.ShortName;
5499 #region IMethodData Members
5501 public ToplevelBlock Block {
5511 public CallingConventions CallingConventions {
5513 return CallingConventions.Standard;
5517 public bool IsExcluded (EmitContext ec)
5522 public MemberName MethodName {
5528 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5529 public abstract Type[] ParameterTypes { get; }
5530 public abstract Type ReturnType { get; }
5531 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5535 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5537 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5538 a.Type == TypeManager.conditional_attribute_type) {
5539 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 ());
5543 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5544 if (declarative_security == null)
5545 declarative_security = new ListDictionary ();
5546 a.ExtractSecurityPermissionSet (declarative_security);
5550 if (a.Target == AttributeTargets.Method) {
5551 method_data.MethodBuilder.SetCustomAttribute (cb);
5555 if (a.Target == AttributeTargets.ReturnValue) {
5556 if (return_attributes == null)
5557 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5559 return_attributes.ApplyAttributeBuilder (a, cb);
5563 ApplyToExtraTarget (a, cb);
5566 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5568 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5571 public override bool Define()
5573 throw new NotSupportedException ();
5576 public virtual void Emit (TypeContainer container)
5578 method_data.Emit (container, this);
5580 if (declarative_security != null) {
5581 foreach (DictionaryEntry de in declarative_security) {
5582 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5589 public override bool IsClsCompliaceRequired(DeclSpace ds)
5594 public bool IsDuplicateImplementation (MethodCore method)
5596 if (Name != method.Name)
5599 Type[] param_types = method.ParameterTypes;
5601 if (param_types.Length != ParameterTypes.Length)
5604 for (int i = 0; i < param_types.Length; i++)
5605 if (param_types [i] != ParameterTypes [i])
5608 Report.SymbolRelatedToPreviousError (method);
5609 Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
5613 public new Location Location {
5615 return base.Location;
5620 // Represents header string for documentation comment.
5622 public override string DocCommentHeader {
5623 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5626 protected override void VerifyObsoleteAttribute()
5633 // Properties and Indexers both generate PropertyBuilders, we use this to share
5634 // their common bits.
5636 abstract public class PropertyBase : MethodCore {
5638 public class GetMethod: PropertyMethod
5640 static string[] attribute_targets = new string [] { "method", "return" };
5642 public GetMethod (MethodCore method):
5643 base (method, "get_")
5647 public GetMethod (MethodCore method, Accessor accessor):
5648 base (method, accessor, "get_")
5652 public override MethodBuilder Define(TypeContainer container)
5654 base.Define (container);
5656 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5658 if (!method_data.Define (container))
5661 return method_data.MethodBuilder;
5664 public override string GetSignatureForError (TypeContainer tc)
5666 return String.Concat (base.GetSignatureForError (tc), ".get");
5669 public override Type ReturnType {
5671 return method.MemberType;
5675 public override string[] ValidAttributeTargets {
5677 return attribute_targets;
5682 public class SetMethod: PropertyMethod {
5684 static string[] attribute_targets = new string [] { "method", "param", "return" };
5685 ImplicitParameter param_attr;
5687 public SetMethod (MethodCore method):
5688 base (method, "set_")
5692 public SetMethod (MethodCore method, Accessor accessor):
5693 base (method, accessor, "set_")
5697 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5699 if (a.Target == AttributeTargets.Parameter) {
5700 if (param_attr == null)
5701 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5703 param_attr.ApplyAttributeBuilder (a, cb);
5707 base.ApplyAttributeBuilder (a, cb);
5710 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5712 Parameter [] parms = new Parameter [1];
5713 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
5714 Parameters parameters = new Parameters (parms, null, method.Location);
5716 bool old_unsafe = ec.InUnsafe;
5717 ec.InUnsafe = InUnsafe;
5718 Type [] types = parameters.GetParameterInfo (ec);
5719 ec.InUnsafe = old_unsafe;
5721 return new InternalParameters (types, parameters);
5724 public override MethodBuilder Define (TypeContainer container)
5726 if (container.EmitContext == null)
5727 throw new InternalErrorException ("SetMethod.Define called too early");
5729 base.Define (container);
5731 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5733 if (!method_data.Define (container))
5736 return method_data.MethodBuilder;
5739 public override string GetSignatureForError (TypeContainer tc)
5741 return String.Concat (base.GetSignatureForError (tc), ".set");
5744 public override Type[] ParameterTypes {
5746 return new Type[] { method.MemberType };
5750 public override Type ReturnType {
5752 return TypeManager.void_type;
5756 public override string[] ValidAttributeTargets {
5758 return attribute_targets;
5763 static string[] attribute_targets = new string [] { "property" };
5765 public abstract class PropertyMethod: AbstractPropertyEventMethod
5767 protected readonly MethodCore method;
5768 protected MethodAttributes flags;
5770 public PropertyMethod (MethodCore method, string prefix)
5771 : base (method, prefix)
5773 this.method = method;
5774 Parent = method.Parent;
5777 public PropertyMethod (MethodCore method, Accessor accessor,
5779 : base (method, accessor, prefix)
5781 this.method = method;
5782 Parent = method.Parent;
5783 this.ModFlags = accessor.ModFlags;
5785 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
5786 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
5787 Environment.Exit (1);
5791 public override AttributeTargets AttributeTargets {
5793 return AttributeTargets.Method;
5797 public override bool IsClsCompliaceRequired(DeclSpace ds)
5799 return method.IsClsCompliaceRequired (ds);
5802 public InternalParameters ParameterInfo
5805 return method_data.ParameterInfo;
5809 public virtual MethodBuilder Define (TypeContainer container)
5812 // Check for custom access modifier
5814 if (ModFlags == 0) {
5815 ModFlags = method.ModFlags;
5816 flags = method.flags;
5818 CheckModifiers (container, ModFlags);
5819 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
5820 flags = Modifiers.MethodAttr (ModFlags);
5821 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
5828 public override Type[] ParameterTypes {
5830 return TypeManager.NoTypes;
5834 public override EmitContext CreateEmitContext (TypeContainer tc,
5837 return new EmitContext (
5838 tc, method.Parent, method.Location, ig, ReturnType,
5839 method.ModFlags, false);
5842 public override ObsoleteAttribute GetObsoleteAttribute ()
5844 return method.GetObsoleteAttribute (method.Parent);
5847 public override string GetSignatureForError (TypeContainer tc)
5849 return String.Concat (tc.Name, '.', method.Name);
5852 void CheckModifiers (TypeContainer container, int modflags)
5855 int mflags = method.ModFlags & Modifiers.Accessibility;
5857 if ((mflags & Modifiers.PUBLIC) != 0) {
5858 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
5860 else if ((mflags & Modifiers.PROTECTED) != 0) {
5861 if ((mflags & Modifiers.INTERNAL) != 0)
5862 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
5864 flags |= Modifiers.PRIVATE;
5866 else if ((mflags & Modifiers.INTERNAL) != 0)
5867 flags |= Modifiers.PRIVATE;
5869 if ((mflags == modflags) || (modflags & (~flags)) != 0)
5870 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
5871 GetSignatureForError (container));
5876 public PropertyMethod Get, Set;
5877 public PropertyBuilder PropertyBuilder;
5878 public MethodBuilder GetBuilder, SetBuilder;
5880 protected EmitContext ec;
5882 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
5883 int allowed_mod, bool is_iface, MemberName name,
5884 Parameters parameters, Attributes attrs,
5886 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
5887 attrs, parameters, loc)
5891 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5893 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5894 a.Error_InvalidSecurityParent ();
5898 PropertyBuilder.SetCustomAttribute (cb);
5901 public override AttributeTargets AttributeTargets {
5903 return AttributeTargets.Property;
5907 public override bool Define ()
5912 if (!IsTypePermitted ())
5918 protected override bool DoDefine ()
5920 if (!base.DoDefine ())
5924 // Accessors modifiers check
5926 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
5927 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
5928 GetSignatureForError ());
5932 if ((Get.IsDummy || Set.IsDummy)
5933 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
5934 Report.Error (276, Location,
5935 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
5936 GetSignatureForError ());
5940 if (MemberType.IsAbstract && MemberType.IsSealed) {
5941 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
5945 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
5949 public override string GetSignatureForError()
5951 if (PropertyBuilder == null)
5952 return GetSignatureForError (Parent);
5954 return TypeManager.CSharpSignature (PropertyBuilder, false);
5958 protected override bool CheckForDuplications ()
5960 ArrayList ar = Parent.Indexers;
5962 int arLen = ar.Count;
5964 for (int i = 0; i < arLen; i++) {
5965 Indexer m = (Indexer) ar [i];
5966 if (IsDuplicateImplementation (m))
5971 ar = Parent.Properties;
5973 int arLen = ar.Count;
5975 for (int i = 0; i < arLen; i++) {
5976 Property m = (Property) ar [i];
5977 if (IsDuplicateImplementation (m))
5985 // TODO: rename to Resolve......
5986 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
5988 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
5989 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
5991 if (base_property == null)
5994 base_ret_type = base_property.PropertyType;
5995 MethodInfo get_accessor = base_property.GetGetMethod (true);
5996 MethodInfo set_accessor = base_property.GetSetMethod (true);
5997 MethodAttributes get_accessor_access, set_accessor_access;
5999 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6000 if (Get != null && !Get.IsDummy && get_accessor == null) {
6001 Report.SymbolRelatedToPreviousError (base_property);
6002 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6005 if (Set != null && !Set.IsDummy && set_accessor == null) {
6006 Report.SymbolRelatedToPreviousError (base_property);
6007 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6012 // Check base class accessors access
6014 get_accessor_access = set_accessor_access = 0;
6015 if ((ModFlags & Modifiers.NEW) == 0) {
6016 if (get_accessor != null) {
6017 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6018 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6020 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6021 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6022 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6025 if (set_accessor != null) {
6026 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6027 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6029 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6030 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6031 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6036 // Get the less restrictive access
6038 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6041 public override void Emit ()
6044 // The PropertyBuilder can be null for explicit implementations, in that
6045 // case, we do not actually emit the ".property", so there is nowhere to
6046 // put the attribute
6048 if (PropertyBuilder != null && OptAttributes != null)
6049 OptAttributes.Emit (ec, this);
6061 /// Tests whether accessors are not in collision with some method (CS0111)
6063 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6065 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6068 protected override void UpdateMemberName ()
6070 base.UpdateMemberName ();
6072 Get.UpdateName (this);
6073 Set.UpdateName (this);
6076 protected override bool VerifyClsCompliance (DeclSpace ds)
6078 if (!base.VerifyClsCompliance (ds))
6081 if ((Get.ModFlags != ModFlags && !Get.IsDummy) || (Set.ModFlags != ModFlags && !Set.IsDummy)) {
6082 Report.Error (3025, Get.ModFlags != ModFlags ? Get.Location : Set.Location,
6083 "CLS-compliant accessors must have the same accessibility as their property");
6088 public override string[] ValidAttributeTargets {
6090 return attribute_targets;
6095 // Represents header string for documentation comment.
6097 public override string DocCommentHeader {
6098 get { return "P:"; }
6102 public class Property : PropertyBase, IIteratorContainer {
6103 const int AllowedModifiers =
6106 Modifiers.PROTECTED |
6107 Modifiers.INTERNAL |
6111 Modifiers.OVERRIDE |
6112 Modifiers.ABSTRACT |
6115 Modifiers.METHOD_YIELDS |
6118 const int AllowedInterfaceModifiers =
6121 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6122 MemberName name, Attributes attrs, Accessor get_block,
6123 Accessor set_block, Location loc)
6124 : base (ds, type, mod,
6125 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6126 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6129 if (get_block == null)
6130 Get = new GetMethod (this);
6132 Get = new GetMethod (this, get_block);
6134 if (set_block == null)
6135 Set = new SetMethod (this);
6137 Set = new SetMethod (this, set_block);
6140 public override bool Define ()
6142 if (!base.Define ())
6148 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6152 GetBuilder = Get.Define (Parent);
6153 if (GetBuilder == null)
6157 // Setup iterator if we are one
6159 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6160 Iterator iterator = new Iterator (
6161 Parent, "get", MemberType,
6162 TypeManager.NoTypes, Get.ParameterInfo,
6163 ModFlags, Get.Block, Location);
6165 if (!iterator.DefineIterator ())
6167 Get.Block = iterator.Block;
6172 SetBuilder = Set.Define (Parent);
6173 if (SetBuilder == null)
6176 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6179 // FIXME - PropertyAttributes.HasDefault ?
6181 PropertyAttributes prop_attr = PropertyAttributes.None;
6183 prop_attr |= PropertyAttributes.RTSpecialName |
6184 PropertyAttributes.SpecialName;
6186 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6187 Name, prop_attr, MemberType, null);
6190 PropertyBuilder.SetGetMethod (GetBuilder);
6193 PropertyBuilder.SetSetMethod (SetBuilder);
6195 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6199 public void SetYields ()
6201 ModFlags |= Modifiers.METHOD_YIELDS;
6206 /// Gigantic workaround for lameness in SRE follows :
6207 /// This class derives from EventInfo and attempts to basically
6208 /// wrap around the EventBuilder so that FindMembers can quickly
6209 /// return this in it search for members
6211 public class MyEventBuilder : EventInfo {
6214 // We use this to "point" to our Builder which is
6215 // not really a MemberInfo
6217 EventBuilder MyBuilder;
6220 // We "catch" and wrap these methods
6222 MethodInfo raise, remove, add;
6224 EventAttributes attributes;
6225 Type declaring_type, reflected_type, event_type;
6230 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6232 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6234 // And now store the values in our own fields.
6236 declaring_type = type_builder;
6238 reflected_type = type_builder;
6240 attributes = event_attr;
6243 this.event_type = event_type;
6247 // Methods that you have to override. Note that you only need
6248 // to "implement" the variants that take the argument (those are
6249 // the "abstract" methods, the others (GetAddMethod()) are
6252 public override MethodInfo GetAddMethod (bool nonPublic)
6257 public override MethodInfo GetRemoveMethod (bool nonPublic)
6262 public override MethodInfo GetRaiseMethod (bool nonPublic)
6268 // These methods make "MyEventInfo" look like a Builder
6270 public void SetRaiseMethod (MethodBuilder raiseMethod)
6272 raise = raiseMethod;
6273 MyBuilder.SetRaiseMethod (raiseMethod);
6276 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6278 remove = removeMethod;
6279 MyBuilder.SetRemoveOnMethod (removeMethod);
6282 public void SetAddOnMethod (MethodBuilder addMethod)
6285 MyBuilder.SetAddOnMethod (addMethod);
6288 public void SetCustomAttribute (CustomAttributeBuilder cb)
6290 MyBuilder.SetCustomAttribute (cb);
6293 public override object [] GetCustomAttributes (bool inherit)
6295 // FIXME : There's nothing which can be seemingly done here because
6296 // we have no way of getting at the custom attribute objects of the
6301 public override object [] GetCustomAttributes (Type t, bool inherit)
6303 // FIXME : Same here !
6307 public override bool IsDefined (Type t, bool b)
6312 public override EventAttributes Attributes {
6318 public override string Name {
6324 public override Type DeclaringType {
6326 return declaring_type;
6330 public override Type ReflectedType {
6332 return reflected_type;
6336 public Type EventType {
6342 public void SetUsed ()
6344 if (my_event != null)
6345 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6350 /// For case when event is declared like property (with add and remove accessors).
6352 public class EventProperty: Event {
6354 static string[] attribute_targets = new string [] { "event", "property" };
6356 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6357 bool is_iface, MemberName name, Object init,
6358 Attributes attrs, Accessor add, Accessor remove,
6360 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6362 Add = new AddDelegateMethod (this, add);
6363 Remove = new RemoveDelegateMethod (this, remove);
6365 // For this event syntax we don't report error CS0067
6366 // because it is hard to do it.
6370 public override string[] ValidAttributeTargets {
6372 return attribute_targets;
6378 /// Event is declared like field.
6380 public class EventField: Event {
6382 static string[] attribute_targets = new string [] { "event", "field", "method" };
6383 static string[] attribute_targets_interface = new string[] { "event", "method" };
6385 public EventField (TypeContainer parent, Expression type, int mod_flags,
6386 bool is_iface, MemberName name, Object init,
6387 Attributes attrs, Location loc)
6388 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6390 Add = new AddDelegateMethod (this);
6391 Remove = new RemoveDelegateMethod (this);
6394 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6396 if (a.Target == AttributeTargets.Field) {
6397 FieldBuilder.SetCustomAttribute (cb);
6401 if (a.Target == AttributeTargets.Method) {
6402 Add.ApplyAttributeBuilder (a, cb);
6403 Remove.ApplyAttributeBuilder (a, cb);
6407 base.ApplyAttributeBuilder (a, cb);
6410 public override string[] ValidAttributeTargets {
6412 return IsInterface ? attribute_targets_interface : attribute_targets;
6417 public abstract class Event : FieldBase {
6419 protected sealed class AddDelegateMethod: DelegateMethod
6422 public AddDelegateMethod (Event method):
6423 base (method, "add_")
6427 public AddDelegateMethod (Event method, Accessor accessor):
6428 base (method, accessor, "add_")
6432 protected override MethodInfo DelegateMethodInfo {
6434 return TypeManager.delegate_combine_delegate_delegate;
6440 protected sealed class RemoveDelegateMethod: DelegateMethod
6442 public RemoveDelegateMethod (Event method):
6443 base (method, "remove_")
6447 public RemoveDelegateMethod (Event method, Accessor accessor):
6448 base (method, accessor, "remove_")
6452 protected override MethodInfo DelegateMethodInfo {
6454 return TypeManager.delegate_remove_delegate_delegate;
6460 public abstract class DelegateMethod: AbstractPropertyEventMethod
6462 protected readonly Event method;
6463 ImplicitParameter param_attr;
6465 static string[] attribute_targets = new string [] { "method", "param", "return" };
6467 public DelegateMethod (Event method, string prefix)
6468 : base (method, prefix)
6470 this.method = method;
6473 public DelegateMethod (Event method, Accessor accessor, string prefix)
6474 : base (method, accessor, prefix)
6476 this.method = method;
6479 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6481 if (a.Target == AttributeTargets.Parameter) {
6482 if (param_attr == null)
6483 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6485 param_attr.ApplyAttributeBuilder (a, cb);
6489 base.ApplyAttributeBuilder (a, cb);
6492 public override AttributeTargets AttributeTargets {
6494 return AttributeTargets.Method;
6498 public override bool IsClsCompliaceRequired(DeclSpace ds)
6500 return method.IsClsCompliaceRequired (ds);
6503 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6505 method_data = new MethodData (method, ip, method.ModFlags,
6506 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6508 if (!method_data.Define (container))
6511 MethodBuilder mb = method_data.MethodBuilder;
6512 mb.DefineParameter (1, ParameterAttributes.None, "value");
6517 public override void Emit (TypeContainer tc)
6519 if (block != null) {
6524 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6525 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6527 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6528 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6529 ig.Emit (OpCodes.Ldsfld, field_info);
6530 ig.Emit (OpCodes.Ldarg_0);
6531 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6532 ig.Emit (OpCodes.Castclass, method.MemberType);
6533 ig.Emit (OpCodes.Stsfld, field_info);
6535 ig.Emit (OpCodes.Ldarg_0);
6536 ig.Emit (OpCodes.Ldarg_0);
6537 ig.Emit (OpCodes.Ldfld, field_info);
6538 ig.Emit (OpCodes.Ldarg_1);
6539 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6540 ig.Emit (OpCodes.Castclass, method.MemberType);
6541 ig.Emit (OpCodes.Stfld, field_info);
6543 ig.Emit (OpCodes.Ret);
6546 protected abstract MethodInfo DelegateMethodInfo { get; }
6548 public override Type[] ParameterTypes {
6550 return new Type[] { method.MemberType };
6554 public override Type ReturnType {
6556 return TypeManager.void_type;
6560 public override EmitContext CreateEmitContext (TypeContainer tc,
6563 return new EmitContext (
6564 tc, method.Parent, Location, ig, ReturnType,
6565 method.ModFlags, false);
6568 public override string GetSignatureForError (TypeContainer tc)
6570 return String.Concat (tc.Name, '.', method.Name);
6573 public override ObsoleteAttribute GetObsoleteAttribute ()
6575 return method.GetObsoleteAttribute (method.Parent);
6578 public override string[] ValidAttributeTargets {
6580 return attribute_targets;
6586 const int AllowedModifiers =
6589 Modifiers.PROTECTED |
6590 Modifiers.INTERNAL |
6595 Modifiers.OVERRIDE |
6599 const int AllowedInterfaceModifiers =
6602 public DelegateMethod Add, Remove;
6603 public MyEventBuilder EventBuilder;
6604 public MethodBuilder AddBuilder, RemoveBuilder;
6606 public Event (TypeContainer parent, Expression type, int mod_flags,
6607 bool is_iface, MemberName name, Object init, Attributes attrs,
6609 : base (parent, type, mod_flags,
6610 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6611 name, init, attrs, loc)
6613 IsInterface = is_iface;
6616 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6618 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6619 a.Error_InvalidSecurityParent ();
6623 EventBuilder.SetCustomAttribute (cb);
6626 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6628 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6631 public override AttributeTargets AttributeTargets {
6633 return AttributeTargets.Event;
6637 public override bool Define ()
6639 EventAttributes e_attr;
6640 e_attr = EventAttributes.None;
6645 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6646 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6647 "': abstract event can not have an initializer");
6651 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6652 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6653 "' : event must be of a delegate type");
6657 EmitContext ec = Parent.EmitContext;
6659 throw new InternalErrorException ("Event.Define called too early?");
6660 bool old_unsafe = ec.InUnsafe;
6661 ec.InUnsafe = InUnsafe;
6663 Parameter [] parms = new Parameter [1];
6664 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6665 Parameters parameters = new Parameters (parms, null, Location);
6666 Type [] types = parameters.GetParameterInfo (ec);
6667 InternalParameters ip = new InternalParameters (types, parameters);
6669 ec.InUnsafe = old_unsafe;
6675 // Now define the accessors
6678 AddBuilder = Add.Define (Parent, ip);
6679 if (AddBuilder == null)
6682 RemoveBuilder = Remove.Define (Parent, ip);
6683 if (RemoveBuilder == null)
6686 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6688 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6689 FieldBuilder = Parent.TypeBuilder.DefineField (
6691 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6692 TypeManager.RegisterPrivateFieldOfEvent (
6693 (EventInfo) EventBuilder, FieldBuilder);
6694 TypeManager.RegisterFieldBase (FieldBuilder, this);
6697 EventBuilder.SetAddOnMethod (AddBuilder);
6698 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6700 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6704 protected override bool CheckBase ()
6706 if (!base.CheckBase ())
6709 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6710 if (!(conflict_symbol is EventInfo)) {
6711 Report.SymbolRelatedToPreviousError (conflict_symbol);
6712 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6720 public override void Emit ()
6722 if (OptAttributes != null) {
6723 EmitContext ec = new EmitContext (
6724 Parent, Location, null, MemberType, ModFlags);
6725 OptAttributes.Emit (ec, this);
6730 Remove.Emit (Parent);
6736 public override string GetSignatureForError ()
6738 if (EventBuilder == null)
6739 return base.GetSignatureForError (Parent);
6741 return TypeManager.GetFullNameSignature (EventBuilder);
6745 // Represents header string for documentation comment.
6747 public override string DocCommentHeader {
6748 get { return "E:"; }
6753 public class Indexer : PropertyBase {
6755 class GetIndexerMethod: GetMethod
6757 public GetIndexerMethod (MethodCore method):
6762 public GetIndexerMethod (MethodCore method, Accessor accessor):
6763 base (method, accessor)
6767 public override Type[] ParameterTypes {
6769 return method.ParameterTypes;
6774 class SetIndexerMethod: SetMethod
6776 readonly Parameters parameters;
6778 public SetIndexerMethod (MethodCore method):
6783 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
6784 base (method, accessor)
6786 this.parameters = parameters;
6789 public override Type[] ParameterTypes {
6791 int top = method.ParameterTypes.Length;
6792 Type [] set_pars = new Type [top + 1];
6793 method.ParameterTypes.CopyTo (set_pars, 0);
6794 set_pars [top] = method.MemberType;
6799 protected override InternalParameters GetParameterInfo (EmitContext ec)
6801 Parameter [] fixed_parms = parameters.FixedParameters;
6803 if (fixed_parms == null){
6804 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
6805 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6806 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6808 // Here is the problem: the `value' parameter has
6809 // to come *after* the array parameter in the declaration
6811 // X (object [] x, Type value)
6814 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6815 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6819 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
6821 fixed_parms.CopyTo (tmp, 0);
6822 tmp [fixed_parms.Length] = new Parameter (
6823 method.Type, "value", Parameter.Modifier.NONE, null);
6825 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
6826 Type [] types = set_formal_params.GetParameterInfo (ec);
6828 return new InternalParameters (types, set_formal_params);
6833 const int AllowedModifiers =
6836 Modifiers.PROTECTED |
6837 Modifiers.INTERNAL |
6841 Modifiers.OVERRIDE |
6846 const int AllowedInterfaceModifiers =
6850 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
6851 bool is_iface, Parameters parameters, Attributes attrs,
6852 Accessor get_block, Accessor set_block, Location loc)
6853 : base (ds, type, mod,
6854 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6855 is_iface, name, parameters, attrs, loc)
6857 if (get_block == null)
6858 Get = new GetIndexerMethod (this);
6860 Get = new GetIndexerMethod (this, get_block);
6862 if (set_block == null)
6863 Set = new SetIndexerMethod (this);
6865 Set = new SetIndexerMethod (this, parameters, set_block);
6868 public override bool Define ()
6870 PropertyAttributes prop_attr =
6871 PropertyAttributes.RTSpecialName |
6872 PropertyAttributes.SpecialName;
6874 if (!base.Define ())
6877 if (MemberType == TypeManager.void_type) {
6878 Report.Error (620, Location, "Indexers cannot have void type");
6882 if (OptAttributes != null) {
6883 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
6884 if (indexer_attr != null) {
6885 // Remove the attribute from the list because it is not emitted
6886 OptAttributes.Attrs.Remove (indexer_attr);
6888 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
6890 if (IsExplicitImpl) {
6891 Report.Error (415, indexer_attr.Location,
6892 "The 'IndexerName' attribute is valid only on an" +
6893 "indexer that is not an explicit interface member declaration");
6897 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6898 Report.Error (609, indexer_attr.Location,
6899 "Cannot set the 'IndexerName' attribute on an indexer marked override");
6903 if (!Tokenizer.IsValidIdentifier (ShortName)) {
6904 Report.Error (633, indexer_attr.Location,
6905 "The argument to the 'IndexerName' attribute must be a valid identifier");
6909 UpdateMemberName ();
6913 if (InterfaceType != null) {
6914 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
6915 if (base_IndexerName != Name)
6916 ShortName = base_IndexerName;
6917 UpdateMemberName ();
6920 if (!Parent.AddToMemberContainer (this, true) ||
6921 !Parent.AddToMemberContainer (Get, true) || !Parent.AddToMemberContainer (Set, true))
6927 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6929 GetBuilder = Get.Define (Parent);
6930 if (GetBuilder == null)
6935 SetBuilder = Set.Define (Parent);
6936 if (SetBuilder == null)
6941 // Now name the parameters
6943 Parameter [] p = Parameters.FixedParameters;
6945 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
6946 Report.Error (631, Location, "ref and out are not valid in this context");
6952 for (i = 0; i < p.Length; ++i) {
6954 GetBuilder.DefineParameter (
6955 i + 1, p [i].Attributes, p [i].Name);
6958 SetBuilder.DefineParameter (
6959 i + 1, p [i].Attributes, p [i].Name);
6963 SetBuilder.DefineParameter (
6964 i + 1, ParameterAttributes.None, "value");
6966 if (i != ParameterTypes.Length) {
6967 Parameter array_param = Parameters.ArrayParameter;
6969 SetBuilder.DefineParameter (
6970 i + 1, array_param.Attributes, array_param.Name);
6974 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6975 Name, prop_attr, MemberType, ParameterTypes);
6978 PropertyBuilder.SetGetMethod (GetBuilder);
6981 PropertyBuilder.SetSetMethod (SetBuilder);
6983 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
6988 public override string GetSignatureForError ()
6990 if (PropertyBuilder == null)
6991 return GetSignatureForError (Parent);
6993 return TypeManager.CSharpSignature (PropertyBuilder, true);
6996 public override string GetSignatureForError(TypeContainer tc)
6998 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7002 public class Operator : MethodCore, IIteratorContainer {
7004 const int AllowedModifiers =
7010 public enum OpType : byte {
7020 // Unary and Binary operators
7043 // Implicit and Explicit
7048 public readonly OpType OperatorType;
7049 public MethodBuilder OperatorMethodBuilder;
7051 public Method OperatorMethod;
7053 static string[] attribute_targets = new string [] { "method", "return" };
7055 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7056 int mod_flags, Parameters parameters,
7057 ToplevelBlock block, Attributes attrs, Location loc)
7058 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7059 new MemberName ("op_" + type), attrs, parameters, loc)
7061 OperatorType = type;
7065 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7067 OperatorMethod.ApplyAttributeBuilder (a, cb);
7070 public override AttributeTargets AttributeTargets {
7072 return AttributeTargets.Method;
7076 protected override bool CheckForDuplications()
7078 ArrayList ar = Parent.Operators;
7080 int arLen = ar.Count;
7082 for (int i = 0; i < arLen; i++) {
7083 Operator o = (Operator) ar [i];
7084 if (IsDuplicateImplementation (o))
7089 ar = Parent.Methods;
7091 int arLen = ar.Count;
7093 for (int i = 0; i < arLen; i++) {
7094 Method m = (Method) ar [i];
7095 if (IsDuplicateImplementation (m))
7103 public override bool Define ()
7106 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7107 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7108 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7115 if (MemberType == TypeManager.void_type) {
7116 Report.Error (590, Location, "User-defined operators cannot return void");
7120 OperatorMethod = new Method (
7121 Parent, Type, ModFlags, false, MemberName,
7122 Parameters, OptAttributes, Location);
7124 OperatorMethod.Block = Block;
7125 OperatorMethod.IsOperator = true;
7126 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7127 OperatorMethod.Define ();
7129 if (OperatorMethod.MethodBuilder == null)
7132 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7134 parameter_types = OperatorMethod.ParameterTypes;
7135 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7136 Type return_type = OperatorMethod.ReturnType;
7137 Type first_arg_type = parameter_types [0];
7142 // Rules for conversion operators
7144 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7145 if (first_arg_type == return_type && first_arg_type == declaring_type){
7148 "User-defined conversion cannot take an object of the " +
7149 "enclosing type and convert to an object of the enclosing" +
7154 if (first_arg_type != declaring_type && return_type != declaring_type){
7157 "User-defined conversion must convert to or from the " +
7162 if (first_arg_type == TypeManager.object_type ||
7163 return_type == TypeManager.object_type){
7166 "User-defined conversion cannot convert to or from " +
7171 if (first_arg_type.IsInterface || return_type.IsInterface){
7174 "User-defined conversion cannot convert to or from an " +
7179 if (first_arg_type.IsSubclassOf (return_type)
7180 || return_type.IsSubclassOf (first_arg_type)){
7181 if (declaring_type.IsSubclassOf (return_type)) {
7182 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7185 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7188 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7189 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7190 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");
7193 } else if (Parameters.FixedParameters.Length == 1) {
7194 // Checks for Unary operators
7196 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7197 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7198 Report.Error (448, Location,
7199 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7202 if (first_arg_type != declaring_type) {
7204 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7209 if (first_arg_type != declaring_type){
7212 "The parameter of a unary operator must be the " +
7217 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7218 if (return_type != TypeManager.bool_type){
7221 "The return type of operator True or False " +
7228 // Checks for Binary operators
7230 if (first_arg_type != declaring_type &&
7231 parameter_types [1] != declaring_type){
7234 "One of the parameters of a binary operator must " +
7235 "be the containing type");
7243 public override void Emit ()
7246 // abstract or extern methods have no bodies
7248 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7251 OperatorMethod.Emit ();
7255 // Operator cannot be override
7256 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7261 public static string GetName (OpType ot)
7264 case OpType.LogicalNot:
7266 case OpType.OnesComplement:
7268 case OpType.Increment:
7270 case OpType.Decrement:
7276 case OpType.Addition:
7278 case OpType.Subtraction:
7280 case OpType.UnaryPlus:
7282 case OpType.UnaryNegation:
7284 case OpType.Multiply:
7286 case OpType.Division:
7288 case OpType.Modulus:
7290 case OpType.BitwiseAnd:
7292 case OpType.BitwiseOr:
7294 case OpType.ExclusiveOr:
7296 case OpType.LeftShift:
7298 case OpType.RightShift:
7300 case OpType.Equality:
7302 case OpType.Inequality:
7304 case OpType.GreaterThan:
7306 case OpType.LessThan:
7308 case OpType.GreaterThanOrEqual:
7310 case OpType.LessThanOrEqual:
7312 case OpType.Implicit:
7314 case OpType.Explicit:
7320 public override string GetSignatureForError (TypeContainer tc)
7322 StringBuilder sb = new StringBuilder ();
7323 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7324 Parameters.FixedParameters [0].GetSignatureForError ());
7326 if (Parameters.FixedParameters.Length > 1) {
7328 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7331 return sb.ToString ();
7334 public override string GetSignatureForError ()
7339 public override string ToString ()
7341 if (OperatorMethod == null)
7344 Type return_type = OperatorMethod.ReturnType;
7345 Type [] param_types = OperatorMethod.ParameterTypes;
7347 if (Parameters.FixedParameters.Length == 1)
7348 return String.Format (
7349 "{0} operator {1}({2})",
7350 TypeManager.CSharpName (return_type),
7351 GetName (OperatorType),
7354 return String.Format (
7355 "{0} operator {1}({2}, {3})",
7356 TypeManager.CSharpName (return_type),
7357 GetName (OperatorType),
7358 param_types [0], param_types [1]);
7361 public override string[] ValidAttributeTargets {
7363 return attribute_targets;
7367 public void SetYields ()
7369 ModFlags |= Modifiers.METHOD_YIELDS;
7374 // This is used to compare method signatures
7376 struct MethodSignature {
7378 public Type RetType;
7379 public Type [] Parameters;
7382 /// This delegate is used to extract methods which have the
7383 /// same signature as the argument
7385 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7387 public MethodSignature (string name, Type ret_type, Type [] parameters)
7392 if (parameters == null)
7393 Parameters = TypeManager.NoTypes;
7395 Parameters = parameters;
7398 public override string ToString ()
7401 if (Parameters.Length != 0){
7402 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7403 for (int i = 0; i < Parameters.Length; i++){
7404 sb.Append (Parameters [i]);
7405 if (i+1 < Parameters.Length)
7408 pars = sb.ToString ();
7411 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7414 public override int GetHashCode ()
7416 return Name.GetHashCode ();
7419 public override bool Equals (Object o)
7421 MethodSignature other = (MethodSignature) o;
7423 if (other.Name != Name)
7426 if (other.RetType != RetType)
7429 if (Parameters == null){
7430 if (other.Parameters == null)
7435 if (other.Parameters == null)
7438 int c = Parameters.Length;
7439 if (other.Parameters.Length != c)
7442 for (int i = 0; i < c; i++)
7443 if (other.Parameters [i] != Parameters [i])
7449 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7451 MethodSignature sig = (MethodSignature) filter_criteria;
7453 if (m.Name != sig.Name)
7457 MethodInfo mi = m as MethodInfo;
7458 PropertyInfo pi = m as PropertyInfo;
7461 ReturnType = mi.ReturnType;
7462 else if (pi != null)
7463 ReturnType = pi.PropertyType;
7468 // we use sig.RetType == null to mean `do not check the
7469 // method return value.
7471 if (sig.RetType != null)
7472 if (ReturnType != sig.RetType)
7477 args = TypeManager.GetArgumentTypes (mi);
7479 args = TypeManager.GetArgumentTypes (pi);
7480 Type [] sigp = sig.Parameters;
7482 if (args.Length != sigp.Length)
7485 for (int i = args.Length; i > 0; ){
7487 if (args [i] != sigp [i])