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;
46 using Mono.CompilerServices.SymbolWriter;
48 namespace Mono.CSharp {
58 /// This is the base class for structs and classes.
60 public abstract class TypeContainer : DeclSpace, IMemberContainer {
62 public class MemberCoreArrayList: ArrayList
65 /// Defines the MemberCore objects that are in this array
67 public virtual void DefineContainerMembers ()
69 foreach (MemberCore mc in this) {
74 throw new InternalErrorException (mc.Location, mc.GetSignatureForError (), e);
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.MemberType;
236 Type [] pt = o.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.MethodBuilder == 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 protected Constructor default_constructor;
439 protected 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";
471 GenericTypeParameterBuilder[] gen_params;
473 ArrayList partial_parts;
476 /// The pending methods that need to be implemented
477 // (interfaces or abstract methods)
479 PendingImplementation pending;
481 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
482 Attributes attrs, Kind kind)
483 : base (ns, parent, name, attrs)
485 if (parent != null && parent.NamespaceEntry != ns)
486 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
489 this.PartialContainer = this;
492 public bool AddMember (MemberCore symbol)
494 return AddToContainer (symbol, symbol.MemberName.MethodName);
497 protected virtual bool AddMemberType (DeclSpace ds)
499 return AddToContainer (ds, ds.Basename);
502 public void AddConstant (Const constant)
504 if (!AddMember (constant))
507 if (constants == null)
508 constants = new MemberCoreArrayList ();
510 constants.Add (constant);
513 public void AddEnum (Mono.CSharp.Enum e)
515 if (!AddMemberType (e))
519 enums = new MemberCoreArrayList ();
524 public TypeContainer AddTypeContainer (TypeContainer tc, bool is_interface)
526 if (!AddMemberType (tc))
530 if (interfaces == null)
531 interfaces = new MemberCoreArrayList ();
535 types = new ArrayList (2);
541 public virtual TypeContainer AddPartial (TypeContainer nextPart, bool is_interface)
543 return AddPartial (nextPart, nextPart.Basename, is_interface);
546 protected TypeContainer AddPartial (TypeContainer nextPart, string name, bool is_interface)
548 nextPart.ModFlags |= Modifiers.PARTIAL;
549 TypeContainer tc = defined_names [name] as TypeContainer;
552 return AddTypeContainer (nextPart, is_interface);
554 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
555 Report.SymbolRelatedToPreviousError (tc);
556 Error_MissingPartialModifier (nextPart);
560 if (tc.Kind != nextPart.Kind) {
561 Report.SymbolRelatedToPreviousError (tc);
562 Report.Error (261, nextPart.Location,
563 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
564 nextPart.GetSignatureForError ());
568 if ((tc.ModFlags & Modifiers.Accessibility) != (nextPart.ModFlags & Modifiers.Accessibility) &&
569 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
570 (nextPart.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
571 Report.SymbolRelatedToPreviousError (tc);
572 Report.Error (262, nextPart.Location,
573 "Partial declarations of `{0}' have conflicting accessibility modifiers",
574 nextPart.GetSignatureForError ());
578 if (tc.MemberName.IsGeneric) {
579 TypeParameter[] tc_names = tc.TypeParameters;
580 TypeParameterName[] part_names = nextPart.MemberName.TypeArguments.GetDeclarations ();
582 for (int i = 0; i < tc_names.Length; ++i) {
583 if (tc_names[i].Name == part_names[i].Name)
586 Report.SymbolRelatedToPreviousError (part_names[i].Location, "");
587 Report.Error (264, tc.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
588 tc.GetSignatureForError ());
593 if (tc.partial_parts == null)
594 tc.partial_parts = new ArrayList (1);
596 tc.ModFlags |= nextPart.ModFlags;
597 if (nextPart.attributes != null) {
598 if (tc.attributes == null)
599 tc.attributes = nextPart.attributes;
601 tc.attributes.AddAttributes (nextPart.attributes.Attrs);
604 nextPart.PartialContainer = tc;
605 tc.partial_parts.Add (nextPart);
609 public void AddDelegate (Delegate d)
611 if (!AddMemberType (d))
614 if (delegates == null)
615 delegates = new MemberCoreArrayList ();
620 public void AddMethod (Method method)
622 if (!AddMember (method))
626 methods = new MethodArrayList (this);
628 if (method.MemberName.Left != null)
629 methods.Insert (0, method);
631 methods.Add (method);
635 // Do not use this method: use AddMethod.
637 // This is only used by iterators.
639 public void AppendMethod (Method method)
641 if (!AddMember (method))
645 methods = new MethodArrayList (this);
647 methods.Add (method);
650 public void AddConstructor (Constructor c)
652 if (c.Name != MemberName.Name) {
653 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
656 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
659 if (default_static_constructor != null) {
660 Report.SymbolRelatedToPreviousError (default_static_constructor);
661 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
665 default_static_constructor = c;
667 if (c.Parameters.Empty){
668 if (default_constructor != null) {
669 Report.SymbolRelatedToPreviousError (default_constructor);
670 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
673 default_constructor = c;
676 if (instance_constructors == null)
677 instance_constructors = new MemberCoreArrayList ();
679 instance_constructors.Add (c);
683 internal static string Error111 {
685 return "`{0}' is already defined. Rename this member or use different parameter types";
689 public void AddField (FieldMember field)
691 if (!AddMember (field))
695 fields = new MemberCoreArrayList ();
699 if ((field.ModFlags & Modifiers.STATIC) != 0)
702 if (first_nonstatic_field == null) {
703 first_nonstatic_field = field;
707 if (Kind == Kind.Struct &&
708 first_nonstatic_field.Parent != field.Parent &&
709 RootContext.WarningLevel >= 3) {
710 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
711 Report.Warning (282, 3, field.Location,
712 "struct instance field `{0}' found in different declaration from instance field `{1}'",
713 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
717 public void AddProperty (Property prop)
719 if (!AddMember (prop) ||
720 !AddMember (prop.Get) || !AddMember (prop.Set))
723 if (properties == null)
724 properties = new MemberCoreArrayList ();
726 if (prop.MemberName.Left != null)
727 properties.Insert (0, prop);
729 properties.Add (prop);
732 public void AddEvent (Event e)
737 if (e is EventProperty) {
738 if (!AddMember (e.Add))
741 if (!AddMember (e.Remove))
746 events = new MemberCoreArrayList ();
752 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
754 public void AddIndexer (Indexer i)
756 if (indexers == null)
757 indexers = new IndexerArrayList (this);
759 if (i.IsExplicitImpl)
760 indexers.Insert (0, i);
765 public void AddOperator (Operator op)
770 if (operators == null)
771 operators = new OperatorArrayList (this);
776 public void AddIterator (Iterator i)
778 if (iterators == null)
779 iterators = new ArrayList ();
784 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
786 if (a.Type == TypeManager.default_member_type) {
787 if (Indexers != null) {
788 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
793 base.ApplyAttributeBuilder (a, cb);
796 public override AttributeTargets AttributeTargets {
798 throw new NotSupportedException ();
802 public ArrayList Types {
808 public MethodArrayList Methods {
814 public ArrayList Constants {
820 public ArrayList Interfaces {
826 public ArrayList Iterators {
832 protected Type BaseType {
834 return TypeBuilder.BaseType;
838 public ArrayList Bases {
848 public ArrayList Fields {
854 public ArrayList InstanceConstructors {
856 return instance_constructors;
860 public ArrayList Properties {
866 public ArrayList Events {
872 public ArrayList Enums {
878 public ArrayList Indexers {
884 public ArrayList Operators {
890 public ArrayList Delegates {
896 protected override TypeAttributes TypeAttr {
898 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
902 public string IndexerName {
904 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
908 public bool IsComImport {
910 if (OptAttributes == null)
913 return OptAttributes.Contains (TypeManager.comimport_attr_type);
917 public virtual void RegisterFieldForInitialization (FieldBase field)
919 if ((field.ModFlags & Modifiers.STATIC) != 0){
920 if (initialized_static_fields == null)
921 initialized_static_fields = new ArrayList (4);
923 initialized_static_fields.Add (field);
925 if (initialized_fields == null)
926 initialized_fields = new ArrayList (4);
928 initialized_fields.Add (field);
933 // Emits the instance field initializers
935 public bool EmitFieldInitializers (EmitContext ec)
940 fields = initialized_static_fields;
942 fields = initialized_fields;
948 foreach (FieldBase f in fields) {
949 f.EmitInitializer (ec);
954 public override string DocComment {
966 public PendingImplementation PendingImplementations {
967 get { return pending; }
970 public override bool GetClsCompliantAttributeValue ()
972 if (PartialContainer != this)
973 return PartialContainer.GetClsCompliantAttributeValue ();
975 return base.GetClsCompliantAttributeValue ();
978 public void AddBasesForPart (DeclSpace part, ArrayList bases)
980 // FIXME: get rid of partial_parts and store lists of bases of each part here
981 // assumed, not verified: 'part' is in 'partial_parts'
982 ((TypeContainer) part).Bases = bases;
985 TypeExpr[] GetNormalBases (out TypeExpr base_class)
991 int count = Bases.Count;
994 if (Kind == Kind.Class){
995 TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
1001 if (!name.IsInterface) {
1002 // base_class could be a class, struct, enum, delegate.
1003 // This is validated in GetClassBases.
1009 TypeExpr [] ifaces = new TypeExpr [count-start];
1011 for (i = start, j = 0; i < count; i++, j++){
1012 TypeExpr resolved = ((Expression) Bases [i]).ResolveAsBaseTerminal (this, false);
1013 if (resolved == null) {
1017 ifaces [j] = resolved;
1020 return ifaces.Length == 0 ? null : ifaces;
1024 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
1026 ArrayList ifaces = new ArrayList (0);
1027 if (iface_exprs != null)
1028 ifaces.AddRange (iface_exprs);
1030 foreach (TypeContainer part in partial_parts) {
1031 TypeExpr new_base_class;
1032 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
1033 if (new_base_class != TypeManager.system_object_expr) {
1034 if (base_class == TypeManager.system_object_expr)
1035 base_class = new_base_class;
1037 if (new_base_class != null && !new_base_class.Equals (base_class)) {
1038 Report.SymbolRelatedToPreviousError (base_class.Location, "");
1039 Report.Error (263, part.Location,
1040 "Partial declarations of `{0}' must not specify different base classes",
1041 part.GetSignatureForError ());
1048 if (new_ifaces == null)
1051 foreach (TypeExpr iface in new_ifaces) {
1052 if (ifaces.Contains (iface))
1059 if (ifaces.Count == 0)
1062 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
1066 /// This function computes the Base class and also the
1067 /// list of interfaces that the class or struct @c implements.
1069 /// The return value is an array (might be null) of
1070 /// interfaces implemented (as Types).
1072 /// The @base_class argument is set to the base object or null
1073 /// if this is `System.Object'.
1075 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1077 TypeExpr[] ifaces = GetNormalBases (out base_class);
1082 int count = ifaces.Length;
1084 for (int i = 0; i < count; i++) {
1085 TypeExpr iface = (TypeExpr) ifaces [i];
1087 if (!iface.IsInterface) {
1088 if (Kind != Kind.Class) {
1089 // TODO: location of symbol related ....
1090 Error_TypeInListIsNotInterface (Location, iface.FullName);
1092 else if (base_class != null)
1093 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1094 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1096 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1097 GetSignatureForError (), iface.GetSignatureForError ());
1102 for (int x = 0; x < i; x++) {
1103 if (iface.Equals (ifaces [x])) {
1104 Report.Error (528, Location,
1105 "`{0}' is already listed in " +
1106 "interface list", iface.GetSignatureForError ());
1111 if ((Kind == Kind.Interface) &&
1112 !iface.AsAccessible (Parent, ModFlags)) {
1113 Report.Error (61, Location,
1114 "Inconsistent accessibility: base " +
1115 "interface `{0}' is less accessible " +
1116 "than interface `{1}'", iface.Name,
1124 bool CheckGenericInterfaces (Type[] ifaces)
1126 ArrayList already_checked = new ArrayList ();
1128 for (int i = 0; i < ifaces.Length; i++) {
1129 Type iface = ifaces [i];
1130 foreach (Type t in already_checked) {
1134 Type[] infered = new Type [CountTypeParameters];
1135 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1138 Report.Error (695, Location,
1139 "`{0}' cannot implement both `{1}' and `{2}' " +
1140 "because they may unify for some type parameter substitutions",
1141 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1142 TypeManager.CSharpName (t));
1146 already_checked.Add (iface);
1154 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1156 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1159 bool DefineTypeBuilder ()
1163 if (TypeManager.NamespaceClash (Name, Location)) {
1167 ModuleBuilder builder = CodeGen.Module.Builder;
1168 Type default_parent = null;
1169 if (Kind == Kind.Struct)
1170 default_parent = TypeManager.value_type;
1171 TypeBuilder = builder.DefineType (
1172 Name, TypeAttr, default_parent, null);
1174 TypeBuilder builder = Parent.TypeBuilder;
1176 TypeBuilder = builder.DefineNestedType (
1177 Basename, TypeAttr, null, null);
1179 } catch (ArgumentException) {
1180 Report.RuntimeMissingSupport (Location, "static classes");
1184 TypeManager.AddUserType (this);
1187 string[] param_names = new string [TypeParameters.Length];
1188 for (int i = 0; i < TypeParameters.Length; i++)
1189 param_names [i] = TypeParameters [i].Name;
1191 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1193 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1194 for (int i = offset; i < gen_params.Length; i++)
1195 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1198 iface_exprs = GetClassBases (out base_type);
1199 if (partial_parts != null) {
1200 iface_exprs = GetNormalPartialBases (ref base_type);
1204 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1205 // which in turn should have called DefineType()s on base types if necessary.
1207 // None of the code below should trigger DefineType()s on classes that we depend on.
1208 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1210 // Let's do it as soon as possible, since code below can call DefineType() on classes
1211 // that depend on us to be populated before they are.
1213 if (!(this is Iterator))
1214 RootContext.RegisterOrder (this);
1216 if (base_type != null) {
1217 if (IsGeneric && TypeManager.IsAttributeType (base_type.Type)) {
1218 Report.Error (698, base_type.Location,
1219 "A generic type cannot derive from `{0}' " +
1220 "because it is an attribute class",
1225 TypeBuilder.SetParent (base_type.Type);
1227 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1228 if (obsolete_attr != null && !IsInObsoleteScope) {
1229 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1233 if (!CheckRecursiveDefinition (this)) {
1237 // add interfaces that were not added at type creation
1238 if (iface_exprs != null) {
1239 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1240 if (ifaces == null) {
1244 foreach (Type itype in ifaces)
1245 TypeBuilder.AddInterfaceImplementation (itype);
1247 foreach (TypeExpr ie in iface_exprs) {
1248 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
1249 if ((oa != null) && !IsInObsoleteScope)
1250 AttributeTester.Report_ObsoleteMessage (
1251 oa, ie.GetSignatureForError (), Location);
1254 if (!CheckGenericInterfaces (ifaces)) {
1258 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1261 if (this is Iterator && !ResolveType ()) {
1269 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1271 public override TypeBuilder DefineType ()
1273 if (TypeBuilder != null)
1279 if (!DefineTypeBuilder ()) {
1284 if (partial_parts != null) {
1285 foreach (TypeContainer part in partial_parts)
1286 part.TypeBuilder = TypeBuilder;
1289 DefineNestedTypes ();
1294 Constraints [] constraints;
1295 public override void SetParameterInfo (ArrayList constraints_list)
1297 if (PartialContainer == this) {
1298 base.SetParameterInfo (constraints_list);
1302 if (constraints_list == null)
1305 constraints = new Constraints [PartialContainer.CountCurrentTypeParameters];
1307 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1308 for (int i = 0; i < constraints.Length; i++) {
1309 foreach (Constraints constraint in constraints_list) {
1310 if (constraint.TypeParameter == current_params [i].Name) {
1311 constraints [i] = constraint;
1318 bool UpdateTypeParameterConstraints ()
1320 if (constraints == null)
1323 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1324 for (int i = 0; i < current_params.Length; i++) {
1325 if (!current_params [i].UpdateConstraints (this, constraints [i])) {
1326 Report.SymbolRelatedToPreviousError (Location, "");
1327 Report.Error (265, PartialContainer.Location,
1328 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1329 PartialContainer.GetSignatureForError (), current_params [i].Name);
1337 public bool ResolveType ()
1339 if ((base_type != null) &&
1340 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1348 if (PartialContainer != this)
1349 throw new InternalErrorException ();
1351 TypeExpr current_type = null;
1353 foreach (TypeParameter type_param in CurrentTypeParameters) {
1354 if (!type_param.Resolve (this)) {
1360 if (partial_parts != null) {
1361 foreach (TypeContainer part in partial_parts) {
1362 if (!part.UpdateTypeParameterConstraints ()) {
1369 foreach (TypeParameter type_param in TypeParameters) {
1370 if (!type_param.DefineType (this)) {
1376 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1378 foreach (TypeParameter type_param in TypeParameters)
1379 if (!type_param.CheckDependencies ()) {
1384 if (current_type != null) {
1385 current_type = current_type.ResolveAsTypeTerminal (this, false);
1386 if (current_type == null) {
1391 CurrentType = current_type.Type;
1397 protected virtual bool DefineNestedTypes ()
1399 if (Interfaces != null) {
1400 foreach (TypeContainer iface in Interfaces)
1401 if (iface.DefineType () == null)
1405 if (Types != null) {
1406 foreach (TypeContainer tc in Types)
1407 if (tc.DefineType () == null)
1411 if (Delegates != null) {
1412 foreach (Delegate d in Delegates)
1413 if (d.DefineType () == null)
1417 if (Enums != null) {
1418 foreach (Enum en in Enums)
1419 if (en.DefineType () == null)
1426 TypeContainer InTransit;
1428 protected bool CheckRecursiveDefinition (TypeContainer tc)
1430 if (InTransit != null) {
1431 Report.SymbolRelatedToPreviousError (this);
1432 if (this is Interface)
1434 529, tc.Location, "Inherited interface `{0}' causes a " +
1435 "cycle in the interface hierarchy of `{1}'",
1436 GetSignatureForError (), tc.GetSignatureForError ());
1439 146, tc.Location, "Circular base class dependency " +
1440 "involving `{0}' and `{1}'",
1441 tc.GetSignatureForError (), GetSignatureForError ());
1447 if (BaseType != null) {
1448 Type t = TypeManager.DropGenericTypeArguments (BaseType);
1449 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1450 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1454 if (iface_exprs != null) {
1455 foreach (TypeExpr iface in iface_exprs) {
1456 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1457 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1458 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1463 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1470 public static void Error_KeywordNotAllowed (Location loc)
1472 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1476 /// Populates our TypeBuilder with fields and methods
1478 public override bool DefineMembers ()
1480 if (members_defined)
1481 return members_defined_ok;
1483 if (!base.DefineMembers ())
1486 members_defined_ok = DoDefineMembers ();
1487 members_defined = true;
1489 return members_defined_ok;
1492 protected virtual bool DoDefineMembers ()
1494 if (iface_exprs != null) {
1495 foreach (TypeExpr iface in iface_exprs) {
1496 ConstructedType ct = iface as ConstructedType;
1497 if ((ct != null) && !ct.CheckConstraints (this))
1502 if (base_type != null) {
1503 ConstructedType ct = base_type as ConstructedType;
1504 if ((ct != null) && !ct.CheckConstraints (this))
1509 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1510 if (conflict_symbol == null) {
1511 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1512 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1514 if ((ModFlags & Modifiers.NEW) == 0) {
1515 Report.SymbolRelatedToPreviousError (conflict_symbol);
1516 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1517 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1522 DefineContainerMembers (constants);
1523 DefineContainerMembers (fields);
1525 if (Kind == Kind.Struct || Kind == Kind.Class) {
1526 pending = PendingImplementation.GetPendingImplementations (this);
1530 // Constructors are not in the defined_names array
1532 DefineContainerMembers (instance_constructors);
1534 DefineContainerMembers (properties);
1535 DefineContainerMembers (events);
1536 DefineContainerMembers (indexers);
1537 DefineContainerMembers (methods);
1538 DefineContainerMembers (operators);
1539 DefineContainerMembers (enums);
1540 DefineContainerMembers (delegates);
1542 if (CurrentType != null) {
1543 GenericType = CurrentType;
1548 member_cache = new MemberCache (this);
1549 if (partial_parts != null) {
1550 foreach (TypeContainer part in partial_parts)
1551 part.member_cache = member_cache;
1554 if (iterators != null) {
1555 foreach (Iterator iterator in iterators) {
1556 if (iterator.DefineType () == null)
1560 foreach (Iterator iterator in iterators) {
1561 if (!iterator.DefineMembers ())
1569 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1572 mcal.DefineContainerMembers ();
1575 public override bool Define ()
1577 if (iterators != null) {
1578 foreach (Iterator iterator in iterators) {
1579 if (!iterator.Define ())
1587 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1589 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1593 /// This function is based by a delegate to the FindMembers routine
1595 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1601 /// This filter is used by FindMembers, and we just keep
1602 /// a global for the filter to `AlwaysAccept'
1604 static MemberFilter accepting_filter;
1607 static TypeContainer ()
1609 accepting_filter = new MemberFilter (AlwaysAccept);
1612 public MethodInfo[] GetMethods ()
1614 ArrayList members = new ArrayList ();
1618 if (methods != null) {
1619 int len = methods.Count;
1620 for (int i = 0; i < len; i++) {
1621 Method m = (Method) methods [i];
1623 members.Add (m.MethodBuilder);
1627 if (operators != null) {
1628 int len = operators.Count;
1629 for (int i = 0; i < len; i++) {
1630 Operator o = (Operator) operators [i];
1632 members.Add (o.MethodBuilder);
1636 if (properties != null) {
1637 int len = properties.Count;
1638 for (int i = 0; i < len; i++) {
1639 Property p = (Property) properties [i];
1641 if (p.GetBuilder != null)
1642 members.Add (p.GetBuilder);
1643 if (p.SetBuilder != null)
1644 members.Add (p.SetBuilder);
1648 if (indexers != null) {
1649 int len = indexers.Count;
1650 for (int i = 0; i < len; i++) {
1651 Indexer ix = (Indexer) indexers [i];
1653 if (ix.GetBuilder != null)
1654 members.Add (ix.GetBuilder);
1655 if (ix.SetBuilder != null)
1656 members.Add (ix.SetBuilder);
1660 if (events != null) {
1661 int len = events.Count;
1662 for (int i = 0; i < len; i++) {
1663 Event e = (Event) events [i];
1665 if (e.AddBuilder != null)
1666 members.Add (e.AddBuilder);
1667 if (e.RemoveBuilder != null)
1668 members.Add (e.RemoveBuilder);
1672 MethodInfo[] retMethods = new MethodInfo [members.Count];
1673 members.CopyTo (retMethods, 0);
1677 // Indicated whether container has StructLayout attribute set Explicit
1678 public bool HasExplicitLayout {
1679 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1680 set { caching_flags |= Flags.HasExplicitLayout; }
1684 // Return the nested type with name @name. Ensures that the nested type
1685 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1687 public Type FindNestedType (string name)
1689 if (PartialContainer != this)
1690 throw new InternalErrorException ("should not happen");
1692 ArrayList [] lists = { types, enums, delegates, interfaces };
1694 for (int j = 0; j < lists.Length; ++j) {
1695 ArrayList list = lists [j];
1699 int len = list.Count;
1700 for (int i = 0; i < len; ++i) {
1701 DeclSpace ds = (DeclSpace) list [i];
1702 if (ds.Basename == name) {
1703 return ds.DefineType ();
1711 private void FindMembers_NestedTypes (int modflags,
1712 BindingFlags bf, MemberFilter filter, object criteria,
1713 ref ArrayList members)
1715 ArrayList [] lists = { types, enums, delegates, interfaces };
1717 for (int j = 0; j < lists.Length; ++j) {
1718 ArrayList list = lists [j];
1722 int len = list.Count;
1723 for (int i = 0; i < len; i++) {
1724 DeclSpace ds = (DeclSpace) list [i];
1726 if ((ds.ModFlags & modflags) == 0)
1729 TypeBuilder tb = ds.TypeBuilder;
1731 if (!(criteria is string) || ds.Basename.Equals (criteria))
1732 tb = ds.DefineType ();
1735 if (tb != null && (filter (tb, criteria) == true)) {
1736 if (members == null)
1737 members = new ArrayList ();
1746 /// This method returns the members of this type just like Type.FindMembers would
1747 /// Only, we need to use this for types which are _being_ defined because MS'
1748 /// implementation can't take care of that.
1751 // FIXME: return an empty static array instead of null, that cleans up
1752 // some code and is consistent with some coding conventions I just found
1756 // Notice that in various cases we check if our field is non-null,
1757 // something that would normally mean that there was a bug elsewhere.
1759 // The problem happens while we are defining p-invoke methods, as those
1760 // will trigger a FindMembers, but this happens before things are defined
1762 // Since the whole process is a no-op, it is fine to check for null here.
1764 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1765 MemberFilter filter, object criteria)
1767 ArrayList members = null;
1770 if ((bf & BindingFlags.Public) != 0)
1771 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1773 if ((bf & BindingFlags.NonPublic) != 0)
1774 modflags |= Modifiers.PRIVATE;
1776 int static_mask = 0, static_flags = 0;
1777 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1778 case BindingFlags.Static:
1779 static_mask = static_flags = Modifiers.STATIC;
1782 case BindingFlags.Instance:
1783 static_mask = Modifiers.STATIC;
1788 static_mask = static_flags = 0;
1792 Timer.StartTimer (TimerType.TcFindMembers);
1795 filter = accepting_filter;
1797 if ((mt & MemberTypes.Field) != 0) {
1798 if (fields != null) {
1799 int len = fields.Count;
1800 for (int i = 0; i < len; i++) {
1801 FieldMember f = (FieldMember) fields [i];
1803 if ((f.ModFlags & modflags) == 0)
1805 if ((f.ModFlags & static_mask) != static_flags)
1808 FieldBuilder fb = f.FieldBuilder;
1809 if (fb != null && filter (fb, criteria) == true) {
1810 if (members == null)
1811 members = new ArrayList ();
1818 if (constants != null) {
1819 int len = constants.Count;
1820 for (int i = 0; i < len; i++) {
1821 Const con = (Const) constants [i];
1823 if ((con.ModFlags & modflags) == 0)
1825 if ((con.ModFlags & static_mask) != static_flags)
1828 FieldBuilder fb = con.FieldBuilder;
1831 fb = con.FieldBuilder;
1833 if (fb != null && filter (fb, criteria) == true) {
1834 if (members == null)
1835 members = new ArrayList ();
1843 if ((mt & MemberTypes.Method) != 0) {
1844 if (methods != null) {
1845 int len = methods.Count;
1846 for (int i = 0; i < len; i++) {
1847 Method m = (Method) methods [i];
1849 if ((m.ModFlags & modflags) == 0)
1851 if ((m.ModFlags & static_mask) != static_flags)
1854 MethodBuilder mb = m.MethodBuilder;
1856 if (mb != null && filter (mb, criteria) == true) {
1857 if (members == null)
1858 members = new ArrayList ();
1865 if (operators != null) {
1866 int len = operators.Count;
1867 for (int i = 0; i < len; i++) {
1868 Operator o = (Operator) operators [i];
1870 if ((o.ModFlags & modflags) == 0)
1872 if ((o.ModFlags & static_mask) != static_flags)
1875 MethodBuilder ob = o.MethodBuilder;
1876 if (ob != null && filter (ob, criteria) == true) {
1877 if (members == null)
1878 members = new ArrayList ();
1885 if (events != null) {
1886 foreach (Event e in events) {
1887 if ((e.ModFlags & modflags) == 0)
1889 if ((e.ModFlags & static_mask) != static_flags)
1892 MethodBuilder b = e.AddBuilder;
1893 if (b != null && filter (b, criteria)) {
1894 if (members == null)
1895 members = new ArrayList (4);
1900 b = e.RemoveBuilder;
1901 if (b != null && filter (b, criteria)) {
1902 if (members == null)
1903 members = new ArrayList (4);
1910 if (properties != null) {
1911 int len = properties.Count;
1912 for (int i = 0; i < len; i++) {
1913 Property p = (Property) properties [i];
1915 if ((p.ModFlags & modflags) == 0)
1917 if ((p.ModFlags & static_mask) != static_flags)
1923 if (b != null && filter (b, criteria) == true) {
1924 if (members == null)
1925 members = new ArrayList ();
1931 if (b != null && filter (b, criteria) == true) {
1932 if (members == null)
1933 members = new ArrayList ();
1940 if (indexers != null) {
1941 int len = indexers.Count;
1942 for (int i = 0; i < len; i++) {
1943 Indexer ix = (Indexer) indexers [i];
1945 if ((ix.ModFlags & modflags) == 0)
1947 if ((ix.ModFlags & static_mask) != static_flags)
1953 if (b != null && filter (b, criteria) == true) {
1954 if (members == null)
1955 members = new ArrayList ();
1961 if (b != null && filter (b, criteria) == true) {
1962 if (members == null)
1963 members = new ArrayList ();
1971 if ((mt & MemberTypes.Event) != 0) {
1972 if (events != null) {
1973 int len = events.Count;
1974 for (int i = 0; i < len; i++) {
1975 Event e = (Event) events [i];
1977 if ((e.ModFlags & modflags) == 0)
1979 if ((e.ModFlags & static_mask) != static_flags)
1982 MemberInfo eb = e.EventBuilder;
1983 if (eb != null && filter (eb, criteria) == true) {
1984 if (members == null)
1985 members = new ArrayList ();
1987 members.Add (e.EventBuilder);
1993 if ((mt & MemberTypes.Property) != 0){
1994 if (properties != null) {
1995 int len = properties.Count;
1996 for (int i = 0; i < len; i++) {
1997 Property p = (Property) properties [i];
1999 if ((p.ModFlags & modflags) == 0)
2001 if ((p.ModFlags & static_mask) != static_flags)
2004 MemberInfo pb = p.PropertyBuilder;
2005 if (pb != null && filter (pb, criteria) == true) {
2006 if (members == null)
2007 members = new ArrayList ();
2009 members.Add (p.PropertyBuilder);
2014 if (indexers != null) {
2015 int len = indexers.Count;
2016 for (int i = 0; i < len; i++) {
2017 Indexer ix = (Indexer) indexers [i];
2019 if ((ix.ModFlags & modflags) == 0)
2021 if ((ix.ModFlags & static_mask) != static_flags)
2024 MemberInfo ib = ix.PropertyBuilder;
2025 if (ib != null && filter (ib, criteria) == true) {
2026 if (members == null)
2027 members = new ArrayList ();
2029 members.Add (ix.PropertyBuilder);
2035 if ((mt & MemberTypes.NestedType) != 0)
2036 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2038 if ((mt & MemberTypes.Constructor) != 0){
2039 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2040 int len = instance_constructors.Count;
2041 for (int i = 0; i < len; i++) {
2042 Constructor c = (Constructor) instance_constructors [i];
2044 ConstructorBuilder cb = c.ConstructorBuilder;
2045 if (cb != null && filter (cb, criteria) == true) {
2046 if (members == null)
2047 members = new ArrayList ();
2054 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2055 ConstructorBuilder cb =
2056 default_static_constructor.ConstructorBuilder;
2058 if (cb != null && filter (cb, criteria) == true) {
2059 if (members == null)
2060 members = new ArrayList ();
2068 // Lookup members in base if requested.
2070 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2071 if (TypeBuilder.BaseType != null) {
2072 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2073 if (list.Count > 0) {
2074 if (members == null)
2075 members = new ArrayList ();
2077 members.AddRange (list);
2083 Timer.StopTimer (TimerType.TcFindMembers);
2085 if (members == null)
2086 return MemberList.Empty;
2088 return new MemberList (members);
2091 public override MemberCache MemberCache {
2093 return member_cache;
2097 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2098 MemberFilter filter, object criteria)
2100 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2103 return ds.FindMembers (mt, bf, filter, criteria);
2105 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2109 /// Emits the values for the constants
2111 public void EmitConstants ()
2113 if (constants != null)
2114 foreach (Const con in constants)
2119 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2124 foreach (MemberCore mc in al) {
2125 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2129 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2134 public virtual void VerifyMembers ()
2137 // Check for internal or private fields that were never assigned
2139 if (RootContext.WarningLevel >= 3) {
2140 CheckMemberUsage (properties, "property");
2141 CheckMemberUsage (methods, "method");
2142 CheckMemberUsage (constants, "constant");
2144 if (fields != null){
2145 foreach (FieldMember f in fields) {
2146 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2150 if ((f.caching_flags & Flags.IsAssigned) == 0)
2151 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2154 const int error_code = 414;
2156 const int error_code = 169;
2158 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2159 f.GetSignatureForError ());
2165 // Only report 649 on level 4
2167 if (RootContext.WarningLevel < 4)
2170 if ((f.caching_flags & Flags.IsAssigned) != 0)
2173 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2174 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2180 // TODO: move to ClassOrStruct
2181 void EmitConstructors ()
2183 if (instance_constructors == null)
2186 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2187 bool has_compliant_args = false;
2189 foreach (Constructor c in instance_constructors) {
2192 if (has_compliant_args)
2195 has_compliant_args = c.HasCompliantArgs;
2197 if (!has_compliant_args)
2198 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2200 foreach (Constructor c in instance_constructors)
2206 /// Emits the code, this step is performed after all
2207 /// the types, enumerations, constructors
2209 public virtual void EmitType ()
2211 if (OptAttributes != null)
2212 OptAttributes.Emit ();
2215 int offset = CountTypeParameters - CurrentTypeParameters.Length;
2216 for (int i = offset; i < gen_params.Length; i++)
2217 CurrentTypeParameters [i - offset].EmitAttributes ();
2221 // Structs with no fields need to have at least one byte.
2222 // The right thing would be to set the PackingSize in a DefineType
2223 // but there are no functions that allow interfaces *and* the size to
2227 if (Kind == Kind.Struct && first_nonstatic_field == null){
2228 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2229 FieldAttributes.Private);
2231 if (HasExplicitLayout){
2232 object [] ctor_args = new object [1];
2235 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2236 TypeManager.field_offset_attribute_ctor, ctor_args);
2237 fb.SetCustomAttribute (cba);
2243 EmitConstructors ();
2245 // Can not continue if constants are broken
2247 if (Report.Errors > 0)
2250 if (default_static_constructor != null)
2251 default_static_constructor.Emit ();
2253 if (methods != null){
2254 foreach (Method m in methods)
2258 if (operators != null)
2259 foreach (Operator o in operators)
2262 if (properties != null)
2263 foreach (Property p in properties)
2266 if (indexers != null){
2271 foreach (FieldMember f in fields)
2274 if (events != null){
2275 foreach (Event e in Events)
2279 if (delegates != null) {
2280 foreach (Delegate d in Delegates) {
2285 if (enums != null) {
2286 foreach (Enum e in enums) {
2291 if (pending != null)
2292 if (pending.VerifyPendingMethods ())
2295 if (iterators != null)
2296 foreach (Iterator iterator in iterators)
2297 iterator.EmitType ();
2300 public override void CloseType ()
2302 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2306 caching_flags |= Flags.CloseTypeCreated;
2307 TypeBuilder.CreateType ();
2308 } catch (TypeLoadException){
2310 // This is fine, the code still created the type
2312 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2313 // Console.WriteLine (e.Message);
2315 Console.WriteLine ("In type: " + Name);
2320 foreach (Enum en in Enums)
2324 foreach (TypeContainer tc in Types)
2325 if (tc.Kind == Kind.Struct)
2328 foreach (TypeContainer tc in Types)
2329 if (tc.Kind != Kind.Struct)
2333 if (Delegates != null)
2334 foreach (Delegate d in Delegates)
2337 if (Iterators != null)
2338 foreach (Iterator i in Iterators)
2346 initialized_fields = null;
2347 initialized_static_fields = null;
2355 default_constructor = null;
2356 default_static_constructor = null;
2358 OptAttributes = null;
2361 member_cache = null;
2365 // Performs the validation on a Method's modifiers (properties have
2366 // the same properties).
2368 public bool MethodModifiersValid (MemberCore mc)
2370 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2371 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2372 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2374 int flags = mc.ModFlags;
2377 // At most one of static, virtual or override
2379 if ((flags & Modifiers.STATIC) != 0){
2380 if ((flags & vao) != 0){
2381 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2382 mc.GetSignatureForError ());
2387 if (Kind == Kind.Struct){
2388 if ((flags & va) != 0){
2389 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2394 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2395 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2396 mc.GetSignatureForError ());
2401 // If the declaration includes the abstract modifier, then the
2402 // declaration does not include static, virtual or extern
2404 if ((flags & Modifiers.ABSTRACT) != 0){
2405 if ((flags & Modifiers.EXTERN) != 0){
2407 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2411 if ((flags & Modifiers.SEALED) != 0) {
2412 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2416 if ((flags & Modifiers.VIRTUAL) != 0){
2417 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2421 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2422 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2427 if ((flags & Modifiers.PRIVATE) != 0){
2428 if ((flags & vao) != 0){
2429 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2434 if ((flags & Modifiers.SEALED) != 0){
2435 if ((flags & Modifiers.OVERRIDE) == 0){
2436 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2444 public Constructor DefaultStaticConstructor {
2445 get { return default_static_constructor; }
2448 protected override bool VerifyClsCompliance ()
2450 if (!base.VerifyClsCompliance ())
2455 Type base_type = TypeBuilder.BaseType;
2456 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2457 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2460 if (!Parent.IsClsComplianceRequired ()) {
2461 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
2462 GetSignatureForError (), Parent.GetSignatureForError ());
2469 /// Checks whether container name is CLS Compliant
2471 void VerifyClsName ()
2473 Hashtable base_members = base_cache == null ?
2475 base_cache.GetPublicMembers ();
2476 Hashtable this_members = new Hashtable ();
2478 foreach (DictionaryEntry entry in defined_names) {
2479 MemberCore mc = (MemberCore)entry.Value;
2480 if (!mc.IsClsComplianceRequired ())
2483 string name = (string) entry.Key;
2484 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2486 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2487 object found = base_members [lcase];
2488 if (found == null) {
2489 found = this_members [lcase];
2490 if (found == null) {
2491 this_members.Add (lcase, mc);
2496 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2499 if (found is MemberInfo) {
2500 if (basename == ((MemberInfo) found).Name)
2502 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2504 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2506 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2512 /// Performs checks for an explicit interface implementation. First it
2513 /// checks whether the `interface_type' is a base inteface implementation.
2514 /// Then it checks whether `name' exists in the interface type.
2516 public virtual bool VerifyImplements (MemberBase mb)
2518 if (ifaces != null) {
2519 foreach (Type t in ifaces){
2520 if (t == mb.InterfaceType)
2525 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2526 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2527 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2531 public void Mark_HasEquals ()
2533 Methods.HasEquals = true;
2536 public void Mark_HasGetHashCode ()
2538 Methods.HasGetHashCode = true;
2545 string IMemberContainer.Name {
2551 Type IMemberContainer.Type {
2557 MemberCache IMemberContainer.MemberCache {
2559 return member_cache;
2563 bool IMemberContainer.IsInterface {
2565 return Kind == Kind.Interface;
2569 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2571 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2573 if (GenericType != null)
2574 return TypeManager.FindMembers (GenericType, mt, new_bf,
2577 return FindMembers (mt, new_bf, null, null);
2581 // Generates xml doc comments (if any), and if required,
2582 // handle warning report.
2584 internal override void GenerateDocComment (DeclSpace ds)
2586 DocUtil.GenerateTypeDocComment (this, ds);
2589 public override string DocCommentHeader {
2590 get { return "T:"; }
2593 public virtual MemberCache BaseCache {
2595 if (base_cache != null)
2597 if (TypeBuilder.BaseType != null)
2598 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2599 if (TypeBuilder.IsInterface)
2600 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2607 public abstract class ClassOrStruct : TypeContainer {
2608 ListDictionary declarative_security;
2610 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2611 MemberName name, Attributes attrs, Kind kind)
2612 : base (ns, parent, name, attrs, kind)
2616 protected override bool AddToContainer (MemberCore symbol, string name)
2618 if (name == MemberName.Name) {
2619 if (symbol is TypeParameter) {
2620 Report.Error (694, symbol.Location,
2621 "Type parameter `{0}' has same name as " +
2622 "containing type, or method", name);
2626 Report.SymbolRelatedToPreviousError (this);
2627 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2628 symbol.GetSignatureForError ());
2632 return base.AddToContainer (symbol, name);
2635 public override void VerifyMembers ()
2637 base.VerifyMembers ();
2639 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2640 foreach (Event e in events){
2641 if ((e.caching_flags & Flags.IsAssigned) == 0)
2642 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2647 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2649 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2650 if (declarative_security == null)
2651 declarative_security = new ListDictionary ();
2653 a.ExtractSecurityPermissionSet (declarative_security);
2657 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2658 HasExplicitLayout = true;
2661 base.ApplyAttributeBuilder (a, cb);
2665 /// Defines the default constructors
2667 protected void DefineDefaultConstructor (bool is_static)
2669 // The default instance constructor is public
2670 // If the class is abstract, the default constructor is protected
2671 // The default static constructor is private
2675 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2677 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2680 Constructor c = new Constructor (this, MemberName.Name, mods,
2681 Parameters.EmptyReadOnlyParameters,
2682 new GeneratedBaseInitializer (Location),
2686 c.Block = new ToplevelBlock (null, Location);
2689 void DefineFieldInitializers ()
2691 if (initialized_fields != null) {
2692 for (int i = 0; i < initialized_fields.Count; ++i) {
2693 FieldBase fb = (FieldBase)initialized_fields[i];
2694 fb.ResolveInitializer ();
2695 if (fb.HasDefaultInitializer && RootContext.Optimize) {
2696 // Field is re-initialized to its default value => removed
2697 initialized_fields.RemoveAt (i);
2703 if (initialized_static_fields != null) {
2704 bool has_complex_initializer = false;
2706 foreach (FieldBase fb in initialized_static_fields) {
2707 if (fb.ResolveInitializer () is Constant)
2710 has_complex_initializer = true;
2713 // Need special check to not optimize code like this
2714 // static int a = b = 5;
2715 // static int b = 0;
2716 if (!has_complex_initializer && RootContext.Optimize) {
2717 for (int i = 0; i < initialized_static_fields.Count; ++i) {
2718 FieldBase fb = (FieldBase)initialized_static_fields[i];
2719 if (fb.HasDefaultInitializer) {
2720 initialized_static_fields.RemoveAt (i);
2726 if (default_static_constructor == null && initialized_static_fields.Count > 0) {
2727 DefineDefaultConstructor (true);
2733 public override bool Define ()
2735 DefineFieldInitializers ();
2737 if (default_static_constructor != null)
2738 default_static_constructor.Define ();
2740 return base.Define ();
2743 public override void Emit ()
2747 if (declarative_security != null) {
2748 foreach (DictionaryEntry de in declarative_security) {
2749 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2754 protected override TypeAttributes TypeAttr {
2756 if (default_static_constructor == null)
2757 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2759 return base.TypeAttr;
2765 // TODO: should be sealed
2766 public class Class : ClassOrStruct {
2767 const int AllowedModifiers =
2770 Modifiers.PROTECTED |
2771 Modifiers.INTERNAL |
2773 Modifiers.ABSTRACT |
2778 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2780 : base (ns, parent, name, attrs, Kind.Class)
2782 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2783 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2785 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2786 Report.FeatureIsNotStandardized (Location, "static classes");
2790 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2792 if (a.Type == TypeManager.attribute_usage_type) {
2793 if (BaseType != TypeManager.attribute_type && !BaseType.IsSubclassOf (TypeManager.attribute_type) &&
2794 TypeBuilder.FullName != "System.Attribute") {
2795 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2799 if (a.Type == TypeManager.conditional_attribute_type &&
2800 !(BaseType == TypeManager.attribute_type || BaseType.IsSubclassOf (TypeManager.attribute_type))) {
2801 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2805 if (a.Type == TypeManager.comimport_attr_type &&
2806 !attributes.Contains (TypeManager.guid_attr_type)) {
2807 a.Error_MissingGuidAttribute ();
2811 if (AttributeTester.IsAttributeExcluded (a.Type))
2814 base.ApplyAttributeBuilder (a, cb);
2817 public override AttributeTargets AttributeTargets {
2819 return AttributeTargets.Class;
2823 protected override void DefineContainerMembers (MemberCoreArrayList list)
2829 base.DefineContainerMembers (list);
2833 foreach (MemberCore m in list) {
2834 if (m is Operator) {
2835 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2839 if (m is Destructor) {
2840 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2844 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2845 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
2850 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2854 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2857 if (m is Constructor) {
2858 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2862 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2865 base.DefineContainerMembers (list);
2868 public override TypeBuilder DefineType ()
2870 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2871 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2875 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2876 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2880 return base.DefineType ();
2883 protected override bool DoDefineMembers ()
2885 if (InstanceConstructors == null && !IsStatic)
2886 DefineDefaultConstructor (false);
2888 return base.DoDefineMembers ();
2891 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2893 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2895 if (base_class == null) {
2896 if (RootContext.StdLib)
2897 base_class = TypeManager.system_object_expr;
2898 else if (Name != "System.Object")
2899 base_class = TypeManager.system_object_expr;
2901 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2903 689, base_class.Location,
2904 "Cannot derive from `{0}' because it is a type parameter",
2905 base_class.GetSignatureForError ());
2909 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
2910 Report.Error (1521, base_class.Location, "Invalid base type");
2914 if (base_class.IsSealed){
2915 Report.SymbolRelatedToPreviousError (base_class.Type);
2916 if (base_class.Type.IsAbstract) {
2917 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2918 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2920 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2921 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2926 if (!base_class.CanInheritFrom ()){
2927 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2928 GetSignatureForError (), base_class.GetSignatureForError ());
2932 if (!base_class.AsAccessible (this, ModFlags)) {
2933 Report.SymbolRelatedToPreviousError (base_class.Type);
2934 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2935 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2940 if (base_class != TypeManager.system_object_expr) {
2941 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2942 GetSignatureForError (), base_class.GetSignatureForError ());
2946 if (ifaces != null) {
2947 foreach (TypeExpr t in ifaces)
2948 Report.SymbolRelatedToPreviousError (t.Type);
2949 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2956 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2957 /// Valid only for attribute classes.
2958 public bool IsExcluded ()
2960 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2961 return (caching_flags & Flags.Excluded) != 0;
2963 caching_flags &= ~Flags.Excluded_Undetected;
2965 if (OptAttributes == null)
2968 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2973 foreach (Attribute a in attrs) {
2974 string condition = a.GetConditionalAttributeValue ();
2975 if (RootContext.AllDefines.Contains (condition))
2979 caching_flags |= Flags.Excluded;
2985 return (ModFlags & Modifiers.STATIC) != 0;
2990 // FIXME: How do we deal with the user specifying a different
2993 protected override TypeAttributes TypeAttr {
2995 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2997 ta |= TypeAttributes.Abstract | TypeAttributes.Sealed;
3003 public sealed class Struct : ClassOrStruct {
3005 // Modifiers allowed in a struct declaration
3007 const int AllowedModifiers =
3010 Modifiers.PROTECTED |
3011 Modifiers.INTERNAL |
3015 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
3016 int mod, Attributes attrs)
3017 : base (ns, parent, name, attrs, Kind.Struct)
3021 if (parent.Parent == null)
3022 accmods = Modifiers.INTERNAL;
3024 accmods = Modifiers.PRIVATE;
3026 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3028 this.ModFlags |= Modifiers.SEALED;
3031 public override AttributeTargets AttributeTargets {
3033 return AttributeTargets.Struct;
3037 const TypeAttributes DefaultTypeAttributes =
3038 TypeAttributes.SequentialLayout |
3039 TypeAttributes.Sealed |
3040 TypeAttributes.BeforeFieldInit;
3043 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3045 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3047 // If we are compiling our runtime,
3048 // and we are defining ValueType, then our
3049 // base is `System.Object'.
3051 if (base_class == null) {
3052 if (!RootContext.StdLib && Name == "System.ValueType")
3053 base_class = TypeManager.system_object_expr;
3055 base_class = TypeManager.system_valuetype_expr;
3062 // FIXME: Allow the user to specify a different set of attributes
3063 // in some cases (Sealed for example is mandatory for a class,
3064 // but what SequentialLayout can be changed
3066 protected override TypeAttributes TypeAttr {
3068 return base.TypeAttr | DefaultTypeAttributes;
3072 public override void RegisterFieldForInitialization (FieldBase field)
3074 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3075 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3076 field.GetSignatureForError ());
3079 base.RegisterFieldForInitialization (field);
3087 public sealed class Interface : TypeContainer, IMemberContainer {
3090 /// Modifiers allowed in a class declaration
3092 public const int AllowedModifiers =
3095 Modifiers.PROTECTED |
3096 Modifiers.INTERNAL |
3100 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3102 : base (ns, parent, name, attrs, Kind.Interface)
3106 if (parent.Parent == null)
3107 accmods = Modifiers.INTERNAL;
3109 accmods = Modifiers.PRIVATE;
3111 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3114 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3116 if (a.Type == TypeManager.comimport_attr_type &&
3117 !attributes.Contains (TypeManager.guid_attr_type)) {
3118 a.Error_MissingGuidAttribute ();
3121 base.ApplyAttributeBuilder (a, cb);
3125 public override AttributeTargets AttributeTargets {
3127 return AttributeTargets.Interface;
3131 const TypeAttributes DefaultTypeAttributes =
3132 TypeAttributes.AutoLayout |
3133 TypeAttributes.Abstract |
3134 TypeAttributes.Interface;
3136 protected override TypeAttributes TypeAttr {
3138 return base.TypeAttr | DefaultTypeAttributes;
3142 protected override bool VerifyClsCompliance ()
3144 if (!base.VerifyClsCompliance ())
3147 if (ifaces != null) {
3148 foreach (Type t in ifaces) {
3149 if (AttributeTester.IsClsCompliant (t))
3152 Report.SymbolRelatedToPreviousError (t);
3153 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3154 GetSignatureForError (), TypeManager.CSharpName (t));
3162 public abstract class MethodCore : MemberBase {
3163 public readonly Parameters Parameters;
3164 protected ToplevelBlock block;
3167 // The method we're overriding if this is an override method.
3169 protected MethodInfo base_method = null;
3171 public MethodCore (DeclSpace parent, GenericMethod generic,
3172 Expression type, int mod, int allowed_mod, bool is_iface,
3173 MemberName name, Attributes attrs, Parameters parameters)
3174 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3177 Parameters = parameters;
3178 IsInterface = is_iface;
3182 // Returns the System.Type array for the parameters of this method
3184 public Type [] ParameterTypes {
3186 return Parameters.Types;
3190 public Parameters ParameterInfo
3197 public ToplevelBlock Block {
3207 public void SetYields ()
3209 ModFlags |= Modifiers.METHOD_YIELDS;
3212 protected override bool CheckBase ()
3214 if (!base.CheckBase ())
3217 // Check whether arguments were correct.
3218 if (!DoDefineParameters ())
3221 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3227 // Is null for System.Object while compiling corlib and base interfaces
3228 if (Parent.PartialContainer.BaseCache == null) {
3229 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3230 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3235 Type base_ret_type = null;
3236 base_method = FindOutBaseMethod (ref base_ret_type);
3238 // method is override
3239 if (base_method != null) {
3241 if (!CheckMethodAgainstBase ())
3244 if ((ModFlags & Modifiers.NEW) == 0) {
3245 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_ret_type))) {
3246 Report.SymbolRelatedToPreviousError (base_method);
3247 if (this is PropertyBase) {
3248 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3249 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3252 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3253 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3258 if (base_method.IsAbstract && !IsInterface) {
3259 Report.SymbolRelatedToPreviousError (base_method);
3260 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3261 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3266 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3267 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3271 if (Name == "Equals" && Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type)
3272 Parent.PartialContainer.Mark_HasEquals ();
3273 else if (Name == "GetHashCode" && Parameters.Empty)
3274 Parent.PartialContainer.Mark_HasGetHashCode ();
3276 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3277 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3279 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3280 Report.SymbolRelatedToPreviousError (base_method);
3281 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3282 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3289 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !(this is Property));
3290 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3291 if (conflict_symbol != null) {
3292 Report.SymbolRelatedToPreviousError (conflict_symbol);
3293 if (this is PropertyBase)
3294 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3296 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3298 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3302 if (conflict_symbol == null) {
3303 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3304 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3309 if ((ModFlags & Modifiers.NEW) == 0) {
3310 if (this is Method && conflict_symbol is MethodBase)
3313 Report.SymbolRelatedToPreviousError (conflict_symbol);
3314 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3315 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3322 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3323 // that have been defined.
3325 // `name' is the user visible name for reporting errors (this is used to
3326 // provide the right name regarding method names and properties)
3328 bool CheckMethodAgainstBase ()
3332 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3333 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3334 Report.Error (506, Location,
3335 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3336 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3340 // Now we check that the overriden method is not final
3342 if (base_method.IsFinal) {
3343 Report.SymbolRelatedToPreviousError (base_method);
3344 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3345 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3349 // Check that the permissions are not being changed
3351 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3352 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3354 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3355 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3360 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3361 ModFlags |= Modifiers.NEW;
3362 Report.SymbolRelatedToPreviousError (base_method);
3363 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3364 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",
3365 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3367 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3368 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3375 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3377 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3379 // when overriding protected internal, the method can be declared
3380 // protected internal only within the same assembly
3383 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3384 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3386 // assemblies differ - report an error
3390 } else if (thisp != base_classp) {
3392 // same assembly, but other attributes differ - report an error
3397 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3399 // if it's not "protected internal", it must be "protected"
3403 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3405 // protected within the same assembly - an error
3408 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3409 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3411 // protected ok, but other attributes differ - report an error
3417 return (thisp == base_classp);
3421 public bool CheckAbstractAndExtern (bool has_block)
3423 if (Parent.PartialContainer.Kind == Kind.Interface)
3427 if ((ModFlags & Modifiers.EXTERN) != 0) {
3428 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3429 GetSignatureForError ());
3433 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3434 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3435 GetSignatureForError ());
3439 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3440 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3441 GetSignatureForError ());
3449 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3451 Report.SymbolRelatedToPreviousError (base_method);
3452 string base_name = TypeManager.GetFullNameSignature (base_method);
3453 string this_name = GetSignatureForError ();
3454 if (suffix != null) {
3455 base_name += suffix;
3456 this_name += suffix;
3459 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3460 this_name, Modifiers.GetDescription (ma), base_name);
3463 protected static string Error722 {
3465 return "`{0}': static types cannot be used as return types";
3470 /// For custom member duplication search in a container
3472 protected abstract bool CheckForDuplications ();
3475 /// Gets base method and its return type
3477 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3479 protected bool DoDefineParameters ()
3481 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3483 // Check if arguments were correct
3484 if (!Parameters.Resolve (rc))
3487 return CheckParameters (ParameterTypes);
3490 bool CheckParameters (Type [] parameters)
3494 foreach (Type partype in parameters){
3495 if (partype == TypeManager.void_type) {
3496 // TODO: location is wrong
3497 Expression.Error_VoidInvalidInTheContext (Location);
3501 if (partype.IsPointer){
3502 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3506 if (ds.AsAccessible (partype, ModFlags))
3509 Report.SymbolRelatedToPreviousError (partype);
3510 if (this is Indexer)
3511 Report.Error (55, Location,
3512 "Inconsistent accessibility: parameter type `" +
3513 TypeManager.CSharpName (partype) + "' is less " +
3514 "accessible than indexer `" + GetSignatureForError () + "'");
3515 else if (this is Operator)
3516 Report.Error (57, Location,
3517 "Inconsistent accessibility: parameter type `" +
3518 TypeManager.CSharpName (partype) + "' is less " +
3519 "accessible than operator `" + GetSignatureForError () + "'");
3521 Report.Error (51, Location,
3522 "Inconsistent accessibility: parameter type `" +
3523 TypeManager.CSharpName (partype) + "' is less " +
3524 "accessible than method `" + GetSignatureForError () + "'");
3531 protected override bool VerifyClsCompliance ()
3533 if (!base.VerifyClsCompliance ()) {
3534 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3535 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3540 if (Parameters.HasArglist) {
3541 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3544 if (!AttributeTester.IsClsCompliant (MemberType)) {
3545 if (this is PropertyBase)
3546 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3547 GetSignatureForError ());
3549 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3550 GetSignatureForError ());
3553 Parameters.VerifyClsCompliance ();
3558 protected bool IsDuplicateImplementation (MethodCore method)
3560 if (method == this || !(method.MemberName.Equals (MemberName)))
3563 Type[] param_types = method.ParameterTypes;
3564 // This never happen. Rewrite this as Equal
3565 if (param_types == null && ParameterTypes == null)
3567 if (param_types == null || ParameterTypes == null)
3570 if (param_types.Length != ParameterTypes.Length)
3573 if (method.Parameters.HasArglist != Parameters.HasArglist)
3578 for (int i = 0; i < param_types.Length; i++) {
3579 if (param_types [i] != ParameterTypes [i])
3583 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3586 // TODO: make operator compatible with MethodCore to avoid this
3587 if (this is Operator && method is Operator) {
3588 if (MemberType != method.MemberType)
3594 // Try to report 663: method only differs on out/ref
3596 Parameters info = ParameterInfo;
3597 Parameters other_info = method.ParameterInfo;
3598 for (int i = 0; i < info.Count; i++){
3600 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3601 Report.SymbolRelatedToPreviousError (method);
3602 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3603 GetSignatureForError ());
3606 Console.WriteLine ("Method is: {0} {1}", method.Location, method);
3607 Console.WriteLine ("this is: {0} {1}", Location, this);
3611 Report.SymbolRelatedToPreviousError (method);
3612 if (this is Operator && method is Operator)
3613 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3615 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3623 public override bool IsUsed {
3624 get { return IsExplicitImpl || base.IsUsed; }
3628 // Returns a string that represents the signature for this
3629 // member which should be used in XML documentation.
3631 public override string GetDocCommentName (DeclSpace ds)
3633 return DocUtil.GetMethodDocCommentName (this, ds);
3637 // Raised (and passed an XmlElement that contains the comment)
3638 // when GenerateDocComment is writing documentation expectedly.
3640 // FIXME: with a few effort, it could be done with XmlReader,
3641 // that means removal of DOM use.
3643 internal override void OnGenerateDocComment (XmlElement el)
3645 DocUtil.OnMethodGenerateDocComment (this, el);
3649 // Represents header string for documentation comment.
3651 public override string DocCommentHeader {
3652 get { return "M:"; }
3657 public abstract class MethodOrOperator : MethodCore, IMethodData
3659 public MethodBuilder MethodBuilder;
3660 ReturnParameter return_attributes;
3661 ListDictionary declarative_security;
3662 protected MethodData MethodData;
3664 static string[] attribute_targets = new string [] { "method", "return" };
3666 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, Expression type, int mod,
3667 int allowed_mod, bool is_interface, MemberName name,
3668 Attributes attrs, Parameters parameters)
3669 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3674 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3676 if (a.Target == AttributeTargets.ReturnValue) {
3677 if (return_attributes == null)
3678 return_attributes = new ReturnParameter (MethodBuilder, Location);
3680 return_attributes.ApplyAttributeBuilder (a, cb);
3684 if (a.Type == TypeManager.methodimpl_attr_type &&
3685 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3686 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3689 if (a.Type == TypeManager.dllimport_type) {
3690 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3691 if ((ModFlags & extern_static) != extern_static) {
3692 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3698 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3699 if (declarative_security == null)
3700 declarative_security = new ListDictionary ();
3701 a.ExtractSecurityPermissionSet (declarative_security);
3705 MethodBuilder.SetCustomAttribute (cb);
3708 public override AttributeTargets AttributeTargets {
3710 return AttributeTargets.Method;
3714 public EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3716 EmitContext ec = new EmitContext (this,
3717 tc, this.ds, Location, ig, MemberType, ModFlags, false);
3719 Iterator iterator = tc as Iterator;
3720 if (iterator != null)
3721 ec.CurrentAnonymousMethod = iterator.Host;
3726 public override bool Define ()
3728 if (!DoDefineBase ())
3731 MethodBuilder mb = null;
3732 if (GenericMethod != null) {
3733 string method_name = MemberName.Name;
3735 if (IsExplicitImpl) {
3736 method_name = TypeManager.CSharpName (InterfaceType) +
3740 mb = Parent.TypeBuilder.DefineMethod (method_name, flags);
3742 if (!GenericMethod.Define (mb))
3749 if (!CheckAbstractAndExtern (block != null))
3755 MethodData = new MethodData (this, ModFlags, flags, this, mb, GenericMethod, base_method);
3757 if (!MethodData.Define (Parent.PartialContainer))
3760 MethodBuilder = MethodData.MethodBuilder;
3762 if (MemberType.IsAbstract && MemberType.IsSealed) {
3763 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3770 public override void Emit ()
3772 if (OptAttributes != null)
3773 OptAttributes.Emit ();
3775 if (declarative_security != null) {
3776 foreach (DictionaryEntry de in declarative_security) {
3777 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3784 protected void Error_ConditionalAttributeIsNotValid ()
3786 Report.Error (577, Location,
3787 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3788 GetSignatureForError ());
3791 public override bool MarkForDuplicationCheck ()
3793 caching_flags |= Flags.TestMethodDuplication;
3797 public override string[] ValidAttributeTargets {
3799 return attribute_targets;
3803 #region IMethodData Members
3805 public CallingConventions CallingConventions {
3807 CallingConventions cc = Parameters.CallingConvention;
3808 if (Parameters.HasArglist)
3809 block.HasVarargs = true;
3812 if ((ModFlags & Modifiers.STATIC) == 0)
3813 cc |= CallingConventions.HasThis;
3815 // FIXME: How is `ExplicitThis' used in C#?
3821 public Type ReturnType {
3827 public MemberName MethodName {
3833 public new Location Location {
3835 return base.Location;
3839 protected override bool CheckBase() {
3840 if (!base.CheckBase ())
3843 // TODO: Destructor should derive from MethodCore
3844 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3845 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3846 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3854 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3856 public bool IsExcluded () {
3857 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3858 return (caching_flags & Flags.Excluded) != 0;
3860 caching_flags &= ~Flags.Excluded_Undetected;
3862 if (base_method == null) {
3863 if (OptAttributes == null)
3866 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3871 foreach (Attribute a in attrs) {
3872 string condition = a.GetConditionalAttributeValue ();
3873 if (condition == null)
3876 if (RootContext.AllDefines.Contains (condition))
3880 caching_flags |= Flags.Excluded;
3884 IMethodData md = TypeManager.GetMethod (base_method);
3886 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
3887 caching_flags |= Flags.Excluded;
3893 if (md.IsExcluded ()) {
3894 caching_flags |= Flags.Excluded;
3900 GenericMethod IMethodData.GenericMethod {
3902 return GenericMethod;
3910 public class SourceMethod : ISourceMethod
3915 protected SourceMethod (DeclSpace parent, MethodBase builder,
3916 ISourceFile file, Location start, Location end)
3918 this.parent = parent;
3919 this.builder = builder;
3921 CodeGen.SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
3924 public string Name {
3925 get { return builder.Name; }
3928 public int NamespaceID {
3929 get { return parent.NamespaceEntry.SymbolFileID; }
3934 if (builder is MethodBuilder)
3935 return ((MethodBuilder) builder).GetToken ().Token;
3936 else if (builder is ConstructorBuilder)
3937 return ((ConstructorBuilder) builder).GetToken ().Token;
3939 throw new NotSupportedException ();
3943 public void CloseMethod ()
3945 if (CodeGen.SymbolWriter != null)
3946 CodeGen.SymbolWriter.CloseMethod ();
3949 public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
3951 if (CodeGen.SymbolWriter == null)
3956 Location start_loc = block.StartLocation;
3957 if (start_loc.IsNull)
3960 Location end_loc = block.EndLocation;
3964 ISourceFile file = start_loc.SourceFile;
3968 return new SourceMethod (
3969 parent, builder, file, start_loc, end_loc);
3973 public class Method : MethodOrOperator, IIteratorContainer {
3976 /// Modifiers allowed in a class declaration
3978 const int AllowedModifiers =
3981 Modifiers.PROTECTED |
3982 Modifiers.INTERNAL |
3987 Modifiers.OVERRIDE |
3988 Modifiers.ABSTRACT |
3990 Modifiers.METHOD_YIELDS |
3993 const int AllowedInterfaceModifiers =
3994 Modifiers.NEW | Modifiers.UNSAFE;
3997 // return_type can be "null" for VOID values.
3999 public Method (DeclSpace parent, GenericMethod generic,
4000 Expression return_type, int mod, bool is_iface,
4001 MemberName name, Parameters parameters, Attributes attrs)
4002 : base (parent, generic, return_type, mod,
4003 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4004 is_iface, name, attrs, parameters)
4008 public override string GetSignatureForError()
4010 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4013 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4015 Report.Error (17, location,
4016 "Program `{0}' has more than one entry point defined: `{1}'",
4017 CodeGen.FileName, TypeManager.CSharpSignature(b));
4020 bool IsEntryPoint (Parameters pinfo)
4022 if (ReturnType != TypeManager.void_type &&
4023 ReturnType != TypeManager.int32_type)
4026 if (pinfo.Count == 0)
4029 if (pinfo.Count > 1)
4032 Type t = pinfo.ParameterType (0);
4034 (t.GetArrayRank () == 1) &&
4035 (TypeManager.GetElementType (t) == TypeManager.string_type) &&
4036 (pinfo.ParameterModifier (0) == Parameter.Modifier.NONE))
4042 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4044 if (a.Type == TypeManager.conditional_attribute_type) {
4045 if (IsExplicitImpl) {
4046 Error_ConditionalAttributeIsNotValid ();
4050 if (ReturnType != TypeManager.void_type) {
4051 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4055 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4056 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4061 Report.Error (582, Location, "Conditional not valid on interface members");
4065 if (MethodData.implementing != null) {
4066 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4067 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4071 for (int i = 0; i < ParameterInfo.Count; ++i) {
4072 if ((ParameterInfo.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4073 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4079 base.ApplyAttributeBuilder (a, cb);
4082 protected override bool CheckForDuplications ()
4084 ArrayList ar = Parent.PartialContainer.Methods;
4086 int arLen = ar.Count;
4088 for (int i = 0; i < arLen; i++) {
4089 Method m = (Method) ar [i];
4090 if (IsDuplicateImplementation (m))
4095 ar = Parent.PartialContainer.Properties;
4097 for (int i = 0; i < ar.Count; ++i) {
4098 PropertyBase pb = (PropertyBase) ar [i];
4099 if (pb.AreAccessorsDuplicateImplementation (this))
4104 ar = Parent.PartialContainer.Indexers;
4106 for (int i = 0; i < ar.Count; ++i) {
4107 PropertyBase pb = (PropertyBase) ar [i];
4108 if (pb.AreAccessorsDuplicateImplementation (this))
4113 ar = Parent.PartialContainer.Events;
4115 for (int i = 0; i < ar.Count; ++i) {
4116 Event ev = (Event) ar [i];
4117 if (ev.AreAccessorsDuplicateImplementation (this))
4128 public override bool Define ()
4130 if (!base.Define ())
4133 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4134 Error1599 (Location, ReturnType);
4138 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4139 Name == "Finalize" && !(this is Destructor)) {
4140 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4144 // Setup iterator if we are one
4146 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4147 Iterator iterator = new Iterator (
4148 this, Parent, GenericMethod, ModFlags);
4150 if (!iterator.DefineIterator ())
4155 // This is used to track the Entry Point,
4157 if (RootContext.NeedsEntryPoint && ((ModFlags & Modifiers.STATIC) != 0) &&
4159 (RootContext.MainClass == null ||
4160 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4161 if (IsEntryPoint (ParameterInfo)) {
4163 if (RootContext.EntryPoint == null) {
4164 if (Parent.IsGeneric || MemberName.IsGeneric) {
4165 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4166 GetSignatureForError ());
4168 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4169 md.SetMemberIsUsed ();
4171 RootContext.EntryPoint = MethodBuilder;
4172 RootContext.EntryPointLocation = Location;
4175 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4176 Error_DuplicateEntryPoint (MethodBuilder, Location);
4179 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4180 GetSignatureForError ());
4190 public override void Emit ()
4192 MethodData.Emit (Parent);
4199 public static void Error1599 (Location loc, Type t)
4201 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4204 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4206 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4207 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4212 if (mi.IsSpecialName)
4215 base_ret_type = mi.ReturnType;
4219 protected override bool VerifyClsCompliance ()
4221 if (!base.VerifyClsCompliance ())
4224 if (ParameterInfo.Count > 0) {
4225 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4227 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4234 public abstract class ConstructorInitializer {
4235 ArrayList argument_list;
4236 protected ConstructorInfo base_constructor;
4239 public ConstructorInitializer (ArrayList argument_list, Location loc)
4241 this.argument_list = argument_list;
4245 public ArrayList Arguments {
4247 return argument_list;
4251 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4253 Expression base_constructor_group;
4257 ec.CurrentBlock = block;
4259 if (argument_list != null){
4260 foreach (Argument a in argument_list){
4261 if (!a.Resolve (ec, loc))
4265 ec.CurrentBlock = null;
4267 if (this is ConstructorBaseInitializer) {
4268 if (ec.ContainerType.BaseType == null)
4271 t = ec.ContainerType.BaseType;
4272 if (ec.ContainerType.IsValueType) {
4273 Report.Error (522, loc,
4274 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4278 t = ec.ContainerType;
4280 base_constructor_group = Expression.MemberLookup (
4281 ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
4282 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4285 if (base_constructor_group == null){
4287 base_constructor_group = Expression.MemberLookup (
4288 t, null, t, ".ctor", MemberTypes.Constructor,
4289 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4293 int errors = Report.Errors;
4294 if (base_constructor_group != null)
4295 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4296 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4299 if (base_constructor == null) {
4300 if (errors == Report.Errors)
4301 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4302 argument_list == null ? 0 : argument_list.Count);
4307 Report.SymbolRelatedToPreviousError (base_constructor);
4308 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4309 base_constructor = null;
4313 if (base_constructor == caller_builder){
4314 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4321 public virtual void Emit (EmitContext ec)
4323 if (base_constructor != null){
4324 ec.Mark (loc, false);
4326 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4328 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4333 public class ConstructorBaseInitializer : ConstructorInitializer {
4334 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4335 base (argument_list, l)
4340 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4341 public GeneratedBaseInitializer (Location loc):
4347 public class ConstructorThisInitializer : ConstructorInitializer {
4348 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4349 base (argument_list, l)
4354 public class Constructor : MethodCore, IMethodData {
4355 public ConstructorBuilder ConstructorBuilder;
4356 public ConstructorInitializer Initializer;
4357 ListDictionary declarative_security;
4360 // Modifiers allowed for a constructor.
4362 public const int AllowedModifiers =
4364 Modifiers.PROTECTED |
4365 Modifiers.INTERNAL |
4371 static string[] attribute_targets = new string [] { "method" };
4373 bool has_compliant_args = false;
4375 // The spec claims that static is not permitted, but
4376 // my very own code has static constructors.
4378 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4379 ConstructorInitializer init, Location loc)
4380 : base (parent, null, null, mod, AllowedModifiers, false,
4381 new MemberName (name, loc), null, args)
4386 public bool HasCompliantArgs {
4387 get { return has_compliant_args; }
4390 public override AttributeTargets AttributeTargets {
4391 get { return AttributeTargets.Constructor; }
4396 // Returns true if this is a default constructor
4398 public bool IsDefault ()
4400 if ((ModFlags & Modifiers.STATIC) != 0)
4401 return Parameters.Empty;
4403 return Parameters.Empty &&
4404 (Initializer is ConstructorBaseInitializer) &&
4405 (Initializer.Arguments == null);
4408 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4410 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4411 if (declarative_security == null) {
4412 declarative_security = new ListDictionary ();
4414 a.ExtractSecurityPermissionSet (declarative_security);
4418 if (a.Type == TypeManager.methodimpl_attr_type &&
4419 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4420 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4423 ConstructorBuilder.SetCustomAttribute (cb);
4426 protected override bool CheckForDuplications ()
4428 ArrayList ar = Parent.PartialContainer.InstanceConstructors;
4430 int arLen = ar.Count;
4432 for (int i = 0; i < arLen; i++) {
4433 Constructor m = (Constructor) ar [i];
4434 if (IsDuplicateImplementation (m))
4441 protected override bool CheckBase ()
4443 if ((ModFlags & Modifiers.STATIC) != 0) {
4444 if (!Parameters.Empty) {
4445 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4446 GetSignatureForError ());
4450 // the rest can be ignored
4454 // Check whether arguments were correct.
4455 if (!DoDefineParameters ())
4458 if (!CheckForDuplications ())
4461 if (Parent.PartialContainer.Kind == Kind.Struct) {
4462 if (ParameterTypes.Length == 0) {
4463 Report.Error (568, Location,
4464 "Structs cannot contain explicit parameterless constructors");
4468 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4469 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4474 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4475 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4482 // Creates the ConstructorBuilder
4484 public override bool Define ()
4486 if (ConstructorBuilder != null)
4489 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4490 MethodAttributes.SpecialName);
4492 if ((ModFlags & Modifiers.STATIC) != 0){
4493 ca |= MethodAttributes.Static | MethodAttributes.Private;
4495 ca |= MethodAttributes.HideBySig;
4497 if ((ModFlags & Modifiers.PUBLIC) != 0)
4498 ca |= MethodAttributes.Public;
4499 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4500 if ((ModFlags & Modifiers.INTERNAL) != 0)
4501 ca |= MethodAttributes.FamORAssem;
4503 ca |= MethodAttributes.Family;
4504 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4505 ca |= MethodAttributes.Assembly;
4507 ca |= MethodAttributes.Private;
4510 if (!CheckAbstractAndExtern (block != null))
4513 // Check if arguments were correct.
4517 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4518 ca, CallingConventions,
4521 if ((ModFlags & Modifiers.UNSAFE) != 0)
4522 ConstructorBuilder.InitLocals = false;
4524 if (Parent.PartialContainer.IsComImport) {
4525 if (!IsDefault ()) {
4526 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4527 Parent.GetSignatureForError ());
4530 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4533 TypeManager.AddMethod (ConstructorBuilder, this);
4541 public override void Emit ()
4543 if (OptAttributes != null)
4544 OptAttributes.Emit ();
4546 EmitContext ec = CreateEmitContext (null, null);
4548 if (block != null) {
4549 // If this is a non-static `struct' constructor and doesn't have any
4550 // initializer, it must initialize all of the struct's fields.
4551 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4552 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4553 block.AddThisVariable (Parent, Location);
4555 if (!block.ResolveMeta (ec, ParameterInfo))
4559 if ((ModFlags & Modifiers.STATIC) == 0){
4560 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4561 Initializer = new GeneratedBaseInitializer (Location);
4565 // Spec mandates that Initializers will not have
4569 if ((Initializer != null) &&
4570 !Initializer.Resolve (ConstructorBuilder, block, ec))
4572 ec.IsStatic = false;
4575 Parameters.ApplyAttributes (ConstructorBuilder);
4577 SourceMethod source = SourceMethod.Create (
4578 Parent, ConstructorBuilder, block);
4581 // Classes can have base initializers and instance field initializers.
4583 if (Parent.PartialContainer.Kind == Kind.Class){
4584 if ((ModFlags & Modifiers.STATIC) == 0){
4587 // If we use a "this (...)" constructor initializer, then
4588 // do not emit field initializers, they are initialized in the other constructor
4590 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4591 Parent.PartialContainer.EmitFieldInitializers (ec);
4594 if (Initializer != null) {
4595 Initializer.Emit (ec);
4598 if ((ModFlags & Modifiers.STATIC) != 0)
4599 Parent.PartialContainer.EmitFieldInitializers (ec);
4601 ec.EmitTopBlock (this, block);
4604 source.CloseMethod ();
4608 if (declarative_security != null) {
4609 foreach (DictionaryEntry de in declarative_security) {
4610 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4617 // Is never override
4618 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4623 public override string GetSignatureForError()
4625 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4628 public override string[] ValidAttributeTargets {
4630 return attribute_targets;
4634 protected override bool VerifyClsCompliance ()
4636 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4640 if (ParameterInfo.Count > 0) {
4641 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4643 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4645 if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4646 foreach (Type param in ParameterTypes) {
4647 if (param.IsArray) {
4653 has_compliant_args = true;
4657 #region IMethodData Members
4659 public System.Reflection.CallingConventions CallingConventions {
4661 CallingConventions cc = Parameters.CallingConvention;
4663 if (Parent.PartialContainer.Kind == Kind.Class)
4664 if ((ModFlags & Modifiers.STATIC) == 0)
4665 cc |= CallingConventions.HasThis;
4667 // FIXME: How is `ExplicitThis' used in C#?
4673 public new Location Location {
4675 return base.Location;
4679 public MemberName MethodName {
4685 public Type ReturnType {
4691 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4693 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4694 return new EmitContext (this, Parent, Location, ig_, null, ModFlags, true);
4697 public bool IsExcluded()
4702 GenericMethod IMethodData.GenericMethod {
4712 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4714 public interface IMethodData
4716 CallingConventions CallingConventions { get; }
4717 Location Location { get; }
4718 MemberName MethodName { get; }
4719 Type ReturnType { get; }
4720 GenericMethod GenericMethod { get; }
4721 Parameters ParameterInfo { get; }
4723 Attributes OptAttributes { get; }
4724 ToplevelBlock Block { get; set; }
4726 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4727 ObsoleteAttribute GetObsoleteAttribute ();
4728 string GetSignatureForError ();
4730 bool IsClsComplianceRequired ();
4731 void SetMemberIsUsed ();
4735 // Encapsulates most of the Method's state
4737 public class MethodData {
4739 readonly IMethodData method;
4741 public readonly GenericMethod GenericMethod;
4744 // Are we implementing an interface ?
4746 public MethodInfo implementing;
4751 protected MemberBase member;
4752 protected int modifiers;
4753 protected MethodAttributes flags;
4754 protected Type declaring_type;
4755 protected MethodInfo parent_method;
4757 MethodBuilder builder = null;
4758 public MethodBuilder MethodBuilder {
4764 public Type DeclaringType {
4766 return declaring_type;
4770 public MethodData (MemberBase member,
4771 int modifiers, MethodAttributes flags, IMethodData method)
4773 this.member = member;
4774 this.modifiers = modifiers;
4777 this.method = method;
4780 public MethodData (MemberBase member,
4781 int modifiers, MethodAttributes flags,
4782 IMethodData method, MethodBuilder builder,
4783 GenericMethod generic, MethodInfo parent_method)
4784 : this (member, modifiers, flags, method)
4786 this.builder = builder;
4787 this.GenericMethod = generic;
4788 this.parent_method = parent_method;
4791 public bool Define (DeclSpace parent)
4793 string name = method.MethodName.Basename;
4794 string method_name = method.MethodName.FullName;
4796 TypeContainer container = parent.PartialContainer;
4798 PendingImplementation pending = container.PendingImplementations;
4799 if (pending != null){
4800 if (member is Indexer) // TODO: test it, but it should work without this IF
4801 implementing = pending.IsInterfaceIndexer (
4802 member.InterfaceType, method.ReturnType, method.ParameterInfo);
4804 implementing = pending.IsInterfaceMethod (
4805 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
4807 if (member.InterfaceType != null){
4808 if (implementing == null){
4809 if (member is PropertyBase) {
4810 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4811 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4812 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4815 Report.Error (539, method.Location,
4816 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4817 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4821 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4822 Report.SymbolRelatedToPreviousError (implementing);
4823 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4824 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4828 method_name = TypeManager.GetFullName (member.InterfaceType) +
4831 if (implementing != null) {
4832 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4833 if (prop_method == null) {
4834 if (implementing.IsSpecialName) {
4835 Report.SymbolRelatedToPreviousError (implementing);
4836 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4837 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4838 implementing.Name.StartsWith ("get_") ? "get" : "set");
4841 } else if (implementing.DeclaringType.IsInterface) {
4842 if (!implementing.IsSpecialName) {
4843 Report.SymbolRelatedToPreviousError (implementing);
4844 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4845 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4848 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4849 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4850 Report.SymbolRelatedToPreviousError (implementing);
4851 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4852 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4861 // For implicit implementations, make sure we are public, for
4862 // explicit implementations, make sure we are private.
4864 if (implementing != null){
4866 // Setting null inside this block will trigger a more
4867 // verbose error reporting for missing interface implementations
4869 // The "candidate" function has been flagged already
4870 // but it wont get cleared
4872 if (member.IsExplicitImpl){
4873 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4874 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4875 implementing = null;
4877 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
4878 Report.SymbolRelatedToPreviousError (implementing);
4879 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
4880 method.GetSignatureForError ());
4883 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4884 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4886 // If this is an interface method implementation,
4887 // check for public accessibility
4889 implementing = null;
4890 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4891 // We may never be private.
4892 implementing = null;
4893 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4895 // We may be protected if we're overriding something.
4897 implementing = null;
4902 // Static is not allowed
4904 if ((modifiers & Modifiers.STATIC) != 0){
4905 implementing = null;
4910 // If implementing is still valid, set flags
4912 if (implementing != null){
4914 // When implementing interface methods, set NewSlot
4915 // unless, we are overwriting a method.
4917 if (implementing.DeclaringType.IsInterface){
4918 if ((modifiers & Modifiers.OVERRIDE) == 0)
4919 flags |= MethodAttributes.NewSlot;
4922 MethodAttributes.Virtual |
4923 MethodAttributes.HideBySig;
4925 // Set Final unless we're virtual, abstract or already overriding a method.
4926 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4927 flags |= MethodAttributes.Final;
4930 EmitContext ec = method.CreateEmitContext (container, null);
4932 DefineMethodBuilder (container, method_name, method.ParameterInfo.Types);
4934 if (builder == null)
4937 if (container.CurrentType != null)
4938 declaring_type = container.CurrentType;
4940 declaring_type = container.TypeBuilder;
4942 if ((modifiers & Modifiers.UNSAFE) != 0)
4943 builder.InitLocals = false;
4945 if (implementing != null){
4947 // clear the pending implemntation flag
4949 if (member is Indexer) {
4950 pending.ImplementIndexer (
4951 member.InterfaceType, builder, method.ReturnType,
4952 method.ParameterInfo, member.IsExplicitImpl);
4954 pending.ImplementMethod (
4955 member.InterfaceType, name, method.ReturnType,
4956 method.ParameterInfo, member.IsExplicitImpl);
4958 if (member.IsExplicitImpl)
4959 container.TypeBuilder.DefineMethodOverride (
4960 builder, implementing);
4964 TypeManager.AddMethod (builder, method);
4966 if (GenericMethod != null) {
4967 bool is_override = member.IsExplicitImpl |
4968 ((modifiers & Modifiers.OVERRIDE) != 0);
4970 if (implementing != null)
4971 parent_method = implementing;
4973 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
4982 /// Create the MethodBuilder for the method
4984 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
4986 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4988 if ((modifiers & extern_static) == extern_static) {
4990 if (method.OptAttributes != null) {
4991 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type);
4992 if (dllimport_attribute != null) {
4993 flags |= MethodAttributes.PinvokeImpl;
4994 builder = dllimport_attribute.DefinePInvokeMethod (
4995 container.TypeBuilder, method_name, flags,
4996 method.ReturnType, ParameterTypes);
5002 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5003 // We are more strict than Microsoft and report CS0626 like error
5004 if (method.OptAttributes == null ||
5005 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type)) {
5006 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",
5007 method.GetSignatureForError ());
5012 if (builder == null) {
5013 builder = container.TypeBuilder.DefineMethod (
5014 method_name, flags, method.CallingConventions,
5015 method.ReturnType, ParameterTypes);
5019 builder.SetGenericMethodSignature (
5020 flags, method.CallingConventions,
5021 method.ReturnType, ParameterTypes);
5028 public void Emit (DeclSpace parent)
5031 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5032 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5034 ec = method.CreateEmitContext (parent, null);
5036 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5038 if (GenericMethod != null)
5039 GenericMethod.EmitAttributes ();
5041 ToplevelBlock block = method.Block;
5043 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5046 // Handle destructors specially
5048 // FIXME: This code generates buggy code
5050 if (member is Destructor)
5051 EmitDestructor (ec, block);
5053 ec.EmitTopBlock (method, block);
5056 source.CloseMethod ();
5059 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5061 ILGenerator ig = ec.ig;
5063 Label finish = ig.DefineLabel ();
5065 block.SetDestructor ();
5067 ig.BeginExceptionBlock ();
5068 ec.ReturnLabel = finish;
5069 ec.HasReturnLabel = true;
5070 ec.EmitTopBlock (method, block);
5072 // ig.MarkLabel (finish);
5073 ig.BeginFinallyBlock ();
5075 if (ec.ContainerType.BaseType != null) {
5076 Expression member_lookup = Expression.MemberLookup (
5077 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5078 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5080 if (member_lookup != null){
5081 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5083 ig.Emit (OpCodes.Ldarg_0);
5084 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5088 ig.EndExceptionBlock ();
5089 //ig.MarkLabel (ec.ReturnLabel);
5090 ig.Emit (OpCodes.Ret);
5094 // TODO: Should derive from MethodCore
5095 public class Destructor : Method {
5097 static string[] attribute_targets = new string [] { "method" };
5099 public Destructor (DeclSpace parent, Expression return_type, int mod,
5100 string name, Parameters parameters, Attributes attrs,
5102 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5106 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5108 if (a.Type == TypeManager.conditional_attribute_type) {
5109 Error_ConditionalAttributeIsNotValid ();
5113 base.ApplyAttributeBuilder (a, cb);
5116 public override string GetSignatureForError ()
5118 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5121 public override string[] ValidAttributeTargets {
5123 return attribute_targets;
5128 abstract public class MemberBase : MemberCore {
5129 public Expression Type;
5131 public MethodAttributes flags;
5132 public readonly DeclSpace ds;
5133 public readonly GenericMethod GenericMethod;
5135 protected readonly int explicit_mod_flags;
5138 // The "short" name of this property / indexer / event. This is the
5139 // name without the explicit interface.
5141 public string ShortName {
5142 get { return MemberName.Name; }
5143 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
5147 // The type of this property / indexer / event
5149 protected Type member_type;
5150 public Type MemberType {
5152 if (member_type == null && Type != null) {
5153 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5154 Type = Type.ResolveAsTypeTerminal (rc, false);
5156 member_type = Type.Type;
5164 // Whether this is an interface member.
5166 public bool IsInterface;
5169 // If true, this is an explicit interface implementation
5171 public bool IsExplicitImpl;
5174 // The interface type we are explicitly implementing
5176 public Type InterfaceType = null;
5179 // The constructor is only exposed to our children
5181 protected MemberBase (DeclSpace parent, GenericMethod generic,
5182 Expression type, int mod, int allowed_mod, int def_mod,
5183 MemberName name, Attributes attrs)
5184 : base (parent, name, attrs)
5186 this.ds = generic != null ? generic : (DeclSpace) parent;
5187 explicit_mod_flags = mod;
5189 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5190 IsExplicitImpl = (MemberName.Left != null);
5191 GenericMethod = generic;
5192 if (GenericMethod != null)
5193 GenericMethod.ModFlags = ModFlags;
5196 protected virtual bool CheckBase ()
5198 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.PartialContainer.Kind == Kind.Struct) {
5199 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5203 if ((RootContext.WarningLevel >= 4) &&
5204 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5205 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5206 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5207 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5212 protected virtual bool DoDefineBase ()
5215 throw new InternalErrorException ();
5218 ModFlags = Modifiers.PUBLIC |
5219 Modifiers.ABSTRACT |
5220 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5222 flags = MethodAttributes.Public |
5223 MethodAttributes.Abstract |
5224 MethodAttributes.HideBySig |
5225 MethodAttributes.NewSlot |
5226 MethodAttributes.Virtual;
5228 if (!Parent.PartialContainer.MethodModifiersValid (this))
5231 flags = Modifiers.MethodAttr (ModFlags);
5234 if (IsExplicitImpl) {
5235 Expression expr = MemberName.Left.GetTypeExpression ();
5236 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (this, false);
5237 if (iface_texpr == null)
5240 InterfaceType = iface_texpr.Type;
5242 if (!InterfaceType.IsInterface) {
5243 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5247 if (!Parent.PartialContainer.VerifyImplements (this))
5250 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5256 protected virtual bool DoDefine ()
5258 if (MemberType == null)
5261 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5262 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5263 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5264 GetSignatureForError (), Parent.GetSignatureForError ());
5268 // verify accessibility
5269 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5270 Report.SymbolRelatedToPreviousError (MemberType);
5271 if (this is Property)
5272 Report.Error (53, Location,
5273 "Inconsistent accessibility: property type `" +
5274 TypeManager.CSharpName (MemberType) + "' is less " +
5275 "accessible than property `" + GetSignatureForError () + "'");
5276 else if (this is Indexer)
5277 Report.Error (54, Location,
5278 "Inconsistent accessibility: indexer return type `" +
5279 TypeManager.CSharpName (MemberType) + "' is less " +
5280 "accessible than indexer `" + GetSignatureForError () + "'");
5281 else if (this is MethodCore) {
5282 if (this is Operator)
5283 Report.Error (56, Location,
5284 "Inconsistent accessibility: return type `" +
5285 TypeManager.CSharpName (MemberType) + "' is less " +
5286 "accessible than operator `" + GetSignatureForError () + "'");
5288 Report.Error (50, Location,
5289 "Inconsistent accessibility: return type `" +
5290 TypeManager.CSharpName (MemberType) + "' is less " +
5291 "accessible than method `" + GetSignatureForError () + "'");
5293 Report.Error (52, Location,
5294 "Inconsistent accessibility: field type `" +
5295 TypeManager.CSharpName (MemberType) + "' is less " +
5296 "accessible than field `" + GetSignatureForError () + "'");
5301 if (IsExplicitImpl) {
5302 Expression expr = MemberName.Left.GetTypeExpression ();
5303 TypeExpr texpr = expr.ResolveAsTypeTerminal (this, false);
5307 InterfaceType = texpr.Type;
5309 if (!InterfaceType.IsInterface) {
5310 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5314 if (!Parent.PartialContainer.VerifyImplements (this))
5317 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5323 protected bool IsTypePermitted ()
5325 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5326 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5332 protected override bool VerifyClsCompliance()
5334 if (base.VerifyClsCompliance ()) {
5338 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
5339 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5347 // Fields and Events both generate FieldBuilders, we use this to share
5348 // their common bits. This is also used to flag usage of the field
5350 abstract public class FieldBase : MemberBase {
5351 public FieldBuilder FieldBuilder;
5352 public Status status;
5353 protected Expression initializer;
5354 ExpressionStatement initializerStatement;
5357 public enum Status : byte {
5358 HAS_OFFSET = 4 // Used by FieldMember.
5361 static string[] attribute_targets = new string [] { "field" };
5364 /// Symbol with same name in base class/struct
5366 public MemberInfo conflict_symbol;
5368 protected FieldBase (DeclSpace parent, Expression type, int mod,
5369 int allowed_mod, MemberName name, Attributes attrs)
5370 : base (parent, null, type, mod, allowed_mod, Modifiers.PRIVATE,
5375 public override AttributeTargets AttributeTargets {
5377 return AttributeTargets.Field;
5381 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5383 if (a.Type == TypeManager.marshal_as_attr_type) {
5384 UnmanagedMarshal marshal = a.GetMarshal (this);
5385 if (marshal != null) {
5386 FieldBuilder.SetMarshal (marshal);
5391 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5392 a.Error_InvalidSecurityParent ();
5396 FieldBuilder.SetCustomAttribute (cb);
5399 public void EmitInitializer (EmitContext ec)
5401 initializerStatement.EmitStatement (ec);
5404 protected override bool CheckBase ()
5406 if (!base.CheckBase ())
5413 conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5414 if (conflict_symbol == null) {
5415 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5416 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5421 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5422 Report.SymbolRelatedToPreviousError (conflict_symbol);
5423 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5424 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5430 public Expression Initializer {
5432 if (value != null) {
5433 this.initializer = value;
5434 Parent.PartialContainer.RegisterFieldForInitialization (this);
5439 protected virtual bool IsFieldClsCompliant {
5441 if (FieldBuilder == null)
5444 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5448 public Expression ResolveInitializer ()
5450 // TODO: again it's too heavy-weight
5451 EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
5452 ec.IsFieldInitializer = true;
5453 initializer = initializer.Resolve (ec);
5454 if (initializer == null)
5456 if (FieldBuilder == null)
5459 FieldExpr fe = new FieldExpr (FieldBuilder, Location, true);
5460 if ((ModFlags & Modifiers.STATIC) == 0)
5462 fe.InstanceExpression = CompilerGeneratedThis.Instance;
5465 initializerStatement = new Assign (fe, initializer, Location).ResolveStatement (ec);
5469 public bool HasDefaultInitializer
5473 Constant c = initializer as Constant;
5477 return c.IsDefaultInitializer (MemberType);
5481 public override string[] ValidAttributeTargets
5484 return attribute_targets;
5488 protected override bool VerifyClsCompliance ()
5490 if (!base.VerifyClsCompliance ())
5493 if (!IsFieldClsCompliant) {
5494 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5500 public void SetAssigned ()
5502 caching_flags |= Flags.IsAssigned;
5506 public abstract class FieldMember : FieldBase
5508 protected FieldMember (DeclSpace parent, Expression type, int mod,
5509 int allowed_mod, MemberName name, Attributes attrs)
5510 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, attrs)
5512 if ((mod & Modifiers.ABSTRACT) != 0)
5513 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5516 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5518 if (a.Type == TypeManager.field_offset_attribute_type)
5520 status |= Status.HAS_OFFSET;
5522 if (!Parent.PartialContainer.HasExplicitLayout) {
5523 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5527 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5528 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5533 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5534 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5538 base.ApplyAttributeBuilder (a, cb);
5541 public override bool Define()
5543 if (MemberType == null || Type == null)
5546 if (MemberType == TypeManager.void_type) {
5547 // TODO: wrong location
5548 Expression.Error_VoidInvalidInTheContext (Location);
5555 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5556 Report.Error (52, Location,
5557 "Inconsistent accessibility: field type `" +
5558 TypeManager.CSharpName (MemberType) + "' is less " +
5559 "accessible than field `" + GetSignatureForError () + "'");
5563 if (!IsTypePermitted ())
5569 public override void Emit ()
5571 if (OptAttributes != null) {
5572 OptAttributes.Emit ();
5575 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5576 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5583 // Represents header string for documentation comment.
5585 public override string DocCommentHeader {
5586 get { return "F:"; }
5590 interface IFixedBuffer
5592 FieldInfo Element { get; }
5593 Type ElementType { get; }
5596 public class FixedFieldExternal: IFixedBuffer
5598 FieldInfo element_field;
5600 public FixedFieldExternal (FieldInfo fi)
5602 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5605 #region IFixedField Members
5607 public FieldInfo Element {
5609 return element_field;
5613 public Type ElementType {
5615 return element_field.FieldType;
5623 /// Fixed buffer implementation
5625 public class FixedField : FieldMember, IFixedBuffer
5627 public const string FixedElementName = "FixedElementField";
5628 static int GlobalCounter = 0;
5629 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5630 static FieldInfo[] fi;
5632 TypeBuilder fixed_buffer_type;
5633 FieldBuilder element;
5634 Expression size_expr;
5637 const int AllowedModifiers =
5640 Modifiers.PROTECTED |
5641 Modifiers.INTERNAL |
5644 public FixedField (DeclSpace parent, Expression type, int mod, string name,
5645 Expression size_expr, Attributes attrs, Location loc):
5646 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5648 if (RootContext.Version == LanguageVersion.ISO_1)
5649 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5651 this.size_expr = size_expr;
5654 public override bool Define()
5657 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5658 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5661 if (Parent.PartialContainer.Kind != Kind.Struct) {
5662 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5663 GetSignatureForError ());
5667 if (!base.Define ())
5670 if (!TypeManager.IsPrimitiveType (MemberType)) {
5671 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",
5672 GetSignatureForError ());
5676 EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
5677 Constant c = size_expr.ResolveAsConstant (ec, this);
5681 IntConstant buffer_size_const = c.ToInt (Location);
5682 if (buffer_size_const == null)
5685 buffer_size = buffer_size_const.Value;
5687 if (buffer_size <= 0) {
5688 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5692 int type_size = Expression.GetTypeSize (MemberType);
5694 if (buffer_size > int.MaxValue / type_size) {
5695 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5696 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5700 buffer_size *= type_size;
5703 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5705 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5706 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5707 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5708 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5710 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5711 TypeManager.RegisterFieldBase (FieldBuilder, this);
5716 public override void Emit()
5719 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5721 object[] fi_val = new object[1];
5722 fi_val [0] = buffer_size;
5724 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5725 ctor_args, fi, fi_val);
5726 fixed_buffer_type.SetCustomAttribute (cab);
5728 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5729 FieldBuilder.SetCustomAttribute (cab);
5733 protected override bool IsFieldClsCompliant {
5739 #region IFixedField Members
5741 public FieldInfo Element {
5747 public Type ElementType {
5757 // The Field class is used to represents class/struct fields during parsing.
5759 public class Field : FieldMember {
5761 // Modifiers allowed in a class declaration
5763 const int AllowedModifiers =
5766 Modifiers.PROTECTED |
5767 Modifiers.INTERNAL |
5770 Modifiers.VOLATILE |
5774 public Field (DeclSpace parent, Expression type, int mod, string name,
5775 Attributes attrs, Location loc)
5776 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5781 public override bool Define ()
5783 if (!base.Define ())
5786 if (RootContext.WarningLevel > 1){
5787 Type ptype = Parent.TypeBuilder.BaseType;
5789 // ptype is only null for System.Object while compiling corlib.
5791 TypeContainer.FindMembers (
5792 ptype, MemberTypes.Method,
5793 BindingFlags.Public |
5794 BindingFlags.Static | BindingFlags.Instance,
5795 System.Type.FilterName, Name);
5799 if ((ModFlags & Modifiers.VOLATILE) != 0){
5800 if (!MemberType.IsClass){
5801 Type vt = MemberType;
5803 if (TypeManager.IsEnumType (vt))
5804 vt = TypeManager.EnumToUnderlying (MemberType);
5806 if (!((vt == TypeManager.bool_type) ||
5807 (vt == TypeManager.sbyte_type) ||
5808 (vt == TypeManager.byte_type) ||
5809 (vt == TypeManager.short_type) ||
5810 (vt == TypeManager.ushort_type) ||
5811 (vt == TypeManager.int32_type) ||
5812 (vt == TypeManager.uint32_type) ||
5813 (vt == TypeManager.char_type) ||
5814 (vt == TypeManager.float_type) ||
5815 (!vt.IsValueType))){
5816 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5817 GetSignatureForError (), TypeManager.CSharpName (vt));
5822 if ((ModFlags & Modifiers.READONLY) != 0){
5823 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5824 GetSignatureForError ());
5829 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5831 if (Parent.PartialContainer.Kind == Kind.Struct &&
5832 ((fa & FieldAttributes.Static) == 0) &&
5833 MemberType == Parent.TypeBuilder &&
5834 !TypeManager.IsBuiltinType (MemberType)){
5835 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5836 "' causes a cycle in the structure layout");
5841 FieldBuilder = Parent.TypeBuilder.DefineField (
5842 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5844 TypeManager.RegisterFieldBase (FieldBuilder, this);
5846 catch (ArgumentException) {
5847 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5854 protected override bool VerifyClsCompliance ()
5856 if (!base.VerifyClsCompliance ())
5859 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5860 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5868 // `set' and `get' accessors are represented with an Accessor.
5870 public class Accessor : IIteratorContainer {
5872 // Null if the accessor is empty, or a Block if not
5874 public const int AllowedModifiers =
5876 Modifiers.PROTECTED |
5877 Modifiers.INTERNAL |
5880 public ToplevelBlock Block;
5881 public Attributes Attributes;
5882 public Location Location;
5883 public int ModFlags;
5886 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5891 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5894 public void SetYields ()
5900 // Ooouh Martin, templates are missing here.
5901 // When it will be possible move here a lot of child code and template method type.
5902 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5903 protected MethodData method_data;
5904 protected ToplevelBlock block;
5905 protected ListDictionary declarative_security;
5907 // The accessor are created event if they are not wanted.
5908 // But we need them because their names are reserved.
5909 // Field says whether accessor will be emited or not
5910 public readonly bool IsDummy;
5912 protected readonly string prefix;
5914 ReturnParameter return_attributes;
5916 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5917 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5919 this.prefix = prefix;
5923 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5925 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5926 accessor.Attributes)
5928 this.prefix = prefix;
5929 this.block = accessor.Block;
5932 static MemberName SetupName (string prefix, MemberBase member, Location loc)
5934 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5937 public void UpdateName (MemberBase member)
5939 SetMemberName (SetupName (prefix, member, Location));
5942 #region IMethodData Members
5944 public ToplevelBlock Block {
5954 public CallingConventions CallingConventions {
5956 return CallingConventions.Standard;
5960 public bool IsExcluded ()
5965 GenericMethod IMethodData.GenericMethod {
5971 public MemberName MethodName {
5977 public Type[] ParameterTypes {
5979 return ParameterInfo.Types;
5983 public abstract Parameters ParameterInfo { get ; }
5984 public abstract Type ReturnType { get; }
5985 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5989 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5991 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5992 a.Type == TypeManager.conditional_attribute_type) {
5993 Report.Error (1667, a.Location,
5994 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5995 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5999 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6000 if (declarative_security == null)
6001 declarative_security = new ListDictionary ();
6002 a.ExtractSecurityPermissionSet (declarative_security);
6006 if (a.Target == AttributeTargets.Method) {
6007 method_data.MethodBuilder.SetCustomAttribute (cb);
6011 if (a.Target == AttributeTargets.ReturnValue) {
6012 if (return_attributes == null)
6013 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6015 return_attributes.ApplyAttributeBuilder (a, cb);
6019 ApplyToExtraTarget (a, cb);
6022 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6024 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6027 public override bool Define()
6029 throw new NotSupportedException ();
6032 public void Emit (DeclSpace parent)
6034 EmitMethod (parent);
6036 if (OptAttributes != null)
6037 OptAttributes.Emit ();
6039 if (declarative_security != null) {
6040 foreach (DictionaryEntry de in declarative_security) {
6041 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6048 protected virtual void EmitMethod (DeclSpace parent)
6050 method_data.Emit (parent);
6053 public override bool IsClsComplianceRequired()
6058 public bool IsDuplicateImplementation (MethodCore method)
6060 if (!MemberName.Equals (method.MemberName))
6063 Type[] param_types = method.ParameterTypes;
6065 if (param_types.Length != ParameterTypes.Length)
6068 for (int i = 0; i < param_types.Length; i++)
6069 if (param_types [i] != ParameterTypes [i])
6072 Report.SymbolRelatedToPreviousError (method);
6073 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
6077 public override bool IsUsed
6087 public new Location Location {
6089 return base.Location;
6094 // Represents header string for documentation comment.
6096 public override string DocCommentHeader {
6097 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6103 // Properties and Indexers both generate PropertyBuilders, we use this to share
6104 // their common bits.
6106 abstract public class PropertyBase : MethodCore {
6108 public class GetMethod : PropertyMethod
6110 static string[] attribute_targets = new string [] { "method", "return" };
6112 public GetMethod (MethodCore method):
6113 base (method, "get_")
6117 public GetMethod (MethodCore method, Accessor accessor):
6118 base (method, accessor, "get_")
6122 public override MethodBuilder Define (DeclSpace parent)
6124 base.Define (parent);
6126 method_data = new MethodData (method, ModFlags, flags, this);
6128 if (!method_data.Define (parent))
6131 return method_data.MethodBuilder;
6134 public override Type ReturnType {
6136 return method.MemberType;
6140 public override Parameters ParameterInfo {
6142 return Parameters.EmptyReadOnlyParameters;
6146 public override string[] ValidAttributeTargets {
6148 return attribute_targets;
6153 public class SetMethod : PropertyMethod {
6155 static string[] attribute_targets = new string [] { "method", "param", "return" };
6156 ImplicitParameter param_attr;
6157 protected Parameters parameters;
6159 public SetMethod (MethodCore method):
6160 base (method, "set_")
6164 public SetMethod (MethodCore method, Accessor accessor):
6165 base (method, accessor, "set_")
6169 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6171 if (a.Target == AttributeTargets.Parameter) {
6172 if (param_attr == null)
6173 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6175 param_attr.ApplyAttributeBuilder (a, cb);
6179 base.ApplyAttributeBuilder (a, cb);
6182 public override Parameters ParameterInfo {
6188 protected virtual void DefineParameters ()
6190 parameters = new Parameters (
6191 new Parameter[] { new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location) },
6192 new Type[] { method.MemberType });
6195 public override MethodBuilder Define (DeclSpace parent)
6197 DefineParameters ();
6201 base.Define (parent);
6203 method_data = new MethodData (method, ModFlags, flags, this);
6205 if (!method_data.Define (parent))
6208 return method_data.MethodBuilder;
6211 public override Type ReturnType {
6213 return TypeManager.void_type;
6217 public override string[] ValidAttributeTargets {
6219 return attribute_targets;
6224 static string[] attribute_targets = new string [] { "property" };
6226 public abstract class PropertyMethod : AbstractPropertyEventMethod
6228 protected readonly MethodCore method;
6229 protected MethodAttributes flags;
6232 public PropertyMethod (MethodCore method, string prefix)
6233 : base (method, prefix)
6235 this.method = method;
6238 public PropertyMethod (MethodCore method, Accessor accessor,
6240 : base (method, accessor, prefix)
6242 this.method = method;
6243 this.ModFlags = accessor.ModFlags;
6244 yields = accessor.Yields;
6246 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6247 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6251 public override AttributeTargets AttributeTargets {
6253 return AttributeTargets.Method;
6257 public override bool IsClsComplianceRequired ()
6259 return method.IsClsComplianceRequired ();
6262 public virtual MethodBuilder Define (DeclSpace parent)
6264 if (!method.CheckAbstractAndExtern (block != null))
6267 TypeContainer container = parent.PartialContainer;
6270 // Check for custom access modifier
6272 if (ModFlags == 0) {
6273 ModFlags = method.ModFlags;
6274 flags = method.flags;
6276 if (container.Kind == Kind.Interface)
6277 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6278 GetSignatureForError ());
6280 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6281 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6284 CheckModifiers (ModFlags);
6285 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6286 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6287 flags = Modifiers.MethodAttr (ModFlags);
6288 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6292 // Setup iterator if we are one
6295 Iterator iterator = new Iterator (this, Parent as TypeContainer, null, ModFlags);
6297 if (!iterator.DefineIterator ())
6304 public bool HasCustomAccessModifier
6307 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6311 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6313 return new EmitContext (method,
6314 ds, method.ds, method.Location, ig, ReturnType,
6315 method.ModFlags, false);
6318 public override ObsoleteAttribute GetObsoleteAttribute ()
6320 return method.GetObsoleteAttribute ();
6323 public override string GetSignatureForError()
6325 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6328 void CheckModifiers (int modflags)
6331 int mflags = method.ModFlags & Modifiers.Accessibility;
6333 if ((mflags & Modifiers.PUBLIC) != 0) {
6334 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6336 else if ((mflags & Modifiers.PROTECTED) != 0) {
6337 if ((mflags & Modifiers.INTERNAL) != 0)
6338 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6340 flags |= Modifiers.PRIVATE;
6342 else if ((mflags & Modifiers.INTERNAL) != 0)
6343 flags |= Modifiers.PRIVATE;
6345 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6346 Report.Error (273, Location,
6347 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6348 GetSignatureForError (), method.GetSignatureForError ());
6352 public override bool MarkForDuplicationCheck ()
6354 caching_flags |= Flags.TestMethodDuplication;
6359 public PropertyMethod Get, Set;
6360 public PropertyBuilder PropertyBuilder;
6361 public MethodBuilder GetBuilder, SetBuilder;
6363 protected EmitContext ec;
6365 public PropertyBase (DeclSpace parent, Expression type, int mod_flags,
6366 int allowed_mod, bool is_iface, MemberName name,
6367 Parameters parameters, Attributes attrs)
6368 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6373 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6375 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6376 a.Error_InvalidSecurityParent ();
6380 PropertyBuilder.SetCustomAttribute (cb);
6383 public override AttributeTargets AttributeTargets {
6385 return AttributeTargets.Property;
6389 public override bool Define ()
6394 if (!IsTypePermitted ())
6400 protected override bool DoDefine ()
6402 if (!base.DoDefine ())
6406 // Accessors modifiers check
6408 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6409 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6410 GetSignatureForError ());
6414 if ((Get.IsDummy || Set.IsDummy)
6415 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6416 Report.Error (276, Location,
6417 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6418 GetSignatureForError ());
6422 if (MemberType.IsAbstract && MemberType.IsSealed) {
6423 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6427 ec = new EmitContext (this, Parent, Location, null, MemberType, ModFlags);
6431 protected override bool CheckForDuplications ()
6433 ArrayList ar = Parent.PartialContainer.Indexers;
6435 int arLen = ar.Count;
6437 for (int i = 0; i < arLen; i++) {
6438 Indexer m = (Indexer) ar [i];
6439 if (IsDuplicateImplementation (m))
6444 ar = Parent.PartialContainer.Properties;
6446 int arLen = ar.Count;
6448 for (int i = 0; i < arLen; i++) {
6449 Property m = (Property) ar [i];
6450 if (IsDuplicateImplementation (m))
6458 // TODO: rename to Resolve......
6459 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6461 PropertyInfo base_property = Parent.PartialContainer.BaseCache.FindMemberToOverride (
6462 Parent.TypeBuilder, Name, ParameterTypes, null, true) as PropertyInfo;
6464 if (base_property == null)
6467 base_ret_type = base_property.PropertyType;
6468 MethodInfo get_accessor = base_property.GetGetMethod (true);
6469 MethodInfo set_accessor = base_property.GetSetMethod (true);
6470 MethodAttributes get_accessor_access, set_accessor_access;
6472 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6473 if (Get != null && !Get.IsDummy && get_accessor == null) {
6474 Report.SymbolRelatedToPreviousError (base_property);
6475 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6478 if (Set != null && !Set.IsDummy && set_accessor == null) {
6479 Report.SymbolRelatedToPreviousError (base_property);
6480 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6485 // Check base class accessors access
6488 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6489 get_accessor_access = set_accessor_access = 0;
6490 if ((ModFlags & Modifiers.NEW) == 0) {
6491 if (get_accessor != null) {
6492 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6493 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6495 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6496 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6499 if (set_accessor != null) {
6500 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6501 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6503 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6504 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6509 // Get the less restrictive access
6511 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6514 public override void Emit ()
6517 // The PropertyBuilder can be null for explicit implementations, in that
6518 // case, we do not actually emit the ".property", so there is nowhere to
6519 // put the attribute
6521 if (PropertyBuilder != null && OptAttributes != null)
6522 OptAttributes.Emit ();
6534 /// Tests whether accessors are not in collision with some method (CS0111)
6536 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6538 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6541 public override bool IsUsed
6547 return Get.IsUsed | Set.IsUsed;
6551 protected override void SetMemberName (MemberName new_name)
6553 base.SetMemberName (new_name);
6555 Get.UpdateName (this);
6556 Set.UpdateName (this);
6559 public override string[] ValidAttributeTargets {
6561 return attribute_targets;
6566 // Represents header string for documentation comment.
6568 public override string DocCommentHeader {
6569 get { return "P:"; }
6573 public class Property : PropertyBase {
6574 const int AllowedModifiers =
6577 Modifiers.PROTECTED |
6578 Modifiers.INTERNAL |
6582 Modifiers.OVERRIDE |
6583 Modifiers.ABSTRACT |
6586 Modifiers.METHOD_YIELDS |
6589 const int AllowedInterfaceModifiers =
6592 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6593 MemberName name, Attributes attrs, Accessor get_block,
6595 : base (parent, type, mod,
6596 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6597 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6599 if (get_block == null)
6600 Get = new GetMethod (this);
6602 Get = new GetMethod (this, get_block);
6604 if (set_block == null)
6605 Set = new SetMethod (this);
6607 Set = new SetMethod (this, set_block);
6610 public override bool Define ()
6612 if (!DoDefineBase ())
6615 if (!base.Define ())
6621 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6624 GetBuilder = Get.Define (Parent);
6625 if (GetBuilder == null)
6629 SetBuilder = Set.Define (Parent);
6631 if (SetBuilder == null)
6635 // FIXME - PropertyAttributes.HasDefault ?
6637 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6638 MemberName.ToString (), PropertyAttributes.None, MemberType, null);
6641 PropertyBuilder.SetGetMethod (GetBuilder);
6644 PropertyBuilder.SetSetMethod (SetBuilder);
6646 TypeManager.RegisterProperty (PropertyBuilder, this);
6652 /// Gigantic workaround for lameness in SRE follows :
6653 /// This class derives from EventInfo and attempts to basically
6654 /// wrap around the EventBuilder so that FindMembers can quickly
6655 /// return this in it search for members
6657 public class MyEventBuilder : EventInfo {
6660 // We use this to "point" to our Builder which is
6661 // not really a MemberInfo
6663 EventBuilder MyBuilder;
6666 // We "catch" and wrap these methods
6668 MethodInfo raise, remove, add;
6670 EventAttributes attributes;
6671 Type declaring_type, reflected_type, event_type;
6676 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6678 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6680 // And now store the values in our own fields.
6682 declaring_type = type_builder;
6684 reflected_type = type_builder;
6686 attributes = event_attr;
6689 this.event_type = event_type;
6693 // Methods that you have to override. Note that you only need
6694 // to "implement" the variants that take the argument (those are
6695 // the "abstract" methods, the others (GetAddMethod()) are
6698 public override MethodInfo GetAddMethod (bool nonPublic)
6703 public override MethodInfo GetRemoveMethod (bool nonPublic)
6708 public override MethodInfo GetRaiseMethod (bool nonPublic)
6714 // These methods make "MyEventInfo" look like a Builder
6716 public void SetRaiseMethod (MethodBuilder raiseMethod)
6718 raise = raiseMethod;
6719 MyBuilder.SetRaiseMethod (raiseMethod);
6722 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6724 remove = removeMethod;
6725 MyBuilder.SetRemoveOnMethod (removeMethod);
6728 public void SetAddOnMethod (MethodBuilder addMethod)
6731 MyBuilder.SetAddOnMethod (addMethod);
6734 public void SetCustomAttribute (CustomAttributeBuilder cb)
6736 MyBuilder.SetCustomAttribute (cb);
6739 public override object [] GetCustomAttributes (bool inherit)
6741 // FIXME : There's nothing which can be seemingly done here because
6742 // we have no way of getting at the custom attribute objects of the
6747 public override object [] GetCustomAttributes (Type t, bool inherit)
6749 // FIXME : Same here !
6753 public override bool IsDefined (Type t, bool b)
6758 public override EventAttributes Attributes {
6764 public override string Name {
6770 public override Type DeclaringType {
6772 return declaring_type;
6776 public override Type ReflectedType {
6778 return reflected_type;
6782 public Type EventType {
6788 public void SetUsed ()
6790 if (my_event != null) {
6791 my_event.SetAssigned ();
6792 my_event.SetMemberIsUsed ();
6798 /// For case when event is declared like property (with add and remove accessors).
6800 public class EventProperty: Event {
6802 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6804 public EventProperty (DeclSpace parent, Expression type, int mod_flags,
6805 bool is_iface, MemberName name,
6806 Attributes attrs, Accessor add, Accessor remove)
6807 : base (parent, type, mod_flags, is_iface, name, attrs)
6809 Add = new AddDelegateMethod (this, add);
6810 Remove = new RemoveDelegateMethod (this, remove);
6812 // For this event syntax we don't report error CS0067
6813 // because it is hard to do it.
6817 public override string[] ValidAttributeTargets {
6819 return attribute_targets;
6825 /// Event is declared like field.
6827 public class EventField : Event {
6829 static string[] attribute_targets = new string [] { "event", "field", "method" };
6830 static string[] attribute_targets_interface = new string[] { "event", "method" };
6832 public EventField (DeclSpace parent, Expression type, int mod_flags,
6833 bool is_iface, MemberName name,
6835 : base (parent, type, mod_flags, is_iface, name, attrs)
6837 Add = new AddDelegateMethod (this);
6838 Remove = new RemoveDelegateMethod (this);
6841 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6843 if (a.Target == AttributeTargets.Field) {
6844 FieldBuilder.SetCustomAttribute (cb);
6848 if (a.Target == AttributeTargets.Method) {
6849 Add.ApplyAttributeBuilder (a, cb);
6850 Remove.ApplyAttributeBuilder (a, cb);
6854 base.ApplyAttributeBuilder (a, cb);
6857 public override bool Define()
6859 if (!base.Define ())
6862 if (initializer != null) {
6863 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
6864 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
6865 GetSignatureForError ());
6873 public override string[] ValidAttributeTargets {
6875 return IsInterface ? attribute_targets_interface : attribute_targets;
6880 public abstract class Event : FieldBase {
6882 protected sealed class AddDelegateMethod: DelegateMethod
6885 public AddDelegateMethod (Event method):
6886 base (method, "add_")
6890 public AddDelegateMethod (Event method, Accessor accessor):
6891 base (method, accessor, "add_")
6895 protected override MethodInfo DelegateMethodInfo {
6897 return TypeManager.delegate_combine_delegate_delegate;
6903 protected sealed class RemoveDelegateMethod: DelegateMethod
6905 public RemoveDelegateMethod (Event method):
6906 base (method, "remove_")
6910 public RemoveDelegateMethod (Event method, Accessor accessor):
6911 base (method, accessor, "remove_")
6915 protected override MethodInfo DelegateMethodInfo {
6917 return TypeManager.delegate_remove_delegate_delegate;
6923 public abstract class DelegateMethod : AbstractPropertyEventMethod
6925 protected readonly Event method;
6926 ImplicitParameter param_attr;
6928 static string[] attribute_targets = new string [] { "method", "param", "return" };
6930 public DelegateMethod (Event method, string prefix)
6931 : base (method, prefix)
6933 this.method = method;
6936 public DelegateMethod (Event method, Accessor accessor, string prefix)
6937 : base (method, accessor, prefix)
6939 this.method = method;
6942 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6944 if (a.Target == AttributeTargets.Parameter) {
6945 if (param_attr == null)
6946 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6948 param_attr.ApplyAttributeBuilder (a, cb);
6952 base.ApplyAttributeBuilder (a, cb);
6955 public override AttributeTargets AttributeTargets {
6957 return AttributeTargets.Method;
6961 public override bool IsClsComplianceRequired ()
6963 return method.IsClsComplianceRequired ();
6966 public MethodBuilder Define (DeclSpace parent)
6968 method_data = new MethodData (method, method.ModFlags,
6969 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6971 if (!method_data.Define (parent))
6974 MethodBuilder mb = method_data.MethodBuilder;
6975 ParameterInfo.ApplyAttributes (mb);
6980 protected override void EmitMethod (DeclSpace parent)
6982 if (block != null) {
6983 base.EmitMethod (parent);
6987 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6990 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6991 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6993 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6994 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6995 ig.Emit (OpCodes.Ldsfld, field_info);
6996 ig.Emit (OpCodes.Ldarg_0);
6997 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6998 ig.Emit (OpCodes.Castclass, method.MemberType);
6999 ig.Emit (OpCodes.Stsfld, field_info);
7001 ig.Emit (OpCodes.Ldarg_0);
7002 ig.Emit (OpCodes.Ldarg_0);
7003 ig.Emit (OpCodes.Ldfld, field_info);
7004 ig.Emit (OpCodes.Ldarg_1);
7005 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7006 ig.Emit (OpCodes.Castclass, method.MemberType);
7007 ig.Emit (OpCodes.Stfld, field_info);
7009 ig.Emit (OpCodes.Ret);
7012 protected abstract MethodInfo DelegateMethodInfo { get; }
7014 public override Type ReturnType {
7016 return TypeManager.void_type;
7020 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7022 return new EmitContext (
7023 ds, method.Parent, Location, ig, ReturnType,
7024 method.ModFlags, false);
7027 public override ObsoleteAttribute GetObsoleteAttribute ()
7029 return method.GetObsoleteAttribute ();
7032 public override string[] ValidAttributeTargets {
7034 return attribute_targets;
7038 public override Parameters ParameterInfo {
7040 return method.parameters;
7047 const int AllowedModifiers =
7050 Modifiers.PROTECTED |
7051 Modifiers.INTERNAL |
7056 Modifiers.OVERRIDE |
7060 const int AllowedInterfaceModifiers =
7063 public DelegateMethod Add, Remove;
7064 public MyEventBuilder EventBuilder;
7065 public MethodBuilder AddBuilder, RemoveBuilder;
7066 Parameters parameters;
7068 protected Event (DeclSpace parent, Expression type, int mod_flags,
7069 bool is_iface, MemberName name, Attributes attrs)
7070 : base (parent, type, mod_flags,
7071 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7074 IsInterface = is_iface;
7077 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7079 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7080 a.Error_InvalidSecurityParent ();
7084 EventBuilder.SetCustomAttribute (cb);
7087 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7089 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7092 public override AttributeTargets AttributeTargets {
7094 return AttributeTargets.Event;
7098 public override bool Define ()
7100 EventAttributes e_attr;
7101 e_attr = EventAttributes.None;
7103 if (!DoDefineBase ())
7109 if (!TypeManager.IsDelegateType (MemberType)) {
7110 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7114 parameters = new Parameters (
7115 new Parameter[] { new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location) },
7116 new Type[] { MemberType } );
7122 // Now define the accessors
7125 AddBuilder = Add.Define (Parent);
7126 if (AddBuilder == null)
7129 RemoveBuilder = Remove.Define (Parent);
7130 if (RemoveBuilder == null)
7133 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7135 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7136 FieldBuilder = Parent.TypeBuilder.DefineField (
7138 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7139 TypeManager.RegisterPrivateFieldOfEvent (
7140 (EventInfo) EventBuilder, FieldBuilder);
7141 TypeManager.RegisterFieldBase (FieldBuilder, this);
7144 EventBuilder.SetAddOnMethod (AddBuilder);
7145 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7147 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7151 protected override bool CheckBase ()
7153 if (!base.CheckBase ())
7156 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7157 if (!(conflict_symbol is EventInfo)) {
7158 Report.SymbolRelatedToPreviousError (conflict_symbol);
7159 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
7167 public override void Emit ()
7169 if (OptAttributes != null) {
7170 OptAttributes.Emit ();
7174 Remove.Emit (Parent);
7179 public override string GetSignatureForError ()
7181 return base.GetSignatureForError ();
7185 // Represents header string for documentation comment.
7187 public override string DocCommentHeader {
7188 get { return "E:"; }
7193 public class Indexer : PropertyBase, IIteratorContainer {
7195 class GetIndexerMethod : GetMethod
7197 public GetIndexerMethod (MethodCore method):
7202 public GetIndexerMethod (MethodCore method, Accessor accessor):
7203 base (method, accessor)
7207 public override Parameters ParameterInfo {
7209 return method.ParameterInfo;
7214 class SetIndexerMethod: SetMethod
7216 public SetIndexerMethod (MethodCore method):
7221 public SetIndexerMethod (MethodCore method, Accessor accessor):
7222 base (method, accessor)
7226 protected override void DefineParameters ()
7228 parameters = Parameters.MergeGenerated (method.Parameters,
7229 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7233 const int AllowedModifiers =
7236 Modifiers.PROTECTED |
7237 Modifiers.INTERNAL |
7241 Modifiers.OVERRIDE |
7246 const int AllowedInterfaceModifiers =
7250 // Are we implementing an interface ?
7252 public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
7253 bool is_iface, Parameters parameters, Attributes attrs,
7254 Accessor get_block, Accessor set_block)
7255 : base (parent, type, mod,
7256 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7257 is_iface, name, parameters, attrs)
7259 if (get_block == null)
7260 Get = new GetIndexerMethod (this);
7262 Get = new GetIndexerMethod (this, get_block);
7264 if (set_block == null)
7265 Set = new SetIndexerMethod (this);
7267 Set = new SetIndexerMethod (this, set_block);
7270 public override bool Define ()
7272 if (!DoDefineBase ())
7275 if (!base.Define ())
7278 if (MemberType == TypeManager.void_type) {
7279 Report.Error (620, Location, "Indexers cannot have void type");
7283 if (OptAttributes != null) {
7284 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7285 if (indexer_attr != null) {
7286 // Remove the attribute from the list because it is not emitted
7287 OptAttributes.Attrs.Remove (indexer_attr);
7289 string name = indexer_attr.GetIndexerAttributeValue ();
7295 if (IsExplicitImpl) {
7296 Report.Error (415, indexer_attr.Location,
7297 "The `IndexerName' attribute is valid only on an " +
7298 "indexer that is not an explicit interface member declaration");
7302 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7303 Report.Error (609, indexer_attr.Location,
7304 "Cannot set the `IndexerName' attribute on an indexer marked override");
7310 if (InterfaceType != null) {
7311 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7312 if (base_IndexerName != Name)
7313 ShortName = base_IndexerName;
7316 if (!Parent.PartialContainer.AddMember (this) ||
7317 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7323 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7325 GetBuilder = Get.Define (Parent);
7326 if (GetBuilder == null)
7330 // Setup iterator if we are one
7332 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7333 Iterator iterator = new Iterator (
7334 Get, Parent, null, ModFlags);
7336 if (!iterator.DefineIterator ())
7341 SetBuilder = Set.Define (Parent);
7343 if (SetBuilder == null)
7348 // Now name the parameters
7350 Parameter [] p = Parameters.FixedParameters;
7352 // TODO: should be done in parser and it needs to do cycle
7353 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7354 Report.Error (631, Location, "ref and out are not valid in this context");
7359 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7360 Name, PropertyAttributes.None, MemberType, ParameterTypes);
7363 PropertyBuilder.SetGetMethod (GetBuilder);
7366 PropertyBuilder.SetSetMethod (SetBuilder);
7368 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7373 public override string GetSignatureForError ()
7375 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7376 if (MemberName.Left != null) {
7378 sb.Append (MemberName.Left);
7381 sb.Append (".this");
7382 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7383 return sb.ToString ();
7386 public override bool MarkForDuplicationCheck ()
7388 caching_flags |= Flags.TestMethodDuplication;
7393 public class Operator : MethodOrOperator, IIteratorContainer {
7395 const int AllowedModifiers =
7401 public enum OpType : byte {
7411 // Unary and Binary operators
7434 // Implicit and Explicit
7438 // Just because of enum
7442 public readonly OpType OperatorType;
7444 public Operator (DeclSpace parent, OpType type, Expression ret_type,
7445 int mod_flags, Parameters parameters,
7446 ToplevelBlock block, Attributes attrs, Location loc)
7447 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7448 new MemberName ("op_" + type, loc), attrs, parameters)
7450 OperatorType = type;
7454 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7456 if (a.Type == TypeManager.conditional_attribute_type) {
7457 Error_ConditionalAttributeIsNotValid ();
7461 base.ApplyAttributeBuilder (a, cb);
7464 protected override bool CheckForDuplications ()
7466 ArrayList ar = Parent.PartialContainer.Operators;
7468 int arLen = ar.Count;
7470 for (int i = 0; i < arLen; i++) {
7471 Operator o = (Operator) ar [i];
7472 if (IsDuplicateImplementation (o))
7477 ar = Parent.PartialContainer.Methods;
7479 int arLen = ar.Count;
7481 for (int i = 0; i < arLen; i++) {
7482 Method m = (Method) ar [i];
7483 if (IsDuplicateImplementation (m))
7491 public override bool Define ()
7493 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7494 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7495 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7499 if (!base.Define ())
7502 if (MemberType == TypeManager.void_type) {
7503 Report.Error (590, Location, "User-defined operators cannot return void");
7507 Type declaring_type = MethodData.DeclaringType;
7508 Type return_type = MemberType;
7509 Type first_arg_type = ParameterTypes [0];
7511 // Rules for conversion operators
7513 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7514 if (first_arg_type == return_type && first_arg_type == declaring_type){
7515 Report.Error (555, Location,
7516 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7520 if ((first_arg_type != declaring_type) && (return_type != declaring_type) &&
7521 !TypeManager.IsNullableTypeOf (first_arg_type, declaring_type) &&
7522 !TypeManager.IsNullableTypeOf (return_type, declaring_type)) {
7525 "User-defined conversion must convert to or from the " +
7530 if (first_arg_type.IsInterface || return_type.IsInterface){
7531 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7532 GetSignatureForError ());
7536 if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type)) {
7537 if (declaring_type.IsSubclassOf (return_type) || declaring_type.IsSubclassOf (first_arg_type)) {
7538 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7539 GetSignatureForError ());
7542 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7543 GetSignatureForError ());
7546 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7547 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
7548 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");
7551 } else if (Parameters.Count == 1) {
7552 // Checks for Unary operators
7554 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7555 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7556 Report.Error (448, Location,
7557 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7560 if (first_arg_type != declaring_type) {
7562 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7567 if (first_arg_type != declaring_type){
7570 "The parameter of a unary operator must be the " +
7575 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7576 if (return_type != TypeManager.bool_type){
7579 "The return type of operator True or False " +
7586 // Checks for Binary operators
7588 if (first_arg_type != declaring_type &&
7589 ParameterTypes [1] != declaring_type){
7592 "One of the parameters of a binary operator must " +
7593 "be the containing type");
7601 protected override bool DoDefine ()
7603 if (!base.DoDefine ())
7606 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7610 public override void Emit ()
7614 Parameters.ApplyAttributes (MethodBuilder);
7617 // abstract or extern methods have no bodies
7619 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7623 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7624 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7626 ec = CreateEmitContext (Parent, null);
7628 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7629 ec.EmitTopBlock (this, Block);
7632 source.CloseMethod ();
7637 // Operator cannot be override
7638 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7643 public static string GetName (OpType ot)
7646 case OpType.LogicalNot:
7648 case OpType.OnesComplement:
7650 case OpType.Increment:
7652 case OpType.Decrement:
7658 case OpType.Addition:
7660 case OpType.Subtraction:
7662 case OpType.UnaryPlus:
7664 case OpType.UnaryNegation:
7666 case OpType.Multiply:
7668 case OpType.Division:
7670 case OpType.Modulus:
7672 case OpType.BitwiseAnd:
7674 case OpType.BitwiseOr:
7676 case OpType.ExclusiveOr:
7678 case OpType.LeftShift:
7680 case OpType.RightShift:
7682 case OpType.Equality:
7684 case OpType.Inequality:
7686 case OpType.GreaterThan:
7688 case OpType.LessThan:
7690 case OpType.GreaterThanOrEqual:
7692 case OpType.LessThanOrEqual:
7694 case OpType.Implicit:
7696 case OpType.Explicit:
7702 public static OpType GetOperatorType (string name)
7704 if (name.StartsWith ("op_")){
7705 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7706 if (Unary.oper_names [i] == name)
7710 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7711 if (Binary.oper_names [i] == name)
7718 public override string GetSignatureForError ()
7720 StringBuilder sb = new StringBuilder ();
7721 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7722 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7725 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7728 sb.Append (Parameters.GetSignatureForError ());
7729 return sb.ToString ();
7734 // This is used to compare method signatures
7736 struct MethodSignature {
7738 public Type RetType;
7739 public Type [] Parameters;
7742 /// This delegate is used to extract methods which have the
7743 /// same signature as the argument
7745 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7747 public MethodSignature (string name, Type ret_type, Type [] parameters)
7752 if (parameters == null)
7753 Parameters = Type.EmptyTypes;
7755 Parameters = parameters;
7758 public override string ToString ()
7761 if (Parameters.Length != 0){
7762 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7763 for (int i = 0; i < Parameters.Length; i++){
7764 sb.Append (Parameters [i]);
7765 if (i+1 < Parameters.Length)
7768 pars = sb.ToString ();
7771 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7774 public override int GetHashCode ()
7776 return Name.GetHashCode ();
7779 public override bool Equals (Object o)
7781 MethodSignature other = (MethodSignature) o;
7783 if (other.Name != Name)
7786 if (other.RetType != RetType)
7789 if (Parameters == null){
7790 if (other.Parameters == null)
7795 if (other.Parameters == null)
7798 int c = Parameters.Length;
7799 if (other.Parameters.Length != c)
7802 for (int i = 0; i < c; i++)
7803 if (other.Parameters [i] != Parameters [i])
7809 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7811 MethodSignature sig = (MethodSignature) filter_criteria;
7813 if (m.Name != sig.Name)
7817 MethodInfo mi = m as MethodInfo;
7818 PropertyInfo pi = m as PropertyInfo;
7821 ReturnType = mi.ReturnType;
7822 else if (pi != null)
7823 ReturnType = pi.PropertyType;
7828 // we use sig.RetType == null to mean `do not check the
7829 // method return value.
7831 if (sig.RetType != null)
7832 if (ReturnType != sig.RetType)
7837 args = TypeManager.GetParameterData (mi).Types;
7839 args = TypeManager.GetArgumentTypes (pi);
7840 Type [] sigp = sig.Parameters;
7842 if (args.Length != sigp.Length)
7845 for (int i = args.Length; i > 0; ){
7847 if (args [i] != sigp [i])