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 throw new InternalErrorException (mc.Location, mc.GetSignatureForError (), e);
84 public virtual void Emit ()
86 foreach (MemberCore mc in this)
91 public class MethodArrayList : MemberCoreArrayList
99 CachedMethods cached_method;
100 TypeContainer container;
102 public MethodArrayList (TypeContainer container)
104 this.container = container;
108 /// Method container contains Equals method
110 public bool HasEquals {
112 cached_method |= CachedMethods.Equals;
116 return (cached_method & CachedMethods.Equals) != 0;
121 /// Method container contains GetHashCode method
123 public bool HasGetHashCode {
125 cached_method |= CachedMethods.GetHashCode;
129 return (cached_method & CachedMethods.GetHashCode) != 0;
133 public override void DefineContainerMembers ()
135 base.DefineContainerMembers ();
137 if (HasEquals && !HasGetHashCode) {
138 Report.Warning (659, 3, container.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
144 public sealed class IndexerArrayList : MemberCoreArrayList
147 /// The indexer name for this container
149 public string IndexerName = DefaultIndexerName;
151 bool seen_normal_indexers = false;
153 TypeContainer container;
155 public IndexerArrayList (TypeContainer container)
157 this.container = container;
161 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
162 /// class is consistent. Either it is `Item' or it is the name defined by all the
163 /// indexers with the `IndexerName' attribute.
165 /// Turns out that the IndexerNameAttribute is applied to each indexer,
166 /// but it is never emitted, instead a DefaultMember attribute is attached
169 public override void DefineContainerMembers()
171 base.DefineContainerMembers ();
173 string class_indexer_name = null;
176 // If there's both an explicit and an implicit interface implementation, the
177 // explicit one actually implements the interface while the other one is just
178 // a normal indexer. See bug #37714.
181 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
182 foreach (Indexer i in this) {
183 if (i.InterfaceType != null) {
184 if (seen_normal_indexers)
185 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
189 seen_normal_indexers = true;
191 if (class_indexer_name == null) {
192 class_indexer_name = i.ShortName;
196 if (i.ShortName != class_indexer_name)
197 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");
200 if (class_indexer_name != null)
201 IndexerName = class_indexer_name;
204 public override void Emit ()
208 if (!seen_normal_indexers)
211 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
212 container.TypeBuilder.SetCustomAttribute (cb);
216 public class OperatorArrayList: MemberCoreArrayList
218 TypeContainer container;
220 public OperatorArrayList (TypeContainer container)
222 this.container = container;
226 // Operator pair checking
231 public Type ret_type;
232 public Type type1, type2;
234 public Operator.OpType ot;
236 public OperatorEntry (int f, Operator o)
240 ret_type = o.MemberType;
241 Type [] pt = o.ParameterTypes;
248 public override int GetHashCode ()
250 return ret_type.GetHashCode ();
253 public override bool Equals (object o)
255 OperatorEntry other = (OperatorEntry) o;
257 if (other.ret_type != ret_type)
259 if (other.type1 != type1)
261 if (other.type2 != type2)
268 // Checks that some operators come in pairs:
274 // They are matched based on the return type and the argument types
276 void CheckPairedOperators ()
278 IDictionary pairs = new HybridDictionary ();
279 Operator true_op = null;
280 Operator false_op = null;
281 bool has_equality_or_inequality = false;
283 // Register all the operators we care about.
284 foreach (Operator op in this){
287 // Skip erroneous code.
288 if (op.MethodBuilder == null)
291 switch (op.OperatorType){
292 case Operator.OpType.Equality:
294 has_equality_or_inequality = true;
296 case Operator.OpType.Inequality:
298 has_equality_or_inequality = true;
301 case Operator.OpType.True:
304 case Operator.OpType.False:
308 case Operator.OpType.GreaterThan:
310 case Operator.OpType.LessThan:
313 case Operator.OpType.GreaterThanOrEqual:
315 case Operator.OpType.LessThanOrEqual:
321 OperatorEntry oe = new OperatorEntry (reg, op);
323 object o = pairs [oe];
327 oe = (OperatorEntry) o;
332 if (true_op != null){
333 if (false_op == null)
334 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
335 true_op.GetSignatureForError ());
336 } else if (false_op != null)
337 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
338 false_op.GetSignatureForError ());
341 // Look for the mistakes.
343 foreach (DictionaryEntry de in pairs){
344 OperatorEntry oe = (OperatorEntry) de.Key;
351 case Operator.OpType.Equality:
354 case Operator.OpType.Inequality:
357 case Operator.OpType.GreaterThan:
360 case Operator.OpType.LessThan:
363 case Operator.OpType.GreaterThanOrEqual:
366 case Operator.OpType.LessThanOrEqual:
370 Report.Error (216, oe.op.Location,
371 "The operator `{0}' requires a matching operator `{1}' to also be defined",
372 oe.op.GetSignatureForError (), s);
375 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
376 if (container.Methods == null || !container.Methods.HasEquals)
377 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
379 if (container.Methods == null || !container.Methods.HasGetHashCode)
380 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
384 public override void DefineContainerMembers ()
386 base.DefineContainerMembers ();
387 CheckPairedOperators ();
392 // Whether this is a struct, class or interface
393 public readonly Kind Kind;
395 // Holds a list of classes and structures
396 protected ArrayList types;
398 // Holds the list of properties
399 MemberCoreArrayList properties;
401 // Holds the list of enumerations
402 MemberCoreArrayList enums;
404 // Holds the list of delegates
405 MemberCoreArrayList delegates;
407 // Holds the list of constructors
408 protected MemberCoreArrayList instance_constructors;
410 // Holds the list of fields
411 MemberCoreArrayList fields;
413 // Holds a list of fields that have initializers
414 protected ArrayList initialized_fields;
416 // Holds a list of static fields that have initializers
417 protected ArrayList initialized_static_fields;
419 // Holds the list of constants
420 MemberCoreArrayList constants;
423 MemberCoreArrayList interfaces;
425 // Holds the methods.
426 MethodArrayList methods;
429 protected MemberCoreArrayList events;
431 // Holds the indexers
432 IndexerArrayList indexers;
434 // Holds the operators
435 MemberCoreArrayList operators;
437 // Holds the iterators
441 // Pointers to the default constructor and the default static constructor
443 protected Constructor default_constructor;
444 protected Constructor default_static_constructor;
447 // Points to the first non-static field added to the container.
449 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
450 // and the first one's as good as any.
452 FieldBase first_nonstatic_field = null;
455 // This one is computed after we can distinguish interfaces
456 // from classes from the arraylist `type_bases'
459 TypeExpr[] iface_exprs;
461 ArrayList type_bases;
463 bool members_defined;
464 bool members_defined_ok;
466 // The interfaces we implement.
467 protected Type[] ifaces;
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 PartialContainer;
476 ArrayList partial_parts;
479 /// The pending methods that need to be implemented
480 // (interfaces or abstract methods)
482 PendingImplementation pending;
484 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
485 Attributes attrs, Kind kind)
486 : base (ns, parent, name, attrs)
488 // FIXME: Remove the second condition -- will require making RootContext.ToplevelTypes partial
489 if (parent != null && parent != RootContext.ToplevelTypes && parent.NamespaceEntry != ns)
490 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
493 this.PartialContainer = this;
496 public bool AddToMemberContainer (MemberCore symbol)
498 return AddToContainer (symbol, symbol.Name);
501 protected virtual bool AddToTypeContainer (DeclSpace ds)
503 return AddToContainer (ds, ds.Basename);
506 public void AddConstant (Const constant)
508 if (!AddToMemberContainer (constant))
511 if (constants == null)
512 constants = new MemberCoreArrayList ();
514 constants.Add (constant);
517 public void AddEnum (Mono.CSharp.Enum e)
519 if (!AddToTypeContainer (e))
523 enums = new MemberCoreArrayList ();
528 public bool AddClassOrStruct (TypeContainer c)
530 if (!AddToTypeContainer (c))
534 types = new ArrayList (2);
540 public virtual TypeContainer AddPartial (TypeContainer nextPart)
542 return AddPartial (nextPart, nextPart.Basename);
545 protected TypeContainer AddPartial (TypeContainer nextPart, string name)
547 nextPart.ModFlags |= Modifiers.PARTIAL;
548 TypeContainer tc = defined_names [name] as TypeContainer;
551 if (nextPart is Interface)
552 AddInterface (nextPart);
554 AddClassOrStruct (nextPart);
558 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
559 Report.SymbolRelatedToPreviousError (tc);
560 Error_MissingPartialModifier (nextPart);
564 if (tc.Kind != nextPart.Kind) {
565 Report.SymbolRelatedToPreviousError (tc);
566 Report.Error (261, nextPart.Location,
567 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
568 nextPart.GetSignatureForError ());
572 if ((tc.ModFlags & Modifiers.Accessibility) != (nextPart.ModFlags & Modifiers.Accessibility) &&
573 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
574 (nextPart.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
575 Report.SymbolRelatedToPreviousError (tc);
576 Report.Error (262, nextPart.Location,
577 "Partial declarations of `{0}' have conflicting accessibility modifiers",
578 nextPart.GetSignatureForError ());
582 if (tc.partial_parts == null)
583 tc.partial_parts = new ArrayList (1);
585 tc.ModFlags |= nextPart.ModFlags;
586 if (nextPart.attributes != null) {
587 if (tc.attributes == null)
588 tc.attributes = nextPart.attributes;
590 tc.attributes.AddAttributes (nextPart.attributes.Attrs);
593 nextPart.PartialContainer = tc;
594 tc.partial_parts.Add (nextPart);
598 public void AddDelegate (Delegate d)
600 if (!AddToTypeContainer (d))
603 if (delegates == null)
604 delegates = new MemberCoreArrayList ();
609 public void AddMethod (Method method)
611 if (!AddToMemberContainer (method))
615 methods = new MethodArrayList (this);
617 if (method.MemberName.Left != null)
618 methods.Insert (0, method);
620 methods.Add (method);
624 // Do not use this method: use AddMethod.
626 // This is only used by iterators.
628 public void AppendMethod (Method method)
630 if (!AddToMemberContainer (method))
634 methods = new MethodArrayList (this);
636 methods.Add (method);
639 public void AddConstructor (Constructor c)
641 if (c.Name != Basename) {
642 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
645 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
648 if (default_static_constructor != null) {
649 Report.SymbolRelatedToPreviousError (default_static_constructor);
650 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
654 default_static_constructor = c;
656 if (c.Parameters.Empty){
657 if (default_constructor != null) {
658 Report.SymbolRelatedToPreviousError (default_constructor);
659 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
662 default_constructor = c;
665 if (instance_constructors == null)
666 instance_constructors = new MemberCoreArrayList ();
668 instance_constructors.Add (c);
672 internal static string Error111 {
674 return "`{0}' is already defined. Rename this member or use different parameter types";
678 public bool AddInterface (TypeContainer iface)
680 if (!AddToTypeContainer (iface))
683 if (interfaces == null)
684 interfaces = new MemberCoreArrayList ();
686 interfaces.Add (iface);
690 public void AddField (FieldMember field)
692 if (!AddToMemberContainer (field))
696 fields = new MemberCoreArrayList ();
700 if ((field.ModFlags & Modifiers.STATIC) != 0)
703 if (first_nonstatic_field == null) {
704 first_nonstatic_field = field;
708 if (Kind == Kind.Struct &&
709 first_nonstatic_field.Parent != field.Parent &&
710 RootContext.WarningLevel >= 3) {
711 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
712 Report.Warning (282, 3, field.Location,
713 "struct instance field `{0}' found in different declaration from instance field `{1}'",
714 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
718 public void AddProperty (Property prop)
720 if (!AddToMemberContainer (prop) ||
721 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
724 if (properties == null)
725 properties = new MemberCoreArrayList ();
727 if (prop.MemberName.Left != null)
728 properties.Insert (0, prop);
730 properties.Add (prop);
733 public void AddEvent (Event e)
735 if (!AddToMemberContainer (e))
738 if (e is EventProperty) {
739 if (!AddToMemberContainer (e.Add))
742 if (!AddToMemberContainer (e.Remove))
747 events = new MemberCoreArrayList ();
753 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
755 public void AddIndexer (Indexer i)
757 if (indexers == null)
758 indexers = new IndexerArrayList (this);
760 if (i.IsExplicitImpl)
761 indexers.Insert (0, i);
766 public void AddOperator (Operator op)
768 if (!AddToMemberContainer (op))
771 if (operators == null)
772 operators = new OperatorArrayList (this);
777 public void AddIterator (Iterator i)
779 if (iterators == null)
780 iterators = new ArrayList ();
785 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
787 if (a.Type == TypeManager.default_member_type) {
788 if (Indexers != null) {
789 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
794 base.ApplyAttributeBuilder (a, cb);
797 public override AttributeTargets AttributeTargets {
799 throw new NotSupportedException ();
803 public ArrayList Types {
809 public MethodArrayList Methods {
815 public ArrayList Constants {
821 public ArrayList Interfaces {
827 public ArrayList Iterators {
833 protected Type BaseType {
835 return TypeBuilder.BaseType;
839 public ArrayList Bases {
849 public ArrayList Fields {
855 public ArrayList InstanceConstructors {
857 return instance_constructors;
861 public ArrayList Properties {
867 public ArrayList Events {
873 public ArrayList Enums {
879 public ArrayList Indexers {
885 public ArrayList Operators {
891 public ArrayList Delegates {
897 protected override TypeAttributes TypeAttr {
899 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
903 public string IndexerName {
905 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
909 public bool IsComImport {
911 if (OptAttributes == null)
914 return OptAttributes.Contains (TypeManager.comimport_attr_type);
918 public virtual void RegisterFieldForInitialization (FieldBase field)
920 if ((field.ModFlags & Modifiers.STATIC) != 0){
921 if (initialized_static_fields == null)
922 initialized_static_fields = new ArrayList (4);
924 initialized_static_fields.Add (field);
926 if (initialized_fields == null)
927 initialized_fields = new ArrayList (4);
929 initialized_fields.Add (field);
934 // Emits the instance field initializers
936 public bool EmitFieldInitializers (EmitContext ec)
941 fields = initialized_static_fields;
943 fields = initialized_fields;
949 foreach (FieldBase f in fields) {
950 f.EmitInitializer (ec);
955 public override string DocComment {
967 public PendingImplementation PendingImplementations {
968 get { return pending; }
971 public override bool GetClsCompliantAttributeValue ()
973 if (PartialContainer != this)
974 return PartialContainer.GetClsCompliantAttributeValue ();
976 return base.GetClsCompliantAttributeValue ();
979 TypeExpr[] GetNormalBases (out TypeExpr base_class)
985 int count = Bases.Count;
988 if (Kind == Kind.Class){
989 TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
995 if (!name.IsInterface) {
996 // base_class could be a class, struct, enum, delegate.
997 // This is validated in GetClassBases.
1003 TypeExpr [] ifaces = new TypeExpr [count-start];
1005 for (i = start, j = 0; i < count; i++, j++){
1006 TypeExpr resolved = ((Expression) Bases [i]).ResolveAsTypeTerminal (this, false);
1007 if (resolved == null) {
1011 ifaces [j] = resolved;
1014 return ifaces.Length == 0 ? null : ifaces;
1018 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
1020 ArrayList ifaces = new ArrayList (0);
1021 if (iface_exprs != null)
1022 ifaces.AddRange (iface_exprs);
1024 foreach (TypeContainer part in partial_parts) {
1025 TypeExpr new_base_class;
1026 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
1027 if (new_base_class != TypeManager.system_object_expr) {
1028 if (base_class == TypeManager.system_object_expr)
1029 base_class = new_base_class;
1031 if (new_base_class != null && !new_base_class.Equals (base_class)) {
1032 Report.SymbolRelatedToPreviousError (base_class.Location, "");
1033 Report.Error (263, part.Location,
1034 "Partial declarations of `{0}' must not specify different base classes",
1035 part.GetSignatureForError ());
1042 if (new_ifaces == null)
1045 foreach (TypeExpr iface in new_ifaces) {
1046 if (ifaces.Contains (iface))
1053 if (ifaces.Count == 0)
1056 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
1060 /// This function computes the Base class and also the
1061 /// list of interfaces that the class or struct @c implements.
1063 /// The return value is an array (might be null) of
1064 /// interfaces implemented (as Types).
1066 /// The @base_class argument is set to the base object or null
1067 /// if this is `System.Object'.
1069 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1071 TypeExpr[] ifaces = GetNormalBases (out base_class);
1076 int count = ifaces.Length;
1078 for (int i = 0; i < count; i++) {
1079 TypeExpr iface = (TypeExpr) ifaces [i];
1081 if (!iface.IsInterface) {
1082 if (Kind != Kind.Class) {
1083 // TODO: location of symbol related ....
1084 Error_TypeInListIsNotInterface (Location, iface.FullName);
1086 else if (base_class != null)
1087 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1088 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1090 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1091 GetSignatureForError (), iface.GetSignatureForError ());
1096 for (int x = 0; x < i; x++) {
1097 if (iface.Equals (ifaces [x])) {
1098 Report.Error (528, Location,
1099 "`{0}' is already listed in " +
1100 "interface list", iface.GetSignatureForError ());
1105 if ((Kind == Kind.Interface) &&
1106 !iface.AsAccessible (Parent, ModFlags)) {
1107 Report.Error (61, Location,
1108 "Inconsistent accessibility: base " +
1109 "interface `{0}' is less accessible " +
1110 "than interface `{1}'", iface.Name,
1120 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1122 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1125 bool DefineTypeBuilder ()
1129 if (TypeManager.NamespaceClash (Name, Location)) {
1133 ModuleBuilder builder = CodeGen.Module.Builder;
1134 TypeBuilder = builder.DefineType (
1135 Name, TypeAttr, null, null);
1137 TypeBuilder builder = Parent.TypeBuilder;
1139 TypeBuilder = builder.DefineNestedType (
1140 Basename, TypeAttr, null, null);
1142 } catch (ArgumentException) {
1143 Report.RuntimeMissingSupport (Location, "static classes");
1147 TypeManager.AddUserType (this);
1149 iface_exprs = GetClassBases (out base_type);
1150 if (partial_parts != null) {
1151 iface_exprs = GetNormalPartialBases (ref base_type);
1155 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1156 // which in turn should have called DefineType()s on base types if necessary.
1158 // None of the code below should trigger DefineType()s on classes that we depend on.
1159 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1161 // Let's do it as soon as possible, since code below can call DefineType() on classes
1162 // that depend on us to be populated before they are.
1164 if (!(this is Iterator))
1165 RootContext.RegisterOrder (this);
1168 if (base_type != null) {
1169 TypeBuilder.SetParent (base_type.Type);
1171 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1172 if (obsolete_attr != null && !IsInObsoleteScope) {
1173 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1177 if (!CheckRecursiveDefinition (this)) {
1181 // add interfaces that were not added at type creation
1182 if (iface_exprs != null) {
1183 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1184 if (ifaces == null) {
1188 foreach (Type itype in ifaces)
1189 TypeBuilder.AddInterfaceImplementation (itype);
1191 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1198 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1200 public override TypeBuilder DefineType ()
1202 if (TypeBuilder != null)
1208 if (!DefineTypeBuilder ()) {
1213 if (partial_parts != null) {
1214 foreach (TypeContainer part in partial_parts)
1215 part.TypeBuilder = TypeBuilder;
1218 DefineNestedTypes ();
1223 protected virtual bool DefineNestedTypes ()
1225 if (Interfaces != null) {
1226 foreach (TypeContainer iface in Interfaces)
1227 if (iface.DefineType () == null)
1231 if (Types != null) {
1232 foreach (TypeContainer tc in Types)
1233 if (tc.DefineType () == null)
1237 if (Delegates != null) {
1238 foreach (Delegate d in Delegates)
1239 if (d.DefineType () == null)
1243 if (Enums != null) {
1244 foreach (Enum en in Enums)
1245 if (en.DefineType () == null)
1252 TypeContainer InTransit;
1254 protected bool CheckRecursiveDefinition (TypeContainer tc)
1256 if (InTransit != null) {
1257 Report.SymbolRelatedToPreviousError (this);
1258 if (this is Interface)
1260 529, tc.Location, "Inherited interface `{0}' causes a " +
1261 "cycle in the interface hierarchy of `{1}'",
1262 GetSignatureForError (), tc.GetSignatureForError ());
1265 146, tc.Location, "Circular base class dependency " +
1266 "involving `{0}' and `{1}'",
1267 tc.GetSignatureForError (), GetSignatureForError ());
1273 if (BaseType != null) {
1274 TypeContainer ptc = TypeManager.LookupTypeContainer (BaseType);
1275 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1279 if (iface_exprs != null) {
1280 foreach (TypeExpr iface in iface_exprs) {
1281 Type itype = iface.Type;
1283 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1284 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1293 public static void Error_KeywordNotAllowed (Location loc)
1295 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1299 /// Populates our TypeBuilder with fields and methods
1301 public override bool DefineMembers ()
1303 if (members_defined)
1304 return members_defined_ok;
1306 if (!base.DefineMembers ())
1309 members_defined_ok = DoDefineMembers ();
1310 members_defined = true;
1312 return members_defined_ok;
1315 protected virtual bool DoDefineMembers ()
1318 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1319 if (conflict_symbol == null) {
1320 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1321 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1323 if ((ModFlags & Modifiers.NEW) == 0) {
1324 Report.SymbolRelatedToPreviousError (conflict_symbol);
1325 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1326 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1331 DefineContainerMembers (constants);
1332 DefineContainerMembers (fields);
1334 if (Kind == Kind.Struct || Kind == Kind.Class) {
1335 pending = PendingImplementation.GetPendingImplementations (this);
1339 // Constructors are not in the defined_names array
1341 DefineContainerMembers (instance_constructors);
1343 DefineContainerMembers (properties);
1344 DefineContainerMembers (events);
1345 DefineContainerMembers (indexers);
1346 DefineContainerMembers (methods);
1347 DefineContainerMembers (operators);
1348 DefineContainerMembers (enums);
1349 DefineContainerMembers (delegates);
1352 member_cache = new MemberCache (this);
1353 if (partial_parts != null) {
1354 foreach (TypeContainer part in partial_parts)
1355 part.member_cache = member_cache;
1358 if (iterators != null) {
1359 foreach (Iterator iterator in iterators) {
1360 if (iterator.DefineType () == null)
1364 foreach (Iterator iterator in iterators) {
1365 if (!iterator.DefineMembers ())
1373 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1376 mcal.DefineContainerMembers ();
1379 public override bool Define ()
1381 if (iterators != null) {
1382 foreach (Iterator iterator in iterators) {
1383 if (!iterator.Define ())
1391 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1393 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1397 /// This function is based by a delegate to the FindMembers routine
1399 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1405 /// This filter is used by FindMembers, and we just keep
1406 /// a global for the filter to `AlwaysAccept'
1408 static MemberFilter accepting_filter;
1411 static TypeContainer ()
1413 accepting_filter = new MemberFilter (AlwaysAccept);
1416 public MethodInfo[] GetMethods ()
1418 ArrayList members = new ArrayList ();
1422 if (methods != null) {
1423 int len = methods.Count;
1424 for (int i = 0; i < len; i++) {
1425 Method m = (Method) methods [i];
1427 members.Add (m.MethodBuilder);
1431 if (operators != null) {
1432 int len = operators.Count;
1433 for (int i = 0; i < len; i++) {
1434 Operator o = (Operator) operators [i];
1436 members.Add (o.MethodBuilder);
1440 if (properties != null) {
1441 int len = properties.Count;
1442 for (int i = 0; i < len; i++) {
1443 Property p = (Property) properties [i];
1445 if (p.GetBuilder != null)
1446 members.Add (p.GetBuilder);
1447 if (p.SetBuilder != null)
1448 members.Add (p.SetBuilder);
1452 if (indexers != null) {
1453 int len = indexers.Count;
1454 for (int i = 0; i < len; i++) {
1455 Indexer ix = (Indexer) indexers [i];
1457 if (ix.GetBuilder != null)
1458 members.Add (ix.GetBuilder);
1459 if (ix.SetBuilder != null)
1460 members.Add (ix.SetBuilder);
1464 if (events != null) {
1465 int len = events.Count;
1466 for (int i = 0; i < len; i++) {
1467 Event e = (Event) events [i];
1469 if (e.AddBuilder != null)
1470 members.Add (e.AddBuilder);
1471 if (e.RemoveBuilder != null)
1472 members.Add (e.RemoveBuilder);
1476 MethodInfo[] retMethods = new MethodInfo [members.Count];
1477 members.CopyTo (retMethods, 0);
1481 // Indicated whether container has StructLayout attribute set Explicit
1482 public bool HasExplicitLayout {
1484 return (caching_flags & Flags.HasExplicitLayout) != 0;
1487 caching_flags |= Flags.HasExplicitLayout;
1491 public override Type FindNestedType (string name)
1493 if (PartialContainer != this)
1494 return PartialContainer.FindNestedType (name);
1496 ArrayList [] lists = { types, enums, delegates, interfaces };
1498 for (int j = 0; j < lists.Length; ++j) {
1499 ArrayList list = lists [j];
1503 int len = list.Count;
1504 for (int i = 0; i < len; ++i) {
1505 DeclSpace ds = (DeclSpace) list [i];
1506 if (ds.Basename == name) {
1507 return ds.DefineType ();
1515 private void FindMembers_NestedTypes (int modflags,
1516 BindingFlags bf, MemberFilter filter, object criteria,
1517 ref ArrayList members)
1519 ArrayList [] lists = { types, enums, delegates, interfaces };
1521 for (int j = 0; j < lists.Length; ++j) {
1522 ArrayList list = lists [j];
1526 int len = list.Count;
1527 for (int i = 0; i < len; i++) {
1528 DeclSpace ds = (DeclSpace) list [i];
1530 if ((ds.ModFlags & modflags) == 0)
1533 TypeBuilder tb = ds.TypeBuilder;
1535 if (!(criteria is string) || ds.Basename.Equals (criteria))
1536 tb = ds.DefineType ();
1539 if (tb != null && (filter (tb, criteria) == true)) {
1540 if (members == null)
1541 members = new ArrayList ();
1550 /// This method returns the members of this type just like Type.FindMembers would
1551 /// Only, we need to use this for types which are _being_ defined because MS'
1552 /// implementation can't take care of that.
1555 // FIXME: return an empty static array instead of null, that cleans up
1556 // some code and is consistent with some coding conventions I just found
1560 // Notice that in various cases we check if our field is non-null,
1561 // something that would normally mean that there was a bug elsewhere.
1563 // The problem happens while we are defining p-invoke methods, as those
1564 // will trigger a FindMembers, but this happens before things are defined
1566 // Since the whole process is a no-op, it is fine to check for null here.
1568 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1569 MemberFilter filter, object criteria)
1571 ArrayList members = null;
1574 if ((bf & BindingFlags.Public) != 0)
1575 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1577 if ((bf & BindingFlags.NonPublic) != 0)
1578 modflags |= Modifiers.PRIVATE;
1580 int static_mask = 0, static_flags = 0;
1581 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1582 case BindingFlags.Static:
1583 static_mask = static_flags = Modifiers.STATIC;
1586 case BindingFlags.Instance:
1587 static_mask = Modifiers.STATIC;
1592 static_mask = static_flags = 0;
1596 Timer.StartTimer (TimerType.TcFindMembers);
1599 filter = accepting_filter;
1601 if ((mt & MemberTypes.Field) != 0) {
1602 if (fields != null) {
1603 int len = fields.Count;
1604 for (int i = 0; i < len; i++) {
1605 FieldMember f = (FieldMember) fields [i];
1607 if ((f.ModFlags & modflags) == 0)
1609 if ((f.ModFlags & static_mask) != static_flags)
1612 FieldBuilder fb = f.FieldBuilder;
1613 if (fb != null && filter (fb, criteria) == true) {
1614 if (members == null)
1615 members = new ArrayList ();
1622 if (constants != null) {
1623 int len = constants.Count;
1624 for (int i = 0; i < len; i++) {
1625 Const con = (Const) constants [i];
1627 if ((con.ModFlags & modflags) == 0)
1629 if ((con.ModFlags & static_mask) != static_flags)
1632 FieldBuilder fb = con.FieldBuilder;
1635 fb = con.FieldBuilder;
1637 if (fb != null && filter (fb, criteria) == true) {
1638 if (members == null)
1639 members = new ArrayList ();
1647 if ((mt & MemberTypes.Method) != 0) {
1648 if (methods != null) {
1649 int len = methods.Count;
1650 for (int i = 0; i < len; i++) {
1651 Method m = (Method) methods [i];
1653 if ((m.ModFlags & modflags) == 0)
1655 if ((m.ModFlags & static_mask) != static_flags)
1658 MethodBuilder mb = m.MethodBuilder;
1660 if (mb != null && filter (mb, criteria) == true) {
1661 if (members == null)
1662 members = new ArrayList ();
1669 if (operators != null) {
1670 int len = operators.Count;
1671 for (int i = 0; i < len; i++) {
1672 Operator o = (Operator) operators [i];
1674 if ((o.ModFlags & modflags) == 0)
1676 if ((o.ModFlags & static_mask) != static_flags)
1679 MethodBuilder ob = o.MethodBuilder;
1680 if (ob != null && filter (ob, criteria) == true) {
1681 if (members == null)
1682 members = new ArrayList ();
1689 if (events != null) {
1690 foreach (Event e in events) {
1691 if ((e.ModFlags & modflags) == 0)
1693 if ((e.ModFlags & static_mask) != static_flags)
1696 MethodBuilder b = e.AddBuilder;
1697 if (b != null && filter (b, criteria)) {
1698 if (members == null)
1699 members = new ArrayList (4);
1704 b = e.RemoveBuilder;
1705 if (b != null && filter (b, criteria)) {
1706 if (members == null)
1707 members = new ArrayList (4);
1714 if (properties != null) {
1715 int len = properties.Count;
1716 for (int i = 0; i < len; i++) {
1717 Property p = (Property) properties [i];
1719 if ((p.ModFlags & modflags) == 0)
1721 if ((p.ModFlags & static_mask) != static_flags)
1727 if (b != null && filter (b, criteria) == true) {
1728 if (members == null)
1729 members = new ArrayList ();
1735 if (b != null && filter (b, criteria) == true) {
1736 if (members == null)
1737 members = new ArrayList ();
1744 if (indexers != null) {
1745 int len = indexers.Count;
1746 for (int i = 0; i < len; i++) {
1747 Indexer ix = (Indexer) indexers [i];
1749 if ((ix.ModFlags & modflags) == 0)
1751 if ((ix.ModFlags & static_mask) != static_flags)
1757 if (b != null && filter (b, criteria) == true) {
1758 if (members == null)
1759 members = new ArrayList ();
1765 if (b != null && filter (b, criteria) == true) {
1766 if (members == null)
1767 members = new ArrayList ();
1775 if ((mt & MemberTypes.Event) != 0) {
1776 if (events != null) {
1777 int len = events.Count;
1778 for (int i = 0; i < len; i++) {
1779 Event e = (Event) events [i];
1781 if ((e.ModFlags & modflags) == 0)
1783 if ((e.ModFlags & static_mask) != static_flags)
1786 MemberInfo eb = e.EventBuilder;
1787 if (eb != null && filter (eb, criteria) == true) {
1788 if (members == null)
1789 members = new ArrayList ();
1791 members.Add (e.EventBuilder);
1797 if ((mt & MemberTypes.Property) != 0){
1798 if (properties != null) {
1799 int len = properties.Count;
1800 for (int i = 0; i < len; i++) {
1801 Property p = (Property) properties [i];
1803 if ((p.ModFlags & modflags) == 0)
1805 if ((p.ModFlags & static_mask) != static_flags)
1808 MemberInfo pb = p.PropertyBuilder;
1809 if (pb != null && filter (pb, criteria) == true) {
1810 if (members == null)
1811 members = new ArrayList ();
1813 members.Add (p.PropertyBuilder);
1818 if (indexers != null) {
1819 int len = indexers.Count;
1820 for (int i = 0; i < len; i++) {
1821 Indexer ix = (Indexer) indexers [i];
1823 if ((ix.ModFlags & modflags) == 0)
1825 if ((ix.ModFlags & static_mask) != static_flags)
1828 MemberInfo ib = ix.PropertyBuilder;
1829 if (ib != null && filter (ib, criteria) == true) {
1830 if (members == null)
1831 members = new ArrayList ();
1833 members.Add (ix.PropertyBuilder);
1839 if ((mt & MemberTypes.NestedType) != 0)
1840 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1842 if ((mt & MemberTypes.Constructor) != 0){
1843 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1844 int len = instance_constructors.Count;
1845 for (int i = 0; i < len; i++) {
1846 Constructor c = (Constructor) instance_constructors [i];
1848 ConstructorBuilder cb = c.ConstructorBuilder;
1849 if (cb != null && filter (cb, criteria) == true) {
1850 if (members == null)
1851 members = new ArrayList ();
1858 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1859 ConstructorBuilder cb =
1860 default_static_constructor.ConstructorBuilder;
1862 if (cb != null && filter (cb, criteria) == true) {
1863 if (members == null)
1864 members = new ArrayList ();
1872 // Lookup members in base if requested.
1874 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1875 if (TypeBuilder.BaseType != null) {
1876 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1877 if (list.Count > 0) {
1878 if (members == null)
1879 members = new ArrayList ();
1881 members.AddRange (list);
1884 if (ifaces != null) {
1885 foreach (Type base_type in ifaces) {
1886 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1888 if (list.Count > 0) {
1889 if (members == null)
1890 members = new ArrayList ();
1891 members.AddRange (list);
1897 Timer.StopTimer (TimerType.TcFindMembers);
1899 if (members == null)
1900 return MemberList.Empty;
1902 return new MemberList (members);
1905 public override MemberCache MemberCache {
1907 return member_cache;
1911 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1912 MemberFilter filter, object criteria)
1914 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1917 return ds.FindMembers (mt, bf, filter, criteria);
1919 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1923 /// Emits the values for the constants
1925 public void EmitConstants ()
1927 if (constants != null)
1928 foreach (Const con in constants)
1933 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
1938 foreach (MemberCore mc in al) {
1939 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1943 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1948 public virtual void VerifyMembers ()
1951 // Check for internal or private fields that were never assigned
1953 if (RootContext.WarningLevel >= 3) {
1954 CheckMemberUsage (properties, "property");
1955 CheckMemberUsage (methods, "method");
1956 CheckMemberUsage (constants, "constant");
1958 if (fields != null){
1959 foreach (FieldMember f in fields) {
1960 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1964 if ((f.caching_flags & Flags.IsAssigned) == 0)
1965 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1968 const int error_code = 414;
1970 const int error_code = 169;
1972 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1973 f.GetSignatureForError ());
1979 // Only report 649 on level 4
1981 if (RootContext.WarningLevel < 4)
1984 if ((f.caching_flags & Flags.IsAssigned) != 0)
1987 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1988 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
1994 // TODO: move to ClassOrStruct
1995 void EmitConstructors ()
1997 if (instance_constructors == null)
2000 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2001 bool has_compliant_args = false;
2003 foreach (Constructor c in instance_constructors) {
2006 if (has_compliant_args)
2009 has_compliant_args = c.HasCompliantArgs;
2011 if (!has_compliant_args)
2012 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2014 foreach (Constructor c in instance_constructors)
2020 /// Emits the code, this step is performed after all
2021 /// the types, enumerations, constructors
2023 public virtual void EmitType ()
2025 if (OptAttributes != null)
2026 OptAttributes.Emit ();
2029 // Structs with no fields need to have at least one byte.
2030 // The right thing would be to set the PackingSize in a DefineType
2031 // but there are no functions that allow interfaces *and* the size to
2035 if (Kind == Kind.Struct && first_nonstatic_field == null){
2036 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2037 FieldAttributes.Private);
2039 if (HasExplicitLayout){
2040 object [] ctor_args = new object [1];
2043 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2044 TypeManager.field_offset_attribute_ctor, ctor_args);
2045 fb.SetCustomAttribute (cba);
2051 EmitConstructors ();
2053 // Can not continue if constants are broken
2055 if (Report.Errors > 0)
2058 if (default_static_constructor != null)
2059 default_static_constructor.Emit ();
2061 if (methods != null){
2062 foreach (Method m in methods)
2066 if (operators != null)
2067 foreach (Operator o in operators)
2070 if (properties != null)
2071 foreach (Property p in properties)
2074 if (indexers != null){
2079 foreach (FieldMember f in fields)
2082 if (events != null){
2083 foreach (Event e in Events)
2087 if (delegates != null) {
2088 foreach (Delegate d in Delegates) {
2093 if (enums != null) {
2094 foreach (Enum e in enums) {
2099 if (pending != null)
2100 if (pending.VerifyPendingMethods ())
2103 if (iterators != null)
2104 foreach (Iterator iterator in iterators)
2105 iterator.EmitType ();
2108 public override void CloseType ()
2110 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2114 caching_flags |= Flags.CloseTypeCreated;
2115 TypeBuilder.CreateType ();
2116 } catch (TypeLoadException){
2118 // This is fine, the code still created the type
2120 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2121 // Console.WriteLine (e.Message);
2123 Console.WriteLine ("In type: " + Name);
2128 foreach (Enum en in Enums)
2132 foreach (TypeContainer tc in Types)
2133 if (tc.Kind == Kind.Struct)
2136 foreach (TypeContainer tc in Types)
2137 if (tc.Kind != Kind.Struct)
2141 if (Delegates != null)
2142 foreach (Delegate d in Delegates)
2145 if (Iterators != null)
2146 foreach (Iterator i in Iterators)
2154 initialized_fields = null;
2155 initialized_static_fields = null;
2163 default_constructor = null;
2164 default_static_constructor = null;
2166 OptAttributes = null;
2169 member_cache = null;
2173 // Performs the validation on a Method's modifiers (properties have
2174 // the same properties).
2176 public bool MethodModifiersValid (MemberCore mc)
2178 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2179 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2180 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2182 int flags = mc.ModFlags;
2185 // At most one of static, virtual or override
2187 if ((flags & Modifiers.STATIC) != 0){
2188 if ((flags & vao) != 0){
2189 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2190 mc.GetSignatureForError ());
2195 if (Kind == Kind.Struct){
2196 if ((flags & va) != 0){
2197 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2202 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2203 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2204 mc.GetSignatureForError ());
2209 // If the declaration includes the abstract modifier, then the
2210 // declaration does not include static, virtual or extern
2212 if ((flags & Modifiers.ABSTRACT) != 0){
2213 if ((flags & Modifiers.EXTERN) != 0){
2215 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2219 if ((flags & Modifiers.SEALED) != 0) {
2220 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2224 if ((flags & Modifiers.VIRTUAL) != 0){
2225 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2229 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2230 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2235 if ((flags & Modifiers.PRIVATE) != 0){
2236 if ((flags & vao) != 0){
2237 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2242 if ((flags & Modifiers.SEALED) != 0){
2243 if ((flags & Modifiers.OVERRIDE) == 0){
2244 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2252 public Constructor DefaultStaticConstructor {
2253 get { return default_static_constructor; }
2256 protected override bool VerifyClsCompliance ()
2258 if (!base.VerifyClsCompliance ())
2263 Type base_type = TypeBuilder.BaseType;
2264 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2265 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2268 if (!Parent.IsClsComplianceRequired ()) {
2269 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
2270 GetSignatureForError (), Parent.GetSignatureForError ());
2277 /// Checks whether container name is CLS Compliant
2279 void VerifyClsName ()
2281 Hashtable base_members = base_cache == null ?
2283 base_cache.GetPublicMembers ();
2284 Hashtable this_members = new Hashtable ();
2286 foreach (DictionaryEntry entry in defined_names) {
2287 MemberCore mc = (MemberCore)entry.Value;
2288 if (!mc.IsClsComplianceRequired ())
2291 string name = (string) entry.Key;
2292 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2294 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2295 object found = base_members [lcase];
2296 if (found == null) {
2297 found = this_members [lcase];
2298 if (found == null) {
2299 this_members.Add (lcase, mc);
2304 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2307 if (found is MemberInfo) {
2308 if (basename == ((MemberInfo) found).Name)
2310 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2312 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2314 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2320 /// Performs checks for an explicit interface implementation. First it
2321 /// checks whether the `interface_type' is a base inteface implementation.
2322 /// Then it checks whether `name' exists in the interface type.
2324 public virtual bool VerifyImplements (MemberBase mb)
2326 if (ifaces != null) {
2327 foreach (Type t in ifaces){
2328 if (t == mb.InterfaceType)
2333 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2334 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2335 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2339 public void Mark_HasEquals ()
2341 Methods.HasEquals = true;
2344 public void Mark_HasGetHashCode ()
2346 Methods.HasGetHashCode = true;
2353 string IMemberContainer.Name {
2359 Type IMemberContainer.Type {
2365 MemberCache IMemberContainer.MemberCache {
2367 return member_cache;
2371 bool IMemberContainer.IsInterface {
2373 return Kind == Kind.Interface;
2377 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2379 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2383 // Generates xml doc comments (if any), and if required,
2384 // handle warning report.
2386 internal override void GenerateDocComment (DeclSpace ds)
2388 DocUtil.GenerateTypeDocComment (this, ds);
2391 public override string DocCommentHeader {
2392 get { return "T:"; }
2395 public virtual MemberCache BaseCache {
2397 if (base_cache != null)
2399 if (TypeBuilder.BaseType != null)
2400 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2401 if (TypeBuilder.IsInterface)
2402 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2408 public abstract class ClassOrStruct : TypeContainer {
2409 ListDictionary declarative_security;
2411 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2412 MemberName name, Attributes attrs, Kind kind)
2413 : base (ns, parent, name, attrs, kind)
2417 protected override bool AddToContainer (MemberCore symbol, string name)
2419 if (name == Basename) {
2420 Report.SymbolRelatedToPreviousError (this);
2421 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2422 symbol.GetSignatureForError ());
2426 return base.AddToContainer (symbol, name);
2429 public override void VerifyMembers ()
2431 base.VerifyMembers ();
2433 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2434 foreach (Event e in events){
2435 if ((e.caching_flags & Flags.IsAssigned) == 0)
2436 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2441 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2443 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2444 if (declarative_security == null)
2445 declarative_security = new ListDictionary ();
2447 a.ExtractSecurityPermissionSet (declarative_security);
2451 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2452 HasExplicitLayout = true;
2455 base.ApplyAttributeBuilder (a, cb);
2459 /// Defines the default constructors
2461 protected void DefineDefaultConstructor (bool is_static)
2463 // The default instance constructor is public
2464 // If the class is abstract, the default constructor is protected
2465 // The default static constructor is private
2469 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2471 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2474 Constructor c = new Constructor (this, MemberName.Name, mods,
2475 Parameters.EmptyReadOnlyParameters,
2476 new GeneratedBaseInitializer (Location),
2480 c.Block = new ToplevelBlock (null, Location);
2483 void DefineFieldInitializers ()
2485 if (initialized_fields != null) {
2486 for (int i = 0; i < initialized_fields.Count; ++i) {
2487 FieldBase fb = (FieldBase)initialized_fields[i];
2488 fb.ResolveInitializer ();
2489 if (fb.HasDefaultInitializer && RootContext.Optimize) {
2490 // Field is re-initialized to its default value => removed
2491 initialized_fields.RemoveAt (i);
2497 if (initialized_static_fields != null) {
2498 bool has_complex_initializer = false;
2500 foreach (FieldBase fb in initialized_static_fields) {
2501 if (fb.ResolveInitializer () is Constant)
2504 has_complex_initializer = true;
2507 // Need special check to not optimize code like this
2508 // static int a = b = 5;
2509 // static int b = 0;
2510 if (!has_complex_initializer && RootContext.Optimize) {
2511 for (int i = 0; i < initialized_static_fields.Count; ++i) {
2512 FieldBase fb = (FieldBase)initialized_static_fields[i];
2513 if (fb.HasDefaultInitializer) {
2514 initialized_static_fields.RemoveAt (i);
2520 if (default_static_constructor == null && initialized_static_fields.Count > 0) {
2521 DefineDefaultConstructor (true);
2527 public override bool Define ()
2529 DefineFieldInitializers ();
2531 if (default_static_constructor != null)
2532 default_static_constructor.Define ();
2534 return base.Define ();
2537 public override void Emit ()
2541 if (declarative_security != null) {
2542 foreach (DictionaryEntry de in declarative_security) {
2543 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2548 protected override TypeAttributes TypeAttr {
2550 if (default_static_constructor == null)
2551 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2553 return base.TypeAttr;
2559 // TODO: should be sealed
2560 public class Class : ClassOrStruct {
2561 const int AllowedModifiers =
2564 Modifiers.PROTECTED |
2565 Modifiers.INTERNAL |
2567 Modifiers.ABSTRACT |
2572 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2574 : base (ns, parent, name, attrs, Kind.Class)
2576 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2577 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2579 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2580 Report.FeatureIsNotStandardized (Location, "static classes");
2584 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2586 if (a.Type == TypeManager.attribute_usage_type) {
2587 if (BaseType != TypeManager.attribute_type && !BaseType.IsSubclassOf (TypeManager.attribute_type) &&
2588 TypeBuilder.FullName != "System.Attribute") {
2589 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2593 if (a.Type == TypeManager.conditional_attribute_type &&
2594 !(BaseType == TypeManager.attribute_type || BaseType.IsSubclassOf (TypeManager.attribute_type))) {
2595 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2599 if (a.Type == TypeManager.comimport_attr_type &&
2600 !attributes.Contains (TypeManager.guid_attr_type)) {
2601 a.Error_MissingGuidAttribute ();
2605 if (AttributeTester.IsAttributeExcluded (a.Type))
2608 base.ApplyAttributeBuilder (a, cb);
2611 public override AttributeTargets AttributeTargets {
2613 return AttributeTargets.Class;
2617 protected override void DefineContainerMembers (MemberCoreArrayList list)
2623 base.DefineContainerMembers (list);
2627 foreach (MemberCore m in list) {
2628 if (m is Operator) {
2629 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2633 if (m is Destructor) {
2634 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2638 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2639 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
2644 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2648 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2651 if (m is Constructor) {
2652 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2656 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2659 base.DefineContainerMembers (list);
2662 public override TypeBuilder DefineType ()
2664 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2665 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2669 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2670 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2674 return base.DefineType ();
2677 protected override bool DoDefineMembers ()
2679 if (InstanceConstructors == null && !IsStatic)
2680 DefineDefaultConstructor (false);
2682 return base.DoDefineMembers ();
2685 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2687 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2689 if (base_class == null) {
2690 if (RootContext.StdLib)
2691 base_class = TypeManager.system_object_expr;
2692 else if (Name != "System.Object")
2693 base_class = TypeManager.system_object_expr;
2695 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
2696 Report.Error (1521, base_class.Location, "Invalid base type");
2700 if (base_class.IsSealed){
2701 Report.SymbolRelatedToPreviousError (base_class.Type);
2702 if (base_class.Type.IsAbstract) {
2703 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2704 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2706 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2707 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2712 if (!base_class.CanInheritFrom ()){
2713 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2714 GetSignatureForError (), base_class.GetSignatureForError ());
2718 if (!base_class.AsAccessible (this, ModFlags)) {
2719 Report.SymbolRelatedToPreviousError (base_class.Type);
2720 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2721 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2726 if (base_class != TypeManager.system_object_expr) {
2727 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2728 GetSignatureForError (), base_class.GetSignatureForError ());
2732 if (ifaces != null) {
2733 foreach (TypeExpr t in ifaces)
2734 Report.SymbolRelatedToPreviousError (t.Type);
2735 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2742 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2743 /// Valid only for attribute classes.
2744 public bool IsExcluded ()
2746 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2747 return (caching_flags & Flags.Excluded) != 0;
2749 caching_flags &= ~Flags.Excluded_Undetected;
2751 if (OptAttributes == null)
2754 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2759 foreach (Attribute a in attrs) {
2760 string condition = a.GetConditionalAttributeValue ();
2761 if (RootContext.AllDefines.Contains (condition))
2765 caching_flags |= Flags.Excluded;
2771 return (ModFlags & Modifiers.STATIC) != 0;
2776 // FIXME: How do we deal with the user specifying a different
2779 protected override TypeAttributes TypeAttr {
2781 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2783 ta |= TypeAttributes.Abstract | TypeAttributes.Sealed;
2789 public sealed class Struct : ClassOrStruct {
2791 // Modifiers allowed in a struct declaration
2793 const int AllowedModifiers =
2796 Modifiers.PROTECTED |
2797 Modifiers.INTERNAL |
2801 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2802 int mod, Attributes attrs)
2803 : base (ns, parent, name, attrs, Kind.Struct)
2807 if (parent.Parent == null)
2808 accmods = Modifiers.INTERNAL;
2810 accmods = Modifiers.PRIVATE;
2812 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2814 this.ModFlags |= Modifiers.SEALED;
2817 public override AttributeTargets AttributeTargets {
2819 return AttributeTargets.Struct;
2823 const TypeAttributes DefaultTypeAttributes =
2824 TypeAttributes.SequentialLayout |
2825 TypeAttributes.Sealed |
2826 TypeAttributes.BeforeFieldInit;
2829 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2831 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2833 // If we are compiling our runtime,
2834 // and we are defining ValueType, then our
2835 // base is `System.Object'.
2837 if (base_class == null) {
2838 if (!RootContext.StdLib && Name == "System.ValueType")
2839 base_class = TypeManager.system_object_expr;
2841 base_class = TypeManager.system_valuetype_expr;
2848 // FIXME: Allow the user to specify a different set of attributes
2849 // in some cases (Sealed for example is mandatory for a class,
2850 // but what SequentialLayout can be changed
2852 protected override TypeAttributes TypeAttr {
2854 return base.TypeAttr | DefaultTypeAttributes;
2858 public override void RegisterFieldForInitialization (FieldBase field)
2860 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2861 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2862 field.GetSignatureForError ());
2865 base.RegisterFieldForInitialization (field);
2873 public sealed class Interface : TypeContainer, IMemberContainer {
2876 /// Modifiers allowed in a class declaration
2878 public const int AllowedModifiers =
2881 Modifiers.PROTECTED |
2882 Modifiers.INTERNAL |
2886 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2888 : base (ns, parent, name, attrs, Kind.Interface)
2892 if (parent.Parent == null)
2893 accmods = Modifiers.INTERNAL;
2895 accmods = Modifiers.PRIVATE;
2897 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
2900 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2902 if (a.Type == TypeManager.comimport_attr_type &&
2903 !attributes.Contains (TypeManager.guid_attr_type)) {
2904 a.Error_MissingGuidAttribute ();
2907 base.ApplyAttributeBuilder (a, cb);
2911 public override AttributeTargets AttributeTargets {
2913 return AttributeTargets.Interface;
2917 const TypeAttributes DefaultTypeAttributes =
2918 TypeAttributes.AutoLayout |
2919 TypeAttributes.Abstract |
2920 TypeAttributes.Interface;
2922 protected override TypeAttributes TypeAttr {
2924 return base.TypeAttr | DefaultTypeAttributes;
2928 protected override bool VerifyClsCompliance ()
2930 if (!base.VerifyClsCompliance ())
2933 if (ifaces != null) {
2934 foreach (Type t in ifaces) {
2935 if (AttributeTester.IsClsCompliant (t))
2938 Report.SymbolRelatedToPreviousError (t);
2939 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2940 GetSignatureForError (), TypeManager.CSharpName (t));
2948 public abstract class MethodCore : MemberBase {
2949 public readonly Parameters Parameters;
2950 protected ToplevelBlock block;
2953 // The method we're overriding if this is an override method.
2955 protected MethodInfo base_method = null;
2957 public MethodCore (DeclSpace parent, Expression type, int mod,
2958 int allowed_mod, bool is_interface, MemberName name,
2959 Attributes attrs, Parameters parameters)
2960 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
2963 Parameters = parameters;
2964 IsInterface = is_interface;
2968 // Returns the System.Type array for the parameters of this method
2970 public Type [] ParameterTypes {
2972 return Parameters.Types;
2976 public Parameters ParameterInfo
2983 public ToplevelBlock Block {
2993 public void SetYields ()
2995 ModFlags |= Modifiers.METHOD_YIELDS;
2998 protected override bool CheckBase ()
3000 if (!base.CheckBase ())
3003 // Check whether arguments were correct.
3004 if (!DoDefineParameters ())
3007 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3013 // Is null for System.Object while compiling corlib and base interfaces
3014 if (ParentContainer.BaseCache == null) {
3015 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3016 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3021 Type base_ret_type = null;
3022 base_method = FindOutBaseMethod (ref base_ret_type);
3024 // method is override
3025 if (base_method != null) {
3027 if (!CheckMethodAgainstBase ())
3030 if ((ModFlags & Modifiers.NEW) == 0) {
3031 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3032 Report.SymbolRelatedToPreviousError (base_method);
3033 if (this is PropertyBase) {
3034 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3035 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3038 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3039 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3044 if (base_method.IsAbstract && !IsInterface) {
3045 Report.SymbolRelatedToPreviousError (base_method);
3046 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3047 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3052 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3053 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3057 if (Name == "Equals" && Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type)
3058 ParentContainer.Mark_HasEquals ();
3059 else if (Name == "GetHashCode" && Parameters.Empty)
3060 ParentContainer.Mark_HasGetHashCode ();
3062 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3063 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3065 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3066 Report.SymbolRelatedToPreviousError (base_method);
3067 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3068 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3075 MemberInfo conflict_symbol = ParentContainer.FindBaseMemberWithSameName (Name, !(this is Property));
3076 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3077 if (conflict_symbol != null) {
3078 Report.SymbolRelatedToPreviousError (conflict_symbol);
3079 if (this is PropertyBase)
3080 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3082 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3084 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3088 if (conflict_symbol == null) {
3089 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3090 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3095 if ((ModFlags & Modifiers.NEW) == 0) {
3096 if (this is Method && conflict_symbol is MethodBase)
3099 Report.SymbolRelatedToPreviousError (conflict_symbol);
3100 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3101 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3108 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3109 // that have been defined.
3111 // `name' is the user visible name for reporting errors (this is used to
3112 // provide the right name regarding method names and properties)
3114 bool CheckMethodAgainstBase ()
3118 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3119 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3120 Report.Error (506, Location,
3121 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3122 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3126 // Now we check that the overriden method is not final
3128 if (base_method.IsFinal) {
3129 Report.SymbolRelatedToPreviousError (base_method);
3130 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3131 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3135 // Check that the permissions are not being changed
3137 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3138 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3140 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3141 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3146 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3147 ModFlags |= Modifiers.NEW;
3148 Report.SymbolRelatedToPreviousError (base_method);
3149 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3150 Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
3151 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3153 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3154 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3161 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3163 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3165 // when overriding protected internal, the method can be declared
3166 // protected internal only within the same assembly
3169 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3170 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3172 // assemblies differ - report an error
3176 } else if (thisp != base_classp) {
3178 // same assembly, but other attributes differ - report an error
3183 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3185 // if it's not "protected internal", it must be "protected"
3189 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3191 // protected within the same assembly - an error
3194 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3195 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3197 // protected ok, but other attributes differ - report an error
3203 return (thisp == base_classp);
3207 public bool CheckAbstractAndExtern (bool has_block)
3209 if (ParentContainer.Kind == Kind.Interface)
3213 if ((ModFlags & Modifiers.EXTERN) != 0) {
3214 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3215 GetSignatureForError ());
3219 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3220 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3221 GetSignatureForError ());
3225 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3226 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3227 GetSignatureForError ());
3235 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3237 Report.SymbolRelatedToPreviousError (base_method);
3238 string base_name = TypeManager.GetFullNameSignature (base_method);
3239 string this_name = GetSignatureForError ();
3240 if (suffix != null) {
3241 base_name += suffix;
3242 this_name += suffix;
3245 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3246 this_name, Modifiers.GetDescription (ma), base_name);
3249 protected static string Error722 {
3251 return "`{0}': static types cannot be used as return types";
3256 /// For custom member duplication search in a container
3258 protected abstract bool CheckForDuplications ();
3261 /// Gets base method and its return type
3263 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3265 protected bool DoDefineParameters ()
3267 // Check if arguments were correct
3268 if (!Parameters.Resolve (this))
3271 return CheckParameters (ParameterTypes);
3274 bool CheckParameters (Type [] parameters)
3277 DeclSpace ds = Parent;
3279 foreach (Type partype in parameters){
3280 if (partype == TypeManager.void_type) {
3282 1547, Location, "Keyword 'void' cannot " +
3283 "be used in this context");
3287 if (partype.IsPointer){
3288 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3292 if (ds.AsAccessible (partype, ModFlags))
3295 Report.SymbolRelatedToPreviousError (partype);
3296 if (this is Indexer)
3297 Report.Error (55, Location,
3298 "Inconsistent accessibility: parameter type `" +
3299 TypeManager.CSharpName (partype) + "' is less " +
3300 "accessible than indexer `" + GetSignatureForError () + "'");
3301 else if (this is Operator)
3302 Report.Error (57, Location,
3303 "Inconsistent accessibility: parameter type `" +
3304 TypeManager.CSharpName (partype) + "' is less " +
3305 "accessible than operator `" + GetSignatureForError () + "'");
3307 Report.Error (51, Location,
3308 "Inconsistent accessibility: parameter type `" +
3309 TypeManager.CSharpName (partype) + "' is less " +
3310 "accessible than method `" + GetSignatureForError () + "'");
3317 protected override bool VerifyClsCompliance ()
3319 if (!base.VerifyClsCompliance ()) {
3320 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3321 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3326 if (Parameters.HasArglist) {
3327 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3330 if (!AttributeTester.IsClsCompliant (MemberType)) {
3331 if (this is PropertyBase)
3332 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3333 GetSignatureForError ());
3335 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3336 GetSignatureForError ());
3339 Parameters.VerifyClsCompliance ();
3344 protected bool IsDuplicateImplementation (MethodCore method)
3346 if (method == this || !(method.MemberName.Equals (MemberName)))
3349 Type[] param_types = method.ParameterTypes;
3350 // This never happen. Rewrite this as Equal
3351 if (param_types == null && ParameterTypes == null)
3353 if (param_types == null || ParameterTypes == null)
3356 if (param_types.Length != ParameterTypes.Length)
3359 if (method.Parameters.HasArglist != Parameters.HasArglist)
3362 for (int i = 0; i < param_types.Length; i++)
3363 if (param_types [i] != ParameterTypes [i])
3366 // TODO: make operator compatible with MethodCore to avoid this
3367 if (this is Operator && method is Operator) {
3368 if (MemberType != method.MemberType)
3373 // Try to report 663: method only differs on out/ref
3375 Parameters info = ParameterInfo;
3376 Parameters other_info = method.ParameterInfo;
3377 for (int i = 0; i < info.Count; i++){
3378 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3379 Report.SymbolRelatedToPreviousError (method);
3380 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3381 GetSignatureForError ());
3386 Report.SymbolRelatedToPreviousError (method);
3387 if (this is Operator && method is Operator)
3388 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3390 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3394 public override bool IsUsed {
3395 get { return IsExplicitImpl || base.IsUsed; }
3399 // Returns a string that represents the signature for this
3400 // member which should be used in XML documentation.
3402 public override string GetDocCommentName (DeclSpace ds)
3404 return DocUtil.GetMethodDocCommentName (this, ds);
3408 // Raised (and passed an XmlElement that contains the comment)
3409 // when GenerateDocComment is writing documentation expectedly.
3411 // FIXME: with a few effort, it could be done with XmlReader,
3412 // that means removal of DOM use.
3414 internal override void OnGenerateDocComment (XmlElement el)
3416 DocUtil.OnMethodGenerateDocComment (this, el);
3420 // Represents header string for documentation comment.
3422 public override string DocCommentHeader {
3423 get { return "M:"; }
3428 public abstract class MethodOrOperator : MethodCore, IMethodData
3430 public MethodBuilder MethodBuilder;
3431 ReturnParameter return_attributes;
3432 ListDictionary declarative_security;
3433 protected MethodData MethodData;
3435 static string[] attribute_targets = new string [] { "method", "return" };
3437 protected MethodOrOperator (DeclSpace parent, Expression type, int mod,
3438 int allowed_mod, bool is_interface, MemberName name,
3439 Attributes attrs, Parameters parameters)
3440 : base (parent, type, mod, allowed_mod, is_interface, name,
3445 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3447 if (a.Target == AttributeTargets.ReturnValue) {
3448 if (return_attributes == null)
3449 return_attributes = new ReturnParameter (MethodBuilder, Location);
3451 return_attributes.ApplyAttributeBuilder (a, cb);
3455 if (a.Type == TypeManager.methodimpl_attr_type &&
3456 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3457 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3460 if (a.Type == TypeManager.dllimport_type) {
3461 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3462 if ((ModFlags & extern_static) != extern_static) {
3463 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3469 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3470 if (declarative_security == null)
3471 declarative_security = new ListDictionary ();
3472 a.ExtractSecurityPermissionSet (declarative_security);
3476 MethodBuilder.SetCustomAttribute (cb);
3479 public override AttributeTargets AttributeTargets {
3481 return AttributeTargets.Method;
3485 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
3487 EmitContext ec = new EmitContext (this, ds, Parent, Location, ig, MemberType, ModFlags, false);
3489 ec.CurrentIterator = ds as Iterator;
3490 if (ec.CurrentIterator != null)
3491 ec.CurrentAnonymousMethod = ec.CurrentIterator.Host;
3496 public override bool Define ()
3501 if (!CheckAbstractAndExtern (block != null))
3507 MethodData = new MethodData (this, ModFlags, flags, this);
3509 if (!MethodData.Define (ParentContainer))
3512 MethodBuilder = MethodData.MethodBuilder;
3514 if (MemberType.IsAbstract && MemberType.IsSealed) {
3515 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3522 public override void Emit ()
3524 if (OptAttributes != null)
3525 OptAttributes.Emit ();
3527 if (declarative_security != null) {
3528 foreach (DictionaryEntry de in declarative_security) {
3529 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3536 protected void Error_ConditionalAttributeIsNotValid ()
3538 Report.Error (577, Location,
3539 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3540 GetSignatureForError ());
3543 public override bool MarkForDuplicationCheck ()
3545 caching_flags |= Flags.TestMethodDuplication;
3549 public override string[] ValidAttributeTargets {
3551 return attribute_targets;
3555 #region IMethodData Members
3557 public CallingConventions CallingConventions {
3559 CallingConventions cc = Parameters.CallingConvention;
3560 if (Parameters.HasArglist)
3561 block.HasVarargs = true;
3564 if ((ModFlags & Modifiers.STATIC) == 0)
3565 cc |= CallingConventions.HasThis;
3567 // FIXME: How is `ExplicitThis' used in C#?
3573 public Type ReturnType {
3579 public MemberName MethodName {
3585 public new Location Location {
3587 return base.Location;
3591 protected override bool CheckBase() {
3592 if (!base.CheckBase ())
3595 // TODO: Destructor should derive from MethodCore
3596 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3597 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3598 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3606 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3608 public bool IsExcluded () {
3609 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3610 return (caching_flags & Flags.Excluded) != 0;
3612 caching_flags &= ~Flags.Excluded_Undetected;
3614 if (base_method == null) {
3615 if (OptAttributes == null)
3618 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3623 foreach (Attribute a in attrs) {
3624 string condition = a.GetConditionalAttributeValue ();
3625 if (condition == null)
3628 if (RootContext.AllDefines.Contains (condition))
3632 caching_flags |= Flags.Excluded;
3636 IMethodData md = TypeManager.GetMethod (base_method);
3638 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
3639 caching_flags |= Flags.Excluded;
3645 if (md.IsExcluded ()) {
3646 caching_flags |= Flags.Excluded;
3656 public class SourceMethod : ISourceMethod
3661 protected SourceMethod (DeclSpace parent, MethodBase builder,
3662 ISourceFile file, Location start, Location end)
3664 this.parent = parent;
3665 this.builder = builder;
3667 CodeGen.SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
3670 public string Name {
3671 get { return builder.Name; }
3674 public int NamespaceID {
3675 get { return parent.NamespaceEntry.SymbolFileID; }
3680 if (builder is MethodBuilder)
3681 return ((MethodBuilder) builder).GetToken ().Token;
3682 else if (builder is ConstructorBuilder)
3683 return ((ConstructorBuilder) builder).GetToken ().Token;
3685 throw new NotSupportedException ();
3689 public void CloseMethod ()
3691 if (CodeGen.SymbolWriter != null)
3692 CodeGen.SymbolWriter.CloseMethod ();
3695 public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
3697 if (CodeGen.SymbolWriter == null)
3702 Location start_loc = block.StartLocation;
3703 if (start_loc.IsNull)
3706 Location end_loc = block.EndLocation;
3710 ISourceFile file = start_loc.SourceFile;
3714 return new SourceMethod (
3715 parent, builder, file, start_loc, end_loc);
3719 public class Method : MethodOrOperator, IIteratorContainer {
3722 /// Modifiers allowed in a class declaration
3724 const int AllowedModifiers =
3727 Modifiers.PROTECTED |
3728 Modifiers.INTERNAL |
3733 Modifiers.OVERRIDE |
3734 Modifiers.ABSTRACT |
3736 Modifiers.METHOD_YIELDS |
3739 const int AllowedInterfaceModifiers =
3740 Modifiers.NEW | Modifiers.UNSAFE;
3743 // return_type can be "null" for VOID values.
3745 public Method (DeclSpace parent, Expression return_type, int mod, bool is_iface,
3746 MemberName name, Parameters parameters, Attributes attrs)
3747 : base (parent, return_type, mod,
3748 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3749 is_iface, name, attrs, parameters)
3753 public override string GetSignatureForError()
3755 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3758 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
3760 Report.Error (17, location,
3761 "Program `{0}' has more than one entry point defined: `{1}'",
3762 CodeGen.FileName, TypeManager.CSharpSignature(b));
3765 bool IsEntryPoint (MethodBuilder b, Parameters pinfo)
3767 if (b.ReturnType != TypeManager.void_type &&
3768 b.ReturnType != TypeManager.int32_type)
3771 if (pinfo.Count == 0)
3774 if (pinfo.Count > 1)
3777 Type t = pinfo.ParameterType(0);
3779 (t.GetArrayRank() == 1) &&
3780 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3781 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3787 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3789 if (a.Type == TypeManager.conditional_attribute_type) {
3790 if (IsExplicitImpl) {
3791 Error_ConditionalAttributeIsNotValid ();
3795 if (ReturnType != TypeManager.void_type) {
3796 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
3800 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3801 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
3806 Report.Error (582, Location, "Conditional not valid on interface members");
3810 if (MethodData.implementing != null) {
3811 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
3812 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
3816 for (int i = 0; i < ParameterInfo.Count; ++i) {
3817 if ((ParameterInfo.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
3818 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
3824 base.ApplyAttributeBuilder (a, cb);
3827 protected override bool CheckForDuplications ()
3829 ArrayList ar = ParentContainer.Methods;
3831 int arLen = ar.Count;
3833 for (int i = 0; i < arLen; i++) {
3834 Method m = (Method) ar [i];
3835 if (IsDuplicateImplementation (m))
3840 ar = ParentContainer.Properties;
3842 for (int i = 0; i < ar.Count; ++i) {
3843 PropertyBase pb = (PropertyBase) ar [i];
3844 if (pb.AreAccessorsDuplicateImplementation (this))
3849 ar = ParentContainer.Indexers;
3851 for (int i = 0; i < ar.Count; ++i) {
3852 PropertyBase pb = (PropertyBase) ar [i];
3853 if (pb.AreAccessorsDuplicateImplementation (this))
3858 ar = ParentContainer.Events;
3860 for (int i = 0; i < ar.Count; ++i) {
3861 Event ev = (Event) ar [i];
3862 if (ev.AreAccessorsDuplicateImplementation (this))
3873 public override bool Define ()
3875 if (!base.Define ())
3878 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3879 Error1599 (Location, ReturnType);
3883 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3884 Name == "Finalize" && !(this is Destructor)) {
3885 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3889 // Setup iterator if we are one
3891 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3892 Iterator iterator = new Iterator (this,
3896 if (!iterator.DefineIterator ())
3901 // This is used to track the Entry Point,
3903 if (Name == "Main" &&
3904 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3905 (RootContext.MainClass == null ||
3906 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3907 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3908 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3909 md.SetMemberIsUsed ();
3911 if (RootContext.EntryPoint == null) {
3912 if (Parent.IsGeneric){
3913 Report.Error (-201, Location,
3914 "Entry point can not be defined in a generic class");
3917 RootContext.EntryPoint = MethodBuilder;
3918 RootContext.EntryPointLocation = Location;
3920 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3921 Error_DuplicateEntryPoint (MethodBuilder, Location);
3924 if (RootContext.WarningLevel >= 4)
3925 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3935 public override void Emit ()
3937 MethodData.Emit (Parent);
3944 public static void Error1599 (Location loc, Type t)
3946 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
3949 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
3951 MethodInfo mi = (MethodInfo) ParentContainer.BaseCache.FindMemberToOverride (
3952 Parent.TypeBuilder, Name, ParameterTypes, false);
3957 if (mi.IsSpecialName)
3960 base_ret_type = mi.ReturnType;
3964 protected override bool VerifyClsCompliance ()
3966 if (!base.VerifyClsCompliance ())
3969 if (ParameterInfo.Count > 0) {
3970 ArrayList al = (ArrayList)ParentContainer.MemberCache.Members [Name];
3972 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3979 public abstract class ConstructorInitializer {
3980 ArrayList argument_list;
3981 protected ConstructorInfo base_constructor;
3984 public ConstructorInitializer (ArrayList argument_list, Location loc)
3986 this.argument_list = argument_list;
3990 public ArrayList Arguments {
3992 return argument_list;
3996 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
3998 Expression base_constructor_group;
4002 ec.CurrentBlock = block;
4004 if (argument_list != null){
4005 foreach (Argument a in argument_list){
4006 if (!a.Resolve (ec, loc))
4010 ec.CurrentBlock = null;
4012 if (this is ConstructorBaseInitializer) {
4013 if (ec.ContainerType.BaseType == null)
4016 t = ec.ContainerType.BaseType;
4017 if (ec.ContainerType.IsValueType) {
4018 Report.Error (522, loc,
4019 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4023 t = ec.ContainerType;
4025 base_constructor_group = Expression.MemberLookup (
4026 ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
4027 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4030 if (base_constructor_group == null){
4032 base_constructor_group = Expression.MemberLookup (
4033 t, null, t, ".ctor", MemberTypes.Constructor,
4034 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4038 int errors = Report.Errors;
4039 if (base_constructor_group != null)
4040 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4041 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4044 if (base_constructor == null) {
4045 if (errors == Report.Errors)
4046 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4047 argument_list == null ? 0 : argument_list.Count);
4052 Report.SymbolRelatedToPreviousError (base_constructor);
4053 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4054 base_constructor = null;
4058 if (base_constructor == caller_builder){
4059 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4066 public virtual void Emit (EmitContext ec)
4068 if (base_constructor != null){
4069 ec.Mark (loc, false);
4071 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4073 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4078 public class ConstructorBaseInitializer : ConstructorInitializer {
4079 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4080 base (argument_list, l)
4085 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4086 public GeneratedBaseInitializer (Location loc):
4092 public class ConstructorThisInitializer : ConstructorInitializer {
4093 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4094 base (argument_list, l)
4099 public class Constructor : MethodCore, IMethodData {
4100 public ConstructorBuilder ConstructorBuilder;
4101 public ConstructorInitializer Initializer;
4102 ListDictionary declarative_security;
4105 // Modifiers allowed for a constructor.
4107 public const int AllowedModifiers =
4109 Modifiers.PROTECTED |
4110 Modifiers.INTERNAL |
4116 static string[] attribute_targets = new string [] { "method" };
4118 bool has_compliant_args = false;
4120 // The spec claims that static is not permitted, but
4121 // my very own code has static constructors.
4123 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4124 ConstructorInitializer init, Location loc)
4125 : base (parent, null, mod, AllowedModifiers, false, new MemberName (name, loc),
4131 public bool HasCompliantArgs {
4132 get { return has_compliant_args; }
4135 public override AttributeTargets AttributeTargets {
4136 get { return AttributeTargets.Constructor; }
4141 // Returns true if this is a default constructor
4143 public bool IsDefault ()
4145 if ((ModFlags & Modifiers.STATIC) != 0)
4146 return Parameters.Empty;
4148 return Parameters.Empty &&
4149 (Initializer is ConstructorBaseInitializer) &&
4150 (Initializer.Arguments == null);
4153 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4155 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4156 if (declarative_security == null) {
4157 declarative_security = new ListDictionary ();
4159 a.ExtractSecurityPermissionSet (declarative_security);
4163 if (a.Type == TypeManager.methodimpl_attr_type &&
4164 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4165 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4168 ConstructorBuilder.SetCustomAttribute (cb);
4171 protected override bool CheckForDuplications ()
4173 ArrayList ar = ParentContainer.InstanceConstructors;
4175 int arLen = ar.Count;
4177 for (int i = 0; i < arLen; i++) {
4178 Constructor m = (Constructor) ar [i];
4179 if (IsDuplicateImplementation (m))
4186 protected override bool CheckBase ()
4188 if ((ModFlags & Modifiers.STATIC) != 0) {
4189 if (!Parameters.Empty) {
4190 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4191 GetSignatureForError ());
4195 // the rest can be ignored
4199 // Check whether arguments were correct.
4200 if (!DoDefineParameters ())
4203 if (!CheckForDuplications ())
4206 if (ParentContainer.Kind == Kind.Struct) {
4207 if (ParameterTypes.Length == 0) {
4208 Report.Error (568, Location,
4209 "Structs cannot contain explicit parameterless constructors");
4213 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4214 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4219 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4220 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4227 // Creates the ConstructorBuilder
4229 public override bool Define ()
4231 if (ConstructorBuilder != null)
4234 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4235 MethodAttributes.SpecialName);
4237 if ((ModFlags & Modifiers.STATIC) != 0) {
4238 ca |= MethodAttributes.Static | MethodAttributes.Private;
4240 ca |= MethodAttributes.HideBySig;
4242 if ((ModFlags & Modifiers.PUBLIC) != 0)
4243 ca |= MethodAttributes.Public;
4244 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4245 if ((ModFlags & Modifiers.INTERNAL) != 0)
4246 ca |= MethodAttributes.FamORAssem;
4248 ca |= MethodAttributes.Family;
4249 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4250 ca |= MethodAttributes.Assembly;
4252 ca |= MethodAttributes.Private;
4255 if (!CheckAbstractAndExtern (block != null))
4258 // Check if arguments were correct.
4262 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4263 ca, CallingConventions,
4266 if ((ModFlags & Modifiers.UNSAFE) != 0)
4267 ConstructorBuilder.InitLocals = false;
4269 if (ParentContainer.IsComImport) {
4270 if (!IsDefault ()) {
4271 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4272 Parent.GetSignatureForError ());
4275 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4278 TypeManager.AddMethod (ConstructorBuilder, this);
4286 public override void Emit ()
4288 if (OptAttributes != null)
4289 OptAttributes.Emit ();
4291 EmitContext ec = CreateEmitContext (null, null);
4293 if (block != null) {
4294 // If this is a non-static `struct' constructor and doesn't have any
4295 // initializer, it must initialize all of the struct's fields.
4296 if ((ParentContainer.Kind == Kind.Struct) &&
4297 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4298 block.AddThisVariable (Parent, Location);
4300 if (!block.ResolveMeta (ec, ParameterInfo))
4304 if ((ModFlags & Modifiers.STATIC) == 0){
4305 if (ParentContainer.Kind == Kind.Class && Initializer == null)
4306 Initializer = new GeneratedBaseInitializer (Location);
4310 // Spec mandates that Initializers will not have
4314 if ((Initializer != null) &&
4315 !Initializer.Resolve (ConstructorBuilder, block, ec))
4317 ec.IsStatic = false;
4320 Parameters.ApplyAttributes (ConstructorBuilder);
4322 SourceMethod source = SourceMethod.Create (
4323 Parent, ConstructorBuilder, block);
4326 // Classes can have base initializers and instance field initializers.
4328 if (ParentContainer.Kind == Kind.Class){
4329 if ((ModFlags & Modifiers.STATIC) == 0){
4332 // If we use a "this (...)" constructor initializer, then
4333 // do not emit field initializers, they are initialized in the other constructor
4335 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4336 ParentContainer.EmitFieldInitializers (ec);
4339 if (Initializer != null) {
4340 Initializer.Emit (ec);
4343 if ((ModFlags & Modifiers.STATIC) != 0)
4344 ParentContainer.EmitFieldInitializers (ec);
4346 ec.EmitTopBlock (this, block);
4349 source.CloseMethod ();
4353 if (declarative_security != null) {
4354 foreach (DictionaryEntry de in declarative_security) {
4355 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4362 // Is never override
4363 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4368 public override string GetSignatureForError()
4370 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4373 public override string[] ValidAttributeTargets {
4375 return attribute_targets;
4379 protected override bool VerifyClsCompliance ()
4381 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4385 if (ParameterInfo.Count > 0) {
4386 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4388 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4390 if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4391 foreach (Type param in ParameterTypes) {
4392 if (param.IsArray) {
4398 has_compliant_args = true;
4402 #region IMethodData Members
4404 public System.Reflection.CallingConventions CallingConventions {
4406 CallingConventions cc = Parameters.CallingConvention;
4408 if (ParentContainer.Kind == Kind.Class)
4409 if ((ModFlags & Modifiers.STATIC) == 0)
4410 cc |= CallingConventions.HasThis;
4412 // FIXME: How is `ExplicitThis' used in C#?
4418 public new Location Location {
4420 return base.Location;
4424 public MemberName MethodName {
4430 public Type ReturnType {
4436 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4438 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4439 return new EmitContext (this, Parent, Location, ig_, null, ModFlags, true);
4442 public bool IsExcluded()
4451 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4453 public interface IMethodData
4455 CallingConventions CallingConventions { get; }
4456 Location Location { get; }
4457 MemberName MethodName { get; }
4458 Type ReturnType { get; }
4459 Parameters ParameterInfo { get; }
4461 Attributes OptAttributes { get; }
4462 ToplevelBlock Block { get; set; }
4464 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4465 ObsoleteAttribute GetObsoleteAttribute ();
4466 string GetSignatureForError ();
4468 bool IsClsComplianceRequired ();
4469 void SetMemberIsUsed ();
4473 // Encapsulates most of the Method's state
4475 public class MethodData {
4477 readonly IMethodData method;
4480 // Are we implementing an interface ?
4482 public MethodInfo implementing;
4487 protected MemberBase member;
4488 protected int modifiers;
4489 protected MethodAttributes flags;
4491 MethodBuilder builder = null;
4492 public MethodBuilder MethodBuilder {
4498 public MethodData (MemberBase member,
4499 int modifiers, MethodAttributes flags, IMethodData method)
4501 this.member = member;
4502 this.modifiers = modifiers;
4505 this.method = method;
4508 public bool Define (DeclSpace parent)
4510 string name = method.MethodName.Name;
4511 string method_name = name;
4513 TypeContainer container = ((TypeContainer) parent).PartialContainer;
4515 PendingImplementation pending = container.PendingImplementations;
4516 if (pending != null){
4517 if (member is Indexer) // TODO: test it, but it should work without this IF
4518 implementing = pending.IsInterfaceIndexer (
4519 member.InterfaceType, method.ReturnType, method.ParameterInfo);
4521 implementing = pending.IsInterfaceMethod (
4522 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
4524 if (member.InterfaceType != null){
4525 if (implementing == null){
4526 if (member is PropertyBase) {
4527 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4528 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4529 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4532 Report.Error (539, method.Location,
4533 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4534 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4538 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4539 Report.SymbolRelatedToPreviousError (implementing);
4540 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4541 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4544 method_name = member.InterfaceType.FullName + "." + name;
4546 if (implementing != null) {
4547 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4548 if (prop_method == null) {
4549 if (implementing.IsSpecialName) {
4550 Report.SymbolRelatedToPreviousError (implementing);
4551 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4552 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4553 implementing.Name.StartsWith ("get_") ? "get" : "set");
4556 } else if (implementing.DeclaringType.IsInterface) {
4557 if (!implementing.IsSpecialName) {
4558 Report.SymbolRelatedToPreviousError (implementing);
4559 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4560 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4563 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4564 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4565 Report.SymbolRelatedToPreviousError (implementing);
4566 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4567 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4576 // For implicit implementations, make sure we are public, for
4577 // explicit implementations, make sure we are private.
4579 if (implementing != null){
4581 // Setting null inside this block will trigger a more
4582 // verbose error reporting for missing interface implementations
4584 // The "candidate" function has been flagged already
4585 // but it wont get cleared
4587 if (member.IsExplicitImpl){
4588 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4589 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4590 implementing = null;
4592 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
4593 Report.SymbolRelatedToPreviousError (implementing);
4594 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
4595 method.GetSignatureForError ());
4598 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4599 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4601 // If this is an interface method implementation,
4602 // check for public accessibility
4604 implementing = null;
4605 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4606 // We may never be private.
4607 implementing = null;
4608 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4610 // We may be protected if we're overriding something.
4612 implementing = null;
4617 // Static is not allowed
4619 if ((modifiers & Modifiers.STATIC) != 0){
4620 implementing = null;
4625 // If implementing is still valid, set flags
4627 if (implementing != null){
4629 // When implementing interface methods, set NewSlot
4630 // unless, we are overwriting a method.
4632 if (implementing.DeclaringType.IsInterface){
4633 if ((modifiers & Modifiers.OVERRIDE) == 0)
4634 flags |= MethodAttributes.NewSlot;
4637 MethodAttributes.Virtual |
4638 MethodAttributes.HideBySig;
4640 // Set Final unless we're virtual, abstract or already overriding a method.
4641 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4642 flags |= MethodAttributes.Final;
4645 DefineMethodBuilder (container, method_name, method.ParameterInfo.Types);
4647 if (builder == null)
4650 if ((modifiers & Modifiers.UNSAFE) != 0)
4651 builder.InitLocals = false;
4653 if (implementing != null){
4655 // clear the pending implemntation flag
4657 if (member is Indexer) {
4658 pending.ImplementIndexer (
4659 member.InterfaceType, builder, method.ReturnType,
4660 method.ParameterInfo, member.IsExplicitImpl);
4662 pending.ImplementMethod (
4663 member.InterfaceType, name, method.ReturnType,
4664 method.ParameterInfo, member.IsExplicitImpl);
4666 if (member.IsExplicitImpl)
4667 container.TypeBuilder.DefineMethodOverride (
4668 builder, implementing);
4672 TypeManager.AddMethod (builder, method);
4679 /// Create the MethodBuilder for the method
4681 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
4683 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4685 if ((modifiers & extern_static) == extern_static) {
4687 if (method.OptAttributes != null) {
4688 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type);
4689 if (dllimport_attribute != null) {
4690 flags |= MethodAttributes.PinvokeImpl;
4691 builder = dllimport_attribute.DefinePInvokeMethod (
4692 container.TypeBuilder, method_name, flags,
4693 method.ReturnType, ParameterTypes);
4699 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4700 // We are more strict than Microsoft and report CS0626 like error
4701 if (method.OptAttributes == null ||
4702 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type)) {
4703 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",
4704 method.GetSignatureForError ());
4709 builder = container.TypeBuilder.DefineMethod (
4710 method_name, flags, method.CallingConventions,
4711 method.ReturnType, ParameterTypes);
4717 public void Emit (DeclSpace parent)
4720 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4721 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
4723 ec = method.CreateEmitContext (parent, null);
4725 method.ParameterInfo.ApplyAttributes (MethodBuilder);
4727 ToplevelBlock block = method.Block;
4729 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
4732 // Handle destructors specially
4734 // FIXME: This code generates buggy code
4736 if (member is Destructor)
4737 EmitDestructor (ec, block);
4739 ec.EmitTopBlock (method, block);
4742 source.CloseMethod ();
4745 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4747 ILGenerator ig = ec.ig;
4749 Label finish = ig.DefineLabel ();
4751 block.SetDestructor ();
4753 ig.BeginExceptionBlock ();
4754 ec.ReturnLabel = finish;
4755 ec.HasReturnLabel = true;
4756 ec.EmitTopBlock (method, block);
4758 // ig.MarkLabel (finish);
4759 ig.BeginFinallyBlock ();
4761 if (ec.ContainerType.BaseType != null) {
4762 Expression member_lookup = Expression.MemberLookup (
4763 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4764 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4766 if (member_lookup != null){
4767 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4769 ig.Emit (OpCodes.Ldarg_0);
4770 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4774 ig.EndExceptionBlock ();
4775 //ig.MarkLabel (ec.ReturnLabel);
4776 ig.Emit (OpCodes.Ret);
4780 // TODO: Should derive from MethodCore
4781 public class Destructor : Method {
4783 static string[] attribute_targets = new string [] { "method" };
4785 public Destructor (DeclSpace parent, Expression return_type, int mod,
4786 string name, Parameters parameters, Attributes attrs,
4788 : base (parent, return_type, mod, false, new MemberName (name, l),
4792 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4794 if (a.Type == TypeManager.conditional_attribute_type) {
4795 Error_ConditionalAttributeIsNotValid ();
4799 base.ApplyAttributeBuilder (a, cb);
4802 public override string GetSignatureForError ()
4804 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
4807 public override string[] ValidAttributeTargets {
4809 return attribute_targets;
4814 abstract public class MemberBase : MemberCore {
4815 public Expression Type;
4817 public MethodAttributes flags;
4819 protected readonly int explicit_mod_flags;
4822 // The "short" name of this property / indexer / event. This is the
4823 // name without the explicit interface.
4825 public string ShortName {
4826 get { return MemberName.Name; }
4827 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
4830 public TypeContainer ParentContainer {
4831 get { return ((TypeContainer) Parent).PartialContainer; }
4835 // The type of this property / indexer / event
4838 public Type MemberType {
4840 if (member_type == null && Type != null) {
4841 Type = Type.ResolveAsTypeTerminal (ResolveContext, false);
4843 member_type = Type.Type;
4851 // Whether this is an interface member.
4853 public bool IsInterface;
4856 // If true, this is an explicit interface implementation
4858 public bool IsExplicitImpl;
4861 // The interface type we are explicitly implementing
4863 public Type InterfaceType = null;
4866 // The constructor is only exposed to our children
4868 protected MemberBase (DeclSpace parent, Expression type, int mod,
4869 int allowed_mod, int def_mod, MemberName name,
4871 : base (parent, name, attrs)
4873 explicit_mod_flags = mod;
4875 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
4876 IsExplicitImpl = (MemberName.Left != null);
4879 protected virtual bool CheckBase ()
4881 if ((ModFlags & Modifiers.PROTECTED) != 0 && ParentContainer.Kind == Kind.Struct) {
4882 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4886 if ((RootContext.WarningLevel >= 4) &&
4887 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4888 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4889 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4890 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4895 protected virtual bool DoDefine ()
4898 throw new InternalErrorException ();
4901 ModFlags = Modifiers.PUBLIC |
4902 Modifiers.ABSTRACT |
4903 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
4905 flags = MethodAttributes.Public |
4906 MethodAttributes.Abstract |
4907 MethodAttributes.HideBySig |
4908 MethodAttributes.NewSlot |
4909 MethodAttributes.Virtual;
4911 if (!ParentContainer.MethodModifiersValid (this))
4914 flags = Modifiers.MethodAttr (ModFlags);
4917 if (MemberType == null)
4920 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
4921 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
4922 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
4923 GetSignatureForError (), Parent.GetSignatureForError ());
4927 // verify accessibility
4928 if (!Parent.AsAccessible (MemberType, ModFlags)) {
4929 Report.SymbolRelatedToPreviousError (MemberType);
4930 if (this is Property)
4931 Report.Error (53, Location,
4932 "Inconsistent accessibility: property type `" +
4933 TypeManager.CSharpName (MemberType) + "' is less " +
4934 "accessible than property `" + GetSignatureForError () + "'");
4935 else if (this is Indexer)
4936 Report.Error (54, Location,
4937 "Inconsistent accessibility: indexer return type `" +
4938 TypeManager.CSharpName (MemberType) + "' is less " +
4939 "accessible than indexer `" + GetSignatureForError () + "'");
4940 else if (this is MethodCore) {
4941 if (this is Operator)
4942 Report.Error (56, Location,
4943 "Inconsistent accessibility: return type `" +
4944 TypeManager.CSharpName (MemberType) + "' is less " +
4945 "accessible than operator `" + GetSignatureForError () + "'");
4947 Report.Error (50, Location,
4948 "Inconsistent accessibility: return type `" +
4949 TypeManager.CSharpName (MemberType) + "' is less " +
4950 "accessible than method `" + GetSignatureForError () + "'");
4952 Report.Error (52, Location,
4953 "Inconsistent accessibility: field type `" +
4954 TypeManager.CSharpName (MemberType) + "' is less " +
4955 "accessible than field `" + GetSignatureForError () + "'");
4960 if (IsExplicitImpl) {
4961 Expression expr = MemberName.Left.GetTypeExpression ();
4962 TypeExpr texpr = expr.ResolveAsTypeTerminal (ResolveContext, false);
4966 InterfaceType = texpr.Type;
4968 if (!InterfaceType.IsInterface) {
4969 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
4973 if (!ParentContainer.VerifyImplements (this))
4976 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
4982 protected bool IsTypePermitted ()
4984 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
4985 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
4991 protected override bool VerifyClsCompliance()
4993 if (base.VerifyClsCompliance ()) {
4997 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
4998 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5006 // Fields and Events both generate FieldBuilders, we use this to share
5007 // their common bits. This is also used to flag usage of the field
5009 abstract public class FieldBase : MemberBase {
5010 public FieldBuilder FieldBuilder;
5011 public Status status;
5012 protected Expression initializer;
5013 ExpressionStatement initializerStatement;
5016 public enum Status : byte {
5017 HAS_OFFSET = 4 // Used by FieldMember.
5020 static string[] attribute_targets = new string [] { "field" };
5023 /// Symbol with same name in base class/struct
5025 public MemberInfo conflict_symbol;
5027 protected FieldBase (DeclSpace parent, Expression type, int mod,
5028 int allowed_mod, MemberName name, Attributes attrs)
5029 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5034 public override AttributeTargets AttributeTargets {
5036 return AttributeTargets.Field;
5040 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5042 if (a.Type == TypeManager.marshal_as_attr_type) {
5043 UnmanagedMarshal marshal = a.GetMarshal (this);
5044 if (marshal != null) {
5045 FieldBuilder.SetMarshal (marshal);
5050 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5051 a.Error_InvalidSecurityParent ();
5055 FieldBuilder.SetCustomAttribute (cb);
5058 public void EmitInitializer (EmitContext ec)
5060 initializerStatement.EmitStatement (ec);
5063 protected override bool CheckBase ()
5065 if (!base.CheckBase ())
5072 conflict_symbol = ParentContainer.FindBaseMemberWithSameName (Name, false);
5073 if (conflict_symbol == null) {
5074 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5075 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5080 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5081 Report.SymbolRelatedToPreviousError (conflict_symbol);
5082 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5083 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5089 public Expression Initializer {
5091 if (value != null) {
5092 this.initializer = value;
5093 ParentContainer.RegisterFieldForInitialization (this);
5098 protected virtual bool IsFieldClsCompliant {
5100 if (FieldBuilder == null)
5103 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5107 public Expression ResolveInitializer ()
5109 // TODO: again it's too heavy-weight
5110 EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
5111 ec.IsFieldInitializer = true;
5112 initializer = initializer.Resolve (ec);
5113 if (initializer == null)
5115 if (FieldBuilder == null)
5118 FieldExpr fe = new FieldExpr (FieldBuilder, Location, true);
5119 if ((ModFlags & Modifiers.STATIC) == 0)
5121 fe.InstanceExpression = CompilerGeneratedThis.Instance;
5124 initializerStatement = new Assign (fe, initializer, Location).ResolveStatement (ec);
5128 public bool HasDefaultInitializer
5132 Constant c = initializer as Constant;
5136 return c.IsDefaultInitializer (MemberType);
5140 public override string[] ValidAttributeTargets
5143 return attribute_targets;
5147 protected override bool VerifyClsCompliance ()
5149 if (!base.VerifyClsCompliance ())
5152 if (!IsFieldClsCompliant) {
5153 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5159 public void SetAssigned ()
5161 caching_flags |= Flags.IsAssigned;
5165 public abstract class FieldMember : FieldBase
5167 protected FieldMember (DeclSpace parent, Expression type, int mod,
5168 int allowed_mod, MemberName name, Attributes attrs)
5169 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, attrs)
5171 if ((mod & Modifiers.ABSTRACT) != 0)
5172 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5175 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5177 if (a.Type == TypeManager.field_offset_attribute_type)
5179 status |= Status.HAS_OFFSET;
5181 if (!ParentContainer.HasExplicitLayout) {
5182 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5186 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5187 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5193 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5194 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5199 base.ApplyAttributeBuilder (a, cb);
5202 public override bool Define()
5204 if (MemberType == null || Type == null)
5207 if (MemberType == TypeManager.void_type) {
5208 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5215 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5216 Report.Error (52, Location,
5217 "Inconsistent accessibility: field type `" +
5218 TypeManager.CSharpName (MemberType) + "' is less " +
5219 "accessible than field `" + GetSignatureForError () + "'");
5223 if (!IsTypePermitted ())
5229 public override void Emit ()
5231 if (OptAttributes != null) {
5232 OptAttributes.Emit ();
5235 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && ParentContainer.HasExplicitLayout) {
5236 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5243 // Represents header string for documentation comment.
5245 public override string DocCommentHeader {
5246 get { return "F:"; }
5250 interface IFixedBuffer
5252 FieldInfo Element { get; }
5253 Type ElementType { get; }
5256 public class FixedFieldExternal: IFixedBuffer
5258 FieldInfo element_field;
5260 public FixedFieldExternal (FieldInfo fi)
5262 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5265 #region IFixedField Members
5267 public FieldInfo Element {
5269 return element_field;
5273 public Type ElementType {
5275 return element_field.FieldType;
5283 /// Fixed buffer implementation
5285 public class FixedField : FieldMember, IFixedBuffer
5287 public const string FixedElementName = "FixedElementField";
5288 static int GlobalCounter = 0;
5289 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5290 static FieldInfo[] fi;
5292 TypeBuilder fixed_buffer_type;
5293 FieldBuilder element;
5294 Expression size_expr;
5297 const int AllowedModifiers =
5300 Modifiers.PROTECTED |
5301 Modifiers.INTERNAL |
5304 public FixedField (DeclSpace parent, Expression type, int mod, string name,
5305 Expression size_expr, Attributes attrs, Location loc):
5306 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5308 if (RootContext.Version == LanguageVersion.ISO_1)
5309 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5311 this.size_expr = size_expr;
5314 public override bool Define()
5317 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5318 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5321 if (ParentContainer.Kind != Kind.Struct) {
5322 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5323 GetSignatureForError ());
5327 if (!base.Define ())
5330 if (!TypeManager.IsPrimitiveType (MemberType)) {
5331 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",
5332 GetSignatureForError ());
5336 EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
5337 Constant c = size_expr.ResolveAsConstant (ec, this);
5341 IntConstant buffer_size_const = c.ToInt (Location);
5342 if (buffer_size_const == null)
5345 buffer_size = buffer_size_const.Value;
5347 if (buffer_size <= 0) {
5348 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5352 int type_size = Expression.GetTypeSize (MemberType);
5354 if (buffer_size > int.MaxValue / type_size) {
5355 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5356 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5360 buffer_size *= type_size;
5363 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5365 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5366 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5367 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5368 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5370 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5371 TypeManager.RegisterFieldBase (FieldBuilder, this);
5376 public override void Emit()
5379 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5381 object[] fi_val = new object[1];
5382 fi_val [0] = buffer_size;
5384 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5385 ctor_args, fi, fi_val);
5386 fixed_buffer_type.SetCustomAttribute (cab);
5389 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5390 FieldBuilder.SetCustomAttribute (cab);
5395 protected override bool IsFieldClsCompliant {
5401 #region IFixedField Members
5403 public FieldInfo Element {
5409 public Type ElementType {
5419 // The Field class is used to represents class/struct fields during parsing.
5421 public class Field : FieldMember {
5423 // Modifiers allowed in a class declaration
5425 const int AllowedModifiers =
5428 Modifiers.PROTECTED |
5429 Modifiers.INTERNAL |
5432 Modifiers.VOLATILE |
5436 public Field (DeclSpace parent, Expression type, int mod, string name,
5437 Attributes attrs, Location loc)
5438 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5443 public override bool Define ()
5445 if (!base.Define ())
5448 if (RootContext.WarningLevel > 1){
5449 Type ptype = Parent.TypeBuilder.BaseType;
5451 // ptype is only null for System.Object while compiling corlib.
5453 TypeContainer.FindMembers (
5454 ptype, MemberTypes.Method,
5455 BindingFlags.Public |
5456 BindingFlags.Static | BindingFlags.Instance,
5457 System.Type.FilterName, Name);
5461 if ((ModFlags & Modifiers.VOLATILE) != 0){
5462 if (!MemberType.IsClass){
5463 Type vt = MemberType;
5465 if (TypeManager.IsEnumType (vt))
5466 vt = TypeManager.EnumToUnderlying (MemberType);
5468 if (!((vt == TypeManager.bool_type) ||
5469 (vt == TypeManager.sbyte_type) ||
5470 (vt == TypeManager.byte_type) ||
5471 (vt == TypeManager.short_type) ||
5472 (vt == TypeManager.ushort_type) ||
5473 (vt == TypeManager.int32_type) ||
5474 (vt == TypeManager.uint32_type) ||
5475 (vt == TypeManager.char_type) ||
5476 (vt == TypeManager.float_type) ||
5477 (!vt.IsValueType))){
5478 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5479 GetSignatureForError (), TypeManager.CSharpName (vt));
5484 if ((ModFlags & Modifiers.READONLY) != 0){
5485 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5486 GetSignatureForError ());
5491 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5493 if (ParentContainer.Kind == Kind.Struct &&
5494 ((fa & FieldAttributes.Static) == 0) &&
5495 MemberType == Parent.TypeBuilder &&
5496 !TypeManager.IsBuiltinType (MemberType)){
5497 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5498 "' causes a cycle in the structure layout");
5503 FieldBuilder = Parent.TypeBuilder.DefineField (
5504 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5506 TypeManager.RegisterFieldBase (FieldBuilder, this);
5508 catch (ArgumentException) {
5509 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5516 protected override bool VerifyClsCompliance ()
5518 if (!base.VerifyClsCompliance ())
5521 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5522 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5530 // `set' and `get' accessors are represented with an Accessor.
5532 public class Accessor : IIteratorContainer {
5534 // Null if the accessor is empty, or a Block if not
5536 public const int AllowedModifiers =
5538 Modifiers.PROTECTED |
5539 Modifiers.INTERNAL |
5542 public ToplevelBlock Block;
5543 public Attributes Attributes;
5544 public Location Location;
5545 public int ModFlags;
5548 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5553 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5556 public void SetYields ()
5562 // Ooouh Martin, templates are missing here.
5563 // When it will be possible move here a lot of child code and template method type.
5564 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5565 protected MethodData method_data;
5566 protected ToplevelBlock block;
5567 protected ListDictionary declarative_security;
5569 // The accessor are created event if they are not wanted.
5570 // But we need them because their names are reserved.
5571 // Field says whether accessor will be emited or not
5572 public readonly bool IsDummy;
5574 protected readonly string prefix;
5576 ReturnParameter return_attributes;
5578 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5579 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5581 this.prefix = prefix;
5585 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5587 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5588 accessor.Attributes)
5590 this.prefix = prefix;
5591 this.block = accessor.Block;
5594 static MemberName SetupName (string prefix, MemberBase member, Location loc)
5596 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5599 public void UpdateName (MemberBase member)
5601 SetMemberName (SetupName (prefix, member, Location));
5604 #region IMethodData Members
5606 public ToplevelBlock Block {
5616 public CallingConventions CallingConventions {
5618 return CallingConventions.Standard;
5622 public bool IsExcluded ()
5627 public MemberName MethodName {
5633 public Type[] ParameterTypes {
5635 return ParameterInfo.Types;
5639 public abstract Parameters ParameterInfo { get ; }
5640 public abstract Type ReturnType { get; }
5641 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5645 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5647 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5648 a.Type == TypeManager.conditional_attribute_type) {
5649 Report.Error (1667, a.Location,
5650 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5651 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5655 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5656 if (declarative_security == null)
5657 declarative_security = new ListDictionary ();
5658 a.ExtractSecurityPermissionSet (declarative_security);
5662 if (a.Target == AttributeTargets.Method) {
5663 method_data.MethodBuilder.SetCustomAttribute (cb);
5667 if (a.Target == AttributeTargets.ReturnValue) {
5668 if (return_attributes == null)
5669 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5671 return_attributes.ApplyAttributeBuilder (a, cb);
5675 ApplyToExtraTarget (a, cb);
5678 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5680 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5683 public override bool Define()
5685 throw new NotSupportedException ();
5688 public void Emit (DeclSpace parent)
5690 EmitMethod (parent);
5692 if (OptAttributes != null)
5693 OptAttributes.Emit ();
5695 if (declarative_security != null) {
5696 foreach (DictionaryEntry de in declarative_security) {
5697 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5704 protected virtual void EmitMethod (DeclSpace parent)
5706 method_data.Emit (parent);
5709 public override bool IsClsComplianceRequired()
5714 public bool IsDuplicateImplementation (MethodCore method)
5716 if (!MemberName.Equals (method.MemberName))
5719 Type[] param_types = method.ParameterTypes;
5721 if (param_types.Length != ParameterTypes.Length)
5724 for (int i = 0; i < param_types.Length; i++)
5725 if (param_types [i] != ParameterTypes [i])
5728 Report.SymbolRelatedToPreviousError (method);
5729 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
5733 public override bool IsUsed
5743 public new Location Location {
5745 return base.Location;
5750 // Represents header string for documentation comment.
5752 public override string DocCommentHeader {
5753 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5759 // Properties and Indexers both generate PropertyBuilders, we use this to share
5760 // their common bits.
5762 abstract public class PropertyBase : MethodCore {
5764 public class GetMethod : PropertyMethod
5766 static string[] attribute_targets = new string [] { "method", "return" };
5768 public GetMethod (MethodCore method):
5769 base (method, "get_")
5773 public GetMethod (MethodCore method, Accessor accessor):
5774 base (method, accessor, "get_")
5778 public override MethodBuilder Define (DeclSpace parent)
5780 base.Define (parent);
5782 method_data = new MethodData (method, ModFlags, flags, this);
5784 if (!method_data.Define (parent))
5787 return method_data.MethodBuilder;
5790 public override Type ReturnType {
5792 return method.MemberType;
5796 public override Parameters ParameterInfo {
5798 return Parameters.EmptyReadOnlyParameters;
5802 public override string[] ValidAttributeTargets {
5804 return attribute_targets;
5809 public class SetMethod : PropertyMethod {
5811 static string[] attribute_targets = new string [] { "method", "param", "return" };
5812 ImplicitParameter param_attr;
5813 protected Parameters parameters;
5815 public SetMethod (MethodCore method):
5816 base (method, "set_")
5820 public SetMethod (MethodCore method, Accessor accessor):
5821 base (method, accessor, "set_")
5825 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5827 if (a.Target == AttributeTargets.Parameter) {
5828 if (param_attr == null)
5829 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5831 param_attr.ApplyAttributeBuilder (a, cb);
5835 base.ApplyAttributeBuilder (a, cb);
5838 public override Parameters ParameterInfo {
5844 protected virtual void DefineParameters ()
5846 parameters = new Parameters (
5847 new Parameter[] { new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location) },
5848 new Type[] { method.MemberType });
5851 public override MethodBuilder Define (DeclSpace parent)
5853 DefineParameters ();
5857 base.Define (parent);
5859 method_data = new MethodData (method, ModFlags, flags, this);
5861 if (!method_data.Define (parent))
5864 return method_data.MethodBuilder;
5867 public override Type ReturnType {
5869 return TypeManager.void_type;
5873 public override string[] ValidAttributeTargets {
5875 return attribute_targets;
5880 static string[] attribute_targets = new string [] { "property" };
5882 public abstract class PropertyMethod : AbstractPropertyEventMethod
5884 protected readonly MethodCore method;
5885 protected MethodAttributes flags;
5888 public PropertyMethod (MethodCore method, string prefix)
5889 : base (method, prefix)
5891 this.method = method;
5894 public PropertyMethod (MethodCore method, Accessor accessor,
5896 : base (method, accessor, prefix)
5898 this.method = method;
5899 this.ModFlags = accessor.ModFlags;
5900 yields = accessor.Yields;
5902 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
5903 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
5907 public override AttributeTargets AttributeTargets {
5909 return AttributeTargets.Method;
5913 public override bool IsClsComplianceRequired()
5915 return method.IsClsComplianceRequired ();
5918 public virtual MethodBuilder Define (DeclSpace parent)
5920 if (!method.CheckAbstractAndExtern (block != null))
5923 TypeContainer container = ((TypeContainer) parent).PartialContainer;
5926 // Check for custom access modifier
5928 if (ModFlags == 0) {
5929 ModFlags = method.ModFlags;
5930 flags = method.flags;
5932 if (container.Kind == Kind.Interface)
5933 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
5934 GetSignatureForError ());
5936 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
5937 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
5940 CheckModifiers (ModFlags);
5941 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
5942 ModFlags |= Modifiers.PROPERTY_CUSTOM;
5943 flags = Modifiers.MethodAttr (ModFlags);
5944 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
5948 // Setup iterator if we are one
5951 Iterator iterator = new Iterator (this, Parent as TypeContainer, ModFlags);
5953 if (!iterator.DefineIterator ())
5960 public bool HasCustomAccessModifier
5963 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
5967 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
5969 return new EmitContext (method,
5970 ds, method.Parent, method.Location, ig, ReturnType,
5971 method.ModFlags, false);
5974 public override ObsoleteAttribute GetObsoleteAttribute ()
5976 return method.GetObsoleteAttribute ();
5979 public override string GetSignatureForError()
5981 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
5984 void CheckModifiers (int modflags)
5987 int mflags = method.ModFlags & Modifiers.Accessibility;
5989 if ((mflags & Modifiers.PUBLIC) != 0) {
5990 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
5992 else if ((mflags & Modifiers.PROTECTED) != 0) {
5993 if ((mflags & Modifiers.INTERNAL) != 0)
5994 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
5996 flags |= Modifiers.PRIVATE;
5998 else if ((mflags & Modifiers.INTERNAL) != 0)
5999 flags |= Modifiers.PRIVATE;
6001 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6002 Report.Error (273, Location,
6003 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6004 GetSignatureForError (), method.GetSignatureForError ());
6008 public override bool MarkForDuplicationCheck ()
6010 caching_flags |= Flags.TestMethodDuplication;
6015 public PropertyMethod Get, Set;
6016 public PropertyBuilder PropertyBuilder;
6017 public MethodBuilder GetBuilder, SetBuilder;
6019 protected EmitContext ec;
6021 public PropertyBase (DeclSpace parent, Expression type, int mod_flags,
6022 int allowed_mod, bool is_iface, MemberName name,
6023 Parameters parameters, Attributes attrs)
6024 : base (parent, type, mod_flags, allowed_mod, is_iface, name,
6029 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6031 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6032 a.Error_InvalidSecurityParent ();
6036 PropertyBuilder.SetCustomAttribute (cb);
6039 public override AttributeTargets AttributeTargets {
6041 return AttributeTargets.Property;
6045 public override bool Define ()
6050 if (!IsTypePermitted ())
6056 protected override bool DoDefine ()
6058 if (!base.DoDefine ())
6062 // Accessors modifiers check
6064 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6065 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6066 GetSignatureForError ());
6070 if ((Get.IsDummy || Set.IsDummy)
6071 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6072 Report.Error (276, Location,
6073 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6074 GetSignatureForError ());
6078 if (MemberType.IsAbstract && MemberType.IsSealed) {
6079 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6086 protected override bool CheckForDuplications ()
6088 ArrayList ar = ParentContainer.Indexers;
6090 int arLen = ar.Count;
6092 for (int i = 0; i < arLen; i++) {
6093 Indexer m = (Indexer) ar [i];
6094 if (IsDuplicateImplementation (m))
6099 ar = ParentContainer.Properties;
6101 int arLen = ar.Count;
6103 for (int i = 0; i < arLen; i++) {
6104 Property m = (Property) ar [i];
6105 if (IsDuplicateImplementation (m))
6113 // TODO: rename to Resolve......
6114 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6116 PropertyInfo base_property = ParentContainer.BaseCache.FindMemberToOverride (
6117 Parent.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6119 if (base_property == null)
6122 base_ret_type = base_property.PropertyType;
6123 MethodInfo get_accessor = base_property.GetGetMethod (true);
6124 MethodInfo set_accessor = base_property.GetSetMethod (true);
6125 MethodAttributes get_accessor_access, set_accessor_access;
6127 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6128 if (Get != null && !Get.IsDummy && get_accessor == null) {
6129 Report.SymbolRelatedToPreviousError (base_property);
6130 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6133 if (Set != null && !Set.IsDummy && set_accessor == null) {
6134 Report.SymbolRelatedToPreviousError (base_property);
6135 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6140 // Check base class accessors access
6143 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6144 get_accessor_access = set_accessor_access = 0;
6145 if ((ModFlags & Modifiers.NEW) == 0) {
6146 if (get_accessor != null) {
6147 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6148 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6150 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6151 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6154 if (set_accessor != null) {
6155 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6156 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6158 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6159 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6164 // Get the less restrictive access
6166 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6169 public override void Emit ()
6172 // The PropertyBuilder can be null for explicit implementations, in that
6173 // case, we do not actually emit the ".property", so there is nowhere to
6174 // put the attribute
6176 if (PropertyBuilder != null && OptAttributes != null)
6177 OptAttributes.Emit ();
6189 /// Tests whether accessors are not in collision with some method (CS0111)
6191 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6193 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6196 public override bool IsUsed
6202 return Get.IsUsed | Set.IsUsed;
6206 protected override void SetMemberName (MemberName new_name)
6208 base.SetMemberName (new_name);
6210 Get.UpdateName (this);
6211 Set.UpdateName (this);
6214 public override string[] ValidAttributeTargets {
6216 return attribute_targets;
6221 // Represents header string for documentation comment.
6223 public override string DocCommentHeader {
6224 get { return "P:"; }
6228 public class Property : PropertyBase {
6229 const int AllowedModifiers =
6232 Modifiers.PROTECTED |
6233 Modifiers.INTERNAL |
6237 Modifiers.OVERRIDE |
6238 Modifiers.ABSTRACT |
6241 Modifiers.METHOD_YIELDS |
6244 const int AllowedInterfaceModifiers =
6247 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6248 MemberName name, Attributes attrs, Accessor get_block,
6250 : base (parent, type, mod,
6251 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6252 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6254 if (get_block == null)
6255 Get = new GetMethod (this);
6257 Get = new GetMethod (this, get_block);
6259 if (set_block == null)
6260 Set = new SetMethod (this);
6262 Set = new SetMethod (this, set_block);
6265 public override bool Define ()
6267 if (!base.Define ())
6273 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6276 GetBuilder = Get.Define (Parent);
6277 if (GetBuilder == null)
6281 SetBuilder = Set.Define (Parent);
6283 if (SetBuilder == null)
6287 // FIXME - PropertyAttributes.HasDefault ?
6289 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6290 Name, PropertyAttributes.None, MemberType, null);
6293 PropertyBuilder.SetGetMethod (GetBuilder);
6296 PropertyBuilder.SetSetMethod (SetBuilder);
6298 TypeManager.RegisterProperty (PropertyBuilder, this);
6304 /// Gigantic workaround for lameness in SRE follows :
6305 /// This class derives from EventInfo and attempts to basically
6306 /// wrap around the EventBuilder so that FindMembers can quickly
6307 /// return this in it search for members
6309 public class MyEventBuilder : EventInfo {
6312 // We use this to "point" to our Builder which is
6313 // not really a MemberInfo
6315 EventBuilder MyBuilder;
6318 // We "catch" and wrap these methods
6320 MethodInfo raise, remove, add;
6322 EventAttributes attributes;
6323 Type declaring_type, reflected_type, event_type;
6328 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6330 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6332 // And now store the values in our own fields.
6334 declaring_type = type_builder;
6336 reflected_type = type_builder;
6338 attributes = event_attr;
6341 this.event_type = event_type;
6345 // Methods that you have to override. Note that you only need
6346 // to "implement" the variants that take the argument (those are
6347 // the "abstract" methods, the others (GetAddMethod()) are
6350 public override MethodInfo GetAddMethod (bool nonPublic)
6355 public override MethodInfo GetRemoveMethod (bool nonPublic)
6360 public override MethodInfo GetRaiseMethod (bool nonPublic)
6366 // These methods make "MyEventInfo" look like a Builder
6368 public void SetRaiseMethod (MethodBuilder raiseMethod)
6370 raise = raiseMethod;
6371 MyBuilder.SetRaiseMethod (raiseMethod);
6374 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6376 remove = removeMethod;
6377 MyBuilder.SetRemoveOnMethod (removeMethod);
6380 public void SetAddOnMethod (MethodBuilder addMethod)
6383 MyBuilder.SetAddOnMethod (addMethod);
6386 public void SetCustomAttribute (CustomAttributeBuilder cb)
6388 MyBuilder.SetCustomAttribute (cb);
6391 public override object [] GetCustomAttributes (bool inherit)
6393 // FIXME : There's nothing which can be seemingly done here because
6394 // we have no way of getting at the custom attribute objects of the
6399 public override object [] GetCustomAttributes (Type t, bool inherit)
6401 // FIXME : Same here !
6405 public override bool IsDefined (Type t, bool b)
6410 public override EventAttributes Attributes {
6416 public override string Name {
6422 public override Type DeclaringType {
6424 return declaring_type;
6428 public override Type ReflectedType {
6430 return reflected_type;
6434 public Type EventType {
6440 public void SetUsed ()
6442 if (my_event != null) {
6443 my_event.SetAssigned ();
6444 my_event.SetMemberIsUsed ();
6450 /// For case when event is declared like property (with add and remove accessors).
6452 public class EventProperty: Event {
6454 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6456 public EventProperty (DeclSpace parent, Expression type, int mod_flags,
6457 bool is_iface, MemberName name,
6458 Attributes attrs, Accessor add, Accessor remove)
6459 : base (parent, type, mod_flags, is_iface, name, attrs)
6461 Add = new AddDelegateMethod (this, add);
6462 Remove = new RemoveDelegateMethod (this, remove);
6464 // For this event syntax we don't report error CS0067
6465 // because it is hard to do it.
6469 public override string[] ValidAttributeTargets {
6471 return attribute_targets;
6477 /// Event is declared like field.
6479 public class EventField : Event {
6481 static string[] attribute_targets = new string [] { "event", "field", "method" };
6482 static string[] attribute_targets_interface = new string[] { "event", "method" };
6484 public EventField (DeclSpace parent, Expression type, int mod_flags,
6485 bool is_iface, MemberName name,
6487 : base (parent, type, mod_flags, is_iface, name, attrs)
6489 Add = new AddDelegateMethod (this);
6490 Remove = new RemoveDelegateMethod (this);
6493 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6495 if (a.Target == AttributeTargets.Field) {
6496 FieldBuilder.SetCustomAttribute (cb);
6500 if (a.Target == AttributeTargets.Method) {
6501 Add.ApplyAttributeBuilder (a, cb);
6502 Remove.ApplyAttributeBuilder (a, cb);
6506 base.ApplyAttributeBuilder (a, cb);
6509 public override bool Define()
6511 if (!base.Define ())
6514 if (initializer != null) {
6515 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
6516 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
6517 GetSignatureForError ());
6525 public override string[] ValidAttributeTargets {
6527 return IsInterface ? attribute_targets_interface : attribute_targets;
6532 public abstract class Event : FieldBase {
6534 protected sealed class AddDelegateMethod: DelegateMethod
6537 public AddDelegateMethod (Event method):
6538 base (method, "add_")
6542 public AddDelegateMethod (Event method, Accessor accessor):
6543 base (method, accessor, "add_")
6547 protected override MethodInfo DelegateMethodInfo {
6549 return TypeManager.delegate_combine_delegate_delegate;
6555 protected sealed class RemoveDelegateMethod: DelegateMethod
6557 public RemoveDelegateMethod (Event method):
6558 base (method, "remove_")
6562 public RemoveDelegateMethod (Event method, Accessor accessor):
6563 base (method, accessor, "remove_")
6567 protected override MethodInfo DelegateMethodInfo {
6569 return TypeManager.delegate_remove_delegate_delegate;
6575 public abstract class DelegateMethod : AbstractPropertyEventMethod
6577 protected readonly Event method;
6578 ImplicitParameter param_attr;
6580 static string[] attribute_targets = new string [] { "method", "param", "return" };
6582 public DelegateMethod (Event method, string prefix)
6583 : base (method, prefix)
6585 this.method = method;
6588 public DelegateMethod (Event method, Accessor accessor, string prefix)
6589 : base (method, accessor, prefix)
6591 this.method = method;
6594 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6596 if (a.Target == AttributeTargets.Parameter) {
6597 if (param_attr == null)
6598 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6600 param_attr.ApplyAttributeBuilder (a, cb);
6604 base.ApplyAttributeBuilder (a, cb);
6607 public override AttributeTargets AttributeTargets {
6609 return AttributeTargets.Method;
6613 public override bool IsClsComplianceRequired ()
6615 return method.IsClsComplianceRequired ();
6618 public MethodBuilder Define (DeclSpace parent)
6620 method_data = new MethodData (method, method.ModFlags,
6621 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6623 if (!method_data.Define (parent))
6626 MethodBuilder mb = method_data.MethodBuilder;
6627 ParameterInfo.ApplyAttributes (mb);
6632 protected override void EmitMethod (DeclSpace parent)
6634 if (block != null) {
6635 base.EmitMethod (parent);
6639 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6642 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6643 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6645 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6646 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6647 ig.Emit (OpCodes.Ldsfld, field_info);
6648 ig.Emit (OpCodes.Ldarg_0);
6649 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6650 ig.Emit (OpCodes.Castclass, method.MemberType);
6651 ig.Emit (OpCodes.Stsfld, field_info);
6653 ig.Emit (OpCodes.Ldarg_0);
6654 ig.Emit (OpCodes.Ldarg_0);
6655 ig.Emit (OpCodes.Ldfld, field_info);
6656 ig.Emit (OpCodes.Ldarg_1);
6657 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6658 ig.Emit (OpCodes.Castclass, method.MemberType);
6659 ig.Emit (OpCodes.Stfld, field_info);
6661 ig.Emit (OpCodes.Ret);
6664 protected abstract MethodInfo DelegateMethodInfo { get; }
6666 public override Type ReturnType {
6668 return TypeManager.void_type;
6672 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6674 return new EmitContext (method,
6675 ds, method.Parent, Location, ig, ReturnType,
6676 method.ModFlags, false);
6679 public override ObsoleteAttribute GetObsoleteAttribute ()
6681 return method.GetObsoleteAttribute ();
6684 public override string[] ValidAttributeTargets {
6686 return attribute_targets;
6690 public override Parameters ParameterInfo {
6692 return method.parameters;
6699 const int AllowedModifiers =
6702 Modifiers.PROTECTED |
6703 Modifiers.INTERNAL |
6708 Modifiers.OVERRIDE |
6712 const int AllowedInterfaceModifiers =
6715 public DelegateMethod Add, Remove;
6716 public MyEventBuilder EventBuilder;
6717 public MethodBuilder AddBuilder, RemoveBuilder;
6718 Parameters parameters;
6720 protected Event (DeclSpace parent, Expression type, int mod_flags,
6721 bool is_iface, MemberName name, Attributes attrs)
6722 : base (parent, type, mod_flags,
6723 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6726 IsInterface = is_iface;
6729 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6731 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6732 a.Error_InvalidSecurityParent ();
6736 EventBuilder.SetCustomAttribute (cb);
6739 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6741 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6744 public override AttributeTargets AttributeTargets {
6746 return AttributeTargets.Event;
6750 public override bool Define ()
6752 EventAttributes e_attr;
6753 e_attr = EventAttributes.None;
6758 if (!TypeManager.IsDelegateType (MemberType)) {
6759 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
6763 parameters = new Parameters (
6764 new Parameter[] { new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location) },
6765 new Type[] { MemberType } );
6771 // Now define the accessors
6774 AddBuilder = Add.Define (Parent);
6775 if (AddBuilder == null)
6778 RemoveBuilder = Remove.Define (Parent);
6779 if (RemoveBuilder == null)
6782 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6784 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6785 FieldBuilder = Parent.TypeBuilder.DefineField (
6787 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6788 TypeManager.RegisterPrivateFieldOfEvent (
6789 (EventInfo) EventBuilder, FieldBuilder);
6790 TypeManager.RegisterFieldBase (FieldBuilder, this);
6793 EventBuilder.SetAddOnMethod (AddBuilder);
6794 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6796 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6800 protected override bool CheckBase ()
6802 if (!base.CheckBase ())
6805 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6806 if (!(conflict_symbol is EventInfo)) {
6807 Report.SymbolRelatedToPreviousError (conflict_symbol);
6808 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
6816 public override void Emit ()
6818 if (OptAttributes != null) {
6819 OptAttributes.Emit ();
6823 Remove.Emit (Parent);
6828 public override string GetSignatureForError ()
6830 return base.GetSignatureForError ();
6834 // Represents header string for documentation comment.
6836 public override string DocCommentHeader {
6837 get { return "E:"; }
6842 public class Indexer : PropertyBase {
6844 class GetIndexerMethod : GetMethod
6846 public GetIndexerMethod (MethodCore method):
6851 public GetIndexerMethod (MethodCore method, Accessor accessor):
6852 base (method, accessor)
6856 public override Parameters ParameterInfo {
6858 return method.ParameterInfo;
6863 class SetIndexerMethod: SetMethod
6865 public SetIndexerMethod (MethodCore method):
6870 public SetIndexerMethod (MethodCore method, Accessor accessor):
6871 base (method, accessor)
6875 protected override void DefineParameters ()
6877 parameters = Parameters.MergeGenerated (method.Parameters,
6878 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
6882 const int AllowedModifiers =
6885 Modifiers.PROTECTED |
6886 Modifiers.INTERNAL |
6890 Modifiers.OVERRIDE |
6895 const int AllowedInterfaceModifiers =
6899 public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
6900 bool is_iface, Parameters parameters, Attributes attrs,
6901 Accessor get_block, Accessor set_block)
6902 : base (parent, type, mod,
6903 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6904 is_iface, name, parameters, attrs)
6906 if (get_block == null)
6907 Get = new GetIndexerMethod (this);
6909 Get = new GetIndexerMethod (this, get_block);
6911 if (set_block == null)
6912 Set = new SetIndexerMethod (this);
6914 Set = new SetIndexerMethod (this, set_block);
6917 public override bool Define ()
6919 if (!base.Define ())
6922 if (MemberType == TypeManager.void_type) {
6923 Report.Error (620, Location, "Indexers cannot have void type");
6927 if (OptAttributes != null) {
6928 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
6929 if (indexer_attr != null) {
6930 // Remove the attribute from the list because it is not emitted
6931 OptAttributes.Attrs.Remove (indexer_attr);
6933 string name = indexer_attr.GetIndexerAttributeValue ();
6939 if (IsExplicitImpl) {
6940 Report.Error (415, indexer_attr.Location,
6941 "The `IndexerName' attribute is valid only on an " +
6942 "indexer that is not an explicit interface member declaration");
6946 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6947 Report.Error (609, indexer_attr.Location,
6948 "Cannot set the `IndexerName' attribute on an indexer marked override");
6954 if (InterfaceType != null) {
6955 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
6956 if (base_IndexerName != Name)
6957 ShortName = base_IndexerName;
6960 if (!ParentContainer.AddToMemberContainer (this) ||
6961 !ParentContainer.AddToMemberContainer (Get) || !ParentContainer.AddToMemberContainer (Set))
6967 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6969 GetBuilder = Get.Define (Parent);
6970 if (GetBuilder == null)
6974 SetBuilder = Set.Define (Parent);
6976 if (SetBuilder == null)
6981 // Now name the parameters
6983 Parameter [] p = Parameters.FixedParameters;
6985 // TODO: should be done in parser and it needs to do cycle
6986 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
6987 Report.Error (631, Location, "ref and out are not valid in this context");
6992 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6993 Name, PropertyAttributes.None, MemberType, ParameterTypes);
6996 PropertyBuilder.SetGetMethod (GetBuilder);
6999 PropertyBuilder.SetSetMethod (SetBuilder);
7001 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7006 public override string GetSignatureForError ()
7008 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7009 if (MemberName.Left != null) {
7011 sb.Append (MemberName.Left);
7014 sb.Append (".this");
7015 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7016 return sb.ToString ();
7019 public override bool MarkForDuplicationCheck ()
7021 caching_flags |= Flags.TestMethodDuplication;
7026 public class Operator : MethodOrOperator, IIteratorContainer {
7028 const int AllowedModifiers =
7034 public enum OpType : byte {
7044 // Unary and Binary operators
7067 // Implicit and Explicit
7071 // Just because of enum
7075 public readonly OpType OperatorType;
7077 public Operator (DeclSpace parent, OpType type, Expression ret_type,
7078 int mod_flags, Parameters parameters,
7079 ToplevelBlock block, Attributes attrs, Location loc)
7080 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7081 new MemberName ("op_" + type, loc), attrs, parameters)
7083 OperatorType = type;
7087 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7089 if (a.Type == TypeManager.conditional_attribute_type) {
7090 Error_ConditionalAttributeIsNotValid ();
7094 base.ApplyAttributeBuilder (a, cb);
7097 protected override bool CheckForDuplications ()
7099 ArrayList ar = ParentContainer.Operators;
7101 int arLen = ar.Count;
7103 for (int i = 0; i < arLen; i++) {
7104 Operator o = (Operator) ar [i];
7105 if (IsDuplicateImplementation (o))
7110 ar = ParentContainer.Methods;
7112 int arLen = ar.Count;
7114 for (int i = 0; i < arLen; i++) {
7115 Method m = (Method) ar [i];
7116 if (IsDuplicateImplementation (m))
7124 public override bool Define ()
7126 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7127 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7128 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7132 if (!base.Define ())
7135 if (MemberType == TypeManager.void_type) {
7136 Report.Error (590, Location, "User-defined operators cannot return void");
7140 Type declaring_type = MethodBuilder.DeclaringType;
7141 Type return_type = MemberType;
7142 Type first_arg_type = ParameterTypes [0];
7144 // Rules for conversion operators
7146 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7147 if (first_arg_type == return_type && first_arg_type == declaring_type){
7148 Report.Error (555, Location,
7149 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7153 if (first_arg_type != declaring_type && return_type != declaring_type){
7156 "User-defined conversion must convert to or from the " +
7161 if (first_arg_type.IsInterface || return_type.IsInterface){
7162 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7163 GetSignatureForError ());
7167 if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type)) {
7168 if (declaring_type.IsSubclassOf (return_type) || declaring_type.IsSubclassOf (first_arg_type)) {
7169 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7170 GetSignatureForError ());
7173 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7174 GetSignatureForError ());
7177 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7178 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
7179 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");
7182 } else if (Parameters.Count == 1) {
7183 // Checks for Unary operators
7185 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7186 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7187 Report.Error (448, Location,
7188 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7191 if (first_arg_type != declaring_type) {
7193 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7198 if (first_arg_type != declaring_type){
7201 "The parameter of a unary operator must be the " +
7206 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7207 if (return_type != TypeManager.bool_type){
7210 "The return type of operator True or False " +
7217 // Checks for Binary operators
7219 if (first_arg_type != declaring_type &&
7220 ParameterTypes [1] != declaring_type){
7223 "One of the parameters of a binary operator must " +
7224 "be the containing type");
7232 protected override bool DoDefine ()
7234 if (!base.DoDefine ())
7237 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7241 public override void Emit ()
7245 Parameters.ApplyAttributes (MethodBuilder);
7248 // abstract or extern methods have no bodies
7250 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7254 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7255 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7257 ec = CreateEmitContext (Parent, null);
7259 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7260 ec.EmitTopBlock (this, Block);
7263 source.CloseMethod ();
7268 // Operator cannot be override
7269 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7274 public static string GetName (OpType ot)
7277 case OpType.LogicalNot:
7279 case OpType.OnesComplement:
7281 case OpType.Increment:
7283 case OpType.Decrement:
7289 case OpType.Addition:
7291 case OpType.Subtraction:
7293 case OpType.UnaryPlus:
7295 case OpType.UnaryNegation:
7297 case OpType.Multiply:
7299 case OpType.Division:
7301 case OpType.Modulus:
7303 case OpType.BitwiseAnd:
7305 case OpType.BitwiseOr:
7307 case OpType.ExclusiveOr:
7309 case OpType.LeftShift:
7311 case OpType.RightShift:
7313 case OpType.Equality:
7315 case OpType.Inequality:
7317 case OpType.GreaterThan:
7319 case OpType.LessThan:
7321 case OpType.GreaterThanOrEqual:
7323 case OpType.LessThanOrEqual:
7325 case OpType.Implicit:
7327 case OpType.Explicit:
7333 public static OpType GetOperatorType (string name)
7335 if (name.StartsWith ("op_")){
7336 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7337 if (Unary.oper_names [i] == name)
7341 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7342 if (Binary.oper_names [i] == name)
7349 public override string GetSignatureForError ()
7351 StringBuilder sb = new StringBuilder ();
7352 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7353 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7356 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7359 sb.Append (Parameters.GetSignatureForError ());
7360 return sb.ToString ();
7365 // This is used to compare method signatures
7367 struct MethodSignature {
7369 public Type RetType;
7370 public Type [] Parameters;
7373 /// This delegate is used to extract methods which have the
7374 /// same signature as the argument
7376 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7378 public MethodSignature (string name, Type ret_type, Type [] parameters)
7383 if (parameters == null)
7384 Parameters = Type.EmptyTypes;
7386 Parameters = parameters;
7389 public override string ToString ()
7392 if (Parameters.Length != 0){
7393 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7394 for (int i = 0; i < Parameters.Length; i++){
7395 sb.Append (Parameters [i]);
7396 if (i+1 < Parameters.Length)
7399 pars = sb.ToString ();
7402 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7405 public override int GetHashCode ()
7407 return Name.GetHashCode ();
7410 public override bool Equals (Object o)
7412 MethodSignature other = (MethodSignature) o;
7414 if (other.Name != Name)
7417 if (other.RetType != RetType)
7420 if (Parameters == null){
7421 if (other.Parameters == null)
7426 if (other.Parameters == null)
7429 int c = Parameters.Length;
7430 if (other.Parameters.Length != c)
7433 for (int i = 0; i < c; i++)
7434 if (other.Parameters [i] != Parameters [i])
7440 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7442 MethodSignature sig = (MethodSignature) filter_criteria;
7444 if (m.Name != sig.Name)
7448 MethodInfo mi = m as MethodInfo;
7449 PropertyInfo pi = m as PropertyInfo;
7452 ReturnType = mi.ReturnType;
7453 else if (pi != null)
7454 ReturnType = pi.PropertyType;
7459 // we use sig.RetType == null to mean `do not check the
7460 // method return value.
7462 if (sig.RetType != null)
7463 if (ReturnType != sig.RetType)
7468 args = TypeManager.GetParameterData (mi).Types;
7470 args = TypeManager.GetArgumentTypes (pi);
7471 Type [] sigp = sig.Parameters;
7473 if (args.Length != sigp.Length)
7476 for (int i = args.Length; i > 0; ){
7478 if (args [i] != sigp [i])