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 // Skip erroneous code.
283 if (op.OperatorMethod == null)
286 switch (op.OperatorType){
287 case Operator.OpType.Equality:
289 has_equality_or_inequality = true;
291 case Operator.OpType.Inequality:
293 has_equality_or_inequality = true;
296 case Operator.OpType.True:
299 case Operator.OpType.False:
303 case Operator.OpType.GreaterThan:
305 case Operator.OpType.LessThan:
308 case Operator.OpType.GreaterThanOrEqual:
310 case Operator.OpType.LessThanOrEqual:
316 OperatorEntry oe = new OperatorEntry (reg, op);
318 object o = pairs [oe];
322 oe = (OperatorEntry) o;
327 if (true_op != null){
328 if (false_op == null)
329 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
330 true_op.GetSignatureForError ());
331 } else if (false_op != null)
332 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
333 false_op.GetSignatureForError ());
336 // Look for the mistakes.
338 foreach (DictionaryEntry de in pairs){
339 OperatorEntry oe = (OperatorEntry) de.Key;
346 case Operator.OpType.Equality:
349 case Operator.OpType.Inequality:
352 case Operator.OpType.GreaterThan:
355 case Operator.OpType.LessThan:
358 case Operator.OpType.GreaterThanOrEqual:
361 case Operator.OpType.LessThanOrEqual:
365 Report.Error (216, oe.op.Location,
366 "The operator `{0}' requires a matching operator `{1}' to also be defined",
367 oe.op.GetSignatureForError (), s);
370 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
371 if (container.Methods == null || !container.Methods.HasEquals)
372 Report.Warning (660, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
374 if (container.Methods == null || !container.Methods.HasGetHashCode)
375 Report.Warning (661, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
379 public override void DefineContainerMembers ()
381 base.DefineContainerMembers ();
382 CheckPairedOperators ();
387 // Whether this is a struct, class or interface
388 public readonly Kind Kind;
390 // Holds a list of classes and structures
393 // Holds the list of properties
394 MemberCoreArrayList properties;
396 // Holds the list of enumerations
397 MemberCoreArrayList enums;
399 // Holds the list of delegates
400 MemberCoreArrayList delegates;
402 // Holds the list of constructors
403 protected MemberCoreArrayList instance_constructors;
405 // Holds the list of fields
406 MemberCoreArrayList fields;
408 // Holds a list of fields that have initializers
409 protected ArrayList initialized_fields;
411 // Holds a list of static fields that have initializers
412 protected ArrayList initialized_static_fields;
414 // Holds the list of constants
415 MemberCoreArrayList constants;
418 MemberCoreArrayList interfaces;
420 // Holds the methods.
421 MethodArrayList methods;
424 protected MemberCoreArrayList events;
426 // Holds the indexers
427 IndexerArrayList indexers;
429 // Holds the operators
430 MemberCoreArrayList operators;
432 // Holds the iterators
435 // Holds the parts of a partial class;
439 // Pointers to the default constructor and the default static constructor
441 protected Constructor default_constructor;
442 protected Constructor default_static_constructor;
445 // Points to the first non-static field added to the container.
447 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
448 // and the first one's as good as any.
450 FieldBase first_nonstatic_field = null;
453 // This one is computed after we can distinguish interfaces
454 // from classes from the arraylist `type_bases'
456 string base_class_name;
458 TypeExpr[] iface_exprs;
460 ArrayList type_bases;
462 bool members_defined;
463 bool members_defined_ok;
465 // The interfaces we implement.
466 protected Type[] ifaces;
467 protected Type ptype;
469 // The base member cache and our member cache
470 MemberCache base_cache;
471 MemberCache member_cache;
473 public const string DefaultIndexerName = "Item";
475 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
476 Attributes attrs, Kind kind, Location l)
477 : base (ns, parent, name, attrs, l)
479 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
480 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
484 types = new ArrayList ();
486 base_class_name = null;
489 public bool AddToMemberContainer (MemberCore symbol)
491 return AddToContainer (symbol, symbol.Name);
494 bool AddToTypeContainer (DeclSpace ds)
496 // Parent == null ==> this == RootContext.Tree.Types
497 return AddToContainer (ds, (Parent == null) ? ds.Name : ds.Basename);
500 public void AddConstant (Const constant)
502 if (!AddToMemberContainer (constant))
505 if (constants == null)
506 constants = new MemberCoreArrayList ();
508 constants.Add (constant);
511 public void AddEnum (Mono.CSharp.Enum e)
513 if (!AddToTypeContainer (e))
517 enums = new MemberCoreArrayList ();
522 public void AddClassOrStruct (TypeContainer c)
524 if (!AddToTypeContainer (c))
530 public void AddDelegate (Delegate d)
532 if (!AddToTypeContainer (d))
535 if (delegates == null)
536 delegates = new MemberCoreArrayList ();
541 public void AddMethod (Method method)
543 if (!AddToMemberContainer (method))
547 methods = new MethodArrayList (this);
549 if (method.MemberName.Left != null)
550 methods.Insert (0, method);
552 methods.Add (method);
555 public void AddConstructor (Constructor c)
557 if (c.Name != Basename) {
558 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
561 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
564 if (default_static_constructor != null) {
565 Report.SymbolRelatedToPreviousError (default_static_constructor);
566 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
570 default_static_constructor = c;
573 if (default_constructor != null) {
574 Report.SymbolRelatedToPreviousError (default_constructor);
575 Report.Error (111, c.Location, Error111, c.Location, c.GetSignatureForError ());
578 default_constructor = c;
581 if (instance_constructors == null)
582 instance_constructors = new MemberCoreArrayList ();
584 instance_constructors.Add (c);
588 internal static string Error111 {
590 return "`{0}' is already defined. Rename this member or use different parameter types";
594 public void AddInterface (TypeContainer iface)
596 if (!AddToTypeContainer (iface))
599 if (interfaces == null) {
600 interfaces = new MemberCoreArrayList ();
603 interfaces.Add (iface);
606 public void AddField (FieldMember field)
608 if (!AddToMemberContainer (field))
612 fields = new MemberCoreArrayList ();
616 if (field.HasInitializer)
617 RegisterFieldForInitialization (field);
619 if ((field.ModFlags & Modifiers.STATIC) != 0)
622 if (first_nonstatic_field == null) {
623 first_nonstatic_field = field;
627 if (Kind == Kind.Struct &&
628 first_nonstatic_field.Parent != field.Parent &&
629 RootContext.WarningLevel >= 3) {
630 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
631 Report.Warning (282, field.Location,
632 "struct instance field `{0}' found in different declaration from instance field `{1}'",
633 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
637 public void AddProperty (Property prop)
639 if (!AddToMemberContainer (prop) ||
640 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
643 if (properties == null)
644 properties = new MemberCoreArrayList ();
646 if (prop.MemberName.Left != null)
647 properties.Insert (0, prop);
649 properties.Add (prop);
652 public void AddEvent (Event e)
654 if (!AddToMemberContainer (e))
657 if (e is EventProperty) {
658 if (!AddToMemberContainer (e.Add))
661 if (!AddToMemberContainer (e.Remove))
666 events = new MemberCoreArrayList ();
673 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
675 public void AddIndexer (Indexer i)
677 if (indexers == null)
678 indexers = new IndexerArrayList (this);
680 if (i.IsExplicitImpl)
681 indexers.Insert (0, i);
686 public void AddOperator (Operator op)
688 if (!AddToMemberContainer (op))
691 if (operators == null)
692 operators = new OperatorArrayList (this);
697 public void AddIterator (Iterator i)
699 if (iterators == null)
700 iterators = new ArrayList ();
705 public void AddType (TypeContainer tc)
710 public void AddPart (ClassPart part)
713 parts = new ArrayList ();
718 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
720 if (a.Type == TypeManager.default_member_type) {
721 if (Indexers != null) {
722 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
727 base.ApplyAttributeBuilder (a, cb);
730 public override AttributeTargets AttributeTargets {
734 return AttributeTargets.Class;
736 return AttributeTargets.Struct;
738 return AttributeTargets.Interface;
740 throw new NotSupportedException ();
745 public ArrayList Types {
751 public MethodArrayList Methods {
757 public ArrayList Constants {
763 public ArrayList Interfaces {
769 public ArrayList Iterators {
777 return base_class_name;
781 public ArrayList Bases {
791 public ArrayList Fields {
797 public ArrayList InstanceConstructors {
799 return instance_constructors;
803 public ArrayList Properties {
809 public ArrayList Events {
815 public ArrayList Enums {
821 public ArrayList Indexers {
827 public ArrayList Operators {
833 public ArrayList Delegates {
839 public ArrayList Parts {
845 protected override TypeAttributes TypeAttr {
847 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
851 public string IndexerName {
853 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
857 public virtual void RegisterFieldForInitialization (FieldMember field)
859 if ((field.ModFlags & Modifiers.STATIC) != 0){
860 if (initialized_static_fields == null)
861 initialized_static_fields = new ArrayList ();
863 initialized_static_fields.Add (field);
865 if (initialized_fields == null)
866 initialized_fields = new ArrayList ();
868 initialized_fields.Add (field);
873 // Emits the instance field initializers
875 public virtual bool EmitFieldInitializers (EmitContext ec)
878 Expression instance_expr;
881 fields = initialized_static_fields;
882 instance_expr = null;
884 fields = initialized_fields;
885 instance_expr = new This (Location.Null).Resolve (ec);
891 foreach (FieldMember f in fields){
892 Expression e = f.GetInitializerExpression (ec);
896 Location l = f.Location;
897 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
898 fe.InstanceExpression = instance_expr;
899 ExpressionStatement a = new Assign (fe, e, l);
901 a = a.ResolveStatement (ec);
905 Constant c = e as Constant;
907 if (c.IsDefaultValue)
911 a.EmitStatement (ec);
918 // Defines the default constructors
920 protected void DefineDefaultConstructor (bool is_static)
924 // The default constructor is public
925 // If the class is abstract, the default constructor is protected
926 // The default static constructor is private
928 int mods = Modifiers.PUBLIC;
930 mods = Modifiers.STATIC | Modifiers.PRIVATE;
931 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
932 mods = Modifiers.PROTECTED;
934 TypeContainer constructor_parent = this;
936 constructor_parent = (TypeContainer) Parts [0];
938 c = new Constructor (constructor_parent, Basename, mods,
939 Parameters.EmptyReadOnlyParameters,
940 new ConstructorBaseInitializer (
941 null, Parameters.EmptyReadOnlyParameters,
947 c.Block = new ToplevelBlock (null, Location);
952 /// The pending methods that need to be implemented
953 // (interfaces or abstract methods)
955 public PendingImplementation Pending;
957 public abstract PendingImplementation GetPendingImplementations ();
959 TypeExpr[] GetPartialBases (out TypeExpr base_class)
961 ArrayList ifaces = new ArrayList ();
964 Location base_loc = Location.Null;
966 foreach (ClassPart part in parts) {
967 TypeExpr new_base_class;
968 TypeExpr[] new_ifaces;
970 new_ifaces = part.GetClassBases (out new_base_class);
971 if (new_ifaces == null && new_base_class != null)
974 if ((base_class != null) && (new_base_class != null) &&
975 !base_class.Equals (new_base_class)) {
976 Report.Error (263, part.Location,
977 "Partial declarations of `{0}' must " +
978 "not specify different base classes",
981 if (!Location.IsNull (base_loc))
982 Report.LocationOfPreviousError (base_loc);
987 if ((base_class == null) && (new_base_class != null)) {
988 base_class = new_base_class;
989 base_loc = part.Location;
992 if (new_ifaces == null)
995 foreach (TypeExpr iface in new_ifaces) {
997 foreach (TypeExpr old_iface in ifaces) {
998 if (old_iface.Equals (iface)) {
1009 TypeExpr[] retval = new TypeExpr [ifaces.Count];
1010 ifaces.CopyTo (retval, 0);
1014 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1018 int count = Bases.Count;
1019 int start = 0, i, j;
1021 if (Kind == Kind.Class){
1022 TypeExpr name = ResolveBaseTypeExpr (
1023 (Expression) Bases [0], false, Location);
1029 if (!name.IsInterface) {
1030 // base_class could be a class, struct, enum, delegate.
1031 // This is validated in GetClassBases.
1037 TypeExpr [] ifaces = new TypeExpr [count-start];
1039 for (i = start, j = 0; i < count; i++, j++){
1040 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1041 if (resolved == null) {
1045 ifaces [j] = resolved;
1052 /// This function computes the Base class and also the
1053 /// list of interfaces that the class or struct @c implements.
1055 /// The return value is an array (might be null) of
1056 /// interfaces implemented (as Types).
1058 /// The @base_class argument is set to the base object or null
1059 /// if this is `System.Object'.
1061 TypeExpr [] GetClassBases (out TypeExpr base_class)
1068 ifaces = GetPartialBases (out base_class);
1069 else if (Bases == null){
1073 ifaces = GetNormalBases (out base_class);
1078 if ((base_class != null) && (Kind == Kind.Class)){
1080 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1081 Report.Error (1521, base_class.Location, "Invalid base type");
1085 if (base_class.IsSealed){
1086 Report.SymbolRelatedToPreviousError (base_class.Type);
1087 if (base_class.Type.IsAbstract) {
1088 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
1089 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1091 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
1092 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1097 if (!base_class.CanInheritFrom ()){
1098 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
1099 GetSignatureForError (), base_class.GetSignatureForError ());
1103 if (!base_class.AsAccessible (this, ModFlags)) {
1104 Report.SymbolRelatedToPreviousError (base_class.Type);
1105 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
1106 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1110 if (base_class != null)
1111 base_class_name = base_class.Name;
1116 int count = ifaces != null ? ifaces.Length : 0;
1118 for (i = 0; i < count; i++) {
1119 TypeExpr iface = (TypeExpr) ifaces [i];
1121 if (!iface.IsInterface) {
1122 if (Kind != Kind.Class) {
1123 // TODO: location of symbol related ....
1124 Error_TypeInListIsNotInterface (Location, iface.FullName);
1126 else if (base_class != null)
1127 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1128 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1130 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1131 GetSignatureForError (), iface.GetSignatureForError ());
1136 for (int x = 0; x < i; x++) {
1137 if (iface.Equals (ifaces [x])) {
1138 Report.Error (528, Location,
1139 "`{0}' is already listed in " +
1140 "interface list", iface.Name);
1145 if ((Kind == Kind.Interface) &&
1146 !iface.AsAccessible (Parent, ModFlags)) {
1147 Report.Error (61, Location,
1148 "Inconsistent accessibility: base " +
1149 "interface `{0}' is less accessible " +
1150 "than interface `{1}'", iface.Name,
1160 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1162 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1166 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1168 public override TypeBuilder DefineType ()
1173 if (TypeBuilder != null)
1176 TypeAttributes type_attributes = TypeAttr;
1180 if (TypeManager.NamespaceClash (Name, Location)) {
1185 ModuleBuilder builder = CodeGen.Module.Builder;
1186 TypeBuilder = builder.DefineType (
1187 Name, type_attributes, null, null);
1189 TypeBuilder builder = Parent.TypeBuilder;
1190 if (builder == null) {
1195 TypeBuilder = builder.DefineNestedType (
1196 Basename, type_attributes, ptype, null);
1198 } catch (ArgumentException) {
1199 Report.RuntimeMissingSupport (Location, "static classes");
1204 TypeManager.AddUserType (Name, this);
1206 if (Parts != null) {
1208 foreach (ClassPart part in Parts) {
1209 part.TypeBuilder = TypeBuilder;
1211 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1212 part.ec.ContainerType = TypeBuilder;
1216 // Normally, we create the EmitContext here.
1217 // The only exception is if we're an Iterator - in this case,
1218 // we already have the `ec', so we don't want to create a new one.
1221 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1222 ec.ContainerType = TypeBuilder;
1225 iface_exprs = GetClassBases (out base_type);
1226 if (iface_exprs == null && base_type != null) {
1231 if (base_type == null) {
1232 if (Kind == Kind.Class){
1233 if (RootContext.StdLib)
1234 base_type = TypeManager.system_object_expr;
1235 else if (Name != "System.Object")
1236 base_type = TypeManager.system_object_expr;
1237 } else if (Kind == Kind.Struct) {
1239 // If we are compiling our runtime,
1240 // and we are defining ValueType, then our
1241 // base is `System.Object'.
1243 if (!RootContext.StdLib && Name == "System.ValueType")
1244 base_type = TypeManager.system_object_expr;
1246 base_type = TypeManager.system_valuetype_expr;
1250 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1251 throw new Exception ();
1253 if (base_type != null) {
1254 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1255 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1256 ptype = base_type.ResolveType (TypeResolveEmitContext);
1257 if (ptype == null) {
1263 if (!CheckRecursiveDefinition (this)) {
1269 TypeBuilder.SetParent (ptype);
1271 // add interfaces that were not added at type creation
1272 if (iface_exprs != null) {
1273 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1274 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1275 TypeResolveEmitContext.ContainerType = TypeBuilder;
1276 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1277 if (ifaces == null) {
1282 foreach (Type itype in ifaces)
1283 TypeBuilder.AddInterfaceImplementation (itype);
1285 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1288 if (!(this is Iterator))
1289 RootContext.RegisterOrder (this);
1291 if (!DefineNestedTypes ()) {
1299 protected virtual bool DefineNestedTypes ()
1301 if (Interfaces != null) {
1302 foreach (TypeContainer iface in Interfaces)
1303 if (iface.DefineType () == null)
1307 if (Types != null) {
1308 foreach (TypeContainer tc in Types)
1309 if (tc.DefineType () == null)
1313 if (Delegates != null) {
1314 foreach (Delegate d in Delegates)
1315 if (d.DefineType () == null)
1319 if (Enums != null) {
1320 foreach (Enum en in Enums)
1321 if (en.DefineType () == null)
1328 TypeContainer InTransit;
1330 protected bool CheckRecursiveDefinition (TypeContainer tc)
1332 if (InTransit != null) {
1333 Report.SymbolRelatedToPreviousError (this);
1334 if (this is Interface)
1336 529, tc.Location, "Inherited interface `{0}' causes a " +
1337 "cycle in the interface hierarchy of `{1}'",
1338 GetSignatureForError (), tc.GetSignatureForError ());
1341 146, tc.Location, "Circular base class dependency " +
1342 "involving `{0}' and `{1}'",
1343 tc.GetSignatureForError (), GetSignatureForError ());
1349 Type parent = ptype;
1350 if (parent != null) {
1351 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1352 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1356 if (iface_exprs != null) {
1357 foreach (TypeExpr iface in iface_exprs) {
1358 Type itype = iface.Type;
1360 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1361 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1370 public static void Error_KeywordNotAllowed (Location loc)
1372 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1376 /// Populates our TypeBuilder with fields and methods
1378 public override bool DefineMembers (TypeContainer container)
1380 if (members_defined)
1381 return members_defined_ok;
1383 if (!base.DefineMembers (container))
1386 members_defined_ok = DoDefineMembers ();
1387 members_defined = true;
1389 return members_defined_ok;
1392 protected virtual bool DoDefineMembers ()
1395 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1396 if (conflict_symbol == null) {
1397 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1398 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1400 if ((ModFlags & Modifiers.NEW) == 0) {
1401 Report.SymbolRelatedToPreviousError (conflict_symbol);
1402 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1403 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1408 DefineContainerMembers (constants);
1409 DefineContainerMembers (fields);
1411 if ((Kind == Kind.Class) && !(this is ClassPart)){
1412 if ((instance_constructors == null) &&
1413 !(this is StaticClass)) {
1414 if (default_constructor == null)
1415 DefineDefaultConstructor (false);
1418 if (initialized_static_fields != null &&
1419 default_static_constructor == null)
1420 DefineDefaultConstructor (true);
1423 if (Kind == Kind.Struct){
1425 // Structs can not have initialized instance
1428 if (initialized_static_fields != null &&
1429 default_static_constructor == null)
1430 DefineDefaultConstructor (true);
1432 if (initialized_fields != null)
1433 ReportStructInitializedInstanceError ();
1436 Pending = GetPendingImplementations ();
1438 if (parts != null) {
1439 foreach (ClassPart part in parts) {
1440 if (!part.DefineMembers (this))
1446 // Constructors are not in the defined_names array
1448 DefineContainerMembers (instance_constructors);
1450 if (default_static_constructor != null)
1451 default_static_constructor.Define ();
1453 DefineContainerMembers (properties);
1454 DefineContainerMembers (events);
1455 DefineContainerMembers (indexers);
1456 DefineContainerMembers (methods);
1457 DefineContainerMembers (operators);
1458 DefineContainerMembers (enums);
1459 DefineContainerMembers (delegates);
1462 if (!(this is ClassPart))
1463 member_cache = new MemberCache (this);
1466 if (parts != null) {
1467 foreach (ClassPart part in parts)
1468 part.member_cache = member_cache;
1471 if (iterators != null) {
1472 foreach (Iterator iterator in iterators) {
1473 if (iterator.DefineType () == null)
1477 foreach (Iterator iterator in iterators) {
1478 if (!iterator.DefineMembers (this))
1486 void ReportStructInitializedInstanceError ()
1488 string n = TypeBuilder.FullName;
1490 foreach (Field f in initialized_fields){
1491 Report.Error (573, Location,
1492 "`{0}': Structs cannot have instance field initializers",
1493 f.GetSignatureForError ());
1497 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1500 mcal.DefineContainerMembers ();
1503 public override bool Define ()
1505 if (parts != null) {
1506 foreach (ClassPart part in parts) {
1507 if (!part.Define ())
1512 if (iterators != null) {
1513 foreach (Iterator iterator in iterators) {
1514 if (!iterator.Define ())
1522 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1524 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1528 /// This function is based by a delegate to the FindMembers routine
1530 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1536 /// This filter is used by FindMembers, and we just keep
1537 /// a global for the filter to `AlwaysAccept'
1539 static MemberFilter accepting_filter;
1542 static TypeContainer ()
1544 accepting_filter = new MemberFilter (AlwaysAccept);
1547 public MethodInfo[] GetMethods ()
1549 ArrayList members = new ArrayList ();
1551 DefineMembers (null);
1553 if (methods != null) {
1554 int len = methods.Count;
1555 for (int i = 0; i < len; i++) {
1556 Method m = (Method) methods [i];
1558 members.Add (m.MethodBuilder);
1562 if (operators != null) {
1563 int len = operators.Count;
1564 for (int i = 0; i < len; i++) {
1565 Operator o = (Operator) operators [i];
1567 members.Add (o.OperatorMethodBuilder);
1571 if (properties != null) {
1572 int len = properties.Count;
1573 for (int i = 0; i < len; i++) {
1574 Property p = (Property) properties [i];
1576 if (p.GetBuilder != null)
1577 members.Add (p.GetBuilder);
1578 if (p.SetBuilder != null)
1579 members.Add (p.SetBuilder);
1583 if (indexers != null) {
1584 int len = indexers.Count;
1585 for (int i = 0; i < len; i++) {
1586 Indexer ix = (Indexer) indexers [i];
1588 if (ix.GetBuilder != null)
1589 members.Add (ix.GetBuilder);
1590 if (ix.SetBuilder != null)
1591 members.Add (ix.SetBuilder);
1595 if (events != null) {
1596 int len = events.Count;
1597 for (int i = 0; i < len; i++) {
1598 Event e = (Event) events [i];
1600 if (e.AddBuilder != null)
1601 members.Add (e.AddBuilder);
1602 if (e.RemoveBuilder != null)
1603 members.Add (e.RemoveBuilder);
1607 MethodInfo[] retMethods = new MethodInfo [members.Count];
1608 members.CopyTo (retMethods, 0);
1612 // Indicated whether container has StructLayout attribute set Explicit
1613 public virtual bool HasExplicitLayout {
1619 public override Type FindNestedType (string name)
1621 ArrayList [] lists = { types, enums, delegates, interfaces };
1623 for (int j = 0; j < lists.Length; ++j) {
1624 ArrayList list = lists [j];
1628 int len = list.Count;
1629 for (int i = 0; i < len; ++i) {
1630 DeclSpace ds = (DeclSpace) list [i];
1631 if (ds.Basename == name) {
1633 return ds.TypeBuilder;
1641 private void FindMembers_NestedTypes (int modflags,
1642 BindingFlags bf, MemberFilter filter, object criteria,
1643 ref ArrayList members)
1645 ArrayList [] lists = { types, enums, delegates, interfaces };
1647 for (int j = 0; j < lists.Length; ++j) {
1648 ArrayList list = lists [j];
1652 int len = list.Count;
1653 for (int i = 0; i < len; i++) {
1654 DeclSpace ds = (DeclSpace) list [i];
1656 if ((ds.ModFlags & modflags) == 0)
1659 TypeBuilder tb = ds.TypeBuilder;
1661 if (!(criteria is string) || ds.Basename.Equals (criteria))
1662 tb = ds.DefineType ();
1665 if (tb != null && (filter (tb, criteria) == true)) {
1666 if (members == null)
1667 members = new ArrayList ();
1676 /// This method returns the members of this type just like Type.FindMembers would
1677 /// Only, we need to use this for types which are _being_ defined because MS'
1678 /// implementation can't take care of that.
1681 // FIXME: return an empty static array instead of null, that cleans up
1682 // some code and is consistent with some coding conventions I just found
1686 // Notice that in various cases we check if our field is non-null,
1687 // something that would normally mean that there was a bug elsewhere.
1689 // The problem happens while we are defining p-invoke methods, as those
1690 // will trigger a FindMembers, but this happens before things are defined
1692 // Since the whole process is a no-op, it is fine to check for null here.
1694 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1695 MemberFilter filter, object criteria)
1697 ArrayList members = null;
1700 if ((bf & BindingFlags.Public) != 0)
1701 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1703 if ((bf & BindingFlags.NonPublic) != 0)
1704 modflags |= Modifiers.PRIVATE;
1706 int static_mask = 0, static_flags = 0;
1707 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1708 case BindingFlags.Static:
1709 static_mask = static_flags = Modifiers.STATIC;
1712 case BindingFlags.Instance:
1713 static_mask = Modifiers.STATIC;
1718 static_mask = static_flags = 0;
1722 Timer.StartTimer (TimerType.TcFindMembers);
1725 filter = accepting_filter;
1727 if ((mt & MemberTypes.Field) != 0) {
1728 if (fields != null) {
1729 int len = fields.Count;
1730 for (int i = 0; i < len; i++) {
1731 FieldMember f = (FieldMember) fields [i];
1733 if ((f.ModFlags & modflags) == 0)
1735 if ((f.ModFlags & static_mask) != static_flags)
1738 FieldBuilder fb = f.FieldBuilder;
1739 if (fb != null && filter (fb, criteria) == true) {
1740 if (members == null)
1741 members = new ArrayList ();
1748 if (constants != null) {
1749 int len = constants.Count;
1750 for (int i = 0; i < len; i++) {
1751 Const con = (Const) constants [i];
1753 if ((con.ModFlags & modflags) == 0)
1755 if ((con.ModFlags & static_mask) != static_flags)
1758 FieldBuilder fb = con.FieldBuilder;
1761 fb = con.FieldBuilder;
1763 if (fb != null && filter (fb, criteria) == true) {
1764 if (members == null)
1765 members = new ArrayList ();
1773 if ((mt & MemberTypes.Method) != 0) {
1774 if (methods != null) {
1775 int len = methods.Count;
1776 for (int i = 0; i < len; i++) {
1777 Method m = (Method) methods [i];
1779 if ((m.ModFlags & modflags) == 0)
1781 if ((m.ModFlags & static_mask) != static_flags)
1784 MethodBuilder mb = m.MethodBuilder;
1786 if (mb != null && filter (mb, criteria) == true) {
1787 if (members == null)
1788 members = new ArrayList ();
1795 if (operators != null) {
1796 int len = operators.Count;
1797 for (int i = 0; i < len; i++) {
1798 Operator o = (Operator) operators [i];
1800 if ((o.ModFlags & modflags) == 0)
1802 if ((o.ModFlags & static_mask) != static_flags)
1805 MethodBuilder ob = o.OperatorMethodBuilder;
1806 if (ob != null && filter (ob, criteria) == true) {
1807 if (members == null)
1808 members = new ArrayList ();
1815 if (properties != null) {
1816 int len = properties.Count;
1817 for (int i = 0; i < len; i++) {
1818 Property p = (Property) properties [i];
1820 if ((p.ModFlags & modflags) == 0)
1822 if ((p.ModFlags & static_mask) != static_flags)
1828 if (b != null && filter (b, criteria) == true) {
1829 if (members == null)
1830 members = new ArrayList ();
1836 if (b != null && filter (b, criteria) == true) {
1837 if (members == null)
1838 members = new ArrayList ();
1845 if (indexers != null) {
1846 int len = indexers.Count;
1847 for (int i = 0; i < len; i++) {
1848 Indexer ix = (Indexer) indexers [i];
1850 if ((ix.ModFlags & modflags) == 0)
1852 if ((ix.ModFlags & static_mask) != static_flags)
1858 if (b != null && filter (b, criteria) == true) {
1859 if (members == null)
1860 members = new ArrayList ();
1866 if (b != null && filter (b, criteria) == true) {
1867 if (members == null)
1868 members = new ArrayList ();
1876 if ((mt & MemberTypes.Event) != 0) {
1877 if (events != null) {
1878 int len = events.Count;
1879 for (int i = 0; i < len; i++) {
1880 Event e = (Event) events [i];
1882 if ((e.ModFlags & modflags) == 0)
1884 if ((e.ModFlags & static_mask) != static_flags)
1887 MemberInfo eb = e.EventBuilder;
1888 if (eb != null && filter (eb, criteria) == true) {
1889 if (members == null)
1890 members = new ArrayList ();
1892 members.Add (e.EventBuilder);
1898 if ((mt & MemberTypes.Property) != 0){
1899 if (properties != null) {
1900 int len = properties.Count;
1901 for (int i = 0; i < len; i++) {
1902 Property p = (Property) properties [i];
1904 if ((p.ModFlags & modflags) == 0)
1906 if ((p.ModFlags & static_mask) != static_flags)
1909 MemberInfo pb = p.PropertyBuilder;
1910 if (pb != null && filter (pb, criteria) == true) {
1911 if (members == null)
1912 members = new ArrayList ();
1914 members.Add (p.PropertyBuilder);
1919 if (indexers != null) {
1920 int len = indexers.Count;
1921 for (int i = 0; i < len; i++) {
1922 Indexer ix = (Indexer) indexers [i];
1924 if ((ix.ModFlags & modflags) == 0)
1926 if ((ix.ModFlags & static_mask) != static_flags)
1929 MemberInfo ib = ix.PropertyBuilder;
1930 if (ib != null && filter (ib, criteria) == true) {
1931 if (members == null)
1932 members = new ArrayList ();
1934 members.Add (ix.PropertyBuilder);
1940 if ((mt & MemberTypes.NestedType) != 0)
1941 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1943 if ((mt & MemberTypes.Constructor) != 0){
1944 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1945 int len = instance_constructors.Count;
1946 for (int i = 0; i < len; i++) {
1947 Constructor c = (Constructor) instance_constructors [i];
1949 ConstructorBuilder cb = c.ConstructorBuilder;
1950 if (cb != null && filter (cb, criteria) == true) {
1951 if (members == null)
1952 members = new ArrayList ();
1959 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1960 ConstructorBuilder cb =
1961 default_static_constructor.ConstructorBuilder;
1963 if (cb != null && filter (cb, criteria) == true) {
1964 if (members == null)
1965 members = new ArrayList ();
1973 // Lookup members in base if requested.
1975 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1976 if (TypeBuilder.BaseType != null) {
1977 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1978 if (list.Count > 0) {
1979 if (members == null)
1980 members = new ArrayList ();
1982 members.AddRange (list);
1985 if (ifaces != null) {
1986 foreach (Type base_type in ifaces) {
1987 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1989 if (list.Count > 0) {
1990 if (members == null)
1991 members = new ArrayList ();
1992 members.AddRange (list);
1998 Timer.StopTimer (TimerType.TcFindMembers);
2000 if (members == null)
2001 return MemberList.Empty;
2003 return new MemberList (members);
2006 public override MemberCache MemberCache {
2008 return member_cache;
2012 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2013 MemberFilter filter, object criteria)
2015 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2018 return ds.FindMembers (mt, bf, filter, criteria);
2020 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2025 // FindMethods will look for methods not only in the type `t', but in
2026 // any interfaces implemented by the type.
2028 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2029 MemberFilter filter, object criteria)
2035 /// Emits the values for the constants
2037 public void EmitConstants ()
2039 if (constants != null)
2040 foreach (Const con in constants)
2045 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2050 foreach (MemberCore mc in al) {
2051 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2055 Report.Warning (169, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2060 public virtual void VerifyMembers ()
2063 // Check for internal or private fields that were never assigned
2065 if (RootContext.WarningLevel >= 3) {
2066 CheckMemberUsage (properties, "property");
2067 CheckMemberUsage (methods, "method");
2068 CheckMemberUsage (constants, "constant");
2070 if (fields != null){
2071 foreach (FieldMember f in fields) {
2072 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2076 if ((f.caching_flags & Flags.IsAssigned) == 0)
2077 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2079 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2080 f.GetSignatureForError ());
2085 // Only report 649 on level 4
2087 if (RootContext.WarningLevel < 4)
2090 if ((f.caching_flags & Flags.IsAssigned) != 0)
2093 Report.Warning (649, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2094 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2101 /// Emits the code, this step is performed after all
2102 /// the types, enumerations, constructors
2104 public void EmitType ()
2106 if (OptAttributes != null)
2107 OptAttributes.Emit (ec, this);
2110 // Structs with no fields need to have at least one byte.
2111 // The right thing would be to set the PackingSize in a DefineType
2112 // but there are no functions that allow interfaces *and* the size to
2116 if (Kind == Kind.Struct && first_nonstatic_field == null){
2117 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2118 FieldAttributes.Private);
2120 if (HasExplicitLayout){
2121 object [] ctor_args = new object [1];
2124 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2125 TypeManager.field_offset_attribute_ctor, ctor_args);
2126 fb.SetCustomAttribute (cba);
2132 if (instance_constructors != null) {
2133 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2134 bool has_compliant_args = false;
2136 foreach (Constructor c in instance_constructors) {
2139 if (has_compliant_args)
2142 has_compliant_args = c.HasCompliantArgs;
2144 if (!has_compliant_args)
2145 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2147 foreach (Constructor c in instance_constructors)
2152 // Can not continue if constants are broken
2154 if (Report.Errors > 0)
2157 if (default_static_constructor != null)
2158 default_static_constructor.Emit ();
2160 if (methods != null)
2161 foreach (Method m in methods)
2164 if (operators != null)
2165 foreach (Operator o in operators)
2168 if (properties != null)
2169 foreach (Property p in properties)
2172 if (indexers != null){
2177 foreach (FieldMember f in fields)
2180 if (events != null){
2181 foreach (Event e in Events)
2185 if (delegates != null) {
2186 foreach (Delegate d in Delegates) {
2191 if (enums != null) {
2192 foreach (Enum e in enums) {
2197 if (parts != null) {
2198 foreach (ClassPart part in parts)
2202 if ((Pending != null) && !(this is ClassPart))
2203 if (Pending.VerifyPendingMethods ())
2206 if (iterators != null)
2207 foreach (Iterator iterator in iterators)
2208 iterator.EmitType ();
2210 // if (types != null)
2211 // foreach (TypeContainer tc in types)
2215 public override void CloseType ()
2217 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2221 caching_flags |= Flags.CloseTypeCreated;
2222 TypeBuilder.CreateType ();
2223 } catch (TypeLoadException){
2225 // This is fine, the code still created the type
2227 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2228 // Console.WriteLine (e.Message);
2230 Console.WriteLine ("In type: " + Name);
2235 foreach (Enum en in Enums)
2239 foreach (TypeContainer tc in Types)
2240 if (tc.Kind == Kind.Struct)
2243 foreach (TypeContainer tc in Types)
2244 if (tc.Kind != Kind.Struct)
2248 if (Delegates != null)
2249 foreach (Delegate d in Delegates)
2252 if (Iterators != null)
2253 foreach (Iterator i in Iterators)
2261 initialized_fields = null;
2262 initialized_static_fields = null;
2271 default_constructor = null;
2272 default_static_constructor = null;
2274 OptAttributes = null;
2277 member_cache = null;
2281 // Performs the validation on a Method's modifiers (properties have
2282 // the same properties).
2284 public bool MethodModifiersValid (MemberCore mc)
2286 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2287 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2288 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2290 int flags = mc.ModFlags;
2293 // At most one of static, virtual or override
2295 if ((flags & Modifiers.STATIC) != 0){
2296 if ((flags & vao) != 0){
2297 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2298 mc.GetSignatureForError ());
2303 if (Kind == Kind.Struct){
2304 if ((flags & va) != 0){
2305 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2310 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2311 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2312 mc.GetSignatureForError ());
2317 // If the declaration includes the abstract modifier, then the
2318 // declaration does not include static, virtual or extern
2320 if ((flags & Modifiers.ABSTRACT) != 0){
2321 if ((flags & Modifiers.EXTERN) != 0){
2323 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2327 if ((flags & Modifiers.SEALED) != 0) {
2328 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2332 if ((flags & Modifiers.VIRTUAL) != 0){
2333 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2337 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2338 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2343 if ((flags & Modifiers.PRIVATE) != 0){
2344 if ((flags & vao) != 0){
2345 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2350 if ((flags & Modifiers.SEALED) != 0){
2351 if ((flags & Modifiers.OVERRIDE) == 0){
2352 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2360 public bool UserDefinedStaticConstructor {
2362 return default_static_constructor != null;
2366 public Constructor DefaultStaticConstructor {
2367 get { return default_static_constructor; }
2370 protected override bool VerifyClsCompliance (DeclSpace ds)
2372 if (!base.VerifyClsCompliance (ds))
2377 Type base_type = TypeBuilder.BaseType;
2378 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2379 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2382 if (!Parent.IsClsCompliaceRequired (ds)) {
2383 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type `{1}'",
2384 GetSignatureForError (), Parent.GetSignatureForError ());
2391 /// Checks whether container name is CLS Compliant
2393 void VerifyClsName ()
2395 Hashtable base_members = base_cache == null ?
2397 base_cache.GetPublicMembers ();
2398 Hashtable this_members = new Hashtable ();
2400 foreach (DictionaryEntry entry in defined_names) {
2401 MemberCore mc = (MemberCore)entry.Value;
2402 if (!mc.IsClsCompliaceRequired (this))
2405 string name = (string)entry.Key;
2406 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2408 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2409 object found = base_members [lcase];
2410 if (found == null) {
2411 found = this_members [lcase];
2412 if (found == null) {
2413 this_members.Add (lcase, mc);
2418 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2421 if (found is MemberInfo) {
2422 if (basename == ((MemberInfo)found).Name)
2424 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2426 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2428 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2434 /// Performs checks for an explicit interface implementation. First it
2435 /// checks whether the `interface_type' is a base inteface implementation.
2436 /// Then it checks whether `name' exists in the interface type.
2438 public virtual bool VerifyImplements (MemberBase mb)
2440 if (ifaces != null) {
2441 foreach (Type t in ifaces){
2442 if (t == mb.InterfaceType)
2447 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2448 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2452 protected override void VerifyObsoleteAttribute()
2454 CheckUsageOfObsoleteAttribute (ptype);
2459 foreach (Type iface in ifaces) {
2460 CheckUsageOfObsoleteAttribute (iface);
2469 string IMemberContainer.Name {
2475 Type IMemberContainer.Type {
2481 MemberCache IMemberContainer.MemberCache {
2483 return member_cache;
2487 bool IMemberContainer.IsInterface {
2489 return Kind == Kind.Interface;
2493 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2495 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2499 // Generates xml doc comments (if any), and if required,
2500 // handle warning report.
2502 internal override void GenerateDocComment (DeclSpace ds)
2504 DocUtil.GenerateTypeDocComment (this, ds);
2507 public override string DocCommentHeader {
2508 get { return "T:"; }
2511 public virtual MemberCache BaseCache {
2513 if (base_cache != null)
2515 if (TypeBuilder.BaseType != null)
2516 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2517 if (TypeBuilder.IsInterface)
2518 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2524 public class PartialContainer : TypeContainer {
2526 public readonly Namespace Namespace;
2527 public readonly int OriginalModFlags;
2528 public readonly int AllowedModifiers;
2529 public readonly TypeAttributes DefaultTypeAttributes;
2531 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2532 MemberName member_name, int mod_flags, Kind kind,
2535 PartialContainer pc;
2536 DeclSpace ds = RootContext.Tree.GetDecl (member_name);
2538 pc = ds as PartialContainer;
2541 Report.LocationOfPreviousError (loc);
2542 Report.Error (260, ds.Location,
2543 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
2544 member_name.GetPartialName());
2549 if (pc.Kind != kind) {
2551 261, loc, "Partial declarations of `{0}' " +
2552 "must be all classes, all structs or " +
2553 "all interfaces", member_name.GetPartialName ());
2557 if (pc.OriginalModFlags != mod_flags) {
2559 262, loc, "Partial declarations of `{0}' " +
2560 "have conflicting accessibility modifiers",
2561 member_name.GetPartialName ());
2568 if (parent is ClassPart)
2569 parent = ((ClassPart) parent).PartialContainer;
2571 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2572 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2574 if (kind == Kind.Interface)
2575 parent.AddInterface (pc);
2576 else if (kind == Kind.Class || kind == Kind.Struct)
2577 parent.AddClassOrStruct (pc);
2579 throw new InvalidOperationException ();
2584 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2585 MemberName name, int mod, Attributes attrs,
2586 Kind kind, Location loc)
2588 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2590 // An error occured; create a dummy container, but don't
2592 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2595 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2600 protected PartialContainer (Namespace ns, TypeContainer parent,
2601 MemberName name, int mod, Kind kind, Location l)
2602 : base (null, parent, name, null, kind, l)
2604 this.Namespace = ns;
2608 AllowedModifiers = Class.AllowedModifiers;
2609 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2613 AllowedModifiers = Struct.AllowedModifiers;
2614 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2617 case Kind.Interface:
2618 AllowedModifiers = Interface.AllowedModifiers;
2619 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2623 throw new InvalidOperationException ();
2627 if (parent.Parent == null)
2628 accmods = Modifiers.INTERNAL;
2630 accmods = Modifiers.PRIVATE;
2632 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2633 this.OriginalModFlags = mod;
2636 public override PendingImplementation GetPendingImplementations ()
2638 return PendingImplementation.GetPendingImplementations (this);
2641 protected override TypeAttributes TypeAttr {
2643 return base.TypeAttr | DefaultTypeAttributes;
2648 public class ClassPart : TypeContainer, IMemberContainer {
2649 public readonly PartialContainer PartialContainer;
2650 public readonly bool IsPartial;
2652 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2653 int mod, Attributes attrs, Kind kind, Location l)
2654 : base (ns, parent, pc.MemberName, attrs, kind, l)
2656 this.PartialContainer = pc;
2657 this.IsPartial = true;
2660 if (parent == null || parent == RootContext.Tree.Types)
2661 accmods = Modifiers.INTERNAL;
2663 accmods = Modifiers.PRIVATE;
2665 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2668 public override PendingImplementation GetPendingImplementations ()
2670 return PartialContainer.Pending;
2673 public override bool VerifyImplements (MemberBase mb)
2675 return PartialContainer.VerifyImplements (mb);
2679 public override void RegisterFieldForInitialization (FieldMember field)
2681 PartialContainer.RegisterFieldForInitialization (field);
2684 public override bool EmitFieldInitializers (EmitContext ec)
2686 return PartialContainer.EmitFieldInitializers (ec);
2689 public override Type FindNestedType (string name)
2691 return PartialContainer.FindNestedType (name);
2694 public override MemberCache BaseCache {
2696 return PartialContainer.BaseCache;
2700 public override TypeBuilder DefineType ()
2702 throw new InternalErrorException ("Should not get here");
2707 public abstract class ClassOrStruct : TypeContainer {
2708 bool has_explicit_layout = false;
2709 ListDictionary declarative_security;
2711 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2712 MemberName name, Attributes attrs, Kind kind,
2714 : base (ns, parent, name, attrs, kind, l)
2718 public override PendingImplementation GetPendingImplementations ()
2720 return PendingImplementation.GetPendingImplementations (this);
2723 public override bool HasExplicitLayout {
2725 return has_explicit_layout;
2729 public override void VerifyMembers ()
2731 base.VerifyMembers ();
2733 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2734 foreach (Event e in events){
2735 if ((e.caching_flags & Flags.IsAssigned) == 0)
2736 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2741 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2743 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2744 if (declarative_security == null)
2745 declarative_security = new ListDictionary ();
2747 a.ExtractSecurityPermissionSet (declarative_security);
2751 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2752 has_explicit_layout = true;
2754 base.ApplyAttributeBuilder (a, cb);
2757 public override void Emit()
2761 if (declarative_security != null) {
2762 foreach (DictionaryEntry de in declarative_security) {
2763 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2770 /// Class handles static classes declaration
2772 public sealed class StaticClass: Class {
2773 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2774 Attributes attrs, Location l)
2775 : base (ns, parent, name, mod, attrs, l)
2777 if (RootContext.Version == LanguageVersion.ISO_1) {
2778 Report.FeatureIsNotStandardized (l, "static classes");
2782 protected override int AllowedModifiersProp {
2784 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2785 Modifiers.STATIC | Modifiers.UNSAFE;
2789 protected override void DefineContainerMembers (MemberCoreArrayList list)
2794 foreach (MemberCore m in list) {
2795 if (m is Operator) {
2796 Report.Error (715, m.Location, "`{0}': static classes cannot contain user-defined operators", m.GetSignatureForError ());
2800 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2801 Report.Warning (-628, 4, m.Location, "`{0}': new protected member declared in static class", m.GetSignatureForError ());
2804 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2808 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2811 if (m is Constructor) {
2812 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2816 if (m is Destructor) {
2817 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2821 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2824 base.DefineContainerMembers (list);
2827 public override TypeBuilder DefineType()
2829 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2830 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2834 TypeBuilder tb = base.DefineType ();
2838 if (ptype != TypeManager.object_type) {
2839 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2843 if (ifaces != null) {
2844 foreach (Type t in ifaces)
2845 Report.SymbolRelatedToPreviousError (t);
2846 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2851 protected override TypeAttributes TypeAttr {
2853 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2858 public class Class : ClassOrStruct {
2859 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2860 public const int AllowedModifiers =
2863 Modifiers.PROTECTED |
2864 Modifiers.INTERNAL |
2866 Modifiers.ABSTRACT |
2870 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2871 Attributes attrs, Location l)
2872 : base (ns, parent, name, attrs, Kind.Class, l)
2874 this.ModFlags = mod;
2877 virtual protected int AllowedModifiersProp {
2879 return AllowedModifiers;
2883 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2885 if (a.Type == TypeManager.attribute_usage_type) {
2886 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2887 TypeBuilder.FullName != "System.Attribute") {
2888 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2892 if (a.Type == TypeManager.conditional_attribute_type &&
2893 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
2894 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2898 if (AttributeTester.IsAttributeExcluded (a.Type))
2901 base.ApplyAttributeBuilder (a, cb);
2904 public const TypeAttributes DefaultTypeAttributes =
2905 TypeAttributes.AutoLayout | TypeAttributes.Class;
2907 public override TypeBuilder DefineType()
2909 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2910 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2914 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2915 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2917 return base.DefineType ();
2920 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2921 /// Valid only for attribute classes.
2922 public bool IsExcluded ()
2924 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2925 return (caching_flags & Flags.Excluded) != 0;
2927 caching_flags &= ~Flags.Excluded_Undetected;
2929 if (OptAttributes == null)
2932 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
2937 foreach (Attribute a in attrs) {
2938 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
2939 if (RootContext.AllDefines.Contains (condition))
2943 caching_flags |= Flags.Excluded;
2948 // FIXME: How do we deal with the user specifying a different
2951 protected override TypeAttributes TypeAttr {
2953 return base.TypeAttr | DefaultTypeAttributes;
2958 public class Struct : ClassOrStruct {
2960 // Modifiers allowed in a struct declaration
2962 public const int AllowedModifiers =
2965 Modifiers.PROTECTED |
2966 Modifiers.INTERNAL |
2970 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2971 int mod, Attributes attrs, Location l)
2972 : base (ns, parent, name, attrs, Kind.Struct, l)
2976 if (parent.Parent == null)
2977 accmods = Modifiers.INTERNAL;
2979 accmods = Modifiers.PRIVATE;
2981 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2983 this.ModFlags |= Modifiers.SEALED;
2986 public const TypeAttributes DefaultTypeAttributes =
2987 TypeAttributes.SequentialLayout |
2988 TypeAttributes.Sealed |
2989 TypeAttributes.BeforeFieldInit;
2992 // FIXME: Allow the user to specify a different set of attributes
2993 // in some cases (Sealed for example is mandatory for a class,
2994 // but what SequentialLayout can be changed
2996 protected override TypeAttributes TypeAttr {
2998 return base.TypeAttr | DefaultTypeAttributes;
3006 public class Interface : TypeContainer, IMemberContainer {
3009 /// Modifiers allowed in a class declaration
3011 public const int AllowedModifiers =
3014 Modifiers.PROTECTED |
3015 Modifiers.INTERNAL |
3019 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3020 Attributes attrs, Location l)
3021 : base (ns, parent, name, attrs, Kind.Interface, l)
3025 if (parent.Parent == null)
3026 accmods = Modifiers.INTERNAL;
3028 accmods = Modifiers.PRIVATE;
3030 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3033 public override PendingImplementation GetPendingImplementations ()
3038 public const TypeAttributes DefaultTypeAttributes =
3039 TypeAttributes.AutoLayout |
3040 TypeAttributes.Abstract |
3041 TypeAttributes.Interface;
3043 protected override TypeAttributes TypeAttr {
3045 return base.TypeAttr | DefaultTypeAttributes;
3049 protected override bool VerifyClsCompliance (DeclSpace ds)
3051 if (!base.VerifyClsCompliance (ds))
3054 if (ifaces != null) {
3055 foreach (Type t in ifaces) {
3056 if (AttributeTester.IsClsCompliant (t))
3059 Report.SymbolRelatedToPreviousError (t);
3060 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3061 GetSignatureForError (), TypeManager.CSharpName (t));
3069 public abstract class MethodCore : MemberBase {
3070 public readonly Parameters Parameters;
3071 protected ToplevelBlock block;
3074 // Parameters, cached for semantic analysis.
3076 protected InternalParameters parameter_info;
3077 protected Type [] parameter_types;
3079 // Whether this is an operator method.
3080 public Operator IsOperator;
3083 // The method we're overriding if this is an override method.
3085 protected MethodInfo base_method = null;
3087 static string[] attribute_targets = new string [] { "method", "return" };
3089 public MethodCore (TypeContainer parent, Expression type, int mod,
3090 int allowed_mod, bool is_interface, MemberName name,
3091 Attributes attrs, Parameters parameters, Location loc)
3092 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3095 Parameters = parameters;
3096 IsInterface = is_interface;
3100 // Returns the System.Type array for the parameters of this method
3102 public Type [] ParameterTypes {
3104 return parameter_types;
3108 public InternalParameters ParameterInfo
3111 return parameter_info;
3115 public ToplevelBlock Block {
3125 public void SetYields ()
3127 ModFlags |= Modifiers.METHOD_YIELDS;
3130 protected override bool CheckBase ()
3132 if (!base.CheckBase ())
3135 // Check whether arguments were correct.
3136 if (!DoDefineParameters ())
3139 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3145 // Is null for System.Object while compiling corlib and base interfaces
3146 if (Parent.BaseCache == null) {
3147 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3148 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3153 Type base_ret_type = null;
3154 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3156 // method is override
3157 if (base_method != null) {
3159 if (!CheckMethodAgainstBase ())
3162 if ((ModFlags & Modifiers.NEW) == 0) {
3163 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3164 Report.SymbolRelatedToPreviousError (base_method);
3165 if (this is PropertyBase) {
3166 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3167 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3170 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3171 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3176 if (base_method.IsAbstract && !IsInterface) {
3177 Report.SymbolRelatedToPreviousError (base_method);
3178 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3179 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3184 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3185 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3189 if (RootContext.WarningLevel > 2) {
3190 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3191 Parent.Methods.HasEquals = true;
3192 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3193 Parent.Methods.HasGetHashCode = true;
3196 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3197 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3199 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3200 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3201 Report.SymbolRelatedToPreviousError (base_method);
3202 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3203 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3210 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3211 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3212 if (conflict_symbol != null) {
3213 Report.SymbolRelatedToPreviousError (conflict_symbol);
3214 if (this is PropertyBase)
3215 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3217 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3219 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3223 if (conflict_symbol == null) {
3224 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3225 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3230 if ((ModFlags & Modifiers.NEW) == 0) {
3231 if (this is Method && conflict_symbol is MethodBase)
3234 Report.SymbolRelatedToPreviousError (conflict_symbol);
3235 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3236 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3243 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3244 // that have been defined.
3246 // `name' is the user visible name for reporting errors (this is used to
3247 // provide the right name regarding method names and properties)
3249 bool CheckMethodAgainstBase ()
3253 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3254 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3255 Report.Error (506, Location,
3256 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3257 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3261 // Now we check that the overriden method is not final
3263 if (base_method.IsFinal) {
3264 Report.SymbolRelatedToPreviousError (base_method);
3265 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3266 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3270 // Check that the permissions are not being changed
3272 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3273 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3275 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3276 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3281 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3282 ModFlags |= Modifiers.NEW;
3283 Report.SymbolRelatedToPreviousError (base_method);
3284 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3285 if (RootContext.WarningLevel >= 2)
3286 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 (), TypeManager.CSharpSignature (base_method));
3288 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3289 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3296 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3298 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3300 // when overriding protected internal, the method can be declared
3301 // protected internal only within the same assembly
3304 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3305 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3307 // assemblies differ - report an error
3311 } else if (thisp != base_classp) {
3313 // same assembly, but other attributes differ - report an error
3318 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3320 // if it's not "protected internal", it must be "protected"
3324 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3326 // protected within the same assembly - an error
3329 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3330 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3332 // protected ok, but other attributes differ - report an error
3338 return (thisp == base_classp);
3342 public bool CheckAbstractAndExtern (bool has_block)
3344 if (Parent.Kind == Kind.Interface)
3348 if ((ModFlags & Modifiers.EXTERN) != 0) {
3349 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3350 GetSignatureForError ());
3354 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3355 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3356 GetSignatureForError ());
3360 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3361 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3362 GetSignatureForError ());
3370 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3372 Report.SymbolRelatedToPreviousError (base_method);
3373 string base_name = TypeManager.GetFullNameSignature (base_method);
3374 string this_name = GetSignatureForError ();
3375 if (suffix != null) {
3376 base_name += suffix;
3377 this_name += suffix;
3380 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3381 this_name, Modifiers.GetDescription (ma), base_name);
3384 protected static string Error722 {
3386 return "`{0}': static types cannot be used as return types";
3391 /// For custom member duplication search in a container
3393 protected abstract bool CheckForDuplications ();
3396 /// Gets base method and its return type
3398 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3400 protected virtual bool DoDefineParameters ()
3402 EmitContext ec = Parent.EmitContext;
3404 throw new InternalErrorException ("DoDefineParameters invoked too early");
3406 bool old_unsafe = ec.InUnsafe;
3407 ec.InUnsafe = InUnsafe;
3408 // Check if arguments were correct
3409 parameter_types = Parameters.GetParameterInfo (ec);
3410 ec.InUnsafe = old_unsafe;
3412 if ((parameter_types == null) ||
3413 !CheckParameters (Parent, parameter_types))
3416 parameter_info = new InternalParameters (parameter_types, Parameters);
3418 Parameter array_param = Parameters.ArrayParameter;
3419 if ((array_param != null) &&
3420 (!array_param.ParameterType.IsArray ||
3421 (array_param.ParameterType.GetArrayRank () != 1))) {
3422 Report.Error (225, Location, "The params parameter must be a single dimensional array");
3429 public override string[] ValidAttributeTargets {
3431 return attribute_targets;
3435 protected override bool VerifyClsCompliance (DeclSpace ds)
3437 if (!base.VerifyClsCompliance (ds)) {
3438 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3439 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3444 if (Parameters.HasArglist) {
3445 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3448 if (!AttributeTester.IsClsCompliant (MemberType)) {
3449 if (this is PropertyBase)
3450 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3451 GetSignatureForError ());
3453 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3454 GetSignatureForError ());
3457 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3462 protected bool IsDuplicateImplementation (MethodCore method)
3464 if (method == this || !(method.MemberName.Equals (MemberName)))
3467 Type[] param_types = method.ParameterTypes;
3468 if (param_types == null && ParameterTypes == null)
3470 if (param_types == null || ParameterTypes == null)
3473 if (param_types.Length != ParameterTypes.Length)
3476 for (int i = 0; i < param_types.Length; i++)
3477 if (param_types [i] != ParameterTypes [i])
3480 // TODO: make operator compatible with MethodCore to avoid this
3481 if (this is Operator && method is Operator) {
3482 if (MemberType != method.MemberType)
3487 // Try to report 663: method only differs on out/ref
3489 ParameterData info = ParameterInfo;
3490 ParameterData other_info = method.ParameterInfo;
3491 for (int i = 0; i < info.Count; i++){
3492 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3493 Report.SymbolRelatedToPreviousError (method);
3494 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3495 GetSignatureForError ());
3500 Report.SymbolRelatedToPreviousError (method);
3501 if (this is Operator && method is Operator)
3502 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3504 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3508 public override bool IsUsed {
3509 get { return IsExplicitImpl || base.IsUsed; }
3513 // Returns a string that represents the signature for this
3514 // member which should be used in XML documentation.
3516 public override string GetDocCommentName (DeclSpace ds)
3518 return DocUtil.GetMethodDocCommentName (this, ds);
3522 // Raised (and passed an XmlElement that contains the comment)
3523 // when GenerateDocComment is writing documentation expectedly.
3525 // FIXME: with a few effort, it could be done with XmlReader,
3526 // that means removal of DOM use.
3528 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3530 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3534 // Represents header string for documentation comment.
3536 public override string DocCommentHeader {
3537 get { return "M:"; }
3540 protected override void VerifyObsoleteAttribute()
3542 base.VerifyObsoleteAttribute ();
3544 if (parameter_types == null)
3547 foreach (Type type in parameter_types) {
3548 CheckUsageOfObsoleteAttribute (type);
3553 public class SourceMethod : ISourceMethod
3555 TypeContainer container;
3558 protected SourceMethod (TypeContainer container, MethodBase builder,
3559 ISourceFile file, Location start, Location end)
3561 this.container = container;
3562 this.builder = builder;
3564 CodeGen.SymbolWriter.OpenMethod (
3565 file, this, start.Row, 0, end.Row, 0);
3568 public string Name {
3569 get { return builder.Name; }
3572 public int NamespaceID {
3573 get { return container.NamespaceEntry.SymbolFileID; }
3578 if (builder is MethodBuilder)
3579 return ((MethodBuilder) builder).GetToken ().Token;
3580 else if (builder is ConstructorBuilder)
3581 return ((ConstructorBuilder) builder).GetToken ().Token;
3583 throw new NotSupportedException ();
3587 public void CloseMethod ()
3589 if (CodeGen.SymbolWriter != null)
3590 CodeGen.SymbolWriter.CloseMethod ();
3593 public static SourceMethod Create (TypeContainer parent,
3594 MethodBase builder, Block block)
3596 if (CodeGen.SymbolWriter == null)
3601 Location start_loc = block.StartLocation;
3602 if (Location.IsNull (start_loc))
3605 Location end_loc = block.EndLocation;
3606 if (Location.IsNull (end_loc))
3609 ISourceFile file = start_loc.SourceFile;
3613 return new SourceMethod (
3614 parent, builder, file, start_loc, end_loc);
3618 public class Method : MethodCore, IIteratorContainer, IMethodData {
3619 public MethodBuilder MethodBuilder;
3620 public MethodData MethodData;
3621 ReturnParameter return_attributes;
3622 ListDictionary declarative_security;
3625 /// Modifiers allowed in a class declaration
3627 const int AllowedModifiers =
3630 Modifiers.PROTECTED |
3631 Modifiers.INTERNAL |
3636 Modifiers.OVERRIDE |
3637 Modifiers.ABSTRACT |
3639 Modifiers.METHOD_YIELDS |
3642 const int AllowedInterfaceModifiers =
3643 Modifiers.NEW | Modifiers.UNSAFE;
3646 // return_type can be "null" for VOID values.
3648 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3649 MemberName name, Parameters parameters, Attributes attrs,
3651 : base (ds, return_type, mod,
3652 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3653 is_iface, name, attrs, parameters, l)
3657 public override AttributeTargets AttributeTargets {
3659 return AttributeTargets.Method;
3663 public override string GetSignatureForError()
3665 if (IsOperator != null)
3666 return IsOperator.GetSignatureForError ();
3668 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3671 void DuplicateEntryPoint (MethodInfo b, Location location)
3675 "Program `" + CodeGen.FileName +
3676 "' has more than one entry point defined: `" +
3677 TypeManager.CSharpSignature(b) + "'");
3680 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3682 if (b.ReturnType != TypeManager.void_type &&
3683 b.ReturnType != TypeManager.int32_type)
3686 if (pinfo.Count == 0)
3689 if (pinfo.Count > 1)
3692 Type t = pinfo.ParameterType(0);
3694 (t.GetArrayRank() == 1) &&
3695 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3696 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3702 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3704 if (a.Target == AttributeTargets.ReturnValue) {
3705 if (return_attributes == null)
3706 return_attributes = new ReturnParameter (MethodBuilder, Location);
3708 return_attributes.ApplyAttributeBuilder (a, cb);
3712 if (a.Type == TypeManager.methodimpl_attr_type &&
3713 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3714 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3717 if (a.Type == TypeManager.dllimport_type) {
3718 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3719 if ((ModFlags & extern_static) != extern_static) {
3720 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3726 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3727 if (declarative_security == null)
3728 declarative_security = new ListDictionary ();
3729 a.ExtractSecurityPermissionSet (declarative_security);
3733 if (a.Type == TypeManager.conditional_attribute_type) {
3734 if (IsOperator != null || IsExplicitImpl) {
3735 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3736 GetSignatureForError ());
3740 if (ReturnType != TypeManager.void_type) {
3741 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
3745 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3746 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
3751 Report.Error (582, Location, "Conditional not valid on interface members");
3755 if (MethodData.implementing != null) {
3756 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
3757 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
3761 for (int i = 0; i < parameter_info.Count; ++i) {
3762 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3763 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
3769 MethodBuilder.SetCustomAttribute (cb);
3772 protected override bool CheckForDuplications ()
3774 ArrayList ar = Parent.Methods;
3776 int arLen = ar.Count;
3778 for (int i = 0; i < arLen; i++) {
3779 Method m = (Method) ar [i];
3780 if (IsDuplicateImplementation (m))
3785 ar = Parent.Properties;
3787 for (int i = 0; i < ar.Count; ++i) {
3788 PropertyBase pb = (PropertyBase) ar [i];
3789 if (pb.AreAccessorsDuplicateImplementation (this))
3794 ar = Parent.Indexers;
3796 for (int i = 0; i < ar.Count; ++i) {
3797 PropertyBase pb = (PropertyBase) ar [i];
3798 if (pb.AreAccessorsDuplicateImplementation (this))
3805 for (int i = 0; i < ar.Count; ++i) {
3806 Event ev = (Event) ar [i];
3807 if (ev.AreAccessorsDuplicateImplementation (this))
3818 public override bool Define ()
3823 if (!CheckAbstractAndExtern (block != null))
3826 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3827 Error1599 (Location, ReturnType);
3834 if (IsOperator != null)
3835 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3837 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3839 if (!MethodData.Define (Parent))
3842 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3843 Name == "Finalize" && !(this is Destructor)) {
3844 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3848 // Setup iterator if we are one
3850 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3851 Iterator iterator = new Iterator (this,
3853 ParameterInfo, ModFlags);
3855 if (!iterator.DefineIterator ())
3859 MethodBuilder = MethodData.MethodBuilder;
3862 // This is used to track the Entry Point,
3864 if (Name == "Main" &&
3865 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3866 (RootContext.MainClass == null ||
3867 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3868 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3869 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3870 md.SetMemberIsUsed ();
3872 if (RootContext.EntryPoint == null) {
3873 RootContext.EntryPoint = MethodBuilder;
3874 RootContext.EntryPointLocation = Location;
3876 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3877 DuplicateEntryPoint (MethodBuilder, Location);
3880 if (RootContext.WarningLevel >= 4)
3881 Report.Warning (28, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3885 if (MemberType.IsAbstract && MemberType.IsSealed) {
3886 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3896 public override void Emit ()
3898 MethodData.Emit (Parent, this);
3901 if (declarative_security != null) {
3902 foreach (DictionaryEntry de in declarative_security) {
3903 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3911 public static void Error1599 (Location loc, Type t)
3913 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
3916 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3918 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3919 container.TypeBuilder, Name, ParameterTypes, false);
3924 base_ret_type = mi.ReturnType;
3928 public override bool MarkForDuplicationCheck ()
3930 caching_flags |= Flags.TestMethodDuplication;
3934 protected override bool VerifyClsCompliance(DeclSpace ds)
3936 if (!base.VerifyClsCompliance (ds))
3939 if (parameter_types.Length > 0) {
3940 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3942 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3948 #region IMethodData Members
3950 public CallingConventions CallingConventions {
3952 CallingConventions cc = Parameters.GetCallingConvention ();
3953 if (Parameters.HasArglist)
3954 block.HasVarargs = true;
3957 if ((ModFlags & Modifiers.STATIC) == 0)
3958 cc |= CallingConventions.HasThis;
3960 // FIXME: How is `ExplicitThis' used in C#?
3966 public Type ReturnType {
3972 public MemberName MethodName {
3978 public new Location Location {
3980 return base.Location;
3984 protected override bool CheckBase() {
3985 if (!base.CheckBase ())
3988 // TODO: Destructor should derive from MethodCore
3989 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3990 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3991 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3998 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4000 EmitContext ec = new EmitContext (
4001 tc, Parent, Location, ig, ReturnType, ModFlags, false);
4003 ec.CurrentIterator = tc as Iterator;
4004 if (ec.CurrentIterator != null)
4005 ec.CurrentAnonymousMethod = ec.CurrentIterator.Host;
4010 public ObsoleteAttribute GetObsoleteAttribute ()
4012 return GetObsoleteAttribute (Parent);
4016 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4018 public bool IsExcluded (EmitContext ec)
4020 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4021 return (caching_flags & Flags.Excluded) != 0;
4023 caching_flags &= ~Flags.Excluded_Undetected;
4025 if (base_method == null) {
4026 if (OptAttributes == null)
4029 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4034 foreach (Attribute a in attrs) {
4035 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4036 if (RootContext.AllDefines.Contains (condition))
4040 caching_flags |= Flags.Excluded;
4044 IMethodData md = TypeManager.GetMethod (base_method);
4046 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4047 caching_flags |= Flags.Excluded;
4053 if (md.IsExcluded (ec)) {
4054 caching_flags |= Flags.Excluded;
4063 public abstract class ConstructorInitializer {
4064 ArrayList argument_list;
4065 protected ConstructorInfo base_constructor;
4066 Parameters parameters;
4069 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4072 this.argument_list = argument_list;
4073 this.parameters = parameters;
4077 public ArrayList Arguments {
4079 return argument_list;
4083 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4085 Expression base_constructor_group;
4089 ec.CurrentBlock = block;
4091 if (argument_list != null){
4092 foreach (Argument a in argument_list){
4093 if (!a.Resolve (ec, loc))
4097 ec.CurrentBlock = null;
4099 if (this is ConstructorBaseInitializer) {
4100 if (ec.ContainerType.BaseType == null)
4103 t = ec.ContainerType.BaseType;
4104 if (ec.ContainerType.IsValueType) {
4105 Report.Error (522, loc,
4106 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4110 t = ec.ContainerType;
4112 base_constructor_group = Expression.MemberLookup (
4113 ec, t, ".ctor", MemberTypes.Constructor,
4114 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4117 if (base_constructor_group == null){
4119 base_constructor_group = Expression.MemberLookup (
4120 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4121 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4125 int errors = Report.Errors;
4126 if (base_constructor_group != null)
4127 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4128 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4131 if (base_constructor == null) {
4132 if (errors == Report.Errors)
4133 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4134 argument_list.Count);
4139 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4140 base_constructor = null;
4144 if (base_constructor == caller_builder){
4145 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4152 public void Emit (EmitContext ec)
4154 if (base_constructor != null){
4155 ec.Mark (loc, false);
4157 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4159 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4164 public class ConstructorBaseInitializer : ConstructorInitializer {
4165 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4166 base (argument_list, pars, l)
4171 public class ConstructorThisInitializer : ConstructorInitializer {
4172 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4173 base (argument_list, pars, l)
4178 public class Constructor : MethodCore, IMethodData {
4179 public ConstructorBuilder ConstructorBuilder;
4180 public ConstructorInitializer Initializer;
4181 ListDictionary declarative_security;
4184 // Modifiers allowed for a constructor.
4186 public const int AllowedModifiers =
4188 Modifiers.PROTECTED |
4189 Modifiers.INTERNAL |
4195 bool has_compliant_args = false;
4197 // The spec claims that static is not permitted, but
4198 // my very own code has static constructors.
4200 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4201 ConstructorInitializer init, Location l)
4202 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4208 public bool HasCompliantArgs {
4210 return has_compliant_args;
4214 public override AttributeTargets AttributeTargets {
4216 return AttributeTargets.Constructor;
4222 // Returns true if this is a default constructor
4224 public bool IsDefault ()
4226 if ((ModFlags & Modifiers.STATIC) != 0)
4227 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4228 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4231 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4232 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4233 (Initializer is ConstructorBaseInitializer) &&
4234 (Initializer.Arguments == null);
4237 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4239 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4240 if (declarative_security == null) {
4241 declarative_security = new ListDictionary ();
4243 a.ExtractSecurityPermissionSet (declarative_security);
4247 ConstructorBuilder.SetCustomAttribute (cb);
4250 protected override bool CheckForDuplications ()
4252 ArrayList ar = Parent.InstanceConstructors;
4254 int arLen = ar.Count;
4256 for (int i = 0; i < arLen; i++) {
4257 Constructor m = (Constructor) ar [i];
4258 if (IsDuplicateImplementation (m))
4265 protected override bool CheckBase ()
4267 // Check whether arguments were correct.
4268 if (!DoDefineParameters ())
4271 // TODO: skip the rest for generated ctor
4272 if ((ModFlags & Modifiers.STATIC) != 0)
4275 if (!CheckForDuplications ())
4278 if (Parent.Kind == Kind.Struct) {
4279 if (ParameterTypes.Length == 0) {
4280 Report.Error (568, Location,
4281 "Structs cannot contain explicit parameterless constructors");
4285 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4286 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4291 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4292 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4299 // Creates the ConstructorBuilder
4301 public override bool Define ()
4303 if (ConstructorBuilder != null)
4306 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4307 MethodAttributes.SpecialName);
4309 if ((ModFlags & Modifiers.STATIC) != 0) {
4310 ca |= MethodAttributes.Static | MethodAttributes.Private;
4312 ca |= MethodAttributes.HideBySig;
4314 if ((ModFlags & Modifiers.PUBLIC) != 0)
4315 ca |= MethodAttributes.Public;
4316 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4317 if ((ModFlags & Modifiers.INTERNAL) != 0)
4318 ca |= MethodAttributes.FamORAssem;
4320 ca |= MethodAttributes.Family;
4321 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4322 ca |= MethodAttributes.Assembly;
4323 else if (IsDefault ())
4324 ca |= MethodAttributes.Public;
4326 ca |= MethodAttributes.Private;
4329 if (!CheckAbstractAndExtern (block != null))
4332 // Check if arguments were correct.
4336 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4337 ca, CallingConventions,
4340 if ((ModFlags & Modifiers.UNSAFE) != 0)
4341 ConstructorBuilder.InitLocals = false;
4343 TypeManager.AddMethod (ConstructorBuilder, this);
4346 // HACK because System.Reflection.Emit is lame
4348 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4356 public override void Emit ()
4358 EmitContext ec = CreateEmitContext (null, null);
4360 // If this is a non-static `struct' constructor and doesn't have any
4361 // initializer, it must initialize all of the struct's fields.
4362 if ((Parent.Kind == Kind.Struct) &&
4363 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4364 Block.AddThisVariable (Parent, Location);
4367 block.ResolveMeta (ec, ParameterInfo);
4369 if ((ModFlags & Modifiers.STATIC) == 0){
4370 if (Parent.Kind == Kind.Class && Initializer == null)
4371 Initializer = new ConstructorBaseInitializer (
4372 null, Parameters.EmptyReadOnlyParameters, Location);
4376 // Spec mandates that Initializers will not have
4380 if ((Initializer != null) &&
4381 !Initializer.Resolve (ConstructorBuilder, block, ec))
4383 ec.IsStatic = false;
4386 Parameters.LabelParameters (ec, ConstructorBuilder);
4388 SourceMethod source = SourceMethod.Create (
4389 Parent, ConstructorBuilder, block);
4392 // Classes can have base initializers and instance field initializers.
4394 if (Parent.Kind == Kind.Class){
4395 if ((ModFlags & Modifiers.STATIC) == 0){
4398 // If we use a "this (...)" constructor initializer, then
4399 // do not emit field initializers, they are initialized in the other constructor
4401 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4402 Parent.EmitFieldInitializers (ec);
4405 if (Initializer != null) {
4406 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4407 ec.TestObsoleteMethodUsage = false;
4409 Initializer.Emit (ec);
4412 if ((ModFlags & Modifiers.STATIC) != 0)
4413 Parent.EmitFieldInitializers (ec);
4415 if (OptAttributes != null)
4416 OptAttributes.Emit (ec, this);
4418 ec.EmitTopBlock (this, block, ParameterInfo);
4421 source.CloseMethod ();
4425 if (declarative_security != null) {
4426 foreach (DictionaryEntry de in declarative_security) {
4427 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4434 // Is never override
4435 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4440 public override string GetSignatureForError()
4442 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4445 protected override bool VerifyClsCompliance (DeclSpace ds)
4447 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4451 if (parameter_types.Length > 0) {
4452 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4454 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4456 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4457 foreach (Type param in parameter_types) {
4458 if (param.IsArray) {
4464 has_compliant_args = true;
4468 #region IMethodData Members
4470 public System.Reflection.CallingConventions CallingConventions {
4472 CallingConventions cc = Parameters.GetCallingConvention ();
4474 if (Parent.Kind == Kind.Class)
4475 if ((ModFlags & Modifiers.STATIC) == 0)
4476 cc |= CallingConventions.HasThis;
4478 // FIXME: How is `ExplicitThis' used in C#?
4484 public new Location Location {
4486 return base.Location;
4490 public MemberName MethodName {
4496 public Type ReturnType {
4502 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4504 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4505 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4508 public ObsoleteAttribute GetObsoleteAttribute ()
4510 return GetObsoleteAttribute (Parent);
4513 public bool IsExcluded(EmitContext ec)
4522 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4524 public interface IMethodData
4526 CallingConventions CallingConventions { get; }
4527 Location Location { get; }
4528 MemberName MethodName { get; }
4529 Type[] ParameterTypes { get; }
4530 Type ReturnType { get; }
4532 Attributes OptAttributes { get; }
4533 ToplevelBlock Block { get; set; }
4535 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4536 ObsoleteAttribute GetObsoleteAttribute ();
4537 string GetSignatureForError ();
4538 bool IsExcluded (EmitContext ec);
4539 bool IsClsCompliaceRequired (DeclSpace ds);
4540 void SetMemberIsUsed ();
4544 // Encapsulates most of the Method's state
4546 public class MethodData {
4548 readonly IMethodData method;
4551 // The return type of this method
4553 public readonly InternalParameters ParameterInfo;
4556 // Are we implementing an interface ?
4558 public MethodInfo implementing;
4563 protected MemberBase member;
4564 protected int modifiers;
4565 protected MethodAttributes flags;
4567 MethodBuilder builder = null;
4568 public MethodBuilder MethodBuilder {
4574 public MethodData (MemberBase member, InternalParameters parameters,
4575 int modifiers, MethodAttributes flags, IMethodData method)
4577 this.member = member;
4578 this.ParameterInfo = parameters;
4579 this.modifiers = modifiers;
4582 this.method = method;
4585 public bool Define (TypeContainer container)
4587 string name = method.MethodName.Name;
4588 string method_name = name;
4590 Type[] ParameterTypes = method.ParameterTypes;
4592 if (container.Pending != null){
4593 if (member is Indexer) // TODO: test it, but it should work without this IF
4594 implementing = container.Pending.IsInterfaceIndexer (
4595 member.InterfaceType, method.ReturnType, ParameterInfo);
4597 implementing = container.Pending.IsInterfaceMethod (
4598 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4600 if (member.InterfaceType != null){
4601 if (implementing == null){
4602 if (member is PropertyBase) {
4603 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4604 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4605 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4608 Report.Error (539, method.Location,
4609 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4610 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4614 if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
4615 Report.SymbolRelatedToPreviousError (implementing);
4616 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4617 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4620 method_name = member.InterfaceType.FullName + "." + name;
4622 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
4623 Report.SymbolRelatedToPreviousError (implementing);
4624 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4625 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4632 // For implicit implementations, make sure we are public, for
4633 // explicit implementations, make sure we are private.
4635 if (implementing != null){
4637 // Setting null inside this block will trigger a more
4638 // verbose error reporting for missing interface implementations
4640 // The "candidate" function has been flagged already
4641 // but it wont get cleared
4643 if (member.IsExplicitImpl){
4644 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4645 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4646 implementing = null;
4648 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4649 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4651 // If this is an interface method implementation,
4652 // check for public accessibility
4654 implementing = null;
4655 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4656 // We may never be private.
4657 implementing = null;
4658 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4660 // We may be protected if we're overriding something.
4662 implementing = null;
4667 // Static is not allowed
4669 if ((modifiers & Modifiers.STATIC) != 0){
4670 implementing = null;
4671 Modifiers.Error_InvalidModifier (method.Location, "static");
4676 // If implementing is still valid, set flags
4678 if (implementing != null){
4680 // When implementing interface methods, set NewSlot
4681 // unless, we are overwriting a method.
4683 if (implementing.DeclaringType.IsInterface){
4684 if ((modifiers & Modifiers.OVERRIDE) == 0)
4685 flags |= MethodAttributes.NewSlot;
4688 MethodAttributes.Virtual |
4689 MethodAttributes.HideBySig;
4691 // Set Final unless we're virtual, abstract or already overriding a method.
4692 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4693 flags |= MethodAttributes.Final;
4696 EmitContext ec = method.CreateEmitContext (container, null);
4698 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4700 if (builder == null)
4703 if ((modifiers & Modifiers.UNSAFE) != 0)
4704 builder.InitLocals = false;
4706 if (implementing != null){
4708 // clear the pending implemntation flag
4710 if (member is Indexer) {
4711 container.Pending.ImplementIndexer (
4712 member.InterfaceType, builder, method.ReturnType,
4713 ParameterInfo, member.IsExplicitImpl);
4715 container.Pending.ImplementMethod (
4716 member.InterfaceType, name, method.ReturnType,
4717 ParameterInfo, member.IsExplicitImpl);
4719 if (member.IsExplicitImpl)
4720 container.TypeBuilder.DefineMethodOverride (
4721 builder, implementing);
4725 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4726 TypeManager.AddMethod (builder, method);
4733 /// Create the MethodBuilder for the method
4735 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4737 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4739 if ((modifiers & extern_static) == extern_static) {
4741 if (method.OptAttributes != null) {
4742 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4743 if (dllimport_attribute != null) {
4744 flags |= MethodAttributes.PinvokeImpl;
4745 builder = dllimport_attribute.DefinePInvokeMethod (
4746 ec, container.TypeBuilder, method_name, flags,
4747 method.ReturnType, ParameterTypes);
4753 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4754 // We are more strict than Microsoft and report CS0626 like error
4755 if (method.OptAttributes == null ||
4756 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4757 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",
4758 method.GetSignatureForError ());
4763 builder = container.TypeBuilder.DefineMethod (
4764 method_name, flags, method.CallingConventions,
4765 method.ReturnType, ParameterTypes);
4771 public void Emit (TypeContainer container, Attributable kind)
4774 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4775 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4777 ec = method.CreateEmitContext (container, null);
4779 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
4780 ec.TestObsoleteMethodUsage = false;
4782 Attributes OptAttributes = method.OptAttributes;
4784 if (OptAttributes != null)
4785 OptAttributes.Emit (ec, kind);
4787 if (member is MethodCore)
4788 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
4790 ToplevelBlock block = method.Block;
4792 SourceMethod source = SourceMethod.Create (
4793 container, MethodBuilder, method.Block);
4796 // Handle destructors specially
4798 // FIXME: This code generates buggy code
4800 if (member is Destructor)
4801 EmitDestructor (ec, block);
4803 ec.EmitTopBlock (method, block, ParameterInfo);
4806 source.CloseMethod ();
4809 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4811 ILGenerator ig = ec.ig;
4813 Label finish = ig.DefineLabel ();
4815 block.SetDestructor ();
4817 ig.BeginExceptionBlock ();
4818 ec.ReturnLabel = finish;
4819 ec.HasReturnLabel = true;
4820 ec.EmitTopBlock (method, block, null);
4822 // ig.MarkLabel (finish);
4823 ig.BeginFinallyBlock ();
4825 if (ec.ContainerType.BaseType != null) {
4826 Expression member_lookup = Expression.MemberLookup (
4827 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4828 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4830 if (member_lookup != null){
4831 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4833 ig.Emit (OpCodes.Ldarg_0);
4834 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4838 ig.EndExceptionBlock ();
4839 //ig.MarkLabel (ec.ReturnLabel);
4840 ig.Emit (OpCodes.Ret);
4844 // TODO: Should derive from MethodCore
4845 public class Destructor : Method {
4847 public Destructor (TypeContainer ds, Expression return_type, int mod,
4848 string name, Parameters parameters, Attributes attrs,
4850 : base (ds, return_type, mod, false, new MemberName (name),
4851 parameters, attrs, l)
4854 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4856 if (a.Type == TypeManager.conditional_attribute_type) {
4857 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4858 GetSignatureForError ());
4862 base.ApplyAttributeBuilder (a, cb);
4865 public override string GetSignatureForError ()
4867 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
4872 abstract public class MemberBase : MemberCore {
4873 public Expression Type;
4875 public MethodAttributes flags;
4877 protected readonly int explicit_mod_flags;
4880 // The "short" name of this property / indexer / event. This is the
4881 // name without the explicit interface.
4883 public string ShortName {
4884 get { return MemberName.Name; }
4886 SetMemberName (new MemberName (MemberName.Left, value));
4891 // The type of this property / indexer / event
4894 public Type MemberType {
4896 if (member_type == null && Type != null) {
4897 EmitContext ec = Parent.EmitContext;
4898 bool old_unsafe = ec.InUnsafe;
4899 ec.InUnsafe = InUnsafe;
4900 Type = Type.ResolveAsTypeTerminal (ec, false);
4901 ec.InUnsafe = old_unsafe;
4903 member_type = Type == null ? null : Type.Type;
4910 // Whether this is an interface member.
4912 public bool IsInterface;
4915 // If true, this is an explicit interface implementation
4917 public bool IsExplicitImpl;
4920 // The interface type we are explicitly implementing
4922 public Type InterfaceType = null;
4925 // The constructor is only exposed to our children
4927 protected MemberBase (TypeContainer parent, Expression type, int mod,
4928 int allowed_mod, int def_mod, MemberName name,
4929 Attributes attrs, Location loc)
4930 : base (parent, name, attrs, loc)
4932 explicit_mod_flags = mod;
4934 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4935 IsExplicitImpl = (MemberName.Left != null);
4938 protected virtual bool CheckBase ()
4940 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4941 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4945 if ((RootContext.WarningLevel >= 4) &&
4946 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4947 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4948 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4949 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4954 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4958 foreach (Type partype in parameters){
4959 if (partype == TypeManager.void_type) {
4961 1547, Location, "Keyword 'void' cannot " +
4962 "be used in this context");
4966 if (partype.IsPointer){
4969 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4973 if (ds.AsAccessible (partype, ModFlags))
4976 if (this is Indexer)
4977 Report.Error (55, Location,
4978 "Inconsistent accessibility: parameter type `" +
4979 TypeManager.CSharpName (partype) + "' is less " +
4980 "accessible than indexer `" + GetSignatureForError () + "'");
4981 else if ((this is Method) && ((Method) this).IsOperator != null)
4982 Report.Error (57, Location,
4983 "Inconsistent accessibility: parameter type `" +
4984 TypeManager.CSharpName (partype) + "' is less " +
4985 "accessible than operator `" + GetSignatureForError () + "'");
4987 Report.Error (51, Location,
4988 "Inconsistent accessibility: parameter type `" +
4989 TypeManager.CSharpName (partype) + "' is less " +
4990 "accessible than method `" + GetSignatureForError () + "'");
4997 protected virtual bool DoDefine ()
4999 EmitContext ec = Parent.EmitContext;
5001 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5004 throw new InternalErrorException ();
5007 ModFlags = Modifiers.PUBLIC |
5008 Modifiers.ABSTRACT |
5009 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5011 flags = MethodAttributes.Public |
5012 MethodAttributes.Abstract |
5013 MethodAttributes.HideBySig |
5014 MethodAttributes.NewSlot |
5015 MethodAttributes.Virtual;
5017 if (!Parent.MethodModifiersValid (this))
5020 flags = Modifiers.MethodAttr (ModFlags);
5023 if (MemberType == null)
5026 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5027 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5028 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5029 GetSignatureForError (), Parent.GetSignatureForError ());
5033 // verify accessibility
5034 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5035 Report.SymbolRelatedToPreviousError (MemberType);
5036 if (this is Property)
5037 Report.Error (53, Location,
5038 "Inconsistent accessibility: property type `" +
5039 TypeManager.CSharpName (MemberType) + "' is less " +
5040 "accessible than property `" + GetSignatureForError () + "'");
5041 else if (this is Indexer)
5042 Report.Error (54, Location,
5043 "Inconsistent accessibility: indexer return type `" +
5044 TypeManager.CSharpName (MemberType) + "' is less " +
5045 "accessible than indexer `" + GetSignatureForError () + "'");
5046 else if (this is MethodCore) {
5047 if (this is Operator)
5048 Report.Error (56, Location,
5049 "Inconsistent accessibility: return type `" +
5050 TypeManager.CSharpName (MemberType) + "' is less " +
5051 "accessible than operator `" + GetSignatureForError () + "'");
5053 Report.Error (50, Location,
5054 "Inconsistent accessibility: return type `" +
5055 TypeManager.CSharpName (MemberType) + "' is less " +
5056 "accessible than method `" + GetSignatureForError () + "'");
5058 Report.Error (52, Location,
5059 "Inconsistent accessibility: field type `" +
5060 TypeManager.CSharpName (MemberType) + "' is less " +
5061 "accessible than field `" + GetSignatureForError () + "'");
5066 if (MemberType.IsPointer && !UnsafeOK (Parent))
5069 if (IsExplicitImpl) {
5070 Expression expr = MemberName.Left.GetTypeExpression (Location);
5071 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5075 InterfaceType = texpr.ResolveType (ec);
5077 if (!InterfaceType.IsInterface) {
5078 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5082 if (!Parent.VerifyImplements (this))
5085 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5091 protected bool IsTypePermitted ()
5093 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5094 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5100 protected override bool VerifyClsCompliance(DeclSpace ds)
5102 if (base.VerifyClsCompliance (ds)) {
5106 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5107 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5112 protected override void VerifyObsoleteAttribute()
5114 CheckUsageOfObsoleteAttribute (MemberType);
5119 // Fields and Events both generate FieldBuilders, we use this to share
5120 // their common bits. This is also used to flag usage of the field
5122 abstract public class FieldBase : MemberBase {
5123 public FieldBuilder FieldBuilder;
5124 public Status status;
5127 public enum Status : byte {
5128 HAS_OFFSET = 4 // Used by FieldMember.
5131 static string[] attribute_targets = new string [] { "field" };
5134 /// Symbol with same name in base class/struct
5136 public MemberInfo conflict_symbol;
5139 // The constructor is only exposed to our children
5141 protected FieldBase (TypeContainer parent, Expression type, int mod,
5142 int allowed_mod, MemberName name, object init,
5143 Attributes attrs, Location loc)
5144 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5150 public override AttributeTargets AttributeTargets {
5152 return AttributeTargets.Field;
5156 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5158 if (a.Type == TypeManager.marshal_as_attr_type) {
5159 UnmanagedMarshal marshal = a.GetMarshal (this);
5160 if (marshal != null) {
5161 FieldBuilder.SetMarshal (marshal);
5166 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5167 a.Error_InvalidSecurityParent ();
5171 FieldBuilder.SetCustomAttribute (cb);
5175 // Whether this field has an initializer.
5177 public bool HasInitializer {
5179 return init != null;
5183 protected readonly Object init;
5186 Expression init_expr;
5187 bool init_expr_initialized = false;
5190 // Resolves and returns the field initializer.
5192 public Expression GetInitializerExpression (EmitContext ec)
5194 if (init_expr_initialized)
5198 if (init is Expression)
5199 e = (Expression) init;
5201 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5203 // TODO: Any reason why we are using parent EC ?
5204 EmitContext parent_ec = Parent.EmitContext;
5206 bool old_is_static = parent_ec.IsStatic;
5207 bool old_is_ctor = parent_ec.IsConstructor;
5208 parent_ec.IsStatic = ec.IsStatic;
5209 parent_ec.IsConstructor = ec.IsConstructor;
5210 parent_ec.IsFieldInitializer = true;
5211 e = e.DoResolve (parent_ec);
5212 parent_ec.IsFieldInitializer = false;
5213 parent_ec.IsStatic = old_is_static;
5214 parent_ec.IsConstructor = old_is_ctor;
5217 init_expr_initialized = true;
5222 protected override bool CheckBase ()
5224 if (!base.CheckBase ())
5231 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5232 if (conflict_symbol == null) {
5233 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5234 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5239 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5240 Report.SymbolRelatedToPreviousError (conflict_symbol);
5241 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5242 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5248 protected virtual bool IsFieldClsCompliant {
5250 if (FieldBuilder == null)
5253 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5257 public override string[] ValidAttributeTargets {
5259 return attribute_targets;
5263 protected override bool VerifyClsCompliance (DeclSpace ds)
5265 if (!base.VerifyClsCompliance (ds))
5268 if (!IsFieldClsCompliant) {
5269 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5275 public void SetAssigned ()
5277 caching_flags |= Flags.IsAssigned;
5281 public abstract class FieldMember: FieldBase
5283 protected FieldMember (TypeContainer parent, Expression type, int mod,
5284 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5285 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5287 if ((mod & Modifiers.ABSTRACT) != 0)
5288 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5291 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5293 if (a.Type == TypeManager.field_offset_attribute_type)
5295 status |= Status.HAS_OFFSET;
5297 if (!Parent.HasExplicitLayout) {
5298 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5302 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5303 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5309 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5310 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5315 base.ApplyAttributeBuilder (a, cb);
5319 public override bool Define()
5321 EmitContext ec = Parent.EmitContext;
5323 throw new InternalErrorException ("FieldMember.Define called too early");
5325 if (MemberType == null)
5328 if (MemberType == TypeManager.void_type) {
5329 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5336 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5337 Report.Error (52, Location,
5338 "Inconsistent accessibility: field type `" +
5339 TypeManager.CSharpName (MemberType) + "' is less " +
5340 "accessible than field `" + GetSignatureForError () + "'");
5344 if (!IsTypePermitted ())
5347 if (MemberType.IsPointer && !UnsafeOK (Parent))
5353 public override void Emit ()
5355 if (OptAttributes != null) {
5356 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5357 OptAttributes.Emit (ec, this);
5360 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5361 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5368 // Represents header string for documentation comment.
5370 public override string DocCommentHeader {
5371 get { return "F:"; }
5375 interface IFixedBuffer
5377 FieldInfo Element { get; }
5378 Type ElementType { get; }
5381 public class FixedFieldExternal: IFixedBuffer
5383 FieldInfo element_field;
5385 public FixedFieldExternal (FieldInfo fi)
5387 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5390 #region IFixedField Members
5392 public FieldInfo Element {
5394 return element_field;
5398 public Type ElementType {
5400 return element_field.FieldType;
5408 /// Fixed buffer implementation
5410 public class FixedField: FieldMember, IFixedBuffer
5412 public const string FixedElementName = "FixedElementField";
5413 static int GlobalCounter = 0;
5414 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5415 static FieldInfo[] fi;
5417 TypeBuilder fixed_buffer_type;
5418 FieldBuilder element;
5419 Expression size_expr;
5422 const int AllowedModifiers =
5425 Modifiers.PROTECTED |
5426 Modifiers.INTERNAL |
5429 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5430 Expression size_expr, Attributes attrs, Location loc):
5431 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5433 if (RootContext.Version == LanguageVersion.ISO_1)
5434 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5436 this.size_expr = size_expr;
5439 public override bool Define()
5442 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5443 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5446 if (Parent.Kind != Kind.Struct) {
5447 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5448 GetSignatureForError ());
5452 if (!base.Define ())
5455 if (!TypeManager.IsPrimitiveType (MemberType)) {
5456 Report.Error (1663, Location, "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
5457 GetSignatureForError ());
5461 Expression e = size_expr.Resolve (Parent.EmitContext);
5465 Constant c = e as Constant;
5467 Const.Error_ExpressionMustBeConstant (e.Location, GetSignatureForError ());
5471 IntConstant buffer_size_const = c.ToInt (Location);
5472 if (buffer_size_const == null)
5475 buffer_size = buffer_size_const.Value;
5477 if (buffer_size <= 0) {
5478 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5482 int type_size = Expression.GetTypeSize (MemberType);
5484 if (buffer_size > int.MaxValue / type_size) {
5485 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5486 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5490 buffer_size *= type_size;
5493 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5495 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5496 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5497 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5498 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5500 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5501 TypeManager.RegisterFieldBase (FieldBuilder, this);
5506 public override void Emit()
5509 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5511 object[] fi_val = new object[1];
5512 fi_val [0] = buffer_size;
5514 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5515 ctor_args, fi, fi_val);
5516 fixed_buffer_type.SetCustomAttribute (cab);
5519 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5520 FieldBuilder.SetCustomAttribute (cab);
5525 protected override bool IsFieldClsCompliant {
5531 #region IFixedField Members
5533 public FieldInfo Element {
5539 public Type ElementType {
5549 // The Field class is used to represents class/struct fields during parsing.
5551 public class Field : FieldMember {
5553 // Modifiers allowed in a class declaration
5555 const int AllowedModifiers =
5558 Modifiers.PROTECTED |
5559 Modifiers.INTERNAL |
5562 Modifiers.VOLATILE |
5566 public Field (TypeContainer parent, Expression type, int mod, string name,
5567 Object expr_or_array_init, Attributes attrs, Location loc)
5568 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5569 expr_or_array_init, attrs, loc)
5573 public override bool Define ()
5575 if (!base.Define ())
5578 if (RootContext.WarningLevel > 1){
5579 Type ptype = Parent.TypeBuilder.BaseType;
5581 // ptype is only null for System.Object while compiling corlib.
5583 TypeContainer.FindMembers (
5584 ptype, MemberTypes.Method,
5585 BindingFlags.Public |
5586 BindingFlags.Static | BindingFlags.Instance,
5587 System.Type.FilterName, Name);
5591 if ((ModFlags & Modifiers.VOLATILE) != 0){
5592 if (!MemberType.IsClass){
5593 Type vt = MemberType;
5595 if (TypeManager.IsEnumType (vt))
5596 vt = TypeManager.EnumToUnderlying (MemberType);
5598 if (!((vt == TypeManager.bool_type) ||
5599 (vt == TypeManager.sbyte_type) ||
5600 (vt == TypeManager.byte_type) ||
5601 (vt == TypeManager.short_type) ||
5602 (vt == TypeManager.ushort_type) ||
5603 (vt == TypeManager.int32_type) ||
5604 (vt == TypeManager.uint32_type) ||
5605 (vt == TypeManager.char_type) ||
5606 (vt == TypeManager.float_type) ||
5607 (!vt.IsValueType))){
5608 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5609 GetSignatureForError (), TypeManager.CSharpName (vt));
5614 if ((ModFlags & Modifiers.READONLY) != 0){
5615 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5616 GetSignatureForError ());
5621 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5623 if (Parent.Kind == Kind.Struct &&
5624 ((fa & FieldAttributes.Static) == 0) &&
5625 MemberType == Parent.TypeBuilder &&
5626 !TypeManager.IsBuiltinType (MemberType)){
5627 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5628 "' causes a cycle in the structure layout");
5633 FieldBuilder = Parent.TypeBuilder.DefineField (
5634 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5636 TypeManager.RegisterFieldBase (FieldBuilder, this);
5638 catch (ArgumentException) {
5639 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5646 protected override bool VerifyClsCompliance (DeclSpace ds)
5648 if (!base.VerifyClsCompliance (ds))
5651 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5652 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5660 // `set' and `get' accessors are represented with an Accessor.
5662 public class Accessor : IIteratorContainer {
5664 // Null if the accessor is empty, or a Block if not
5666 public const int AllowedModifiers =
5668 Modifiers.PROTECTED |
5669 Modifiers.INTERNAL |
5672 public ToplevelBlock Block;
5673 public Attributes Attributes;
5674 public Location Location;
5675 public int ModFlags;
5678 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5683 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5686 public void SetYields ()
5692 // Ooouh Martin, templates are missing here.
5693 // When it will be possible move here a lot of child code and template method type.
5694 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5695 protected MethodData method_data;
5696 protected ToplevelBlock block;
5697 protected ListDictionary declarative_security;
5699 // The accessor are created event if they are not wanted.
5700 // But we need them because their names are reserved.
5701 // Field says whether accessor will be emited or not
5702 public readonly bool IsDummy;
5704 protected readonly string prefix;
5706 ReturnParameter return_attributes;
5708 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5709 : base (null, SetupName (prefix, member), null, member.Location)
5711 this.prefix = prefix;
5715 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5717 : base (null, SetupName (prefix, member),
5718 accessor.Attributes, accessor.Location)
5720 this.prefix = prefix;
5721 this.block = accessor.Block;
5724 static MemberName SetupName (string prefix, MemberBase member)
5726 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
5729 public void UpdateName (MemberBase member)
5731 SetMemberName (SetupName (prefix, member));
5734 #region IMethodData Members
5736 public ToplevelBlock Block {
5746 public CallingConventions CallingConventions {
5748 return CallingConventions.Standard;
5752 public bool IsExcluded (EmitContext ec)
5757 public MemberName MethodName {
5763 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5764 public abstract Type[] ParameterTypes { get; }
5765 public abstract Type ReturnType { get; }
5766 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5770 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5772 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5773 a.Type == TypeManager.conditional_attribute_type) {
5774 Report.Error (1667, a.Location,
5775 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5776 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5780 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5781 if (declarative_security == null)
5782 declarative_security = new ListDictionary ();
5783 a.ExtractSecurityPermissionSet (declarative_security);
5787 if (a.Target == AttributeTargets.Method) {
5788 method_data.MethodBuilder.SetCustomAttribute (cb);
5792 if (a.Target == AttributeTargets.ReturnValue) {
5793 if (return_attributes == null)
5794 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5796 return_attributes.ApplyAttributeBuilder (a, cb);
5800 ApplyToExtraTarget (a, cb);
5803 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5805 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5808 public override bool Define()
5810 throw new NotSupportedException ();
5813 public virtual void Emit (TypeContainer container)
5815 EmitMethod (container);
5817 if (declarative_security != null) {
5818 foreach (DictionaryEntry de in declarative_security) {
5819 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5826 protected virtual void EmitMethod (TypeContainer container)
5828 method_data.Emit (container, this);
5831 public override bool IsClsCompliaceRequired(DeclSpace ds)
5836 public bool IsDuplicateImplementation (MethodCore method)
5838 if (!MemberName.Equals (method.MemberName))
5841 Type[] param_types = method.ParameterTypes;
5843 if (param_types.Length != ParameterTypes.Length)
5846 for (int i = 0; i < param_types.Length; i++)
5847 if (param_types [i] != ParameterTypes [i])
5850 Report.SymbolRelatedToPreviousError (method);
5851 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
5855 public override bool IsUsed
5865 public new Location Location {
5867 return base.Location;
5872 // Represents header string for documentation comment.
5874 public override string DocCommentHeader {
5875 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5878 protected override void VerifyObsoleteAttribute()
5885 // Properties and Indexers both generate PropertyBuilders, we use this to share
5886 // their common bits.
5888 abstract public class PropertyBase : MethodCore {
5890 public class GetMethod: PropertyMethod
5892 static string[] attribute_targets = new string [] { "method", "return" };
5894 public GetMethod (MethodCore method):
5895 base (method, "get_")
5899 public GetMethod (MethodCore method, Accessor accessor):
5900 base (method, accessor, "get_")
5904 public override MethodBuilder Define(TypeContainer container)
5906 base.Define (container);
5908 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5910 if (!method_data.Define (container))
5913 return method_data.MethodBuilder;
5916 public override Type ReturnType {
5918 return method.MemberType;
5922 public override string[] ValidAttributeTargets {
5924 return attribute_targets;
5929 public class SetMethod: PropertyMethod {
5931 static string[] attribute_targets = new string [] { "method", "param", "return" };
5932 ImplicitParameter param_attr;
5934 public SetMethod (MethodCore method):
5935 base (method, "set_")
5939 public SetMethod (MethodCore method, Accessor accessor):
5940 base (method, accessor, "set_")
5944 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5946 if (a.Target == AttributeTargets.Parameter) {
5947 if (param_attr == null)
5948 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
5950 param_attr.ApplyAttributeBuilder (a, cb);
5954 base.ApplyAttributeBuilder (a, cb);
5957 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5959 Parameter [] parms = new Parameter [1];
5960 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
5961 Parameters parameters = new Parameters (parms, null);
5963 bool old_unsafe = ec.InUnsafe;
5964 ec.InUnsafe = InUnsafe;
5965 Type [] types = parameters.GetParameterInfo (ec);
5966 ec.InUnsafe = old_unsafe;
5968 return new InternalParameters (types, parameters);
5971 public override MethodBuilder Define (TypeContainer container)
5973 if (container.EmitContext == null)
5974 throw new InternalErrorException ("SetMethod.Define called too early");
5976 base.Define (container);
5978 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5980 if (!method_data.Define (container))
5983 return method_data.MethodBuilder;
5986 public override Type[] ParameterTypes {
5988 return new Type[] { method.MemberType };
5992 public override Type ReturnType {
5994 return TypeManager.void_type;
5998 public override string[] ValidAttributeTargets {
6000 return attribute_targets;
6005 static string[] attribute_targets = new string [] { "property" };
6007 public abstract class PropertyMethod: AbstractPropertyEventMethod
6009 protected readonly MethodCore method;
6010 protected MethodAttributes flags;
6013 public PropertyMethod (MethodCore method, string prefix)
6014 : base (method, prefix)
6016 this.method = method;
6017 Parent = method.Parent;
6020 public PropertyMethod (MethodCore method, Accessor accessor,
6022 : base (method, accessor, prefix)
6024 this.method = method;
6025 Parent = method.Parent;
6026 this.ModFlags = accessor.ModFlags;
6027 yields = accessor.Yields;
6029 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6030 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6034 public override AttributeTargets AttributeTargets {
6036 return AttributeTargets.Method;
6040 public override bool IsClsCompliaceRequired(DeclSpace ds)
6042 return method.IsClsCompliaceRequired (ds);
6045 public InternalParameters ParameterInfo
6048 return method_data.ParameterInfo;
6052 public virtual MethodBuilder Define (TypeContainer container)
6054 if (!method.CheckAbstractAndExtern (block != null))
6058 // Check for custom access modifier
6060 if (ModFlags == 0) {
6061 ModFlags = method.ModFlags;
6062 flags = method.flags;
6064 if (container.Kind == Kind.Interface)
6065 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6066 GetSignatureForError ());
6068 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6069 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6072 CheckModifiers (container, ModFlags);
6073 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6074 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6075 flags = Modifiers.MethodAttr (ModFlags);
6076 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6080 // Setup iterator if we are one
6083 Iterator iterator = new Iterator (this,
6084 Parent, method.ParameterInfo, ModFlags);
6086 if (!iterator.DefineIterator ())
6093 public bool HasCustomAccessModifier
6096 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6100 public override Type[] ParameterTypes {
6102 return TypeManager.NoTypes;
6106 public override EmitContext CreateEmitContext (TypeContainer tc,
6109 return new EmitContext (
6110 tc, method.Parent, method.Location, ig, ReturnType,
6111 method.ModFlags, false);
6114 public override ObsoleteAttribute GetObsoleteAttribute ()
6116 return method.GetObsoleteAttribute (method.Parent);
6119 public override string GetSignatureForError()
6121 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6124 void CheckModifiers (TypeContainer container, int modflags)
6127 int mflags = method.ModFlags & Modifiers.Accessibility;
6129 if ((mflags & Modifiers.PUBLIC) != 0) {
6130 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6132 else if ((mflags & Modifiers.PROTECTED) != 0) {
6133 if ((mflags & Modifiers.INTERNAL) != 0)
6134 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6136 flags |= Modifiers.PRIVATE;
6138 else if ((mflags & Modifiers.INTERNAL) != 0)
6139 flags |= Modifiers.PRIVATE;
6141 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6142 Report.Error (273, Location,
6143 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6144 GetSignatureForError (), method.GetSignatureForError ());
6148 public override bool MarkForDuplicationCheck ()
6150 caching_flags |= Flags.TestMethodDuplication;
6156 public PropertyMethod Get, Set;
6157 public PropertyBuilder PropertyBuilder;
6158 public MethodBuilder GetBuilder, SetBuilder;
6160 protected EmitContext ec;
6162 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6163 int allowed_mod, bool is_iface, MemberName name,
6164 Parameters parameters, Attributes attrs,
6166 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6167 attrs, parameters, loc)
6171 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6173 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6174 a.Error_InvalidSecurityParent ();
6178 PropertyBuilder.SetCustomAttribute (cb);
6181 public override AttributeTargets AttributeTargets {
6183 return AttributeTargets.Property;
6187 public override bool Define ()
6192 if (!IsTypePermitted ())
6198 protected override bool DoDefine ()
6200 if (!base.DoDefine ())
6204 // Accessors modifiers check
6206 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6207 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6208 GetSignatureForError ());
6212 if ((Get.IsDummy || Set.IsDummy)
6213 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6214 Report.Error (276, Location,
6215 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6216 GetSignatureForError ());
6220 if (MemberType.IsAbstract && MemberType.IsSealed) {
6221 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6225 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6229 protected override bool CheckForDuplications ()
6231 ArrayList ar = Parent.Indexers;
6233 int arLen = ar.Count;
6235 for (int i = 0; i < arLen; i++) {
6236 Indexer m = (Indexer) ar [i];
6237 if (IsDuplicateImplementation (m))
6242 ar = Parent.Properties;
6244 int arLen = ar.Count;
6246 for (int i = 0; i < arLen; i++) {
6247 Property m = (Property) ar [i];
6248 if (IsDuplicateImplementation (m))
6256 // TODO: rename to Resolve......
6257 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6259 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6260 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6262 if (base_property == null)
6265 base_ret_type = base_property.PropertyType;
6266 MethodInfo get_accessor = base_property.GetGetMethod (true);
6267 MethodInfo set_accessor = base_property.GetSetMethod (true);
6268 MethodAttributes get_accessor_access, set_accessor_access;
6270 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6271 if (Get != null && !Get.IsDummy && get_accessor == null) {
6272 Report.SymbolRelatedToPreviousError (base_property);
6273 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6276 if (Set != null && !Set.IsDummy && set_accessor == null) {
6277 Report.SymbolRelatedToPreviousError (base_property);
6278 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6283 // Check base class accessors access
6286 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6287 get_accessor_access = set_accessor_access = 0;
6288 if ((ModFlags & Modifiers.NEW) == 0) {
6289 if (get_accessor != null) {
6290 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6291 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6293 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6294 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6297 if (set_accessor != null) {
6298 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6299 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6301 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6302 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6307 // Get the less restrictive access
6309 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6312 public override void Emit ()
6315 // The PropertyBuilder can be null for explicit implementations, in that
6316 // case, we do not actually emit the ".property", so there is nowhere to
6317 // put the attribute
6319 if (PropertyBuilder != null && OptAttributes != null)
6320 OptAttributes.Emit (ec, this);
6332 /// Tests whether accessors are not in collision with some method (CS0111)
6334 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6336 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6339 public override bool IsUsed
6345 return Get.IsUsed | Set.IsUsed;
6349 protected override void SetMemberName (MemberName new_name)
6351 base.SetMemberName (new_name);
6353 Get.UpdateName (this);
6354 Set.UpdateName (this);
6357 public override string[] ValidAttributeTargets {
6359 return attribute_targets;
6364 // Represents header string for documentation comment.
6366 public override string DocCommentHeader {
6367 get { return "P:"; }
6371 public class Property : PropertyBase {
6372 const int AllowedModifiers =
6375 Modifiers.PROTECTED |
6376 Modifiers.INTERNAL |
6380 Modifiers.OVERRIDE |
6381 Modifiers.ABSTRACT |
6384 Modifiers.METHOD_YIELDS |
6387 const int AllowedInterfaceModifiers =
6390 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6391 MemberName name, Attributes attrs, Accessor get_block,
6392 Accessor set_block, Location loc)
6393 : base (ds, type, mod,
6394 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6395 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6398 if (get_block == null)
6399 Get = new GetMethod (this);
6401 Get = new GetMethod (this, get_block);
6403 if (set_block == null)
6404 Set = new SetMethod (this);
6406 Set = new SetMethod (this, set_block);
6409 public override bool Define ()
6411 if (!base.Define ())
6417 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6420 GetBuilder = Get.Define (Parent);
6421 if (GetBuilder == null)
6426 SetBuilder = Set.Define (Parent);
6427 if (SetBuilder == null)
6430 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6433 // FIXME - PropertyAttributes.HasDefault ?
6435 PropertyAttributes prop_attr = PropertyAttributes.None;
6437 prop_attr |= PropertyAttributes.RTSpecialName |
6438 PropertyAttributes.SpecialName;
6440 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6441 Name, prop_attr, MemberType, null);
6444 PropertyBuilder.SetGetMethod (GetBuilder);
6447 PropertyBuilder.SetSetMethod (SetBuilder);
6449 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6455 /// Gigantic workaround for lameness in SRE follows :
6456 /// This class derives from EventInfo and attempts to basically
6457 /// wrap around the EventBuilder so that FindMembers can quickly
6458 /// return this in it search for members
6460 public class MyEventBuilder : EventInfo {
6463 // We use this to "point" to our Builder which is
6464 // not really a MemberInfo
6466 EventBuilder MyBuilder;
6469 // We "catch" and wrap these methods
6471 MethodInfo raise, remove, add;
6473 EventAttributes attributes;
6474 Type declaring_type, reflected_type, event_type;
6479 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6481 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6483 // And now store the values in our own fields.
6485 declaring_type = type_builder;
6487 reflected_type = type_builder;
6489 attributes = event_attr;
6492 this.event_type = event_type;
6496 // Methods that you have to override. Note that you only need
6497 // to "implement" the variants that take the argument (those are
6498 // the "abstract" methods, the others (GetAddMethod()) are
6501 public override MethodInfo GetAddMethod (bool nonPublic)
6506 public override MethodInfo GetRemoveMethod (bool nonPublic)
6511 public override MethodInfo GetRaiseMethod (bool nonPublic)
6517 // These methods make "MyEventInfo" look like a Builder
6519 public void SetRaiseMethod (MethodBuilder raiseMethod)
6521 raise = raiseMethod;
6522 MyBuilder.SetRaiseMethod (raiseMethod);
6525 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6527 remove = removeMethod;
6528 MyBuilder.SetRemoveOnMethod (removeMethod);
6531 public void SetAddOnMethod (MethodBuilder addMethod)
6534 MyBuilder.SetAddOnMethod (addMethod);
6537 public void SetCustomAttribute (CustomAttributeBuilder cb)
6539 MyBuilder.SetCustomAttribute (cb);
6542 public override object [] GetCustomAttributes (bool inherit)
6544 // FIXME : There's nothing which can be seemingly done here because
6545 // we have no way of getting at the custom attribute objects of the
6550 public override object [] GetCustomAttributes (Type t, bool inherit)
6552 // FIXME : Same here !
6556 public override bool IsDefined (Type t, bool b)
6561 public override EventAttributes Attributes {
6567 public override string Name {
6573 public override Type DeclaringType {
6575 return declaring_type;
6579 public override Type ReflectedType {
6581 return reflected_type;
6585 public Type EventType {
6591 public void SetUsed ()
6593 if (my_event != null) {
6594 my_event.SetAssigned ();
6595 my_event.SetMemberIsUsed ();
6601 /// For case when event is declared like property (with add and remove accessors).
6603 public class EventProperty: Event {
6605 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6607 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6608 bool is_iface, MemberName name, Object init,
6609 Attributes attrs, Accessor add, Accessor remove,
6611 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6613 Add = new AddDelegateMethod (this, add);
6614 Remove = new RemoveDelegateMethod (this, remove);
6616 // For this event syntax we don't report error CS0067
6617 // because it is hard to do it.
6621 public override string[] ValidAttributeTargets {
6623 return attribute_targets;
6629 /// Event is declared like field.
6631 public class EventField: Event {
6633 static string[] attribute_targets = new string [] { "event", "field", "method" };
6634 static string[] attribute_targets_interface = new string[] { "event", "method" };
6636 public EventField (TypeContainer parent, Expression type, int mod_flags,
6637 bool is_iface, MemberName name, Object init,
6638 Attributes attrs, Location loc)
6639 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6641 Add = new AddDelegateMethod (this);
6642 Remove = new RemoveDelegateMethod (this);
6645 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6647 if (a.Target == AttributeTargets.Field) {
6648 FieldBuilder.SetCustomAttribute (cb);
6652 if (a.Target == AttributeTargets.Method) {
6653 Add.ApplyAttributeBuilder (a, cb);
6654 Remove.ApplyAttributeBuilder (a, cb);
6658 base.ApplyAttributeBuilder (a, cb);
6661 public override string[] ValidAttributeTargets {
6663 return IsInterface ? attribute_targets_interface : attribute_targets;
6668 public abstract class Event : FieldBase {
6670 protected sealed class AddDelegateMethod: DelegateMethod
6673 public AddDelegateMethod (Event method):
6674 base (method, "add_")
6678 public AddDelegateMethod (Event method, Accessor accessor):
6679 base (method, accessor, "add_")
6683 protected override MethodInfo DelegateMethodInfo {
6685 return TypeManager.delegate_combine_delegate_delegate;
6691 protected sealed class RemoveDelegateMethod: DelegateMethod
6693 public RemoveDelegateMethod (Event method):
6694 base (method, "remove_")
6698 public RemoveDelegateMethod (Event method, Accessor accessor):
6699 base (method, accessor, "remove_")
6703 protected override MethodInfo DelegateMethodInfo {
6705 return TypeManager.delegate_remove_delegate_delegate;
6711 public abstract class DelegateMethod: AbstractPropertyEventMethod
6713 protected readonly Event method;
6714 ImplicitParameter param_attr;
6716 static string[] attribute_targets = new string [] { "method", "param", "return" };
6718 public DelegateMethod (Event method, string prefix)
6719 : base (method, prefix)
6721 this.method = method;
6724 public DelegateMethod (Event method, Accessor accessor, string prefix)
6725 : base (method, accessor, prefix)
6727 this.method = method;
6730 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6732 if (a.Target == AttributeTargets.Parameter) {
6733 if (param_attr == null)
6734 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6736 param_attr.ApplyAttributeBuilder (a, cb);
6740 base.ApplyAttributeBuilder (a, cb);
6743 public override AttributeTargets AttributeTargets {
6745 return AttributeTargets.Method;
6749 public override bool IsClsCompliaceRequired(DeclSpace ds)
6751 return method.IsClsCompliaceRequired (ds);
6754 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6756 method_data = new MethodData (method, ip, method.ModFlags,
6757 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6759 if (!method_data.Define (container))
6762 MethodBuilder mb = method_data.MethodBuilder;
6763 mb.DefineParameter (1, ParameterAttributes.None, "value");
6768 protected override void EmitMethod (TypeContainer tc)
6770 if (block != null) {
6771 base.EmitMethod (tc);
6775 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6778 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6779 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6781 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6782 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6783 ig.Emit (OpCodes.Ldsfld, field_info);
6784 ig.Emit (OpCodes.Ldarg_0);
6785 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6786 ig.Emit (OpCodes.Castclass, method.MemberType);
6787 ig.Emit (OpCodes.Stsfld, field_info);
6789 ig.Emit (OpCodes.Ldarg_0);
6790 ig.Emit (OpCodes.Ldarg_0);
6791 ig.Emit (OpCodes.Ldfld, field_info);
6792 ig.Emit (OpCodes.Ldarg_1);
6793 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6794 ig.Emit (OpCodes.Castclass, method.MemberType);
6795 ig.Emit (OpCodes.Stfld, field_info);
6797 ig.Emit (OpCodes.Ret);
6800 protected abstract MethodInfo DelegateMethodInfo { get; }
6802 public override Type[] ParameterTypes {
6804 return new Type[] { method.MemberType };
6808 public override Type ReturnType {
6810 return TypeManager.void_type;
6814 public override EmitContext CreateEmitContext (TypeContainer tc,
6817 return new EmitContext (
6818 tc, method.Parent, Location, ig, ReturnType,
6819 method.ModFlags, false);
6822 public override ObsoleteAttribute GetObsoleteAttribute ()
6824 return method.GetObsoleteAttribute (method.Parent);
6827 public override string[] ValidAttributeTargets {
6829 return attribute_targets;
6835 const int AllowedModifiers =
6838 Modifiers.PROTECTED |
6839 Modifiers.INTERNAL |
6844 Modifiers.OVERRIDE |
6848 const int AllowedInterfaceModifiers =
6851 public DelegateMethod Add, Remove;
6852 public MyEventBuilder EventBuilder;
6853 public MethodBuilder AddBuilder, RemoveBuilder;
6855 public Event (TypeContainer parent, Expression type, int mod_flags,
6856 bool is_iface, MemberName name, Object init, Attributes attrs,
6858 : base (parent, type, mod_flags,
6859 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6860 name, init, attrs, loc)
6862 IsInterface = is_iface;
6865 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6867 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6868 a.Error_InvalidSecurityParent ();
6872 EventBuilder.SetCustomAttribute (cb);
6875 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6877 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6880 public override AttributeTargets AttributeTargets {
6882 return AttributeTargets.Event;
6886 public override bool Define ()
6888 EventAttributes e_attr;
6889 e_attr = EventAttributes.None;
6894 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6895 Report.Error (74, Location, "`" + GetSignatureForError () +
6896 "': abstract event cannot have an initializer");
6900 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6901 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
6905 EmitContext ec = Parent.EmitContext;
6907 throw new InternalErrorException ("Event.Define called too early?");
6908 bool old_unsafe = ec.InUnsafe;
6909 ec.InUnsafe = InUnsafe;
6911 Parameter [] parms = new Parameter [1];
6912 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
6913 Parameters parameters = new Parameters (parms, null);
6914 Type [] types = parameters.GetParameterInfo (ec);
6915 InternalParameters ip = new InternalParameters (types, parameters);
6917 ec.InUnsafe = old_unsafe;
6923 // Now define the accessors
6926 AddBuilder = Add.Define (Parent, ip);
6927 if (AddBuilder == null)
6930 RemoveBuilder = Remove.Define (Parent, ip);
6931 if (RemoveBuilder == null)
6934 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6936 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6937 FieldBuilder = Parent.TypeBuilder.DefineField (
6939 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6940 TypeManager.RegisterPrivateFieldOfEvent (
6941 (EventInfo) EventBuilder, FieldBuilder);
6942 TypeManager.RegisterFieldBase (FieldBuilder, this);
6945 EventBuilder.SetAddOnMethod (AddBuilder);
6946 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6948 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6952 protected override bool CheckBase ()
6954 if (!base.CheckBase ())
6957 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6958 if (!(conflict_symbol is EventInfo)) {
6959 Report.SymbolRelatedToPreviousError (conflict_symbol);
6960 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
6968 public override void Emit ()
6970 if (OptAttributes != null) {
6971 EmitContext ec = new EmitContext (
6972 Parent, Location, null, MemberType, ModFlags);
6973 OptAttributes.Emit (ec, this);
6977 Remove.Emit (Parent);
6982 public override string GetSignatureForError ()
6984 return base.GetSignatureForError ();
6988 // Represents header string for documentation comment.
6990 public override string DocCommentHeader {
6991 get { return "E:"; }
6996 public class Indexer : PropertyBase {
6998 class GetIndexerMethod: GetMethod
7000 public GetIndexerMethod (MethodCore method):
7005 public GetIndexerMethod (MethodCore method, Accessor accessor):
7006 base (method, accessor)
7010 public override Type[] ParameterTypes {
7012 return method.ParameterTypes;
7017 class SetIndexerMethod: SetMethod
7019 readonly Parameters parameters;
7021 public SetIndexerMethod (MethodCore method):
7026 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7027 base (method, accessor)
7029 this.parameters = parameters;
7032 public override Type[] ParameterTypes {
7034 int top = method.ParameterTypes.Length;
7035 Type [] set_pars = new Type [top + 1];
7036 method.ParameterTypes.CopyTo (set_pars, 0);
7037 set_pars [top] = method.MemberType;
7042 protected override InternalParameters GetParameterInfo (EmitContext ec)
7044 Parameter [] fixed_parms = parameters.FixedParameters;
7046 if (fixed_parms == null){
7047 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7048 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7049 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7051 // Here is the problem: the `value' parameter has
7052 // to come *after* the array parameter in the declaration
7054 // X (object [] x, Type value)
7057 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7058 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7062 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7064 fixed_parms.CopyTo (tmp, 0);
7065 tmp [fixed_parms.Length] = new Parameter (
7066 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7068 Parameters set_formal_params = new Parameters (tmp, null);
7069 Type [] types = set_formal_params.GetParameterInfo (ec);
7071 return new InternalParameters (types, set_formal_params);
7076 const int AllowedModifiers =
7079 Modifiers.PROTECTED |
7080 Modifiers.INTERNAL |
7084 Modifiers.OVERRIDE |
7089 const int AllowedInterfaceModifiers =
7093 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7094 bool is_iface, Parameters parameters, Attributes attrs,
7095 Accessor get_block, Accessor set_block, Location loc)
7096 : base (ds, type, mod,
7097 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7098 is_iface, name, parameters, attrs, loc)
7100 if (get_block == null)
7101 Get = new GetIndexerMethod (this);
7103 Get = new GetIndexerMethod (this, get_block);
7105 if (set_block == null)
7106 Set = new SetIndexerMethod (this);
7108 Set = new SetIndexerMethod (this, parameters, set_block);
7111 public override bool Define ()
7113 PropertyAttributes prop_attr =
7114 PropertyAttributes.RTSpecialName |
7115 PropertyAttributes.SpecialName;
7117 if (!base.Define ())
7120 if (MemberType == TypeManager.void_type) {
7121 Report.Error (620, Location, "Indexers cannot have void type");
7125 if (OptAttributes != null) {
7126 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7127 if (indexer_attr != null) {
7128 // Remove the attribute from the list because it is not emitted
7129 OptAttributes.Attrs.Remove (indexer_attr);
7131 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7133 if (IsExplicitImpl) {
7134 Report.Error (415, indexer_attr.Location,
7135 "The `IndexerName' attribute is valid only on an " +
7136 "indexer that is not an explicit interface member declaration");
7140 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7141 Report.Error (609, indexer_attr.Location,
7142 "Cannot set the `IndexerName' attribute on an indexer marked override");
7146 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7147 Report.Error (633, indexer_attr.Location,
7148 "The argument to the `IndexerName' attribute must be a valid identifier");
7154 if (InterfaceType != null) {
7155 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7156 if (base_IndexerName != Name)
7157 ShortName = base_IndexerName;
7160 if (!Parent.AddToMemberContainer (this) ||
7161 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7167 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7169 GetBuilder = Get.Define (Parent);
7170 if (GetBuilder == null)
7175 SetBuilder = Set.Define (Parent);
7176 if (SetBuilder == null)
7181 // Now name the parameters
7183 Parameter [] p = Parameters.FixedParameters;
7185 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7186 Report.Error (631, Location, "ref and out are not valid in this context");
7192 for (i = 0; i < p.Length; ++i) {
7194 GetBuilder.DefineParameter (
7195 i + 1, p [i].Attributes, p [i].Name);
7198 SetBuilder.DefineParameter (
7199 i + 1, p [i].Attributes, p [i].Name);
7203 SetBuilder.DefineParameter (
7204 i + 1, ParameterAttributes.None, "value");
7206 if (i != ParameterTypes.Length) {
7207 Parameter array_param = Parameters.ArrayParameter;
7209 SetBuilder.DefineParameter (
7210 i + 1, array_param.Attributes, array_param.Name);
7214 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7215 Name, prop_attr, MemberType, ParameterTypes);
7218 PropertyBuilder.SetGetMethod (GetBuilder);
7221 PropertyBuilder.SetSetMethod (SetBuilder);
7223 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7228 public override string GetSignatureForError ()
7230 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7231 if (MemberName.Left != null) {
7233 sb.Append (MemberName.Left);
7236 sb.Append (".this");
7237 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7238 return sb.ToString ();
7241 public override bool MarkForDuplicationCheck ()
7243 caching_flags |= Flags.TestMethodDuplication;
7249 public class Operator : MethodCore, IIteratorContainer {
7251 const int AllowedModifiers =
7257 public enum OpType : byte {
7267 // Unary and Binary operators
7290 // Implicit and Explicit
7294 // Just because of enum
7298 public readonly OpType OperatorType;
7299 public MethodBuilder OperatorMethodBuilder;
7301 public Method OperatorMethod;
7303 static string[] attribute_targets = new string [] { "method", "return" };
7305 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7306 int mod_flags, Parameters parameters,
7307 ToplevelBlock block, Attributes attrs, Location loc)
7308 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7309 new MemberName ("op_" + type), attrs, parameters, loc)
7311 OperatorType = type;
7315 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7317 OperatorMethod.ApplyAttributeBuilder (a, cb);
7320 public override AttributeTargets AttributeTargets {
7322 return AttributeTargets.Method;
7326 protected override bool CheckForDuplications()
7328 ArrayList ar = Parent.Operators;
7330 int arLen = ar.Count;
7332 for (int i = 0; i < arLen; i++) {
7333 Operator o = (Operator) ar [i];
7334 if (IsDuplicateImplementation (o))
7339 ar = Parent.Methods;
7341 int arLen = ar.Count;
7343 for (int i = 0; i < arLen; i++) {
7344 Method m = (Method) ar [i];
7345 if (IsDuplicateImplementation (m))
7353 public override bool Define ()
7355 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7356 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7357 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7364 if (MemberType == TypeManager.void_type) {
7365 Report.Error (590, Location, "User-defined operators cannot return void");
7369 OperatorMethod = new Method (
7370 Parent, Type, ModFlags, false, MemberName,
7371 Parameters, OptAttributes, Location);
7373 OperatorMethod.Block = Block;
7374 OperatorMethod.IsOperator = this;
7375 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7376 OperatorMethod.Define ();
7378 if (OperatorMethod.MethodBuilder == null)
7381 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7383 parameter_types = OperatorMethod.ParameterTypes;
7384 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7385 Type return_type = OperatorMethod.ReturnType;
7386 Type first_arg_type = parameter_types [0];
7391 // Rules for conversion operators
7393 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7394 if (first_arg_type == return_type && first_arg_type == declaring_type){
7395 Report.Error (555, Location,
7396 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7400 if (first_arg_type != declaring_type && return_type != declaring_type){
7403 "User-defined conversion must convert to or from the " +
7408 if (first_arg_type == TypeManager.object_type ||
7409 return_type == TypeManager.object_type){
7412 "User-defined conversion cannot convert to or from " +
7417 if (first_arg_type.IsInterface || return_type.IsInterface){
7418 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7419 GetSignatureForError ());
7423 if (first_arg_type.IsSubclassOf (return_type)
7424 || return_type.IsSubclassOf (first_arg_type)){
7425 if (declaring_type.IsSubclassOf (return_type)) {
7426 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7427 GetSignatureForError ());
7430 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7431 GetSignatureForError ());
7434 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7435 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7436 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");
7439 } else if (Parameters.FixedParameters.Length == 1) {
7440 // Checks for Unary operators
7442 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7443 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7444 Report.Error (448, Location,
7445 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7448 if (first_arg_type != declaring_type) {
7450 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7455 if (first_arg_type != declaring_type){
7458 "The parameter of a unary operator must be the " +
7463 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7464 if (return_type != TypeManager.bool_type){
7467 "The return type of operator True or False " +
7474 // Checks for Binary operators
7476 if (first_arg_type != declaring_type &&
7477 parameter_types [1] != declaring_type){
7480 "One of the parameters of a binary operator must " +
7481 "be the containing type");
7489 public override void Emit ()
7492 // abstract or extern methods have no bodies
7494 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7497 OperatorMethod.Emit ();
7501 // Operator cannot be override
7502 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7507 public static string GetName (OpType ot)
7510 case OpType.LogicalNot:
7512 case OpType.OnesComplement:
7514 case OpType.Increment:
7516 case OpType.Decrement:
7522 case OpType.Addition:
7524 case OpType.Subtraction:
7526 case OpType.UnaryPlus:
7528 case OpType.UnaryNegation:
7530 case OpType.Multiply:
7532 case OpType.Division:
7534 case OpType.Modulus:
7536 case OpType.BitwiseAnd:
7538 case OpType.BitwiseOr:
7540 case OpType.ExclusiveOr:
7542 case OpType.LeftShift:
7544 case OpType.RightShift:
7546 case OpType.Equality:
7548 case OpType.Inequality:
7550 case OpType.GreaterThan:
7552 case OpType.LessThan:
7554 case OpType.GreaterThanOrEqual:
7556 case OpType.LessThanOrEqual:
7558 case OpType.Implicit:
7560 case OpType.Explicit:
7566 public static OpType GetOperatorType (string name)
7568 if (name.StartsWith ("op_")){
7569 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7570 if (Unary.oper_names [i] == name)
7574 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7575 if (Binary.oper_names [i] == name)
7582 public override string GetSignatureForError ()
7584 StringBuilder sb = new StringBuilder ();
7585 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7586 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7589 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7592 sb.Append (Parameters.GetSignatureForError ());
7593 return sb.ToString ();
7596 public override bool MarkForDuplicationCheck ()
7598 caching_flags |= Flags.TestMethodDuplication;
7602 public override string[] ValidAttributeTargets {
7604 return attribute_targets;
7610 // This is used to compare method signatures
7612 struct MethodSignature {
7614 public Type RetType;
7615 public Type [] Parameters;
7618 /// This delegate is used to extract methods which have the
7619 /// same signature as the argument
7621 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7623 public MethodSignature (string name, Type ret_type, Type [] parameters)
7628 if (parameters == null)
7629 Parameters = TypeManager.NoTypes;
7631 Parameters = parameters;
7634 public override string ToString ()
7637 if (Parameters.Length != 0){
7638 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7639 for (int i = 0; i < Parameters.Length; i++){
7640 sb.Append (Parameters [i]);
7641 if (i+1 < Parameters.Length)
7644 pars = sb.ToString ();
7647 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7650 public override int GetHashCode ()
7652 return Name.GetHashCode ();
7655 public override bool Equals (Object o)
7657 MethodSignature other = (MethodSignature) o;
7659 if (other.Name != Name)
7662 if (other.RetType != RetType)
7665 if (Parameters == null){
7666 if (other.Parameters == null)
7671 if (other.Parameters == null)
7674 int c = Parameters.Length;
7675 if (other.Parameters.Length != c)
7678 for (int i = 0; i < c; i++)
7679 if (other.Parameters [i] != Parameters [i])
7685 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7687 MethodSignature sig = (MethodSignature) filter_criteria;
7689 if (m.Name != sig.Name)
7693 MethodInfo mi = m as MethodInfo;
7694 PropertyInfo pi = m as PropertyInfo;
7697 ReturnType = mi.ReturnType;
7698 else if (pi != null)
7699 ReturnType = pi.PropertyType;
7704 // we use sig.RetType == null to mean `do not check the
7705 // method return value.
7707 if (sig.RetType != null)
7708 if (ReturnType != sig.RetType)
7713 args = TypeManager.GetArgumentTypes (mi);
7715 args = TypeManager.GetArgumentTypes (pi);
7716 Type [] sigp = sig.Parameters;
7718 if (args.Length != sigp.Length)
7721 for (int i = args.Length; i > 0; ){
7723 if (args [i] != sigp [i])