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)
468 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
469 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
473 types = new ArrayList ();
475 base_class_name = null;
478 public bool AddToMemberContainer (MemberCore symbol)
480 return AddToContainer (symbol, String.Concat (Name, ".", symbol.Name), symbol.Name);
483 bool AddToTypeContainer (DeclSpace ds)
485 return AddToContainer (ds, ds.Name, ds.Basename);
488 public void AddConstant (Const constant)
490 if (!AddToMemberContainer (constant))
493 if (constants == null)
494 constants = new MemberCoreArrayList ();
496 constants.Add (constant);
499 public void AddEnum (Mono.CSharp.Enum e)
501 if (!AddToTypeContainer (e))
505 enums = new MemberCoreArrayList ();
510 public void AddClassOrStruct (TypeContainer c)
512 if (!AddToTypeContainer (c))
518 public void AddDelegate (Delegate d)
520 if (!AddToTypeContainer (d))
523 if (delegates == null)
524 delegates = new MemberCoreArrayList ();
529 public void AddMethod (Method method)
531 if (!AddToMemberContainer (method))
535 methods = new MethodArrayList (this);
537 if (method.Name.IndexOf ('.') != -1)
538 methods.Insert (0, method);
540 methods.Add (method);
543 public void AddConstructor (Constructor c)
545 if (c.Name != Basename) {
546 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
549 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
552 if (default_static_constructor != null) {
553 Report.SymbolRelatedToPreviousError (default_static_constructor);
554 Report.Error (111, c.Location, Error111, Name, c.Name);
558 default_static_constructor = c;
561 if (default_constructor != null) {
562 Report.SymbolRelatedToPreviousError (default_constructor);
563 Report.Error (111, c.Location, Error111, c.Location, Name, c.Name);
566 default_constructor = c;
569 if (instance_constructors == null)
570 instance_constructors = new MemberCoreArrayList ();
572 instance_constructors.Add (c);
576 internal static string Error111 {
578 return "Type '{0}' already defines a member called '{1}' with the same parameter types";
582 public void AddInterface (TypeContainer iface)
584 if (!AddToTypeContainer (iface))
587 if (interfaces == null) {
588 interfaces = new MemberCoreArrayList ();
591 interfaces.Add (iface);
594 public void AddField (FieldMember field)
596 if (!AddToMemberContainer (field))
600 fields = new MemberCoreArrayList ();
604 if (field.HasInitializer){
605 if ((field.ModFlags & Modifiers.STATIC) != 0){
606 if (initialized_static_fields == null)
607 initialized_static_fields = new ArrayList ();
609 initialized_static_fields.Add (field);
611 if (initialized_fields == null)
612 initialized_fields = new ArrayList ();
614 initialized_fields.Add (field);
618 if ((field.ModFlags & Modifiers.STATIC) == 0)
619 have_nonstatic_fields = true;
622 public void AddProperty (Property prop)
624 if (!AddToMemberContainer (prop) ||
625 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
628 if (properties == null)
629 properties = new MemberCoreArrayList ();
631 if (prop.Name.IndexOf ('.') != -1)
632 properties.Insert (0, prop);
634 properties.Add (prop);
637 public void AddEvent (Event e)
639 if (!AddToMemberContainer (e))
642 if (e is EventProperty) {
643 if (!AddToMemberContainer (e.Add))
646 if (!AddToMemberContainer (e.Remove))
651 events = new MemberCoreArrayList ();
658 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
660 public void AddIndexer (Indexer i)
662 if (indexers == null)
663 indexers = new IndexerArrayList (this);
665 if (i.IsExplicitImpl)
666 indexers.Insert (0, i);
671 public void AddOperator (Operator op)
673 if (!AddToMemberContainer (op))
676 if (operators == null)
677 operators = new OperatorArrayList (this);
682 public void AddIterator (Iterator i)
684 if (iterators == null)
685 iterators = new ArrayList ();
690 public void AddType (TypeContainer tc)
695 public void AddPart (ClassPart part)
698 parts = new ArrayList ();
703 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
705 if (a.Type == TypeManager.default_member_type) {
706 if (Indexers != null) {
707 Report.Error (646, a.Location,
708 "Cannot specify the DefaultMember attribute on" +
709 " a type containing an indexer");
714 base.ApplyAttributeBuilder (a, cb);
717 public override AttributeTargets AttributeTargets {
721 return AttributeTargets.Class;
723 return AttributeTargets.Struct;
725 return AttributeTargets.Interface;
727 throw new NotSupportedException ();
732 public ArrayList Types {
738 public MethodArrayList Methods {
744 public ArrayList Constants {
750 public ArrayList Interfaces {
756 public ArrayList Iterators {
764 return base_class_name;
768 public ArrayList Bases {
778 public ArrayList Fields {
784 public ArrayList InstanceConstructors {
786 return instance_constructors;
790 public ArrayList Properties {
796 public ArrayList Events {
802 public ArrayList Enums {
808 public ArrayList Indexers {
814 public ArrayList Operators {
820 public ArrayList Delegates {
826 public ArrayList Parts {
832 public virtual TypeAttributes TypeAttr {
834 return Modifiers.TypeAttr (ModFlags, this);
838 public string IndexerName {
840 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
845 // Emits the instance field initializers
847 public virtual bool EmitFieldInitializers (EmitContext ec)
850 Expression instance_expr;
853 fields = initialized_static_fields;
854 instance_expr = null;
856 fields = initialized_fields;
857 instance_expr = new This (Location.Null).Resolve (ec);
863 foreach (Field f in fields){
864 Expression e = f.GetInitializerExpression (ec);
868 Location l = f.Location;
869 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
870 fe.InstanceExpression = instance_expr;
871 ExpressionStatement a = new Assign (fe, e, l);
873 a = a.ResolveStatement (ec);
877 if (RootContext.Optimize) {
878 Constant c = e as Constant;
880 if (c.IsDefaultValue)
885 a.EmitStatement (ec);
892 // Defines the default constructors
894 protected void DefineDefaultConstructor (bool is_static)
898 // The default constructor is public
899 // If the class is abstract, the default constructor is protected
900 // The default static constructor is private
902 int mods = Modifiers.PUBLIC;
904 mods = Modifiers.STATIC | Modifiers.PRIVATE;
905 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
906 mods = Modifiers.PROTECTED;
908 TypeContainer constructor_parent = this;
910 constructor_parent = (TypeContainer) Parts [0];
912 c = new Constructor (constructor_parent, Basename, mods,
913 Parameters.EmptyReadOnlyParameters,
914 new ConstructorBaseInitializer (
915 null, Parameters.EmptyReadOnlyParameters,
921 c.Block = new ToplevelBlock (null, Location);
926 /// The pending methods that need to be implemented
927 // (interfaces or abstract methods)
929 public PendingImplementation Pending;
931 public abstract PendingImplementation GetPendingImplementations ();
933 TypeExpr[] GetPartialBases (out TypeExpr base_class, out bool error)
935 ArrayList ifaces = new ArrayList ();
938 Location base_loc = Location.Null;
940 foreach (ClassPart part in parts) {
941 TypeExpr new_base_class;
942 TypeExpr[] new_ifaces;
944 new_ifaces = part.GetClassBases (out new_base_class, out error);
948 if ((base_class != null) && (new_base_class != null) &&
949 !base_class.Equals (new_base_class)) {
950 Report.Error (263, part.Location,
951 "Partial declarations of `{0}' must " +
952 "not specify different base classes",
955 if (!Location.IsNull (base_loc))
956 Report.LocationOfPreviousError (base_loc);
962 if ((base_class == null) && (new_base_class != null)) {
963 base_class = new_base_class;
964 base_loc = part.Location;
967 if (new_ifaces == null)
970 foreach (TypeExpr iface in new_ifaces) {
972 foreach (TypeExpr old_iface in ifaces) {
973 if (old_iface.Equals (iface)) {
986 TypeExpr[] retval = new TypeExpr [ifaces.Count];
987 ifaces.CopyTo (retval, 0);
991 TypeExpr[] GetNormalBases (out TypeExpr base_class, out bool error)
995 int count = Bases.Count;
998 if (Kind == Kind.Class){
999 TypeExpr name = ResolveBaseTypeExpr (
1000 (Expression) Bases [0], false, Location);
1007 if (!name.IsInterface) {
1008 // base_class could be a class, struct, enum, delegate.
1009 // This is validated in GetClassBases.
1015 TypeExpr [] ifaces = new TypeExpr [count-start];
1017 for (i = start, j = 0; i < count; i++, j++){
1018 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1019 if (resolved == null) {
1024 ifaces [j] = resolved;
1032 /// This function computes the Base class and also the
1033 /// list of interfaces that the class or struct @c implements.
1035 /// The return value is an array (might be null) of
1036 /// interfaces implemented (as Types).
1038 /// The @base_class argument is set to the base object or null
1039 /// if this is `System.Object'.
1041 TypeExpr [] GetClassBases (out TypeExpr base_class, out bool error)
1050 ifaces = GetPartialBases (out base_class, out error);
1051 else if (Bases == null){
1055 ifaces = GetNormalBases (out base_class, out error);
1060 if ((base_class != null) && (Kind == Kind.Class)){
1062 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1063 Report.Error (1521, base_class.Location, "Invalid base type");
1068 if (base_class.IsSealed){
1070 Report.SymbolRelatedToPreviousError (base_class.Type);
1071 if (base_class.Type.IsAbstract) {
1072 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1074 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1079 if (!base_class.CanInheritFrom ()){
1080 Report.Error (644, Location,
1081 "`{0}' cannot inherit from special class `{1}'",
1082 Name, base_class.Name);
1087 if (!base_class.AsAccessible (this, ModFlags)) {
1088 Report.SymbolRelatedToPreviousError (base_class.Type);
1089 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1090 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1094 if (base_class != null)
1095 base_class_name = base_class.Name;
1100 int count = ifaces != null ? ifaces.Length : 0;
1102 for (i = 0; i < count; i++) {
1103 TypeExpr iface = (TypeExpr) ifaces [i];
1105 if (!iface.IsInterface) {
1107 if (Kind != Kind.Class) {
1108 string what = Kind == Kind.Struct ? "Struct" : "Interface";
1110 Report.Error (527, Location,
1111 "In {0} `{1}', type `{2}' is not "+
1112 "an interface", what, Name, iface.Name);
1114 else if (base_class != null)
1115 Report.Error (1721, Location,
1116 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1119 Report.Error (1722, Location,
1120 "In Class `{0}', `{1}' is not " +
1121 "an interface, a base class must be listed first", Name, iface.Name);
1126 for (int x = 0; x < i; x++) {
1127 if (iface.Equals (ifaces [x])) {
1128 Report.Error (528, Location,
1129 "`{0}' is already listed in " +
1130 "interface list", iface.Name);
1135 if ((Kind == Kind.Interface) &&
1136 !iface.AsAccessible (Parent, ModFlags)) {
1137 Report.Error (61, Location,
1138 "Inconsistent accessibility: base " +
1139 "interface `{0}' is less accessible " +
1140 "than interface `{1}'", iface.Name,
1155 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1157 public override TypeBuilder DefineType ()
1159 if (TypeBuilder != null)
1166 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
1173 TypeExpr[] iface_exprs = GetClassBases (out base_type, out error);
1177 if (base_type == null) {
1178 if (Kind == Kind.Class){
1179 if (RootContext.StdLib)
1180 base_type = TypeManager.system_object_expr;
1181 else if (Name != "System.Object")
1182 base_type = TypeManager.system_object_expr;
1183 } else if (Kind == Kind.Struct) {
1185 // If we are compiling our runtime,
1186 // and we are defining ValueType, then our
1187 // base is `System.Object'.
1189 if (!RootContext.StdLib && Name == "System.ValueType")
1190 base_type = TypeManager.system_object_expr;
1192 base_type = TypeManager.system_valuetype_expr;
1196 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1197 throw new Exception ();
1199 TypeAttributes type_attributes = TypeAttr;
1201 if (base_type != null) {
1202 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1203 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1204 ptype = base_type.ResolveType (TypeResolveEmitContext);
1205 if (ptype == null) {
1213 if (TypeManager.NamespaceClash (Name, Location)) {
1218 ModuleBuilder builder = CodeGen.Module.Builder;
1219 TypeBuilder = builder.DefineType (
1220 Name, type_attributes, ptype, null);
1223 TypeBuilder builder = Parent.TypeBuilder;
1224 if (builder == null)
1227 TypeBuilder = builder.DefineNestedType (
1228 Basename, type_attributes, ptype, null);
1231 catch (ArgumentException) {
1232 Report.RuntimeMissingSupport (Location, "static classes");
1236 if (Parts != null) {
1238 foreach (ClassPart part in Parts) {
1239 part.TypeBuilder = TypeBuilder;
1241 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1242 part.ec.ContainerType = TypeBuilder;
1246 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1247 ec.ContainerType = TypeBuilder;
1251 // Structs with no fields need to have at least one byte.
1252 // The right thing would be to set the PackingSize in a DefineType
1253 // but there are no functions that allow interfaces *and* the size to
1257 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1258 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1259 FieldAttributes.Private);
1262 // add interfaces that were not added at type creation
1263 if (iface_exprs != null) {
1264 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1265 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1266 TypeResolveEmitContext.ContainerType = TypeBuilder;
1267 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1268 if (ifaces == null) {
1273 foreach (Type itype in ifaces)
1274 TypeBuilder.AddInterfaceImplementation (itype);
1276 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1279 TypeManager.AddUserType (Name, TypeBuilder, this);
1281 if (!(this is Iterator))
1282 RootContext.RegisterOrder (this);
1284 if (!DefineNestedTypes ()) {
1293 protected virtual bool DefineNestedTypes ()
1295 if (Interfaces != null) {
1296 foreach (TypeContainer iface in Interfaces)
1297 if (iface.DefineType () == null)
1301 if (Types != null) {
1302 foreach (TypeContainer tc in Types)
1303 if (tc.DefineType () == null)
1307 if (Delegates != null) {
1308 foreach (Delegate d in Delegates)
1309 if (d.DefineType () == null)
1313 if (Enums != null) {
1314 foreach (Enum en in Enums)
1315 if (en.DefineType () == null)
1322 static void Error_KeywordNotAllowed (Location loc)
1324 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1328 /// Populates our TypeBuilder with fields and methods
1330 public override bool DefineMembers (TypeContainer container)
1332 if (members_defined)
1333 return members_defined_ok;
1335 members_defined_ok = DoDefineMembers ();
1336 members_defined = true;
1338 return members_defined_ok;
1341 bool DoDefineMembers ()
1344 if ((ModFlags & Modifiers.NEW) != 0)
1345 Error_KeywordNotAllowed (Location);
1347 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1348 if (conflict_symbol == null) {
1349 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1350 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1352 if ((ModFlags & Modifiers.NEW) == 0) {
1353 Report.SymbolRelatedToPreviousError (conflict_symbol);
1354 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1359 DefineContainerMembers (constants);
1360 DefineContainerMembers (fields);
1362 if ((Kind == Kind.Class) && !(this is ClassPart)){
1363 if ((instance_constructors == null) &&
1364 !(this is StaticClass)) {
1365 if (default_constructor == null)
1366 DefineDefaultConstructor (false);
1369 if (initialized_static_fields != null &&
1370 default_static_constructor == null)
1371 DefineDefaultConstructor (true);
1374 if (Kind == Kind.Struct){
1376 // Structs can not have initialized instance
1379 if (initialized_static_fields != null &&
1380 default_static_constructor == null)
1381 DefineDefaultConstructor (true);
1383 if (initialized_fields != null)
1384 ReportStructInitializedInstanceError ();
1387 Pending = GetPendingImplementations ();
1389 if (parts != null) {
1390 foreach (ClassPart part in parts) {
1391 if (!part.DefineMembers (this))
1397 // Constructors are not in the defined_names array
1399 DefineContainerMembers (instance_constructors);
1401 if (default_static_constructor != null)
1402 default_static_constructor.Define ();
1404 DefineContainerMembers (properties);
1405 DefineContainerMembers (events);
1406 DefineContainerMembers (indexers);
1407 DefineContainerMembers (methods);
1408 DefineContainerMembers (operators);
1409 DefineContainerMembers (enums);
1410 DefineContainerMembers (delegates);
1413 if (!(this is ClassPart))
1414 member_cache = new MemberCache (this);
1417 if (parts != null) {
1418 foreach (ClassPart part in parts)
1419 part.member_cache = member_cache;
1422 if (iterators != null) {
1423 foreach (Iterator iterator in iterators) {
1424 if (iterator.DefineType () == null)
1428 foreach (Iterator iterator in iterators) {
1429 if (!iterator.DefineMembers (this))
1437 void ReportStructInitializedInstanceError ()
1439 string n = TypeBuilder.FullName;
1441 foreach (Field f in initialized_fields){
1444 "`" + n + "." + f.Name + "': can not have " +
1445 "instance field initializers in structs");
1449 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1452 mcal.DefineContainerMembers ();
1455 public override bool Define ()
1457 if (parts != null) {
1458 foreach (ClassPart part in parts) {
1459 if (!part.Define ())
1467 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1469 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1473 /// This function is based by a delegate to the FindMembers routine
1475 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1481 /// This filter is used by FindMembers, and we just keep
1482 /// a global for the filter to `AlwaysAccept'
1484 static MemberFilter accepting_filter;
1487 static TypeContainer ()
1489 accepting_filter = new MemberFilter (AlwaysAccept);
1492 public MethodInfo[] GetMethods ()
1494 ArrayList members = new ArrayList ();
1496 DefineMembers (null);
1498 if (methods != null) {
1499 int len = methods.Count;
1500 for (int i = 0; i < len; i++) {
1501 Method m = (Method) methods [i];
1503 members.Add (m.MethodBuilder);
1507 if (operators != null) {
1508 int len = operators.Count;
1509 for (int i = 0; i < len; i++) {
1510 Operator o = (Operator) operators [i];
1512 members.Add (o.OperatorMethodBuilder);
1516 if (properties != null) {
1517 int len = properties.Count;
1518 for (int i = 0; i < len; i++) {
1519 Property p = (Property) properties [i];
1521 if (p.GetBuilder != null)
1522 members.Add (p.GetBuilder);
1523 if (p.SetBuilder != null)
1524 members.Add (p.SetBuilder);
1528 if (indexers != null) {
1529 int len = indexers.Count;
1530 for (int i = 0; i < len; i++) {
1531 Indexer ix = (Indexer) indexers [i];
1533 if (ix.GetBuilder != null)
1534 members.Add (ix.GetBuilder);
1535 if (ix.SetBuilder != null)
1536 members.Add (ix.SetBuilder);
1540 if (events != null) {
1541 int len = events.Count;
1542 for (int i = 0; i < len; i++) {
1543 Event e = (Event) events [i];
1545 if (e.AddBuilder != null)
1546 members.Add (e.AddBuilder);
1547 if (e.RemoveBuilder != null)
1548 members.Add (e.RemoveBuilder);
1552 MethodInfo[] retMethods = new MethodInfo [members.Count];
1553 members.CopyTo (retMethods, 0);
1557 // Indicated whether container has StructLayout attribute set Explicit
1558 public virtual bool HasExplicitLayout {
1564 public override Type FindNestedType (string name)
1566 ArrayList [] lists = { types, enums, delegates, interfaces };
1568 for (int j = 0; j < lists.Length; ++j) {
1569 ArrayList list = lists [j];
1573 int len = list.Count;
1574 for (int i = 0; i < len; ++i) {
1575 DeclSpace ds = (DeclSpace) list [i];
1576 if (ds.Basename == name) {
1578 return ds.TypeBuilder;
1586 private void FindMembers_NestedTypes (int modflags,
1587 BindingFlags bf, MemberFilter filter, object criteria,
1588 ref ArrayList members)
1590 ArrayList [] lists = { types, enums, delegates, interfaces };
1592 for (int j = 0; j < lists.Length; ++j) {
1593 ArrayList list = lists [j];
1597 int len = list.Count;
1598 for (int i = 0; i < len; i++) {
1599 DeclSpace ds = (DeclSpace) list [i];
1601 if ((ds.ModFlags & modflags) == 0)
1604 TypeBuilder tb = ds.TypeBuilder;
1606 if (!(criteria is string) || ds.Basename.Equals (criteria))
1607 tb = ds.DefineType ();
1610 if (tb != null && (filter (tb, criteria) == true)) {
1611 if (members == null)
1612 members = new ArrayList ();
1621 /// This method returns the members of this type just like Type.FindMembers would
1622 /// Only, we need to use this for types which are _being_ defined because MS'
1623 /// implementation can't take care of that.
1626 // FIXME: return an empty static array instead of null, that cleans up
1627 // some code and is consistent with some coding conventions I just found
1631 // Notice that in various cases we check if our field is non-null,
1632 // something that would normally mean that there was a bug elsewhere.
1634 // The problem happens while we are defining p-invoke methods, as those
1635 // will trigger a FindMembers, but this happens before things are defined
1637 // Since the whole process is a no-op, it is fine to check for null here.
1639 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1640 MemberFilter filter, object criteria)
1642 ArrayList members = null;
1645 if ((bf & BindingFlags.Public) != 0)
1646 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1648 if ((bf & BindingFlags.NonPublic) != 0)
1649 modflags |= Modifiers.PRIVATE;
1651 int static_mask = 0, static_flags = 0;
1652 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1653 case BindingFlags.Static:
1654 static_mask = static_flags = Modifiers.STATIC;
1657 case BindingFlags.Instance:
1658 static_mask = Modifiers.STATIC;
1663 static_mask = static_flags = 0;
1667 Timer.StartTimer (TimerType.TcFindMembers);
1670 filter = accepting_filter;
1672 if ((mt & MemberTypes.Field) != 0) {
1673 if (fields != null) {
1674 int len = fields.Count;
1675 for (int i = 0; i < len; i++) {
1676 FieldMember f = (FieldMember) fields [i];
1678 if ((f.ModFlags & modflags) == 0)
1680 if ((f.ModFlags & static_mask) != static_flags)
1683 FieldBuilder fb = f.FieldBuilder;
1684 if (fb != null && filter (fb, criteria) == true) {
1685 if (members == null)
1686 members = new ArrayList ();
1693 if (constants != null) {
1694 int len = constants.Count;
1695 for (int i = 0; i < len; i++) {
1696 Const con = (Const) constants [i];
1698 if ((con.ModFlags & modflags) == 0)
1700 if ((con.ModFlags & static_mask) != static_flags)
1703 FieldBuilder fb = con.FieldBuilder;
1706 fb = con.FieldBuilder;
1708 if (fb != null && filter (fb, criteria) == true) {
1709 if (members == null)
1710 members = new ArrayList ();
1718 if ((mt & MemberTypes.Method) != 0) {
1719 if (methods != null) {
1720 int len = methods.Count;
1721 for (int i = 0; i < len; i++) {
1722 Method m = (Method) methods [i];
1724 if ((m.ModFlags & modflags) == 0)
1726 if ((m.ModFlags & static_mask) != static_flags)
1729 MethodBuilder mb = m.MethodBuilder;
1731 if (mb != null && filter (mb, criteria) == true) {
1732 if (members == null)
1733 members = new ArrayList ();
1740 if (operators != null) {
1741 int len = operators.Count;
1742 for (int i = 0; i < len; i++) {
1743 Operator o = (Operator) operators [i];
1745 if ((o.ModFlags & modflags) == 0)
1747 if ((o.ModFlags & static_mask) != static_flags)
1750 MethodBuilder ob = o.OperatorMethodBuilder;
1751 if (ob != null && filter (ob, criteria) == true) {
1752 if (members == null)
1753 members = new ArrayList ();
1760 if (properties != null) {
1761 int len = properties.Count;
1762 for (int i = 0; i < len; i++) {
1763 Property p = (Property) properties [i];
1765 if ((p.ModFlags & modflags) == 0)
1767 if ((p.ModFlags & static_mask) != static_flags)
1773 if (b != null && filter (b, criteria) == true) {
1774 if (members == null)
1775 members = new ArrayList ();
1781 if (b != null && filter (b, criteria) == true) {
1782 if (members == null)
1783 members = new ArrayList ();
1790 if (indexers != null) {
1791 int len = indexers.Count;
1792 for (int i = 0; i < len; i++) {
1793 Indexer ix = (Indexer) indexers [i];
1795 if ((ix.ModFlags & modflags) == 0)
1797 if ((ix.ModFlags & static_mask) != static_flags)
1803 if (b != null && filter (b, criteria) == true) {
1804 if (members == null)
1805 members = new ArrayList ();
1811 if (b != null && filter (b, criteria) == true) {
1812 if (members == null)
1813 members = new ArrayList ();
1821 if ((mt & MemberTypes.Event) != 0) {
1822 if (events != null) {
1823 int len = events.Count;
1824 for (int i = 0; i < len; i++) {
1825 Event e = (Event) events [i];
1827 if ((e.ModFlags & modflags) == 0)
1829 if ((e.ModFlags & static_mask) != static_flags)
1832 MemberInfo eb = e.EventBuilder;
1833 if (eb != null && filter (eb, criteria) == true) {
1834 if (members == null)
1835 members = new ArrayList ();
1837 members.Add (e.EventBuilder);
1843 if ((mt & MemberTypes.Property) != 0){
1844 if (properties != null) {
1845 int len = properties.Count;
1846 for (int i = 0; i < len; i++) {
1847 Property p = (Property) properties [i];
1849 if ((p.ModFlags & modflags) == 0)
1851 if ((p.ModFlags & static_mask) != static_flags)
1854 MemberInfo pb = p.PropertyBuilder;
1855 if (pb != null && filter (pb, criteria) == true) {
1856 if (members == null)
1857 members = new ArrayList ();
1859 members.Add (p.PropertyBuilder);
1864 if (indexers != null) {
1865 int len = indexers.Count;
1866 for (int i = 0; i < len; i++) {
1867 Indexer ix = (Indexer) indexers [i];
1869 if ((ix.ModFlags & modflags) == 0)
1871 if ((ix.ModFlags & static_mask) != static_flags)
1874 MemberInfo ib = ix.PropertyBuilder;
1875 if (ib != null && filter (ib, criteria) == true) {
1876 if (members == null)
1877 members = new ArrayList ();
1879 members.Add (ix.PropertyBuilder);
1885 if ((mt & MemberTypes.NestedType) != 0)
1886 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1888 if ((mt & MemberTypes.Constructor) != 0){
1889 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1890 int len = instance_constructors.Count;
1891 for (int i = 0; i < len; i++) {
1892 Constructor c = (Constructor) instance_constructors [i];
1894 ConstructorBuilder cb = c.ConstructorBuilder;
1895 if (cb != null && filter (cb, criteria) == true) {
1896 if (members == null)
1897 members = new ArrayList ();
1904 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1905 ConstructorBuilder cb =
1906 default_static_constructor.ConstructorBuilder;
1908 if (cb != null && filter (cb, criteria) == true) {
1909 if (members == null)
1910 members = new ArrayList ();
1918 // Lookup members in base if requested.
1920 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1921 if (TypeBuilder.BaseType != null) {
1922 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1923 if (list.Count > 0) {
1924 if (members == null)
1925 members = new ArrayList ();
1927 members.AddRange (list);
1930 if (ifaces != null) {
1931 foreach (Type base_type in ifaces) {
1932 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1934 if (list.Count > 0) {
1935 if (members == null)
1936 members = new ArrayList ();
1937 members.AddRange (list);
1943 Timer.StopTimer (TimerType.TcFindMembers);
1945 if (members == null)
1946 return MemberList.Empty;
1948 return new MemberList (members);
1951 public override MemberCache MemberCache {
1953 return member_cache;
1957 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1958 MemberFilter filter, object criteria)
1960 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1963 return ds.FindMembers (mt, bf, filter, criteria);
1965 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1970 // FindMethods will look for methods not only in the type `t', but in
1971 // any interfaces implemented by the type.
1973 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1974 MemberFilter filter, object criteria)
1980 /// Emits the values for the constants
1982 public void EmitConstants ()
1984 if (constants != null)
1985 foreach (Const con in constants)
1990 protected virtual void VerifyMembers (EmitContext ec)
1993 // Check for internal or private fields that were never assigned
1995 if (RootContext.WarningLevel >= 4) {
1996 if (fields != null){
1997 foreach (Field f in fields) {
1998 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2001 if ((f.status & Field.Status.USED) == 0){
2002 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2007 // Only report 649 on level 4
2009 if (RootContext.WarningLevel < 4)
2012 if ((f.status & Field.Status.ASSIGNED) != 0)
2015 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2022 /// Emits the code, this step is performed after all
2023 /// the types, enumerations, constructors
2025 public void EmitType ()
2027 if (OptAttributes != null)
2028 OptAttributes.Emit (ec, this);
2032 if (instance_constructors != null) {
2033 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2034 bool has_compliant_args = false;
2036 foreach (Constructor c in instance_constructors) {
2039 if (has_compliant_args)
2042 has_compliant_args = c.HasCompliantArgs;
2044 if (!has_compliant_args)
2045 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2047 foreach (Constructor c in instance_constructors)
2054 if (default_static_constructor != null)
2055 default_static_constructor.Emit ();
2057 if (methods != null)
2058 foreach (Method m in methods)
2061 if (operators != null)
2062 foreach (Operator o in operators)
2065 if (properties != null)
2066 foreach (Property p in properties)
2069 if (indexers != null){
2074 foreach (FieldMember f in fields)
2077 if (events != null){
2078 foreach (Event e in Events)
2082 if (delegates != null) {
2083 foreach (Delegate d in Delegates) {
2088 if (enums != null) {
2089 foreach (Enum e in enums) {
2094 if (parts != null) {
2095 foreach (ClassPart part in parts)
2099 if ((Pending != null) && !(this is ClassPart))
2100 if (Pending.VerifyPendingMethods ())
2105 if (iterators != null)
2106 foreach (Iterator iterator in iterators)
2107 iterator.EmitType ();
2109 // if (types != null)
2110 // foreach (TypeContainer tc in types)
2114 public override void CloseType ()
2116 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2120 caching_flags |= Flags.CloseTypeCreated;
2121 TypeBuilder.CreateType ();
2122 } catch (TypeLoadException){
2124 // This is fine, the code still created the type
2126 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2127 // Console.WriteLine (e.Message);
2129 Console.WriteLine ("In type: " + Name);
2134 foreach (Enum en in Enums)
2138 foreach (TypeContainer tc in Types)
2139 if (tc.Kind == Kind.Struct)
2142 foreach (TypeContainer tc in Types)
2143 if (tc.Kind != Kind.Struct)
2147 if (Delegates != null)
2148 foreach (Delegate d in Delegates)
2151 if (Iterators != null)
2152 foreach (Iterator i in Iterators)
2160 initialized_fields = null;
2161 initialized_static_fields = null;
2170 default_constructor = null;
2171 default_static_constructor = null;
2173 OptAttributes = null;
2176 member_cache = null;
2179 // TODO: make it obsolete and use GetSignatureForError
2180 public string MakeName (string n)
2182 return "`" + Name + "." + n + "'";
2186 // Performs the validation on a Method's modifiers (properties have
2187 // the same properties).
2189 public bool MethodModifiersValid (MemberCore mc)
2191 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2192 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2193 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2195 int flags = mc.ModFlags;
2198 // At most one of static, virtual or override
2200 if ((flags & Modifiers.STATIC) != 0){
2201 if ((flags & vao) != 0){
2202 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2203 GetSignatureForError ());
2208 if (Kind == Kind.Struct){
2209 if ((flags & va) != 0){
2210 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2215 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2216 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2221 // If the declaration includes the abstract modifier, then the
2222 // declaration does not include static, virtual or extern
2224 if ((flags & Modifiers.ABSTRACT) != 0){
2225 if ((flags & Modifiers.EXTERN) != 0){
2227 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2231 if ((flags & Modifiers.SEALED) != 0) {
2232 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2236 if ((flags & Modifiers.VIRTUAL) != 0){
2237 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2241 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2242 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2247 if ((flags & Modifiers.PRIVATE) != 0){
2248 if ((flags & vao) != 0){
2249 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2254 if ((flags & Modifiers.SEALED) != 0){
2255 if ((flags & Modifiers.OVERRIDE) == 0){
2256 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2264 public bool UserDefinedStaticConstructor {
2266 return default_static_constructor != null;
2270 public Constructor DefaultStaticConstructor {
2271 get { return default_static_constructor; }
2274 protected override bool VerifyClsCompliance (DeclSpace ds)
2276 if (!base.VerifyClsCompliance (ds))
2281 Type base_type = TypeBuilder.BaseType;
2282 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2283 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2286 if (!Parent.IsClsCompliaceRequired (ds)) {
2287 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2288 GetSignatureForError (), Parent.GetSignatureForError ());
2295 /// Checks whether container name is CLS Compliant
2297 void VerifyClsName ()
2299 Hashtable base_members = base_cache == null ?
2301 base_cache.GetPublicMembers ();
2302 Hashtable this_members = new Hashtable ();
2304 foreach (DictionaryEntry entry in defined_names) {
2305 MemberCore mc = (MemberCore)entry.Value;
2306 if (!mc.IsClsCompliaceRequired (this))
2309 string name = (string)entry.Key;
2310 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2312 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2313 object found = base_members [lcase];
2314 if (found == null) {
2315 found = this_members [lcase];
2316 if (found == null) {
2317 this_members.Add (lcase, mc);
2322 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2325 if (found is MemberInfo) {
2326 if (basename == ((MemberInfo)found).Name)
2328 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2330 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2332 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2338 /// Performs checks for an explicit interface implementation. First it
2339 /// checks whether the `interface_type' is a base inteface implementation.
2340 /// Then it checks whether `name' exists in the interface type.
2342 public virtual bool VerifyImplements (Type interface_type, string full,
2343 string name, Location loc)
2347 if (ifaces != null){
2348 foreach (Type t in ifaces){
2349 if (t == interface_type){
2357 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2358 full, interface_type.FullName);
2365 protected override void VerifyObsoleteAttribute()
2367 CheckUsageOfObsoleteAttribute (ptype);
2372 foreach (Type iface in ifaces) {
2373 CheckUsageOfObsoleteAttribute (iface);
2382 string IMemberContainer.Name {
2388 Type IMemberContainer.Type {
2394 MemberCache IMemberContainer.MemberCache {
2396 return member_cache;
2400 bool IMemberContainer.IsInterface {
2402 return Kind == Kind.Interface;
2406 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2408 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2412 // Generates xml doc comments (if any), and if required,
2413 // handle warning report.
2415 internal override void GenerateDocComment (DeclSpace ds)
2417 DocUtil.GenerateTypeDocComment (this, ds);
2420 public override string DocCommentHeader {
2421 get { return "T:"; }
2424 public virtual MemberCache BaseCache {
2426 if (base_cache != null)
2428 if (TypeBuilder.BaseType != null)
2429 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2430 if (TypeBuilder.IsInterface)
2431 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2437 public class PartialContainer : TypeContainer {
2439 public readonly Namespace Namespace;
2440 public readonly int OriginalModFlags;
2441 public readonly int AllowedModifiers;
2442 public readonly TypeAttributes DefaultTypeAttributes;
2444 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2445 MemberName member_name, int mod_flags, Kind kind,
2448 PartialContainer pc;
2449 string full_name = member_name.GetName (true);
2450 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2452 pc = ds as PartialContainer;
2456 260, ds.Location, "Missing partial modifier " +
2457 "on declaration of type `{0}'; another " +
2458 "partial implementation of this type exists",
2459 member_name.GetPartialName());
2461 Report.LocationOfPreviousError (loc);
2465 if (pc.Kind != kind) {
2467 261, loc, "Partial declarations of `{0}' " +
2468 "must be all classes, all structs or " +
2469 "all interfaces", member_name.GetPartialName ());
2473 if (pc.OriginalModFlags != mod_flags) {
2475 262, loc, "Partial declarations of `{0}' " +
2476 "have conflicting accessibility modifiers",
2477 member_name.GetPartialName ());
2484 if (parent is ClassPart)
2485 parent = ((ClassPart) parent).PartialContainer;
2487 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2488 RootContext.Tree.RecordDecl (full_name, pc);
2490 if (kind == Kind.Interface)
2491 parent.AddInterface (pc);
2492 else if (kind == Kind.Class || kind == Kind.Struct)
2493 parent.AddClassOrStruct (pc);
2495 throw new InvalidOperationException ();
2500 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2501 MemberName name, int mod, Attributes attrs,
2502 Kind kind, Location loc)
2504 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2506 // An error occured; create a dummy container, but don't
2508 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2511 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2516 protected PartialContainer (Namespace ns, TypeContainer parent,
2517 MemberName name, int mod, Kind kind, Location l)
2518 : base (null, parent, name, null, kind, l)
2520 this.Namespace = ns;
2524 AllowedModifiers = Class.AllowedModifiers;
2525 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2529 AllowedModifiers = Struct.AllowedModifiers;
2530 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2533 case Kind.Interface:
2534 AllowedModifiers = Interface.AllowedModifiers;
2535 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2539 throw new InvalidOperationException ();
2543 if (parent.Parent == null)
2544 accmods = Modifiers.INTERNAL;
2546 accmods = Modifiers.PRIVATE;
2548 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2549 this.OriginalModFlags = mod;
2552 public override PendingImplementation GetPendingImplementations ()
2554 return PendingImplementation.GetPendingImplementations (this);
2557 public override TypeAttributes TypeAttr {
2559 return base.TypeAttr | DefaultTypeAttributes;
2564 public class ClassPart : TypeContainer, IMemberContainer {
2565 public readonly PartialContainer PartialContainer;
2566 public readonly bool IsPartial;
2568 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2569 int mod, Attributes attrs, Kind kind, Location l)
2570 : base (ns, parent, pc.MemberName, attrs, kind, l)
2572 this.PartialContainer = pc;
2573 this.IsPartial = true;
2576 if (parent == null || parent == RootContext.Tree.Types)
2577 accmods = Modifiers.INTERNAL;
2579 accmods = Modifiers.PRIVATE;
2581 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2584 public override PendingImplementation GetPendingImplementations ()
2586 return PartialContainer.Pending;
2589 public override bool VerifyImplements (Type interface_type, string full,
2590 string name, Location loc)
2592 return PartialContainer.VerifyImplements (
2593 interface_type, full, name, loc);
2596 public override bool EmitFieldInitializers (EmitContext ec)
2598 return PartialContainer.EmitFieldInitializers (ec);
2601 public override Type FindNestedType (string name)
2603 return PartialContainer.FindNestedType (name);
2606 public override MemberCache BaseCache {
2608 return PartialContainer.BaseCache;
2613 public abstract class ClassOrStruct : TypeContainer {
2614 bool hasExplicitLayout = false;
2615 ListDictionary declarative_security;
2617 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2618 MemberName name, Attributes attrs, Kind kind,
2620 : base (ns, parent, name, attrs, kind, l)
2624 public override PendingImplementation GetPendingImplementations ()
2626 return PendingImplementation.GetPendingImplementations (this);
2629 public override bool HasExplicitLayout {
2631 return hasExplicitLayout;
2635 protected override void VerifyMembers (EmitContext ec)
2637 base.VerifyMembers (ec);
2639 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2640 foreach (Event e in events){
2642 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2647 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2649 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2650 if (declarative_security == null)
2651 declarative_security = new ListDictionary ();
2653 a.ExtractSecurityPermissionSet (declarative_security);
2657 if (a.Type == TypeManager.struct_layout_attribute_type &&
2658 a.GetLayoutKindValue () == LayoutKind.Explicit)
2659 hasExplicitLayout = true;
2661 base.ApplyAttributeBuilder (a, cb);
2664 public override void Emit()
2668 if (declarative_security != null) {
2669 foreach (DictionaryEntry de in declarative_security) {
2670 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2677 /// Class handles static classes declaration
2679 public sealed class StaticClass: Class {
2680 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2681 Attributes attrs, Location l)
2682 : base (ns, parent, name, mod, attrs, l)
2684 if (RootContext.Version == LanguageVersion.ISO_1) {
2685 Report.FeatureIsNotStandardized (l, "static classes");
2689 protected override int AllowedModifiersProp {
2691 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2692 Modifiers.STATIC | Modifiers.UNSAFE;
2696 protected override void DefineContainerMembers (MemberCoreArrayList list)
2701 foreach (MemberCore m in list) {
2702 if (m is Operator) {
2703 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2707 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2708 Report.Warning (628, 4, m.Location, "'{0}': new protected member declared in static class", m.GetSignatureForError (this));
2711 Report.Error (720, m.Location, "'{0}': cannot declare indexers in a static class", m.GetSignatureForError (this));
2715 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2718 if (m is Constructor) {
2719 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2723 if (m is Destructor) {
2724 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2728 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2731 base.DefineContainerMembers (list);
2734 public override TypeBuilder DefineType()
2736 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2737 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2741 TypeBuilder tb = base.DefineType ();
2745 if (ptype != TypeManager.object_type) {
2746 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2750 if (ifaces != null) {
2751 foreach (Type t in ifaces)
2752 Report.SymbolRelatedToPreviousError (t);
2753 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2758 public override TypeAttributes TypeAttr {
2760 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2765 public class Class : ClassOrStruct {
2766 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2767 public const int AllowedModifiers =
2770 Modifiers.PROTECTED |
2771 Modifiers.INTERNAL |
2773 Modifiers.ABSTRACT |
2777 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2778 Attributes attrs, Location l)
2779 : base (ns, parent, name, attrs, Kind.Class, l)
2781 this.ModFlags = mod;
2784 virtual protected int AllowedModifiersProp {
2786 return AllowedModifiers;
2790 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2792 if (a.Type == TypeManager.attribute_usage_type) {
2793 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2794 TypeBuilder.FullName != "System.Attribute") {
2795 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2799 base.ApplyAttributeBuilder (a, cb);
2802 public const TypeAttributes DefaultTypeAttributes =
2803 TypeAttributes.AutoLayout | TypeAttributes.Class;
2805 public override TypeBuilder DefineType()
2807 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2808 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2812 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2813 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2815 return base.DefineType ();
2819 // FIXME: How do we deal with the user specifying a different
2822 public override TypeAttributes TypeAttr {
2824 return base.TypeAttr | DefaultTypeAttributes;
2829 public class Struct : ClassOrStruct {
2831 // Modifiers allowed in a struct declaration
2833 public const int AllowedModifiers =
2836 Modifiers.PROTECTED |
2837 Modifiers.INTERNAL |
2841 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2842 int mod, Attributes attrs, Location l)
2843 : base (ns, parent, name, attrs, Kind.Struct, l)
2847 if (parent.Parent == null)
2848 accmods = Modifiers.INTERNAL;
2850 accmods = Modifiers.PRIVATE;
2852 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2854 this.ModFlags |= Modifiers.SEALED;
2857 public const TypeAttributes DefaultTypeAttributes =
2858 TypeAttributes.SequentialLayout |
2859 TypeAttributes.Sealed |
2860 TypeAttributes.BeforeFieldInit;
2863 // FIXME: Allow the user to specify a different set of attributes
2864 // in some cases (Sealed for example is mandatory for a class,
2865 // but what SequentialLayout can be changed
2867 public override TypeAttributes TypeAttr {
2869 return base.TypeAttr | DefaultTypeAttributes;
2877 public class Interface : TypeContainer, IMemberContainer {
2879 /// Modifiers allowed in a class declaration
2881 public const int AllowedModifiers =
2884 Modifiers.PROTECTED |
2885 Modifiers.INTERNAL |
2889 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2890 Attributes attrs, Location l)
2891 : base (ns, parent, name, attrs, Kind.Interface, l)
2895 if (parent.Parent == null)
2896 accmods = Modifiers.INTERNAL;
2898 accmods = Modifiers.PRIVATE;
2900 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2903 public override PendingImplementation GetPendingImplementations ()
2908 public const TypeAttributes DefaultTypeAttributes =
2909 TypeAttributes.AutoLayout |
2910 TypeAttributes.Abstract |
2911 TypeAttributes.Interface;
2913 public override TypeAttributes TypeAttr {
2915 return base.TypeAttr | DefaultTypeAttributes;
2920 public abstract class MethodCore : MemberBase {
2921 public readonly Parameters Parameters;
2922 protected ToplevelBlock block;
2925 // Parameters, cached for semantic analysis.
2927 protected InternalParameters parameter_info;
2928 protected Type [] parameter_types;
2930 // Whether this is an operator method.
2931 public bool IsOperator;
2934 // The method we're overriding if this is an override method.
2936 protected MethodInfo base_method = null;
2938 static string[] attribute_targets = new string [] { "method", "return" };
2940 public MethodCore (TypeContainer parent, Expression type, int mod,
2941 int allowed_mod, bool is_interface, MemberName name,
2942 Attributes attrs, Parameters parameters, Location loc)
2943 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
2946 Parameters = parameters;
2947 IsInterface = is_interface;
2951 // Returns the System.Type array for the parameters of this method
2953 public Type [] ParameterTypes {
2955 return parameter_types;
2959 public InternalParameters ParameterInfo
2962 return parameter_info;
2966 public ToplevelBlock Block {
2976 protected override bool CheckBase ()
2978 if (!base.CheckBase ())
2981 // Check whether arguments were correct.
2982 if (!DoDefineParameters ())
2985 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
2991 // Is null for System.Object while compiling corlib and base interfaces
2992 if (Parent.BaseCache == null) {
2993 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
2994 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
2999 Type base_ret_type = null;
3000 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3002 // method is override
3003 if (base_method != null) {
3005 if (!CheckMethodAgainstBase ())
3008 if ((ModFlags & Modifiers.NEW) == 0) {
3009 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3010 Report.SymbolRelatedToPreviousError (base_method);
3011 if (this is PropertyBase) {
3012 Report.Error (1715, Location, "'{0}': type must be '{1}' to match overridden member '{2}'",
3013 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3016 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3017 "change return type when overriding inherited member");
3022 if (base_method.IsAbstract && !IsInterface) {
3023 Report.SymbolRelatedToPreviousError (base_method);
3024 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3029 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3030 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3034 if (RootContext.WarningLevel > 2) {
3035 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3036 Parent.Methods.HasEquals = true;
3037 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3038 Parent.Methods.HasGetHashCode = true;
3041 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3042 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3044 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3045 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3046 Report.SymbolRelatedToPreviousError (base_method);
3047 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3054 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3055 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3056 if (conflict_symbol != null) {
3057 Report.SymbolRelatedToPreviousError (conflict_symbol);
3058 if (this is PropertyBase)
3059 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3061 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3063 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3067 if (conflict_symbol == null) {
3068 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3069 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3074 if ((ModFlags & Modifiers.NEW) == 0) {
3075 if (this is Method && conflict_symbol is MethodBase)
3078 Report.SymbolRelatedToPreviousError (conflict_symbol);
3079 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3087 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3088 // that have been defined.
3090 // `name' is the user visible name for reporting errors (this is used to
3091 // provide the right name regarding method names and properties)
3093 bool CheckMethodAgainstBase ()
3097 // TODO: replace with GetSignatureForError
3098 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3100 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3101 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3103 506, Location, Parent.MakeName (Name) +
3104 ": cannot override inherited member `" +
3105 name + "' because it is not " +
3106 "virtual, abstract or override");
3110 // Now we check that the overriden method is not final
3112 if (base_method.IsFinal) {
3113 Report.SymbolRelatedToPreviousError (base_method);
3114 Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
3115 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3119 // Check that the permissions are not being changed
3121 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3122 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3124 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3125 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3130 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3131 ModFlags |= Modifiers.NEW;
3132 Report.SymbolRelatedToPreviousError (base_method);
3133 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3134 if (RootContext.WarningLevel >= 2)
3135 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));
3137 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3143 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3145 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3147 // when overriding protected internal, the method can be declared
3148 // protected internal only within the same assembly
3151 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3152 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3154 // assemblies differ - report an error
3158 } else if (thisp != base_classp) {
3160 // same assembly, but other attributes differ - report an error
3165 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3167 // if it's not "protected internal", it must be "protected"
3171 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3173 // protected within the same assembly - an error
3176 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3177 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3179 // protected ok, but other attributes differ - report an error
3185 return (thisp == base_classp);
3189 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3192 // FIXME: report the old/new permissions?
3195 507, Location, parent.MakeName (Name) +
3196 ": can't change the access modifiers when overriding inherited " +
3197 "member `" + name + "'");
3200 protected static string Error722 {
3202 return "'{0}': static types cannot be used as return types";
3207 /// For custom member duplication search in a container
3209 protected abstract bool CheckForDuplications ();
3212 /// Gets base method and its return type
3214 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3216 protected virtual bool DoDefineParameters ()
3218 EmitContext ec = Parent.EmitContext;
3220 throw new InternalErrorException ("DoDefineParameters invoked too early");
3222 bool old_unsafe = ec.InUnsafe;
3223 ec.InUnsafe = InUnsafe;
3224 // Check if arguments were correct
3225 parameter_types = Parameters.GetParameterInfo (ec);
3226 ec.InUnsafe = old_unsafe;
3228 if ((parameter_types == null) ||
3229 !CheckParameters (Parent, parameter_types))
3232 parameter_info = new InternalParameters (parameter_types, Parameters);
3234 Parameter array_param = Parameters.ArrayParameter;
3235 if ((array_param != null) &&
3236 (!array_param.ParameterType.IsArray ||
3237 (array_param.ParameterType.GetArrayRank () != 1))) {
3238 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3245 public override string[] ValidAttributeTargets {
3247 return attribute_targets;
3251 protected override bool VerifyClsCompliance (DeclSpace ds)
3253 if (!base.VerifyClsCompliance (ds)) {
3254 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3255 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3260 if (Parameters.HasArglist) {
3261 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3264 if (!AttributeTester.IsClsCompliant (MemberType)) {
3265 if (this is PropertyBase)
3266 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3267 GetSignatureForError ());
3269 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3270 GetSignatureForError ());
3273 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3278 protected bool IsDuplicateImplementation (MethodCore method)
3280 if ((method == this) || (method.Name != Name))
3283 Type[] param_types = method.ParameterTypes;
3284 if (param_types == null)
3287 if (param_types.Length != ParameterTypes.Length)
3290 for (int i = 0; i < param_types.Length; i++)
3291 if (param_types [i] != ParameterTypes [i])
3294 // TODO: make operator compatible with MethodCore to avoid this
3295 if (this is Operator && method is Operator) {
3296 if (MemberType != method.MemberType)
3301 // Try to report 663: method only differs on out/ref
3303 ParameterData info = ParameterInfo;
3304 ParameterData other_info = method.ParameterInfo;
3305 for (int i = 0; i < info.Count; i++){
3306 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3307 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3312 Report.SymbolRelatedToPreviousError (method);
3313 if (this is Operator && method is Operator)
3314 Report.Error (557, Location, "Duplicate user-defined conversion in type '{0}'", Parent.Name);
3316 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3321 // Returns a string that represents the signature for this
3322 // member which should be used in XML documentation.
3324 public override string GetDocCommentName (DeclSpace ds)
3326 return DocUtil.GetMethodDocCommentName (this, ds);
3330 // Raised (and passed an XmlElement that contains the comment)
3331 // when GenerateDocComment is writing documentation expectedly.
3333 // FIXME: with a few effort, it could be done with XmlReader,
3334 // that means removal of DOM use.
3336 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3338 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3342 // Represents header string for documentation comment.
3344 public override string DocCommentHeader {
3345 get { return "M:"; }
3348 protected override void VerifyObsoleteAttribute()
3350 base.VerifyObsoleteAttribute ();
3352 if (parameter_types == null)
3355 foreach (Type type in parameter_types) {
3356 CheckUsageOfObsoleteAttribute (type);
3361 public class SourceMethod : ISourceMethod
3363 TypeContainer container;
3366 protected SourceMethod (TypeContainer container, MethodBase builder,
3367 ISourceFile file, Location start, Location end)
3369 this.container = container;
3370 this.builder = builder;
3372 CodeGen.SymbolWriter.OpenMethod (
3373 file, this, start.Row, 0, end.Row, 0);
3376 public string Name {
3377 get { return builder.Name; }
3380 public int NamespaceID {
3381 get { return container.NamespaceEntry.SymbolFileID; }
3386 if (builder is MethodBuilder)
3387 return ((MethodBuilder) builder).GetToken ().Token;
3388 else if (builder is ConstructorBuilder)
3389 return ((ConstructorBuilder) builder).GetToken ().Token;
3391 throw new NotSupportedException ();
3395 public void CloseMethod ()
3397 if (CodeGen.SymbolWriter != null)
3398 CodeGen.SymbolWriter.CloseMethod ();
3401 public static SourceMethod Create (TypeContainer parent,
3402 MethodBase builder, Block block)
3404 if (CodeGen.SymbolWriter == null)
3409 Location start_loc = block.StartLocation;
3410 if (Location.IsNull (start_loc))
3413 Location end_loc = block.EndLocation;
3414 if (Location.IsNull (end_loc))
3417 ISourceFile file = start_loc.SourceFile;
3421 return new SourceMethod (
3422 parent, builder, file, start_loc, end_loc);
3426 public class Method : MethodCore, IIteratorContainer, IMethodData {
3427 public MethodBuilder MethodBuilder;
3428 public MethodData MethodData;
3429 ReturnParameter return_attributes;
3430 ListDictionary declarative_security;
3433 /// Modifiers allowed in a class declaration
3435 const int AllowedModifiers =
3438 Modifiers.PROTECTED |
3439 Modifiers.INTERNAL |
3444 Modifiers.OVERRIDE |
3445 Modifiers.ABSTRACT |
3447 Modifiers.METHOD_YIELDS |
3450 const int AllowedInterfaceModifiers =
3451 Modifiers.NEW | Modifiers.UNSAFE;
3454 // return_type can be "null" for VOID values.
3456 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3457 MemberName name, Parameters parameters, Attributes attrs,
3459 : base (ds, return_type, mod,
3460 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3461 is_iface, name, attrs, parameters, l)
3465 public override AttributeTargets AttributeTargets {
3467 return AttributeTargets.Method;
3471 public override string GetSignatureForError()
3473 if (MethodBuilder == null) {
3474 return GetSignatureForError (Parent);
3476 return TypeManager.CSharpSignature (MethodBuilder);
3480 /// Use this method when MethodBuilder is null
3482 public override string GetSignatureForError (TypeContainer tc)
3484 // TODO: get params from somewhere
3485 if (parameter_info == null)
3486 return base.GetSignatureForError (tc);
3488 // TODO: move to parameters
3489 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3490 if (parameter_info.Parameters.FixedParameters != null) {
3491 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3492 Parameter p = parameter_info.Parameters.FixedParameters [i];
3493 args.Append (p.GetSignatureForError ());
3495 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3500 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3503 void DuplicateEntryPoint (MethodInfo b, Location location)
3507 "Program `" + CodeGen.FileName +
3508 "' has more than one entry point defined: `" +
3509 TypeManager.CSharpSignature(b) + "'");
3512 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3514 if (b.ReturnType != TypeManager.void_type &&
3515 b.ReturnType != TypeManager.int32_type)
3518 if (pinfo.Count == 0)
3521 if (pinfo.Count > 1)
3524 Type t = pinfo.ParameterType(0);
3526 (t.GetArrayRank() == 1) &&
3527 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3528 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3534 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3536 if (a.Target == AttributeTargets.ReturnValue) {
3537 if (return_attributes == null)
3538 return_attributes = new ReturnParameter (MethodBuilder, Location);
3540 return_attributes.ApplyAttributeBuilder (a, cb);
3544 if (a.Type == TypeManager.methodimpl_attr_type &&
3545 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3546 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3549 if (a.Type == TypeManager.dllimport_type) {
3550 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3551 if ((ModFlags & extern_static) != extern_static) {
3552 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3558 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3559 if (declarative_security == null)
3560 declarative_security = new ListDictionary ();
3561 a.ExtractSecurityPermissionSet (declarative_security);
3565 if (a.Type == TypeManager.conditional_attribute_type) {
3566 if (IsOperator || IsExplicitImpl) {
3567 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3571 if (ReturnType != TypeManager.void_type) {
3572 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3576 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3577 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3582 Report.Error (582, Location, "Conditional not valid on interface members");
3586 if (MethodData.IsImplementing) {
3587 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3591 for (int i = 0; i < parameter_info.Count; ++i) {
3592 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3593 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3599 MethodBuilder.SetCustomAttribute (cb);
3602 protected override bool CheckForDuplications ()
3604 ArrayList ar = Parent.Methods;
3606 int arLen = ar.Count;
3608 for (int i = 0; i < arLen; i++) {
3609 Method m = (Method) ar [i];
3610 if (IsDuplicateImplementation (m))
3615 ar = Parent.Properties;
3617 for (int i = 0; i < ar.Count; ++i) {
3618 PropertyBase pb = (PropertyBase) ar [i];
3619 if (pb.AreAccessorsDuplicateImplementation (this))
3624 ar = Parent.Indexers;
3626 for (int i = 0; i < ar.Count; ++i) {
3627 PropertyBase pb = (PropertyBase) ar [i];
3628 if (pb.AreAccessorsDuplicateImplementation (this))
3635 for (int i = 0; i < ar.Count; ++i) {
3636 Event ev = (Event) ar [i];
3637 if (ev.AreAccessorsDuplicateImplementation (this))
3648 public override bool Define ()
3653 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3654 Error1599 (Location, ReturnType);
3662 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3664 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3666 if (!MethodData.Define (Parent))
3670 // Setup iterator if we are one
3672 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3673 Iterator iterator = new Iterator (
3674 Parent, Name, MemberType, ParameterTypes,
3675 ParameterInfo, ModFlags, block, Location);
3677 if (!iterator.DefineIterator ())
3680 block = iterator.Block;
3683 MethodBuilder = MethodData.MethodBuilder;
3686 // This is used to track the Entry Point,
3688 if (Name == "Main" &&
3689 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3690 (RootContext.MainClass == null ||
3691 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3692 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3693 if (RootContext.EntryPoint == null) {
3694 RootContext.EntryPoint = MethodBuilder;
3695 RootContext.EntryPointLocation = Location;
3697 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3698 DuplicateEntryPoint (MethodBuilder, Location);
3701 if (RootContext.WarningLevel >= 4)
3702 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3706 if (MemberType.IsAbstract && MemberType.IsSealed) {
3707 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3717 public override void Emit ()
3719 MethodData.Emit (Parent, this);
3722 if (declarative_security != null) {
3723 foreach (DictionaryEntry de in declarative_security) {
3724 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3732 public static void Error1599 (Location loc, Type t)
3734 Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
3737 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3739 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3740 container.TypeBuilder, Name, ParameterTypes, false);
3745 base_ret_type = mi.ReturnType;
3749 public override bool MarkForDuplicationCheck ()
3751 caching_flags |= Flags.TestMethodDuplication;
3755 protected override bool VerifyClsCompliance(DeclSpace ds)
3757 if (!base.VerifyClsCompliance (ds))
3760 if (parameter_types.Length > 0) {
3761 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3763 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3770 void IIteratorContainer.SetYields ()
3772 ModFlags |= Modifiers.METHOD_YIELDS;
3775 #region IMethodData Members
3777 public CallingConventions CallingConventions {
3779 CallingConventions cc = Parameters.GetCallingConvention ();
3780 if (Parameters.HasArglist)
3781 block.HasVarargs = true;
3784 if ((ModFlags & Modifiers.STATIC) == 0)
3785 cc |= CallingConventions.HasThis;
3787 // FIXME: How is `ExplicitThis' used in C#?
3793 public Type ReturnType {
3799 public MemberName MethodName {
3805 public new Location Location {
3807 return base.Location;
3811 protected override bool CheckBase() {
3812 if (!base.CheckBase ())
3815 // TODO: Destructor should derive from MethodCore
3816 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3817 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3818 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3825 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3827 return new EmitContext (
3828 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3831 public ObsoleteAttribute GetObsoleteAttribute ()
3833 return GetObsoleteAttribute (Parent);
3837 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3839 public bool IsExcluded (EmitContext ec)
3841 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3842 return (caching_flags & Flags.Excluded) != 0;
3844 caching_flags &= ~Flags.Excluded_Undetected;
3846 if (base_method == null) {
3847 if (OptAttributes == null)
3850 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3855 foreach (Attribute a in attrs) {
3856 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3857 if (RootContext.AllDefines.Contains (condition))
3861 caching_flags |= Flags.Excluded;
3865 IMethodData md = TypeManager.GetMethod (base_method);
3867 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
3868 caching_flags |= Flags.Excluded;
3874 if (md.IsExcluded (ec)) {
3875 caching_flags |= Flags.Excluded;
3884 public abstract class ConstructorInitializer {
3885 ArrayList argument_list;
3886 protected ConstructorInfo base_constructor;
3887 Parameters parameters;
3890 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
3893 this.argument_list = argument_list;
3894 this.parameters = parameters;
3898 public ArrayList Arguments {
3900 return argument_list;
3904 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
3906 Expression base_constructor_group;
3910 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
3912 if (argument_list != null){
3913 foreach (Argument a in argument_list){
3914 if (!a.Resolve (ec, loc))
3918 ec.CurrentBlock = null;
3920 if (this is ConstructorBaseInitializer) {
3921 if (ec.ContainerType.BaseType == null)
3924 t = ec.ContainerType.BaseType;
3925 if (ec.ContainerType.IsValueType) {
3926 Report.Error (522, loc,
3927 "structs cannot call base class constructors");
3931 t = ec.ContainerType;
3933 base_constructor_group = Expression.MemberLookup (
3934 ec, t, ".ctor", MemberTypes.Constructor,
3935 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3938 if (base_constructor_group == null){
3940 base_constructor_group = Expression.MemberLookup (
3941 ec, t, null, t, ".ctor", MemberTypes.Constructor,
3942 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3946 int errors = Report.Errors;
3947 if (base_constructor_group != null)
3948 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
3949 ec, (MethodGroupExpr) base_constructor_group, argument_list,
3952 if (base_constructor == null) {
3953 if (errors == Report.Errors)
3954 Report.Error (1501, loc, "Can not find a constructor for this argument list");
3959 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
3960 TypeManager.CSharpSignature (base_constructor));
3961 base_constructor = null;
3965 if (base_constructor == caller_builder){
3966 Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
3973 public void Emit (EmitContext ec)
3975 if (base_constructor != null){
3976 ec.Mark (loc, false);
3978 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
3980 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
3985 /// Method search for base ctor. (We do not cache it).
3987 Constructor GetOverloadedConstructor (TypeContainer tc)
3989 if (tc.InstanceConstructors == null)
3992 foreach (Constructor c in tc.InstanceConstructors) {
3993 if (Arguments == null) {
3994 if (c.ParameterTypes.Length == 0)
4002 int count = c.ParameterInfo.Count;
4004 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4005 for (int i = 0; i < count-1; i++)
4006 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4011 if (c.ParameterTypes.Length != Arguments.Count)
4014 for (int i = 0; i < Arguments.Count; ++i)
4015 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4030 //TODO: implement caching when it will be necessary
4031 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4033 Constructor ctor = GetOverloadedConstructor (tc);
4037 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4041 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4045 public class ConstructorBaseInitializer : ConstructorInitializer {
4046 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4047 base (argument_list, pars, l)
4051 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4052 if (base_constructor == null)
4055 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4056 if (type_ds == null) {
4057 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (base_constructor);
4060 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (base_constructor), loc);
4065 base.CheckObsoleteAttribute (type_ds, loc);
4070 public class ConstructorThisInitializer : ConstructorInitializer {
4071 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4072 base (argument_list, pars, l)
4077 public class Constructor : MethodCore, IMethodData {
4078 public ConstructorBuilder ConstructorBuilder;
4079 public ConstructorInitializer Initializer;
4080 ListDictionary declarative_security;
4083 // Modifiers allowed for a constructor.
4085 public const int AllowedModifiers =
4087 Modifiers.PROTECTED |
4088 Modifiers.INTERNAL |
4094 bool has_compliant_args = false;
4096 // The spec claims that static is not permitted, but
4097 // my very own code has static constructors.
4099 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4100 ConstructorInitializer init, Location l)
4101 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4107 public override string GetSignatureForError()
4109 if (ConstructorBuilder == null)
4110 return GetSignatureForError (Parent);
4112 return TypeManager.CSharpSignature (ConstructorBuilder);
4115 public bool HasCompliantArgs {
4117 return has_compliant_args;
4121 public override AttributeTargets AttributeTargets {
4123 return AttributeTargets.Constructor;
4129 // Returns true if this is a default constructor
4131 public bool IsDefault ()
4133 if ((ModFlags & Modifiers.STATIC) != 0)
4134 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4135 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4138 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4139 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4140 (Initializer is ConstructorBaseInitializer) &&
4141 (Initializer.Arguments == null);
4144 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4146 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4147 if (declarative_security == null) {
4148 declarative_security = new ListDictionary ();
4150 a.ExtractSecurityPermissionSet (declarative_security);
4154 ConstructorBuilder.SetCustomAttribute (cb);
4157 protected override bool CheckForDuplications ()
4159 ArrayList ar = Parent.InstanceConstructors;
4161 int arLen = ar.Count;
4163 for (int i = 0; i < arLen; i++) {
4164 Constructor m = (Constructor) ar [i];
4165 if (IsDuplicateImplementation (m))
4172 protected override bool CheckBase ()
4174 // Check whether arguments were correct.
4175 if (!DoDefineParameters ())
4178 // TODO: skip the rest for generated ctor
4179 if ((ModFlags & Modifiers.STATIC) != 0)
4182 if (!CheckForDuplications ())
4185 if (Parent.Kind == Kind.Struct) {
4186 if (ParameterTypes.Length == 0) {
4187 Report.Error (568, Location,
4188 "Structs can not contain explicit parameterless " +
4193 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4194 Report.Error (666, Location, "Protected member in struct declaration");
4199 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4200 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4207 // Creates the ConstructorBuilder
4209 public override bool Define ()
4211 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4212 MethodAttributes.SpecialName);
4214 if ((ModFlags & Modifiers.STATIC) != 0) {
4215 ca |= MethodAttributes.Static | MethodAttributes.Private;
4217 ca |= MethodAttributes.HideBySig;
4219 if ((ModFlags & Modifiers.PUBLIC) != 0)
4220 ca |= MethodAttributes.Public;
4221 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4222 if ((ModFlags & Modifiers.INTERNAL) != 0)
4223 ca |= MethodAttributes.FamORAssem;
4225 ca |= MethodAttributes.Family;
4226 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4227 ca |= MethodAttributes.Assembly;
4228 else if (IsDefault ())
4229 ca |= MethodAttributes.Public;
4231 ca |= MethodAttributes.Private;
4234 // Check if arguments were correct.
4238 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4239 ca, CallingConventions,
4242 if ((ModFlags & Modifiers.UNSAFE) != 0)
4243 ConstructorBuilder.InitLocals = false;
4245 TypeManager.AddMethod (ConstructorBuilder, this);
4248 // HACK because System.Reflection.Emit is lame
4250 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4258 public override void Emit ()
4260 EmitContext ec = CreateEmitContext (null, null);
4263 // extern methods have no bodies
4265 if ((ModFlags & Modifiers.EXTERN) != 0) {
4266 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4268 179, Location, "External constructor `" +
4269 TypeManager.CSharpSignature (ConstructorBuilder) +
4270 "' can not have a body");
4273 } else if (block == null) {
4275 501, Location, "Constructor `" +
4276 TypeManager.CSharpSignature (ConstructorBuilder) +
4277 "' must declare a body since it is not marked extern");
4281 if ((ModFlags & Modifiers.STATIC) == 0){
4282 if (Parent.Kind == Kind.Class && Initializer == null)
4283 Initializer = new ConstructorBaseInitializer (
4284 null, Parameters.EmptyReadOnlyParameters, Location);
4288 // Spec mandates that Initializers will not have
4292 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4294 ec.IsStatic = false;
4297 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4299 SourceMethod source = SourceMethod.Create (
4300 Parent, ConstructorBuilder, block);
4303 // Classes can have base initializers and instance field initializers.
4305 if (Parent.Kind == Kind.Class){
4306 if ((ModFlags & Modifiers.STATIC) == 0){
4309 // If we use a "this (...)" constructor initializer, then
4310 // do not emit field initializers, they are initialized in the other constructor
4312 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4313 Parent.EmitFieldInitializers (ec);
4316 if (Initializer != null) {
4317 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null)
4318 Initializer.CheckObsoleteAttribute (Parent, Location);
4320 ec.TestObsoleteMethodUsage = false;
4321 Initializer.Emit (ec);
4324 if ((ModFlags & Modifiers.STATIC) != 0)
4325 Parent.EmitFieldInitializers (ec);
4327 if (OptAttributes != null)
4328 OptAttributes.Emit (ec, this);
4330 // If this is a non-static `struct' constructor and doesn't have any
4331 // initializer, it must initialize all of the struct's fields.
4332 if ((Parent.Kind == Kind.Struct) &&
4333 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4334 Block.AddThisVariable (Parent, Location);
4336 ec.EmitTopBlock (block, ParameterInfo, Location);
4339 source.CloseMethod ();
4343 if (declarative_security != null) {
4344 foreach (DictionaryEntry de in declarative_security) {
4345 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4352 // Is never override
4353 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4358 protected override bool VerifyClsCompliance (DeclSpace ds)
4360 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4364 if (parameter_types.Length > 0) {
4365 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4367 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4369 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4370 foreach (Type param in parameter_types) {
4371 if (param.IsArray) {
4377 has_compliant_args = true;
4381 #region IMethodData Members
4383 public System.Reflection.CallingConventions CallingConventions {
4385 CallingConventions cc = Parameters.GetCallingConvention ();
4387 if (Parent.Kind == Kind.Class)
4388 if ((ModFlags & Modifiers.STATIC) == 0)
4389 cc |= CallingConventions.HasThis;
4391 // FIXME: How is `ExplicitThis' used in C#?
4397 public new Location Location {
4399 return base.Location;
4403 public MemberName MethodName {
4409 public Type ReturnType {
4415 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4417 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4418 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4421 public ObsoleteAttribute GetObsoleteAttribute ()
4426 public bool IsExcluded(EmitContext ec)
4435 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4437 public interface IMethodData
4439 CallingConventions CallingConventions { get; }
4440 Location Location { get; }
4441 MemberName MethodName { get; }
4442 Type[] ParameterTypes { get; }
4443 Type ReturnType { get; }
4445 Attributes OptAttributes { get; }
4446 ToplevelBlock Block { get; }
4448 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4449 ObsoleteAttribute GetObsoleteAttribute ();
4450 string GetSignatureForError (TypeContainer tc);
4451 bool IsExcluded (EmitContext ec);
4452 bool IsClsCompliaceRequired (DeclSpace ds);
4456 // Encapsulates most of the Method's state
4458 public class MethodData {
4460 readonly IMethodData method;
4463 // The return type of this method
4465 public readonly InternalParameters ParameterInfo;
4468 // Are we implementing an interface ?
4470 public bool IsImplementing = false;
4475 protected MemberBase member;
4476 protected int modifiers;
4477 protected MethodAttributes flags;
4479 MethodBuilder builder = null;
4480 public MethodBuilder MethodBuilder {
4486 public MethodData (MemberBase member, InternalParameters parameters,
4487 int modifiers, MethodAttributes flags, IMethodData method)
4489 this.member = member;
4490 this.ParameterInfo = parameters;
4491 this.modifiers = modifiers;
4494 this.method = method;
4497 public bool Define (TypeContainer container)
4499 MethodInfo implementing = null;
4501 string name = method.MethodName.Name;
4502 string method_name = name;
4504 Type[] ParameterTypes = method.ParameterTypes;
4506 if (container.Pending != null){
4507 if (member is Indexer) // TODO: test it, but it should work without this IF
4508 implementing = container.Pending.IsInterfaceIndexer (
4509 member.InterfaceType, method.ReturnType, ParameterTypes);
4511 implementing = container.Pending.IsInterfaceMethod (
4512 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4514 if (member.InterfaceType != null){
4515 if (implementing == null){
4516 if (member is PropertyBase) {
4517 Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
4518 method.GetSignatureForError (container), member.ExplicitInterfaceName);
4521 Report.Error (539, method.Location,
4522 "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
4526 if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
4527 Report.SymbolRelatedToPreviousError (implementing);
4528 Report.Error (683, method.Location, "'{0}' explicit method implementation cannot implement '{1}' because it is an accessor",
4529 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4532 method_name = member.InterfaceType.FullName + "." + name;
4534 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
4535 Report.SymbolRelatedToPreviousError (implementing);
4536 Report.Error (686, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
4537 method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4544 // For implicit implementations, make sure we are public, for
4545 // explicit implementations, make sure we are private.
4547 if (implementing != null){
4549 // Setting null inside this block will trigger a more
4550 // verbose error reporting for missing interface implementations
4552 // The "candidate" function has been flagged already
4553 // but it wont get cleared
4555 if (member.IsExplicitImpl){
4556 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4557 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4558 implementing = null;
4560 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4561 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4563 // If this is an interface method implementation,
4564 // check for public accessibility
4566 implementing = null;
4567 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4568 // We may never be private.
4569 implementing = null;
4570 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4572 // We may be protected if we're overriding something.
4574 implementing = null;
4579 // Static is not allowed
4581 if ((modifiers & Modifiers.STATIC) != 0){
4582 implementing = null;
4583 Modifiers.Error_InvalidModifier (method.Location, "static");
4588 // If implementing is still valid, set flags
4590 if (implementing != null){
4592 // When implementing interface methods, set NewSlot
4593 // unless, we are overwriting a method.
4595 if (implementing.DeclaringType.IsInterface){
4596 if ((modifiers & Modifiers.OVERRIDE) == 0)
4597 flags |= MethodAttributes.NewSlot;
4600 MethodAttributes.Virtual |
4601 MethodAttributes.HideBySig;
4603 // Set Final unless we're virtual, abstract or already overriding a method.
4604 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4605 flags |= MethodAttributes.Final;
4607 IsImplementing = true;
4610 EmitContext ec = method.CreateEmitContext (container, null);
4612 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4614 if (builder == null)
4617 if ((modifiers & Modifiers.UNSAFE) != 0)
4618 builder.InitLocals = false;
4620 if (IsImplementing){
4622 // clear the pending implemntation flag
4624 if (member is Indexer) {
4625 container.Pending.ImplementIndexer (
4626 member.InterfaceType, builder, method.ReturnType,
4627 ParameterTypes, member.IsExplicitImpl);
4629 container.Pending.ImplementMethod (
4630 member.InterfaceType, name, method.ReturnType,
4631 ParameterTypes, member.IsExplicitImpl);
4633 if (member.IsExplicitImpl)
4634 container.TypeBuilder.DefineMethodOverride (
4635 builder, implementing);
4639 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4640 TypeManager.AddMethod (builder, method);
4647 /// Create the MethodBuilder for the method
4649 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4651 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4653 if ((modifiers & extern_static) == extern_static) {
4655 if (method.OptAttributes != null) {
4656 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4657 if (dllimport_attribute != null) {
4658 flags |= MethodAttributes.PinvokeImpl;
4659 builder = dllimport_attribute.DefinePInvokeMethod (
4660 ec, container.TypeBuilder, method_name, flags,
4661 method.ReturnType, ParameterTypes);
4667 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4668 // We are more strict than Microsoft and report CS0626 like error
4669 if (method.OptAttributes == null ||
4670 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4671 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));
4676 builder = container.TypeBuilder.DefineMethod (
4677 method_name, flags, method.CallingConventions,
4678 method.ReturnType, ParameterTypes);
4684 public void Emit (TypeContainer container, Attributable kind)
4687 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4688 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4690 ec = method.CreateEmitContext (container, null);
4692 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
4693 ec.TestObsoleteMethodUsage = false;
4695 Location loc = method.Location;
4696 Attributes OptAttributes = method.OptAttributes;
4698 if (OptAttributes != null)
4699 OptAttributes.Emit (ec, kind);
4701 if (member is MethodCore)
4702 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4704 ToplevelBlock block = method.Block;
4707 // abstract or extern methods have no bodies
4709 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4714 // abstract or extern methods have no bodies.
4716 if ((modifiers & Modifiers.ABSTRACT) != 0)
4718 500, method.Location, "Abstract method `" +
4719 TypeManager.CSharpSignature (builder) +
4720 "' can not have a body");
4722 if ((modifiers & Modifiers.EXTERN) != 0)
4724 179, method.Location, "External method `" +
4725 TypeManager.CSharpSignature (builder) +
4726 "' can not have a body");
4732 // Methods must have a body unless they're extern or abstract
4734 if (block == null) {
4736 501, method.Location, "Method `" +
4737 TypeManager.CSharpSignature (builder) +
4738 "' must declare a body since it is not marked " +
4739 "abstract or extern");
4743 SourceMethod source = SourceMethod.Create (
4744 container, MethodBuilder, method.Block);
4747 // Handle destructors specially
4749 // FIXME: This code generates buggy code
4751 if (member is Destructor)
4752 EmitDestructor (ec, block);
4754 ec.EmitTopBlock (block, ParameterInfo, loc);
4757 source.CloseMethod ();
4760 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4762 ILGenerator ig = ec.ig;
4764 Label finish = ig.DefineLabel ();
4766 block.SetDestructor ();
4768 ig.BeginExceptionBlock ();
4769 ec.ReturnLabel = finish;
4770 ec.HasReturnLabel = true;
4771 ec.EmitTopBlock (block, null, method.Location);
4773 // ig.MarkLabel (finish);
4774 ig.BeginFinallyBlock ();
4776 if (ec.ContainerType.BaseType != null) {
4777 Expression member_lookup = Expression.MemberLookup (
4778 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4779 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4781 if (member_lookup != null){
4782 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4784 ig.Emit (OpCodes.Ldarg_0);
4785 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4789 ig.EndExceptionBlock ();
4790 //ig.MarkLabel (ec.ReturnLabel);
4791 ig.Emit (OpCodes.Ret);
4795 // Should derive from MethodCore
4796 public class Destructor : Method {
4798 public Destructor (TypeContainer ds, Expression return_type, int mod,
4799 string name, Parameters parameters, Attributes attrs,
4801 : base (ds, return_type, mod, false, new MemberName (name),
4802 parameters, attrs, l)
4805 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4807 if (a.Type == TypeManager.conditional_attribute_type) {
4808 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4812 base.ApplyAttributeBuilder (a, cb);
4816 abstract public class MemberBase : MemberCore {
4817 public Expression Type;
4819 public MethodAttributes flags;
4821 protected readonly int explicit_mod_flags;
4824 // The "short" name of this property / indexer / event. This is the
4825 // name without the explicit interface.
4827 public string ShortName;
4830 // The type of this property / indexer / event
4832 public Type MemberType;
4835 // If true, this is an explicit interface implementation
4837 public bool IsExplicitImpl = false;
4840 // The name of the interface we are explicitly implementing
4842 public MemberName ExplicitInterfaceName = null;
4845 // Whether this is an interface member.
4847 public bool IsInterface;
4850 // If true, the interface type we are explicitly implementing
4852 public Type InterfaceType = null;
4855 // The constructor is only exposed to our children
4857 protected MemberBase (TypeContainer parent, Expression type, int mod,
4858 int allowed_mod, int def_mod, MemberName name,
4859 Attributes attrs, Location loc)
4860 : base (parent, name, attrs, loc)
4862 explicit_mod_flags = mod;
4864 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4866 // Check for explicit interface implementation
4867 if (MemberName.Left != null) {
4868 ExplicitInterfaceName = MemberName.Left;
4869 ShortName = MemberName.Name;
4870 IsExplicitImpl = true;
4875 protected virtual bool CheckBase ()
4877 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4878 Report.Error (666, Location, "Protected member in struct declaration");
4882 if ((RootContext.WarningLevel >= 4) &&
4883 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4884 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4885 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4886 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4891 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4895 foreach (Type partype in parameters){
4896 if (partype == TypeManager.void_type) {
4898 1547, Location, "Keyword 'void' cannot " +
4899 "be used in this context");
4903 if (partype.IsPointer){
4906 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4910 if (ds.AsAccessible (partype, ModFlags))
4913 if (this is Indexer)
4914 Report.Error (55, Location,
4915 "Inconsistent accessibility: parameter type `" +
4916 TypeManager.CSharpName (partype) + "' is less " +
4917 "accessible than indexer `" + Name + "'");
4918 else if ((this is Method) && ((Method) this).IsOperator)
4919 Report.Error (57, Location,
4920 "Inconsistent accessibility: parameter type `" +
4921 TypeManager.CSharpName (partype) + "' is less " +
4922 "accessible than operator `" + Name + "'");
4924 Report.Error (51, Location,
4925 "Inconsistent accessibility: parameter type `" +
4926 TypeManager.CSharpName (partype) + "' is less " +
4927 "accessible than method `" + Name + "'");
4934 protected virtual bool DoDefine ()
4936 EmitContext ec = Parent.EmitContext;
4938 throw new InternalErrorException ("MemberBase.DoDefine called too early");
4941 throw new InternalErrorException ();
4944 ModFlags = Modifiers.PUBLIC |
4945 Modifiers.ABSTRACT |
4946 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
4948 flags = MethodAttributes.Public |
4949 MethodAttributes.Abstract |
4950 MethodAttributes.HideBySig |
4951 MethodAttributes.NewSlot |
4952 MethodAttributes.Virtual;
4954 if (!Parent.MethodModifiersValid (this))
4957 flags = Modifiers.MethodAttr (ModFlags);
4960 // Lookup Type, verify validity
4961 bool old_unsafe = ec.InUnsafe;
4962 ec.InUnsafe = InUnsafe;
4963 Type = Type.ResolveAsTypeTerminal (ec, false);
4964 ec.InUnsafe = old_unsafe;
4969 MemberType = Type.Type;
4971 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
4972 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
4973 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
4978 // verify accessibility
4979 if (!Parent.AsAccessible (MemberType, ModFlags)) {
4980 Report.SymbolRelatedToPreviousError (MemberType);
4981 if (this is Property)
4982 Report.Error (53, Location,
4983 "Inconsistent accessibility: property type `" +
4984 TypeManager.CSharpName (MemberType) + "' is less " +
4985 "accessible than property `" + GetSignatureForError () + "'");
4986 else if (this is Indexer)
4987 Report.Error (54, Location,
4988 "Inconsistent accessibility: indexer return type `" +
4989 TypeManager.CSharpName (MemberType) + "' is less " +
4990 "accessible than indexer `" + Name + "'");
4991 else if (this is MethodCore) {
4992 if (this is Operator)
4993 Report.Error (56, Location,
4994 "Inconsistent accessibility: return type `" +
4995 TypeManager.CSharpName (MemberType) + "' is less " +
4996 "accessible than operator `" + Name + "'");
4998 Report.Error (50, Location,
4999 "Inconsistent accessibility: return type `" +
5000 TypeManager.CSharpName (MemberType) + "' is less " +
5001 "accessible than method `" + Name + "'");
5003 Report.Error (52, Location,
5004 "Inconsistent accessibility: field type `" +
5005 TypeManager.CSharpName (MemberType) + "' is less " +
5006 "accessible than field `" + Name + "'");
5011 if (MemberType.IsPointer && !UnsafeOK (Parent))
5014 if (IsExplicitImpl) {
5015 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
5016 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5020 InterfaceType = texpr.ResolveType (ec);
5022 if (!InterfaceType.IsInterface) {
5023 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5028 // Compute the full name that we need to export.
5029 if (InterfaceType.FullName != ExplicitInterfaceName) {
5030 ExplicitInterfaceName = InterfaceType.FullName;
5031 UpdateMemberName ();
5035 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5038 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5045 /// The name of the member can be changed during definition (see IndexerName attribute)
5047 protected virtual void UpdateMemberName ()
5049 MemberName.Name = ShortName;
5052 public override string GetSignatureForError (TypeContainer tc)
5054 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5057 protected bool IsTypePermitted ()
5059 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5060 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5066 protected override bool VerifyClsCompliance(DeclSpace ds)
5068 if (base.VerifyClsCompliance (ds)) {
5072 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5073 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5078 protected override void VerifyObsoleteAttribute()
5080 CheckUsageOfObsoleteAttribute (MemberType);
5085 // Fields and Events both generate FieldBuilders, we use this to share
5086 // their common bits. This is also used to flag usage of the field
5088 abstract public class FieldBase : MemberBase {
5089 public FieldBuilder FieldBuilder;
5090 public Status status;
5093 public enum Status : byte {
5096 HAS_OFFSET = 4 // Used by FieldMember.
5099 static string[] attribute_targets = new string [] { "field" };
5102 /// Symbol with same name in base class/struct
5104 public MemberInfo conflict_symbol;
5107 // The constructor is only exposed to our children
5109 protected FieldBase (TypeContainer parent, Expression type, int mod,
5110 int allowed_mod, MemberName name, object init,
5111 Attributes attrs, Location loc)
5112 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5118 public override AttributeTargets AttributeTargets {
5120 return AttributeTargets.Field;
5124 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5126 if (a.Type == TypeManager.marshal_as_attr_type) {
5127 UnmanagedMarshal marshal = a.GetMarshal (this);
5128 if (marshal != null) {
5129 FieldBuilder.SetMarshal (marshal);
5134 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5135 a.Error_InvalidSecurityParent ();
5139 FieldBuilder.SetCustomAttribute (cb);
5143 // Whether this field has an initializer.
5145 public bool HasInitializer {
5147 return init != null;
5151 protected readonly Object init;
5154 Expression init_expr;
5155 bool init_expr_initialized = false;
5158 // Resolves and returns the field initializer.
5160 public Expression GetInitializerExpression (EmitContext ec)
5162 if (init_expr_initialized)
5166 if (init is Expression)
5167 e = (Expression) init;
5169 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5171 EmitContext parent_ec = Parent.EmitContext;
5173 bool old_is_static = parent_ec.IsStatic;
5174 parent_ec.IsStatic = ec.IsStatic;
5175 parent_ec.IsFieldInitializer = true;
5176 e = e.DoResolve (parent_ec);
5177 parent_ec.IsFieldInitializer = false;
5178 parent_ec.IsStatic = old_is_static;
5181 init_expr_initialized = true;
5186 protected override bool CheckBase ()
5188 if (!base.CheckBase ())
5195 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5196 if (conflict_symbol == null) {
5197 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5198 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5203 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5204 Report.SymbolRelatedToPreviousError (conflict_symbol);
5205 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5211 public override string GetSignatureForError ()
5213 if (FieldBuilder == null) {
5214 return base.GetSignatureForError (Parent);
5216 return TypeManager.GetFullNameSignature (FieldBuilder);
5219 protected virtual bool IsFieldClsCompliant {
5221 if (FieldBuilder == null)
5224 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5228 public override string[] ValidAttributeTargets {
5230 return attribute_targets;
5234 protected override bool VerifyClsCompliance (DeclSpace ds)
5236 if (!base.VerifyClsCompliance (ds))
5239 if (!IsFieldClsCompliant) {
5240 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5246 public void SetAssigned ()
5248 status |= Status.ASSIGNED;
5252 public abstract class FieldMember: FieldBase
5254 protected FieldMember (TypeContainer parent, Expression type, int mod,
5255 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5256 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5258 if ((mod & Modifiers.ABSTRACT) != 0)
5259 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5262 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5264 if (a.Type == TypeManager.field_offset_attribute_type)
5266 status |= Status.HAS_OFFSET;
5268 if (!Parent.HasExplicitLayout) {
5269 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5273 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5274 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5280 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5281 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5286 base.ApplyAttributeBuilder (a, cb);
5290 public override bool Define()
5292 EmitContext ec = Parent.EmitContext;
5294 throw new InternalErrorException ("FieldMember.Define called too early");
5296 bool old_unsafe = ec.InUnsafe;
5297 ec.InUnsafe = InUnsafe;
5298 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
5302 MemberType = texpr.ResolveType (ec);
5304 ec.InUnsafe = old_unsafe;
5306 if (MemberType == TypeManager.void_type) {
5307 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5314 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5315 Report.Error (52, Location,
5316 "Inconsistent accessibility: field type `" +
5317 TypeManager.CSharpName (MemberType) + "' is less " +
5318 "accessible than field `" + Name + "'");
5322 if (!IsTypePermitted ())
5325 if (MemberType.IsPointer && !UnsafeOK (Parent))
5331 public override void Emit ()
5333 if (OptAttributes != null) {
5334 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5335 OptAttributes.Emit (ec, this);
5338 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5339 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5346 // Represents header string for documentation comment.
5348 public override string DocCommentHeader {
5349 get { return "F:"; }
5353 interface IFixedBuffer
5355 FieldInfo Element { get; }
5356 Type ElementType { get; }
5359 public class FixedFieldExternal: IFixedBuffer
5361 FieldInfo element_field;
5363 public FixedFieldExternal (FieldInfo fi)
5365 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5368 #region IFixedField Members
5370 public FieldInfo Element {
5372 return element_field;
5376 public Type ElementType {
5378 return element_field.FieldType;
5386 /// Fixed buffer implementation
5388 public class FixedField: FieldMember, IFixedBuffer
5390 public const string FixedElementName = "FixedElementField";
5391 static int GlobalCounter = 0;
5392 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5393 static FieldInfo[] fi;
5395 TypeBuilder fixed_buffer_type;
5396 FieldBuilder element;
5397 Expression size_expr;
5400 const int AllowedModifiers =
5403 Modifiers.PROTECTED |
5404 Modifiers.INTERNAL |
5407 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5408 Expression size_expr, Attributes attrs, Location loc):
5409 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5411 if (RootContext.Version == LanguageVersion.ISO_1)
5412 Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
5414 this.size_expr = size_expr;
5417 public override bool Define()
5420 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5421 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5424 if (Parent.Kind != Kind.Struct) {
5425 Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
5429 if (!base.Define ())
5432 if (!MemberType.IsPrimitive) {
5433 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");
5437 Expression e = size_expr.Resolve (Parent.EmitContext);
5441 Constant c = e as Constant;
5443 Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
5447 buffer_size = (int)c.GetValue ();
5448 if (buffer_size <= 0) {
5449 Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
5452 buffer_size *= Expression.GetTypeSize (MemberType);
5455 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5457 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5458 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5459 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5460 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5462 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5463 TypeManager.RegisterFieldBase (FieldBuilder, this);
5468 public override void Emit()
5471 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5473 object[] fi_val = new object[1];
5474 fi_val [0] = buffer_size;
5476 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5477 ctor_args, fi, fi_val);
5478 fixed_buffer_type.SetCustomAttribute (cab);
5481 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5482 FieldBuilder.SetCustomAttribute (cab);
5487 protected override bool IsFieldClsCompliant {
5493 #region IFixedField Members
5495 public FieldInfo Element {
5501 public Type ElementType {
5511 // The Field class is used to represents class/struct fields during parsing.
5513 public class Field : FieldMember {
5515 // Modifiers allowed in a class declaration
5517 const int AllowedModifiers =
5520 Modifiers.PROTECTED |
5521 Modifiers.INTERNAL |
5524 Modifiers.VOLATILE |
5528 public Field (TypeContainer parent, Expression type, int mod, string name,
5529 Object expr_or_array_init, Attributes attrs, Location loc)
5530 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5531 expr_or_array_init, attrs, loc)
5535 public override bool Define ()
5537 if (!base.Define ())
5540 if (RootContext.WarningLevel > 1){
5541 Type ptype = Parent.TypeBuilder.BaseType;
5543 // ptype is only null for System.Object while compiling corlib.
5545 TypeContainer.FindMembers (
5546 ptype, MemberTypes.Method,
5547 BindingFlags.Public |
5548 BindingFlags.Static | BindingFlags.Instance,
5549 System.Type.FilterName, Name);
5553 if ((ModFlags & Modifiers.VOLATILE) != 0){
5554 if (!MemberType.IsClass){
5555 Type vt = MemberType;
5557 if (TypeManager.IsEnumType (vt))
5558 vt = TypeManager.EnumToUnderlying (MemberType);
5560 if (!((vt == TypeManager.bool_type) ||
5561 (vt == TypeManager.sbyte_type) ||
5562 (vt == TypeManager.byte_type) ||
5563 (vt == TypeManager.short_type) ||
5564 (vt == TypeManager.ushort_type) ||
5565 (vt == TypeManager.int32_type) ||
5566 (vt == TypeManager.uint32_type) ||
5567 (vt == TypeManager.char_type) ||
5568 (vt == TypeManager.float_type) ||
5569 (!vt.IsValueType))){
5571 677, Location, Parent.MakeName (Name) +
5572 " A volatile field can not be of type `" +
5573 TypeManager.CSharpName (vt) + "'");
5578 if ((ModFlags & Modifiers.READONLY) != 0){
5581 "A field can not be both volatile and readonly");
5586 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5588 if (Parent.Kind == Kind.Struct &&
5589 ((fa & FieldAttributes.Static) == 0) &&
5590 MemberType == Parent.TypeBuilder &&
5591 !TypeManager.IsBuiltinType (MemberType)){
5592 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5593 "' causes a cycle in the structure layout");
5598 FieldBuilder = Parent.TypeBuilder.DefineField (
5599 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5601 TypeManager.RegisterFieldBase (FieldBuilder, this);
5603 catch (ArgumentException) {
5604 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5613 // `set' and `get' accessors are represented with an Accessor.
5615 public class Accessor {
5617 // Null if the accessor is empty, or a Block if not
5619 public const int AllowedModifiers =
5621 Modifiers.PROTECTED |
5622 Modifiers.INTERNAL |
5625 public ToplevelBlock Block;
5626 public Attributes Attributes;
5627 public Location Location;
5628 public int ModFlags;
5630 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5635 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5640 // Ooouh Martin, templates are missing here.
5641 // When it will be possible move here a lot of child code and template method type.
5642 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5643 protected MethodData method_data;
5644 protected ToplevelBlock block;
5645 protected ListDictionary declarative_security;
5647 // The accessor are created event if they are not wanted.
5648 // But we need them because their names are reserved.
5649 // Field says whether accessor will be emited or not
5650 public readonly bool IsDummy;
5652 protected readonly string prefix;
5654 ReturnParameter return_attributes;
5656 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5657 : base (null, SetupName (prefix, member), null, member.Location)
5659 this.prefix = prefix;
5663 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5665 : base (null, SetupName (prefix, member),
5666 accessor.Attributes, accessor.Location)
5668 this.prefix = prefix;
5669 this.block = accessor.Block;
5672 static MemberName SetupName (string prefix, MemberBase member)
5674 MemberName name = member.MemberName.Clone ();
5675 name.Name = prefix + member.ShortName;
5679 public void UpdateName (MemberBase member)
5681 MemberName.Name = prefix + member.ShortName;
5684 #region IMethodData Members
5686 public ToplevelBlock Block {
5696 public CallingConventions CallingConventions {
5698 return CallingConventions.Standard;
5702 public bool IsExcluded (EmitContext ec)
5707 public MemberName MethodName {
5713 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5714 public abstract Type[] ParameterTypes { get; }
5715 public abstract Type ReturnType { get; }
5716 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5720 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5722 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5723 a.Type == TypeManager.conditional_attribute_type) {
5724 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 ());
5728 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5729 if (declarative_security == null)
5730 declarative_security = new ListDictionary ();
5731 a.ExtractSecurityPermissionSet (declarative_security);
5735 if (a.Target == AttributeTargets.Method) {
5736 method_data.MethodBuilder.SetCustomAttribute (cb);
5740 if (a.Target == AttributeTargets.ReturnValue) {
5741 if (return_attributes == null)
5742 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5744 return_attributes.ApplyAttributeBuilder (a, cb);
5748 ApplyToExtraTarget (a, cb);
5751 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5753 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5756 public override bool Define()
5758 throw new NotSupportedException ();
5761 public virtual void Emit (TypeContainer container)
5763 method_data.Emit (container, this);
5765 if (declarative_security != null) {
5766 foreach (DictionaryEntry de in declarative_security) {
5767 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5774 public override bool IsClsCompliaceRequired(DeclSpace ds)
5779 public bool IsDuplicateImplementation (MethodCore method)
5781 if (Name != method.Name)
5784 Type[] param_types = method.ParameterTypes;
5786 if (param_types.Length != ParameterTypes.Length)
5789 for (int i = 0; i < param_types.Length; i++)
5790 if (param_types [i] != ParameterTypes [i])
5793 Report.SymbolRelatedToPreviousError (method);
5794 Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
5798 public new Location Location {
5800 return base.Location;
5805 // Represents header string for documentation comment.
5807 public override string DocCommentHeader {
5808 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5811 protected override void VerifyObsoleteAttribute()
5818 // Properties and Indexers both generate PropertyBuilders, we use this to share
5819 // their common bits.
5821 abstract public class PropertyBase : MethodCore {
5823 public class GetMethod: PropertyMethod
5825 static string[] attribute_targets = new string [] { "method", "return" };
5827 public GetMethod (MethodCore method):
5828 base (method, "get_")
5832 public GetMethod (MethodCore method, Accessor accessor):
5833 base (method, accessor, "get_")
5837 public override MethodBuilder Define(TypeContainer container)
5839 base.Define (container);
5841 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5843 if (!method_data.Define (container))
5846 return method_data.MethodBuilder;
5849 public override string GetSignatureForError (TypeContainer tc)
5851 return String.Concat (base.GetSignatureForError (tc), ".get");
5854 public override Type ReturnType {
5856 return method.MemberType;
5860 public override string[] ValidAttributeTargets {
5862 return attribute_targets;
5867 public class SetMethod: PropertyMethod {
5869 static string[] attribute_targets = new string [] { "method", "param", "return" };
5870 ImplicitParameter param_attr;
5872 public SetMethod (MethodCore method):
5873 base (method, "set_")
5877 public SetMethod (MethodCore method, Accessor accessor):
5878 base (method, accessor, "set_")
5882 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5884 if (a.Target == AttributeTargets.Parameter) {
5885 if (param_attr == null)
5886 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5888 param_attr.ApplyAttributeBuilder (a, cb);
5892 base.ApplyAttributeBuilder (a, cb);
5895 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5897 Parameter [] parms = new Parameter [1];
5898 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
5899 Parameters parameters = new Parameters (parms, null, method.Location);
5901 bool old_unsafe = ec.InUnsafe;
5902 ec.InUnsafe = InUnsafe;
5903 Type [] types = parameters.GetParameterInfo (ec);
5904 ec.InUnsafe = old_unsafe;
5906 return new InternalParameters (types, parameters);
5909 public override MethodBuilder Define (TypeContainer container)
5911 if (container.EmitContext == null)
5912 throw new InternalErrorException ("SetMethod.Define called too early");
5914 base.Define (container);
5916 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5918 if (!method_data.Define (container))
5921 return method_data.MethodBuilder;
5924 public override string GetSignatureForError (TypeContainer tc)
5926 return String.Concat (base.GetSignatureForError (tc), ".set");
5929 public override Type[] ParameterTypes {
5931 return new Type[] { method.MemberType };
5935 public override Type ReturnType {
5937 return TypeManager.void_type;
5941 public override string[] ValidAttributeTargets {
5943 return attribute_targets;
5948 static string[] attribute_targets = new string [] { "property" };
5950 public abstract class PropertyMethod: AbstractPropertyEventMethod
5952 protected readonly MethodCore method;
5953 protected MethodAttributes flags;
5955 public PropertyMethod (MethodCore method, string prefix)
5956 : base (method, prefix)
5958 this.method = method;
5959 Parent = method.Parent;
5962 public PropertyMethod (MethodCore method, Accessor accessor,
5964 : base (method, accessor, prefix)
5966 this.method = method;
5967 Parent = method.Parent;
5968 this.ModFlags = accessor.ModFlags;
5970 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
5971 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
5975 public override AttributeTargets AttributeTargets {
5977 return AttributeTargets.Method;
5981 public override bool IsClsCompliaceRequired(DeclSpace ds)
5983 return method.IsClsCompliaceRequired (ds);
5986 public InternalParameters ParameterInfo
5989 return method_data.ParameterInfo;
5993 public virtual MethodBuilder Define (TypeContainer container)
5996 // Check for custom access modifier
5998 if (ModFlags == 0) {
5999 ModFlags = method.ModFlags;
6000 flags = method.flags;
6002 CheckModifiers (container, ModFlags);
6003 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6004 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6005 flags = Modifiers.MethodAttr (ModFlags);
6006 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6013 public bool HasCustomAccessModifier
6016 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6020 public override Type[] ParameterTypes {
6022 return TypeManager.NoTypes;
6026 public override EmitContext CreateEmitContext (TypeContainer tc,
6029 return new EmitContext (
6030 tc, method.Parent, method.Location, ig, ReturnType,
6031 method.ModFlags, false);
6034 public override ObsoleteAttribute GetObsoleteAttribute ()
6036 return method.GetObsoleteAttribute (method.Parent);
6039 public override string GetSignatureForError (TypeContainer tc)
6041 return String.Concat (tc.Name, '.', method.Name);
6044 void CheckModifiers (TypeContainer container, int modflags)
6047 int mflags = method.ModFlags & Modifiers.Accessibility;
6049 if ((mflags & Modifiers.PUBLIC) != 0) {
6050 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6052 else if ((mflags & Modifiers.PROTECTED) != 0) {
6053 if ((mflags & Modifiers.INTERNAL) != 0)
6054 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6056 flags |= Modifiers.PRIVATE;
6058 else if ((mflags & Modifiers.INTERNAL) != 0)
6059 flags |= Modifiers.PRIVATE;
6061 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6062 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6063 GetSignatureForError (container));
6066 public override bool MarkForDuplicationCheck ()
6068 caching_flags |= Flags.TestMethodDuplication;
6074 public PropertyMethod Get, Set;
6075 public PropertyBuilder PropertyBuilder;
6076 public MethodBuilder GetBuilder, SetBuilder;
6078 protected EmitContext ec;
6080 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6081 int allowed_mod, bool is_iface, MemberName name,
6082 Parameters parameters, Attributes attrs,
6084 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6085 attrs, parameters, loc)
6089 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6091 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6092 a.Error_InvalidSecurityParent ();
6096 PropertyBuilder.SetCustomAttribute (cb);
6099 public override AttributeTargets AttributeTargets {
6101 return AttributeTargets.Property;
6105 public override bool Define ()
6110 if (!IsTypePermitted ())
6116 protected override bool DoDefine ()
6118 if (!base.DoDefine ())
6122 // Accessors modifiers check
6124 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6125 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6126 GetSignatureForError ());
6130 if ((Get.IsDummy || Set.IsDummy)
6131 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6132 Report.Error (276, Location,
6133 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6134 GetSignatureForError ());
6138 if (MemberType.IsAbstract && MemberType.IsSealed) {
6139 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6143 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6147 public override string GetSignatureForError()
6149 if (PropertyBuilder == null)
6150 return GetSignatureForError (Parent);
6152 return TypeManager.CSharpSignature (PropertyBuilder, false);
6155 protected override bool CheckForDuplications ()
6157 ArrayList ar = Parent.Indexers;
6159 int arLen = ar.Count;
6161 for (int i = 0; i < arLen; i++) {
6162 Indexer m = (Indexer) ar [i];
6163 if (IsDuplicateImplementation (m))
6168 ar = Parent.Properties;
6170 int arLen = ar.Count;
6172 for (int i = 0; i < arLen; i++) {
6173 Property m = (Property) ar [i];
6174 if (IsDuplicateImplementation (m))
6182 // TODO: rename to Resolve......
6183 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6185 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6186 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6188 if (base_property == null)
6191 base_ret_type = base_property.PropertyType;
6192 MethodInfo get_accessor = base_property.GetGetMethod (true);
6193 MethodInfo set_accessor = base_property.GetSetMethod (true);
6194 MethodAttributes get_accessor_access, set_accessor_access;
6196 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6197 if (Get != null && !Get.IsDummy && get_accessor == null) {
6198 Report.SymbolRelatedToPreviousError (base_property);
6199 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6202 if (Set != null && !Set.IsDummy && set_accessor == null) {
6203 Report.SymbolRelatedToPreviousError (base_property);
6204 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6209 // Check base class accessors access
6211 get_accessor_access = set_accessor_access = 0;
6212 if ((ModFlags & Modifiers.NEW) == 0) {
6213 if (get_accessor != null) {
6214 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6215 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6217 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6218 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6219 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6222 if (set_accessor != null) {
6223 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6224 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6226 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6227 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6228 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6233 // Get the less restrictive access
6235 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6238 public override void Emit ()
6241 // The PropertyBuilder can be null for explicit implementations, in that
6242 // case, we do not actually emit the ".property", so there is nowhere to
6243 // put the attribute
6245 if (PropertyBuilder != null && OptAttributes != null)
6246 OptAttributes.Emit (ec, this);
6258 /// Tests whether accessors are not in collision with some method (CS0111)
6260 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6262 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6265 protected override void UpdateMemberName ()
6267 base.UpdateMemberName ();
6269 Get.UpdateName (this);
6270 Set.UpdateName (this);
6273 protected override bool VerifyClsCompliance (DeclSpace ds)
6275 if (!base.VerifyClsCompliance (ds))
6278 if ((Get.ModFlags != ModFlags && !Get.IsDummy) || (Set.ModFlags != ModFlags && !Set.IsDummy)) {
6279 Report.Error (3025, Get.ModFlags != ModFlags ? Get.Location : Set.Location,
6280 "CLS-compliant accessors must have the same accessibility as their property");
6285 public override string[] ValidAttributeTargets {
6287 return attribute_targets;
6292 // Represents header string for documentation comment.
6294 public override string DocCommentHeader {
6295 get { return "P:"; }
6299 public class Property : PropertyBase, IIteratorContainer {
6300 const int AllowedModifiers =
6303 Modifiers.PROTECTED |
6304 Modifiers.INTERNAL |
6308 Modifiers.OVERRIDE |
6309 Modifiers.ABSTRACT |
6312 Modifiers.METHOD_YIELDS |
6315 const int AllowedInterfaceModifiers =
6318 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6319 MemberName name, Attributes attrs, Accessor get_block,
6320 Accessor set_block, Location loc)
6321 : base (ds, type, mod,
6322 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6323 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6326 if (get_block == null)
6327 Get = new GetMethod (this);
6329 Get = new GetMethod (this, get_block);
6331 if (set_block == null)
6332 Set = new SetMethod (this);
6334 Set = new SetMethod (this, set_block);
6337 public override bool Define ()
6339 if (!base.Define ())
6345 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6349 GetBuilder = Get.Define (Parent);
6350 if (GetBuilder == null)
6354 // Setup iterator if we are one
6356 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6357 Iterator iterator = new Iterator (
6358 Parent, "get", MemberType,
6359 TypeManager.NoTypes, Get.ParameterInfo,
6360 ModFlags, Get.Block, Location);
6362 if (!iterator.DefineIterator ())
6364 Get.Block = iterator.Block;
6369 SetBuilder = Set.Define (Parent);
6370 if (SetBuilder == null)
6373 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6376 // FIXME - PropertyAttributes.HasDefault ?
6378 PropertyAttributes prop_attr = PropertyAttributes.None;
6380 prop_attr |= PropertyAttributes.RTSpecialName |
6381 PropertyAttributes.SpecialName;
6383 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6384 Name, prop_attr, MemberType, null);
6387 PropertyBuilder.SetGetMethod (GetBuilder);
6390 PropertyBuilder.SetSetMethod (SetBuilder);
6392 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6396 public void SetYields ()
6398 ModFlags |= Modifiers.METHOD_YIELDS;
6403 /// Gigantic workaround for lameness in SRE follows :
6404 /// This class derives from EventInfo and attempts to basically
6405 /// wrap around the EventBuilder so that FindMembers can quickly
6406 /// return this in it search for members
6408 public class MyEventBuilder : EventInfo {
6411 // We use this to "point" to our Builder which is
6412 // not really a MemberInfo
6414 EventBuilder MyBuilder;
6417 // We "catch" and wrap these methods
6419 MethodInfo raise, remove, add;
6421 EventAttributes attributes;
6422 Type declaring_type, reflected_type, event_type;
6427 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6429 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6431 // And now store the values in our own fields.
6433 declaring_type = type_builder;
6435 reflected_type = type_builder;
6437 attributes = event_attr;
6440 this.event_type = event_type;
6444 // Methods that you have to override. Note that you only need
6445 // to "implement" the variants that take the argument (those are
6446 // the "abstract" methods, the others (GetAddMethod()) are
6449 public override MethodInfo GetAddMethod (bool nonPublic)
6454 public override MethodInfo GetRemoveMethod (bool nonPublic)
6459 public override MethodInfo GetRaiseMethod (bool nonPublic)
6465 // These methods make "MyEventInfo" look like a Builder
6467 public void SetRaiseMethod (MethodBuilder raiseMethod)
6469 raise = raiseMethod;
6470 MyBuilder.SetRaiseMethod (raiseMethod);
6473 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6475 remove = removeMethod;
6476 MyBuilder.SetRemoveOnMethod (removeMethod);
6479 public void SetAddOnMethod (MethodBuilder addMethod)
6482 MyBuilder.SetAddOnMethod (addMethod);
6485 public void SetCustomAttribute (CustomAttributeBuilder cb)
6487 MyBuilder.SetCustomAttribute (cb);
6490 public override object [] GetCustomAttributes (bool inherit)
6492 // FIXME : There's nothing which can be seemingly done here because
6493 // we have no way of getting at the custom attribute objects of the
6498 public override object [] GetCustomAttributes (Type t, bool inherit)
6500 // FIXME : Same here !
6504 public override bool IsDefined (Type t, bool b)
6509 public override EventAttributes Attributes {
6515 public override string Name {
6521 public override Type DeclaringType {
6523 return declaring_type;
6527 public override Type ReflectedType {
6529 return reflected_type;
6533 public Type EventType {
6539 public void SetUsed ()
6541 if (my_event != null)
6542 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6547 /// For case when event is declared like property (with add and remove accessors).
6549 public class EventProperty: Event {
6551 static string[] attribute_targets = new string [] { "event", "property" };
6553 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6554 bool is_iface, MemberName name, Object init,
6555 Attributes attrs, Accessor add, Accessor remove,
6557 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6559 Add = new AddDelegateMethod (this, add);
6560 Remove = new RemoveDelegateMethod (this, remove);
6562 // For this event syntax we don't report error CS0067
6563 // because it is hard to do it.
6567 public override string[] ValidAttributeTargets {
6569 return attribute_targets;
6575 /// Event is declared like field.
6577 public class EventField: Event {
6579 static string[] attribute_targets = new string [] { "event", "field", "method" };
6580 static string[] attribute_targets_interface = new string[] { "event", "method" };
6582 public EventField (TypeContainer parent, Expression type, int mod_flags,
6583 bool is_iface, MemberName name, Object init,
6584 Attributes attrs, Location loc)
6585 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6587 Add = new AddDelegateMethod (this);
6588 Remove = new RemoveDelegateMethod (this);
6591 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6593 if (a.Target == AttributeTargets.Field) {
6594 FieldBuilder.SetCustomAttribute (cb);
6598 if (a.Target == AttributeTargets.Method) {
6599 Add.ApplyAttributeBuilder (a, cb);
6600 Remove.ApplyAttributeBuilder (a, cb);
6604 base.ApplyAttributeBuilder (a, cb);
6607 public override string[] ValidAttributeTargets {
6609 return IsInterface ? attribute_targets_interface : attribute_targets;
6614 public abstract class Event : FieldBase {
6616 protected sealed class AddDelegateMethod: DelegateMethod
6619 public AddDelegateMethod (Event method):
6620 base (method, "add_")
6624 public AddDelegateMethod (Event method, Accessor accessor):
6625 base (method, accessor, "add_")
6629 protected override MethodInfo DelegateMethodInfo {
6631 return TypeManager.delegate_combine_delegate_delegate;
6637 protected sealed class RemoveDelegateMethod: DelegateMethod
6639 public RemoveDelegateMethod (Event method):
6640 base (method, "remove_")
6644 public RemoveDelegateMethod (Event method, Accessor accessor):
6645 base (method, accessor, "remove_")
6649 protected override MethodInfo DelegateMethodInfo {
6651 return TypeManager.delegate_remove_delegate_delegate;
6657 public abstract class DelegateMethod: AbstractPropertyEventMethod
6659 protected readonly Event method;
6660 ImplicitParameter param_attr;
6662 static string[] attribute_targets = new string [] { "method", "param", "return" };
6664 public DelegateMethod (Event method, string prefix)
6665 : base (method, prefix)
6667 this.method = method;
6670 public DelegateMethod (Event method, Accessor accessor, string prefix)
6671 : base (method, accessor, prefix)
6673 this.method = method;
6676 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6678 if (a.Target == AttributeTargets.Parameter) {
6679 if (param_attr == null)
6680 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6682 param_attr.ApplyAttributeBuilder (a, cb);
6686 base.ApplyAttributeBuilder (a, cb);
6689 public override AttributeTargets AttributeTargets {
6691 return AttributeTargets.Method;
6695 public override bool IsClsCompliaceRequired(DeclSpace ds)
6697 return method.IsClsCompliaceRequired (ds);
6700 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6702 method_data = new MethodData (method, ip, method.ModFlags,
6703 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6705 if (!method_data.Define (container))
6708 MethodBuilder mb = method_data.MethodBuilder;
6709 mb.DefineParameter (1, ParameterAttributes.None, "value");
6714 public override void Emit (TypeContainer tc)
6716 if (block != null) {
6721 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6722 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6724 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6725 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6726 ig.Emit (OpCodes.Ldsfld, field_info);
6727 ig.Emit (OpCodes.Ldarg_0);
6728 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6729 ig.Emit (OpCodes.Castclass, method.MemberType);
6730 ig.Emit (OpCodes.Stsfld, field_info);
6732 ig.Emit (OpCodes.Ldarg_0);
6733 ig.Emit (OpCodes.Ldarg_0);
6734 ig.Emit (OpCodes.Ldfld, field_info);
6735 ig.Emit (OpCodes.Ldarg_1);
6736 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6737 ig.Emit (OpCodes.Castclass, method.MemberType);
6738 ig.Emit (OpCodes.Stfld, field_info);
6740 ig.Emit (OpCodes.Ret);
6743 protected abstract MethodInfo DelegateMethodInfo { get; }
6745 public override Type[] ParameterTypes {
6747 return new Type[] { method.MemberType };
6751 public override Type ReturnType {
6753 return TypeManager.void_type;
6757 public override EmitContext CreateEmitContext (TypeContainer tc,
6760 return new EmitContext (
6761 tc, method.Parent, Location, ig, ReturnType,
6762 method.ModFlags, false);
6765 public override string GetSignatureForError (TypeContainer tc)
6767 return String.Concat (tc.Name, '.', method.Name);
6770 public override ObsoleteAttribute GetObsoleteAttribute ()
6772 return method.GetObsoleteAttribute (method.Parent);
6775 public override string[] ValidAttributeTargets {
6777 return attribute_targets;
6783 const int AllowedModifiers =
6786 Modifiers.PROTECTED |
6787 Modifiers.INTERNAL |
6792 Modifiers.OVERRIDE |
6796 const int AllowedInterfaceModifiers =
6799 public DelegateMethod Add, Remove;
6800 public MyEventBuilder EventBuilder;
6801 public MethodBuilder AddBuilder, RemoveBuilder;
6803 public Event (TypeContainer parent, Expression type, int mod_flags,
6804 bool is_iface, MemberName name, Object init, Attributes attrs,
6806 : base (parent, type, mod_flags,
6807 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6808 name, init, attrs, loc)
6810 IsInterface = is_iface;
6813 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6815 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6816 a.Error_InvalidSecurityParent ();
6820 EventBuilder.SetCustomAttribute (cb);
6823 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6825 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6828 public override AttributeTargets AttributeTargets {
6830 return AttributeTargets.Event;
6834 public override bool Define ()
6836 EventAttributes e_attr;
6837 e_attr = EventAttributes.None;
6842 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6843 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6844 "': abstract event can not have an initializer");
6848 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6849 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6850 "' : event must be of a delegate type");
6854 EmitContext ec = Parent.EmitContext;
6856 throw new InternalErrorException ("Event.Define called too early?");
6857 bool old_unsafe = ec.InUnsafe;
6858 ec.InUnsafe = InUnsafe;
6860 Parameter [] parms = new Parameter [1];
6861 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6862 Parameters parameters = new Parameters (parms, null, Location);
6863 Type [] types = parameters.GetParameterInfo (ec);
6864 InternalParameters ip = new InternalParameters (types, parameters);
6866 ec.InUnsafe = old_unsafe;
6872 // Now define the accessors
6875 AddBuilder = Add.Define (Parent, ip);
6876 if (AddBuilder == null)
6879 RemoveBuilder = Remove.Define (Parent, ip);
6880 if (RemoveBuilder == null)
6883 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6885 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6886 FieldBuilder = Parent.TypeBuilder.DefineField (
6888 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6889 TypeManager.RegisterPrivateFieldOfEvent (
6890 (EventInfo) EventBuilder, FieldBuilder);
6891 TypeManager.RegisterFieldBase (FieldBuilder, this);
6894 EventBuilder.SetAddOnMethod (AddBuilder);
6895 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6897 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6901 protected override bool CheckBase ()
6903 if (!base.CheckBase ())
6906 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6907 if (!(conflict_symbol is EventInfo)) {
6908 Report.SymbolRelatedToPreviousError (conflict_symbol);
6909 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6917 public override void Emit ()
6919 if (OptAttributes != null) {
6920 EmitContext ec = new EmitContext (
6921 Parent, Location, null, MemberType, ModFlags);
6922 OptAttributes.Emit (ec, this);
6927 Remove.Emit (Parent);
6933 public override string GetSignatureForError ()
6935 if (EventBuilder == null)
6936 return base.GetSignatureForError (Parent);
6938 return TypeManager.GetFullNameSignature (EventBuilder);
6942 // Represents header string for documentation comment.
6944 public override string DocCommentHeader {
6945 get { return "E:"; }
6950 public class Indexer : PropertyBase {
6952 class GetIndexerMethod: GetMethod
6954 public GetIndexerMethod (MethodCore method):
6959 public GetIndexerMethod (MethodCore method, Accessor accessor):
6960 base (method, accessor)
6964 // TODO: one GetSignatureForError is enough (reuse Parent member)
6965 public override string GetSignatureForError (TypeContainer tc)
6967 string core = base.GetSignatureForError (tc);
6968 return core.Replace (TypeContainer.DefaultIndexerName,
6969 String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
6972 public override Type[] ParameterTypes {
6974 return method.ParameterTypes;
6979 class SetIndexerMethod: SetMethod
6981 readonly Parameters parameters;
6983 public SetIndexerMethod (MethodCore method):
6988 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
6989 base (method, accessor)
6991 this.parameters = parameters;
6994 public override Type[] ParameterTypes {
6996 int top = method.ParameterTypes.Length;
6997 Type [] set_pars = new Type [top + 1];
6998 method.ParameterTypes.CopyTo (set_pars, 0);
6999 set_pars [top] = method.MemberType;
7004 protected override InternalParameters GetParameterInfo (EmitContext ec)
7006 Parameter [] fixed_parms = parameters.FixedParameters;
7008 if (fixed_parms == null){
7009 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7010 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7011 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7013 // Here is the problem: the `value' parameter has
7014 // to come *after* the array parameter in the declaration
7016 // X (object [] x, Type value)
7019 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7020 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7024 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7026 fixed_parms.CopyTo (tmp, 0);
7027 tmp [fixed_parms.Length] = new Parameter (
7028 method.Type, "value", Parameter.Modifier.NONE, null);
7030 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7031 Type [] types = set_formal_params.GetParameterInfo (ec);
7033 return new InternalParameters (types, set_formal_params);
7038 const int AllowedModifiers =
7041 Modifiers.PROTECTED |
7042 Modifiers.INTERNAL |
7046 Modifiers.OVERRIDE |
7051 const int AllowedInterfaceModifiers =
7055 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7056 bool is_iface, Parameters parameters, Attributes attrs,
7057 Accessor get_block, Accessor set_block, Location loc)
7058 : base (ds, type, mod,
7059 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7060 is_iface, name, parameters, attrs, loc)
7062 if (get_block == null)
7063 Get = new GetIndexerMethod (this);
7065 Get = new GetIndexerMethod (this, get_block);
7067 if (set_block == null)
7068 Set = new SetIndexerMethod (this);
7070 Set = new SetIndexerMethod (this, parameters, set_block);
7073 public override bool Define ()
7075 PropertyAttributes prop_attr =
7076 PropertyAttributes.RTSpecialName |
7077 PropertyAttributes.SpecialName;
7079 if (!base.Define ())
7082 if (MemberType == TypeManager.void_type) {
7083 Report.Error (620, Location, "Indexers cannot have void type");
7087 if (OptAttributes != null) {
7088 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7089 if (indexer_attr != null) {
7090 // Remove the attribute from the list because it is not emitted
7091 OptAttributes.Attrs.Remove (indexer_attr);
7093 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7095 if (IsExplicitImpl) {
7096 Report.Error (415, indexer_attr.Location,
7097 "The 'IndexerName' attribute is valid only on an " +
7098 "indexer that is not an explicit interface member declaration");
7102 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7103 Report.Error (609, indexer_attr.Location,
7104 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7108 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7109 Report.Error (633, indexer_attr.Location,
7110 "The argument to the 'IndexerName' attribute must be a valid identifier");
7114 UpdateMemberName ();
7118 if (InterfaceType != null) {
7119 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7120 if (base_IndexerName != Name)
7121 ShortName = base_IndexerName;
7122 UpdateMemberName ();
7125 if (!Parent.AddToMemberContainer (this) ||
7126 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7132 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7134 GetBuilder = Get.Define (Parent);
7135 if (GetBuilder == null)
7140 SetBuilder = Set.Define (Parent);
7141 if (SetBuilder == null)
7146 // Now name the parameters
7148 Parameter [] p = Parameters.FixedParameters;
7150 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7151 Report.Error (631, Location, "ref and out are not valid in this context");
7157 for (i = 0; i < p.Length; ++i) {
7159 GetBuilder.DefineParameter (
7160 i + 1, p [i].Attributes, p [i].Name);
7163 SetBuilder.DefineParameter (
7164 i + 1, p [i].Attributes, p [i].Name);
7168 SetBuilder.DefineParameter (
7169 i + 1, ParameterAttributes.None, "value");
7171 if (i != ParameterTypes.Length) {
7172 Parameter array_param = Parameters.ArrayParameter;
7174 SetBuilder.DefineParameter (
7175 i + 1, array_param.Attributes, array_param.Name);
7179 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7180 Name, prop_attr, MemberType, ParameterTypes);
7183 PropertyBuilder.SetGetMethod (GetBuilder);
7186 PropertyBuilder.SetSetMethod (SetBuilder);
7188 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7193 public override string GetSignatureForError ()
7195 if (PropertyBuilder == null)
7196 return GetSignatureForError (Parent);
7198 return TypeManager.CSharpSignature (PropertyBuilder, true);
7201 public override string GetSignatureForError(TypeContainer tc)
7203 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7206 public override bool MarkForDuplicationCheck ()
7208 caching_flags |= Flags.TestMethodDuplication;
7214 public class Operator : MethodCore, IIteratorContainer {
7216 const int AllowedModifiers =
7222 public enum OpType : byte {
7232 // Unary and Binary operators
7255 // Implicit and Explicit
7260 public readonly OpType OperatorType;
7261 public MethodBuilder OperatorMethodBuilder;
7263 public Method OperatorMethod;
7265 static string[] attribute_targets = new string [] { "method", "return" };
7267 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7268 int mod_flags, Parameters parameters,
7269 ToplevelBlock block, Attributes attrs, Location loc)
7270 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7271 new MemberName ("op_" + type), attrs, parameters, loc)
7273 OperatorType = type;
7277 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7279 OperatorMethod.ApplyAttributeBuilder (a, cb);
7282 public override AttributeTargets AttributeTargets {
7284 return AttributeTargets.Method;
7288 protected override bool CheckForDuplications()
7290 ArrayList ar = Parent.Operators;
7292 int arLen = ar.Count;
7294 for (int i = 0; i < arLen; i++) {
7295 Operator o = (Operator) ar [i];
7296 if (IsDuplicateImplementation (o))
7301 ar = Parent.Methods;
7303 int arLen = ar.Count;
7305 for (int i = 0; i < arLen; i++) {
7306 Method m = (Method) ar [i];
7307 if (IsDuplicateImplementation (m))
7315 public override bool Define ()
7318 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7319 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7320 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7327 if (MemberType == TypeManager.void_type) {
7328 Report.Error (590, Location, "User-defined operators cannot return void");
7332 OperatorMethod = new Method (
7333 Parent, Type, ModFlags, false, MemberName,
7334 Parameters, OptAttributes, Location);
7336 OperatorMethod.Block = Block;
7337 OperatorMethod.IsOperator = true;
7338 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7339 OperatorMethod.Define ();
7341 if (OperatorMethod.MethodBuilder == null)
7344 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7346 parameter_types = OperatorMethod.ParameterTypes;
7347 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7348 Type return_type = OperatorMethod.ReturnType;
7349 Type first_arg_type = parameter_types [0];
7354 // Rules for conversion operators
7356 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7357 if (first_arg_type == return_type && first_arg_type == declaring_type){
7360 "User-defined conversion cannot take an object of the " +
7361 "enclosing type and convert to an object of the enclosing" +
7366 if (first_arg_type != declaring_type && return_type != declaring_type){
7369 "User-defined conversion must convert to or from the " +
7374 if (first_arg_type == TypeManager.object_type ||
7375 return_type == TypeManager.object_type){
7378 "User-defined conversion cannot convert to or from " +
7383 if (first_arg_type.IsInterface || return_type.IsInterface){
7386 "User-defined conversion cannot convert to or from an " +
7391 if (first_arg_type.IsSubclassOf (return_type)
7392 || return_type.IsSubclassOf (first_arg_type)){
7393 if (declaring_type.IsSubclassOf (return_type)) {
7394 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7397 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7400 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7401 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7402 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");
7405 } else if (Parameters.FixedParameters.Length == 1) {
7406 // Checks for Unary operators
7408 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7409 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7410 Report.Error (448, Location,
7411 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7414 if (first_arg_type != declaring_type) {
7416 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7421 if (first_arg_type != declaring_type){
7424 "The parameter of a unary operator must be the " +
7429 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7430 if (return_type != TypeManager.bool_type){
7433 "The return type of operator True or False " +
7440 // Checks for Binary operators
7442 if (first_arg_type != declaring_type &&
7443 parameter_types [1] != declaring_type){
7446 "One of the parameters of a binary operator must " +
7447 "be the containing type");
7455 public override void Emit ()
7458 // abstract or extern methods have no bodies
7460 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7463 OperatorMethod.Emit ();
7467 // Operator cannot be override
7468 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7473 public static string GetName (OpType ot)
7476 case OpType.LogicalNot:
7478 case OpType.OnesComplement:
7480 case OpType.Increment:
7482 case OpType.Decrement:
7488 case OpType.Addition:
7490 case OpType.Subtraction:
7492 case OpType.UnaryPlus:
7494 case OpType.UnaryNegation:
7496 case OpType.Multiply:
7498 case OpType.Division:
7500 case OpType.Modulus:
7502 case OpType.BitwiseAnd:
7504 case OpType.BitwiseOr:
7506 case OpType.ExclusiveOr:
7508 case OpType.LeftShift:
7510 case OpType.RightShift:
7512 case OpType.Equality:
7514 case OpType.Inequality:
7516 case OpType.GreaterThan:
7518 case OpType.LessThan:
7520 case OpType.GreaterThanOrEqual:
7522 case OpType.LessThanOrEqual:
7524 case OpType.Implicit:
7526 case OpType.Explicit:
7532 public override string GetSignatureForError (TypeContainer tc)
7534 StringBuilder sb = new StringBuilder ();
7535 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7536 Parameters.FixedParameters [0].GetSignatureForError ());
7538 if (Parameters.FixedParameters.Length > 1) {
7540 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7543 return sb.ToString ();
7546 public override string GetSignatureForError ()
7551 public override bool MarkForDuplicationCheck ()
7553 caching_flags |= Flags.TestMethodDuplication;
7557 public override string ToString ()
7559 if (OperatorMethod == null)
7562 Type return_type = OperatorMethod.ReturnType;
7563 Type [] param_types = OperatorMethod.ParameterTypes;
7565 if (Parameters.FixedParameters.Length == 1)
7566 return String.Format (
7567 "{0} operator {1}({2})",
7568 TypeManager.CSharpName (return_type),
7569 GetName (OperatorType),
7572 return String.Format (
7573 "{0} operator {1}({2}, {3})",
7574 TypeManager.CSharpName (return_type),
7575 GetName (OperatorType),
7576 param_types [0], param_types [1]);
7579 public override string[] ValidAttributeTargets {
7581 return attribute_targets;
7585 public void SetYields ()
7587 ModFlags |= Modifiers.METHOD_YIELDS;
7592 // This is used to compare method signatures
7594 struct MethodSignature {
7596 public Type RetType;
7597 public Type [] Parameters;
7600 /// This delegate is used to extract methods which have the
7601 /// same signature as the argument
7603 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7605 public MethodSignature (string name, Type ret_type, Type [] parameters)
7610 if (parameters == null)
7611 Parameters = TypeManager.NoTypes;
7613 Parameters = parameters;
7616 public override string ToString ()
7619 if (Parameters.Length != 0){
7620 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7621 for (int i = 0; i < Parameters.Length; i++){
7622 sb.Append (Parameters [i]);
7623 if (i+1 < Parameters.Length)
7626 pars = sb.ToString ();
7629 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7632 public override int GetHashCode ()
7634 return Name.GetHashCode ();
7637 public override bool Equals (Object o)
7639 MethodSignature other = (MethodSignature) o;
7641 if (other.Name != Name)
7644 if (other.RetType != RetType)
7647 if (Parameters == null){
7648 if (other.Parameters == null)
7653 if (other.Parameters == null)
7656 int c = Parameters.Length;
7657 if (other.Parameters.Length != c)
7660 for (int i = 0; i < c; i++)
7661 if (other.Parameters [i] != Parameters [i])
7667 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7669 MethodSignature sig = (MethodSignature) filter_criteria;
7671 if (m.Name != sig.Name)
7675 MethodInfo mi = m as MethodInfo;
7676 PropertyInfo pi = m as PropertyInfo;
7679 ReturnType = mi.ReturnType;
7680 else if (pi != null)
7681 ReturnType = pi.PropertyType;
7686 // we use sig.RetType == null to mean `do not check the
7687 // method return value.
7689 if (sig.RetType != null)
7690 if (ReturnType != sig.RetType)
7695 args = TypeManager.GetArgumentTypes (mi);
7697 args = TypeManager.GetArgumentTypes (pi);
7698 Type [] sigp = sig.Parameters;
7700 if (args.Length != sigp.Length)
7703 for (int i = args.Length; i > 0; ){
7705 if (args [i] != sigp [i])