2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 namespace Mono.CSharp {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
79 public virtual void Emit ()
81 foreach (MemberCore mc in this)
86 public class MethodArrayList: MemberCoreArrayList
94 CachedMethods cached_method;
95 TypeContainer container;
97 public MethodArrayList (TypeContainer container)
99 this.container = container;
103 /// Method container contains Equals method
105 public bool HasEquals {
107 cached_method |= CachedMethods.Equals;
111 return (cached_method & CachedMethods.Equals) != 0;
116 /// Method container contains GetHashCode method
118 public bool HasGetHashCode {
120 cached_method |= CachedMethods.GetHashCode;
124 return (cached_method & CachedMethods.GetHashCode) != 0;
128 public override void DefineContainerMembers ()
130 base.DefineContainerMembers ();
132 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
133 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
139 public sealed class IndexerArrayList: MemberCoreArrayList
142 /// The indexer name for this container
144 public string IndexerName = DefaultIndexerName;
146 bool seen_normal_indexers = false;
148 TypeContainer container;
150 public IndexerArrayList (TypeContainer container)
152 this.container = container;
156 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
157 /// class is consistent. Either it is `Item' or it is the name defined by all the
158 /// indexers with the `IndexerName' attribute.
160 /// Turns out that the IndexerNameAttribute is applied to each indexer,
161 /// but it is never emitted, instead a DefaultMember attribute is attached
164 public override void DefineContainerMembers()
166 base.DefineContainerMembers ();
168 string class_indexer_name = null;
171 // If there's both an explicit and an implicit interface implementation, the
172 // explicit one actually implements the interface while the other one is just
173 // a normal indexer. See bug #37714.
176 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
177 foreach (Indexer i in this) {
178 if (i.InterfaceType != null) {
179 if (seen_normal_indexers)
180 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
184 seen_normal_indexers = true;
186 if (class_indexer_name == null) {
187 class_indexer_name = i.ShortName;
191 if (i.ShortName != class_indexer_name)
192 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
195 if (class_indexer_name != null)
196 IndexerName = class_indexer_name;
199 public override void Emit ()
203 if (!seen_normal_indexers)
206 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
207 container.TypeBuilder.SetCustomAttribute (cb);
211 public class OperatorArrayList: MemberCoreArrayList
213 TypeContainer container;
215 public OperatorArrayList (TypeContainer container)
217 this.container = container;
221 // Operator pair checking
226 public Type ret_type;
227 public Type type1, type2;
229 public Operator.OpType ot;
231 public OperatorEntry (int f, Operator o)
235 ret_type = o.OperatorMethod.ReturnType;
236 Type [] pt = o.OperatorMethod.ParameterTypes;
243 public override int GetHashCode ()
245 return ret_type.GetHashCode ();
248 public override bool Equals (object o)
250 OperatorEntry other = (OperatorEntry) o;
252 if (other.ret_type != ret_type)
254 if (other.type1 != type1)
256 if (other.type2 != type2)
263 // Checks that some operators come in pairs:
269 // They are matched based on the return type and the argument types
271 void CheckPairedOperators ()
273 Hashtable pairs = new Hashtable (null, null);
274 Operator true_op = null;
275 Operator false_op = null;
276 bool has_equality_or_inequality = false;
278 // Register all the operators we care about.
279 foreach (Operator op in this){
282 switch (op.OperatorType){
283 case Operator.OpType.Equality:
285 has_equality_or_inequality = true;
287 case Operator.OpType.Inequality:
289 has_equality_or_inequality = true;
292 case Operator.OpType.True:
295 case Operator.OpType.False:
299 case Operator.OpType.GreaterThan:
301 case Operator.OpType.LessThan:
304 case Operator.OpType.GreaterThanOrEqual:
306 case Operator.OpType.LessThanOrEqual:
312 OperatorEntry oe = new OperatorEntry (reg, op);
314 object o = pairs [oe];
318 oe = (OperatorEntry) o;
323 if (true_op != null){
324 if (false_op == null)
325 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
326 } else if (false_op != null)
327 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
330 // Look for the mistakes.
332 foreach (DictionaryEntry de in pairs){
333 OperatorEntry oe = (OperatorEntry) de.Key;
340 case Operator.OpType.Equality:
343 case Operator.OpType.Inequality:
346 case Operator.OpType.GreaterThan:
349 case Operator.OpType.LessThan:
352 case Operator.OpType.GreaterThanOrEqual:
355 case Operator.OpType.LessThanOrEqual:
359 Report.Error (216, oe.op.Location,
360 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
363 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
364 if (container.Methods == null || !container.Methods.HasEquals)
365 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
367 if (container.Methods == null || !container.Methods.HasGetHashCode)
368 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
372 public override void DefineContainerMembers ()
374 base.DefineContainerMembers ();
375 CheckPairedOperators ();
380 // Whether this is a struct, class or interface
381 public readonly Kind Kind;
383 // Holds a list of classes and structures
386 // Holds the list of properties
387 MemberCoreArrayList properties;
389 // Holds the list of enumerations
390 MemberCoreArrayList enums;
392 // Holds the list of delegates
393 MemberCoreArrayList delegates;
395 // Holds the list of constructors
396 protected MemberCoreArrayList instance_constructors;
398 // Holds the list of fields
399 MemberCoreArrayList fields;
401 // Holds a list of fields that have initializers
402 protected ArrayList initialized_fields;
404 // Holds a list of static fields that have initializers
405 protected ArrayList initialized_static_fields;
407 // Holds the list of constants
408 MemberCoreArrayList constants;
411 MemberCoreArrayList interfaces;
413 // Holds the methods.
414 MethodArrayList methods;
417 protected MemberCoreArrayList events;
419 // Holds the indexers
420 IndexerArrayList indexers;
422 // Holds the operators
423 MemberCoreArrayList operators;
425 // Holds the iterators
428 // Holds the parts of a partial class;
432 // Pointers to the default constructor and the default static constructor
434 protected Constructor default_constructor;
435 protected Constructor default_static_constructor;
438 // Whether we have at least one non-static field
440 bool have_nonstatic_fields = false;
443 // This one is computed after we can distinguish interfaces
444 // from classes from the arraylist `type_bases'
446 string base_class_name;
449 ArrayList type_bases;
451 bool members_defined;
452 bool members_defined_ok;
454 // The interfaces we implement.
455 protected Type [] ifaces;
456 protected Type ptype;
458 // The base member cache and our member cache
459 MemberCache base_cache;
460 MemberCache member_cache;
462 public const string DefaultIndexerName = "Item";
464 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
465 Attributes attrs, Kind kind, Location l)
466 : base (ns, parent, name, attrs, l)
470 types = new ArrayList ();
472 base_class_name = null;
475 public bool AddToMemberContainer (MemberCore symbol)
477 return AddToContainer (symbol, String.Concat (Name, '.', symbol.Name), symbol.Name);
480 bool AddToTypeContainer (DeclSpace ds)
482 return AddToContainer (ds, ds.Name, ds.Basename);
485 public void AddConstant (Const constant)
487 if (!AddToMemberContainer (constant))
490 if (constants == null)
491 constants = new MemberCoreArrayList ();
493 constants.Add (constant);
496 public void AddEnum (Mono.CSharp.Enum e)
498 if (!AddToTypeContainer (e))
502 enums = new MemberCoreArrayList ();
507 public void AddClassOrStruct (TypeContainer c)
509 if (!AddToTypeContainer (c))
515 public void AddDelegate (Delegate d)
517 if (!AddToTypeContainer (d))
520 if (delegates == null)
521 delegates = new MemberCoreArrayList ();
526 public void AddMethod (Method method)
528 if (!AddToMemberContainer (method))
532 methods = new MethodArrayList (this);
534 if (method.Name.IndexOf ('.') != -1)
535 methods.Insert (0, method);
537 methods.Add (method);
540 public void AddConstructor (Constructor c)
542 if (c.Name != Basename) {
543 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
546 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
549 if (default_static_constructor != null) {
550 Report.SymbolRelatedToPreviousError (default_static_constructor);
551 Report.Error (111, c.Location, Error111, Name, c.Name);
555 default_static_constructor = c;
558 if (default_constructor != null) {
559 Report.SymbolRelatedToPreviousError (default_constructor);
560 Report.Error (111, c.Location, Error111, c.Location, Name, c.Name);
563 default_constructor = c;
566 if (instance_constructors == null)
567 instance_constructors = new MemberCoreArrayList ();
569 instance_constructors.Add (c);
573 internal static string Error111 {
575 return "Type '{0}' already defines a member called '{1}' with the same parameter types";
579 public void AddInterface (TypeContainer iface)
581 if (!AddToTypeContainer (iface))
584 if (interfaces == null) {
585 interfaces = new MemberCoreArrayList ();
588 interfaces.Add (iface);
591 public void AddField (FieldMember field)
593 if (!AddToMemberContainer (field))
597 fields = new MemberCoreArrayList ();
601 if (field.HasInitializer){
602 if ((field.ModFlags & Modifiers.STATIC) != 0){
603 if (initialized_static_fields == null)
604 initialized_static_fields = new ArrayList ();
606 initialized_static_fields.Add (field);
608 if (initialized_fields == null)
609 initialized_fields = new ArrayList ();
611 initialized_fields.Add (field);
615 if ((field.ModFlags & Modifiers.STATIC) == 0)
616 have_nonstatic_fields = true;
619 public void AddProperty (Property prop)
621 if (!AddToMemberContainer (prop) ||
622 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
625 if (properties == null)
626 properties = new MemberCoreArrayList ();
628 if (prop.Name.IndexOf ('.') != -1)
629 properties.Insert (0, prop);
631 properties.Add (prop);
634 public void AddEvent (Event e)
636 if (!AddToMemberContainer (e))
639 if (e is EventProperty) {
640 if (!AddToMemberContainer (e.Add))
643 if (!AddToMemberContainer (e.Remove))
648 events = new MemberCoreArrayList ();
655 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
657 public void AddIndexer (Indexer i)
659 if (indexers == null)
660 indexers = new IndexerArrayList (this);
662 if (i.IsExplicitImpl)
663 indexers.Insert (0, i);
668 public void AddOperator (Operator op)
670 if (!AddToMemberContainer (op))
673 if (operators == null)
674 operators = new OperatorArrayList (this);
679 public void AddIterator (Iterator i)
681 if (iterators == null)
682 iterators = new ArrayList ();
687 public void AddType (TypeContainer tc)
692 public void AddPart (ClassPart part)
695 parts = new ArrayList ();
700 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
702 if (a.Type == TypeManager.default_member_type) {
703 if (Indexers != null) {
704 Report.Error (646, a.Location,
705 "Cannot specify the DefaultMember attribute on" +
706 " a type containing an indexer");
711 base.ApplyAttributeBuilder (a, cb);
714 public override AttributeTargets AttributeTargets {
718 return AttributeTargets.Class;
720 return AttributeTargets.Struct;
722 return AttributeTargets.Interface;
724 throw new NotSupportedException ();
729 public ArrayList Types {
735 public MethodArrayList Methods {
741 public ArrayList Constants {
747 public ArrayList Interfaces {
753 public ArrayList Iterators {
761 return base_class_name;
765 public ArrayList Bases {
775 public ArrayList Fields {
781 public ArrayList InstanceConstructors {
783 return instance_constructors;
787 public ArrayList Properties {
793 public ArrayList Events {
799 public ArrayList Enums {
805 public ArrayList Indexers {
811 public ArrayList Operators {
817 public ArrayList Delegates {
823 public ArrayList Parts {
829 public virtual TypeAttributes TypeAttr {
831 return Modifiers.TypeAttr (ModFlags, this);
835 public string IndexerName {
837 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
842 // Emits the instance field initializers
844 public bool EmitFieldInitializers (EmitContext ec)
847 Expression instance_expr;
850 fields = initialized_static_fields;
851 instance_expr = null;
853 fields = initialized_fields;
854 instance_expr = new This (Location.Null).Resolve (ec);
860 foreach (Field f in fields){
861 Expression e = f.GetInitializerExpression (ec);
865 Location l = f.Location;
866 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
867 fe.InstanceExpression = instance_expr;
868 ExpressionStatement a = new Assign (fe, e, l);
870 a = a.ResolveStatement (ec);
874 if (RootContext.Optimize) {
875 Constant c = e as Constant;
877 if (c.IsDefaultValue)
882 a.EmitStatement (ec);
889 // Defines the default constructors
891 protected void DefineDefaultConstructor (bool is_static)
895 // The default constructor is public
896 // If the class is abstract, the default constructor is protected
897 // The default static constructor is private
899 int mods = Modifiers.PUBLIC;
901 mods = Modifiers.STATIC | Modifiers.PRIVATE;
902 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
903 mods = Modifiers.PROTECTED;
905 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
906 new ConstructorBaseInitializer (
907 null, Parameters.EmptyReadOnlyParameters,
913 c.Block = new ToplevelBlock (null, Location);
918 /// The pending methods that need to be implemented
919 // (interfaces or abstract methods)
921 public PendingImplementation Pending;
923 public abstract void Register ();
925 public abstract PendingImplementation GetPendingImplementations ();
927 TypeExpr[] GetPartialBases (out TypeExpr base_class, out bool error)
929 ArrayList ifaces = new ArrayList ();
932 Location base_loc = Location.Null;
934 foreach (ClassPart part in parts) {
935 TypeExpr new_base_class;
936 TypeExpr[] new_ifaces;
938 new_ifaces = part.GetClassBases (out new_base_class, out error);
942 if ((base_class != null) && (new_base_class != null) &&
943 !base_class.Equals (new_base_class)) {
944 Report.Error (263, part.Location,
945 "Partial declarations of `{0}' must " +
946 "not specify different base classes",
949 if (!Location.IsNull (base_loc))
950 Report.LocationOfPreviousError (base_loc);
956 if ((base_class == null) && (new_base_class != null)) {
957 base_class = new_base_class;
958 base_loc = part.Location;
961 if (new_ifaces == null)
964 foreach (TypeExpr iface in new_ifaces) {
966 foreach (TypeExpr old_iface in ifaces) {
967 if (old_iface.Equals (iface)) {
980 TypeExpr[] retval = new TypeExpr [ifaces.Count];
981 ifaces.CopyTo (retval, 0);
985 TypeExpr[] GetNormalBases (out TypeExpr base_class, out bool error)
989 int count = Bases.Count;
992 if (Kind == Kind.Class){
993 TypeExpr name = ResolveBaseTypeExpr (
994 (Expression) Bases [0], false, Location);
1001 if (!name.IsInterface) {
1002 // base_class could be a class, struct, enum, delegate.
1003 // This is validated in GetClassBases.
1009 TypeExpr [] ifaces = new TypeExpr [count-start];
1011 for (i = start, j = 0; i < count; i++, j++){
1012 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1013 if (resolved == null) {
1018 ifaces [j] = resolved;
1026 /// This function computes the Base class and also the
1027 /// list of interfaces that the class or struct @c implements.
1029 /// The return value is an array (might be null) of
1030 /// interfaces implemented (as Types).
1032 /// The @base_class argument is set to the base object or null
1033 /// if this is `System.Object'.
1035 TypeExpr [] GetClassBases (out TypeExpr base_class, out bool error)
1044 ifaces = GetPartialBases (out base_class, out error);
1045 else if (Bases == null){
1049 ifaces = GetNormalBases (out base_class, out error);
1054 if ((base_class != null) && (Kind == Kind.Class)){
1056 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1057 Report.Error (1521, base_class.Location, "Invalid base type");
1062 if (base_class.IsSealed){
1064 Report.SymbolRelatedToPreviousError (base_class.Type);
1065 if (base_class.Type.IsAbstract) {
1066 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1068 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1073 if (!base_class.CanInheritFrom ()){
1074 Report.Error (644, Location,
1075 "`{0}' cannot inherit from special class `{1}'",
1076 Name, base_class.Name);
1081 if (!base_class.AsAccessible (this, ModFlags)) {
1082 Report.SymbolRelatedToPreviousError (base_class.Type);
1083 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1084 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1088 if (base_class != null)
1089 base_class_name = base_class.Name;
1094 int count = ifaces != null ? ifaces.Length : 0;
1096 for (i = 0; i < count; i++) {
1097 TypeExpr iface = (TypeExpr) ifaces [i];
1099 if (!iface.IsInterface) {
1101 if (Kind != Kind.Class) {
1102 string what = Kind == Kind.Struct ? "Struct" : "Interface";
1104 Report.Error (527, Location,
1105 "In {0} `{1}', type `{2}' is not "+
1106 "an interface", what, Name, iface.Name);
1108 else if (base_class != null)
1109 Report.Error (1721, Location,
1110 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1113 Report.Error (1722, Location,
1114 "In Class `{0}', `{1}' is not " +
1115 "an interface, a base class must be listed first", Name, iface.Name);
1120 for (int x = 0; x < i; x++) {
1121 if (iface.Equals (ifaces [x])) {
1122 Report.Error (528, Location,
1123 "`{0}' is already listed in " +
1124 "interface list", iface.Name);
1129 if ((Kind == Kind.Interface) &&
1130 !iface.AsAccessible (Parent, ModFlags)) {
1131 Report.Error (61, Location,
1132 "Inconsistent accessibility: base " +
1133 "interface `{0}' is less accessible " +
1134 "than interface `{1}'", iface.Name,
1149 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1151 public override TypeBuilder DefineType ()
1153 if (TypeBuilder != null)
1160 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
1167 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1169 TypeExpr[] iface_exprs = GetClassBases (out base_type, out error);
1173 if (base_type == null) {
1174 if (Kind == Kind.Class){
1175 if (RootContext.StdLib)
1176 base_type = TypeManager.system_object_expr;
1177 else if (Name != "System.Object")
1178 base_type = TypeManager.system_object_expr;
1179 } else if (Kind == Kind.Struct) {
1181 // If we are compiling our runtime,
1182 // and we are defining ValueType, then our
1183 // base is `System.Object'.
1185 if (!RootContext.StdLib && Name == "System.ValueType")
1186 base_type = TypeManager.system_object_expr;
1188 base_type = TypeManager.system_valuetype_expr;
1192 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1193 throw new Exception ();
1195 TypeAttributes type_attributes = TypeAttr;
1197 if (base_type != null) {
1198 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1199 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1200 ptype = base_type.ResolveType (ec);
1201 if (ptype == null) {
1209 if (TypeManager.NamespaceClash (Name, Location)) {
1214 ModuleBuilder builder = CodeGen.Module.Builder;
1215 TypeBuilder = builder.DefineType (
1216 Name, type_attributes, ptype, null);
1219 TypeBuilder builder = Parent.DefineType ();
1220 if (builder == null)
1223 TypeBuilder = builder.DefineNestedType (
1224 Basename, type_attributes, ptype, null);
1227 catch (ArgumentException) {
1228 Report.RuntimeMissingSupport (Location, "static classes");
1233 // Structs with no fields need to have at least one byte.
1234 // The right thing would be to set the PackingSize in a DefineType
1235 // but there are no functions that allow interfaces *and* the size to
1239 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1240 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1241 FieldAttributes.Private);
1244 // add interfaces that were not added at type creation
1245 if (iface_exprs != null) {
1246 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1247 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1248 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1249 if (ifaces == null) {
1254 foreach (Type itype in ifaces)
1255 TypeBuilder.AddInterfaceImplementation (itype);
1257 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1261 // Finish the setup for the EmitContext
1263 ec.ContainerType = TypeBuilder;
1265 TypeManager.AddUserType (Name, TypeBuilder, this);
1267 if (!(this is Iterator))
1268 RootContext.RegisterOrder (this);
1270 if (!DefineNestedTypes ()) {
1279 protected virtual bool DefineNestedTypes ()
1281 if (Interfaces != null) {
1282 foreach (TypeContainer iface in Interfaces)
1283 if (iface.DefineType () == null)
1287 if (Types != null) {
1288 foreach (TypeContainer tc in Types)
1289 if (tc.DefineType () == null)
1293 if (Delegates != null) {
1294 foreach (Delegate d in Delegates)
1295 if (d.DefineType () == null)
1299 if (Enums != null) {
1300 foreach (Enum en in Enums)
1301 if (en.DefineType () == null)
1305 if (Parts != null) {
1306 foreach (ClassPart part in Parts) {
1307 part.TypeBuilder = TypeBuilder;
1309 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1316 static void Error_KeywordNotAllowed (Location loc)
1318 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1322 /// Populates our TypeBuilder with fields and methods
1324 public override bool DefineMembers (TypeContainer container)
1326 if (members_defined)
1327 return members_defined_ok;
1329 members_defined_ok = DoDefineMembers ();
1330 members_defined = true;
1332 return members_defined_ok;
1335 bool DoDefineMembers ()
1338 if ((ModFlags & Modifiers.NEW) != 0)
1339 Error_KeywordNotAllowed (Location);
1341 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1342 if (conflict_symbol == null) {
1343 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1344 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1346 if ((ModFlags & Modifiers.NEW) == 0) {
1347 Report.SymbolRelatedToPreviousError (conflict_symbol);
1348 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1353 DefineContainerMembers (constants);
1354 DefineContainerMembers (fields);
1356 if ((Kind == Kind.Class) && !(this is ClassPart)){
1357 if ((instance_constructors == null) &&
1358 !(this is StaticClass)) {
1359 if (default_constructor == null)
1360 DefineDefaultConstructor (false);
1363 if (initialized_static_fields != null &&
1364 default_static_constructor == null)
1365 DefineDefaultConstructor (true);
1368 if (Kind == Kind.Struct){
1370 // Structs can not have initialized instance
1373 if (initialized_static_fields != null &&
1374 default_static_constructor == null)
1375 DefineDefaultConstructor (true);
1377 if (initialized_fields != null)
1378 ReportStructInitializedInstanceError ();
1381 Pending = GetPendingImplementations ();
1383 if (parts != null) {
1384 foreach (ClassPart part in parts) {
1385 if (!part.DefineMembers (this))
1391 // Constructors are not in the defined_names array
1393 DefineContainerMembers (instance_constructors);
1395 if (default_static_constructor != null)
1396 default_static_constructor.Define ();
1398 DefineContainerMembers (properties);
1399 DefineContainerMembers (events);
1400 DefineContainerMembers (indexers);
1401 DefineContainerMembers (methods);
1402 DefineContainerMembers (operators);
1403 DefineContainerMembers (enums);
1404 DefineContainerMembers (delegates);
1407 if (!(this is ClassPart))
1408 member_cache = new MemberCache (this);
1411 if (parts != null) {
1412 foreach (ClassPart part in parts)
1413 part.member_cache = member_cache;
1416 if (iterators != null) {
1417 foreach (Iterator iterator in iterators) {
1418 if (iterator.DefineType () == null)
1422 foreach (Iterator iterator in iterators) {
1423 if (!iterator.DefineMembers (this))
1431 void ReportStructInitializedInstanceError ()
1433 string n = TypeBuilder.FullName;
1435 foreach (Field f in initialized_fields){
1438 "`" + n + "." + f.Name + "': can not have " +
1439 "instance field initializers in structs");
1443 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1446 mcal.DefineContainerMembers ();
1449 public override bool Define ()
1451 if (parts != null) {
1452 foreach (ClassPart part in parts) {
1453 if (!part.Define ())
1461 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1463 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1467 /// This function is based by a delegate to the FindMembers routine
1469 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1475 /// This filter is used by FindMembers, and we just keep
1476 /// a global for the filter to `AlwaysAccept'
1478 static MemberFilter accepting_filter;
1481 static TypeContainer ()
1483 accepting_filter = new MemberFilter (AlwaysAccept);
1486 public MethodInfo[] GetMethods ()
1488 ArrayList members = new ArrayList ();
1490 DefineMembers (null);
1492 if (methods != null) {
1493 int len = methods.Count;
1494 for (int i = 0; i < len; i++) {
1495 Method m = (Method) methods [i];
1497 members.Add (m.MethodBuilder);
1501 if (operators != null) {
1502 int len = operators.Count;
1503 for (int i = 0; i < len; i++) {
1504 Operator o = (Operator) operators [i];
1506 members.Add (o.OperatorMethodBuilder);
1510 if (properties != null) {
1511 int len = properties.Count;
1512 for (int i = 0; i < len; i++) {
1513 Property p = (Property) properties [i];
1515 if (p.GetBuilder != null)
1516 members.Add (p.GetBuilder);
1517 if (p.SetBuilder != null)
1518 members.Add (p.SetBuilder);
1522 if (indexers != null) {
1523 int len = indexers.Count;
1524 for (int i = 0; i < len; i++) {
1525 Indexer ix = (Indexer) indexers [i];
1527 if (ix.GetBuilder != null)
1528 members.Add (ix.GetBuilder);
1529 if (ix.SetBuilder != null)
1530 members.Add (ix.SetBuilder);
1534 if (events != null) {
1535 int len = events.Count;
1536 for (int i = 0; i < len; i++) {
1537 Event e = (Event) events [i];
1539 if (e.AddBuilder != null)
1540 members.Add (e.AddBuilder);
1541 if (e.RemoveBuilder != null)
1542 members.Add (e.RemoveBuilder);
1546 MethodInfo[] retMethods = new MethodInfo [members.Count];
1547 members.CopyTo (retMethods, 0);
1551 // Indicated whether container has StructLayout attribute set Explicit
1552 public virtual bool HasExplicitLayout {
1558 public override Type FindNestedType (string name)
1560 ArrayList [] lists = { types, enums, delegates, interfaces };
1562 for (int j = 0; j < lists.Length; ++j) {
1563 ArrayList list = lists [j];
1567 int len = list.Count;
1568 for (int i = 0; i < len; ++i) {
1569 DeclSpace ds = (DeclSpace) list [i];
1570 if (ds.Basename == name) {
1572 return ds.TypeBuilder;
1577 if (Parts != null) {
1578 foreach (ClassPart cp in Parts) {
1579 Type t = cp.PartFindNestedType (name);
1588 private void FindMembers_NestedTypes (int modflags,
1589 BindingFlags bf, MemberFilter filter, object criteria,
1590 ref ArrayList members)
1592 ArrayList [] lists = { types, enums, delegates, interfaces };
1594 for (int j = 0; j < lists.Length; ++j) {
1595 ArrayList list = lists [j];
1599 int len = list.Count;
1600 for (int i = 0; i < len; i++) {
1601 DeclSpace ds = (DeclSpace) list [i];
1603 if ((ds.ModFlags & modflags) == 0)
1606 TypeBuilder tb = ds.TypeBuilder;
1608 if (!(criteria is string) || ds.Basename.Equals (criteria))
1609 tb = ds.DefineType ();
1612 if (tb != null && (filter (tb, criteria) == true)) {
1613 if (members == null)
1614 members = new ArrayList ();
1623 /// This method returns the members of this type just like Type.FindMembers would
1624 /// Only, we need to use this for types which are _being_ defined because MS'
1625 /// implementation can't take care of that.
1628 // FIXME: return an empty static array instead of null, that cleans up
1629 // some code and is consistent with some coding conventions I just found
1633 // Notice that in various cases we check if our field is non-null,
1634 // something that would normally mean that there was a bug elsewhere.
1636 // The problem happens while we are defining p-invoke methods, as those
1637 // will trigger a FindMembers, but this happens before things are defined
1639 // Since the whole process is a no-op, it is fine to check for null here.
1641 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1642 MemberFilter filter, object criteria)
1644 ArrayList members = null;
1647 if ((bf & BindingFlags.Public) != 0)
1648 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1650 if ((bf & BindingFlags.NonPublic) != 0)
1651 modflags |= Modifiers.PRIVATE;
1653 int static_mask = 0, static_flags = 0;
1654 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1655 case BindingFlags.Static:
1656 static_mask = static_flags = Modifiers.STATIC;
1659 case BindingFlags.Instance:
1660 static_mask = Modifiers.STATIC;
1665 static_mask = static_flags = 0;
1669 Timer.StartTimer (TimerType.TcFindMembers);
1672 filter = accepting_filter;
1674 if ((mt & MemberTypes.Field) != 0) {
1675 if (fields != null) {
1676 int len = fields.Count;
1677 for (int i = 0; i < len; i++) {
1678 FieldMember f = (FieldMember) fields [i];
1680 if ((f.ModFlags & modflags) == 0)
1682 if ((f.ModFlags & static_mask) != static_flags)
1685 FieldBuilder fb = f.FieldBuilder;
1686 if (fb != null && filter (fb, criteria) == true) {
1687 if (members == null)
1688 members = new ArrayList ();
1695 if (constants != null) {
1696 int len = constants.Count;
1697 for (int i = 0; i < len; i++) {
1698 Const con = (Const) constants [i];
1700 if ((con.ModFlags & modflags) == 0)
1702 if ((con.ModFlags & static_mask) != static_flags)
1705 FieldBuilder fb = con.FieldBuilder;
1708 fb = con.FieldBuilder;
1710 if (fb != null && filter (fb, criteria) == true) {
1711 if (members == null)
1712 members = new ArrayList ();
1720 if ((mt & MemberTypes.Method) != 0) {
1721 if (methods != null) {
1722 int len = methods.Count;
1723 for (int i = 0; i < len; i++) {
1724 Method m = (Method) methods [i];
1726 if ((m.ModFlags & modflags) == 0)
1728 if ((m.ModFlags & static_mask) != static_flags)
1731 MethodBuilder mb = m.MethodBuilder;
1733 if (mb != null && filter (mb, criteria) == true) {
1734 if (members == null)
1735 members = new ArrayList ();
1742 if (operators != null) {
1743 int len = operators.Count;
1744 for (int i = 0; i < len; i++) {
1745 Operator o = (Operator) operators [i];
1747 if ((o.ModFlags & modflags) == 0)
1749 if ((o.ModFlags & static_mask) != static_flags)
1752 MethodBuilder ob = o.OperatorMethodBuilder;
1753 if (ob != null && filter (ob, criteria) == true) {
1754 if (members == null)
1755 members = new ArrayList ();
1762 if (properties != null) {
1763 int len = properties.Count;
1764 for (int i = 0; i < len; i++) {
1765 Property p = (Property) properties [i];
1767 if ((p.ModFlags & modflags) == 0)
1769 if ((p.ModFlags & static_mask) != static_flags)
1775 if (b != null && filter (b, criteria) == true) {
1776 if (members == null)
1777 members = new ArrayList ();
1783 if (b != null && filter (b, criteria) == true) {
1784 if (members == null)
1785 members = new ArrayList ();
1792 if (indexers != null) {
1793 int len = indexers.Count;
1794 for (int i = 0; i < len; i++) {
1795 Indexer ix = (Indexer) indexers [i];
1797 if ((ix.ModFlags & modflags) == 0)
1799 if ((ix.ModFlags & static_mask) != static_flags)
1805 if (b != null && filter (b, criteria) == true) {
1806 if (members == null)
1807 members = new ArrayList ();
1813 if (b != null && filter (b, criteria) == true) {
1814 if (members == null)
1815 members = new ArrayList ();
1823 if ((mt & MemberTypes.Event) != 0) {
1824 if (events != null) {
1825 int len = events.Count;
1826 for (int i = 0; i < len; i++) {
1827 Event e = (Event) events [i];
1829 if ((e.ModFlags & modflags) == 0)
1831 if ((e.ModFlags & static_mask) != static_flags)
1834 MemberInfo eb = e.EventBuilder;
1835 if (eb != null && filter (eb, criteria) == true) {
1836 if (members == null)
1837 members = new ArrayList ();
1839 members.Add (e.EventBuilder);
1845 if ((mt & MemberTypes.Property) != 0){
1846 if (properties != null) {
1847 int len = properties.Count;
1848 for (int i = 0; i < len; i++) {
1849 Property p = (Property) properties [i];
1851 if ((p.ModFlags & modflags) == 0)
1853 if ((p.ModFlags & static_mask) != static_flags)
1856 MemberInfo pb = p.PropertyBuilder;
1857 if (pb != null && filter (pb, criteria) == true) {
1858 if (members == null)
1859 members = new ArrayList ();
1861 members.Add (p.PropertyBuilder);
1866 if (indexers != null) {
1867 int len = indexers.Count;
1868 for (int i = 0; i < len; i++) {
1869 Indexer ix = (Indexer) indexers [i];
1871 if ((ix.ModFlags & modflags) == 0)
1873 if ((ix.ModFlags & static_mask) != static_flags)
1876 MemberInfo ib = ix.PropertyBuilder;
1877 if (ib != null && filter (ib, criteria) == true) {
1878 if (members == null)
1879 members = new ArrayList ();
1881 members.Add (ix.PropertyBuilder);
1887 if ((mt & MemberTypes.NestedType) != 0)
1888 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1890 if ((mt & MemberTypes.Constructor) != 0){
1891 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1892 int len = instance_constructors.Count;
1893 for (int i = 0; i < len; i++) {
1894 Constructor c = (Constructor) instance_constructors [i];
1896 ConstructorBuilder cb = c.ConstructorBuilder;
1897 if (cb != null && filter (cb, criteria) == true) {
1898 if (members == null)
1899 members = new ArrayList ();
1906 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1907 ConstructorBuilder cb =
1908 default_static_constructor.ConstructorBuilder;
1910 if (cb != null && filter (cb, criteria) == true) {
1911 if (members == null)
1912 members = new ArrayList ();
1920 // Lookup members in base if requested.
1922 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1923 if (TypeBuilder.BaseType != null) {
1924 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1925 if (list.Count > 0) {
1926 if (members == null)
1927 members = new ArrayList ();
1929 members.AddRange (list);
1932 if (ifaces != null) {
1933 foreach (Type base_type in ifaces) {
1934 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1936 if (list.Count > 0) {
1937 if (members == null)
1938 members = new ArrayList ();
1939 members.AddRange (list);
1945 Timer.StopTimer (TimerType.TcFindMembers);
1947 if (members == null)
1948 return MemberList.Empty;
1950 return new MemberList (members);
1953 public override MemberCache MemberCache {
1955 return member_cache;
1959 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1960 MemberFilter filter, object criteria)
1962 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1965 return ds.FindMembers (mt, bf, filter, criteria);
1967 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1972 // FindMethods will look for methods not only in the type `t', but in
1973 // any interfaces implemented by the type.
1975 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1976 MemberFilter filter, object criteria)
1982 /// Emits the values for the constants
1984 public void EmitConstants ()
1986 if (constants != null)
1987 foreach (Const con in constants)
1992 protected virtual void VerifyMembers (EmitContext ec)
1995 // Check for internal or private fields that were never assigned
1997 if (RootContext.WarningLevel >= 4) {
1998 if (fields != null){
1999 foreach (Field f in fields) {
2000 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2003 if ((f.status & Field.Status.USED) == 0){
2004 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2009 // Only report 649 on level 4
2011 if (RootContext.WarningLevel < 4)
2014 if ((f.status & Field.Status.ASSIGNED) != 0)
2017 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2024 /// Emits the code, this step is performed after all
2025 /// the types, enumerations, constructors
2027 public void EmitType ()
2029 if (OptAttributes != null)
2030 OptAttributes.Emit (ec, this);
2034 if (instance_constructors != null) {
2035 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2036 bool has_compliant_args = false;
2038 foreach (Constructor c in instance_constructors) {
2041 if (has_compliant_args)
2044 has_compliant_args = c.HasCompliantArgs;
2046 if (!has_compliant_args)
2047 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2049 foreach (Constructor c in instance_constructors)
2056 if (default_static_constructor != null)
2057 default_static_constructor.Emit ();
2059 if (methods != null)
2060 foreach (Method m in methods)
2063 if (operators != null)
2064 foreach (Operator o in operators)
2067 if (properties != null)
2068 foreach (Property p in properties)
2071 if (indexers != null){
2076 foreach (FieldMember f in fields)
2079 if (events != null){
2080 foreach (Event e in Events)
2084 if (delegates != null) {
2085 foreach (Delegate d in Delegates) {
2090 if (enums != null) {
2091 foreach (Enum e in enums) {
2096 if (parts != null) {
2097 foreach (ClassPart part in parts)
2101 if ((Pending != null) && !(this is ClassPart))
2102 if (Pending.VerifyPendingMethods ())
2107 if (iterators != null)
2108 foreach (Iterator iterator in iterators)
2109 iterator.EmitType ();
2111 // if (types != null)
2112 // foreach (TypeContainer tc in types)
2116 public override void CloseType ()
2118 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2122 caching_flags |= Flags.CloseTypeCreated;
2123 TypeBuilder.CreateType ();
2124 } catch (TypeLoadException){
2126 // This is fine, the code still created the type
2128 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2129 // Console.WriteLine (e.Message);
2131 Console.WriteLine ("In type: " + Name);
2136 foreach (Enum en in Enums)
2140 foreach (TypeContainer tc in Types)
2141 if (tc.Kind == Kind.Struct)
2144 foreach (TypeContainer tc in Types)
2145 if (tc.Kind != Kind.Struct)
2149 if (Delegates != null)
2150 foreach (Delegate d in Delegates)
2153 if (Iterators != null)
2154 foreach (Iterator i in Iterators)
2162 initialized_fields = null;
2163 initialized_static_fields = null;
2172 default_constructor = null;
2173 default_static_constructor = null;
2175 OptAttributes = null;
2178 member_cache = null;
2181 // TODO: make it obsolete and use GetSignatureForError
2182 public string MakeName (string n)
2184 return "`" + Name + "." + n + "'";
2188 // Performs the validation on a Method's modifiers (properties have
2189 // the same properties).
2191 public bool MethodModifiersValid (MemberCore mc)
2193 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2194 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2195 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2197 int flags = mc.ModFlags;
2200 // At most one of static, virtual or override
2202 if ((flags & Modifiers.STATIC) != 0){
2203 if ((flags & vao) != 0){
2204 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2205 GetSignatureForError ());
2210 if (Kind == Kind.Struct){
2211 if ((flags & va) != 0){
2212 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2217 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2218 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2223 // If the declaration includes the abstract modifier, then the
2224 // declaration does not include static, virtual or extern
2226 if ((flags & Modifiers.ABSTRACT) != 0){
2227 if ((flags & Modifiers.EXTERN) != 0){
2229 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2233 if ((flags & Modifiers.SEALED) != 0) {
2234 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2238 if ((flags & Modifiers.VIRTUAL) != 0){
2239 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2243 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2244 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2249 if ((flags & Modifiers.PRIVATE) != 0){
2250 if ((flags & vao) != 0){
2251 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2256 if ((flags & Modifiers.SEALED) != 0){
2257 if ((flags & Modifiers.OVERRIDE) == 0){
2258 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2266 public bool UserDefinedStaticConstructor {
2268 return default_static_constructor != null;
2272 public Constructor DefaultStaticConstructor {
2273 get { return default_static_constructor; }
2276 protected override bool VerifyClsCompliance (DeclSpace ds)
2278 if (!base.VerifyClsCompliance (ds))
2283 Type base_type = TypeBuilder.BaseType;
2284 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2285 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2288 if (!Parent.IsClsCompliaceRequired (ds)) {
2289 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2290 GetSignatureForError (), Parent.GetSignatureForError ());
2297 /// Checks whether container name is CLS Compliant
2299 void VerifyClsName ()
2301 Hashtable base_members = base_cache == null ?
2303 base_cache.GetPublicMembers ();
2304 Hashtable this_members = new Hashtable ();
2306 foreach (DictionaryEntry entry in defined_names) {
2307 MemberCore mc = (MemberCore)entry.Value;
2308 if (!mc.IsClsCompliaceRequired (this))
2311 string name = (string)entry.Key;
2312 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2314 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2315 object found = base_members [lcase];
2316 if (found == null) {
2317 found = this_members [lcase];
2318 if (found == null) {
2319 this_members.Add (lcase, mc);
2324 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2327 if (found is MemberInfo) {
2328 if (basename == ((MemberInfo)found).Name)
2330 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2332 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2334 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2340 /// Performs checks for an explicit interface implementation. First it
2341 /// checks whether the `interface_type' is a base inteface implementation.
2342 /// Then it checks whether `name' exists in the interface type.
2344 public virtual bool VerifyImplements (Type interface_type, string full,
2345 string name, Location loc)
2349 if (ifaces != null){
2350 foreach (Type t in ifaces){
2351 if (t == interface_type){
2359 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2360 full, interface_type.FullName);
2367 protected override void VerifyObsoleteAttribute()
2369 CheckUsageOfObsoleteAttribute (ptype);
2374 foreach (Type iface in ifaces) {
2375 CheckUsageOfObsoleteAttribute (iface);
2384 string IMemberContainer.Name {
2390 Type IMemberContainer.Type {
2396 MemberCache IMemberContainer.MemberCache {
2398 return member_cache;
2402 bool IMemberContainer.IsInterface {
2404 return Kind == Kind.Interface;
2408 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2410 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2414 // Generates xml doc comments (if any), and if required,
2415 // handle warning report.
2417 internal override void GenerateDocComment (DeclSpace ds)
2419 DocUtil.GenerateTypeDocComment (this, ds);
2422 public override string DocCommentHeader {
2423 get { return "T:"; }
2426 public virtual MemberCache BaseCache {
2428 if (base_cache != null)
2430 if (TypeBuilder.BaseType != null)
2431 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2432 if (TypeBuilder.IsInterface)
2433 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
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 Type FindNestedType (string name)
2614 return PartialContainer.FindNestedType (name);
2617 public Type PartFindNestedType (string name)
2619 return base.FindNestedType (name);
2622 public override MemberCache BaseCache {
2624 return PartialContainer.BaseCache;
2629 public abstract class ClassOrStruct : TypeContainer {
2630 bool hasExplicitLayout = false;
2631 ListDictionary declarative_security;
2633 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2634 MemberName name, Attributes attrs, Kind kind,
2636 : base (ns, parent, name, attrs, kind, l)
2640 public override PendingImplementation GetPendingImplementations ()
2642 return PendingImplementation.GetPendingImplementations (this);
2645 public override bool HasExplicitLayout {
2647 return hasExplicitLayout;
2651 protected override void VerifyMembers (EmitContext ec)
2653 base.VerifyMembers (ec);
2655 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2656 foreach (Event e in events){
2658 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2663 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2665 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2666 if (declarative_security == null)
2667 declarative_security = new ListDictionary ();
2669 a.ExtractSecurityPermissionSet (declarative_security);
2673 if (a.Type == TypeManager.struct_layout_attribute_type &&
2674 a.GetLayoutKindValue () == LayoutKind.Explicit)
2675 hasExplicitLayout = true;
2677 base.ApplyAttributeBuilder (a, cb);
2680 public override void Emit()
2684 if (declarative_security != null) {
2685 foreach (DictionaryEntry de in declarative_security) {
2686 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2691 public override void Register ()
2693 Parent.AddClassOrStruct (this);
2698 /// Class handles static classes declaration
2700 public sealed class StaticClass: Class {
2701 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2702 Attributes attrs, Location l)
2703 : base (ns, parent, name, mod, attrs, l)
2705 if (RootContext.Version == LanguageVersion.ISO_1) {
2706 Report.FeatureIsNotStandardized (l, "static classes");
2707 Environment.Exit (1);
2711 protected override int AllowedModifiersProp {
2713 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2714 Modifiers.STATIC | Modifiers.UNSAFE;
2718 protected override void DefineContainerMembers (MemberCoreArrayList list)
2723 foreach (MemberCore m in list) {
2724 if (m is Operator) {
2725 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2729 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2730 Report.Warning (628, 4, m.Location, "'{0}': new protected member declared in static class", m.GetSignatureForError (this));
2732 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2735 if (m is Constructor) {
2736 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2740 if (m is Destructor) {
2741 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2745 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2748 base.DefineContainerMembers (list);
2751 public override TypeBuilder DefineType()
2753 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2754 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2758 TypeBuilder tb = base.DefineType ();
2762 if (ptype != TypeManager.object_type) {
2763 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2767 if (ifaces != null) {
2768 foreach (Type t in ifaces)
2769 Report.SymbolRelatedToPreviousError (t);
2770 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2775 public override TypeAttributes TypeAttr {
2777 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2782 public class Class : ClassOrStruct {
2783 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2784 public const int AllowedModifiers =
2787 Modifiers.PROTECTED |
2788 Modifiers.INTERNAL |
2790 Modifiers.ABSTRACT |
2794 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2795 Attributes attrs, Location l)
2796 : base (ns, parent, name, attrs, Kind.Class, l)
2798 this.ModFlags = mod;
2801 virtual protected int AllowedModifiersProp {
2803 return AllowedModifiers;
2807 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2809 if (a.Type == TypeManager.attribute_usage_type) {
2810 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2811 TypeBuilder.FullName != "System.Attribute") {
2812 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2816 base.ApplyAttributeBuilder (a, cb);
2819 public const TypeAttributes DefaultTypeAttributes =
2820 TypeAttributes.AutoLayout | TypeAttributes.Class;
2822 public override TypeBuilder DefineType()
2824 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2825 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2829 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2830 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2832 return base.DefineType ();
2836 // FIXME: How do we deal with the user specifying a different
2839 public override TypeAttributes TypeAttr {
2841 return base.TypeAttr | DefaultTypeAttributes;
2846 public class Struct : ClassOrStruct {
2848 // Modifiers allowed in a struct declaration
2850 public const int AllowedModifiers =
2853 Modifiers.PROTECTED |
2854 Modifiers.INTERNAL |
2858 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2859 int mod, Attributes attrs, Location l)
2860 : base (ns, parent, name, attrs, Kind.Struct, l)
2864 if (parent.Parent == null)
2865 accmods = Modifiers.INTERNAL;
2867 accmods = Modifiers.PRIVATE;
2869 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2871 this.ModFlags |= Modifiers.SEALED;
2874 public const TypeAttributes DefaultTypeAttributes =
2875 TypeAttributes.SequentialLayout |
2876 TypeAttributes.Sealed |
2877 TypeAttributes.BeforeFieldInit;
2880 // FIXME: Allow the user to specify a different set of attributes
2881 // in some cases (Sealed for example is mandatory for a class,
2882 // but what SequentialLayout can be changed
2884 public override TypeAttributes TypeAttr {
2886 return base.TypeAttr | DefaultTypeAttributes;
2894 public class Interface : TypeContainer, IMemberContainer {
2896 /// Modifiers allowed in a class declaration
2898 public const int AllowedModifiers =
2901 Modifiers.PROTECTED |
2902 Modifiers.INTERNAL |
2906 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2907 Attributes attrs, Location l)
2908 : base (ns, parent, name, attrs, Kind.Interface, l)
2912 if (parent.Parent == null)
2913 accmods = Modifiers.INTERNAL;
2915 accmods = Modifiers.PRIVATE;
2917 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2920 public override void Register ()
2922 Parent.AddInterface (this);
2925 public override PendingImplementation GetPendingImplementations ()
2930 public const TypeAttributes DefaultTypeAttributes =
2931 TypeAttributes.AutoLayout |
2932 TypeAttributes.Abstract |
2933 TypeAttributes.Interface;
2935 public override TypeAttributes TypeAttr {
2937 return base.TypeAttr | DefaultTypeAttributes;
2942 public abstract class MethodCore : MemberBase {
2943 public readonly Parameters Parameters;
2944 protected ToplevelBlock block;
2947 // Parameters, cached for semantic analysis.
2949 protected InternalParameters parameter_info;
2950 protected Type [] parameter_types;
2952 // Whether this is an operator method.
2953 public bool IsOperator;
2956 // The method we're overriding if this is an override method.
2958 protected MethodInfo base_method = null;
2960 static string[] attribute_targets = new string [] { "method", "return" };
2962 public MethodCore (TypeContainer parent, Expression type, int mod,
2963 int allowed_mod, bool is_interface, MemberName name,
2964 Attributes attrs, Parameters parameters, Location loc)
2965 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
2968 Parameters = parameters;
2969 IsInterface = is_interface;
2973 // Returns the System.Type array for the parameters of this method
2975 public Type [] ParameterTypes {
2977 return parameter_types;
2981 public InternalParameters ParameterInfo
2984 return parameter_info;
2988 public ToplevelBlock Block {
2998 protected override bool CheckBase ()
3000 if (!base.CheckBase ())
3003 // Check whether arguments were correct.
3004 if (!DoDefineParameters ())
3007 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3013 // Is null for System.Object while compiling corlib and base interfaces
3014 if (Parent.BaseCache == null) {
3015 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3016 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3021 Type base_ret_type = null;
3022 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3024 // method is override
3025 if (base_method != null) {
3027 if (!CheckMethodAgainstBase ())
3030 if ((ModFlags & Modifiers.NEW) == 0) {
3031 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3032 Report.SymbolRelatedToPreviousError (base_method);
3033 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3034 "change return type when overriding inherited member");
3038 if (base_method.IsAbstract && !IsInterface) {
3039 Report.SymbolRelatedToPreviousError (base_method);
3040 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3045 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3046 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3050 if (RootContext.WarningLevel > 2) {
3051 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3052 Parent.Methods.HasEquals = true;
3053 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3054 Parent.Methods.HasGetHashCode = true;
3057 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3058 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3060 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3061 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3062 Report.SymbolRelatedToPreviousError (base_method);
3063 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3070 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3071 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3072 if (conflict_symbol != null) {
3073 Report.SymbolRelatedToPreviousError (conflict_symbol);
3074 if (this is PropertyBase)
3075 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3077 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3079 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3083 if (conflict_symbol == null) {
3084 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3085 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3090 if ((ModFlags & Modifiers.NEW) == 0) {
3091 if (this is Method && conflict_symbol is MethodBase)
3094 Report.SymbolRelatedToPreviousError (conflict_symbol);
3095 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3103 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3104 // that have been defined.
3106 // `name' is the user visible name for reporting errors (this is used to
3107 // provide the right name regarding method names and properties)
3109 bool CheckMethodAgainstBase ()
3113 // TODO: replace with GetSignatureForError
3114 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3116 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3117 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3119 506, Location, Parent.MakeName (Name) +
3120 ": cannot override inherited member `" +
3121 name + "' because it is not " +
3122 "virtual, abstract or override");
3126 // Now we check that the overriden method is not final
3128 if (base_method.IsFinal) {
3129 Report.SymbolRelatedToPreviousError (base_method);
3130 Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
3131 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3135 // Check that the permissions are not being changed
3137 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3138 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3140 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3141 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3146 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3147 ModFlags |= Modifiers.NEW;
3148 Report.SymbolRelatedToPreviousError (base_method);
3149 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3150 if (RootContext.WarningLevel >= 2)
3151 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));
3153 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3159 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3161 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3163 // when overriding protected internal, the method can be declared
3164 // protected internal only within the same assembly
3167 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3168 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3170 // assemblies differ - report an error
3174 } else if (thisp != base_classp) {
3176 // same assembly, but other attributes differ - report an error
3181 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3183 // if it's not "protected internal", it must be "protected"
3187 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3189 // protected within the same assembly - an error
3192 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3193 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3195 // protected ok, but other attributes differ - report an error
3201 return (thisp == base_classp);
3205 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3208 // FIXME: report the old/new permissions?
3211 507, Location, parent.MakeName (Name) +
3212 ": can't change the access modifiers when overriding inherited " +
3213 "member `" + name + "'");
3216 protected static string Error722 {
3218 return "'{0}': static types cannot be used as return types";
3223 /// For custom member duplication search in a container
3225 protected abstract bool CheckForDuplications ();
3228 /// Gets base method and its return type
3230 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3232 protected virtual bool DoDefineParameters ()
3234 EmitContext ec = Parent.EmitContext;
3236 throw new InternalErrorException ("DoDefineParameters invoked too early");
3238 bool old_unsafe = ec.InUnsafe;
3239 ec.InUnsafe = InUnsafe;
3240 // Check if arguments were correct
3241 parameter_types = Parameters.GetParameterInfo (ec);
3242 ec.InUnsafe = old_unsafe;
3244 if ((parameter_types == null) ||
3245 !CheckParameters (Parent, parameter_types))
3248 parameter_info = new InternalParameters (parameter_types, Parameters);
3250 Parameter array_param = Parameters.ArrayParameter;
3251 if ((array_param != null) &&
3252 (!array_param.ParameterType.IsArray ||
3253 (array_param.ParameterType.GetArrayRank () != 1))) {
3254 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3261 public override string[] ValidAttributeTargets {
3263 return attribute_targets;
3267 protected override bool VerifyClsCompliance (DeclSpace ds)
3269 if (!base.VerifyClsCompliance (ds)) {
3270 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3271 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3276 if (Parameters.HasArglist) {
3277 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3280 if (!AttributeTester.IsClsCompliant (MemberType)) {
3281 if (this is PropertyBase)
3282 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3283 GetSignatureForError ());
3285 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3286 GetSignatureForError ());
3289 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3294 protected bool IsDuplicateImplementation (MethodCore method)
3296 if ((method == this) || (method.Name != Name))
3299 Type[] param_types = method.ParameterTypes;
3300 if (param_types == null)
3303 if (param_types.Length != ParameterTypes.Length)
3306 for (int i = 0; i < param_types.Length; i++)
3307 if (param_types [i] != ParameterTypes [i])
3310 // TODO: make operator compatible with MethodCore to avoid this
3311 if (this is Operator && method is Operator) {
3312 if (MemberType != method.MemberType)
3317 // Try to report 663: method only differs on out/ref
3319 ParameterData info = ParameterInfo;
3320 ParameterData other_info = method.ParameterInfo;
3321 for (int i = 0; i < info.Count; i++){
3322 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3323 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3328 Report.SymbolRelatedToPreviousError (method);
3329 if (this is Operator && method is Operator)
3330 Report.Error (557, Location, "Duplicate user-defined conversion in type '{0}'", Parent.Name);
3332 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3337 // Returns a string that represents the signature for this
3338 // member which should be used in XML documentation.
3340 public override string GetDocCommentName (DeclSpace ds)
3342 return DocUtil.GetMethodDocCommentName (this, ds);
3346 // Raised (and passed an XmlElement that contains the comment)
3347 // when GenerateDocComment is writing documentation expectedly.
3349 // FIXME: with a few effort, it could be done with XmlReader,
3350 // that means removal of DOM use.
3352 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3354 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3358 // Represents header string for documentation comment.
3360 public override string DocCommentHeader {
3361 get { return "M:"; }
3364 protected override void VerifyObsoleteAttribute()
3366 base.VerifyObsoleteAttribute ();
3368 if (parameter_types == null)
3371 foreach (Type type in parameter_types) {
3372 CheckUsageOfObsoleteAttribute (type);
3377 public class SourceMethod : ISourceMethod
3379 TypeContainer container;
3382 protected SourceMethod (TypeContainer container, MethodBase builder,
3383 ISourceFile file, Location start, Location end)
3385 this.container = container;
3386 this.builder = builder;
3388 CodeGen.SymbolWriter.OpenMethod (
3389 file, this, start.Row, 0, end.Row, 0);
3392 public string Name {
3393 get { return builder.Name; }
3396 public int NamespaceID {
3397 get { return container.NamespaceEntry.SymbolFileID; }
3402 if (builder is MethodBuilder)
3403 return ((MethodBuilder) builder).GetToken ().Token;
3404 else if (builder is ConstructorBuilder)
3405 return ((ConstructorBuilder) builder).GetToken ().Token;
3407 throw new NotSupportedException ();
3411 public void CloseMethod ()
3413 if (CodeGen.SymbolWriter != null)
3414 CodeGen.SymbolWriter.CloseMethod ();
3417 public static SourceMethod Create (TypeContainer parent,
3418 MethodBase builder, Block block)
3420 if (CodeGen.SymbolWriter == null)
3425 Location start_loc = block.StartLocation;
3426 if (Location.IsNull (start_loc))
3429 Location end_loc = block.EndLocation;
3430 if (Location.IsNull (end_loc))
3433 ISourceFile file = start_loc.SourceFile;
3437 return new SourceMethod (
3438 parent, builder, file, start_loc, end_loc);
3442 public class Method : MethodCore, IIteratorContainer, IMethodData {
3443 public MethodBuilder MethodBuilder;
3444 public MethodData MethodData;
3445 ReturnParameter return_attributes;
3446 ListDictionary declarative_security;
3449 /// Modifiers allowed in a class declaration
3451 const int AllowedModifiers =
3454 Modifiers.PROTECTED |
3455 Modifiers.INTERNAL |
3460 Modifiers.OVERRIDE |
3461 Modifiers.ABSTRACT |
3463 Modifiers.METHOD_YIELDS |
3466 const int AllowedInterfaceModifiers =
3467 Modifiers.NEW | Modifiers.UNSAFE;
3470 // return_type can be "null" for VOID values.
3472 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3473 MemberName name, Parameters parameters, Attributes attrs,
3475 : base (ds, return_type, mod,
3476 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3477 is_iface, name, attrs, parameters, l)
3481 public override AttributeTargets AttributeTargets {
3483 return AttributeTargets.Method;
3487 public override string GetSignatureForError()
3489 if (MethodBuilder == null) {
3490 return GetSignatureForError (Parent);
3492 return TypeManager.CSharpSignature (MethodBuilder);
3496 /// Use this method when MethodBuilder is null
3498 public override string GetSignatureForError (TypeContainer tc)
3500 // TODO: get params from somewhere
3501 if (parameter_info == null)
3502 return base.GetSignatureForError (tc);
3504 // TODO: move to parameters
3505 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3506 if (parameter_info.Parameters.FixedParameters != null) {
3507 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3508 Parameter p = parameter_info.Parameters.FixedParameters [i];
3509 args.Append (p.GetSignatureForError ());
3511 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3516 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3519 void DuplicateEntryPoint (MethodInfo b, Location location)
3523 "Program `" + CodeGen.FileName +
3524 "' has more than one entry point defined: `" +
3525 TypeManager.CSharpSignature(b) + "'");
3528 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3530 if (b.ReturnType != TypeManager.void_type &&
3531 b.ReturnType != TypeManager.int32_type)
3534 if (pinfo.Count == 0)
3537 if (pinfo.Count > 1)
3540 Type t = pinfo.ParameterType(0);
3542 (t.GetArrayRank() == 1) &&
3543 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3544 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3550 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3552 if (a.Target == AttributeTargets.ReturnValue) {
3553 if (return_attributes == null)
3554 return_attributes = new ReturnParameter (MethodBuilder, Location);
3556 return_attributes.ApplyAttributeBuilder (a, cb);
3560 if (a.Type == TypeManager.methodimpl_attr_type &&
3561 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3562 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3565 if (a.Type == TypeManager.dllimport_type) {
3566 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3567 if ((ModFlags & extern_static) != extern_static) {
3568 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3574 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3575 if (declarative_security == null)
3576 declarative_security = new ListDictionary ();
3577 a.ExtractSecurityPermissionSet (declarative_security);
3581 if (a.Type == TypeManager.conditional_attribute_type) {
3582 if (IsOperator || IsExplicitImpl) {
3583 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3587 if (ReturnType != TypeManager.void_type) {
3588 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3592 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3593 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3598 Report.Error (582, Location, "Conditional not valid on interface members");
3602 if (MethodData.IsImplementing) {
3603 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3607 for (int i = 0; i < parameter_info.Count; ++i) {
3608 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3609 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3615 MethodBuilder.SetCustomAttribute (cb);
3618 protected override bool CheckForDuplications ()
3620 ArrayList ar = Parent.Methods;
3622 int arLen = ar.Count;
3624 for (int i = 0; i < arLen; i++) {
3625 Method m = (Method) ar [i];
3626 if (IsDuplicateImplementation (m))
3631 ar = Parent.Properties;
3633 for (int i = 0; i < ar.Count; ++i) {
3634 PropertyBase pb = (PropertyBase) ar [i];
3635 if (pb.AreAccessorsDuplicateImplementation (this))
3640 ar = Parent.Indexers;
3642 for (int i = 0; i < ar.Count; ++i) {
3643 PropertyBase pb = (PropertyBase) ar [i];
3644 if (pb.AreAccessorsDuplicateImplementation (this))
3651 for (int i = 0; i < ar.Count; ++i) {
3652 Event ev = (Event) ar [i];
3653 if (ev.AreAccessorsDuplicateImplementation (this))
3664 public override bool Define ()
3669 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3670 Error1599 (Location, ReturnType);
3678 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3680 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3682 if (!MethodData.Define (Parent))
3686 // Setup iterator if we are one
3688 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3689 Iterator iterator = new Iterator (
3690 Parent, Name, MemberType, ParameterTypes,
3691 ParameterInfo, ModFlags, block, Location);
3693 if (!iterator.DefineIterator ())
3696 block = iterator.Block;
3699 MethodBuilder = MethodData.MethodBuilder;
3702 // This is used to track the Entry Point,
3704 if (Name == "Main" &&
3705 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3706 (RootContext.MainClass == null ||
3707 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3708 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3709 if (RootContext.EntryPoint == null) {
3710 RootContext.EntryPoint = MethodBuilder;
3711 RootContext.EntryPointLocation = Location;
3713 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3714 DuplicateEntryPoint (MethodBuilder, Location);
3717 if (RootContext.WarningLevel >= 4)
3718 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3722 if (MemberType.IsAbstract && MemberType.IsSealed) {
3723 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3733 public override void Emit ()
3735 MethodData.Emit (Parent, this);
3738 if (declarative_security != null) {
3739 foreach (DictionaryEntry de in declarative_security) {
3740 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3748 public static void Error1599 (Location loc, Type t)
3750 Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
3753 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3755 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3756 container.TypeBuilder, Name, ParameterTypes, false);
3761 base_ret_type = mi.ReturnType;
3765 public override bool MarkForDuplicationCheck ()
3767 caching_flags |= Flags.TestMethodDuplication;
3771 protected override bool VerifyClsCompliance(DeclSpace ds)
3773 if (!base.VerifyClsCompliance (ds))
3776 if (parameter_types.Length > 0) {
3777 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3779 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3786 void IIteratorContainer.SetYields ()
3788 ModFlags |= Modifiers.METHOD_YIELDS;
3791 #region IMethodData Members
3793 public CallingConventions CallingConventions {
3795 CallingConventions cc = Parameters.GetCallingConvention ();
3796 if (Parameters.HasArglist)
3797 block.HasVarargs = true;
3800 if ((ModFlags & Modifiers.STATIC) == 0)
3801 cc |= CallingConventions.HasThis;
3803 // FIXME: How is `ExplicitThis' used in C#?
3809 public Type ReturnType {
3815 public MemberName MethodName {
3821 public new Location Location {
3823 return base.Location;
3827 protected override bool CheckBase() {
3828 if (!base.CheckBase ())
3831 // TODO: Destructor should derive from MethodCore
3832 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3833 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3834 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3841 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3843 return new EmitContext (
3844 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3847 public ObsoleteAttribute GetObsoleteAttribute ()
3849 return GetObsoleteAttribute (Parent);
3853 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3855 public bool IsExcluded (EmitContext ec)
3857 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3858 return (caching_flags & Flags.Excluded) != 0;
3860 caching_flags &= ~Flags.Excluded_Undetected;
3862 if (base_method == null) {
3863 if (OptAttributes == null)
3866 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3871 foreach (Attribute a in attrs) {
3872 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3873 if (RootContext.AllDefines.Contains (condition))
3877 caching_flags |= Flags.Excluded;
3881 IMethodData md = TypeManager.GetMethod (base_method);
3883 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
3884 caching_flags |= Flags.Excluded;
3890 if (md.IsExcluded (ec)) {
3891 caching_flags |= Flags.Excluded;
3900 public abstract class ConstructorInitializer {
3901 ArrayList argument_list;
3902 protected ConstructorInfo base_constructor;
3903 Parameters parameters;
3906 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
3909 this.argument_list = argument_list;
3910 this.parameters = parameters;
3914 public ArrayList Arguments {
3916 return argument_list;
3920 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
3922 Expression base_constructor_group;
3926 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
3928 if (argument_list != null){
3929 foreach (Argument a in argument_list){
3930 if (!a.Resolve (ec, loc))
3934 ec.CurrentBlock = null;
3936 if (this is ConstructorBaseInitializer) {
3937 if (ec.ContainerType.BaseType == null)
3940 t = ec.ContainerType.BaseType;
3941 if (ec.ContainerType.IsValueType) {
3942 Report.Error (522, loc,
3943 "structs cannot call base class constructors");
3947 t = ec.ContainerType;
3949 base_constructor_group = Expression.MemberLookup (
3950 ec, t, ".ctor", MemberTypes.Constructor,
3951 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3954 if (base_constructor_group == null){
3956 base_constructor_group = Expression.MemberLookup (
3957 ec, t, null, t, ".ctor", MemberTypes.Constructor,
3958 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3962 int errors = Report.Errors;
3963 if (base_constructor_group != null)
3964 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
3965 ec, (MethodGroupExpr) base_constructor_group, argument_list,
3968 if (base_constructor == null) {
3969 if (errors == Report.Errors)
3970 Report.Error (1501, loc, "Can not find a constructor for this argument list");
3975 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
3976 TypeManager.CSharpSignature (base_constructor));
3977 base_constructor = null;
3981 if (base_constructor == caller_builder){
3982 Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
3989 public void Emit (EmitContext ec)
3991 if (base_constructor != null){
3992 ec.Mark (loc, false);
3994 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
3996 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4001 /// Method search for base ctor. (We do not cache it).
4003 Constructor GetOverloadedConstructor (TypeContainer tc)
4005 if (tc.InstanceConstructors == null)
4008 foreach (Constructor c in tc.InstanceConstructors) {
4009 if (Arguments == null) {
4010 if (c.ParameterTypes.Length == 0)
4018 int count = c.ParameterInfo.Count;
4020 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4021 for (int i = 0; i < count-1; i++)
4022 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4027 if (c.ParameterTypes.Length != Arguments.Count)
4030 for (int i = 0; i < Arguments.Count; ++i)
4031 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4046 //TODO: implement caching when it will be necessary
4047 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4049 Constructor ctor = GetOverloadedConstructor (tc);
4053 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4057 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4061 public class ConstructorBaseInitializer : ConstructorInitializer {
4062 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4063 base (argument_list, pars, l)
4067 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4068 if (base_constructor == null)
4071 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4072 if (type_ds == null) {
4073 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (base_constructor);
4076 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (base_constructor), loc);
4081 base.CheckObsoleteAttribute (type_ds, loc);
4086 public class ConstructorThisInitializer : ConstructorInitializer {
4087 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4088 base (argument_list, pars, l)
4093 public class Constructor : MethodCore, IMethodData {
4094 public ConstructorBuilder ConstructorBuilder;
4095 public ConstructorInitializer Initializer;
4096 ListDictionary declarative_security;
4099 // Modifiers allowed for a constructor.
4101 public const int AllowedModifiers =
4103 Modifiers.PROTECTED |
4104 Modifiers.INTERNAL |
4110 bool has_compliant_args = false;
4112 // The spec claims that static is not permitted, but
4113 // my very own code has static constructors.
4115 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4116 ConstructorInitializer init, Location l)
4117 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4123 public override string GetSignatureForError()
4125 if (ConstructorBuilder == null)
4126 return GetSignatureForError (Parent);
4128 return TypeManager.CSharpSignature (ConstructorBuilder);
4131 public bool HasCompliantArgs {
4133 return has_compliant_args;
4137 public override AttributeTargets AttributeTargets {
4139 return AttributeTargets.Constructor;
4145 // Returns true if this is a default constructor
4147 public bool IsDefault ()
4149 if ((ModFlags & Modifiers.STATIC) != 0)
4150 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4151 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4154 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4155 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4156 (Initializer is ConstructorBaseInitializer) &&
4157 (Initializer.Arguments == null);
4160 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4162 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4163 if (declarative_security == null) {
4164 declarative_security = new ListDictionary ();
4166 a.ExtractSecurityPermissionSet (declarative_security);
4170 ConstructorBuilder.SetCustomAttribute (cb);
4173 protected override bool CheckForDuplications ()
4175 ArrayList ar = Parent.InstanceConstructors;
4177 int arLen = ar.Count;
4179 for (int i = 0; i < arLen; i++) {
4180 Constructor m = (Constructor) ar [i];
4181 if (IsDuplicateImplementation (m))
4188 protected override bool CheckBase ()
4190 // Check whether arguments were correct.
4191 if (!DoDefineParameters ())
4194 // TODO: skip the rest for generated ctor
4195 if ((ModFlags & Modifiers.STATIC) != 0)
4198 if (!CheckForDuplications ())
4201 if (Parent.Kind == Kind.Struct) {
4202 if (ParameterTypes.Length == 0) {
4203 Report.Error (568, Location,
4204 "Structs can not contain explicit parameterless " +
4209 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4210 Report.Error (666, Location, "Protected member in struct declaration");
4215 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4216 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4223 // Creates the ConstructorBuilder
4225 public override bool Define ()
4227 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4228 MethodAttributes.SpecialName);
4230 if ((ModFlags & Modifiers.STATIC) != 0) {
4231 ca |= MethodAttributes.Static | MethodAttributes.Private;
4233 ca |= MethodAttributes.HideBySig;
4235 if ((ModFlags & Modifiers.PUBLIC) != 0)
4236 ca |= MethodAttributes.Public;
4237 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4238 if ((ModFlags & Modifiers.INTERNAL) != 0)
4239 ca |= MethodAttributes.FamORAssem;
4241 ca |= MethodAttributes.Family;
4242 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4243 ca |= MethodAttributes.Assembly;
4244 else if (IsDefault ())
4245 ca |= MethodAttributes.Public;
4247 ca |= MethodAttributes.Private;
4250 // Check if arguments were correct.
4254 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4255 ca, CallingConventions,
4258 if ((ModFlags & Modifiers.UNSAFE) != 0)
4259 ConstructorBuilder.InitLocals = false;
4261 TypeManager.AddMethod (ConstructorBuilder, this);
4264 // HACK because System.Reflection.Emit is lame
4266 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4274 public override void Emit ()
4276 EmitContext ec = CreateEmitContext (null, null);
4279 // extern methods have no bodies
4281 if ((ModFlags & Modifiers.EXTERN) != 0) {
4282 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4284 179, Location, "External constructor `" +
4285 TypeManager.CSharpSignature (ConstructorBuilder) +
4286 "' can not have a body");
4289 } else if (block == null) {
4291 501, Location, "Constructor `" +
4292 TypeManager.CSharpSignature (ConstructorBuilder) +
4293 "' must declare a body since it is not marked extern");
4297 if ((ModFlags & Modifiers.STATIC) == 0){
4298 if (Parent.Kind == Kind.Class && Initializer == null)
4299 Initializer = new ConstructorBaseInitializer (
4300 null, Parameters.EmptyReadOnlyParameters, Location);
4304 // Spec mandates that Initializers will not have
4308 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4310 ec.IsStatic = false;
4313 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4315 SourceMethod source = SourceMethod.Create (
4316 Parent, ConstructorBuilder, block);
4319 // Classes can have base initializers and instance field initializers.
4321 if (Parent.Kind == Kind.Class){
4322 if ((ModFlags & Modifiers.STATIC) == 0){
4325 // If we use a "this (...)" constructor initializer, then
4326 // do not emit field initializers, they are initialized in the other constructor
4328 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4329 Parent.EmitFieldInitializers (ec);
4332 if (Initializer != null) {
4333 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4334 Initializer.CheckObsoleteAttribute (Parent, Location);
4336 ec.TestObsoleteMethodUsage = false;
4337 Initializer.Emit (ec);
4340 if ((ModFlags & Modifiers.STATIC) != 0)
4341 Parent.EmitFieldInitializers (ec);
4343 if (OptAttributes != null)
4344 OptAttributes.Emit (ec, this);
4346 // If this is a non-static `struct' constructor and doesn't have any
4347 // initializer, it must initialize all of the struct's fields.
4348 if ((Parent.Kind == Kind.Struct) &&
4349 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4350 Block.AddThisVariable (Parent, Location);
4352 ec.EmitTopBlock (block, ParameterInfo, Location);
4355 source.CloseMethod ();
4359 if (declarative_security != null) {
4360 foreach (DictionaryEntry de in declarative_security) {
4361 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4368 // Is never override
4369 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4374 protected override bool VerifyClsCompliance (DeclSpace ds)
4376 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4380 if (parameter_types.Length > 0) {
4381 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4383 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4385 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4386 foreach (Type param in parameter_types) {
4387 if (param.IsArray) {
4393 has_compliant_args = true;
4397 #region IMethodData Members
4399 public System.Reflection.CallingConventions CallingConventions {
4401 CallingConventions cc = Parameters.GetCallingConvention ();
4403 if (Parent.Kind == Kind.Class)
4404 if ((ModFlags & Modifiers.STATIC) == 0)
4405 cc |= CallingConventions.HasThis;
4407 // FIXME: How is `ExplicitThis' used in C#?
4413 public new Location Location {
4415 return base.Location;
4419 public MemberName MethodName {
4425 public Type ReturnType {
4431 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4433 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4434 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4437 public ObsoleteAttribute GetObsoleteAttribute ()
4442 public bool IsExcluded(EmitContext ec)
4451 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4453 public interface IMethodData
4455 CallingConventions CallingConventions { get; }
4456 Location Location { get; }
4457 MemberName MethodName { get; }
4458 Type[] ParameterTypes { get; }
4459 Type ReturnType { get; }
4461 Attributes OptAttributes { get; }
4462 ToplevelBlock Block { get; }
4464 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4465 ObsoleteAttribute GetObsoleteAttribute ();
4466 string GetSignatureForError (TypeContainer tc);
4467 bool IsExcluded (EmitContext ec);
4468 bool IsClsCompliaceRequired (DeclSpace ds);
4472 // Encapsulates most of the Method's state
4474 public class MethodData {
4476 readonly IMethodData method;
4479 // The return type of this method
4481 public readonly InternalParameters ParameterInfo;
4484 // Are we implementing an interface ?
4486 public bool IsImplementing = false;
4491 protected MemberBase member;
4492 protected int modifiers;
4493 protected MethodAttributes flags;
4495 MethodBuilder builder = null;
4496 public MethodBuilder MethodBuilder {
4502 public MethodData (MemberBase member, InternalParameters parameters,
4503 int modifiers, MethodAttributes flags, IMethodData method)
4505 this.member = member;
4506 this.ParameterInfo = parameters;
4507 this.modifiers = modifiers;
4510 this.method = method;
4513 public bool Define (TypeContainer container)
4515 MethodInfo implementing = null;
4517 string name = method.MethodName.Name;
4518 string method_name = name;
4520 Type[] ParameterTypes = method.ParameterTypes;
4522 if (container.Pending != null){
4523 if (member is Indexer) // TODO: test it, but it should work without this IF
4524 implementing = container.Pending.IsInterfaceIndexer (
4525 member.InterfaceType, method.ReturnType, ParameterTypes);
4527 implementing = container.Pending.IsInterfaceMethod (
4528 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4530 if (member.InterfaceType != null){
4531 if (implementing == null){
4532 if (member is PropertyBase) {
4533 Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
4534 method.GetSignatureForError (container), member.ExplicitInterfaceName);
4537 Report.Error (539, method.Location,
4538 "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
4542 method_name = member.InterfaceType.FullName + "." + name;
4544 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
4545 Report.SymbolRelatedToPreviousError (implementing);
4546 Report.Error (688, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
4547 method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4554 // For implicit implementations, make sure we are public, for
4555 // explicit implementations, make sure we are private.
4557 if (implementing != null){
4559 // Setting null inside this block will trigger a more
4560 // verbose error reporting for missing interface implementations
4562 // The "candidate" function has been flagged already
4563 // but it wont get cleared
4565 if (member.IsExplicitImpl){
4566 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4567 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4568 implementing = null;
4570 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4571 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4573 // If this is an interface method implementation,
4574 // check for public accessibility
4576 implementing = null;
4577 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4578 // We may never be private.
4579 implementing = null;
4580 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4582 // We may be protected if we're overriding something.
4584 implementing = null;
4589 // Static is not allowed
4591 if ((modifiers & Modifiers.STATIC) != 0){
4592 implementing = null;
4593 Modifiers.Error_InvalidModifier (method.Location, "static");
4598 // If implementing is still valid, set flags
4600 if (implementing != null){
4602 // When implementing interface methods, set NewSlot
4603 // unless, we are overwriting a method.
4605 if (implementing.DeclaringType.IsInterface){
4606 if ((modifiers & Modifiers.OVERRIDE) == 0)
4607 flags |= MethodAttributes.NewSlot;
4610 MethodAttributes.Virtual |
4611 MethodAttributes.HideBySig;
4613 // Set Final unless we're virtual, abstract or already overriding a method.
4614 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4615 flags |= MethodAttributes.Final;
4617 IsImplementing = true;
4620 EmitContext ec = method.CreateEmitContext (container, null);
4622 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4624 if (builder == null)
4627 if ((modifiers & Modifiers.UNSAFE) != 0)
4628 builder.InitLocals = false;
4630 if (IsImplementing){
4632 // clear the pending implemntation flag
4634 if (member is Indexer) {
4635 container.Pending.ImplementIndexer (
4636 member.InterfaceType, builder, method.ReturnType,
4637 ParameterTypes, member.IsExplicitImpl);
4639 container.Pending.ImplementMethod (
4640 member.InterfaceType, name, method.ReturnType,
4641 ParameterTypes, member.IsExplicitImpl);
4643 if (member.IsExplicitImpl)
4644 container.TypeBuilder.DefineMethodOverride (
4645 builder, implementing);
4649 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4650 TypeManager.AddMethod (builder, method);
4657 /// Create the MethodBuilder for the method
4659 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4661 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4663 if ((modifiers & extern_static) == extern_static) {
4665 if (method.OptAttributes != null) {
4666 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4667 if (dllimport_attribute != null) {
4668 flags |= MethodAttributes.PinvokeImpl;
4669 builder = dllimport_attribute.DefinePInvokeMethod (
4670 ec, container.TypeBuilder, method_name, flags,
4671 method.ReturnType, ParameterTypes);
4677 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4678 // We are more strict than Microsoft and report CS0626 like error
4679 if (method.OptAttributes == null ||
4680 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4681 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));
4686 builder = container.TypeBuilder.DefineMethod (
4687 method_name, flags, method.CallingConventions,
4688 method.ReturnType, ParameterTypes);
4694 public void Emit (TypeContainer container, Attributable kind)
4697 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4698 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4700 ec = method.CreateEmitContext (container, null);
4702 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container.Parent) != null)
4703 ec.TestObsoleteMethodUsage = false;
4705 Location loc = method.Location;
4706 Attributes OptAttributes = method.OptAttributes;
4708 if (OptAttributes != null)
4709 OptAttributes.Emit (ec, kind);
4711 if (member is MethodCore)
4712 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4714 ToplevelBlock block = method.Block;
4717 // abstract or extern methods have no bodies
4719 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4724 // abstract or extern methods have no bodies.
4726 if ((modifiers & Modifiers.ABSTRACT) != 0)
4728 500, method.Location, "Abstract method `" +
4729 TypeManager.CSharpSignature (builder) +
4730 "' can not have a body");
4732 if ((modifiers & Modifiers.EXTERN) != 0)
4734 179, method.Location, "External method `" +
4735 TypeManager.CSharpSignature (builder) +
4736 "' can not have a body");
4742 // Methods must have a body unless they're extern or abstract
4744 if (block == null) {
4746 501, method.Location, "Method `" +
4747 TypeManager.CSharpSignature (builder) +
4748 "' must declare a body since it is not marked " +
4749 "abstract or extern");
4753 SourceMethod source = SourceMethod.Create (
4754 container, MethodBuilder, method.Block);
4757 // Handle destructors specially
4759 // FIXME: This code generates buggy code
4761 if (member is Destructor)
4762 EmitDestructor (ec, block);
4764 ec.EmitTopBlock (block, ParameterInfo, loc);
4767 source.CloseMethod ();
4770 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4772 ILGenerator ig = ec.ig;
4774 Label finish = ig.DefineLabel ();
4776 block.SetDestructor ();
4778 ig.BeginExceptionBlock ();
4779 ec.ReturnLabel = finish;
4780 ec.HasReturnLabel = true;
4781 ec.EmitTopBlock (block, null, method.Location);
4783 // ig.MarkLabel (finish);
4784 ig.BeginFinallyBlock ();
4786 if (ec.ContainerType.BaseType != null) {
4787 Expression member_lookup = Expression.MemberLookup (
4788 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4789 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4791 if (member_lookup != null){
4792 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4794 ig.Emit (OpCodes.Ldarg_0);
4795 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4799 ig.EndExceptionBlock ();
4800 //ig.MarkLabel (ec.ReturnLabel);
4801 ig.Emit (OpCodes.Ret);
4805 // Should derive from MethodCore
4806 public class Destructor : Method {
4808 public Destructor (TypeContainer ds, Expression return_type, int mod,
4809 string name, Parameters parameters, Attributes attrs,
4811 : base (ds, return_type, mod, false, new MemberName (name),
4812 parameters, attrs, l)
4815 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4817 if (a.Type == TypeManager.conditional_attribute_type) {
4818 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4822 base.ApplyAttributeBuilder (a, cb);
4826 abstract public class MemberBase : MemberCore {
4827 public Expression Type;
4829 public MethodAttributes flags;
4831 protected readonly int explicit_mod_flags;
4834 // The "short" name of this property / indexer / event. This is the
4835 // name without the explicit interface.
4837 public string ShortName;
4840 // The type of this property / indexer / event
4842 public Type MemberType;
4845 // If true, this is an explicit interface implementation
4847 public bool IsExplicitImpl = false;
4850 // The name of the interface we are explicitly implementing
4852 public MemberName ExplicitInterfaceName = null;
4855 // Whether this is an interface member.
4857 public bool IsInterface;
4860 // If true, the interface type we are explicitly implementing
4862 public Type InterfaceType = null;
4865 // The constructor is only exposed to our children
4867 protected MemberBase (TypeContainer parent, Expression type, int mod,
4868 int allowed_mod, int def_mod, MemberName name,
4869 Attributes attrs, Location loc)
4870 : base (parent, name, attrs, loc)
4872 explicit_mod_flags = mod;
4874 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4876 // Check for explicit interface implementation
4877 if (MemberName.Left != null) {
4878 ExplicitInterfaceName = MemberName.Left;
4879 ShortName = MemberName.Name;
4880 IsExplicitImpl = true;
4885 protected virtual bool CheckBase ()
4887 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4888 Report.Error (666, Location, "Protected member in struct declaration");
4892 if ((RootContext.WarningLevel >= 4) &&
4893 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4894 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4895 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4896 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4901 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4905 foreach (Type partype in parameters){
4906 if (partype == TypeManager.void_type) {
4908 1547, Location, "Keyword 'void' cannot " +
4909 "be used in this context");
4913 if (partype.IsPointer){
4916 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4920 if (ds.AsAccessible (partype, ModFlags))
4923 if (this is Indexer)
4924 Report.Error (55, Location,
4925 "Inconsistent accessibility: parameter type `" +
4926 TypeManager.CSharpName (partype) + "' is less " +
4927 "accessible than indexer `" + Name + "'");
4928 else if ((this is Method) && ((Method) this).IsOperator)
4929 Report.Error (57, Location,
4930 "Inconsistent accessibility: parameter type `" +
4931 TypeManager.CSharpName (partype) + "' is less " +
4932 "accessible than operator `" + Name + "'");
4934 Report.Error (51, Location,
4935 "Inconsistent accessibility: parameter type `" +
4936 TypeManager.CSharpName (partype) + "' is less " +
4937 "accessible than method `" + Name + "'");
4944 protected virtual bool DoDefine ()
4946 EmitContext ec = Parent.EmitContext;
4948 throw new InternalErrorException ("MemberBase.DoDefine called too early");
4951 throw new InternalErrorException ();
4954 ModFlags = Modifiers.PUBLIC |
4955 Modifiers.ABSTRACT |
4956 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
4958 flags = MethodAttributes.Public |
4959 MethodAttributes.Abstract |
4960 MethodAttributes.HideBySig |
4961 MethodAttributes.NewSlot |
4962 MethodAttributes.Virtual;
4964 if (!Parent.MethodModifiersValid (this))
4967 flags = Modifiers.MethodAttr (ModFlags);
4970 // Lookup Type, verify validity
4971 bool old_unsafe = ec.InUnsafe;
4972 ec.InUnsafe = InUnsafe;
4973 Type = Type.ResolveAsTypeTerminal (ec, false);
4974 ec.InUnsafe = old_unsafe;
4979 MemberType = Type.Type;
4981 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
4982 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
4983 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
4988 // verify accessibility
4989 if (!Parent.AsAccessible (MemberType, ModFlags)) {
4990 Report.SymbolRelatedToPreviousError (MemberType);
4991 if (this is Property)
4992 Report.Error (53, Location,
4993 "Inconsistent accessibility: property type `" +
4994 TypeManager.CSharpName (MemberType) + "' is less " +
4995 "accessible than property `" + GetSignatureForError () + "'");
4996 else if (this is Indexer)
4997 Report.Error (54, Location,
4998 "Inconsistent accessibility: indexer return type `" +
4999 TypeManager.CSharpName (MemberType) + "' is less " +
5000 "accessible than indexer `" + Name + "'");
5001 else if (this is MethodCore) {
5002 if (this is Operator)
5003 Report.Error (56, Location,
5004 "Inconsistent accessibility: return type `" +
5005 TypeManager.CSharpName (MemberType) + "' is less " +
5006 "accessible than operator `" + Name + "'");
5008 Report.Error (50, Location,
5009 "Inconsistent accessibility: return type `" +
5010 TypeManager.CSharpName (MemberType) + "' is less " +
5011 "accessible than method `" + Name + "'");
5013 Report.Error (52, Location,
5014 "Inconsistent accessibility: field type `" +
5015 TypeManager.CSharpName (MemberType) + "' is less " +
5016 "accessible than field `" + Name + "'");
5021 if (MemberType.IsPointer && !UnsafeOK (Parent))
5024 if (IsExplicitImpl) {
5025 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
5026 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5030 InterfaceType = texpr.ResolveType (ec);
5032 if (!InterfaceType.IsInterface) {
5033 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5038 // Compute the full name that we need to export.
5039 if (InterfaceType.FullName != ExplicitInterfaceName) {
5040 ExplicitInterfaceName = InterfaceType.FullName;
5041 UpdateMemberName ();
5045 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5048 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5055 /// The name of the member can be changed during definition (see IndexerName attribute)
5057 protected virtual void UpdateMemberName ()
5059 MemberName.Name = ShortName;
5062 public override string GetSignatureForError (TypeContainer tc)
5064 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5067 protected bool IsTypePermitted ()
5069 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5070 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5076 protected override bool VerifyClsCompliance(DeclSpace ds)
5078 if (base.VerifyClsCompliance (ds)) {
5082 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5083 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5088 protected override void VerifyObsoleteAttribute()
5090 CheckUsageOfObsoleteAttribute (MemberType);
5095 // Fields and Events both generate FieldBuilders, we use this to share
5096 // their common bits. This is also used to flag usage of the field
5098 abstract public class FieldBase : MemberBase {
5099 public FieldBuilder FieldBuilder;
5100 public Status status;
5103 public enum Status : byte {
5106 HAS_OFFSET = 4 // Used by FieldMember.
5109 static string[] attribute_targets = new string [] { "field" };
5112 /// Symbol with same name in base class/struct
5114 public MemberInfo conflict_symbol;
5117 // The constructor is only exposed to our children
5119 protected FieldBase (TypeContainer parent, Expression type, int mod,
5120 int allowed_mod, MemberName name, object init,
5121 Attributes attrs, Location loc)
5122 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5128 public override AttributeTargets AttributeTargets {
5130 return AttributeTargets.Field;
5134 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5136 if (a.Type == TypeManager.marshal_as_attr_type) {
5137 UnmanagedMarshal marshal = a.GetMarshal (this);
5138 if (marshal != null) {
5139 FieldBuilder.SetMarshal (marshal);
5144 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5145 a.Error_InvalidSecurityParent ();
5149 FieldBuilder.SetCustomAttribute (cb);
5153 // Whether this field has an initializer.
5155 public bool HasInitializer {
5157 return init != null;
5161 protected readonly Object init;
5164 Expression init_expr;
5165 bool init_expr_initialized = false;
5168 // Resolves and returns the field initializer.
5170 public Expression GetInitializerExpression (EmitContext ec)
5172 if (init_expr_initialized)
5176 if (init is Expression)
5177 e = (Expression) init;
5179 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5181 ec.IsFieldInitializer = true;
5182 e = e.DoResolve (ec);
5183 ec.IsFieldInitializer = false;
5186 init_expr_initialized = true;
5191 protected override bool CheckBase ()
5193 if (!base.CheckBase ())
5200 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5201 if (conflict_symbol == null) {
5202 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5203 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5208 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5209 Report.SymbolRelatedToPreviousError (conflict_symbol);
5210 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5216 public override string GetSignatureForError ()
5218 if (FieldBuilder == null) {
5219 return base.GetSignatureForError (Parent);
5221 return TypeManager.GetFullNameSignature (FieldBuilder);
5224 protected virtual bool IsFieldClsCompliant {
5226 if (FieldBuilder == null)
5229 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5233 public override string[] ValidAttributeTargets {
5235 return attribute_targets;
5239 protected override bool VerifyClsCompliance (DeclSpace ds)
5241 if (!base.VerifyClsCompliance (ds))
5244 if (!IsFieldClsCompliant) {
5245 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5251 public void SetAssigned ()
5253 status |= Status.ASSIGNED;
5257 public abstract class FieldMember: FieldBase
5261 protected FieldMember (TypeContainer parent, Expression type, int mod,
5262 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5263 : base (parent, type, mod, allowed_mod, name, init, attrs, loc)
5267 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5269 if (a.Type == TypeManager.field_offset_attribute_type)
5271 status |= Status.HAS_OFFSET;
5273 if (!Parent.HasExplicitLayout) {
5274 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5278 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5279 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5283 base.ApplyAttributeBuilder (a, cb);
5287 public override bool Define()
5289 EmitContext ec = Parent.EmitContext;
5291 throw new InternalErrorException ("FieldMember.Define called too early");
5293 bool old_unsafe = ec.InUnsafe;
5294 ec.InUnsafe = InUnsafe;
5295 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
5299 MemberType = texpr.ResolveType (ec);
5301 ec.InUnsafe = old_unsafe;
5303 if (MemberType == TypeManager.void_type) {
5304 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5311 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5312 Report.Error (52, Location,
5313 "Inconsistent accessibility: field type `" +
5314 TypeManager.CSharpName (MemberType) + "' is less " +
5315 "accessible than field `" + Name + "'");
5319 if (!IsTypePermitted ())
5322 if (MemberType.IsPointer && !UnsafeOK (Parent))
5328 public override void Emit ()
5330 if (OptAttributes != null) {
5331 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5332 OptAttributes.Emit (ec, this);
5335 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5336 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5343 // Represents header string for documentation comment.
5345 public override string DocCommentHeader {
5346 get { return "F:"; }
5350 interface IFixedBuffer
5352 FieldInfo Element { get; }
5353 Type ElementType { get; }
5356 public class FixedFieldExternal: IFixedBuffer
5358 FieldInfo element_field;
5360 public FixedFieldExternal (FieldInfo fi)
5362 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5365 #region IFixedField Members
5367 public FieldInfo Element {
5369 return element_field;
5373 public Type ElementType {
5375 return element_field.FieldType;
5383 /// Fixed buffer implementation
5385 public class FixedField: FieldMember, IFixedBuffer
5387 public const string FixedElementName = "FixedElementField";
5388 static int GlobalCounter = 0;
5389 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5390 static FieldInfo[] fi;
5392 TypeBuilder fixed_buffer_type;
5393 FieldBuilder element;
5394 Expression size_expr;
5397 const int AllowedModifiers =
5400 Modifiers.PROTECTED |
5401 Modifiers.INTERNAL |
5404 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5405 Expression size_expr, Attributes attrs, Location loc):
5406 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5408 if (RootContext.Version == LanguageVersion.ISO_1)
5409 Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
5411 this.size_expr = size_expr;
5414 public override bool Define()
5417 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5418 Report.Warning (-23, Location, "Only not private or internal fixed sized buffers are supported by .NET 1.x");
5421 if (Parent.Kind != Kind.Struct) {
5422 Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
5426 if (!base.Define ())
5429 if (!MemberType.IsPrimitive) {
5430 Report.Error (1663, Location, "Fixed sized buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double");
5434 Expression e = size_expr.Resolve (Parent.EmitContext);
5438 Constant c = e as Constant;
5440 Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
5444 buffer_size = (int)c.GetValue ();
5445 if (buffer_size <= 0) {
5446 Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
5449 buffer_size *= Expression.GetTypeSize (MemberType);
5452 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5454 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5455 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5456 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5457 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5459 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5460 TypeManager.RegisterFieldBase (FieldBuilder, this);
5465 public override void Emit()
5468 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5470 object[] fi_val = new object[1];
5471 fi_val [0] = buffer_size;
5473 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5474 ctor_args, fi, fi_val);
5475 fixed_buffer_type.SetCustomAttribute (cab);
5478 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5479 FieldBuilder.SetCustomAttribute (cab);
5484 protected override bool IsFieldClsCompliant {
5490 #region IFixedField Members
5492 public FieldInfo Element {
5498 public Type ElementType {
5508 // The Field class is used to represents class/struct fields during parsing.
5510 public class Field : FieldMember {
5512 // Modifiers allowed in a class declaration
5514 const int AllowedModifiers =
5517 Modifiers.PROTECTED |
5518 Modifiers.INTERNAL |
5521 Modifiers.VOLATILE |
5525 public Field (TypeContainer parent, Expression type, int mod, string name,
5526 Object expr_or_array_init, Attributes attrs, Location loc)
5527 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5528 expr_or_array_init, attrs, loc)
5532 public override bool Define ()
5534 if (!base.Define ())
5537 if (RootContext.WarningLevel > 1){
5538 Type ptype = Parent.TypeBuilder.BaseType;
5540 // ptype is only null for System.Object while compiling corlib.
5542 TypeContainer.FindMembers (
5543 ptype, MemberTypes.Method,
5544 BindingFlags.Public |
5545 BindingFlags.Static | BindingFlags.Instance,
5546 System.Type.FilterName, Name);
5550 if ((ModFlags & Modifiers.VOLATILE) != 0){
5551 if (!MemberType.IsClass){
5552 Type vt = MemberType;
5554 if (TypeManager.IsEnumType (vt))
5555 vt = TypeManager.EnumToUnderlying (MemberType);
5557 if (!((vt == TypeManager.bool_type) ||
5558 (vt == TypeManager.sbyte_type) ||
5559 (vt == TypeManager.byte_type) ||
5560 (vt == TypeManager.short_type) ||
5561 (vt == TypeManager.ushort_type) ||
5562 (vt == TypeManager.int32_type) ||
5563 (vt == TypeManager.uint32_type) ||
5564 (vt == TypeManager.char_type) ||
5565 (vt == TypeManager.float_type) ||
5566 (!vt.IsValueType))){
5568 677, Location, Parent.MakeName (Name) +
5569 " A volatile field can not be of type `" +
5570 TypeManager.CSharpName (vt) + "'");
5575 if ((ModFlags & Modifiers.READONLY) != 0){
5578 "A field can not be both volatile and readonly");
5583 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5585 if (Parent.Kind == Kind.Struct &&
5586 ((fa & FieldAttributes.Static) == 0) &&
5587 MemberType == Parent.TypeBuilder &&
5588 !TypeManager.IsBuiltinType (MemberType)){
5589 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5590 "' causes a cycle in the structure layout");
5595 FieldBuilder = Parent.TypeBuilder.DefineField (
5596 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5598 TypeManager.RegisterFieldBase (FieldBuilder, this);
5600 catch (ArgumentException) {
5601 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5610 // `set' and `get' accessors are represented with an Accessor.
5612 public class Accessor {
5614 // Null if the accessor is empty, or a Block if not
5616 public const int AllowedModifiers =
5618 Modifiers.PROTECTED |
5619 Modifiers.INTERNAL |
5622 public ToplevelBlock Block;
5623 public Attributes Attributes;
5624 public Location Location;
5625 public int ModFlags;
5627 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5632 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5637 // Ooouh Martin, templates are missing here.
5638 // When it will be possible move here a lot of child code and template method type.
5639 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5640 protected MethodData method_data;
5641 protected ToplevelBlock block;
5642 protected ListDictionary declarative_security;
5644 // The accessor are created event if they are not wanted.
5645 // But we need them because their names are reserved.
5646 // Field says whether accessor will be emited or not
5647 public readonly bool IsDummy;
5649 protected readonly string prefix;
5651 ReturnParameter return_attributes;
5653 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5654 : base (null, SetupName (prefix, member), null, member.Location)
5656 this.prefix = prefix;
5660 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5662 : base (null, SetupName (prefix, member),
5663 accessor.Attributes, accessor.Location)
5665 this.prefix = prefix;
5666 this.block = accessor.Block;
5669 static MemberName SetupName (string prefix, MemberBase member)
5671 MemberName name = member.MemberName.Clone ();
5672 name.Name = prefix + member.ShortName;
5676 public void UpdateName (MemberBase member)
5678 MemberName.Name = prefix + member.ShortName;
5681 #region IMethodData Members
5683 public ToplevelBlock Block {
5693 public CallingConventions CallingConventions {
5695 return CallingConventions.Standard;
5699 public bool IsExcluded (EmitContext ec)
5704 public MemberName MethodName {
5710 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5711 public abstract Type[] ParameterTypes { get; }
5712 public abstract Type ReturnType { get; }
5713 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5717 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5719 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5720 a.Type == TypeManager.conditional_attribute_type) {
5721 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 ());
5725 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5726 if (declarative_security == null)
5727 declarative_security = new ListDictionary ();
5728 a.ExtractSecurityPermissionSet (declarative_security);
5732 if (a.Target == AttributeTargets.Method) {
5733 method_data.MethodBuilder.SetCustomAttribute (cb);
5737 if (a.Target == AttributeTargets.ReturnValue) {
5738 if (return_attributes == null)
5739 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5741 return_attributes.ApplyAttributeBuilder (a, cb);
5745 ApplyToExtraTarget (a, cb);
5748 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5750 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5753 public override bool Define()
5755 throw new NotSupportedException ();
5758 public virtual void Emit (TypeContainer container)
5760 method_data.Emit (container, this);
5762 if (declarative_security != null) {
5763 foreach (DictionaryEntry de in declarative_security) {
5764 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5771 public override bool IsClsCompliaceRequired(DeclSpace ds)
5776 public bool IsDuplicateImplementation (MethodCore method)
5778 if (Name != method.Name)
5781 Type[] param_types = method.ParameterTypes;
5783 if (param_types.Length != ParameterTypes.Length)
5786 for (int i = 0; i < param_types.Length; i++)
5787 if (param_types [i] != ParameterTypes [i])
5790 Report.SymbolRelatedToPreviousError (method);
5791 Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
5795 public new Location Location {
5797 return base.Location;
5802 // Represents header string for documentation comment.
5804 public override string DocCommentHeader {
5805 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5808 protected override void VerifyObsoleteAttribute()
5815 // Properties and Indexers both generate PropertyBuilders, we use this to share
5816 // their common bits.
5818 abstract public class PropertyBase : MethodCore {
5820 public class GetMethod: PropertyMethod
5822 static string[] attribute_targets = new string [] { "method", "return" };
5824 public GetMethod (MethodCore method):
5825 base (method, "get_")
5829 public GetMethod (MethodCore method, Accessor accessor):
5830 base (method, accessor, "get_")
5834 public override MethodBuilder Define(TypeContainer container)
5836 base.Define (container);
5838 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5840 if (!method_data.Define (container))
5843 return method_data.MethodBuilder;
5846 public override string GetSignatureForError (TypeContainer tc)
5848 return String.Concat (base.GetSignatureForError (tc), ".get");
5851 public override Type ReturnType {
5853 return method.MemberType;
5857 public override string[] ValidAttributeTargets {
5859 return attribute_targets;
5864 public class SetMethod: PropertyMethod {
5866 static string[] attribute_targets = new string [] { "method", "param", "return" };
5867 ImplicitParameter param_attr;
5869 public SetMethod (MethodCore method):
5870 base (method, "set_")
5874 public SetMethod (MethodCore method, Accessor accessor):
5875 base (method, accessor, "set_")
5879 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5881 if (a.Target == AttributeTargets.Parameter) {
5882 if (param_attr == null)
5883 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5885 param_attr.ApplyAttributeBuilder (a, cb);
5889 base.ApplyAttributeBuilder (a, cb);
5892 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5894 Parameter [] parms = new Parameter [1];
5895 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
5896 Parameters parameters = new Parameters (parms, null, method.Location);
5898 bool old_unsafe = ec.InUnsafe;
5899 ec.InUnsafe = InUnsafe;
5900 Type [] types = parameters.GetParameterInfo (ec);
5901 ec.InUnsafe = old_unsafe;
5903 return new InternalParameters (types, parameters);
5906 public override MethodBuilder Define (TypeContainer container)
5908 if (container.EmitContext == null)
5909 throw new InternalErrorException ("SetMethod.Define called too early");
5911 base.Define (container);
5913 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5915 if (!method_data.Define (container))
5918 return method_data.MethodBuilder;
5921 public override string GetSignatureForError (TypeContainer tc)
5923 return String.Concat (base.GetSignatureForError (tc), ".set");
5926 public override Type[] ParameterTypes {
5928 return new Type[] { method.MemberType };
5932 public override Type ReturnType {
5934 return TypeManager.void_type;
5938 public override string[] ValidAttributeTargets {
5940 return attribute_targets;
5945 static string[] attribute_targets = new string [] { "property" };
5947 public abstract class PropertyMethod: AbstractPropertyEventMethod
5949 protected readonly MethodCore method;
5950 protected MethodAttributes flags;
5952 public PropertyMethod (MethodCore method, string prefix)
5953 : base (method, prefix)
5955 this.method = method;
5956 Parent = method.Parent;
5959 public PropertyMethod (MethodCore method, Accessor accessor,
5961 : base (method, accessor, prefix)
5963 this.method = method;
5964 Parent = method.Parent;
5965 this.ModFlags = accessor.ModFlags;
5967 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
5968 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
5969 Environment.Exit (1);
5973 public override AttributeTargets AttributeTargets {
5975 return AttributeTargets.Method;
5979 public override bool IsClsCompliaceRequired(DeclSpace ds)
5981 return method.IsClsCompliaceRequired (ds);
5984 public InternalParameters ParameterInfo
5987 return method_data.ParameterInfo;
5991 public virtual MethodBuilder Define (TypeContainer container)
5994 // Check for custom access modifier
5996 if (ModFlags == 0) {
5997 ModFlags = method.ModFlags;
5998 flags = method.flags;
6000 CheckModifiers (container, ModFlags);
6001 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6002 flags = Modifiers.MethodAttr (ModFlags);
6003 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6010 public override Type[] ParameterTypes {
6012 return TypeManager.NoTypes;
6016 public override EmitContext CreateEmitContext (TypeContainer tc,
6019 return new EmitContext (
6020 tc, method.Parent, method.Location, ig, ReturnType,
6021 method.ModFlags, false);
6024 public override ObsoleteAttribute GetObsoleteAttribute ()
6026 return method.GetObsoleteAttribute (method.Parent);
6029 public override string GetSignatureForError (TypeContainer tc)
6031 return String.Concat (tc.Name, '.', method.Name);
6034 void CheckModifiers (TypeContainer container, int modflags)
6037 int mflags = method.ModFlags & Modifiers.Accessibility;
6039 if ((mflags & Modifiers.PUBLIC) != 0) {
6040 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6042 else if ((mflags & Modifiers.PROTECTED) != 0) {
6043 if ((mflags & Modifiers.INTERNAL) != 0)
6044 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6046 flags |= Modifiers.PRIVATE;
6048 else if ((mflags & Modifiers.INTERNAL) != 0)
6049 flags |= Modifiers.PRIVATE;
6051 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6052 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6053 GetSignatureForError (container));
6056 public override bool MarkForDuplicationCheck ()
6058 caching_flags |= Flags.TestMethodDuplication;
6064 public PropertyMethod Get, Set;
6065 public PropertyBuilder PropertyBuilder;
6066 public MethodBuilder GetBuilder, SetBuilder;
6068 protected EmitContext ec;
6070 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6071 int allowed_mod, bool is_iface, MemberName name,
6072 Parameters parameters, Attributes attrs,
6074 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6075 attrs, parameters, loc)
6079 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6081 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6082 a.Error_InvalidSecurityParent ();
6086 PropertyBuilder.SetCustomAttribute (cb);
6089 public override AttributeTargets AttributeTargets {
6091 return AttributeTargets.Property;
6095 public override bool Define ()
6100 if (!IsTypePermitted ())
6106 protected override bool DoDefine ()
6108 if (!base.DoDefine ())
6112 // Accessors modifiers check
6114 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6115 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6116 GetSignatureForError ());
6120 if ((Get.IsDummy || Set.IsDummy)
6121 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6122 Report.Error (276, Location,
6123 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6124 GetSignatureForError ());
6128 if (MemberType.IsAbstract && MemberType.IsSealed) {
6129 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6133 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6137 public override string GetSignatureForError()
6139 if (PropertyBuilder == null)
6140 return GetSignatureForError (Parent);
6142 return TypeManager.CSharpSignature (PropertyBuilder, false);
6145 protected override bool CheckForDuplications ()
6147 ArrayList ar = Parent.Indexers;
6149 int arLen = ar.Count;
6151 for (int i = 0; i < arLen; i++) {
6152 Indexer m = (Indexer) ar [i];
6153 if (IsDuplicateImplementation (m))
6158 ar = Parent.Properties;
6160 int arLen = ar.Count;
6162 for (int i = 0; i < arLen; i++) {
6163 Property m = (Property) ar [i];
6164 if (IsDuplicateImplementation (m))
6172 // TODO: rename to Resolve......
6173 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6175 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6176 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6178 if (base_property == null)
6181 base_ret_type = base_property.PropertyType;
6182 MethodInfo get_accessor = base_property.GetGetMethod (true);
6183 MethodInfo set_accessor = base_property.GetSetMethod (true);
6184 MethodAttributes get_accessor_access, set_accessor_access;
6186 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6187 if (Get != null && !Get.IsDummy && get_accessor == null) {
6188 Report.SymbolRelatedToPreviousError (base_property);
6189 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6192 if (Set != null && !Set.IsDummy && set_accessor == null) {
6193 Report.SymbolRelatedToPreviousError (base_property);
6194 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6199 // Check base class accessors access
6201 get_accessor_access = set_accessor_access = 0;
6202 if ((ModFlags & Modifiers.NEW) == 0) {
6203 if (get_accessor != null) {
6204 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6205 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6207 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6208 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6209 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6212 if (set_accessor != null) {
6213 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6214 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6216 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6217 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6218 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6223 // Get the less restrictive access
6225 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6228 public override void Emit ()
6231 // The PropertyBuilder can be null for explicit implementations, in that
6232 // case, we do not actually emit the ".property", so there is nowhere to
6233 // put the attribute
6235 if (PropertyBuilder != null && OptAttributes != null)
6236 OptAttributes.Emit (ec, this);
6248 /// Tests whether accessors are not in collision with some method (CS0111)
6250 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6252 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6255 protected override void UpdateMemberName ()
6257 base.UpdateMemberName ();
6259 Get.UpdateName (this);
6260 Set.UpdateName (this);
6263 protected override bool VerifyClsCompliance (DeclSpace ds)
6265 if (!base.VerifyClsCompliance (ds))
6268 if ((Get.ModFlags != ModFlags && !Get.IsDummy) || (Set.ModFlags != ModFlags && !Set.IsDummy)) {
6269 Report.Error (3025, Get.ModFlags != ModFlags ? Get.Location : Set.Location,
6270 "CLS-compliant accessors must have the same accessibility as their property");
6275 public override string[] ValidAttributeTargets {
6277 return attribute_targets;
6282 // Represents header string for documentation comment.
6284 public override string DocCommentHeader {
6285 get { return "P:"; }
6289 public class Property : PropertyBase, IIteratorContainer {
6290 const int AllowedModifiers =
6293 Modifiers.PROTECTED |
6294 Modifiers.INTERNAL |
6298 Modifiers.OVERRIDE |
6299 Modifiers.ABSTRACT |
6302 Modifiers.METHOD_YIELDS |
6305 const int AllowedInterfaceModifiers =
6308 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6309 MemberName name, Attributes attrs, Accessor get_block,
6310 Accessor set_block, Location loc)
6311 : base (ds, type, mod,
6312 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6313 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6316 if (get_block == null)
6317 Get = new GetMethod (this);
6319 Get = new GetMethod (this, get_block);
6321 if (set_block == null)
6322 Set = new SetMethod (this);
6324 Set = new SetMethod (this, set_block);
6327 public override bool Define ()
6329 if (!base.Define ())
6335 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6339 GetBuilder = Get.Define (Parent);
6340 if (GetBuilder == null)
6344 // Setup iterator if we are one
6346 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6347 Iterator iterator = new Iterator (
6348 Parent, "get", MemberType,
6349 TypeManager.NoTypes, Get.ParameterInfo,
6350 ModFlags, Get.Block, Location);
6352 if (!iterator.DefineIterator ())
6354 Get.Block = iterator.Block;
6359 SetBuilder = Set.Define (Parent);
6360 if (SetBuilder == null)
6363 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6366 // FIXME - PropertyAttributes.HasDefault ?
6368 PropertyAttributes prop_attr = PropertyAttributes.None;
6370 prop_attr |= PropertyAttributes.RTSpecialName |
6371 PropertyAttributes.SpecialName;
6373 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6374 Name, prop_attr, MemberType, null);
6377 PropertyBuilder.SetGetMethod (GetBuilder);
6380 PropertyBuilder.SetSetMethod (SetBuilder);
6382 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6386 public void SetYields ()
6388 ModFlags |= Modifiers.METHOD_YIELDS;
6393 /// Gigantic workaround for lameness in SRE follows :
6394 /// This class derives from EventInfo and attempts to basically
6395 /// wrap around the EventBuilder so that FindMembers can quickly
6396 /// return this in it search for members
6398 public class MyEventBuilder : EventInfo {
6401 // We use this to "point" to our Builder which is
6402 // not really a MemberInfo
6404 EventBuilder MyBuilder;
6407 // We "catch" and wrap these methods
6409 MethodInfo raise, remove, add;
6411 EventAttributes attributes;
6412 Type declaring_type, reflected_type, event_type;
6417 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6419 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6421 // And now store the values in our own fields.
6423 declaring_type = type_builder;
6425 reflected_type = type_builder;
6427 attributes = event_attr;
6430 this.event_type = event_type;
6434 // Methods that you have to override. Note that you only need
6435 // to "implement" the variants that take the argument (those are
6436 // the "abstract" methods, the others (GetAddMethod()) are
6439 public override MethodInfo GetAddMethod (bool nonPublic)
6444 public override MethodInfo GetRemoveMethod (bool nonPublic)
6449 public override MethodInfo GetRaiseMethod (bool nonPublic)
6455 // These methods make "MyEventInfo" look like a Builder
6457 public void SetRaiseMethod (MethodBuilder raiseMethod)
6459 raise = raiseMethod;
6460 MyBuilder.SetRaiseMethod (raiseMethod);
6463 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6465 remove = removeMethod;
6466 MyBuilder.SetRemoveOnMethod (removeMethod);
6469 public void SetAddOnMethod (MethodBuilder addMethod)
6472 MyBuilder.SetAddOnMethod (addMethod);
6475 public void SetCustomAttribute (CustomAttributeBuilder cb)
6477 MyBuilder.SetCustomAttribute (cb);
6480 public override object [] GetCustomAttributes (bool inherit)
6482 // FIXME : There's nothing which can be seemingly done here because
6483 // we have no way of getting at the custom attribute objects of the
6488 public override object [] GetCustomAttributes (Type t, bool inherit)
6490 // FIXME : Same here !
6494 public override bool IsDefined (Type t, bool b)
6499 public override EventAttributes Attributes {
6505 public override string Name {
6511 public override Type DeclaringType {
6513 return declaring_type;
6517 public override Type ReflectedType {
6519 return reflected_type;
6523 public Type EventType {
6529 public void SetUsed ()
6531 if (my_event != null)
6532 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6537 /// For case when event is declared like property (with add and remove accessors).
6539 public class EventProperty: Event {
6541 static string[] attribute_targets = new string [] { "event", "property" };
6543 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6544 bool is_iface, MemberName name, Object init,
6545 Attributes attrs, Accessor add, Accessor remove,
6547 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6549 Add = new AddDelegateMethod (this, add);
6550 Remove = new RemoveDelegateMethod (this, remove);
6552 // For this event syntax we don't report error CS0067
6553 // because it is hard to do it.
6557 public override string[] ValidAttributeTargets {
6559 return attribute_targets;
6565 /// Event is declared like field.
6567 public class EventField: Event {
6569 static string[] attribute_targets = new string [] { "event", "field", "method" };
6570 static string[] attribute_targets_interface = new string[] { "event", "method" };
6572 public EventField (TypeContainer parent, Expression type, int mod_flags,
6573 bool is_iface, MemberName name, Object init,
6574 Attributes attrs, Location loc)
6575 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6577 Add = new AddDelegateMethod (this);
6578 Remove = new RemoveDelegateMethod (this);
6581 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6583 if (a.Target == AttributeTargets.Field) {
6584 FieldBuilder.SetCustomAttribute (cb);
6588 if (a.Target == AttributeTargets.Method) {
6589 Add.ApplyAttributeBuilder (a, cb);
6590 Remove.ApplyAttributeBuilder (a, cb);
6594 base.ApplyAttributeBuilder (a, cb);
6597 public override string[] ValidAttributeTargets {
6599 return IsInterface ? attribute_targets_interface : attribute_targets;
6604 public abstract class Event : FieldBase {
6606 protected sealed class AddDelegateMethod: DelegateMethod
6609 public AddDelegateMethod (Event method):
6610 base (method, "add_")
6614 public AddDelegateMethod (Event method, Accessor accessor):
6615 base (method, accessor, "add_")
6619 protected override MethodInfo DelegateMethodInfo {
6621 return TypeManager.delegate_combine_delegate_delegate;
6627 protected sealed class RemoveDelegateMethod: DelegateMethod
6629 public RemoveDelegateMethod (Event method):
6630 base (method, "remove_")
6634 public RemoveDelegateMethod (Event method, Accessor accessor):
6635 base (method, accessor, "remove_")
6639 protected override MethodInfo DelegateMethodInfo {
6641 return TypeManager.delegate_remove_delegate_delegate;
6647 public abstract class DelegateMethod: AbstractPropertyEventMethod
6649 protected readonly Event method;
6650 ImplicitParameter param_attr;
6652 static string[] attribute_targets = new string [] { "method", "param", "return" };
6654 public DelegateMethod (Event method, string prefix)
6655 : base (method, prefix)
6657 this.method = method;
6660 public DelegateMethod (Event method, Accessor accessor, string prefix)
6661 : base (method, accessor, prefix)
6663 this.method = method;
6666 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6668 if (a.Target == AttributeTargets.Parameter) {
6669 if (param_attr == null)
6670 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6672 param_attr.ApplyAttributeBuilder (a, cb);
6676 base.ApplyAttributeBuilder (a, cb);
6679 public override AttributeTargets AttributeTargets {
6681 return AttributeTargets.Method;
6685 public override bool IsClsCompliaceRequired(DeclSpace ds)
6687 return method.IsClsCompliaceRequired (ds);
6690 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6692 method_data = new MethodData (method, ip, method.ModFlags,
6693 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6695 if (!method_data.Define (container))
6698 MethodBuilder mb = method_data.MethodBuilder;
6699 mb.DefineParameter (1, ParameterAttributes.None, "value");
6704 public override void Emit (TypeContainer tc)
6706 if (block != null) {
6711 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6712 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6714 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6715 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6716 ig.Emit (OpCodes.Ldsfld, field_info);
6717 ig.Emit (OpCodes.Ldarg_0);
6718 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6719 ig.Emit (OpCodes.Castclass, method.MemberType);
6720 ig.Emit (OpCodes.Stsfld, field_info);
6722 ig.Emit (OpCodes.Ldarg_0);
6723 ig.Emit (OpCodes.Ldarg_0);
6724 ig.Emit (OpCodes.Ldfld, field_info);
6725 ig.Emit (OpCodes.Ldarg_1);
6726 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6727 ig.Emit (OpCodes.Castclass, method.MemberType);
6728 ig.Emit (OpCodes.Stfld, field_info);
6730 ig.Emit (OpCodes.Ret);
6733 protected abstract MethodInfo DelegateMethodInfo { get; }
6735 public override Type[] ParameterTypes {
6737 return new Type[] { method.MemberType };
6741 public override Type ReturnType {
6743 return TypeManager.void_type;
6747 public override EmitContext CreateEmitContext (TypeContainer tc,
6750 return new EmitContext (
6751 tc, method.Parent, Location, ig, ReturnType,
6752 method.ModFlags, false);
6755 public override string GetSignatureForError (TypeContainer tc)
6757 return String.Concat (tc.Name, '.', method.Name);
6760 public override ObsoleteAttribute GetObsoleteAttribute ()
6762 return method.GetObsoleteAttribute (method.Parent);
6765 public override string[] ValidAttributeTargets {
6767 return attribute_targets;
6773 const int AllowedModifiers =
6776 Modifiers.PROTECTED |
6777 Modifiers.INTERNAL |
6782 Modifiers.OVERRIDE |
6786 const int AllowedInterfaceModifiers =
6789 public DelegateMethod Add, Remove;
6790 public MyEventBuilder EventBuilder;
6791 public MethodBuilder AddBuilder, RemoveBuilder;
6793 public Event (TypeContainer parent, Expression type, int mod_flags,
6794 bool is_iface, MemberName name, Object init, Attributes attrs,
6796 : base (parent, type, mod_flags,
6797 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6798 name, init, attrs, loc)
6800 IsInterface = is_iface;
6803 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6805 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6806 a.Error_InvalidSecurityParent ();
6810 EventBuilder.SetCustomAttribute (cb);
6813 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6815 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6818 public override AttributeTargets AttributeTargets {
6820 return AttributeTargets.Event;
6824 public override bool Define ()
6826 EventAttributes e_attr;
6827 e_attr = EventAttributes.None;
6832 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6833 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6834 "': abstract event can not have an initializer");
6838 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6839 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6840 "' : event must be of a delegate type");
6844 EmitContext ec = Parent.EmitContext;
6846 throw new InternalErrorException ("Event.Define called too early?");
6847 bool old_unsafe = ec.InUnsafe;
6848 ec.InUnsafe = InUnsafe;
6850 Parameter [] parms = new Parameter [1];
6851 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6852 Parameters parameters = new Parameters (parms, null, Location);
6853 Type [] types = parameters.GetParameterInfo (ec);
6854 InternalParameters ip = new InternalParameters (types, parameters);
6856 ec.InUnsafe = old_unsafe;
6862 // Now define the accessors
6865 AddBuilder = Add.Define (Parent, ip);
6866 if (AddBuilder == null)
6869 RemoveBuilder = Remove.Define (Parent, ip);
6870 if (RemoveBuilder == null)
6873 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6875 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6876 FieldBuilder = Parent.TypeBuilder.DefineField (
6878 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6879 TypeManager.RegisterPrivateFieldOfEvent (
6880 (EventInfo) EventBuilder, FieldBuilder);
6881 TypeManager.RegisterFieldBase (FieldBuilder, this);
6884 EventBuilder.SetAddOnMethod (AddBuilder);
6885 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6887 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6891 protected override bool CheckBase ()
6893 if (!base.CheckBase ())
6896 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6897 if (!(conflict_symbol is EventInfo)) {
6898 Report.SymbolRelatedToPreviousError (conflict_symbol);
6899 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6907 public override void Emit ()
6909 if (OptAttributes != null) {
6910 EmitContext ec = new EmitContext (
6911 Parent, Location, null, MemberType, ModFlags);
6912 OptAttributes.Emit (ec, this);
6917 Remove.Emit (Parent);
6923 public override string GetSignatureForError ()
6925 if (EventBuilder == null)
6926 return base.GetSignatureForError (Parent);
6928 return TypeManager.GetFullNameSignature (EventBuilder);
6932 // Represents header string for documentation comment.
6934 public override string DocCommentHeader {
6935 get { return "E:"; }
6940 public class Indexer : PropertyBase {
6942 class GetIndexerMethod: GetMethod
6944 public GetIndexerMethod (MethodCore method):
6949 public GetIndexerMethod (MethodCore method, Accessor accessor):
6950 base (method, accessor)
6954 // TODO: one GetSignatureForError is enough (reuse Parent member)
6955 public override string GetSignatureForError (TypeContainer tc)
6957 string core = base.GetSignatureForError (tc);
6958 return core.Replace (TypeContainer.DefaultIndexerName,
6959 String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
6962 public override Type[] ParameterTypes {
6964 return method.ParameterTypes;
6969 class SetIndexerMethod: SetMethod
6971 readonly Parameters parameters;
6973 public SetIndexerMethod (MethodCore method):
6978 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
6979 base (method, accessor)
6981 this.parameters = parameters;
6984 public override Type[] ParameterTypes {
6986 int top = method.ParameterTypes.Length;
6987 Type [] set_pars = new Type [top + 1];
6988 method.ParameterTypes.CopyTo (set_pars, 0);
6989 set_pars [top] = method.MemberType;
6994 protected override InternalParameters GetParameterInfo (EmitContext ec)
6996 Parameter [] fixed_parms = parameters.FixedParameters;
6998 if (fixed_parms == null){
6999 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7000 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7001 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7003 // Here is the problem: the `value' parameter has
7004 // to come *after* the array parameter in the declaration
7006 // X (object [] x, Type value)
7009 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7010 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7014 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7016 fixed_parms.CopyTo (tmp, 0);
7017 tmp [fixed_parms.Length] = new Parameter (
7018 method.Type, "value", Parameter.Modifier.NONE, null);
7020 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7021 Type [] types = set_formal_params.GetParameterInfo (ec);
7023 return new InternalParameters (types, set_formal_params);
7028 const int AllowedModifiers =
7031 Modifiers.PROTECTED |
7032 Modifiers.INTERNAL |
7036 Modifiers.OVERRIDE |
7041 const int AllowedInterfaceModifiers =
7045 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7046 bool is_iface, Parameters parameters, Attributes attrs,
7047 Accessor get_block, Accessor set_block, Location loc)
7048 : base (ds, type, mod,
7049 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7050 is_iface, name, parameters, attrs, loc)
7052 if (get_block == null)
7053 Get = new GetIndexerMethod (this);
7055 Get = new GetIndexerMethod (this, get_block);
7057 if (set_block == null)
7058 Set = new SetIndexerMethod (this);
7060 Set = new SetIndexerMethod (this, parameters, set_block);
7063 public override bool Define ()
7065 PropertyAttributes prop_attr =
7066 PropertyAttributes.RTSpecialName |
7067 PropertyAttributes.SpecialName;
7069 if (!base.Define ())
7072 if (MemberType == TypeManager.void_type) {
7073 Report.Error (620, Location, "Indexers cannot have void type");
7077 if (OptAttributes != null) {
7078 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7079 if (indexer_attr != null) {
7080 // Remove the attribute from the list because it is not emitted
7081 OptAttributes.Attrs.Remove (indexer_attr);
7083 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7085 if (IsExplicitImpl) {
7086 Report.Error (415, indexer_attr.Location,
7087 "The 'IndexerName' attribute is valid only on an " +
7088 "indexer that is not an explicit interface member declaration");
7092 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7093 Report.Error (609, indexer_attr.Location,
7094 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7098 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7099 Report.Error (633, indexer_attr.Location,
7100 "The argument to the 'IndexerName' attribute must be a valid identifier");
7104 UpdateMemberName ();
7108 if (InterfaceType != null) {
7109 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7110 if (base_IndexerName != Name)
7111 ShortName = base_IndexerName;
7112 UpdateMemberName ();
7115 if (!Parent.AddToMemberContainer (this) ||
7116 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7122 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7124 GetBuilder = Get.Define (Parent);
7125 if (GetBuilder == null)
7130 SetBuilder = Set.Define (Parent);
7131 if (SetBuilder == null)
7136 // Now name the parameters
7138 Parameter [] p = Parameters.FixedParameters;
7140 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7141 Report.Error (631, Location, "ref and out are not valid in this context");
7147 for (i = 0; i < p.Length; ++i) {
7149 GetBuilder.DefineParameter (
7150 i + 1, p [i].Attributes, p [i].Name);
7153 SetBuilder.DefineParameter (
7154 i + 1, p [i].Attributes, p [i].Name);
7158 SetBuilder.DefineParameter (
7159 i + 1, ParameterAttributes.None, "value");
7161 if (i != ParameterTypes.Length) {
7162 Parameter array_param = Parameters.ArrayParameter;
7164 SetBuilder.DefineParameter (
7165 i + 1, array_param.Attributes, array_param.Name);
7169 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7170 Name, prop_attr, MemberType, ParameterTypes);
7173 PropertyBuilder.SetGetMethod (GetBuilder);
7176 PropertyBuilder.SetSetMethod (SetBuilder);
7178 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7183 public override string GetSignatureForError ()
7185 if (PropertyBuilder == null)
7186 return GetSignatureForError (Parent);
7188 return TypeManager.CSharpSignature (PropertyBuilder, true);
7191 public override string GetSignatureForError(TypeContainer tc)
7193 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7196 public override bool MarkForDuplicationCheck ()
7198 caching_flags |= Flags.TestMethodDuplication;
7204 public class Operator : MethodCore, IIteratorContainer {
7206 const int AllowedModifiers =
7212 public enum OpType : byte {
7222 // Unary and Binary operators
7245 // Implicit and Explicit
7250 public readonly OpType OperatorType;
7251 public MethodBuilder OperatorMethodBuilder;
7253 public Method OperatorMethod;
7255 static string[] attribute_targets = new string [] { "method", "return" };
7257 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7258 int mod_flags, Parameters parameters,
7259 ToplevelBlock block, Attributes attrs, Location loc)
7260 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7261 new MemberName ("op_" + type), attrs, parameters, loc)
7263 OperatorType = type;
7267 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7269 OperatorMethod.ApplyAttributeBuilder (a, cb);
7272 public override AttributeTargets AttributeTargets {
7274 return AttributeTargets.Method;
7278 protected override bool CheckForDuplications()
7280 ArrayList ar = Parent.Operators;
7282 int arLen = ar.Count;
7284 for (int i = 0; i < arLen; i++) {
7285 Operator o = (Operator) ar [i];
7286 if (IsDuplicateImplementation (o))
7291 ar = Parent.Methods;
7293 int arLen = ar.Count;
7295 for (int i = 0; i < arLen; i++) {
7296 Method m = (Method) ar [i];
7297 if (IsDuplicateImplementation (m))
7305 public override bool Define ()
7308 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7309 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7310 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7317 if (MemberType == TypeManager.void_type) {
7318 Report.Error (590, Location, "User-defined operators cannot return void");
7322 OperatorMethod = new Method (
7323 Parent, Type, ModFlags, false, MemberName,
7324 Parameters, OptAttributes, Location);
7326 OperatorMethod.Block = Block;
7327 OperatorMethod.IsOperator = true;
7328 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7329 OperatorMethod.Define ();
7331 if (OperatorMethod.MethodBuilder == null)
7334 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7336 parameter_types = OperatorMethod.ParameterTypes;
7337 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7338 Type return_type = OperatorMethod.ReturnType;
7339 Type first_arg_type = parameter_types [0];
7344 // Rules for conversion operators
7346 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7347 if (first_arg_type == return_type && first_arg_type == declaring_type){
7350 "User-defined conversion cannot take an object of the " +
7351 "enclosing type and convert to an object of the enclosing" +
7356 if (first_arg_type != declaring_type && return_type != declaring_type){
7359 "User-defined conversion must convert to or from the " +
7364 if (first_arg_type == TypeManager.object_type ||
7365 return_type == TypeManager.object_type){
7368 "User-defined conversion cannot convert to or from " +
7373 if (first_arg_type.IsInterface || return_type.IsInterface){
7376 "User-defined conversion cannot convert to or from an " +
7381 if (first_arg_type.IsSubclassOf (return_type)
7382 || return_type.IsSubclassOf (first_arg_type)){
7383 if (declaring_type.IsSubclassOf (return_type)) {
7384 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7387 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7390 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7391 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7392 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");
7395 } else if (Parameters.FixedParameters.Length == 1) {
7396 // Checks for Unary operators
7398 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7399 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7400 Report.Error (448, Location,
7401 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7404 if (first_arg_type != declaring_type) {
7406 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7411 if (first_arg_type != declaring_type){
7414 "The parameter of a unary operator must be the " +
7419 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7420 if (return_type != TypeManager.bool_type){
7423 "The return type of operator True or False " +
7430 // Checks for Binary operators
7432 if (first_arg_type != declaring_type &&
7433 parameter_types [1] != declaring_type){
7436 "One of the parameters of a binary operator must " +
7437 "be the containing type");
7445 public override void Emit ()
7448 // abstract or extern methods have no bodies
7450 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7453 OperatorMethod.Emit ();
7457 // Operator cannot be override
7458 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7463 public static string GetName (OpType ot)
7466 case OpType.LogicalNot:
7468 case OpType.OnesComplement:
7470 case OpType.Increment:
7472 case OpType.Decrement:
7478 case OpType.Addition:
7480 case OpType.Subtraction:
7482 case OpType.UnaryPlus:
7484 case OpType.UnaryNegation:
7486 case OpType.Multiply:
7488 case OpType.Division:
7490 case OpType.Modulus:
7492 case OpType.BitwiseAnd:
7494 case OpType.BitwiseOr:
7496 case OpType.ExclusiveOr:
7498 case OpType.LeftShift:
7500 case OpType.RightShift:
7502 case OpType.Equality:
7504 case OpType.Inequality:
7506 case OpType.GreaterThan:
7508 case OpType.LessThan:
7510 case OpType.GreaterThanOrEqual:
7512 case OpType.LessThanOrEqual:
7514 case OpType.Implicit:
7516 case OpType.Explicit:
7522 public override string GetSignatureForError (TypeContainer tc)
7524 StringBuilder sb = new StringBuilder ();
7525 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7526 Parameters.FixedParameters [0].GetSignatureForError ());
7528 if (Parameters.FixedParameters.Length > 1) {
7530 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7533 return sb.ToString ();
7536 public override string GetSignatureForError ()
7541 public override bool MarkForDuplicationCheck ()
7543 caching_flags |= Flags.TestMethodDuplication;
7547 public override string ToString ()
7549 if (OperatorMethod == null)
7552 Type return_type = OperatorMethod.ReturnType;
7553 Type [] param_types = OperatorMethod.ParameterTypes;
7555 if (Parameters.FixedParameters.Length == 1)
7556 return String.Format (
7557 "{0} operator {1}({2})",
7558 TypeManager.CSharpName (return_type),
7559 GetName (OperatorType),
7562 return String.Format (
7563 "{0} operator {1}({2}, {3})",
7564 TypeManager.CSharpName (return_type),
7565 GetName (OperatorType),
7566 param_types [0], param_types [1]);
7569 public override string[] ValidAttributeTargets {
7571 return attribute_targets;
7575 public void SetYields ()
7577 ModFlags |= Modifiers.METHOD_YIELDS;
7582 // This is used to compare method signatures
7584 struct MethodSignature {
7586 public Type RetType;
7587 public Type [] Parameters;
7590 /// This delegate is used to extract methods which have the
7591 /// same signature as the argument
7593 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7595 public MethodSignature (string name, Type ret_type, Type [] parameters)
7600 if (parameters == null)
7601 Parameters = TypeManager.NoTypes;
7603 Parameters = parameters;
7606 public override string ToString ()
7609 if (Parameters.Length != 0){
7610 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7611 for (int i = 0; i < Parameters.Length; i++){
7612 sb.Append (Parameters [i]);
7613 if (i+1 < Parameters.Length)
7616 pars = sb.ToString ();
7619 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7622 public override int GetHashCode ()
7624 return Name.GetHashCode ();
7627 public override bool Equals (Object o)
7629 MethodSignature other = (MethodSignature) o;
7631 if (other.Name != Name)
7634 if (other.RetType != RetType)
7637 if (Parameters == null){
7638 if (other.Parameters == null)
7643 if (other.Parameters == null)
7646 int c = Parameters.Length;
7647 if (other.Parameters.Length != c)
7650 for (int i = 0; i < c; i++)
7651 if (other.Parameters [i] != Parameters [i])
7657 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7659 MethodSignature sig = (MethodSignature) filter_criteria;
7661 if (m.Name != sig.Name)
7665 MethodInfo mi = m as MethodInfo;
7666 PropertyInfo pi = m as PropertyInfo;
7669 ReturnType = mi.ReturnType;
7670 else if (pi != null)
7671 ReturnType = pi.PropertyType;
7676 // we use sig.RetType == null to mean `do not check the
7677 // method return value.
7679 if (sig.RetType != null)
7680 if (ReturnType != sig.RetType)
7685 args = TypeManager.GetArgumentTypes (mi);
7687 args = TypeManager.GetArgumentTypes (pi);
7688 Type [] sigp = sig.Parameters;
7690 if (args.Length != sigp.Length)
7693 for (int i = args.Length; i > 0; ){
7695 if (args [i] != sigp [i])