2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 namespace Mono.CSharp {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
79 public virtual void Emit ()
81 foreach (MemberCore mc in this)
86 public class MethodArrayList : MemberCoreArrayList
94 CachedMethods cached_method;
95 TypeContainer container;
97 public MethodArrayList (TypeContainer container)
99 this.container = container;
103 /// Method container contains Equals method
105 public bool HasEquals {
107 cached_method |= CachedMethods.Equals;
111 return (cached_method & CachedMethods.Equals) != 0;
116 /// Method container contains GetHashCode method
118 public bool HasGetHashCode {
120 cached_method |= CachedMethods.GetHashCode;
124 return (cached_method & CachedMethods.GetHashCode) != 0;
128 public override void DefineContainerMembers ()
130 base.DefineContainerMembers ();
132 if (HasEquals && !HasGetHashCode) {
133 Report.Warning (659, 3, container.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
139 public sealed class IndexerArrayList : MemberCoreArrayList
142 /// The indexer name for this container
144 public string IndexerName = DefaultIndexerName;
146 bool seen_normal_indexers = false;
148 TypeContainer container;
150 public IndexerArrayList (TypeContainer container)
152 this.container = container;
156 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
157 /// class is consistent. Either it is `Item' or it is the name defined by all the
158 /// indexers with the `IndexerName' attribute.
160 /// Turns out that the IndexerNameAttribute is applied to each indexer,
161 /// but it is never emitted, instead a DefaultMember attribute is attached
164 public override void DefineContainerMembers()
166 base.DefineContainerMembers ();
168 string class_indexer_name = null;
171 // If there's both an explicit and an implicit interface implementation, the
172 // explicit one actually implements the interface while the other one is just
173 // a normal indexer. See bug #37714.
176 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
177 foreach (Indexer i in this) {
178 if (i.InterfaceType != null) {
179 if (seen_normal_indexers)
180 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
184 seen_normal_indexers = true;
186 if (class_indexer_name == null) {
187 class_indexer_name = i.ShortName;
191 if (i.ShortName != class_indexer_name)
192 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
195 if (class_indexer_name != null)
196 IndexerName = class_indexer_name;
199 public override void Emit ()
203 if (!seen_normal_indexers)
206 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
207 container.TypeBuilder.SetCustomAttribute (cb);
211 public class OperatorArrayList: MemberCoreArrayList
213 TypeContainer container;
215 public OperatorArrayList (TypeContainer container)
217 this.container = container;
221 // Operator pair checking
226 public Type ret_type;
227 public Type type1, type2;
229 public Operator.OpType ot;
231 public OperatorEntry (int f, Operator o)
235 ret_type = o.OperatorMethod.ReturnType;
236 Type [] pt = o.OperatorMethod.ParameterTypes;
243 public override int GetHashCode ()
245 return ret_type.GetHashCode ();
248 public override bool Equals (object o)
250 OperatorEntry other = (OperatorEntry) o;
252 if (other.ret_type != ret_type)
254 if (other.type1 != type1)
256 if (other.type2 != type2)
263 // Checks that some operators come in pairs:
269 // They are matched based on the return type and the argument types
271 void CheckPairedOperators ()
273 IDictionary pairs = new HybridDictionary ();
274 Operator true_op = null;
275 Operator false_op = null;
276 bool has_equality_or_inequality = false;
278 // Register all the operators we care about.
279 foreach (Operator op in this){
282 // Skip erroneous code.
283 if (op.OperatorMethod == null)
286 switch (op.OperatorType){
287 case Operator.OpType.Equality:
289 has_equality_or_inequality = true;
291 case Operator.OpType.Inequality:
293 has_equality_or_inequality = true;
296 case Operator.OpType.True:
299 case Operator.OpType.False:
303 case Operator.OpType.GreaterThan:
305 case Operator.OpType.LessThan:
308 case Operator.OpType.GreaterThanOrEqual:
310 case Operator.OpType.LessThanOrEqual:
316 OperatorEntry oe = new OperatorEntry (reg, op);
318 object o = pairs [oe];
322 oe = (OperatorEntry) o;
327 if (true_op != null){
328 if (false_op == null)
329 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
330 true_op.GetSignatureForError ());
331 } else if (false_op != null)
332 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
333 false_op.GetSignatureForError ());
336 // Look for the mistakes.
338 foreach (DictionaryEntry de in pairs){
339 OperatorEntry oe = (OperatorEntry) de.Key;
346 case Operator.OpType.Equality:
349 case Operator.OpType.Inequality:
352 case Operator.OpType.GreaterThan:
355 case Operator.OpType.LessThan:
358 case Operator.OpType.GreaterThanOrEqual:
361 case Operator.OpType.LessThanOrEqual:
365 Report.Error (216, oe.op.Location,
366 "The operator `{0}' requires a matching operator `{1}' to also be defined",
367 oe.op.GetSignatureForError (), s);
370 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
371 if (container.Methods == null || !container.Methods.HasEquals)
372 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
374 if (container.Methods == null || !container.Methods.HasGetHashCode)
375 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
379 public override void DefineContainerMembers ()
381 base.DefineContainerMembers ();
382 CheckPairedOperators ();
387 // Whether this is a struct, class or interface
388 public readonly Kind Kind;
390 // Holds a list of classes and structures
391 protected ArrayList types;
393 // Holds the list of properties
394 MemberCoreArrayList properties;
396 // Holds the list of enumerations
397 MemberCoreArrayList enums;
399 // Holds the list of delegates
400 MemberCoreArrayList delegates;
402 // Holds the list of constructors
403 protected MemberCoreArrayList instance_constructors;
405 // Holds the list of fields
406 MemberCoreArrayList fields;
408 // Holds a list of fields that have initializers
409 protected ArrayList initialized_fields;
411 // Holds a list of static fields that have initializers
412 protected ArrayList initialized_static_fields;
414 // Holds the list of constants
415 MemberCoreArrayList constants;
418 MemberCoreArrayList interfaces;
420 // Holds the methods.
421 MethodArrayList methods;
424 protected MemberCoreArrayList events;
426 // Holds the indexers
427 IndexerArrayList indexers;
429 // Holds the operators
430 MemberCoreArrayList operators;
432 // Holds the iterators
436 // Pointers to the default constructor and the default static constructor
438 Constructor default_constructor;
439 Constructor default_static_constructor;
442 // Points to the first non-static field added to the container.
444 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
445 // and the first one's as good as any.
447 FieldBase first_nonstatic_field = null;
450 // This one is computed after we can distinguish interfaces
451 // from classes from the arraylist `type_bases'
454 TypeExpr[] iface_exprs;
456 ArrayList type_bases;
458 bool members_defined;
459 bool members_defined_ok;
461 // The interfaces we implement.
462 protected Type[] ifaces;
464 // The base member cache and our member cache
465 MemberCache base_cache;
466 MemberCache member_cache;
468 public const string DefaultIndexerName = "Item";
470 public TypeContainer PartialContainer;
471 ArrayList partial_parts;
474 /// The pending methods that need to be implemented
475 // (interfaces or abstract methods)
477 PendingImplementation pending;
479 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
480 Attributes attrs, Kind kind)
481 : base (ns, parent, name, attrs)
483 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
484 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
487 this.PartialContainer = this;
490 public bool AddToMemberContainer (MemberCore symbol)
492 return AddToContainer (symbol, symbol.Name);
495 protected virtual bool AddToTypeContainer (DeclSpace ds)
497 return AddToContainer (ds, ds.Basename);
500 public void AddConstant (Const constant)
502 if (!AddToMemberContainer (constant))
505 if (constants == null)
506 constants = new MemberCoreArrayList ();
508 constants.Add (constant);
511 public void AddEnum (Mono.CSharp.Enum e)
513 if (!AddToTypeContainer (e))
517 enums = new MemberCoreArrayList ();
522 public bool AddClassOrStruct (TypeContainer c)
524 if (!AddToTypeContainer (c))
528 types = new ArrayList (2);
530 RootContext.Tree.RecordDecl (c.NamespaceEntry.NS, c.MemberName, c);
535 public virtual TypeContainer AddPartial (TypeContainer nextPart)
537 return AddPartial (nextPart, nextPart.Basename);
540 protected TypeContainer AddPartial (TypeContainer nextPart, string name)
542 nextPart.ModFlags |= Modifiers.PARTIAL;
543 TypeContainer tc = defined_names [name] as TypeContainer;
546 if (nextPart is Interface)
547 AddInterface (nextPart);
549 AddClassOrStruct (nextPart);
553 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
554 Report.SymbolRelatedToPreviousError (tc);
555 Error_MissingPartialModifier (nextPart);
559 if (tc.Kind != nextPart.Kind) {
560 Report.SymbolRelatedToPreviousError (tc);
561 Report.Error (261, nextPart.Location,
562 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
563 nextPart.GetSignatureForError ());
567 if ((tc.ModFlags & Modifiers.Accessibility) != (nextPart.ModFlags & Modifiers.Accessibility)) {
568 Report.SymbolRelatedToPreviousError (tc);
569 Report.Error (262, nextPart.Location,
570 "Partial declarations of `{0}' have conflicting accessibility modifiers",
571 nextPart.GetSignatureForError ());
575 if (tc.partial_parts == null)
576 tc.partial_parts = new ArrayList (1);
578 tc.ModFlags |= nextPart.ModFlags;
579 if (nextPart.attributes != null) {
580 if (tc.attributes == null)
581 tc.attributes = nextPart.attributes;
583 tc.attributes.AddAttributes (nextPart.attributes.Attrs);
586 nextPart.PartialContainer = tc;
587 tc.partial_parts.Add (nextPart);
591 public void AddDelegate (Delegate d)
593 if (!AddToTypeContainer (d))
596 if (delegates == null)
597 delegates = new MemberCoreArrayList ();
602 public void AddMethod (Method method)
604 if (!AddToMemberContainer (method))
608 methods = new MethodArrayList (this);
610 if (method.MemberName.Left != null)
611 methods.Insert (0, method);
613 methods.Add (method);
617 // Do not use this method: use AddMethod.
619 // This is only used by iterators.
621 public void AppendMethod (Method method)
623 if (!AddToMemberContainer (method))
627 methods = new MethodArrayList (this);
629 methods.Add (method);
632 public void AddConstructor (Constructor c)
634 if (c.Name != Basename) {
635 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
638 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
641 if (default_static_constructor != null) {
642 Report.SymbolRelatedToPreviousError (default_static_constructor);
643 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
647 default_static_constructor = c;
650 if (default_constructor != null) {
651 Report.SymbolRelatedToPreviousError (default_constructor);
652 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
655 default_constructor = c;
658 if (instance_constructors == null)
659 instance_constructors = new MemberCoreArrayList ();
661 instance_constructors.Add (c);
665 internal static string Error111 {
667 return "`{0}' is already defined. Rename this member or use different parameter types";
671 public bool AddInterface (TypeContainer iface)
673 if (!AddToTypeContainer (iface))
676 if (interfaces == null) {
677 interfaces = new MemberCoreArrayList ();
680 RootContext.Tree.RecordDecl (iface.NamespaceEntry.NS, iface.MemberName, iface);
681 interfaces.Add (iface);
685 public void AddField (FieldMember field)
687 if (!AddToMemberContainer (field))
691 fields = new MemberCoreArrayList ();
695 if ((field.ModFlags & Modifiers.STATIC) != 0)
698 if (first_nonstatic_field == null) {
699 first_nonstatic_field = field;
703 if (Kind == Kind.Struct &&
704 first_nonstatic_field.Parent != field.Parent &&
705 RootContext.WarningLevel >= 3) {
706 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
707 Report.Warning (282, 3, field.Location,
708 "struct instance field `{0}' found in different declaration from instance field `{1}'",
709 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
713 public void AddProperty (Property prop)
715 if (!AddToMemberContainer (prop) ||
716 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
719 if (properties == null)
720 properties = new MemberCoreArrayList ();
722 if (prop.MemberName.Left != null)
723 properties.Insert (0, prop);
725 properties.Add (prop);
728 public void AddEvent (Event e)
730 if (!AddToMemberContainer (e))
733 if (e is EventProperty) {
734 if (!AddToMemberContainer (e.Add))
737 if (!AddToMemberContainer (e.Remove))
742 events = new MemberCoreArrayList ();
749 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
751 public void AddIndexer (Indexer i)
753 if (indexers == null)
754 indexers = new IndexerArrayList (this);
756 if (i.IsExplicitImpl)
757 indexers.Insert (0, i);
762 public void AddOperator (Operator op)
764 if (!AddToMemberContainer (op))
767 if (operators == null)
768 operators = new OperatorArrayList (this);
773 public void AddIterator (Iterator i)
775 if (iterators == null)
776 iterators = new ArrayList ();
781 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
783 if (a.Type == TypeManager.default_member_type) {
784 if (Indexers != null) {
785 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
790 base.ApplyAttributeBuilder (a, cb);
793 public override AttributeTargets AttributeTargets {
795 throw new NotSupportedException ();
799 public ArrayList Types {
805 public MethodArrayList Methods {
811 public ArrayList Constants {
817 public ArrayList Interfaces {
823 public ArrayList Iterators {
829 protected Type BaseType {
831 return TypeBuilder.BaseType;
835 public ArrayList Bases {
845 public ArrayList Fields {
851 public ArrayList InstanceConstructors {
853 return instance_constructors;
857 public ArrayList Properties {
863 public ArrayList Events {
869 public ArrayList Enums {
875 public ArrayList Indexers {
881 public ArrayList Operators {
887 public ArrayList Delegates {
893 protected override TypeAttributes TypeAttr {
895 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
899 public string IndexerName {
901 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
905 public bool IsComImport {
907 if (OptAttributes == null)
910 return OptAttributes.Contains (TypeManager.comimport_attr_type);
914 public virtual void RegisterFieldForInitialization (FieldBase field)
916 if ((field.ModFlags & Modifiers.STATIC) != 0){
917 if (initialized_static_fields == null)
918 initialized_static_fields = new ArrayList (4);
920 initialized_static_fields.Add (field);
922 if (initialized_fields == null)
923 initialized_fields = new ArrayList (4);
925 initialized_fields.Add (field);
930 // Emits the instance field initializers
932 public bool EmitFieldInitializers (EmitContext ec)
937 fields = initialized_static_fields;
939 fields = initialized_fields;
945 foreach (FieldBase f in fields) {
946 f.EmitInitializer (ec);
952 // Defines the default constructors
954 protected void DefineDefaultConstructor (bool is_static)
956 // The default instance constructor is public
957 // If the class is abstract, the default constructor is protected
958 // The default static constructor is private
962 if (initialized_static_fields == null || default_static_constructor != null)
964 mods = Modifiers.STATIC | Modifiers.PRIVATE;
966 if (instance_constructors != null)
969 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
972 Constructor c = new Constructor (this, Basename, mods,
973 Parameters.EmptyReadOnlyParameters,
974 new GeneratedBaseInitializer (Location),
978 c.Block = new ToplevelBlock (null, Location);
981 public override string DocComment {
993 public PendingImplementation PendingImplementations {
994 get { return pending; }
997 public override bool GetClsCompliantAttributeValue ()
999 if (PartialContainer != this)
1000 return PartialContainer.GetClsCompliantAttributeValue ();
1002 return base.GetClsCompliantAttributeValue ();
1005 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1011 int count = Bases.Count;
1012 int start = 0, i, j;
1014 if (Kind == Kind.Class){
1015 TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
1021 if (!name.IsInterface) {
1022 // base_class could be a class, struct, enum, delegate.
1023 // This is validated in GetClassBases.
1029 TypeExpr [] ifaces = new TypeExpr [count-start];
1031 for (i = start, j = 0; i < count; i++, j++){
1032 TypeExpr resolved = ((Expression) Bases [i]).ResolveAsTypeTerminal (this, false);
1033 if (resolved == null) {
1037 ifaces [j] = resolved;
1040 return ifaces.Length == 0 ? null : ifaces;
1044 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
1046 ArrayList ifaces = new ArrayList (0);
1047 if (iface_exprs != null)
1048 ifaces.AddRange (iface_exprs);
1050 foreach (TypeContainer part in partial_parts) {
1051 TypeExpr new_base_class;
1052 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
1053 if (new_base_class != TypeManager.system_object_expr) {
1054 if (base_class == TypeManager.system_object_expr)
1055 base_class = new_base_class;
1057 if (new_base_class != null && !new_base_class.Equals (base_class)) {
1058 Report.SymbolRelatedToPreviousError (base_class.Location, "");
1059 Report.Error (263, part.Location,
1060 "Partial declarations of `{0}' must not specify different base classes",
1061 part.GetSignatureForError ());
1068 if (new_ifaces == null)
1071 foreach (TypeExpr iface in new_ifaces) {
1072 if (ifaces.Contains (iface))
1079 if (ifaces.Count == 0)
1082 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
1086 /// This function computes the Base class and also the
1087 /// list of interfaces that the class or struct @c implements.
1089 /// The return value is an array (might be null) of
1090 /// interfaces implemented (as Types).
1092 /// The @base_class argument is set to the base object or null
1093 /// if this is `System.Object'.
1095 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1097 TypeExpr[] ifaces = GetNormalBases (out base_class);
1102 int count = ifaces.Length;
1104 for (int i = 0; i < count; i++) {
1105 TypeExpr iface = (TypeExpr) ifaces [i];
1107 if (!iface.IsInterface) {
1108 if (Kind != Kind.Class) {
1109 // TODO: location of symbol related ....
1110 Error_TypeInListIsNotInterface (Location, iface.FullName);
1112 else if (base_class != null)
1113 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1114 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1116 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1117 GetSignatureForError (), iface.GetSignatureForError ());
1122 for (int x = 0; x < i; x++) {
1123 if (iface.Equals (ifaces [x])) {
1124 Report.Error (528, Location,
1125 "`{0}' is already listed in " +
1126 "interface list", iface.GetSignatureForError ());
1131 if ((Kind == Kind.Interface) &&
1132 !iface.AsAccessible (Parent, ModFlags)) {
1133 Report.Error (61, Location,
1134 "Inconsistent accessibility: base " +
1135 "interface `{0}' is less accessible " +
1136 "than interface `{1}'", iface.Name,
1146 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1148 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1151 bool DefineTypeBuilder ()
1155 if (TypeManager.NamespaceClash (Name, Location)) {
1159 ModuleBuilder builder = CodeGen.Module.Builder;
1160 TypeBuilder = builder.DefineType (
1161 Name, TypeAttr, null, null);
1163 TypeBuilder builder = Parent.TypeBuilder;
1165 TypeBuilder = builder.DefineNestedType (
1166 Basename, TypeAttr, null, null);
1168 } catch (ArgumentException) {
1169 Report.RuntimeMissingSupport (Location, "static classes");
1173 TypeManager.AddUserType (this);
1175 iface_exprs = GetClassBases (out base_type);
1176 if (partial_parts != null) {
1177 iface_exprs = GetNormalPartialBases (ref base_type);
1181 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1182 // which in turn should have called DefineType()s on base types if necessary.
1184 // None of the code below should trigger DefineType()s on classes that we depend on.
1185 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1187 // Let's do it as soon as possible, since code below can call DefineType() on classes
1188 // that depend on us to be populated before they are.
1190 if (!(this is Iterator))
1191 RootContext.RegisterOrder (this);
1194 if (base_type != null) {
1195 TypeBuilder.SetParent (base_type.Type);
1197 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1198 if (obsolete_attr != null && !IsInObsoleteScope) {
1199 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1203 if (!CheckRecursiveDefinition (this)) {
1207 // add interfaces that were not added at type creation
1208 if (iface_exprs != null) {
1209 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1210 if (ifaces == null) {
1214 foreach (Type itype in ifaces)
1215 TypeBuilder.AddInterfaceImplementation (itype);
1217 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1224 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1226 public override TypeBuilder DefineType ()
1228 if (TypeBuilder != null)
1234 if (!DefineTypeBuilder ()) {
1239 if (partial_parts != null) {
1240 foreach (TypeContainer part in partial_parts)
1241 part.TypeBuilder = TypeBuilder;
1244 DefineNestedTypes ();
1249 protected virtual bool DefineNestedTypes ()
1251 if (Interfaces != null) {
1252 foreach (TypeContainer iface in Interfaces)
1253 if (iface.DefineType () == null)
1257 if (Types != null) {
1258 foreach (TypeContainer tc in Types)
1259 if (tc.DefineType () == null)
1263 if (Delegates != null) {
1264 foreach (Delegate d in Delegates)
1265 if (d.DefineType () == null)
1269 if (Enums != null) {
1270 foreach (Enum en in Enums)
1271 if (en.DefineType () == null)
1278 TypeContainer InTransit;
1280 protected bool CheckRecursiveDefinition (TypeContainer tc)
1282 if (InTransit != null) {
1283 Report.SymbolRelatedToPreviousError (this);
1284 if (this is Interface)
1286 529, tc.Location, "Inherited interface `{0}' causes a " +
1287 "cycle in the interface hierarchy of `{1}'",
1288 GetSignatureForError (), tc.GetSignatureForError ());
1291 146, tc.Location, "Circular base class dependency " +
1292 "involving `{0}' and `{1}'",
1293 tc.GetSignatureForError (), GetSignatureForError ());
1299 if (BaseType != null) {
1300 TypeContainer ptc = TypeManager.LookupTypeContainer (BaseType);
1301 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1305 if (iface_exprs != null) {
1306 foreach (TypeExpr iface in iface_exprs) {
1307 Type itype = iface.Type;
1309 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1310 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1319 public static void Error_KeywordNotAllowed (Location loc)
1321 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1325 /// Populates our TypeBuilder with fields and methods
1327 public override bool DefineMembers ()
1329 if (members_defined)
1330 return members_defined_ok;
1332 if (!base.DefineMembers ())
1335 members_defined_ok = DoDefineMembers ();
1336 members_defined = true;
1338 return members_defined_ok;
1341 public virtual void DefineDefaultConstructor ()
1345 protected virtual bool DoDefineMembers ()
1348 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1349 if (conflict_symbol == null) {
1350 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1351 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1353 if ((ModFlags & Modifiers.NEW) == 0) {
1354 Report.SymbolRelatedToPreviousError (conflict_symbol);
1355 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1356 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1361 DefineContainerMembers (constants);
1362 DefineContainerMembers (fields);
1364 DefineDefaultConstructor ();
1366 if (Kind == Kind.Struct || Kind == Kind.Class) {
1367 pending = PendingImplementation.GetPendingImplementations (this);
1371 // Constructors are not in the defined_names array
1373 DefineContainerMembers (instance_constructors);
1375 if (default_static_constructor != null)
1376 default_static_constructor.Define ();
1378 DefineContainerMembers (properties);
1379 DefineContainerMembers (events);
1380 DefineContainerMembers (indexers);
1381 DefineContainerMembers (methods);
1382 DefineContainerMembers (operators);
1383 DefineContainerMembers (enums);
1384 DefineContainerMembers (delegates);
1387 member_cache = new MemberCache (this);
1388 if (partial_parts != null) {
1389 foreach (TypeContainer part in partial_parts)
1390 part.member_cache = member_cache;
1393 if (iterators != null) {
1394 foreach (Iterator iterator in iterators) {
1395 if (iterator.DefineType () == null)
1399 foreach (Iterator iterator in iterators) {
1400 if (!iterator.DefineMembers ())
1408 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1411 mcal.DefineContainerMembers ();
1414 public override bool Define ()
1416 if (iterators != null) {
1417 foreach (Iterator iterator in iterators) {
1418 if (!iterator.Define ())
1426 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1428 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1432 /// This function is based by a delegate to the FindMembers routine
1434 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1440 /// This filter is used by FindMembers, and we just keep
1441 /// a global for the filter to `AlwaysAccept'
1443 static MemberFilter accepting_filter;
1446 static TypeContainer ()
1448 accepting_filter = new MemberFilter (AlwaysAccept);
1451 public MethodInfo[] GetMethods ()
1453 ArrayList members = new ArrayList ();
1457 if (methods != null) {
1458 int len = methods.Count;
1459 for (int i = 0; i < len; i++) {
1460 Method m = (Method) methods [i];
1462 members.Add (m.MethodBuilder);
1466 if (operators != null) {
1467 int len = operators.Count;
1468 for (int i = 0; i < len; i++) {
1469 Operator o = (Operator) operators [i];
1471 members.Add (o.OperatorMethodBuilder);
1475 if (properties != null) {
1476 int len = properties.Count;
1477 for (int i = 0; i < len; i++) {
1478 Property p = (Property) properties [i];
1480 if (p.GetBuilder != null)
1481 members.Add (p.GetBuilder);
1482 if (p.SetBuilder != null)
1483 members.Add (p.SetBuilder);
1487 if (indexers != null) {
1488 int len = indexers.Count;
1489 for (int i = 0; i < len; i++) {
1490 Indexer ix = (Indexer) indexers [i];
1492 if (ix.GetBuilder != null)
1493 members.Add (ix.GetBuilder);
1494 if (ix.SetBuilder != null)
1495 members.Add (ix.SetBuilder);
1499 if (events != null) {
1500 int len = events.Count;
1501 for (int i = 0; i < len; i++) {
1502 Event e = (Event) events [i];
1504 if (e.AddBuilder != null)
1505 members.Add (e.AddBuilder);
1506 if (e.RemoveBuilder != null)
1507 members.Add (e.RemoveBuilder);
1511 MethodInfo[] retMethods = new MethodInfo [members.Count];
1512 members.CopyTo (retMethods, 0);
1516 // Indicated whether container has StructLayout attribute set Explicit
1517 public bool HasExplicitLayout {
1519 return (caching_flags & Flags.HasExplicitLayout) != 0;
1522 caching_flags |= Flags.HasExplicitLayout;
1526 public override Type FindNestedType (string name)
1528 if (PartialContainer != this)
1529 return PartialContainer.FindNestedType (name);
1531 ArrayList [] lists = { types, enums, delegates, interfaces };
1533 for (int j = 0; j < lists.Length; ++j) {
1534 ArrayList list = lists [j];
1538 int len = list.Count;
1539 for (int i = 0; i < len; ++i) {
1540 DeclSpace ds = (DeclSpace) list [i];
1541 if (ds.Basename == name) {
1542 return ds.DefineType ();
1550 private void FindMembers_NestedTypes (int modflags,
1551 BindingFlags bf, MemberFilter filter, object criteria,
1552 ref ArrayList members)
1554 ArrayList [] lists = { types, enums, delegates, interfaces };
1556 for (int j = 0; j < lists.Length; ++j) {
1557 ArrayList list = lists [j];
1561 int len = list.Count;
1562 for (int i = 0; i < len; i++) {
1563 DeclSpace ds = (DeclSpace) list [i];
1565 if ((ds.ModFlags & modflags) == 0)
1568 TypeBuilder tb = ds.TypeBuilder;
1570 if (!(criteria is string) || ds.Basename.Equals (criteria))
1571 tb = ds.DefineType ();
1574 if (tb != null && (filter (tb, criteria) == true)) {
1575 if (members == null)
1576 members = new ArrayList ();
1585 /// This method returns the members of this type just like Type.FindMembers would
1586 /// Only, we need to use this for types which are _being_ defined because MS'
1587 /// implementation can't take care of that.
1590 // FIXME: return an empty static array instead of null, that cleans up
1591 // some code and is consistent with some coding conventions I just found
1595 // Notice that in various cases we check if our field is non-null,
1596 // something that would normally mean that there was a bug elsewhere.
1598 // The problem happens while we are defining p-invoke methods, as those
1599 // will trigger a FindMembers, but this happens before things are defined
1601 // Since the whole process is a no-op, it is fine to check for null here.
1603 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1604 MemberFilter filter, object criteria)
1606 ArrayList members = null;
1609 if ((bf & BindingFlags.Public) != 0)
1610 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1612 if ((bf & BindingFlags.NonPublic) != 0)
1613 modflags |= Modifiers.PRIVATE;
1615 int static_mask = 0, static_flags = 0;
1616 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1617 case BindingFlags.Static:
1618 static_mask = static_flags = Modifiers.STATIC;
1621 case BindingFlags.Instance:
1622 static_mask = Modifiers.STATIC;
1627 static_mask = static_flags = 0;
1631 Timer.StartTimer (TimerType.TcFindMembers);
1634 filter = accepting_filter;
1636 if ((mt & MemberTypes.Field) != 0) {
1637 if (fields != null) {
1638 int len = fields.Count;
1639 for (int i = 0; i < len; i++) {
1640 FieldMember f = (FieldMember) fields [i];
1642 if ((f.ModFlags & modflags) == 0)
1644 if ((f.ModFlags & static_mask) != static_flags)
1647 FieldBuilder fb = f.FieldBuilder;
1648 if (fb != null && filter (fb, criteria) == true) {
1649 if (members == null)
1650 members = new ArrayList ();
1657 if (constants != null) {
1658 int len = constants.Count;
1659 for (int i = 0; i < len; i++) {
1660 Const con = (Const) constants [i];
1662 if ((con.ModFlags & modflags) == 0)
1664 if ((con.ModFlags & static_mask) != static_flags)
1667 FieldBuilder fb = con.FieldBuilder;
1670 fb = con.FieldBuilder;
1672 if (fb != null && filter (fb, criteria) == true) {
1673 if (members == null)
1674 members = new ArrayList ();
1682 if ((mt & MemberTypes.Method) != 0) {
1683 if (methods != null) {
1684 int len = methods.Count;
1685 for (int i = 0; i < len; i++) {
1686 Method m = (Method) methods [i];
1688 if ((m.ModFlags & modflags) == 0)
1690 if ((m.ModFlags & static_mask) != static_flags)
1693 MethodBuilder mb = m.MethodBuilder;
1695 if (mb != null && filter (mb, criteria) == true) {
1696 if (members == null)
1697 members = new ArrayList ();
1704 if (operators != null) {
1705 int len = operators.Count;
1706 for (int i = 0; i < len; i++) {
1707 Operator o = (Operator) operators [i];
1709 if ((o.ModFlags & modflags) == 0)
1711 if ((o.ModFlags & static_mask) != static_flags)
1714 MethodBuilder ob = o.OperatorMethodBuilder;
1715 if (ob != null && filter (ob, criteria) == true) {
1716 if (members == null)
1717 members = new ArrayList ();
1724 if (properties != null) {
1725 int len = properties.Count;
1726 for (int i = 0; i < len; i++) {
1727 Property p = (Property) properties [i];
1729 if ((p.ModFlags & modflags) == 0)
1731 if ((p.ModFlags & static_mask) != static_flags)
1737 if (b != null && filter (b, criteria) == true) {
1738 if (members == null)
1739 members = new ArrayList ();
1745 if (b != null && filter (b, criteria) == true) {
1746 if (members == null)
1747 members = new ArrayList ();
1754 if (indexers != null) {
1755 int len = indexers.Count;
1756 for (int i = 0; i < len; i++) {
1757 Indexer ix = (Indexer) indexers [i];
1759 if ((ix.ModFlags & modflags) == 0)
1761 if ((ix.ModFlags & static_mask) != static_flags)
1767 if (b != null && filter (b, criteria) == true) {
1768 if (members == null)
1769 members = new ArrayList ();
1775 if (b != null && filter (b, criteria) == true) {
1776 if (members == null)
1777 members = new ArrayList ();
1785 if ((mt & MemberTypes.Event) != 0) {
1786 if (events != null) {
1787 int len = events.Count;
1788 for (int i = 0; i < len; i++) {
1789 Event e = (Event) events [i];
1791 if ((e.ModFlags & modflags) == 0)
1793 if ((e.ModFlags & static_mask) != static_flags)
1796 MemberInfo eb = e.EventBuilder;
1797 if (eb != null && filter (eb, criteria) == true) {
1798 if (members == null)
1799 members = new ArrayList ();
1801 members.Add (e.EventBuilder);
1807 if ((mt & MemberTypes.Property) != 0){
1808 if (properties != null) {
1809 int len = properties.Count;
1810 for (int i = 0; i < len; i++) {
1811 Property p = (Property) properties [i];
1813 if ((p.ModFlags & modflags) == 0)
1815 if ((p.ModFlags & static_mask) != static_flags)
1818 MemberInfo pb = p.PropertyBuilder;
1819 if (pb != null && filter (pb, criteria) == true) {
1820 if (members == null)
1821 members = new ArrayList ();
1823 members.Add (p.PropertyBuilder);
1828 if (indexers != null) {
1829 int len = indexers.Count;
1830 for (int i = 0; i < len; i++) {
1831 Indexer ix = (Indexer) indexers [i];
1833 if ((ix.ModFlags & modflags) == 0)
1835 if ((ix.ModFlags & static_mask) != static_flags)
1838 MemberInfo ib = ix.PropertyBuilder;
1839 if (ib != null && filter (ib, criteria) == true) {
1840 if (members == null)
1841 members = new ArrayList ();
1843 members.Add (ix.PropertyBuilder);
1849 if ((mt & MemberTypes.NestedType) != 0)
1850 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1852 if ((mt & MemberTypes.Constructor) != 0){
1853 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1854 int len = instance_constructors.Count;
1855 for (int i = 0; i < len; i++) {
1856 Constructor c = (Constructor) instance_constructors [i];
1858 ConstructorBuilder cb = c.ConstructorBuilder;
1859 if (cb != null && filter (cb, criteria) == true) {
1860 if (members == null)
1861 members = new ArrayList ();
1868 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1869 ConstructorBuilder cb =
1870 default_static_constructor.ConstructorBuilder;
1872 if (cb != null && filter (cb, criteria) == true) {
1873 if (members == null)
1874 members = new ArrayList ();
1882 // Lookup members in base if requested.
1884 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1885 if (TypeBuilder.BaseType != null) {
1886 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1887 if (list.Count > 0) {
1888 if (members == null)
1889 members = new ArrayList ();
1891 members.AddRange (list);
1894 if (ifaces != null) {
1895 foreach (Type base_type in ifaces) {
1896 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1898 if (list.Count > 0) {
1899 if (members == null)
1900 members = new ArrayList ();
1901 members.AddRange (list);
1907 Timer.StopTimer (TimerType.TcFindMembers);
1909 if (members == null)
1910 return MemberList.Empty;
1912 return new MemberList (members);
1915 public override MemberCache MemberCache {
1917 return member_cache;
1921 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1922 MemberFilter filter, object criteria)
1924 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1927 return ds.FindMembers (mt, bf, filter, criteria);
1929 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1934 /// Emits the values for the constants
1936 public void EmitConstants ()
1938 if (constants != null)
1939 foreach (Const con in constants)
1944 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
1949 foreach (MemberCore mc in al) {
1950 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1954 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1959 public virtual void VerifyMembers ()
1962 // Check for internal or private fields that were never assigned
1964 if (RootContext.WarningLevel >= 3) {
1965 CheckMemberUsage (properties, "property");
1966 CheckMemberUsage (methods, "method");
1967 CheckMemberUsage (constants, "constant");
1969 if (fields != null){
1970 foreach (FieldMember f in fields) {
1971 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1975 if ((f.caching_flags & Flags.IsAssigned) == 0)
1976 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1979 const int error_code = 414;
1981 const int error_code = 169;
1983 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1984 f.GetSignatureForError ());
1990 // Only report 649 on level 4
1992 if (RootContext.WarningLevel < 4)
1995 if ((f.caching_flags & Flags.IsAssigned) != 0)
1998 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1999 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2005 // TODO: move to ClassOrStruct
2006 void EmitConstructors ()
2008 if (instance_constructors == null)
2011 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2012 bool has_compliant_args = false;
2014 foreach (Constructor c in instance_constructors) {
2017 if (has_compliant_args)
2020 has_compliant_args = c.HasCompliantArgs;
2022 if (!has_compliant_args)
2023 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2025 foreach (Constructor c in instance_constructors)
2031 /// Emits the code, this step is performed after all
2032 /// the types, enumerations, constructors
2034 public virtual void EmitType ()
2036 if (OptAttributes != null)
2037 OptAttributes.Emit ();
2040 // Structs with no fields need to have at least one byte.
2041 // The right thing would be to set the PackingSize in a DefineType
2042 // but there are no functions that allow interfaces *and* the size to
2046 if (Kind == Kind.Struct && first_nonstatic_field == null){
2047 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2048 FieldAttributes.Private);
2050 if (HasExplicitLayout){
2051 object [] ctor_args = new object [1];
2054 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2055 TypeManager.field_offset_attribute_ctor, ctor_args);
2056 fb.SetCustomAttribute (cba);
2062 EmitConstructors ();
2064 // Can not continue if constants are broken
2066 if (Report.Errors > 0)
2069 if (default_static_constructor != null)
2070 default_static_constructor.Emit ();
2072 if (methods != null){
2073 foreach (Method m in methods)
2077 if (operators != null)
2078 foreach (Operator o in operators)
2081 if (properties != null)
2082 foreach (Property p in properties)
2085 if (indexers != null){
2090 foreach (FieldMember f in fields)
2093 if (events != null){
2094 foreach (Event e in Events)
2098 if (delegates != null) {
2099 foreach (Delegate d in Delegates) {
2104 if (enums != null) {
2105 foreach (Enum e in enums) {
2110 if (pending != null)
2111 if (pending.VerifyPendingMethods ())
2114 if (iterators != null)
2115 foreach (Iterator iterator in iterators)
2116 iterator.EmitType ();
2119 public override void CloseType ()
2121 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2125 caching_flags |= Flags.CloseTypeCreated;
2126 TypeBuilder.CreateType ();
2127 } catch (TypeLoadException){
2129 // This is fine, the code still created the type
2131 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2132 // Console.WriteLine (e.Message);
2134 Console.WriteLine ("In type: " + Name);
2139 foreach (Enum en in Enums)
2143 foreach (TypeContainer tc in Types)
2144 if (tc.Kind == Kind.Struct)
2147 foreach (TypeContainer tc in Types)
2148 if (tc.Kind != Kind.Struct)
2152 if (Delegates != null)
2153 foreach (Delegate d in Delegates)
2156 if (Iterators != null)
2157 foreach (Iterator i in Iterators)
2165 initialized_fields = null;
2166 initialized_static_fields = null;
2174 default_constructor = null;
2175 default_static_constructor = null;
2177 OptAttributes = null;
2180 member_cache = null;
2184 // Performs the validation on a Method's modifiers (properties have
2185 // the same properties).
2187 public bool MethodModifiersValid (MemberCore mc)
2189 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2190 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2191 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2193 int flags = mc.ModFlags;
2196 // At most one of static, virtual or override
2198 if ((flags & Modifiers.STATIC) != 0){
2199 if ((flags & vao) != 0){
2200 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2201 mc.GetSignatureForError ());
2206 if (Kind == Kind.Struct){
2207 if ((flags & va) != 0){
2208 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2213 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2214 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2215 mc.GetSignatureForError ());
2220 // If the declaration includes the abstract modifier, then the
2221 // declaration does not include static, virtual or extern
2223 if ((flags & Modifiers.ABSTRACT) != 0){
2224 if ((flags & Modifiers.EXTERN) != 0){
2226 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2230 if ((flags & Modifiers.SEALED) != 0) {
2231 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2235 if ((flags & Modifiers.VIRTUAL) != 0){
2236 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2240 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2241 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2246 if ((flags & Modifiers.PRIVATE) != 0){
2247 if ((flags & vao) != 0){
2248 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2253 if ((flags & Modifiers.SEALED) != 0){
2254 if ((flags & Modifiers.OVERRIDE) == 0){
2255 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2263 public bool UserDefinedStaticConstructor {
2265 return default_static_constructor != null;
2269 public Constructor DefaultStaticConstructor {
2270 get { return default_static_constructor; }
2273 protected override bool VerifyClsCompliance ()
2275 if (!base.VerifyClsCompliance ())
2280 Type base_type = TypeBuilder.BaseType;
2281 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2282 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2285 if (!Parent.IsClsComplianceRequired ()) {
2286 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
2287 GetSignatureForError (), Parent.GetSignatureForError ());
2294 /// Checks whether container name is CLS Compliant
2296 void VerifyClsName ()
2298 Hashtable base_members = base_cache == null ?
2300 base_cache.GetPublicMembers ();
2301 Hashtable this_members = new Hashtable ();
2303 foreach (DictionaryEntry entry in defined_names) {
2304 MemberCore mc = (MemberCore)entry.Value;
2305 if (!mc.IsClsComplianceRequired ())
2308 string name = (string) entry.Key;
2309 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2311 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2312 object found = base_members [lcase];
2313 if (found == null) {
2314 found = this_members [lcase];
2315 if (found == null) {
2316 this_members.Add (lcase, mc);
2321 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2324 if (found is MemberInfo) {
2325 if (basename == ((MemberInfo) found).Name)
2327 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2329 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2331 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2337 /// Performs checks for an explicit interface implementation. First it
2338 /// checks whether the `interface_type' is a base inteface implementation.
2339 /// Then it checks whether `name' exists in the interface type.
2341 public virtual bool VerifyImplements (MemberBase mb)
2343 if (ifaces != null) {
2344 foreach (Type t in ifaces){
2345 if (t == mb.InterfaceType)
2350 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2351 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2352 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2356 public void Mark_HasEquals ()
2358 Methods.HasEquals = true;
2361 public void Mark_HasGetHashCode ()
2363 Methods.HasGetHashCode = true;
2370 string IMemberContainer.Name {
2376 Type IMemberContainer.Type {
2382 MemberCache IMemberContainer.MemberCache {
2384 return member_cache;
2388 bool IMemberContainer.IsInterface {
2390 return Kind == Kind.Interface;
2394 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2396 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2400 // Generates xml doc comments (if any), and if required,
2401 // handle warning report.
2403 internal override void GenerateDocComment (DeclSpace ds)
2405 DocUtil.GenerateTypeDocComment (this, ds);
2408 public override string DocCommentHeader {
2409 get { return "T:"; }
2412 public virtual MemberCache BaseCache {
2414 if (base_cache != null)
2416 if (TypeBuilder.BaseType != null)
2417 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2418 if (TypeBuilder.IsInterface)
2419 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2425 public abstract class ClassOrStruct : TypeContainer {
2426 ListDictionary declarative_security;
2428 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2429 MemberName name, Attributes attrs, Kind kind)
2430 : base (ns, parent, name, attrs, kind)
2434 protected override bool AddToContainer (MemberCore symbol, string name)
2436 if (name == Basename) {
2437 Report.SymbolRelatedToPreviousError (this);
2438 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2439 symbol.GetSignatureForError ());
2443 return base.AddToContainer (symbol, name);
2447 public override void DefineDefaultConstructor ()
2449 DefineDefaultConstructor (true);
2452 public override void VerifyMembers ()
2454 base.VerifyMembers ();
2456 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2457 foreach (Event e in events){
2458 if ((e.caching_flags & Flags.IsAssigned) == 0)
2459 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2464 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2466 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2467 if (declarative_security == null)
2468 declarative_security = new ListDictionary ();
2470 a.ExtractSecurityPermissionSet (declarative_security);
2474 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2475 HasExplicitLayout = true;
2478 base.ApplyAttributeBuilder (a, cb);
2481 public override void Emit()
2485 if (declarative_security != null) {
2486 foreach (DictionaryEntry de in declarative_security) {
2487 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2494 // TODO: should be sealed
2495 public class Class : ClassOrStruct {
2496 const int AllowedModifiers =
2499 Modifiers.PROTECTED |
2500 Modifiers.INTERNAL |
2502 Modifiers.ABSTRACT |
2507 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2509 : base (ns, parent, name, attrs, Kind.Class)
2511 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2512 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2514 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2515 Report.FeatureIsNotStandardized (Location, "static classes");
2519 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2521 if (a.Type == TypeManager.attribute_usage_type) {
2522 if (BaseType != TypeManager.attribute_type && !BaseType.IsSubclassOf (TypeManager.attribute_type) &&
2523 TypeBuilder.FullName != "System.Attribute") {
2524 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2528 if (a.Type == TypeManager.conditional_attribute_type &&
2529 !(BaseType == TypeManager.attribute_type || BaseType.IsSubclassOf (TypeManager.attribute_type))) {
2530 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2534 if (AttributeTester.IsAttributeExcluded (a.Type))
2537 base.ApplyAttributeBuilder (a, cb);
2540 public override AttributeTargets AttributeTargets {
2542 return AttributeTargets.Class;
2546 protected override void DefineContainerMembers (MemberCoreArrayList list)
2552 base.DefineContainerMembers (list);
2556 foreach (MemberCore m in list) {
2557 if (m is Operator) {
2558 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2562 if (m is Destructor) {
2563 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2567 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2568 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
2573 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2577 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2580 if (m is Constructor) {
2581 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2585 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2588 base.DefineContainerMembers (list);
2591 public override void DefineDefaultConstructor ()
2594 DefineDefaultConstructor (false);
2596 base.DefineDefaultConstructor ();
2599 public override TypeBuilder DefineType ()
2601 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2602 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2606 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2607 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2611 return base.DefineType ();
2614 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2616 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2618 if (base_class == null) {
2619 if (RootContext.StdLib)
2620 base_class = TypeManager.system_object_expr;
2621 else if (Name != "System.Object")
2622 base_class = TypeManager.system_object_expr;
2624 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
2625 Report.Error (1521, base_class.Location, "Invalid base type");
2629 if (base_class.IsSealed){
2630 Report.SymbolRelatedToPreviousError (base_class.Type);
2631 if (base_class.Type.IsAbstract) {
2632 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2633 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2635 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2636 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2641 if (!base_class.CanInheritFrom ()){
2642 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2643 GetSignatureForError (), base_class.GetSignatureForError ());
2647 if (!base_class.AsAccessible (this, ModFlags)) {
2648 Report.SymbolRelatedToPreviousError (base_class.Type);
2649 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2650 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2655 if (base_class != TypeManager.system_object_expr) {
2656 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2657 GetSignatureForError (), base_class.GetSignatureForError ());
2661 if (ifaces != null) {
2662 foreach (TypeExpr t in ifaces)
2663 Report.SymbolRelatedToPreviousError (t.Type);
2664 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2671 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2672 /// Valid only for attribute classes.
2673 public bool IsExcluded ()
2675 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2676 return (caching_flags & Flags.Excluded) != 0;
2678 caching_flags &= ~Flags.Excluded_Undetected;
2680 if (OptAttributes == null)
2683 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2688 foreach (Attribute a in attrs) {
2689 string condition = a.GetConditionalAttributeValue ();
2690 if (RootContext.AllDefines.Contains (condition))
2694 caching_flags |= Flags.Excluded;
2700 return (ModFlags & Modifiers.STATIC) != 0;
2705 // FIXME: How do we deal with the user specifying a different
2708 protected override TypeAttributes TypeAttr {
2710 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2712 ta |= TypeAttributes.Abstract | TypeAttributes.Sealed;
2718 public sealed class Struct : ClassOrStruct {
2720 // Modifiers allowed in a struct declaration
2722 const int AllowedModifiers =
2725 Modifiers.PROTECTED |
2726 Modifiers.INTERNAL |
2730 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2731 int mod, Attributes attrs)
2732 : base (ns, parent, name, attrs, Kind.Struct)
2736 if (parent.Parent == null)
2737 accmods = Modifiers.INTERNAL;
2739 accmods = Modifiers.PRIVATE;
2741 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2743 this.ModFlags |= Modifiers.SEALED;
2746 public override AttributeTargets AttributeTargets {
2748 return AttributeTargets.Struct;
2752 const TypeAttributes DefaultTypeAttributes =
2753 TypeAttributes.SequentialLayout |
2754 TypeAttributes.Sealed |
2755 TypeAttributes.BeforeFieldInit;
2758 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2760 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2762 // If we are compiling our runtime,
2763 // and we are defining ValueType, then our
2764 // base is `System.Object'.
2766 if (base_class == null) {
2767 if (!RootContext.StdLib && Name == "System.ValueType")
2768 base_class = TypeManager.system_object_expr;
2770 base_class = TypeManager.system_valuetype_expr;
2777 // FIXME: Allow the user to specify a different set of attributes
2778 // in some cases (Sealed for example is mandatory for a class,
2779 // but what SequentialLayout can be changed
2781 protected override TypeAttributes TypeAttr {
2783 return base.TypeAttr | DefaultTypeAttributes;
2787 public override void RegisterFieldForInitialization (FieldBase field)
2789 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2790 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2791 field.GetSignatureForError ());
2794 base.RegisterFieldForInitialization (field);
2802 public sealed class Interface : TypeContainer, IMemberContainer {
2805 /// Modifiers allowed in a class declaration
2807 public const int AllowedModifiers =
2810 Modifiers.PROTECTED |
2811 Modifiers.INTERNAL |
2815 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2817 : base (ns, parent, name, attrs, Kind.Interface)
2821 if (parent.Parent == null)
2822 accmods = Modifiers.INTERNAL;
2824 accmods = Modifiers.PRIVATE;
2826 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
2829 public override AttributeTargets AttributeTargets {
2831 return AttributeTargets.Interface;
2835 const TypeAttributes DefaultTypeAttributes =
2836 TypeAttributes.AutoLayout |
2837 TypeAttributes.Abstract |
2838 TypeAttributes.Interface;
2840 protected override TypeAttributes TypeAttr {
2842 return base.TypeAttr | DefaultTypeAttributes;
2846 protected override bool VerifyClsCompliance ()
2848 if (!base.VerifyClsCompliance ())
2851 if (ifaces != null) {
2852 foreach (Type t in ifaces) {
2853 if (AttributeTester.IsClsCompliant (t))
2856 Report.SymbolRelatedToPreviousError (t);
2857 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2858 GetSignatureForError (), TypeManager.CSharpName (t));
2866 public abstract class MethodCore : MemberBase {
2867 public readonly Parameters Parameters;
2868 protected ToplevelBlock block;
2870 // Whether this is an operator method.
2871 public Operator IsOperator;
2874 // The method we're overriding if this is an override method.
2876 protected MethodInfo base_method = null;
2878 static string[] attribute_targets = new string [] { "method", "return" };
2880 public MethodCore (DeclSpace parent, Expression type, int mod,
2881 int allowed_mod, bool is_interface, MemberName name,
2882 Attributes attrs, Parameters parameters)
2883 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
2886 Parameters = parameters;
2887 IsInterface = is_interface;
2891 // Returns the System.Type array for the parameters of this method
2893 public Type [] ParameterTypes {
2895 return Parameters.Types;
2899 public Parameters ParameterInfo
2906 public ToplevelBlock Block {
2916 public void SetYields ()
2918 ModFlags |= Modifiers.METHOD_YIELDS;
2921 protected override bool CheckBase ()
2923 if (!base.CheckBase ())
2926 // Check whether arguments were correct.
2927 if (!DoDefineParameters ())
2930 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
2936 // Is null for System.Object while compiling corlib and base interfaces
2937 if (ParentContainer.BaseCache == null) {
2938 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
2939 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
2944 Type base_ret_type = null;
2945 if (IsOperator == null)
2946 base_method = FindOutBaseMethod (ref base_ret_type);
2948 // method is override
2949 if (base_method != null) {
2951 if (!CheckMethodAgainstBase ())
2954 if ((ModFlags & Modifiers.NEW) == 0) {
2955 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
2956 Report.SymbolRelatedToPreviousError (base_method);
2957 if (this is PropertyBase) {
2958 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
2959 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
2962 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
2963 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
2968 if (base_method.IsAbstract && !IsInterface) {
2969 Report.SymbolRelatedToPreviousError (base_method);
2970 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
2971 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
2976 if (base_method.IsSpecialName && !(this is PropertyBase)) {
2977 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
2981 if (Name == "Equals" && Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type)
2982 ParentContainer.Mark_HasEquals ();
2983 else if (Name == "GetHashCode" && Parameters.Empty)
2984 ParentContainer.Mark_HasGetHashCode ();
2986 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2987 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
2989 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
2990 Report.SymbolRelatedToPreviousError (base_method);
2991 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2992 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
2999 MemberInfo conflict_symbol = ParentContainer.FindBaseMemberWithSameName (Name, !(this is Property));
3000 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3001 if (conflict_symbol != null) {
3002 Report.SymbolRelatedToPreviousError (conflict_symbol);
3003 if (this is PropertyBase)
3004 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3006 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3008 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3012 if (conflict_symbol == null) {
3013 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3014 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3019 if ((ModFlags & Modifiers.NEW) == 0) {
3020 if (this is Method && conflict_symbol is MethodBase)
3023 Report.SymbolRelatedToPreviousError (conflict_symbol);
3024 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3025 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3032 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3033 // that have been defined.
3035 // `name' is the user visible name for reporting errors (this is used to
3036 // provide the right name regarding method names and properties)
3038 bool CheckMethodAgainstBase ()
3042 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3043 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3044 Report.Error (506, Location,
3045 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3046 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3050 // Now we check that the overriden method is not final
3052 if (base_method.IsFinal) {
3053 Report.SymbolRelatedToPreviousError (base_method);
3054 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3055 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3059 // Check that the permissions are not being changed
3061 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3062 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3064 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3065 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3070 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3071 ModFlags |= Modifiers.NEW;
3072 Report.SymbolRelatedToPreviousError (base_method);
3073 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3074 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",
3075 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3077 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3078 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3085 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3087 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3089 // when overriding protected internal, the method can be declared
3090 // protected internal only within the same assembly
3093 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3094 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3096 // assemblies differ - report an error
3100 } else if (thisp != base_classp) {
3102 // same assembly, but other attributes differ - report an error
3107 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3109 // if it's not "protected internal", it must be "protected"
3113 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3115 // protected within the same assembly - an error
3118 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3119 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3121 // protected ok, but other attributes differ - report an error
3127 return (thisp == base_classp);
3131 public bool CheckAbstractAndExtern (bool has_block)
3133 if (ParentContainer.Kind == Kind.Interface)
3137 if ((ModFlags & Modifiers.EXTERN) != 0) {
3138 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3139 GetSignatureForError ());
3143 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3144 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3145 GetSignatureForError ());
3149 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3150 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3151 GetSignatureForError ());
3159 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3161 Report.SymbolRelatedToPreviousError (base_method);
3162 string base_name = TypeManager.GetFullNameSignature (base_method);
3163 string this_name = GetSignatureForError ();
3164 if (suffix != null) {
3165 base_name += suffix;
3166 this_name += suffix;
3169 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3170 this_name, Modifiers.GetDescription (ma), base_name);
3173 protected static string Error722 {
3175 return "`{0}': static types cannot be used as return types";
3180 /// For custom member duplication search in a container
3182 protected abstract bool CheckForDuplications ();
3185 /// Gets base method and its return type
3187 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3189 protected bool DoDefineParameters ()
3191 // Check if arguments were correct
3192 if (!Parameters.Resolve (this))
3195 return CheckParameters (ParameterTypes);
3198 bool CheckParameters (Type [] parameters)
3201 DeclSpace ds = Parent;
3203 foreach (Type partype in parameters){
3204 if (partype == TypeManager.void_type) {
3206 1547, Location, "Keyword 'void' cannot " +
3207 "be used in this context");
3211 if (partype.IsPointer){
3212 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3216 if (ds.AsAccessible (partype, ModFlags))
3219 if (this is Indexer)
3220 Report.Error (55, Location,
3221 "Inconsistent accessibility: parameter type `" +
3222 TypeManager.CSharpName (partype) + "' is less " +
3223 "accessible than indexer `" + GetSignatureForError () + "'");
3224 else if ((this is Method) && ((Method) this).IsOperator != null)
3225 Report.Error (57, Location,
3226 "Inconsistent accessibility: parameter type `" +
3227 TypeManager.CSharpName (partype) + "' is less " +
3228 "accessible than operator `" + GetSignatureForError () + "'");
3230 Report.Error (51, Location,
3231 "Inconsistent accessibility: parameter type `" +
3232 TypeManager.CSharpName (partype) + "' is less " +
3233 "accessible than method `" + GetSignatureForError () + "'");
3240 public override string[] ValidAttributeTargets {
3242 return attribute_targets;
3246 protected override bool VerifyClsCompliance ()
3248 if (!base.VerifyClsCompliance ()) {
3249 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3250 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3255 if (Parameters.HasArglist) {
3256 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3259 if (!AttributeTester.IsClsCompliant (MemberType)) {
3260 if (this is PropertyBase)
3261 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3262 GetSignatureForError ());
3264 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3265 GetSignatureForError ());
3268 Parameters.VerifyClsCompliance ();
3273 protected bool IsDuplicateImplementation (MethodCore method)
3275 if (method == this || !(method.MemberName.Equals (MemberName)))
3278 Type[] param_types = method.ParameterTypes;
3279 // This never happen. Rewrite this as Equal
3280 if (param_types == null && ParameterTypes == null)
3282 if (param_types == null || ParameterTypes == null)
3285 if (param_types.Length != ParameterTypes.Length)
3288 if (method.Parameters.HasArglist != Parameters.HasArglist)
3291 for (int i = 0; i < param_types.Length; i++)
3292 if (param_types [i] != ParameterTypes [i])
3295 // TODO: make operator compatible with MethodCore to avoid this
3296 if (this is Operator && method is Operator) {
3297 if (MemberType != method.MemberType)
3302 // Try to report 663: method only differs on out/ref
3304 Parameters info = ParameterInfo;
3305 Parameters other_info = method.ParameterInfo;
3306 for (int i = 0; i < info.Count; i++){
3307 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3308 Report.SymbolRelatedToPreviousError (method);
3309 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3310 GetSignatureForError ());
3315 Report.SymbolRelatedToPreviousError (method);
3316 if (this is Operator && method is Operator)
3317 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3319 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3323 public override bool IsUsed {
3324 get { return IsExplicitImpl || base.IsUsed; }
3328 // Returns a string that represents the signature for this
3329 // member which should be used in XML documentation.
3331 public override string GetDocCommentName (DeclSpace ds)
3333 return DocUtil.GetMethodDocCommentName (this, ds);
3337 // Raised (and passed an XmlElement that contains the comment)
3338 // when GenerateDocComment is writing documentation expectedly.
3340 // FIXME: with a few effort, it could be done with XmlReader,
3341 // that means removal of DOM use.
3343 internal override void OnGenerateDocComment (XmlElement el)
3345 DocUtil.OnMethodGenerateDocComment (this, el);
3349 // Represents header string for documentation comment.
3351 public override string DocCommentHeader {
3352 get { return "M:"; }
3357 public class SourceMethod : ISourceMethod
3362 protected SourceMethod (DeclSpace parent, MethodBase builder,
3363 ISourceFile file, Location start, Location end)
3365 this.parent = parent;
3366 this.builder = builder;
3368 CodeGen.SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
3371 public string Name {
3372 get { return builder.Name; }
3375 public int NamespaceID {
3376 get { return parent.NamespaceEntry.SymbolFileID; }
3381 if (builder is MethodBuilder)
3382 return ((MethodBuilder) builder).GetToken ().Token;
3383 else if (builder is ConstructorBuilder)
3384 return ((ConstructorBuilder) builder).GetToken ().Token;
3386 throw new NotSupportedException ();
3390 public void CloseMethod ()
3392 if (CodeGen.SymbolWriter != null)
3393 CodeGen.SymbolWriter.CloseMethod ();
3396 public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
3398 if (CodeGen.SymbolWriter == null)
3403 Location start_loc = block.StartLocation;
3404 if (start_loc.IsNull)
3407 Location end_loc = block.EndLocation;
3411 ISourceFile file = start_loc.SourceFile;
3415 return new SourceMethod (
3416 parent, builder, file, start_loc, end_loc);
3420 public class Method : MethodCore, IIteratorContainer, IMethodData {
3421 public MethodBuilder MethodBuilder;
3422 public MethodData MethodData;
3423 ReturnParameter return_attributes;
3424 ListDictionary declarative_security;
3427 /// Modifiers allowed in a class declaration
3429 const int AllowedModifiers =
3432 Modifiers.PROTECTED |
3433 Modifiers.INTERNAL |
3438 Modifiers.OVERRIDE |
3439 Modifiers.ABSTRACT |
3441 Modifiers.METHOD_YIELDS |
3444 const int AllowedInterfaceModifiers =
3445 Modifiers.NEW | Modifiers.UNSAFE;
3448 // return_type can be "null" for VOID values.
3450 public Method (DeclSpace parent, Expression return_type, int mod, bool is_iface,
3451 MemberName name, Parameters parameters, Attributes attrs)
3452 : base (parent, return_type, mod,
3453 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3454 is_iface, name, attrs, parameters)
3458 public override AttributeTargets AttributeTargets {
3460 return AttributeTargets.Method;
3464 public override string GetSignatureForError()
3466 if (IsOperator != null)
3467 return IsOperator.GetSignatureForError ();
3469 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3472 void DuplicateEntryPoint (MethodInfo b, Location location)
3476 "Program `" + CodeGen.FileName +
3477 "' has more than one entry point defined: `" +
3478 TypeManager.CSharpSignature(b) + "'");
3481 bool IsEntryPoint (MethodBuilder b, Parameters pinfo)
3483 if (b.ReturnType != TypeManager.void_type &&
3484 b.ReturnType != TypeManager.int32_type)
3487 if (pinfo.Count == 0)
3490 if (pinfo.Count > 1)
3493 Type t = pinfo.ParameterType(0);
3495 (t.GetArrayRank() == 1) &&
3496 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3497 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3503 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3505 if (a.Target == AttributeTargets.ReturnValue) {
3506 if (return_attributes == null)
3507 return_attributes = new ReturnParameter (MethodBuilder, Location);
3509 return_attributes.ApplyAttributeBuilder (a, cb);
3513 if (a.Type == TypeManager.methodimpl_attr_type &&
3514 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3515 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3518 if (a.Type == TypeManager.dllimport_type) {
3519 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3520 if ((ModFlags & extern_static) != extern_static) {
3521 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3527 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3528 if (declarative_security == null)
3529 declarative_security = new ListDictionary ();
3530 a.ExtractSecurityPermissionSet (declarative_security);
3534 if (a.Type == TypeManager.conditional_attribute_type) {
3535 if (IsOperator != null || IsExplicitImpl) {
3536 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3537 GetSignatureForError ());
3541 if (ReturnType != TypeManager.void_type) {
3542 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
3546 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3547 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
3552 Report.Error (582, Location, "Conditional not valid on interface members");
3556 if (MethodData.implementing != null) {
3557 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
3558 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
3562 for (int i = 0; i < ParameterInfo.Count; ++i) {
3563 if ((ParameterInfo.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
3564 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
3570 MethodBuilder.SetCustomAttribute (cb);
3573 protected override bool CheckForDuplications ()
3575 ArrayList ar = ParentContainer.Methods;
3577 int arLen = ar.Count;
3579 for (int i = 0; i < arLen; i++) {
3580 Method m = (Method) ar [i];
3581 if (IsDuplicateImplementation (m))
3586 ar = ParentContainer.Properties;
3588 for (int i = 0; i < ar.Count; ++i) {
3589 PropertyBase pb = (PropertyBase) ar [i];
3590 if (pb.AreAccessorsDuplicateImplementation (this))
3595 ar = ParentContainer.Indexers;
3597 for (int i = 0; i < ar.Count; ++i) {
3598 PropertyBase pb = (PropertyBase) ar [i];
3599 if (pb.AreAccessorsDuplicateImplementation (this))
3604 ar = ParentContainer.Events;
3606 for (int i = 0; i < ar.Count; ++i) {
3607 Event ev = (Event) ar [i];
3608 if (ev.AreAccessorsDuplicateImplementation (this))
3619 public override bool Define ()
3624 if (!CheckAbstractAndExtern (block != null))
3627 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3628 Error1599 (Location, ReturnType);
3635 if (IsOperator != null)
3636 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3638 MethodData = new MethodData (this, ModFlags, flags, this);
3640 if (!MethodData.Define (ParentContainer))
3643 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3644 Name == "Finalize" && !(this is Destructor)) {
3645 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3649 // Setup iterator if we are one
3651 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3652 Iterator iterator = new Iterator (this,
3656 if (!iterator.DefineIterator ())
3660 MethodBuilder = MethodData.MethodBuilder;
3663 // This is used to track the Entry Point,
3665 if (Name == "Main" &&
3666 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3667 (RootContext.MainClass == null ||
3668 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3669 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3670 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3671 md.SetMemberIsUsed ();
3673 if (RootContext.EntryPoint == null) {
3674 RootContext.EntryPoint = MethodBuilder;
3675 RootContext.EntryPointLocation = Location;
3677 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3678 DuplicateEntryPoint (MethodBuilder, Location);
3681 if (RootContext.WarningLevel >= 4)
3682 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3686 if (MemberType.IsAbstract && MemberType.IsSealed) {
3687 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3697 public override void Emit ()
3699 MethodData.Emit (Parent);
3702 if (declarative_security != null) {
3703 foreach (DictionaryEntry de in declarative_security) {
3704 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3712 public static void Error1599 (Location loc, Type t)
3714 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
3717 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
3719 MethodInfo mi = (MethodInfo) ParentContainer.BaseCache.FindMemberToOverride (
3720 Parent.TypeBuilder, Name, ParameterTypes, false);
3725 base_ret_type = mi.ReturnType;
3729 public override bool MarkForDuplicationCheck ()
3731 caching_flags |= Flags.TestMethodDuplication;
3735 protected override bool VerifyClsCompliance ()
3737 if (!base.VerifyClsCompliance ())
3740 if (ParameterInfo.Count > 0) {
3741 ArrayList al = (ArrayList)ParentContainer.MemberCache.Members [Name];
3743 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3749 #region IMethodData Members
3751 public CallingConventions CallingConventions {
3753 CallingConventions cc = Parameters.CallingConvention;
3754 if (Parameters.HasArglist)
3755 block.HasVarargs = true;
3758 if ((ModFlags & Modifiers.STATIC) == 0)
3759 cc |= CallingConventions.HasThis;
3761 // FIXME: How is `ExplicitThis' used in C#?
3767 public Type ReturnType {
3773 public MemberName MethodName {
3779 public new Location Location {
3781 return base.Location;
3785 protected override bool CheckBase() {
3786 if (!base.CheckBase ())
3789 // TODO: Destructor should derive from MethodCore
3790 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3791 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3792 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3799 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
3801 EmitContext ec = new EmitContext (this, ds, Parent, Location, ig, ReturnType, ModFlags, false);
3803 ec.CurrentIterator = ds as Iterator;
3804 if (ec.CurrentIterator != null)
3805 ec.CurrentAnonymousMethod = ec.CurrentIterator.Host;
3811 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3813 public bool IsExcluded ()
3815 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3816 return (caching_flags & Flags.Excluded) != 0;
3818 caching_flags &= ~Flags.Excluded_Undetected;
3820 if (base_method == null) {
3821 if (OptAttributes == null)
3824 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3829 foreach (Attribute a in attrs) {
3830 string condition = a.GetConditionalAttributeValue ();
3831 if (RootContext.AllDefines.Contains (condition))
3835 caching_flags |= Flags.Excluded;
3839 IMethodData md = TypeManager.GetMethod (base_method);
3841 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
3842 caching_flags |= Flags.Excluded;
3848 if (md.IsExcluded ()) {
3849 caching_flags |= Flags.Excluded;
3858 public abstract class ConstructorInitializer {
3859 ArrayList argument_list;
3860 protected ConstructorInfo base_constructor;
3863 public ConstructorInitializer (ArrayList argument_list, Location loc)
3865 this.argument_list = argument_list;
3869 public ArrayList Arguments {
3871 return argument_list;
3875 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
3877 Expression base_constructor_group;
3881 ec.CurrentBlock = block;
3883 if (argument_list != null){
3884 foreach (Argument a in argument_list){
3885 if (!a.Resolve (ec, loc))
3889 ec.CurrentBlock = null;
3891 if (this is ConstructorBaseInitializer) {
3892 if (ec.ContainerType.BaseType == null)
3895 t = ec.ContainerType.BaseType;
3896 if (ec.ContainerType.IsValueType) {
3897 Report.Error (522, loc,
3898 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
3902 t = ec.ContainerType;
3904 base_constructor_group = Expression.MemberLookup (
3905 ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
3906 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3909 if (base_constructor_group == null){
3911 base_constructor_group = Expression.MemberLookup (
3912 t, null, t, ".ctor", MemberTypes.Constructor,
3913 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3917 int errors = Report.Errors;
3918 if (base_constructor_group != null)
3919 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
3920 ec, (MethodGroupExpr) base_constructor_group, argument_list,
3923 if (base_constructor == null) {
3924 if (errors == Report.Errors)
3925 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
3926 argument_list == null ? 0 : argument_list.Count);
3931 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
3932 base_constructor = null;
3936 if (base_constructor == caller_builder){
3937 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
3944 public virtual void Emit (EmitContext ec)
3946 if (base_constructor != null){
3947 ec.Mark (loc, false);
3949 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
3951 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
3956 public class ConstructorBaseInitializer : ConstructorInitializer {
3957 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
3958 base (argument_list, l)
3963 class GeneratedBaseInitializer: ConstructorBaseInitializer {
3964 public GeneratedBaseInitializer (Location loc):
3970 public class ConstructorThisInitializer : ConstructorInitializer {
3971 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
3972 base (argument_list, l)
3977 public class Constructor : MethodCore, IMethodData {
3978 public ConstructorBuilder ConstructorBuilder;
3979 public ConstructorInitializer Initializer;
3980 ListDictionary declarative_security;
3983 // Modifiers allowed for a constructor.
3985 public const int AllowedModifiers =
3987 Modifiers.PROTECTED |
3988 Modifiers.INTERNAL |
3994 bool has_compliant_args = false;
3996 // The spec claims that static is not permitted, but
3997 // my very own code has static constructors.
3999 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4000 ConstructorInitializer init, Location loc)
4001 : base (parent, null, mod, AllowedModifiers, false, new MemberName (name, loc),
4007 public bool HasCompliantArgs {
4008 get { return has_compliant_args; }
4011 public override AttributeTargets AttributeTargets {
4012 get { return AttributeTargets.Constructor; }
4017 // Returns true if this is a default constructor
4019 public bool IsDefault ()
4021 if ((ModFlags & Modifiers.STATIC) != 0)
4022 return Parameters.Empty;
4024 return Parameters.Empty &&
4025 (Initializer is ConstructorBaseInitializer) &&
4026 (Initializer.Arguments == null);
4029 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4031 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4032 if (declarative_security == null) {
4033 declarative_security = new ListDictionary ();
4035 a.ExtractSecurityPermissionSet (declarative_security);
4039 ConstructorBuilder.SetCustomAttribute (cb);
4042 protected override bool CheckForDuplications ()
4044 ArrayList ar = ParentContainer.InstanceConstructors;
4046 int arLen = ar.Count;
4048 for (int i = 0; i < arLen; i++) {
4049 Constructor m = (Constructor) ar [i];
4050 if (IsDuplicateImplementation (m))
4057 protected override bool CheckBase ()
4059 // Check whether arguments were correct.
4060 if (!DoDefineParameters ())
4063 // TODO: skip the rest for generated ctor
4064 if ((ModFlags & Modifiers.STATIC) != 0)
4067 if (!CheckForDuplications ())
4070 if (ParentContainer.Kind == Kind.Struct) {
4071 if (ParameterTypes.Length == 0) {
4072 Report.Error (568, Location,
4073 "Structs cannot contain explicit parameterless constructors");
4077 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4078 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4083 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4084 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4091 // Creates the ConstructorBuilder
4093 public override bool Define ()
4095 if (ConstructorBuilder != null)
4098 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4099 MethodAttributes.SpecialName);
4101 if ((ModFlags & Modifiers.STATIC) != 0) {
4102 ca |= MethodAttributes.Static | MethodAttributes.Private;
4104 ca |= MethodAttributes.HideBySig;
4106 if ((ModFlags & Modifiers.PUBLIC) != 0)
4107 ca |= MethodAttributes.Public;
4108 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4109 if ((ModFlags & Modifiers.INTERNAL) != 0)
4110 ca |= MethodAttributes.FamORAssem;
4112 ca |= MethodAttributes.Family;
4113 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4114 ca |= MethodAttributes.Assembly;
4115 else if (IsDefault ())
4116 ca |= MethodAttributes.Public;
4118 ca |= MethodAttributes.Private;
4121 if (!CheckAbstractAndExtern (block != null))
4124 // Check if arguments were correct.
4128 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4129 ca, CallingConventions,
4132 if ((ModFlags & Modifiers.UNSAFE) != 0)
4133 ConstructorBuilder.InitLocals = false;
4135 if (ParentContainer.IsComImport) {
4136 if (!IsDefault ()) {
4137 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4138 Parent.GetSignatureForError ());
4141 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4144 TypeManager.AddMethod (ConstructorBuilder, this);
4152 public override void Emit ()
4154 EmitContext ec = CreateEmitContext (null, null);
4156 // If this is a non-static `struct' constructor and doesn't have any
4157 // initializer, it must initialize all of the struct's fields.
4158 if ((ParentContainer.Kind == Kind.Struct) &&
4159 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4160 Block.AddThisVariable (Parent, Location);
4162 if (block != null) {
4163 if (!block.ResolveMeta (ec, ParameterInfo))
4167 if ((ModFlags & Modifiers.STATIC) == 0){
4168 if (ParentContainer.Kind == Kind.Class && Initializer == null)
4169 Initializer = new GeneratedBaseInitializer (Location);
4173 // Spec mandates that Initializers will not have
4177 if ((Initializer != null) &&
4178 !Initializer.Resolve (ConstructorBuilder, block, ec))
4180 ec.IsStatic = false;
4183 Parameters.ApplyAttributes (ConstructorBuilder);
4185 SourceMethod source = SourceMethod.Create (
4186 Parent, ConstructorBuilder, block);
4189 // Classes can have base initializers and instance field initializers.
4191 if (ParentContainer.Kind == Kind.Class){
4192 if ((ModFlags & Modifiers.STATIC) == 0){
4195 // If we use a "this (...)" constructor initializer, then
4196 // do not emit field initializers, they are initialized in the other constructor
4198 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4199 ParentContainer.EmitFieldInitializers (ec);
4202 if (Initializer != null) {
4203 Initializer.Emit (ec);
4206 if ((ModFlags & Modifiers.STATIC) != 0)
4207 ParentContainer.EmitFieldInitializers (ec);
4209 if (OptAttributes != null)
4210 OptAttributes.Emit ();
4212 ec.EmitTopBlock (this, block);
4215 source.CloseMethod ();
4219 if (declarative_security != null) {
4220 foreach (DictionaryEntry de in declarative_security) {
4221 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4228 // Is never override
4229 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4234 public override string GetSignatureForError()
4236 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4239 protected override bool VerifyClsCompliance ()
4241 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4245 if (ParameterInfo.Count > 0) {
4246 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4248 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4250 if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4251 foreach (Type param in ParameterTypes) {
4252 if (param.IsArray) {
4258 has_compliant_args = true;
4262 #region IMethodData Members
4264 public System.Reflection.CallingConventions CallingConventions {
4266 CallingConventions cc = Parameters.CallingConvention;
4268 if (ParentContainer.Kind == Kind.Class)
4269 if ((ModFlags & Modifiers.STATIC) == 0)
4270 cc |= CallingConventions.HasThis;
4272 // FIXME: How is `ExplicitThis' used in C#?
4278 public new Location Location {
4280 return base.Location;
4284 public MemberName MethodName {
4290 public Type ReturnType {
4296 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4298 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4299 return new EmitContext (this, Parent, Location, ig_, null, ModFlags, true);
4302 public bool IsExcluded()
4311 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4313 public interface IMethodData
4315 CallingConventions CallingConventions { get; }
4316 Location Location { get; }
4317 MemberName MethodName { get; }
4318 Type ReturnType { get; }
4319 Parameters ParameterInfo { get; }
4321 Attributes OptAttributes { get; }
4322 ToplevelBlock Block { get; set; }
4324 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4325 ObsoleteAttribute GetObsoleteAttribute ();
4326 string GetSignatureForError ();
4328 bool IsClsComplianceRequired ();
4329 void SetMemberIsUsed ();
4333 // Encapsulates most of the Method's state
4335 public class MethodData {
4337 readonly IMethodData method;
4340 // Are we implementing an interface ?
4342 public MethodInfo implementing;
4347 protected MemberBase member;
4348 protected int modifiers;
4349 protected MethodAttributes flags;
4351 MethodBuilder builder = null;
4352 public MethodBuilder MethodBuilder {
4358 public MethodData (MemberBase member,
4359 int modifiers, MethodAttributes flags, IMethodData method)
4361 this.member = member;
4362 this.modifiers = modifiers;
4365 this.method = method;
4368 public bool Define (DeclSpace parent)
4370 string name = method.MethodName.Name;
4371 string method_name = name;
4373 TypeContainer container = ((TypeContainer) parent).PartialContainer;
4375 PendingImplementation pending = container.PendingImplementations;
4376 if (pending != null){
4377 if (member is Indexer) // TODO: test it, but it should work without this IF
4378 implementing = pending.IsInterfaceIndexer (
4379 member.InterfaceType, method.ReturnType, method.ParameterInfo);
4381 implementing = pending.IsInterfaceMethod (
4382 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
4384 if (member.InterfaceType != null){
4385 if (implementing == null){
4386 if (member is PropertyBase) {
4387 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4388 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4389 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4392 Report.Error (539, method.Location,
4393 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4394 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4398 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4399 Report.SymbolRelatedToPreviousError (implementing);
4400 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4401 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4404 method_name = member.InterfaceType.FullName + "." + name;
4406 if (implementing != null) {
4407 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4408 if (prop_method != null) {
4409 if (!implementing.IsSpecialName) {
4410 Report.SymbolRelatedToPreviousError (implementing);
4411 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4412 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4415 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4416 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4417 Report.SymbolRelatedToPreviousError (implementing);
4418 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4419 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4428 // For implicit implementations, make sure we are public, for
4429 // explicit implementations, make sure we are private.
4431 if (implementing != null){
4433 // Setting null inside this block will trigger a more
4434 // verbose error reporting for missing interface implementations
4436 // The "candidate" function has been flagged already
4437 // but it wont get cleared
4439 if (member.IsExplicitImpl){
4440 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4441 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4442 implementing = null;
4444 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4445 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4447 // If this is an interface method implementation,
4448 // check for public accessibility
4450 implementing = null;
4451 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4452 // We may never be private.
4453 implementing = null;
4454 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4456 // We may be protected if we're overriding something.
4458 implementing = null;
4463 // Static is not allowed
4465 if ((modifiers & Modifiers.STATIC) != 0){
4466 implementing = null;
4471 // If implementing is still valid, set flags
4473 if (implementing != null){
4475 // When implementing interface methods, set NewSlot
4476 // unless, we are overwriting a method.
4478 if (implementing.DeclaringType.IsInterface){
4479 if ((modifiers & Modifiers.OVERRIDE) == 0)
4480 flags |= MethodAttributes.NewSlot;
4483 MethodAttributes.Virtual |
4484 MethodAttributes.HideBySig;
4486 // Set Final unless we're virtual, abstract or already overriding a method.
4487 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4488 flags |= MethodAttributes.Final;
4491 DefineMethodBuilder (container, method_name, method.ParameterInfo.Types);
4493 if (builder == null)
4496 if ((modifiers & Modifiers.UNSAFE) != 0)
4497 builder.InitLocals = false;
4499 if (implementing != null){
4501 // clear the pending implemntation flag
4503 if (member is Indexer) {
4504 pending.ImplementIndexer (
4505 member.InterfaceType, builder, method.ReturnType,
4506 method.ParameterInfo, member.IsExplicitImpl);
4508 pending.ImplementMethod (
4509 member.InterfaceType, name, method.ReturnType,
4510 method.ParameterInfo, member.IsExplicitImpl);
4512 if (member.IsExplicitImpl)
4513 container.TypeBuilder.DefineMethodOverride (
4514 builder, implementing);
4518 TypeManager.AddMethod (builder, method);
4525 /// Create the MethodBuilder for the method
4527 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
4529 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4531 if ((modifiers & extern_static) == extern_static) {
4533 if (method.OptAttributes != null) {
4534 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type);
4535 if (dllimport_attribute != null) {
4536 flags |= MethodAttributes.PinvokeImpl;
4537 builder = dllimport_attribute.DefinePInvokeMethod (
4538 container.TypeBuilder, method_name, flags,
4539 method.ReturnType, ParameterTypes);
4545 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4546 // We are more strict than Microsoft and report CS0626 like error
4547 if (method.OptAttributes == null ||
4548 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type)) {
4549 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",
4550 method.GetSignatureForError ());
4555 builder = container.TypeBuilder.DefineMethod (
4556 method_name, flags, method.CallingConventions,
4557 method.ReturnType, ParameterTypes);
4563 public void Emit (DeclSpace parent)
4566 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4567 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
4569 ec = method.CreateEmitContext (parent, null);
4571 method.ParameterInfo.ApplyAttributes (MethodBuilder);
4573 Attributes OptAttributes = method.OptAttributes;
4575 if (OptAttributes != null)
4576 OptAttributes.Emit ();
4578 ToplevelBlock block = method.Block;
4580 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
4583 // Handle destructors specially
4585 // FIXME: This code generates buggy code
4587 if (member is Destructor)
4588 EmitDestructor (ec, block);
4590 ec.EmitTopBlock (method, block);
4593 source.CloseMethod ();
4596 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4598 ILGenerator ig = ec.ig;
4600 Label finish = ig.DefineLabel ();
4602 block.SetDestructor ();
4604 ig.BeginExceptionBlock ();
4605 ec.ReturnLabel = finish;
4606 ec.HasReturnLabel = true;
4607 ec.EmitTopBlock (method, block);
4609 // ig.MarkLabel (finish);
4610 ig.BeginFinallyBlock ();
4612 if (ec.ContainerType.BaseType != null) {
4613 Expression member_lookup = Expression.MemberLookup (
4614 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4615 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4617 if (member_lookup != null){
4618 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4620 ig.Emit (OpCodes.Ldarg_0);
4621 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4625 ig.EndExceptionBlock ();
4626 //ig.MarkLabel (ec.ReturnLabel);
4627 ig.Emit (OpCodes.Ret);
4631 // TODO: Should derive from MethodCore
4632 public class Destructor : Method {
4634 public Destructor (DeclSpace parent, Expression return_type, int mod,
4635 string name, Parameters parameters, Attributes attrs,
4637 : base (parent, return_type, mod, false, new MemberName (name, l),
4641 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4643 if (a.Type == TypeManager.conditional_attribute_type) {
4644 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4645 GetSignatureForError ());
4649 base.ApplyAttributeBuilder (a, cb);
4652 public override string GetSignatureForError ()
4654 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
4659 abstract public class MemberBase : MemberCore {
4660 public Expression Type;
4662 public MethodAttributes flags;
4664 protected readonly int explicit_mod_flags;
4667 // The "short" name of this property / indexer / event. This is the
4668 // name without the explicit interface.
4670 public string ShortName {
4671 get { return MemberName.Name; }
4672 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
4675 public TypeContainer ParentContainer {
4676 get { return ((TypeContainer) Parent).PartialContainer; }
4680 // The type of this property / indexer / event
4683 public Type MemberType {
4685 if (member_type == null && Type != null) {
4686 Type = Type.ResolveAsTypeTerminal (ResolveContext, false);
4688 member_type = Type.Type;
4696 // Whether this is an interface member.
4698 public bool IsInterface;
4701 // If true, this is an explicit interface implementation
4703 public bool IsExplicitImpl;
4706 // The interface type we are explicitly implementing
4708 public Type InterfaceType = null;
4711 // The constructor is only exposed to our children
4713 protected MemberBase (DeclSpace parent, Expression type, int mod,
4714 int allowed_mod, int def_mod, MemberName name,
4716 : base (parent, name, attrs)
4718 explicit_mod_flags = mod;
4720 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
4721 IsExplicitImpl = (MemberName.Left != null);
4724 protected virtual bool CheckBase ()
4726 if ((ModFlags & Modifiers.PROTECTED) != 0 && ParentContainer.Kind == Kind.Struct) {
4727 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4731 if ((RootContext.WarningLevel >= 4) &&
4732 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4733 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4734 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4735 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4740 protected virtual bool DoDefine ()
4743 throw new InternalErrorException ();
4746 ModFlags = Modifiers.PUBLIC |
4747 Modifiers.ABSTRACT |
4748 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
4750 flags = MethodAttributes.Public |
4751 MethodAttributes.Abstract |
4752 MethodAttributes.HideBySig |
4753 MethodAttributes.NewSlot |
4754 MethodAttributes.Virtual;
4756 if (!ParentContainer.MethodModifiersValid (this))
4759 flags = Modifiers.MethodAttr (ModFlags);
4762 if (MemberType == null)
4765 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
4766 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
4767 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
4768 GetSignatureForError (), Parent.GetSignatureForError ());
4772 // verify accessibility
4773 if (!Parent.AsAccessible (MemberType, ModFlags)) {
4774 Report.SymbolRelatedToPreviousError (MemberType);
4775 if (this is Property)
4776 Report.Error (53, Location,
4777 "Inconsistent accessibility: property type `" +
4778 TypeManager.CSharpName (MemberType) + "' is less " +
4779 "accessible than property `" + GetSignatureForError () + "'");
4780 else if (this is Indexer)
4781 Report.Error (54, Location,
4782 "Inconsistent accessibility: indexer return type `" +
4783 TypeManager.CSharpName (MemberType) + "' is less " +
4784 "accessible than indexer `" + GetSignatureForError () + "'");
4785 else if (this is MethodCore) {
4786 if (this is Operator)
4787 Report.Error (56, Location,
4788 "Inconsistent accessibility: return type `" +
4789 TypeManager.CSharpName (MemberType) + "' is less " +
4790 "accessible than operator `" + GetSignatureForError () + "'");
4792 Report.Error (50, Location,
4793 "Inconsistent accessibility: return type `" +
4794 TypeManager.CSharpName (MemberType) + "' is less " +
4795 "accessible than method `" + GetSignatureForError () + "'");
4797 Report.Error (52, Location,
4798 "Inconsistent accessibility: field type `" +
4799 TypeManager.CSharpName (MemberType) + "' is less " +
4800 "accessible than field `" + GetSignatureForError () + "'");
4805 if (IsExplicitImpl) {
4806 Expression expr = MemberName.Left.GetTypeExpression ();
4807 TypeExpr texpr = expr.ResolveAsTypeTerminal (ResolveContext, false);
4811 InterfaceType = texpr.Type;
4813 if (!InterfaceType.IsInterface) {
4814 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
4818 if (!ParentContainer.VerifyImplements (this))
4821 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
4827 protected bool IsTypePermitted ()
4829 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
4830 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
4836 protected override bool VerifyClsCompliance()
4838 if (base.VerifyClsCompliance ()) {
4842 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
4843 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
4851 // Fields and Events both generate FieldBuilders, we use this to share
4852 // their common bits. This is also used to flag usage of the field
4854 abstract public class FieldBase : MemberBase {
4855 public FieldBuilder FieldBuilder;
4856 public Status status;
4857 protected Expression initializer;
4860 public enum Status : byte {
4861 HAS_OFFSET = 4 // Used by FieldMember.
4864 static string[] attribute_targets = new string [] { "field" };
4867 /// Symbol with same name in base class/struct
4869 public MemberInfo conflict_symbol;
4871 protected FieldBase (DeclSpace parent, Expression type, int mod,
4872 int allowed_mod, MemberName name, Attributes attrs)
4873 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
4878 public override AttributeTargets AttributeTargets {
4880 return AttributeTargets.Field;
4884 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4886 if (a.Type == TypeManager.marshal_as_attr_type) {
4887 UnmanagedMarshal marshal = a.GetMarshal (this);
4888 if (marshal != null) {
4889 FieldBuilder.SetMarshal (marshal);
4894 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
4895 a.Error_InvalidSecurityParent ();
4899 FieldBuilder.SetCustomAttribute (cb);
4902 public void EmitInitializer (EmitContext ec)
4904 // Replace DeclSpace because of partial classes
4905 ec.DeclContainer = DeclContainer;
4907 ec.IsFieldInitializer = true;
4908 initializer = initializer.Resolve (ec);
4909 ec.IsFieldInitializer = false;
4910 if (initializer == null)
4913 FieldExpr fe = new FieldExpr (FieldBuilder, Location, true);
4914 if ((ModFlags & Modifiers.STATIC) == 0)
4915 fe.InstanceExpression = new This (Location).Resolve (ec);
4917 ExpressionStatement a = new Assign (fe, initializer, Location);
4919 a = a.ResolveStatement (ec);
4923 Constant c = initializer as Constant;
4924 if (c != null && CanElideInitializer (c))
4927 a.EmitStatement (ec);
4930 bool CanElideInitializer (Constant c)
4932 if (MemberType == c.Type)
4933 return c.IsDefaultValue;
4935 if (c.Type == TypeManager.null_type)
4941 protected override bool CheckBase ()
4943 if (!base.CheckBase ())
4950 conflict_symbol = ParentContainer.FindBaseMemberWithSameName (Name, false);
4951 if (conflict_symbol == null) {
4952 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
4953 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
4958 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
4959 Report.SymbolRelatedToPreviousError (conflict_symbol);
4960 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
4961 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
4967 public Expression Initializer {
4969 if (value != null) {
4970 this.initializer = value;
4971 ParentContainer.RegisterFieldForInitialization (this);
4976 protected virtual bool IsFieldClsCompliant {
4978 if (FieldBuilder == null)
4981 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
4985 public override string[] ValidAttributeTargets {
4987 return attribute_targets;
4991 protected override bool VerifyClsCompliance ()
4993 if (!base.VerifyClsCompliance ())
4996 if (!IsFieldClsCompliant) {
4997 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5003 public void SetAssigned ()
5005 caching_flags |= Flags.IsAssigned;
5009 public abstract class FieldMember : FieldBase
5011 protected FieldMember (DeclSpace parent, Expression type, int mod,
5012 int allowed_mod, MemberName name, Attributes attrs)
5013 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, attrs)
5015 if ((mod & Modifiers.ABSTRACT) != 0)
5016 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5019 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5021 if (a.Type == TypeManager.field_offset_attribute_type)
5023 status |= Status.HAS_OFFSET;
5025 if (!ParentContainer.HasExplicitLayout) {
5026 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5030 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5031 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5037 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5038 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5043 base.ApplyAttributeBuilder (a, cb);
5046 public override bool Define()
5048 if (MemberType == null || Type == null)
5051 if (MemberType == TypeManager.void_type) {
5052 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5059 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5060 Report.Error (52, Location,
5061 "Inconsistent accessibility: field type `" +
5062 TypeManager.CSharpName (MemberType) + "' is less " +
5063 "accessible than field `" + GetSignatureForError () + "'");
5067 if (!IsTypePermitted ())
5073 public override void Emit ()
5075 if (OptAttributes != null) {
5076 OptAttributes.Emit ();
5079 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && ParentContainer.HasExplicitLayout) {
5080 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5087 // Represents header string for documentation comment.
5089 public override string DocCommentHeader {
5090 get { return "F:"; }
5094 interface IFixedBuffer
5096 FieldInfo Element { get; }
5097 Type ElementType { get; }
5100 public class FixedFieldExternal: IFixedBuffer
5102 FieldInfo element_field;
5104 public FixedFieldExternal (FieldInfo fi)
5106 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5109 #region IFixedField Members
5111 public FieldInfo Element {
5113 return element_field;
5117 public Type ElementType {
5119 return element_field.FieldType;
5127 /// Fixed buffer implementation
5129 public class FixedField : FieldMember, IFixedBuffer
5131 public const string FixedElementName = "FixedElementField";
5132 static int GlobalCounter = 0;
5133 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5134 static FieldInfo[] fi;
5136 TypeBuilder fixed_buffer_type;
5137 FieldBuilder element;
5138 Expression size_expr;
5141 const int AllowedModifiers =
5144 Modifiers.PROTECTED |
5145 Modifiers.INTERNAL |
5148 public FixedField (DeclSpace parent, Expression type, int mod, string name,
5149 Expression size_expr, Attributes attrs, Location loc):
5150 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5152 if (RootContext.Version == LanguageVersion.ISO_1)
5153 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5155 this.size_expr = size_expr;
5158 public override bool Define()
5161 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5162 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5165 if (ParentContainer.Kind != Kind.Struct) {
5166 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5167 GetSignatureForError ());
5171 if (!base.Define ())
5174 if (!TypeManager.IsPrimitiveType (MemberType)) {
5175 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",
5176 GetSignatureForError ());
5180 EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
5181 Constant c = size_expr.ResolveAsConstant (ec, this);
5185 IntConstant buffer_size_const = c.ToInt (Location);
5186 if (buffer_size_const == null)
5189 buffer_size = buffer_size_const.Value;
5191 if (buffer_size <= 0) {
5192 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5196 int type_size = Expression.GetTypeSize (MemberType);
5198 if (buffer_size > int.MaxValue / type_size) {
5199 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5200 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5204 buffer_size *= type_size;
5207 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5209 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5210 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5211 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5212 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5214 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5215 TypeManager.RegisterFieldBase (FieldBuilder, this);
5220 public override void Emit()
5223 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5225 object[] fi_val = new object[1];
5226 fi_val [0] = buffer_size;
5228 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5229 ctor_args, fi, fi_val);
5230 fixed_buffer_type.SetCustomAttribute (cab);
5233 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5234 FieldBuilder.SetCustomAttribute (cab);
5239 protected override bool IsFieldClsCompliant {
5245 #region IFixedField Members
5247 public FieldInfo Element {
5253 public Type ElementType {
5263 // The Field class is used to represents class/struct fields during parsing.
5265 public class Field : FieldMember {
5267 // Modifiers allowed in a class declaration
5269 const int AllowedModifiers =
5272 Modifiers.PROTECTED |
5273 Modifiers.INTERNAL |
5276 Modifiers.VOLATILE |
5280 public Field (DeclSpace parent, Expression type, int mod, string name,
5281 Attributes attrs, Location loc)
5282 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5287 public override bool Define ()
5289 if (!base.Define ())
5292 if (RootContext.WarningLevel > 1){
5293 Type ptype = Parent.TypeBuilder.BaseType;
5295 // ptype is only null for System.Object while compiling corlib.
5297 TypeContainer.FindMembers (
5298 ptype, MemberTypes.Method,
5299 BindingFlags.Public |
5300 BindingFlags.Static | BindingFlags.Instance,
5301 System.Type.FilterName, Name);
5305 if ((ModFlags & Modifiers.VOLATILE) != 0){
5306 if (!MemberType.IsClass){
5307 Type vt = MemberType;
5309 if (TypeManager.IsEnumType (vt))
5310 vt = TypeManager.EnumToUnderlying (MemberType);
5312 if (!((vt == TypeManager.bool_type) ||
5313 (vt == TypeManager.sbyte_type) ||
5314 (vt == TypeManager.byte_type) ||
5315 (vt == TypeManager.short_type) ||
5316 (vt == TypeManager.ushort_type) ||
5317 (vt == TypeManager.int32_type) ||
5318 (vt == TypeManager.uint32_type) ||
5319 (vt == TypeManager.char_type) ||
5320 (vt == TypeManager.float_type) ||
5321 (!vt.IsValueType))){
5322 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5323 GetSignatureForError (), TypeManager.CSharpName (vt));
5328 if ((ModFlags & Modifiers.READONLY) != 0){
5329 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5330 GetSignatureForError ());
5335 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5337 if (ParentContainer.Kind == Kind.Struct &&
5338 ((fa & FieldAttributes.Static) == 0) &&
5339 MemberType == Parent.TypeBuilder &&
5340 !TypeManager.IsBuiltinType (MemberType)){
5341 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5342 "' causes a cycle in the structure layout");
5347 FieldBuilder = Parent.TypeBuilder.DefineField (
5348 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5350 TypeManager.RegisterFieldBase (FieldBuilder, this);
5352 catch (ArgumentException) {
5353 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5360 protected override bool VerifyClsCompliance ()
5362 if (!base.VerifyClsCompliance ())
5365 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5366 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5374 // `set' and `get' accessors are represented with an Accessor.
5376 public class Accessor : IIteratorContainer {
5378 // Null if the accessor is empty, or a Block if not
5380 public const int AllowedModifiers =
5382 Modifiers.PROTECTED |
5383 Modifiers.INTERNAL |
5386 public ToplevelBlock Block;
5387 public Attributes Attributes;
5388 public Location Location;
5389 public int ModFlags;
5392 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5397 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5400 public void SetYields ()
5406 // Ooouh Martin, templates are missing here.
5407 // When it will be possible move here a lot of child code and template method type.
5408 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5409 protected MethodData method_data;
5410 protected ToplevelBlock block;
5411 protected ListDictionary declarative_security;
5413 // The accessor are created event if they are not wanted.
5414 // But we need them because their names are reserved.
5415 // Field says whether accessor will be emited or not
5416 public readonly bool IsDummy;
5418 protected readonly string prefix;
5420 ReturnParameter return_attributes;
5422 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5423 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5425 this.prefix = prefix;
5429 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5431 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5432 accessor.Attributes)
5434 this.prefix = prefix;
5435 this.block = accessor.Block;
5438 static MemberName SetupName (string prefix, MemberBase member, Location loc)
5440 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5443 public void UpdateName (MemberBase member)
5445 SetMemberName (SetupName (prefix, member, Location));
5448 #region IMethodData Members
5450 public ToplevelBlock Block {
5460 public CallingConventions CallingConventions {
5462 return CallingConventions.Standard;
5466 public bool IsExcluded ()
5471 public MemberName MethodName {
5477 public Type[] ParameterTypes {
5479 return ParameterInfo.Types;
5483 public abstract Parameters ParameterInfo { get ; }
5484 public abstract Type ReturnType { get; }
5485 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5489 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5491 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5492 a.Type == TypeManager.conditional_attribute_type) {
5493 Report.Error (1667, a.Location,
5494 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5495 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5499 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5500 if (declarative_security == null)
5501 declarative_security = new ListDictionary ();
5502 a.ExtractSecurityPermissionSet (declarative_security);
5506 if (a.Target == AttributeTargets.Method) {
5507 method_data.MethodBuilder.SetCustomAttribute (cb);
5511 if (a.Target == AttributeTargets.ReturnValue) {
5512 if (return_attributes == null)
5513 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5515 return_attributes.ApplyAttributeBuilder (a, cb);
5519 ApplyToExtraTarget (a, cb);
5522 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5524 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5527 public override bool Define()
5529 throw new NotSupportedException ();
5532 public virtual void Emit (DeclSpace parent)
5534 EmitMethod (parent);
5536 if (declarative_security != null) {
5537 foreach (DictionaryEntry de in declarative_security) {
5538 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5545 protected virtual void EmitMethod (DeclSpace parent)
5547 method_data.Emit (parent);
5550 public override bool IsClsComplianceRequired()
5555 public bool IsDuplicateImplementation (MethodCore method)
5557 if (!MemberName.Equals (method.MemberName))
5560 Type[] param_types = method.ParameterTypes;
5562 if (param_types.Length != ParameterTypes.Length)
5565 for (int i = 0; i < param_types.Length; i++)
5566 if (param_types [i] != ParameterTypes [i])
5569 Report.SymbolRelatedToPreviousError (method);
5570 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
5574 public override bool IsUsed
5584 public new Location Location {
5586 return base.Location;
5591 // Represents header string for documentation comment.
5593 public override string DocCommentHeader {
5594 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5600 // Properties and Indexers both generate PropertyBuilders, we use this to share
5601 // their common bits.
5603 abstract public class PropertyBase : MethodCore {
5605 public class GetMethod : PropertyMethod
5607 static string[] attribute_targets = new string [] { "method", "return" };
5609 public GetMethod (MethodCore method):
5610 base (method, "get_")
5614 public GetMethod (MethodCore method, Accessor accessor):
5615 base (method, accessor, "get_")
5619 public override MethodBuilder Define (DeclSpace parent)
5621 base.Define (parent);
5623 method_data = new MethodData (method, ModFlags, flags, this);
5625 if (!method_data.Define (parent))
5628 return method_data.MethodBuilder;
5631 public override Type ReturnType {
5633 return method.MemberType;
5637 public override Parameters ParameterInfo {
5639 return Parameters.EmptyReadOnlyParameters;
5643 public override string[] ValidAttributeTargets {
5645 return attribute_targets;
5650 public class SetMethod : PropertyMethod {
5652 static string[] attribute_targets = new string [] { "method", "param", "return" };
5653 ImplicitParameter param_attr;
5654 protected Parameters parameters;
5656 public SetMethod (MethodCore method):
5657 base (method, "set_")
5661 public SetMethod (MethodCore method, Accessor accessor):
5662 base (method, accessor, "set_")
5666 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5668 if (a.Target == AttributeTargets.Parameter) {
5669 if (param_attr == null)
5670 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5672 param_attr.ApplyAttributeBuilder (a, cb);
5676 base.ApplyAttributeBuilder (a, cb);
5679 public override Parameters ParameterInfo {
5685 protected virtual void DefineParameters ()
5687 parameters = new Parameters (
5688 new Parameter[] { new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location) },
5689 new Type[] { method.MemberType });
5692 public override MethodBuilder Define (DeclSpace parent)
5694 DefineParameters ();
5698 base.Define (parent);
5700 method_data = new MethodData (method, ModFlags, flags, this);
5702 if (!method_data.Define (parent))
5705 return method_data.MethodBuilder;
5708 public override Type ReturnType {
5710 return TypeManager.void_type;
5714 public override string[] ValidAttributeTargets {
5716 return attribute_targets;
5721 static string[] attribute_targets = new string [] { "property" };
5723 public abstract class PropertyMethod : AbstractPropertyEventMethod
5725 protected readonly MethodCore method;
5726 protected MethodAttributes flags;
5729 public PropertyMethod (MethodCore method, string prefix)
5730 : base (method, prefix)
5732 this.method = method;
5735 public PropertyMethod (MethodCore method, Accessor accessor,
5737 : base (method, accessor, prefix)
5739 this.method = method;
5740 this.ModFlags = accessor.ModFlags;
5741 yields = accessor.Yields;
5743 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
5744 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
5748 public override AttributeTargets AttributeTargets {
5750 return AttributeTargets.Method;
5754 public override bool IsClsComplianceRequired()
5756 return method.IsClsComplianceRequired ();
5759 public virtual MethodBuilder Define (DeclSpace parent)
5761 if (!method.CheckAbstractAndExtern (block != null))
5764 TypeContainer container = ((TypeContainer) parent).PartialContainer;
5767 // Check for custom access modifier
5769 if (ModFlags == 0) {
5770 ModFlags = method.ModFlags;
5771 flags = method.flags;
5773 if (container.Kind == Kind.Interface)
5774 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
5775 GetSignatureForError ());
5777 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
5778 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
5781 CheckModifiers (ModFlags);
5782 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
5783 ModFlags |= Modifiers.PROPERTY_CUSTOM;
5784 flags = Modifiers.MethodAttr (ModFlags);
5785 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
5789 // Setup iterator if we are one
5792 Iterator iterator = new Iterator (this, Parent as TypeContainer, ModFlags);
5794 if (!iterator.DefineIterator ())
5801 public bool HasCustomAccessModifier
5804 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
5808 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
5810 return new EmitContext (method,
5811 ds, method.Parent, method.Location, ig, ReturnType,
5812 method.ModFlags, false);
5815 public override ObsoleteAttribute GetObsoleteAttribute ()
5817 return method.GetObsoleteAttribute ();
5820 public override string GetSignatureForError()
5822 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
5825 void CheckModifiers (int modflags)
5828 int mflags = method.ModFlags & Modifiers.Accessibility;
5830 if ((mflags & Modifiers.PUBLIC) != 0) {
5831 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
5833 else if ((mflags & Modifiers.PROTECTED) != 0) {
5834 if ((mflags & Modifiers.INTERNAL) != 0)
5835 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
5837 flags |= Modifiers.PRIVATE;
5839 else if ((mflags & Modifiers.INTERNAL) != 0)
5840 flags |= Modifiers.PRIVATE;
5842 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
5843 Report.Error (273, Location,
5844 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
5845 GetSignatureForError (), method.GetSignatureForError ());
5849 public override bool MarkForDuplicationCheck ()
5851 caching_flags |= Flags.TestMethodDuplication;
5857 public PropertyMethod Get, Set;
5858 public PropertyBuilder PropertyBuilder;
5859 public MethodBuilder GetBuilder, SetBuilder;
5861 protected EmitContext ec;
5863 public PropertyBase (DeclSpace parent, Expression type, int mod_flags,
5864 int allowed_mod, bool is_iface, MemberName name,
5865 Parameters parameters, Attributes attrs)
5866 : base (parent, type, mod_flags, allowed_mod, is_iface, name,
5871 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5873 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5874 a.Error_InvalidSecurityParent ();
5878 PropertyBuilder.SetCustomAttribute (cb);
5881 public override AttributeTargets AttributeTargets {
5883 return AttributeTargets.Property;
5887 public override bool Define ()
5892 if (!IsTypePermitted ())
5898 protected override bool DoDefine ()
5900 if (!base.DoDefine ())
5904 // Accessors modifiers check
5906 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
5907 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
5908 GetSignatureForError ());
5912 if ((Get.IsDummy || Set.IsDummy)
5913 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
5914 Report.Error (276, Location,
5915 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
5916 GetSignatureForError ());
5920 if (MemberType.IsAbstract && MemberType.IsSealed) {
5921 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
5928 protected override bool CheckForDuplications ()
5930 ArrayList ar = ParentContainer.Indexers;
5932 int arLen = ar.Count;
5934 for (int i = 0; i < arLen; i++) {
5935 Indexer m = (Indexer) ar [i];
5936 if (IsDuplicateImplementation (m))
5941 ar = ParentContainer.Properties;
5943 int arLen = ar.Count;
5945 for (int i = 0; i < arLen; i++) {
5946 Property m = (Property) ar [i];
5947 if (IsDuplicateImplementation (m))
5955 // TODO: rename to Resolve......
5956 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
5958 PropertyInfo base_property = ParentContainer.BaseCache.FindMemberToOverride (
5959 Parent.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
5961 if (base_property == null)
5964 base_ret_type = base_property.PropertyType;
5965 MethodInfo get_accessor = base_property.GetGetMethod (true);
5966 MethodInfo set_accessor = base_property.GetSetMethod (true);
5967 MethodAttributes get_accessor_access, set_accessor_access;
5969 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
5970 if (Get != null && !Get.IsDummy && get_accessor == null) {
5971 Report.SymbolRelatedToPreviousError (base_property);
5972 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
5975 if (Set != null && !Set.IsDummy && set_accessor == null) {
5976 Report.SymbolRelatedToPreviousError (base_property);
5977 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
5982 // Check base class accessors access
5985 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
5986 get_accessor_access = set_accessor_access = 0;
5987 if ((ModFlags & Modifiers.NEW) == 0) {
5988 if (get_accessor != null) {
5989 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
5990 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
5992 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
5993 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
5996 if (set_accessor != null) {
5997 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
5998 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6000 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6001 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6006 // Get the less restrictive access
6008 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6011 public override void Emit ()
6014 // The PropertyBuilder can be null for explicit implementations, in that
6015 // case, we do not actually emit the ".property", so there is nowhere to
6016 // put the attribute
6018 if (PropertyBuilder != null && OptAttributes != null)
6019 OptAttributes.Emit ();
6031 /// Tests whether accessors are not in collision with some method (CS0111)
6033 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6035 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6038 public override bool IsUsed
6044 return Get.IsUsed | Set.IsUsed;
6048 protected override void SetMemberName (MemberName new_name)
6050 base.SetMemberName (new_name);
6052 Get.UpdateName (this);
6053 Set.UpdateName (this);
6056 public override string[] ValidAttributeTargets {
6058 return attribute_targets;
6063 // Represents header string for documentation comment.
6065 public override string DocCommentHeader {
6066 get { return "P:"; }
6070 public class Property : PropertyBase {
6071 const int AllowedModifiers =
6074 Modifiers.PROTECTED |
6075 Modifiers.INTERNAL |
6079 Modifiers.OVERRIDE |
6080 Modifiers.ABSTRACT |
6083 Modifiers.METHOD_YIELDS |
6086 const int AllowedInterfaceModifiers =
6089 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6090 MemberName name, Attributes attrs, Accessor get_block,
6092 : base (parent, type, mod,
6093 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6094 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6096 if (get_block == null)
6097 Get = new GetMethod (this);
6099 Get = new GetMethod (this, get_block);
6101 if (set_block == null)
6102 Set = new SetMethod (this);
6104 Set = new SetMethod (this, set_block);
6107 public override bool Define ()
6109 if (!base.Define ())
6115 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6118 GetBuilder = Get.Define (Parent);
6119 if (GetBuilder == null)
6123 SetBuilder = Set.Define (Parent);
6125 if (SetBuilder == null)
6129 // FIXME - PropertyAttributes.HasDefault ?
6131 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6132 Name, PropertyAttributes.None, MemberType, null);
6135 PropertyBuilder.SetGetMethod (GetBuilder);
6138 PropertyBuilder.SetSetMethod (SetBuilder);
6140 TypeManager.RegisterProperty (PropertyBuilder, this);
6146 /// Gigantic workaround for lameness in SRE follows :
6147 /// This class derives from EventInfo and attempts to basically
6148 /// wrap around the EventBuilder so that FindMembers can quickly
6149 /// return this in it search for members
6151 public class MyEventBuilder : EventInfo {
6154 // We use this to "point" to our Builder which is
6155 // not really a MemberInfo
6157 EventBuilder MyBuilder;
6160 // We "catch" and wrap these methods
6162 MethodInfo raise, remove, add;
6164 EventAttributes attributes;
6165 Type declaring_type, reflected_type, event_type;
6170 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6172 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6174 // And now store the values in our own fields.
6176 declaring_type = type_builder;
6178 reflected_type = type_builder;
6180 attributes = event_attr;
6183 this.event_type = event_type;
6187 // Methods that you have to override. Note that you only need
6188 // to "implement" the variants that take the argument (those are
6189 // the "abstract" methods, the others (GetAddMethod()) are
6192 public override MethodInfo GetAddMethod (bool nonPublic)
6197 public override MethodInfo GetRemoveMethod (bool nonPublic)
6202 public override MethodInfo GetRaiseMethod (bool nonPublic)
6208 // These methods make "MyEventInfo" look like a Builder
6210 public void SetRaiseMethod (MethodBuilder raiseMethod)
6212 raise = raiseMethod;
6213 MyBuilder.SetRaiseMethod (raiseMethod);
6216 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6218 remove = removeMethod;
6219 MyBuilder.SetRemoveOnMethod (removeMethod);
6222 public void SetAddOnMethod (MethodBuilder addMethod)
6225 MyBuilder.SetAddOnMethod (addMethod);
6228 public void SetCustomAttribute (CustomAttributeBuilder cb)
6230 MyBuilder.SetCustomAttribute (cb);
6233 public override object [] GetCustomAttributes (bool inherit)
6235 // FIXME : There's nothing which can be seemingly done here because
6236 // we have no way of getting at the custom attribute objects of the
6241 public override object [] GetCustomAttributes (Type t, bool inherit)
6243 // FIXME : Same here !
6247 public override bool IsDefined (Type t, bool b)
6252 public override EventAttributes Attributes {
6258 public override string Name {
6264 public override Type DeclaringType {
6266 return declaring_type;
6270 public override Type ReflectedType {
6272 return reflected_type;
6276 public Type EventType {
6282 public void SetUsed ()
6284 if (my_event != null) {
6285 my_event.SetAssigned ();
6286 my_event.SetMemberIsUsed ();
6292 /// For case when event is declared like property (with add and remove accessors).
6294 public class EventProperty: Event {
6296 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6298 public EventProperty (DeclSpace parent, Expression type, int mod_flags,
6299 bool is_iface, MemberName name,
6300 Attributes attrs, Accessor add, Accessor remove)
6301 : base (parent, type, mod_flags, is_iface, name, attrs)
6303 Add = new AddDelegateMethod (this, add);
6304 Remove = new RemoveDelegateMethod (this, remove);
6306 // For this event syntax we don't report error CS0067
6307 // because it is hard to do it.
6311 public override string[] ValidAttributeTargets {
6313 return attribute_targets;
6319 /// Event is declared like field.
6321 public class EventField : Event {
6323 static string[] attribute_targets = new string [] { "event", "field", "method" };
6324 static string[] attribute_targets_interface = new string[] { "event", "method" };
6326 public EventField (DeclSpace parent, Expression type, int mod_flags,
6327 bool is_iface, MemberName name,
6329 : base (parent, type, mod_flags, is_iface, name, attrs)
6331 Add = new AddDelegateMethod (this);
6332 Remove = new RemoveDelegateMethod (this);
6335 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6337 if (a.Target == AttributeTargets.Field) {
6338 FieldBuilder.SetCustomAttribute (cb);
6342 if (a.Target == AttributeTargets.Method) {
6343 Add.ApplyAttributeBuilder (a, cb);
6344 Remove.ApplyAttributeBuilder (a, cb);
6348 base.ApplyAttributeBuilder (a, cb);
6351 public override bool Define()
6353 if (!base.Define ())
6356 if (initializer != null) {
6357 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
6358 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
6359 GetSignatureForError ());
6367 public override string[] ValidAttributeTargets {
6369 return IsInterface ? attribute_targets_interface : attribute_targets;
6374 public abstract class Event : FieldBase {
6376 protected sealed class AddDelegateMethod: DelegateMethod
6379 public AddDelegateMethod (Event method):
6380 base (method, "add_")
6384 public AddDelegateMethod (Event method, Accessor accessor):
6385 base (method, accessor, "add_")
6389 protected override MethodInfo DelegateMethodInfo {
6391 return TypeManager.delegate_combine_delegate_delegate;
6397 protected sealed class RemoveDelegateMethod: DelegateMethod
6399 public RemoveDelegateMethod (Event method):
6400 base (method, "remove_")
6404 public RemoveDelegateMethod (Event method, Accessor accessor):
6405 base (method, accessor, "remove_")
6409 protected override MethodInfo DelegateMethodInfo {
6411 return TypeManager.delegate_remove_delegate_delegate;
6417 public abstract class DelegateMethod : AbstractPropertyEventMethod
6419 protected readonly Event method;
6420 ImplicitParameter param_attr;
6422 static string[] attribute_targets = new string [] { "method", "param", "return" };
6424 public DelegateMethod (Event method, string prefix)
6425 : base (method, prefix)
6427 this.method = method;
6430 public DelegateMethod (Event method, Accessor accessor, string prefix)
6431 : base (method, accessor, prefix)
6433 this.method = method;
6436 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6438 if (a.Target == AttributeTargets.Parameter) {
6439 if (param_attr == null)
6440 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6442 param_attr.ApplyAttributeBuilder (a, cb);
6446 base.ApplyAttributeBuilder (a, cb);
6449 public override AttributeTargets AttributeTargets {
6451 return AttributeTargets.Method;
6455 public override bool IsClsComplianceRequired ()
6457 return method.IsClsComplianceRequired ();
6460 public MethodBuilder Define (DeclSpace parent)
6462 method_data = new MethodData (method, method.ModFlags,
6463 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6465 if (!method_data.Define (parent))
6468 MethodBuilder mb = method_data.MethodBuilder;
6469 ParameterInfo.ApplyAttributes (mb);
6474 protected override void EmitMethod (DeclSpace parent)
6476 if (block != null) {
6477 base.EmitMethod (parent);
6481 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6484 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6485 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6487 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6488 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6489 ig.Emit (OpCodes.Ldsfld, field_info);
6490 ig.Emit (OpCodes.Ldarg_0);
6491 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6492 ig.Emit (OpCodes.Castclass, method.MemberType);
6493 ig.Emit (OpCodes.Stsfld, field_info);
6495 ig.Emit (OpCodes.Ldarg_0);
6496 ig.Emit (OpCodes.Ldarg_0);
6497 ig.Emit (OpCodes.Ldfld, field_info);
6498 ig.Emit (OpCodes.Ldarg_1);
6499 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6500 ig.Emit (OpCodes.Castclass, method.MemberType);
6501 ig.Emit (OpCodes.Stfld, field_info);
6503 ig.Emit (OpCodes.Ret);
6506 protected abstract MethodInfo DelegateMethodInfo { get; }
6508 public override Type ReturnType {
6510 return TypeManager.void_type;
6514 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6516 return new EmitContext (method,
6517 ds, method.Parent, Location, ig, ReturnType,
6518 method.ModFlags, false);
6521 public override ObsoleteAttribute GetObsoleteAttribute ()
6523 return method.GetObsoleteAttribute ();
6526 public override string[] ValidAttributeTargets {
6528 return attribute_targets;
6532 public override Parameters ParameterInfo {
6534 return method.parameters;
6541 const int AllowedModifiers =
6544 Modifiers.PROTECTED |
6545 Modifiers.INTERNAL |
6550 Modifiers.OVERRIDE |
6554 const int AllowedInterfaceModifiers =
6557 public DelegateMethod Add, Remove;
6558 public MyEventBuilder EventBuilder;
6559 public MethodBuilder AddBuilder, RemoveBuilder;
6560 Parameters parameters;
6562 protected Event (DeclSpace parent, Expression type, int mod_flags,
6563 bool is_iface, MemberName name, Attributes attrs)
6564 : base (parent, type, mod_flags,
6565 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6568 IsInterface = is_iface;
6571 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6573 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6574 a.Error_InvalidSecurityParent ();
6578 EventBuilder.SetCustomAttribute (cb);
6581 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6583 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6586 public override AttributeTargets AttributeTargets {
6588 return AttributeTargets.Event;
6592 public override bool Define ()
6594 EventAttributes e_attr;
6595 e_attr = EventAttributes.None;
6600 if (!TypeManager.IsDelegateType (MemberType)) {
6601 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
6605 parameters = new Parameters (
6606 new Parameter[] { new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location) },
6607 new Type[] { MemberType } );
6613 // Now define the accessors
6616 AddBuilder = Add.Define (Parent);
6617 if (AddBuilder == null)
6620 RemoveBuilder = Remove.Define (Parent);
6621 if (RemoveBuilder == null)
6624 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6626 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6627 FieldBuilder = Parent.TypeBuilder.DefineField (
6629 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6630 TypeManager.RegisterPrivateFieldOfEvent (
6631 (EventInfo) EventBuilder, FieldBuilder);
6632 TypeManager.RegisterFieldBase (FieldBuilder, this);
6635 EventBuilder.SetAddOnMethod (AddBuilder);
6636 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6638 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6642 protected override bool CheckBase ()
6644 if (!base.CheckBase ())
6647 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6648 if (!(conflict_symbol is EventInfo)) {
6649 Report.SymbolRelatedToPreviousError (conflict_symbol);
6650 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
6658 public override void Emit ()
6660 if (OptAttributes != null) {
6661 OptAttributes.Emit ();
6665 Remove.Emit (Parent);
6670 public override string GetSignatureForError ()
6672 return base.GetSignatureForError ();
6676 // Represents header string for documentation comment.
6678 public override string DocCommentHeader {
6679 get { return "E:"; }
6684 public class Indexer : PropertyBase {
6686 class GetIndexerMethod : GetMethod
6688 public GetIndexerMethod (MethodCore method):
6693 public GetIndexerMethod (MethodCore method, Accessor accessor):
6694 base (method, accessor)
6698 public override Parameters ParameterInfo {
6700 return method.ParameterInfo;
6705 class SetIndexerMethod: SetMethod
6707 public SetIndexerMethod (MethodCore method):
6712 public SetIndexerMethod (MethodCore method, Accessor accessor):
6713 base (method, accessor)
6717 protected override void DefineParameters ()
6719 parameters = Parameters.MergeGenerated (method.Parameters,
6720 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
6724 const int AllowedModifiers =
6727 Modifiers.PROTECTED |
6728 Modifiers.INTERNAL |
6732 Modifiers.OVERRIDE |
6737 const int AllowedInterfaceModifiers =
6741 public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
6742 bool is_iface, Parameters parameters, Attributes attrs,
6743 Accessor get_block, Accessor set_block)
6744 : base (parent, type, mod,
6745 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6746 is_iface, name, parameters, attrs)
6748 if (get_block == null)
6749 Get = new GetIndexerMethod (this);
6751 Get = new GetIndexerMethod (this, get_block);
6753 if (set_block == null)
6754 Set = new SetIndexerMethod (this);
6756 Set = new SetIndexerMethod (this, set_block);
6759 public override bool Define ()
6761 if (!base.Define ())
6764 if (MemberType == TypeManager.void_type) {
6765 Report.Error (620, Location, "Indexers cannot have void type");
6769 if (OptAttributes != null) {
6770 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
6771 if (indexer_attr != null) {
6772 // Remove the attribute from the list because it is not emitted
6773 OptAttributes.Attrs.Remove (indexer_attr);
6775 ShortName = indexer_attr.GetIndexerAttributeValue ();
6777 if (IsExplicitImpl) {
6778 Report.Error (415, indexer_attr.Location,
6779 "The `IndexerName' attribute is valid only on an " +
6780 "indexer that is not an explicit interface member declaration");
6784 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6785 Report.Error (609, indexer_attr.Location,
6786 "Cannot set the `IndexerName' attribute on an indexer marked override");
6790 if (!Tokenizer.IsValidIdentifier (ShortName)) {
6791 Report.Error (633, indexer_attr.Location,
6792 "The argument to the `IndexerName' attribute must be a valid identifier");
6798 if (InterfaceType != null) {
6799 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
6800 if (base_IndexerName != Name)
6801 ShortName = base_IndexerName;
6804 if (!ParentContainer.AddToMemberContainer (this) ||
6805 !ParentContainer.AddToMemberContainer (Get) || !ParentContainer.AddToMemberContainer (Set))
6811 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6813 GetBuilder = Get.Define (Parent);
6814 if (GetBuilder == null)
6818 SetBuilder = Set.Define (Parent);
6820 if (SetBuilder == null)
6825 // Now name the parameters
6827 Parameter [] p = Parameters.FixedParameters;
6829 // TODO: should be done in parser and it needs to do cycle
6830 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
6831 Report.Error (631, Location, "ref and out are not valid in this context");
6836 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6837 Name, PropertyAttributes.None, MemberType, ParameterTypes);
6840 PropertyBuilder.SetGetMethod (GetBuilder);
6843 PropertyBuilder.SetSetMethod (SetBuilder);
6845 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
6850 public override string GetSignatureForError ()
6852 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
6853 if (MemberName.Left != null) {
6855 sb.Append (MemberName.Left);
6858 sb.Append (".this");
6859 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
6860 return sb.ToString ();
6863 public override bool MarkForDuplicationCheck ()
6865 caching_flags |= Flags.TestMethodDuplication;
6870 public class Operator : MethodCore, IIteratorContainer {
6872 const int AllowedModifiers =
6878 public enum OpType : byte {
6888 // Unary and Binary operators
6911 // Implicit and Explicit
6915 // Just because of enum
6919 public readonly OpType OperatorType;
6920 public MethodBuilder OperatorMethodBuilder;
6922 public Method OperatorMethod;
6924 static string[] attribute_targets = new string [] { "method", "return" };
6926 public Operator (DeclSpace parent, OpType type, Expression ret_type,
6927 int mod_flags, Parameters parameters,
6928 ToplevelBlock block, Attributes attrs, Location loc)
6929 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
6930 new MemberName ("op_" + type, loc), attrs, parameters)
6932 OperatorType = type;
6936 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6938 OperatorMethod.ApplyAttributeBuilder (a, cb);
6941 public override AttributeTargets AttributeTargets {
6943 return AttributeTargets.Method;
6947 protected override bool CheckForDuplications ()
6949 ArrayList ar = ParentContainer.Operators;
6951 int arLen = ar.Count;
6953 for (int i = 0; i < arLen; i++) {
6954 Operator o = (Operator) ar [i];
6955 if (IsDuplicateImplementation (o))
6960 ar = ParentContainer.Methods;
6962 int arLen = ar.Count;
6964 for (int i = 0; i < arLen; i++) {
6965 Method m = (Method) ar [i];
6966 if (IsDuplicateImplementation (m))
6974 public override bool Define ()
6976 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
6977 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
6978 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
6985 if (MemberType == TypeManager.void_type) {
6986 Report.Error (590, Location, "User-defined operators cannot return void");
6990 OperatorMethod = new Method (
6991 Parent, Type, ModFlags, false, MemberName,
6992 Parameters, OptAttributes);
6994 OperatorMethod.Block = Block;
6995 OperatorMethod.IsOperator = this;
6996 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
6997 OperatorMethod.Define ();
6999 if (OperatorMethod.MethodBuilder == null)
7002 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7004 Type[] parameter_types = OperatorMethod.ParameterTypes;
7005 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7006 Type return_type = OperatorMethod.ReturnType;
7007 Type first_arg_type = parameter_types [0];
7012 // Rules for conversion operators
7014 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7015 if (first_arg_type == return_type && first_arg_type == declaring_type){
7016 Report.Error (555, Location,
7017 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7021 if (first_arg_type != declaring_type && return_type != declaring_type){
7024 "User-defined conversion must convert to or from the " +
7029 if (first_arg_type.IsInterface || return_type.IsInterface){
7030 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7031 GetSignatureForError ());
7035 if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type)) {
7036 if (declaring_type.IsSubclassOf (return_type) || declaring_type.IsSubclassOf (first_arg_type)) {
7037 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7038 GetSignatureForError ());
7041 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7042 GetSignatureForError ());
7045 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7046 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7047 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");
7050 } else if (Parameters.Count == 1) {
7051 // Checks for Unary operators
7053 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7054 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7055 Report.Error (448, Location,
7056 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7059 if (first_arg_type != declaring_type) {
7061 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7066 if (first_arg_type != declaring_type){
7069 "The parameter of a unary operator must be the " +
7074 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7075 if (return_type != TypeManager.bool_type){
7078 "The return type of operator True or False " +
7085 // Checks for Binary operators
7087 if (first_arg_type != declaring_type &&
7088 parameter_types [1] != declaring_type){
7091 "One of the parameters of a binary operator must " +
7092 "be the containing type");
7100 public override void Emit ()
7103 // abstract or extern methods have no bodies
7105 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7108 OperatorMethod.Emit ();
7112 // Operator cannot be override
7113 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7118 public static string GetName (OpType ot)
7121 case OpType.LogicalNot:
7123 case OpType.OnesComplement:
7125 case OpType.Increment:
7127 case OpType.Decrement:
7133 case OpType.Addition:
7135 case OpType.Subtraction:
7137 case OpType.UnaryPlus:
7139 case OpType.UnaryNegation:
7141 case OpType.Multiply:
7143 case OpType.Division:
7145 case OpType.Modulus:
7147 case OpType.BitwiseAnd:
7149 case OpType.BitwiseOr:
7151 case OpType.ExclusiveOr:
7153 case OpType.LeftShift:
7155 case OpType.RightShift:
7157 case OpType.Equality:
7159 case OpType.Inequality:
7161 case OpType.GreaterThan:
7163 case OpType.LessThan:
7165 case OpType.GreaterThanOrEqual:
7167 case OpType.LessThanOrEqual:
7169 case OpType.Implicit:
7171 case OpType.Explicit:
7177 public static OpType GetOperatorType (string name)
7179 if (name.StartsWith ("op_")){
7180 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7181 if (Unary.oper_names [i] == name)
7185 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7186 if (Binary.oper_names [i] == name)
7193 public override string GetSignatureForError ()
7195 StringBuilder sb = new StringBuilder ();
7196 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7197 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7200 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7203 sb.Append (Parameters.GetSignatureForError ());
7204 return sb.ToString ();
7207 public override bool MarkForDuplicationCheck ()
7209 caching_flags |= Flags.TestMethodDuplication;
7213 public override string[] ValidAttributeTargets {
7215 return attribute_targets;
7221 // This is used to compare method signatures
7223 struct MethodSignature {
7225 public Type RetType;
7226 public Type [] Parameters;
7229 /// This delegate is used to extract methods which have the
7230 /// same signature as the argument
7232 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7234 public MethodSignature (string name, Type ret_type, Type [] parameters)
7239 if (parameters == null)
7240 Parameters = Type.EmptyTypes;
7242 Parameters = parameters;
7245 public override string ToString ()
7248 if (Parameters.Length != 0){
7249 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7250 for (int i = 0; i < Parameters.Length; i++){
7251 sb.Append (Parameters [i]);
7252 if (i+1 < Parameters.Length)
7255 pars = sb.ToString ();
7258 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7261 public override int GetHashCode ()
7263 return Name.GetHashCode ();
7266 public override bool Equals (Object o)
7268 MethodSignature other = (MethodSignature) o;
7270 if (other.Name != Name)
7273 if (other.RetType != RetType)
7276 if (Parameters == null){
7277 if (other.Parameters == null)
7282 if (other.Parameters == null)
7285 int c = Parameters.Length;
7286 if (other.Parameters.Length != c)
7289 for (int i = 0; i < c; i++)
7290 if (other.Parameters [i] != Parameters [i])
7296 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7298 MethodSignature sig = (MethodSignature) filter_criteria;
7300 if (m.Name != sig.Name)
7304 MethodInfo mi = m as MethodInfo;
7305 PropertyInfo pi = m as PropertyInfo;
7308 ReturnType = mi.ReturnType;
7309 else if (pi != null)
7310 ReturnType = pi.PropertyType;
7315 // we use sig.RetType == null to mean `do not check the
7316 // method return value.
7318 if (sig.RetType != null)
7319 if (ReturnType != sig.RetType)
7324 args = TypeManager.GetParameterData (mi).Types;
7326 args = TypeManager.GetArgumentTypes (pi);
7327 Type [] sigp = sig.Parameters;
7329 if (args.Length != sigp.Length)
7332 for (int i = args.Length; i > 0; ){
7334 if (args [i] != sigp [i])