2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 namespace Mono.CSharp {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
79 throw new InternalErrorException (mc.Location, mc.GetSignatureForError (), e);
84 public virtual void Emit ()
86 foreach (MemberCore mc in this)
91 public class MethodArrayList : MemberCoreArrayList
99 CachedMethods cached_method;
100 TypeContainer container;
102 public MethodArrayList (TypeContainer container)
104 this.container = container;
108 /// Method container contains Equals method
110 public bool HasEquals {
112 cached_method |= CachedMethods.Equals;
116 return (cached_method & CachedMethods.Equals) != 0;
121 /// Method container contains GetHashCode method
123 public bool HasGetHashCode {
125 cached_method |= CachedMethods.GetHashCode;
129 return (cached_method & CachedMethods.GetHashCode) != 0;
133 public override void DefineContainerMembers ()
135 base.DefineContainerMembers ();
137 if (HasEquals && !HasGetHashCode) {
138 Report.Warning (659, 3, container.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
144 public sealed class IndexerArrayList : MemberCoreArrayList
147 /// The indexer name for this container
149 public string IndexerName = DefaultIndexerName;
151 bool seen_normal_indexers = false;
153 TypeContainer container;
155 public IndexerArrayList (TypeContainer container)
157 this.container = container;
161 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
162 /// class is consistent. Either it is `Item' or it is the name defined by all the
163 /// indexers with the `IndexerName' attribute.
165 /// Turns out that the IndexerNameAttribute is applied to each indexer,
166 /// but it is never emitted, instead a DefaultMember attribute is attached
169 public override void DefineContainerMembers()
171 base.DefineContainerMembers ();
173 string class_indexer_name = null;
176 // If there's both an explicit and an implicit interface implementation, the
177 // explicit one actually implements the interface while the other one is just
178 // a normal indexer. See bug #37714.
181 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
182 foreach (Indexer i in this) {
183 if (i.InterfaceType != null) {
184 if (seen_normal_indexers)
185 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
189 seen_normal_indexers = true;
191 if (class_indexer_name == null) {
192 class_indexer_name = i.ShortName;
196 if (i.ShortName != class_indexer_name)
197 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
200 if (class_indexer_name != null)
201 IndexerName = class_indexer_name;
204 public override void Emit ()
208 if (!seen_normal_indexers)
211 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
212 container.TypeBuilder.SetCustomAttribute (cb);
216 public class OperatorArrayList: MemberCoreArrayList
218 TypeContainer container;
220 public OperatorArrayList (TypeContainer container)
222 this.container = container;
226 // Operator pair checking
231 public Type ret_type;
232 public Type type1, type2;
234 public Operator.OpType ot;
236 public OperatorEntry (int f, Operator o)
240 ret_type = o.MemberType;
241 Type [] pt = o.ParameterTypes;
248 public override int GetHashCode ()
250 return ret_type.GetHashCode ();
253 public override bool Equals (object o)
255 OperatorEntry other = (OperatorEntry) o;
257 if (other.ret_type != ret_type)
259 if (other.type1 != type1)
261 if (other.type2 != type2)
268 // Checks that some operators come in pairs:
274 // They are matched based on the return type and the argument types
276 void CheckPairedOperators ()
278 IDictionary pairs = new HybridDictionary ();
279 Operator true_op = null;
280 Operator false_op = null;
281 bool has_equality_or_inequality = false;
283 // Register all the operators we care about.
284 foreach (Operator op in this){
287 // Skip erroneous code.
288 if (op.MethodBuilder == null)
291 switch (op.OperatorType){
292 case Operator.OpType.Equality:
294 has_equality_or_inequality = true;
296 case Operator.OpType.Inequality:
298 has_equality_or_inequality = true;
301 case Operator.OpType.True:
304 case Operator.OpType.False:
308 case Operator.OpType.GreaterThan:
310 case Operator.OpType.LessThan:
313 case Operator.OpType.GreaterThanOrEqual:
315 case Operator.OpType.LessThanOrEqual:
321 OperatorEntry oe = new OperatorEntry (reg, op);
323 object o = pairs [oe];
327 oe = (OperatorEntry) o;
332 if (true_op != null){
333 if (false_op == null)
334 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
335 true_op.GetSignatureForError ());
336 } else if (false_op != null)
337 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
338 false_op.GetSignatureForError ());
341 // Look for the mistakes.
343 foreach (DictionaryEntry de in pairs){
344 OperatorEntry oe = (OperatorEntry) de.Key;
351 case Operator.OpType.Equality:
354 case Operator.OpType.Inequality:
357 case Operator.OpType.GreaterThan:
360 case Operator.OpType.LessThan:
363 case Operator.OpType.GreaterThanOrEqual:
366 case Operator.OpType.LessThanOrEqual:
370 Report.Error (216, oe.op.Location,
371 "The operator `{0}' requires a matching operator `{1}' to also be defined",
372 oe.op.GetSignatureForError (), s);
375 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
376 if (container.Methods == null || !container.Methods.HasEquals)
377 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
379 if (container.Methods == null || !container.Methods.HasGetHashCode)
380 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
384 public override void DefineContainerMembers ()
386 base.DefineContainerMembers ();
387 CheckPairedOperators ();
392 // Whether this is a struct, class or interface
393 public readonly Kind Kind;
395 // Holds a list of classes and structures
396 protected ArrayList types;
398 // Holds the list of properties
399 MemberCoreArrayList properties;
401 // Holds the list of enumerations
402 MemberCoreArrayList enums;
404 // Holds the list of delegates
405 MemberCoreArrayList delegates;
407 // Holds the list of constructors
408 protected MemberCoreArrayList instance_constructors;
410 // Holds the list of fields
411 MemberCoreArrayList fields;
413 // Holds a list of fields that have initializers
414 protected ArrayList initialized_fields;
416 // Holds a list of static fields that have initializers
417 protected ArrayList initialized_static_fields;
419 // Holds the list of constants
420 MemberCoreArrayList constants;
423 MemberCoreArrayList interfaces;
425 // Holds the methods.
426 MethodArrayList methods;
429 protected MemberCoreArrayList events;
431 // Holds the indexers
432 IndexerArrayList indexers;
434 // Holds the operators
435 MemberCoreArrayList operators;
437 // Holds the iterators
441 // Pointers to the default constructor and the default static constructor
443 protected Constructor default_constructor;
444 protected Constructor default_static_constructor;
447 // Points to the first non-static field added to the container.
449 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
450 // and the first one's as good as any.
452 FieldBase first_nonstatic_field = null;
455 // This one is computed after we can distinguish interfaces
456 // from classes from the arraylist `type_bases'
459 TypeExpr[] iface_exprs;
462 ArrayList type_bases;
464 bool members_defined;
465 bool members_defined_ok;
467 // The interfaces we implement.
468 protected Type[] ifaces;
470 // The base member cache and our member cache
471 MemberCache base_cache;
472 MemberCache member_cache;
474 public const string DefaultIndexerName = "Item";
477 GenericTypeParameterBuilder[] gen_params;
480 ArrayList partial_parts;
483 /// The pending methods that need to be implemented
484 // (interfaces or abstract methods)
486 PendingImplementation pending;
488 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
489 Attributes attrs, Kind kind)
490 : base (ns, parent, name, attrs)
492 if (parent != null && parent.NamespaceEntry != ns)
493 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
496 this.PartialContainer = this;
499 public bool AddMember (MemberCore symbol)
501 return AddToContainer (symbol, symbol.MemberName.MethodName);
504 protected virtual bool AddMemberType (DeclSpace ds)
506 return AddToContainer (ds, ds.Basename);
509 public void AddConstant (Const constant)
511 if (!AddMember (constant))
514 if (constants == null)
515 constants = new MemberCoreArrayList ();
517 constants.Add (constant);
520 public void AddEnum (Mono.CSharp.Enum e)
522 if (!AddMemberType (e))
526 enums = new MemberCoreArrayList ();
531 public TypeContainer AddTypeContainer (TypeContainer tc, bool is_interface)
533 if (!AddMemberType (tc))
537 if (interfaces == null)
538 interfaces = new MemberCoreArrayList ();
542 types = new ArrayList (2);
548 public virtual TypeContainer AddPartial (TypeContainer nextPart, bool is_interface)
550 return AddPartial (nextPart, nextPart.Basename, is_interface);
553 protected TypeContainer AddPartial (TypeContainer nextPart, string name, bool is_interface)
555 nextPart.ModFlags |= Modifiers.PARTIAL;
556 TypeContainer tc = defined_names [name] as TypeContainer;
559 return AddTypeContainer (nextPart, is_interface);
561 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
562 Report.SymbolRelatedToPreviousError (tc);
563 Error_MissingPartialModifier (nextPart);
567 if (tc.Kind != nextPart.Kind) {
568 Report.SymbolRelatedToPreviousError (tc);
569 Report.Error (261, nextPart.Location,
570 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
571 nextPart.GetSignatureForError ());
575 if ((tc.ModFlags & Modifiers.Accessibility) != (nextPart.ModFlags & Modifiers.Accessibility) &&
576 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
577 (nextPart.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
578 Report.SymbolRelatedToPreviousError (tc);
579 Report.Error (262, nextPart.Location,
580 "Partial declarations of `{0}' have conflicting accessibility modifiers",
581 nextPart.GetSignatureForError ());
585 if (tc.MemberName.IsGeneric) {
586 TypeParameter[] tc_names = tc.TypeParameters;
587 TypeParameterName[] part_names = nextPart.MemberName.TypeArguments.GetDeclarations ();
589 for (int i = 0; i < tc_names.Length; ++i) {
590 if (tc_names[i].Name == part_names[i].Name)
593 Report.SymbolRelatedToPreviousError (part_names[i].Location, "");
594 Report.Error (264, tc.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
595 tc.GetSignatureForError ());
600 if (tc.partial_parts == null)
601 tc.partial_parts = new ArrayList (1);
603 tc.ModFlags |= nextPart.ModFlags;
604 if (nextPart.attributes != null) {
605 if (tc.attributes == null)
606 tc.attributes = nextPart.attributes;
608 tc.attributes.AddAttributes (nextPart.attributes.Attrs);
611 nextPart.PartialContainer = tc;
612 tc.partial_parts.Add (nextPart);
616 public void AddDelegate (Delegate d)
618 if (!AddMemberType (d))
621 if (delegates == null)
622 delegates = new MemberCoreArrayList ();
627 public void AddMethod (Method method)
629 if (!AddMember (method))
633 methods = new MethodArrayList (this);
635 if (method.MemberName.Left != null)
636 methods.Insert (0, method);
638 methods.Add (method);
642 // Do not use this method: use AddMethod.
644 // This is only used by iterators.
646 public void AppendMethod (Method method)
648 if (!AddMember (method))
652 methods = new MethodArrayList (this);
654 methods.Add (method);
657 public void AddConstructor (Constructor c)
659 if (c.Name != MemberName.Name) {
660 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
663 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
666 if (default_static_constructor != null) {
667 Report.SymbolRelatedToPreviousError (default_static_constructor);
668 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
672 default_static_constructor = c;
674 if (c.Parameters.Empty){
675 if (default_constructor != null) {
676 Report.SymbolRelatedToPreviousError (default_constructor);
677 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
680 default_constructor = c;
683 if (instance_constructors == null)
684 instance_constructors = new MemberCoreArrayList ();
686 instance_constructors.Add (c);
690 internal static string Error111 {
692 return "`{0}' is already defined. Rename this member or use different parameter types";
696 public void AddField (FieldMember field)
698 if (!AddMember (field))
702 fields = new MemberCoreArrayList ();
706 if ((field.ModFlags & Modifiers.STATIC) != 0)
709 if (first_nonstatic_field == null) {
710 first_nonstatic_field = field;
714 if (Kind == Kind.Struct &&
715 first_nonstatic_field.Parent != field.Parent &&
716 RootContext.WarningLevel >= 3) {
717 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
718 Report.Warning (282, 3, field.Location,
719 "struct instance field `{0}' found in different declaration from instance field `{1}'",
720 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
724 public void AddProperty (Property prop)
726 if (!AddMember (prop) ||
727 !AddMember (prop.Get) || !AddMember (prop.Set))
730 if (properties == null)
731 properties = new MemberCoreArrayList ();
733 if (prop.MemberName.Left != null)
734 properties.Insert (0, prop);
736 properties.Add (prop);
739 public void AddEvent (Event e)
744 if (e is EventProperty) {
745 if (!AddMember (e.Add))
748 if (!AddMember (e.Remove))
753 events = new MemberCoreArrayList ();
759 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
761 public void AddIndexer (Indexer i)
763 if (indexers == null)
764 indexers = new IndexerArrayList (this);
766 if (i.IsExplicitImpl)
767 indexers.Insert (0, i);
772 public void AddOperator (Operator op)
777 if (operators == null)
778 operators = new OperatorArrayList (this);
783 public void AddIterator (Iterator i)
785 if (iterators == null)
786 iterators = new ArrayList ();
791 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
793 if (a.Type == TypeManager.default_member_type) {
794 if (Indexers != null) {
795 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
800 base.ApplyAttributeBuilder (a, cb);
803 public override AttributeTargets AttributeTargets {
805 throw new NotSupportedException ();
809 public ArrayList Types {
815 public MethodArrayList Methods {
821 public ArrayList Constants {
827 public ArrayList Interfaces {
833 public ArrayList Iterators {
839 protected Type BaseType {
841 return TypeBuilder.BaseType;
845 public ArrayList Bases {
855 public ArrayList Fields {
861 public ArrayList InstanceConstructors {
863 return instance_constructors;
867 public ArrayList Properties {
873 public ArrayList Events {
879 public ArrayList Enums {
885 public ArrayList Indexers {
891 public ArrayList Operators {
897 public ArrayList Delegates {
903 protected override TypeAttributes TypeAttr {
905 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
909 public string IndexerName {
911 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
915 public bool IsComImport {
917 if (OptAttributes == null)
920 return OptAttributes.Contains (TypeManager.comimport_attr_type);
924 public virtual void RegisterFieldForInitialization (FieldBase field)
926 if ((field.ModFlags & Modifiers.STATIC) != 0){
927 if (initialized_static_fields == null)
928 initialized_static_fields = new ArrayList (4);
930 initialized_static_fields.Add (field);
932 if (initialized_fields == null)
933 initialized_fields = new ArrayList (4);
935 initialized_fields.Add (field);
940 // Emits the instance field initializers
942 public bool EmitFieldInitializers (EmitContext ec)
947 fields = initialized_static_fields;
949 fields = initialized_fields;
955 foreach (FieldBase f in fields) {
956 f.EmitInitializer (ec);
961 public override string DocComment {
973 public PendingImplementation PendingImplementations {
974 get { return pending; }
977 public override bool GetClsCompliantAttributeValue ()
979 if (PartialContainer != this)
980 return PartialContainer.GetClsCompliantAttributeValue ();
982 return base.GetClsCompliantAttributeValue ();
985 public void AddBasesForPart (DeclSpace part, ArrayList bases)
987 // FIXME: get rid of partial_parts and store lists of bases of each part here
988 // assumed, not verified: 'part' is in 'partial_parts'
989 ((TypeContainer) part).Bases = bases;
992 TypeExpr[] GetNormalBases (out TypeExpr base_class)
998 int count = Bases.Count;
1001 if (Kind == Kind.Class){
1002 TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
1008 if (!name.IsInterface) {
1009 // base_class could be a class, struct, enum, delegate.
1010 // This is validated in GetClassBases.
1016 TypeExpr [] ifaces = new TypeExpr [count-start];
1018 for (i = start, j = 0; i < count; i++, j++){
1019 TypeExpr resolved = ((Expression) Bases [i]).ResolveAsBaseTerminal (this, false);
1020 if (resolved == null) {
1024 ifaces [j] = resolved;
1027 return ifaces.Length == 0 ? null : ifaces;
1031 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
1033 ArrayList ifaces = new ArrayList (0);
1034 if (iface_exprs != null)
1035 ifaces.AddRange (iface_exprs);
1037 foreach (TypeContainer part in partial_parts) {
1038 TypeExpr new_base_class;
1039 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
1040 if (new_base_class != TypeManager.system_object_expr) {
1041 if (base_class == TypeManager.system_object_expr)
1042 base_class = new_base_class;
1044 if (new_base_class != null && !new_base_class.Equals (base_class)) {
1045 Report.SymbolRelatedToPreviousError (base_class.Location, "");
1046 Report.Error (263, part.Location,
1047 "Partial declarations of `{0}' must not specify different base classes",
1048 part.GetSignatureForError ());
1055 if (new_ifaces == null)
1058 foreach (TypeExpr iface in new_ifaces) {
1059 if (ifaces.Contains (iface))
1066 if (ifaces.Count == 0)
1069 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
1073 /// This function computes the Base class and also the
1074 /// list of interfaces that the class or struct @c implements.
1076 /// The return value is an array (might be null) of
1077 /// interfaces implemented (as Types).
1079 /// The @base_class argument is set to the base object or null
1080 /// if this is `System.Object'.
1082 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1084 TypeExpr[] ifaces = GetNormalBases (out base_class);
1089 int count = ifaces.Length;
1091 for (int i = 0; i < count; i++) {
1092 TypeExpr iface = (TypeExpr) ifaces [i];
1094 if (!iface.IsInterface) {
1095 if (Kind != Kind.Class) {
1096 // TODO: location of symbol related ....
1097 Error_TypeInListIsNotInterface (Location, iface.FullName);
1099 else if (base_class != null)
1100 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1101 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1103 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1104 GetSignatureForError (), iface.GetSignatureForError ());
1109 for (int x = 0; x < i; x++) {
1110 if (iface.Equals (ifaces [x])) {
1111 Report.Error (528, Location,
1112 "`{0}' is already listed in " +
1113 "interface list", iface.GetSignatureForError ());
1118 if ((Kind == Kind.Interface) &&
1119 !iface.AsAccessible (Parent, ModFlags)) {
1120 Report.Error (61, Location,
1121 "Inconsistent accessibility: base " +
1122 "interface `{0}' is less accessible " +
1123 "than interface `{1}'", iface.Name,
1131 bool CheckGenericInterfaces (Type[] ifaces)
1134 ArrayList already_checked = new ArrayList ();
1136 for (int i = 0; i < ifaces.Length; i++) {
1137 Type iface = ifaces [i];
1138 foreach (Type t in already_checked) {
1142 Type[] infered = new Type [CountTypeParameters];
1143 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1146 Report.Error (695, Location,
1147 "`{0}' cannot implement both `{1}' and `{2}' " +
1148 "because they may unify for some type parameter substitutions",
1149 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1150 TypeManager.CSharpName (t));
1154 already_checked.Add (iface);
1163 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1165 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1168 bool DefineTypeBuilder ()
1172 if (TypeManager.NamespaceClash (Name, Location)) {
1176 ModuleBuilder builder = CodeGen.Module.Builder;
1177 Type default_parent = null;
1178 if (Kind == Kind.Struct)
1179 default_parent = TypeManager.value_type;
1180 TypeBuilder = builder.DefineType (
1181 Name, TypeAttr, default_parent, null);
1183 TypeBuilder builder = Parent.TypeBuilder;
1185 TypeBuilder = builder.DefineNestedType (
1186 Basename, TypeAttr, null, null);
1188 } catch (ArgumentException) {
1189 Report.RuntimeMissingSupport (Location, "static classes");
1193 TypeManager.AddUserType (this);
1197 string[] param_names = new string [TypeParameters.Length];
1198 for (int i = 0; i < TypeParameters.Length; i++)
1199 param_names [i] = TypeParameters [i].Name;
1201 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1203 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1204 for (int i = offset; i < gen_params.Length; i++)
1205 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1209 iface_exprs = GetClassBases (out base_type);
1210 if (partial_parts != null) {
1211 iface_exprs = GetNormalPartialBases (ref base_type);
1215 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1216 // which in turn should have called DefineType()s on base types if necessary.
1218 // None of the code below should trigger DefineType()s on classes that we depend on.
1219 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1221 // Let's do it as soon as possible, since code below can call DefineType() on classes
1222 // that depend on us to be populated before they are.
1224 if (!(this is Iterator))
1225 RootContext.RegisterOrder (this);
1227 if (base_type != null) {
1228 if (IsGeneric && TypeManager.IsAttributeType (base_type.Type)) {
1229 Report.Error (698, base_type.Location,
1230 "A generic type cannot derive from `{0}' " +
1231 "because it is an attribute class",
1236 TypeBuilder.SetParent (base_type.Type);
1238 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1239 if (obsolete_attr != null && !IsInObsoleteScope) {
1240 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1244 if (!CheckRecursiveDefinition (this)) {
1248 // add interfaces that were not added at type creation
1249 if (iface_exprs != null) {
1250 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1251 if (ifaces == null) {
1255 foreach (Type itype in ifaces)
1256 TypeBuilder.AddInterfaceImplementation (itype);
1258 foreach (TypeExpr ie in iface_exprs) {
1259 ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (ie.Type);
1260 if ((oa != null) && !IsInObsoleteScope)
1261 AttributeTester.Report_ObsoleteMessage (
1262 oa, ie.GetSignatureForError (), Location);
1265 if (!CheckGenericInterfaces (ifaces)) {
1269 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1272 if (this is Iterator && !ResolveType ()) {
1280 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1282 public override TypeBuilder DefineType ()
1284 if (TypeBuilder != null)
1290 if (!DefineTypeBuilder ()) {
1295 if (partial_parts != null) {
1296 foreach (TypeContainer part in partial_parts)
1297 part.TypeBuilder = TypeBuilder;
1300 DefineNestedTypes ();
1305 Constraints [] constraints;
1306 public override void SetParameterInfo (ArrayList constraints_list)
1308 if (PartialContainer == this) {
1309 base.SetParameterInfo (constraints_list);
1313 if (constraints_list == null)
1316 constraints = new Constraints [PartialContainer.CountCurrentTypeParameters];
1318 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1319 for (int i = 0; i < constraints.Length; i++) {
1320 foreach (Constraints constraint in constraints_list) {
1321 if (constraint.TypeParameter == current_params [i].Name) {
1322 constraints [i] = constraint;
1329 bool UpdateTypeParameterConstraints ()
1331 if (constraints == null)
1334 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1335 for (int i = 0; i < current_params.Length; i++) {
1336 if (!current_params [i].UpdateConstraints (this, constraints [i])) {
1337 Report.SymbolRelatedToPreviousError (Location, "");
1338 Report.Error (265, PartialContainer.Location,
1339 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1340 PartialContainer.GetSignatureForError (), current_params [i].Name);
1348 public bool ResolveType ()
1350 if ((base_type != null) &&
1351 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1359 if (PartialContainer != this)
1360 throw new InternalErrorException ();
1362 TypeExpr current_type = null;
1364 foreach (TypeParameter type_param in CurrentTypeParameters) {
1365 if (!type_param.Resolve (this)) {
1371 if (partial_parts != null) {
1372 foreach (TypeContainer part in partial_parts) {
1373 if (!part.UpdateTypeParameterConstraints ()) {
1380 foreach (TypeParameter type_param in TypeParameters) {
1381 if (!type_param.DefineType (this)) {
1387 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1389 foreach (TypeParameter type_param in TypeParameters)
1390 if (!type_param.CheckDependencies ()) {
1395 if (current_type != null) {
1396 current_type = current_type.ResolveAsTypeTerminal (this, false);
1397 if (current_type == null) {
1402 CurrentType = current_type.Type;
1408 protected virtual bool DefineNestedTypes ()
1410 if (Interfaces != null) {
1411 foreach (TypeContainer iface in Interfaces)
1412 if (iface.DefineType () == null)
1416 if (Types != null) {
1417 foreach (TypeContainer tc in Types)
1418 if (tc.DefineType () == null)
1422 if (Delegates != null) {
1423 foreach (Delegate d in Delegates)
1424 if (d.DefineType () == null)
1428 if (Enums != null) {
1429 foreach (Enum en in Enums)
1430 if (en.DefineType () == null)
1437 TypeContainer InTransit;
1439 protected bool CheckRecursiveDefinition (TypeContainer tc)
1441 if (InTransit != null) {
1442 Report.SymbolRelatedToPreviousError (this);
1443 if (this is Interface)
1445 529, tc.Location, "Inherited interface `{0}' causes a " +
1446 "cycle in the interface hierarchy of `{1}'",
1447 GetSignatureForError (), tc.GetSignatureForError ());
1450 146, tc.Location, "Circular base class dependency " +
1451 "involving `{0}' and `{1}'",
1452 tc.GetSignatureForError (), GetSignatureForError ());
1458 if (BaseType != null) {
1459 Type t = TypeManager.DropGenericTypeArguments (BaseType);
1460 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1461 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1465 if (iface_exprs != null) {
1466 foreach (TypeExpr iface in iface_exprs) {
1467 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1468 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1469 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1474 if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1481 public static void Error_KeywordNotAllowed (Location loc)
1483 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1487 /// Populates our TypeBuilder with fields and methods
1489 public override bool DefineMembers ()
1491 if (members_defined)
1492 return members_defined_ok;
1494 if (!base.DefineMembers ())
1497 members_defined_ok = DoDefineMembers ();
1498 members_defined = true;
1500 return members_defined_ok;
1503 protected virtual bool DoDefineMembers ()
1505 if (iface_exprs != null) {
1506 foreach (TypeExpr iface in iface_exprs) {
1507 ConstructedType ct = iface as ConstructedType;
1508 if ((ct != null) && !ct.CheckConstraints (this))
1513 if (base_type != null) {
1514 ConstructedType ct = base_type as ConstructedType;
1515 if ((ct != null) && !ct.CheckConstraints (this))
1520 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1521 if (conflict_symbol == null) {
1522 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1523 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1525 if ((ModFlags & Modifiers.NEW) == 0) {
1526 Report.SymbolRelatedToPreviousError (conflict_symbol);
1527 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1528 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1533 DefineContainerMembers (constants);
1534 DefineContainerMembers (fields);
1536 if (Kind == Kind.Struct || Kind == Kind.Class) {
1537 pending = PendingImplementation.GetPendingImplementations (this);
1541 // Constructors are not in the defined_names array
1543 DefineContainerMembers (instance_constructors);
1545 DefineContainerMembers (properties);
1546 DefineContainerMembers (events);
1547 DefineContainerMembers (indexers);
1548 DefineContainerMembers (methods);
1549 DefineContainerMembers (operators);
1550 DefineContainerMembers (enums);
1551 DefineContainerMembers (delegates);
1553 if (CurrentType != null) {
1554 GenericType = CurrentType;
1559 member_cache = new MemberCache (this);
1560 if (partial_parts != null) {
1561 foreach (TypeContainer part in partial_parts)
1562 part.member_cache = member_cache;
1565 if (iterators != null) {
1566 foreach (Iterator iterator in iterators) {
1567 if (iterator.DefineType () == null)
1571 foreach (Iterator iterator in iterators) {
1572 if (!iterator.DefineMembers ())
1580 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1583 mcal.DefineContainerMembers ();
1586 public override bool Define ()
1588 if (iterators != null) {
1589 foreach (Iterator iterator in iterators) {
1590 if (!iterator.Define ())
1598 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1600 return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1604 /// This function is based by a delegate to the FindMembers routine
1606 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1612 /// This filter is used by FindMembers, and we just keep
1613 /// a global for the filter to `AlwaysAccept'
1615 static MemberFilter accepting_filter;
1618 static TypeContainer ()
1620 accepting_filter = new MemberFilter (AlwaysAccept);
1623 public MethodInfo[] GetMethods ()
1625 ArrayList members = new ArrayList ();
1629 if (methods != null) {
1630 int len = methods.Count;
1631 for (int i = 0; i < len; i++) {
1632 Method m = (Method) methods [i];
1634 members.Add (m.MethodBuilder);
1638 if (operators != null) {
1639 int len = operators.Count;
1640 for (int i = 0; i < len; i++) {
1641 Operator o = (Operator) operators [i];
1643 members.Add (o.MethodBuilder);
1647 if (properties != null) {
1648 int len = properties.Count;
1649 for (int i = 0; i < len; i++) {
1650 Property p = (Property) properties [i];
1652 if (p.GetBuilder != null)
1653 members.Add (p.GetBuilder);
1654 if (p.SetBuilder != null)
1655 members.Add (p.SetBuilder);
1659 if (indexers != null) {
1660 int len = indexers.Count;
1661 for (int i = 0; i < len; i++) {
1662 Indexer ix = (Indexer) indexers [i];
1664 if (ix.GetBuilder != null)
1665 members.Add (ix.GetBuilder);
1666 if (ix.SetBuilder != null)
1667 members.Add (ix.SetBuilder);
1671 if (events != null) {
1672 int len = events.Count;
1673 for (int i = 0; i < len; i++) {
1674 Event e = (Event) events [i];
1676 if (e.AddBuilder != null)
1677 members.Add (e.AddBuilder);
1678 if (e.RemoveBuilder != null)
1679 members.Add (e.RemoveBuilder);
1683 MethodInfo[] retMethods = new MethodInfo [members.Count];
1684 members.CopyTo (retMethods, 0);
1688 // Indicated whether container has StructLayout attribute set Explicit
1689 public bool HasExplicitLayout {
1690 get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1691 set { caching_flags |= Flags.HasExplicitLayout; }
1695 // Return the nested type with name @name. Ensures that the nested type
1696 // is defined if necessary. Do _not_ use this when you have a MemberCache handy.
1698 public Type FindNestedType (string name)
1700 if (PartialContainer != this)
1701 throw new InternalErrorException ("should not happen");
1703 ArrayList [] lists = { types, enums, delegates, interfaces };
1705 for (int j = 0; j < lists.Length; ++j) {
1706 ArrayList list = lists [j];
1710 int len = list.Count;
1711 for (int i = 0; i < len; ++i) {
1712 DeclSpace ds = (DeclSpace) list [i];
1713 if (ds.Basename == name) {
1714 return ds.DefineType ();
1722 private void FindMembers_NestedTypes (int modflags,
1723 BindingFlags bf, MemberFilter filter, object criteria,
1724 ref ArrayList members)
1726 ArrayList [] lists = { types, enums, delegates, interfaces };
1728 for (int j = 0; j < lists.Length; ++j) {
1729 ArrayList list = lists [j];
1733 int len = list.Count;
1734 for (int i = 0; i < len; i++) {
1735 DeclSpace ds = (DeclSpace) list [i];
1737 if ((ds.ModFlags & modflags) == 0)
1740 TypeBuilder tb = ds.TypeBuilder;
1742 if (!(criteria is string) || ds.Basename.Equals (criteria))
1743 tb = ds.DefineType ();
1746 if (tb != null && (filter (tb, criteria) == true)) {
1747 if (members == null)
1748 members = new ArrayList ();
1757 /// This method returns the members of this type just like Type.FindMembers would
1758 /// Only, we need to use this for types which are _being_ defined because MS'
1759 /// implementation can't take care of that.
1762 // FIXME: return an empty static array instead of null, that cleans up
1763 // some code and is consistent with some coding conventions I just found
1767 // Notice that in various cases we check if our field is non-null,
1768 // something that would normally mean that there was a bug elsewhere.
1770 // The problem happens while we are defining p-invoke methods, as those
1771 // will trigger a FindMembers, but this happens before things are defined
1773 // Since the whole process is a no-op, it is fine to check for null here.
1775 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1776 MemberFilter filter, object criteria)
1778 ArrayList members = null;
1781 if ((bf & BindingFlags.Public) != 0)
1782 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1784 if ((bf & BindingFlags.NonPublic) != 0)
1785 modflags |= Modifiers.PRIVATE;
1787 int static_mask = 0, static_flags = 0;
1788 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1789 case BindingFlags.Static:
1790 static_mask = static_flags = Modifiers.STATIC;
1793 case BindingFlags.Instance:
1794 static_mask = Modifiers.STATIC;
1799 static_mask = static_flags = 0;
1803 Timer.StartTimer (TimerType.TcFindMembers);
1806 filter = accepting_filter;
1808 if ((mt & MemberTypes.Field) != 0) {
1809 if (fields != null) {
1810 int len = fields.Count;
1811 for (int i = 0; i < len; i++) {
1812 FieldMember f = (FieldMember) fields [i];
1814 if ((f.ModFlags & modflags) == 0)
1816 if ((f.ModFlags & static_mask) != static_flags)
1819 FieldBuilder fb = f.FieldBuilder;
1820 if (fb != null && filter (fb, criteria) == true) {
1821 if (members == null)
1822 members = new ArrayList ();
1829 if (constants != null) {
1830 int len = constants.Count;
1831 for (int i = 0; i < len; i++) {
1832 Const con = (Const) constants [i];
1834 if ((con.ModFlags & modflags) == 0)
1836 if ((con.ModFlags & static_mask) != static_flags)
1839 FieldBuilder fb = con.FieldBuilder;
1842 fb = con.FieldBuilder;
1844 if (fb != null && filter (fb, criteria) == true) {
1845 if (members == null)
1846 members = new ArrayList ();
1854 if ((mt & MemberTypes.Method) != 0) {
1855 if (methods != null) {
1856 int len = methods.Count;
1857 for (int i = 0; i < len; i++) {
1858 Method m = (Method) methods [i];
1860 if ((m.ModFlags & modflags) == 0)
1862 if ((m.ModFlags & static_mask) != static_flags)
1865 MethodBuilder mb = m.MethodBuilder;
1867 if (mb != null && filter (mb, criteria) == true) {
1868 if (members == null)
1869 members = new ArrayList ();
1876 if (operators != null) {
1877 int len = operators.Count;
1878 for (int i = 0; i < len; i++) {
1879 Operator o = (Operator) operators [i];
1881 if ((o.ModFlags & modflags) == 0)
1883 if ((o.ModFlags & static_mask) != static_flags)
1886 MethodBuilder ob = o.MethodBuilder;
1887 if (ob != null && filter (ob, criteria) == true) {
1888 if (members == null)
1889 members = new ArrayList ();
1896 if (events != null) {
1897 foreach (Event e in events) {
1898 if ((e.ModFlags & modflags) == 0)
1900 if ((e.ModFlags & static_mask) != static_flags)
1903 MethodBuilder b = e.AddBuilder;
1904 if (b != null && filter (b, criteria)) {
1905 if (members == null)
1906 members = new ArrayList (4);
1911 b = e.RemoveBuilder;
1912 if (b != null && filter (b, criteria)) {
1913 if (members == null)
1914 members = new ArrayList (4);
1921 if (properties != null) {
1922 int len = properties.Count;
1923 for (int i = 0; i < len; i++) {
1924 Property p = (Property) properties [i];
1926 if ((p.ModFlags & modflags) == 0)
1928 if ((p.ModFlags & static_mask) != static_flags)
1934 if (b != null && filter (b, criteria) == true) {
1935 if (members == null)
1936 members = new ArrayList ();
1942 if (b != null && filter (b, criteria) == true) {
1943 if (members == null)
1944 members = new ArrayList ();
1951 if (indexers != null) {
1952 int len = indexers.Count;
1953 for (int i = 0; i < len; i++) {
1954 Indexer ix = (Indexer) indexers [i];
1956 if ((ix.ModFlags & modflags) == 0)
1958 if ((ix.ModFlags & static_mask) != static_flags)
1964 if (b != null && filter (b, criteria) == true) {
1965 if (members == null)
1966 members = new ArrayList ();
1972 if (b != null && filter (b, criteria) == true) {
1973 if (members == null)
1974 members = new ArrayList ();
1982 if ((mt & MemberTypes.Event) != 0) {
1983 if (events != null) {
1984 int len = events.Count;
1985 for (int i = 0; i < len; i++) {
1986 Event e = (Event) events [i];
1988 if ((e.ModFlags & modflags) == 0)
1990 if ((e.ModFlags & static_mask) != static_flags)
1993 MemberInfo eb = e.EventBuilder;
1994 if (eb != null && filter (eb, criteria) == true) {
1995 if (members == null)
1996 members = new ArrayList ();
1998 members.Add (e.EventBuilder);
2004 if ((mt & MemberTypes.Property) != 0){
2005 if (properties != null) {
2006 int len = properties.Count;
2007 for (int i = 0; i < len; i++) {
2008 Property p = (Property) properties [i];
2010 if ((p.ModFlags & modflags) == 0)
2012 if ((p.ModFlags & static_mask) != static_flags)
2015 MemberInfo pb = p.PropertyBuilder;
2016 if (pb != null && filter (pb, criteria) == true) {
2017 if (members == null)
2018 members = new ArrayList ();
2020 members.Add (p.PropertyBuilder);
2025 if (indexers != null) {
2026 int len = indexers.Count;
2027 for (int i = 0; i < len; i++) {
2028 Indexer ix = (Indexer) indexers [i];
2030 if ((ix.ModFlags & modflags) == 0)
2032 if ((ix.ModFlags & static_mask) != static_flags)
2035 MemberInfo ib = ix.PropertyBuilder;
2036 if (ib != null && filter (ib, criteria) == true) {
2037 if (members == null)
2038 members = new ArrayList ();
2040 members.Add (ix.PropertyBuilder);
2046 if ((mt & MemberTypes.NestedType) != 0)
2047 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2049 if ((mt & MemberTypes.Constructor) != 0){
2050 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2051 int len = instance_constructors.Count;
2052 for (int i = 0; i < len; i++) {
2053 Constructor c = (Constructor) instance_constructors [i];
2055 ConstructorBuilder cb = c.ConstructorBuilder;
2056 if (cb != null && filter (cb, criteria) == true) {
2057 if (members == null)
2058 members = new ArrayList ();
2065 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2066 ConstructorBuilder cb =
2067 default_static_constructor.ConstructorBuilder;
2069 if (cb != null && filter (cb, criteria) == true) {
2070 if (members == null)
2071 members = new ArrayList ();
2079 // Lookup members in base if requested.
2081 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2082 if (TypeBuilder.BaseType != null) {
2083 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2084 if (list.Count > 0) {
2085 if (members == null)
2086 members = new ArrayList ();
2088 members.AddRange (list);
2093 Timer.StopTimer (TimerType.TcFindMembers);
2095 if (members == null)
2096 return MemberList.Empty;
2098 return new MemberList (members);
2101 public override MemberCache MemberCache {
2103 return member_cache;
2107 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2108 MemberFilter filter, object criteria)
2110 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2113 return ds.FindMembers (mt, bf, filter, criteria);
2115 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2119 /// Emits the values for the constants
2121 public void EmitConstants ()
2123 if (constants != null)
2124 foreach (Const con in constants)
2129 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2134 foreach (MemberCore mc in al) {
2135 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2139 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2144 public virtual void VerifyMembers ()
2147 // Check for internal or private fields that were never assigned
2149 if (RootContext.WarningLevel >= 3) {
2150 CheckMemberUsage (properties, "property");
2151 CheckMemberUsage (methods, "method");
2152 CheckMemberUsage (constants, "constant");
2154 if (fields != null){
2155 foreach (FieldMember f in fields) {
2156 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2160 if ((f.caching_flags & Flags.IsAssigned) == 0)
2161 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2164 const int error_code = 414;
2166 const int error_code = 169;
2168 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2169 f.GetSignatureForError ());
2175 // Only report 649 on level 4
2177 if (RootContext.WarningLevel < 4)
2180 if ((f.caching_flags & Flags.IsAssigned) != 0)
2183 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2184 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2190 // TODO: move to ClassOrStruct
2191 void EmitConstructors ()
2193 if (instance_constructors == null)
2196 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2197 bool has_compliant_args = false;
2199 foreach (Constructor c in instance_constructors) {
2202 if (has_compliant_args)
2205 has_compliant_args = c.HasCompliantArgs;
2207 if (!has_compliant_args)
2208 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2210 foreach (Constructor c in instance_constructors)
2216 /// Emits the code, this step is performed after all
2217 /// the types, enumerations, constructors
2219 public virtual void EmitType ()
2221 if (OptAttributes != null)
2222 OptAttributes.Emit ();
2226 int offset = CountTypeParameters - CurrentTypeParameters.Length;
2227 for (int i = offset; i < gen_params.Length; i++)
2228 CurrentTypeParameters [i - offset].EmitAttributes ();
2233 // Structs with no fields need to have at least one byte.
2234 // The right thing would be to set the PackingSize in a DefineType
2235 // but there are no functions that allow interfaces *and* the size to
2239 if (Kind == Kind.Struct && first_nonstatic_field == null){
2240 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2241 FieldAttributes.Private);
2243 if (HasExplicitLayout){
2244 object [] ctor_args = new object [1];
2247 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2248 TypeManager.field_offset_attribute_ctor, ctor_args);
2249 fb.SetCustomAttribute (cba);
2255 EmitConstructors ();
2257 // Can not continue if constants are broken
2259 if (Report.Errors > 0)
2262 if (default_static_constructor != null)
2263 default_static_constructor.Emit ();
2265 if (methods != null){
2266 foreach (Method m in methods)
2270 if (operators != null)
2271 foreach (Operator o in operators)
2274 if (properties != null)
2275 foreach (Property p in properties)
2278 if (indexers != null){
2283 foreach (FieldMember f in fields)
2286 if (events != null){
2287 foreach (Event e in Events)
2291 if (delegates != null) {
2292 foreach (Delegate d in Delegates) {
2297 if (enums != null) {
2298 foreach (Enum e in enums) {
2303 if (pending != null)
2304 if (pending.VerifyPendingMethods ())
2307 if (iterators != null)
2308 foreach (Iterator iterator in iterators)
2309 iterator.EmitType ();
2312 public override void CloseType ()
2314 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2318 caching_flags |= Flags.CloseTypeCreated;
2319 TypeBuilder.CreateType ();
2320 } catch (TypeLoadException){
2322 // This is fine, the code still created the type
2324 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2325 // Console.WriteLine (e.Message);
2327 Console.WriteLine ("In type: " + Name);
2332 foreach (Enum en in Enums)
2336 foreach (TypeContainer tc in Types)
2337 if (tc.Kind == Kind.Struct)
2340 foreach (TypeContainer tc in Types)
2341 if (tc.Kind != Kind.Struct)
2345 if (Delegates != null)
2346 foreach (Delegate d in Delegates)
2349 if (Iterators != null)
2350 foreach (Iterator i in Iterators)
2358 initialized_fields = null;
2359 initialized_static_fields = null;
2367 default_constructor = null;
2368 default_static_constructor = null;
2370 OptAttributes = null;
2373 member_cache = null;
2377 // Performs the validation on a Method's modifiers (properties have
2378 // the same properties).
2380 public bool MethodModifiersValid (MemberCore mc)
2382 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2383 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2384 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2386 int flags = mc.ModFlags;
2389 // At most one of static, virtual or override
2391 if ((flags & Modifiers.STATIC) != 0){
2392 if ((flags & vao) != 0){
2393 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2394 mc.GetSignatureForError ());
2399 if (Kind == Kind.Struct){
2400 if ((flags & va) != 0){
2401 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2406 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2407 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2408 mc.GetSignatureForError ());
2413 // If the declaration includes the abstract modifier, then the
2414 // declaration does not include static, virtual or extern
2416 if ((flags & Modifiers.ABSTRACT) != 0){
2417 if ((flags & Modifiers.EXTERN) != 0){
2419 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2423 if ((flags & Modifiers.SEALED) != 0) {
2424 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2428 if ((flags & Modifiers.VIRTUAL) != 0){
2429 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2433 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2434 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2439 if ((flags & Modifiers.PRIVATE) != 0){
2440 if ((flags & vao) != 0){
2441 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2446 if ((flags & Modifiers.SEALED) != 0){
2447 if ((flags & Modifiers.OVERRIDE) == 0){
2448 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2456 public Constructor DefaultStaticConstructor {
2457 get { return default_static_constructor; }
2460 protected override bool VerifyClsCompliance ()
2462 if (!base.VerifyClsCompliance ())
2467 Type base_type = TypeBuilder.BaseType;
2468 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2469 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2472 if (!Parent.IsClsComplianceRequired ()) {
2473 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
2474 GetSignatureForError (), Parent.GetSignatureForError ());
2481 /// Checks whether container name is CLS Compliant
2483 void VerifyClsName ()
2485 Hashtable base_members = base_cache == null ?
2487 base_cache.GetPublicMembers ();
2488 Hashtable this_members = new Hashtable ();
2490 foreach (DictionaryEntry entry in defined_names) {
2491 MemberCore mc = (MemberCore)entry.Value;
2492 if (!mc.IsClsComplianceRequired ())
2495 string name = (string) entry.Key;
2496 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2498 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2499 object found = base_members [lcase];
2500 if (found == null) {
2501 found = this_members [lcase];
2502 if (found == null) {
2503 this_members.Add (lcase, mc);
2508 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2511 if (found is MemberInfo) {
2512 if (basename == ((MemberInfo) found).Name)
2514 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2516 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2519 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2521 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2528 /// Performs checks for an explicit interface implementation. First it
2529 /// checks whether the `interface_type' is a base inteface implementation.
2530 /// Then it checks whether `name' exists in the interface type.
2532 public virtual bool VerifyImplements (MemberBase mb)
2534 if (ifaces != null) {
2535 foreach (Type t in ifaces){
2536 if (t == mb.InterfaceType)
2541 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2542 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2543 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2547 public void Mark_HasEquals ()
2549 Methods.HasEquals = true;
2552 public void Mark_HasGetHashCode ()
2554 Methods.HasGetHashCode = true;
2561 string IMemberContainer.Name {
2567 Type IMemberContainer.Type {
2573 MemberCache IMemberContainer.MemberCache {
2575 return member_cache;
2579 bool IMemberContainer.IsInterface {
2581 return Kind == Kind.Interface;
2585 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2587 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2589 if (GenericType != null)
2590 return TypeManager.FindMembers (GenericType, mt, new_bf,
2593 return FindMembers (mt, new_bf, null, null);
2597 // Generates xml doc comments (if any), and if required,
2598 // handle warning report.
2600 internal override void GenerateDocComment (DeclSpace ds)
2602 DocUtil.GenerateTypeDocComment (this, ds);
2605 public override string DocCommentHeader {
2606 get { return "T:"; }
2609 public virtual MemberCache BaseCache {
2611 if (base_cache != null)
2613 if (TypeBuilder.BaseType != null)
2614 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2615 if (TypeBuilder.IsInterface)
2616 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2622 public abstract class ClassOrStruct : TypeContainer {
2623 ListDictionary declarative_security;
2625 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2626 MemberName name, Attributes attrs, Kind kind)
2627 : base (ns, parent, name, attrs, kind)
2631 protected override bool AddToContainer (MemberCore symbol, string name)
2633 if (name == MemberName.Name) {
2634 if (symbol is TypeParameter) {
2635 Report.Error (694, symbol.Location,
2636 "Type parameter `{0}' has same name as " +
2637 "containing type, or method", name);
2641 Report.SymbolRelatedToPreviousError (this);
2642 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2643 symbol.GetSignatureForError ());
2647 return base.AddToContainer (symbol, name);
2650 public override void VerifyMembers ()
2652 base.VerifyMembers ();
2654 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2655 foreach (Event e in events){
2656 if ((e.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2659 if ((e.caching_flags & Flags.IsUsed) == 0)
2660 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2665 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2667 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2668 if (declarative_security == null)
2669 declarative_security = new ListDictionary ();
2671 a.ExtractSecurityPermissionSet (declarative_security);
2675 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2676 HasExplicitLayout = true;
2679 base.ApplyAttributeBuilder (a, cb);
2683 /// Defines the default constructors
2685 protected void DefineDefaultConstructor (bool is_static)
2687 // The default instance constructor is public
2688 // If the class is abstract, the default constructor is protected
2689 // The default static constructor is private
2693 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2695 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2698 Constructor c = new Constructor (this, MemberName.Name, mods,
2699 Parameters.EmptyReadOnlyParameters,
2700 new GeneratedBaseInitializer (Location),
2704 c.Block = new ToplevelBlock (null, Location);
2707 void DefineFieldInitializers ()
2709 if (initialized_fields != null) {
2710 for (int i = 0; i < initialized_fields.Count; ++i) {
2711 FieldBase fb = (FieldBase)initialized_fields[i];
2712 fb.ResolveInitializer ();
2713 if (fb.HasDefaultInitializer && RootContext.Optimize) {
2714 // Field is re-initialized to its default value => removed
2715 initialized_fields.RemoveAt (i);
2721 if (initialized_static_fields != null) {
2722 bool has_complex_initializer = false;
2724 foreach (FieldBase fb in initialized_static_fields) {
2725 if (fb.ResolveInitializer () is Constant)
2728 has_complex_initializer = true;
2731 // Need special check to not optimize code like this
2732 // static int a = b = 5;
2733 // static int b = 0;
2734 if (!has_complex_initializer && RootContext.Optimize) {
2735 for (int i = 0; i < initialized_static_fields.Count; ++i) {
2736 FieldBase fb = (FieldBase)initialized_static_fields[i];
2737 if (fb.HasDefaultInitializer) {
2738 initialized_static_fields.RemoveAt (i);
2744 if (default_static_constructor == null && initialized_static_fields.Count > 0) {
2745 DefineDefaultConstructor (true);
2751 public override bool Define ()
2753 DefineFieldInitializers ();
2755 if (default_static_constructor != null)
2756 default_static_constructor.Define ();
2758 return base.Define ();
2761 public override void Emit ()
2765 if (declarative_security != null) {
2766 foreach (DictionaryEntry de in declarative_security) {
2767 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2772 protected override TypeAttributes TypeAttr {
2774 if (default_static_constructor == null)
2775 return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2777 return base.TypeAttr;
2783 // TODO: should be sealed
2784 public class Class : ClassOrStruct {
2785 const int AllowedModifiers =
2788 Modifiers.PROTECTED |
2789 Modifiers.INTERNAL |
2791 Modifiers.ABSTRACT |
2796 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2798 : base (ns, parent, name, attrs, Kind.Class)
2800 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2801 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2803 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2804 Report.FeatureIsNotStandardized (Location, "static classes");
2808 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2810 if (a.Type == TypeManager.attribute_usage_type) {
2811 if (BaseType != TypeManager.attribute_type && !BaseType.IsSubclassOf (TypeManager.attribute_type) &&
2812 TypeBuilder.FullName != "System.Attribute") {
2813 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2817 if (a.Type == TypeManager.conditional_attribute_type &&
2818 !(BaseType == TypeManager.attribute_type || BaseType.IsSubclassOf (TypeManager.attribute_type))) {
2819 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2823 if (a.Type == TypeManager.comimport_attr_type &&
2824 !attributes.Contains (TypeManager.guid_attr_type)) {
2825 a.Error_MissingGuidAttribute ();
2829 if (AttributeTester.IsAttributeExcluded (a.Type))
2832 base.ApplyAttributeBuilder (a, cb);
2835 public override AttributeTargets AttributeTargets {
2837 return AttributeTargets.Class;
2841 protected override void DefineContainerMembers (MemberCoreArrayList list)
2847 base.DefineContainerMembers (list);
2851 foreach (MemberCore m in list) {
2852 if (m is Operator) {
2853 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2857 if (m is Destructor) {
2858 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2862 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2863 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
2868 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2872 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2875 if (m is Constructor) {
2876 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2880 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2883 base.DefineContainerMembers (list);
2886 public override TypeBuilder DefineType ()
2888 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2889 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2893 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2894 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2898 return base.DefineType ();
2901 protected override bool DoDefineMembers ()
2903 if (InstanceConstructors == null && !IsStatic)
2904 DefineDefaultConstructor (false);
2906 return base.DoDefineMembers ();
2909 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2911 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2913 if (base_class == null) {
2914 if (RootContext.StdLib)
2915 base_class = TypeManager.system_object_expr;
2916 else if (Name != "System.Object")
2917 base_class = TypeManager.system_object_expr;
2919 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2921 689, base_class.Location,
2922 "Cannot derive from `{0}' because it is a type parameter",
2923 base_class.GetSignatureForError ());
2927 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
2928 Report.Error (1521, base_class.Location, "Invalid base type");
2932 if (base_class.IsSealed){
2933 Report.SymbolRelatedToPreviousError (base_class.Type);
2934 if (base_class.Type.IsAbstract) {
2935 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2936 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2938 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2939 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2944 if (!base_class.CanInheritFrom ()){
2945 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2946 GetSignatureForError (), base_class.GetSignatureForError ());
2950 if (!base_class.AsAccessible (this, ModFlags)) {
2951 Report.SymbolRelatedToPreviousError (base_class.Type);
2952 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2953 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2958 if (base_class != TypeManager.system_object_expr) {
2959 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2960 GetSignatureForError (), base_class.GetSignatureForError ());
2964 if (ifaces != null) {
2965 foreach (TypeExpr t in ifaces)
2966 Report.SymbolRelatedToPreviousError (t.Type);
2967 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2974 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2975 /// Valid only for attribute classes.
2976 public bool IsExcluded ()
2978 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2979 return (caching_flags & Flags.Excluded) != 0;
2981 caching_flags &= ~Flags.Excluded_Undetected;
2983 if (OptAttributes == null)
2986 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2991 foreach (Attribute a in attrs) {
2992 string condition = a.GetConditionalAttributeValue ();
2993 if (RootContext.AllDefines.Contains (condition))
2997 caching_flags |= Flags.Excluded;
3003 return (ModFlags & Modifiers.STATIC) != 0;
3008 // FIXME: How do we deal with the user specifying a different
3011 protected override TypeAttributes TypeAttr {
3013 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
3015 ta |= TypeAttributes.Abstract | TypeAttributes.Sealed;
3021 public sealed class Struct : ClassOrStruct {
3023 // Modifiers allowed in a struct declaration
3025 const int AllowedModifiers =
3028 Modifiers.PROTECTED |
3029 Modifiers.INTERNAL |
3033 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
3034 int mod, Attributes attrs)
3035 : base (ns, parent, name, attrs, Kind.Struct)
3039 if (parent.Parent == null)
3040 accmods = Modifiers.INTERNAL;
3042 accmods = Modifiers.PRIVATE;
3044 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3046 this.ModFlags |= Modifiers.SEALED;
3049 public override AttributeTargets AttributeTargets {
3051 return AttributeTargets.Struct;
3055 const TypeAttributes DefaultTypeAttributes =
3056 TypeAttributes.SequentialLayout |
3057 TypeAttributes.Sealed |
3058 TypeAttributes.BeforeFieldInit;
3061 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
3063 TypeExpr[] ifaces = base.GetClassBases (out base_class);
3065 // If we are compiling our runtime,
3066 // and we are defining ValueType, then our
3067 // base is `System.Object'.
3069 if (base_class == null) {
3070 if (!RootContext.StdLib && Name == "System.ValueType")
3071 base_class = TypeManager.system_object_expr;
3073 base_class = TypeManager.system_valuetype_expr;
3080 // FIXME: Allow the user to specify a different set of attributes
3081 // in some cases (Sealed for example is mandatory for a class,
3082 // but what SequentialLayout can be changed
3084 protected override TypeAttributes TypeAttr {
3086 return base.TypeAttr | DefaultTypeAttributes;
3090 public override void RegisterFieldForInitialization (FieldBase field)
3092 if ((field.ModFlags & Modifiers.STATIC) == 0) {
3093 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3094 field.GetSignatureForError ());
3097 base.RegisterFieldForInitialization (field);
3105 public sealed class Interface : TypeContainer, IMemberContainer {
3108 /// Modifiers allowed in a class declaration
3110 public const int AllowedModifiers =
3113 Modifiers.PROTECTED |
3114 Modifiers.INTERNAL |
3118 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3120 : base (ns, parent, name, attrs, Kind.Interface)
3124 if (parent.Parent == null)
3125 accmods = Modifiers.INTERNAL;
3127 accmods = Modifiers.PRIVATE;
3129 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3132 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3134 if (a.Type == TypeManager.comimport_attr_type &&
3135 !attributes.Contains (TypeManager.guid_attr_type)) {
3136 a.Error_MissingGuidAttribute ();
3139 base.ApplyAttributeBuilder (a, cb);
3143 public override AttributeTargets AttributeTargets {
3145 return AttributeTargets.Interface;
3149 const TypeAttributes DefaultTypeAttributes =
3150 TypeAttributes.AutoLayout |
3151 TypeAttributes.Abstract |
3152 TypeAttributes.Interface;
3154 protected override TypeAttributes TypeAttr {
3156 return base.TypeAttr | DefaultTypeAttributes;
3160 protected override bool VerifyClsCompliance ()
3162 if (!base.VerifyClsCompliance ())
3165 if (ifaces != null) {
3166 foreach (Type t in ifaces) {
3167 if (AttributeTester.IsClsCompliant (t))
3170 Report.SymbolRelatedToPreviousError (t);
3171 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3172 GetSignatureForError (), TypeManager.CSharpName (t));
3180 public abstract class MethodCore : MemberBase {
3181 public readonly Parameters Parameters;
3182 protected ToplevelBlock block;
3185 // The method we're overriding if this is an override method.
3187 protected MethodInfo base_method = null;
3189 public MethodCore (DeclSpace parent, GenericMethod generic,
3190 Expression type, int mod, int allowed_mod, bool is_iface,
3191 MemberName name, Attributes attrs, Parameters parameters)
3192 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3195 Parameters = parameters;
3196 IsInterface = is_iface;
3200 // Returns the System.Type array for the parameters of this method
3202 public Type [] ParameterTypes {
3204 return Parameters.Types;
3208 public Parameters ParameterInfo
3215 public ToplevelBlock Block {
3225 public void SetYields ()
3227 ModFlags |= Modifiers.METHOD_YIELDS;
3230 protected override bool CheckBase ()
3232 if (!base.CheckBase ())
3235 // Check whether arguments were correct.
3236 if (!DoDefineParameters ())
3239 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3245 // Is null for System.Object while compiling corlib and base interfaces
3246 if (Parent.PartialContainer.BaseCache == null) {
3247 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3248 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3253 Type base_ret_type = null;
3254 base_method = FindOutBaseMethod (ref base_ret_type);
3256 // method is override
3257 if (base_method != null) {
3259 if (!CheckMethodAgainstBase ())
3262 if ((ModFlags & Modifiers.NEW) == 0) {
3263 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_ret_type))) {
3264 Report.SymbolRelatedToPreviousError (base_method);
3265 if (this is PropertyBase) {
3266 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3267 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3270 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3271 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3276 if (base_method.IsAbstract && !IsInterface) {
3277 Report.SymbolRelatedToPreviousError (base_method);
3278 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3279 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3284 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3285 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3289 if (Name == "Equals" && Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type)
3290 Parent.PartialContainer.Mark_HasEquals ();
3291 else if (Name == "GetHashCode" && Parameters.Empty)
3292 Parent.PartialContainer.Mark_HasGetHashCode ();
3294 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3295 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3297 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3298 Report.SymbolRelatedToPreviousError (base_method);
3299 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3300 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3307 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !(this is Property));
3308 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3309 if (conflict_symbol != null) {
3310 Report.SymbolRelatedToPreviousError (conflict_symbol);
3311 if (this is PropertyBase)
3312 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3314 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3316 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3320 if (conflict_symbol == null) {
3321 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3322 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3327 if ((ModFlags & Modifiers.NEW) == 0) {
3328 if (this is Method && conflict_symbol is MethodBase)
3331 Report.SymbolRelatedToPreviousError (conflict_symbol);
3332 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3333 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3340 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3341 // that have been defined.
3343 // `name' is the user visible name for reporting errors (this is used to
3344 // provide the right name regarding method names and properties)
3346 bool CheckMethodAgainstBase ()
3350 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3351 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3352 Report.Error (506, Location,
3353 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3354 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3358 // Now we check that the overriden method is not final
3360 if (base_method.IsFinal) {
3361 Report.SymbolRelatedToPreviousError (base_method);
3362 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3363 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3367 // Check that the permissions are not being changed
3369 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3370 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3372 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3373 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3378 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3379 ModFlags |= Modifiers.NEW;
3380 Report.SymbolRelatedToPreviousError (base_method);
3381 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3382 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",
3383 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3385 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3386 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3393 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3395 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3397 // when overriding protected internal, the method can be declared
3398 // protected internal only within the same assembly
3401 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3402 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3404 // assemblies differ - report an error
3408 } else if (thisp != base_classp) {
3410 // same assembly, but other attributes differ - report an error
3415 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3417 // if it's not "protected internal", it must be "protected"
3421 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3423 // protected within the same assembly - an error
3426 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3427 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3429 // protected ok, but other attributes differ - report an error
3435 return (thisp == base_classp);
3439 public bool CheckAbstractAndExtern (bool has_block)
3441 if (Parent.PartialContainer.Kind == Kind.Interface)
3445 if ((ModFlags & Modifiers.EXTERN) != 0) {
3446 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3447 GetSignatureForError ());
3451 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3452 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3453 GetSignatureForError ());
3457 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3458 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3459 GetSignatureForError ());
3467 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3469 Report.SymbolRelatedToPreviousError (base_method);
3470 string base_name = TypeManager.GetFullNameSignature (base_method);
3471 string this_name = GetSignatureForError ();
3472 if (suffix != null) {
3473 base_name += suffix;
3474 this_name += suffix;
3477 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3478 this_name, Modifiers.GetDescription (ma), base_name);
3481 protected static string Error722 {
3483 return "`{0}': static types cannot be used as return types";
3488 /// For custom member duplication search in a container
3490 protected abstract bool CheckForDuplications ();
3493 /// Gets base method and its return type
3495 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3497 protected bool DoDefineParameters ()
3499 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3501 // Check if arguments were correct
3502 if (!Parameters.Resolve (rc))
3505 return CheckParameters (ParameterTypes);
3508 bool CheckParameters (Type [] parameters)
3512 foreach (Type partype in parameters){
3513 if (partype == TypeManager.void_type) {
3514 // TODO: location is wrong
3515 Expression.Error_VoidInvalidInTheContext (Location);
3519 if (partype.IsPointer){
3520 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3524 if (ds.AsAccessible (partype, ModFlags))
3527 Report.SymbolRelatedToPreviousError (partype);
3528 if (this is Indexer)
3529 Report.Error (55, Location,
3530 "Inconsistent accessibility: parameter type `" +
3531 TypeManager.CSharpName (partype) + "' is less " +
3532 "accessible than indexer `" + GetSignatureForError () + "'");
3533 else if (this is Operator)
3534 Report.Error (57, Location,
3535 "Inconsistent accessibility: parameter type `" +
3536 TypeManager.CSharpName (partype) + "' is less " +
3537 "accessible than operator `" + GetSignatureForError () + "'");
3539 Report.Error (51, Location,
3540 "Inconsistent accessibility: parameter type `" +
3541 TypeManager.CSharpName (partype) + "' is less " +
3542 "accessible than method `" + GetSignatureForError () + "'");
3549 protected override bool VerifyClsCompliance ()
3551 if (!base.VerifyClsCompliance ()) {
3552 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3553 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3558 if (Parameters.HasArglist) {
3559 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3562 if (!AttributeTester.IsClsCompliant (MemberType)) {
3563 if (this is PropertyBase)
3564 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3565 GetSignatureForError ());
3567 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3568 GetSignatureForError ());
3571 Parameters.VerifyClsCompliance ();
3576 protected bool IsDuplicateImplementation (MethodCore method)
3578 if (method == this || !(method.MemberName.Equals (MemberName)))
3581 Type[] param_types = method.ParameterTypes;
3582 // This never happen. Rewrite this as Equal
3583 if (param_types == null && ParameterTypes == null)
3585 if (param_types == null || ParameterTypes == null)
3588 if (param_types.Length != ParameterTypes.Length)
3591 if (method.Parameters.HasArglist != Parameters.HasArglist)
3596 for (int i = 0; i < param_types.Length; i++) {
3597 if (param_types [i] != ParameterTypes [i])
3601 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3604 // TODO: make operator compatible with MethodCore to avoid this
3605 if (this is Operator && method is Operator) {
3606 if (MemberType != method.MemberType)
3612 // Try to report 663: method only differs on out/ref
3614 Parameters info = ParameterInfo;
3615 Parameters other_info = method.ParameterInfo;
3616 for (int i = 0; i < info.Count; i++){
3618 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3619 Report.SymbolRelatedToPreviousError (method);
3620 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3621 GetSignatureForError ());
3624 Console.WriteLine ("Method is: {0} {1}", method.Location, method);
3625 Console.WriteLine ("this is: {0} {1}", Location, this);
3629 Report.SymbolRelatedToPreviousError (method);
3630 if (this is Operator && method is Operator)
3631 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3633 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3641 public override bool IsUsed {
3642 get { return IsExplicitImpl || base.IsUsed; }
3646 // Returns a string that represents the signature for this
3647 // member which should be used in XML documentation.
3649 public override string GetDocCommentName (DeclSpace ds)
3651 return DocUtil.GetMethodDocCommentName (this, ds);
3655 // Raised (and passed an XmlElement that contains the comment)
3656 // when GenerateDocComment is writing documentation expectedly.
3658 // FIXME: with a few effort, it could be done with XmlReader,
3659 // that means removal of DOM use.
3661 internal override void OnGenerateDocComment (XmlElement el)
3663 DocUtil.OnMethodGenerateDocComment (this, el);
3667 // Represents header string for documentation comment.
3669 public override string DocCommentHeader {
3670 get { return "M:"; }
3675 public abstract class MethodOrOperator : MethodCore, IMethodData
3677 public MethodBuilder MethodBuilder;
3678 ReturnParameter return_attributes;
3679 ListDictionary declarative_security;
3680 protected MethodData MethodData;
3682 static string[] attribute_targets = new string [] { "method", "return" };
3684 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, Expression type, int mod,
3685 int allowed_mod, bool is_interface, MemberName name,
3686 Attributes attrs, Parameters parameters)
3687 : base (parent, generic, type, mod, allowed_mod, is_interface, name,
3692 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3694 if (a.Target == AttributeTargets.ReturnValue) {
3695 if (return_attributes == null)
3696 return_attributes = new ReturnParameter (MethodBuilder, Location);
3698 return_attributes.ApplyAttributeBuilder (a, cb);
3702 if (a.Type == TypeManager.methodimpl_attr_type &&
3703 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3704 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3707 if (a.Type == TypeManager.dllimport_type) {
3708 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3709 if ((ModFlags & extern_static) != extern_static) {
3710 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3716 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3717 if (declarative_security == null)
3718 declarative_security = new ListDictionary ();
3719 a.ExtractSecurityPermissionSet (declarative_security);
3723 MethodBuilder.SetCustomAttribute (cb);
3726 public override AttributeTargets AttributeTargets {
3728 return AttributeTargets.Method;
3732 public EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3734 EmitContext ec = new EmitContext (this,
3735 tc, this.ds, Location, ig, MemberType, ModFlags, false);
3737 Iterator iterator = tc as Iterator;
3738 if (iterator != null)
3739 ec.CurrentAnonymousMethod = iterator.Host;
3744 public override bool Define ()
3746 if (!DoDefineBase ())
3749 MethodBuilder mb = null;
3751 if (GenericMethod != null) {
3752 string method_name = MemberName.Name;
3754 if (IsExplicitImpl) {
3755 method_name = TypeManager.CSharpName (InterfaceType) +
3759 mb = Parent.TypeBuilder.DefineMethod (method_name, flags);
3761 if (!GenericMethod.Define (mb, block))
3769 if (!CheckAbstractAndExtern (block != null))
3775 MethodData = new MethodData (this, ModFlags, flags, this, mb, GenericMethod, base_method);
3777 if (!MethodData.Define (Parent.PartialContainer))
3780 MethodBuilder = MethodData.MethodBuilder;
3782 if (MemberType.IsAbstract && MemberType.IsSealed) {
3783 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3790 public override void Emit ()
3792 if (OptAttributes != null)
3793 OptAttributes.Emit ();
3795 if (declarative_security != null) {
3796 foreach (DictionaryEntry de in declarative_security) {
3797 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3804 protected void Error_ConditionalAttributeIsNotValid ()
3806 Report.Error (577, Location,
3807 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3808 GetSignatureForError ());
3811 public override bool MarkForDuplicationCheck ()
3813 caching_flags |= Flags.TestMethodDuplication;
3817 public override string[] ValidAttributeTargets {
3819 return attribute_targets;
3823 #region IMethodData Members
3825 public CallingConventions CallingConventions {
3827 CallingConventions cc = Parameters.CallingConvention;
3828 if (Parameters.HasArglist)
3829 block.HasVarargs = true;
3832 if ((ModFlags & Modifiers.STATIC) == 0)
3833 cc |= CallingConventions.HasThis;
3835 // FIXME: How is `ExplicitThis' used in C#?
3841 public Type ReturnType {
3847 public MemberName MethodName {
3853 public new Location Location {
3855 return base.Location;
3859 protected override bool CheckBase() {
3860 if (!base.CheckBase ())
3863 // TODO: Destructor should derive from MethodCore
3864 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3865 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3866 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3874 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3876 public bool IsExcluded () {
3877 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3878 return (caching_flags & Flags.Excluded) != 0;
3880 caching_flags &= ~Flags.Excluded_Undetected;
3882 if (base_method == null) {
3883 if (OptAttributes == null)
3886 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3891 foreach (Attribute a in attrs) {
3892 string condition = a.GetConditionalAttributeValue ();
3893 if (condition == null)
3896 if (RootContext.AllDefines.Contains (condition))
3900 caching_flags |= Flags.Excluded;
3904 IMethodData md = TypeManager.GetMethod (base_method);
3906 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
3907 caching_flags |= Flags.Excluded;
3913 if (md.IsExcluded ()) {
3914 caching_flags |= Flags.Excluded;
3920 GenericMethod IMethodData.GenericMethod {
3922 return GenericMethod;
3930 public class SourceMethod : ISourceMethod
3935 protected SourceMethod (DeclSpace parent, MethodBase builder,
3936 ISourceFile file, Location start, Location end)
3938 this.parent = parent;
3939 this.builder = builder;
3941 CodeGen.SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
3944 public string Name {
3945 get { return builder.Name; }
3948 public int NamespaceID {
3949 get { return parent.NamespaceEntry.SymbolFileID; }
3954 if (builder is MethodBuilder)
3955 return ((MethodBuilder) builder).GetToken ().Token;
3956 else if (builder is ConstructorBuilder)
3957 return ((ConstructorBuilder) builder).GetToken ().Token;
3959 throw new NotSupportedException ();
3963 public void CloseMethod ()
3965 if (CodeGen.SymbolWriter != null)
3966 CodeGen.SymbolWriter.CloseMethod ();
3969 public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
3971 if (CodeGen.SymbolWriter == null)
3976 Location start_loc = block.StartLocation;
3977 if (start_loc.IsNull)
3980 Location end_loc = block.EndLocation;
3984 ISourceFile file = start_loc.SourceFile;
3988 return new SourceMethod (
3989 parent, builder, file, start_loc, end_loc);
3993 public class Method : MethodOrOperator, IIteratorContainer {
3996 /// Modifiers allowed in a class declaration
3998 const int AllowedModifiers =
4001 Modifiers.PROTECTED |
4002 Modifiers.INTERNAL |
4007 Modifiers.OVERRIDE |
4008 Modifiers.ABSTRACT |
4010 Modifiers.METHOD_YIELDS |
4013 const int AllowedInterfaceModifiers =
4014 Modifiers.NEW | Modifiers.UNSAFE;
4017 // return_type can be "null" for VOID values.
4019 public Method (DeclSpace parent, GenericMethod generic,
4020 Expression return_type, int mod, bool is_iface,
4021 MemberName name, Parameters parameters, Attributes attrs)
4022 : base (parent, generic, return_type, mod,
4023 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4024 is_iface, name, attrs, parameters)
4028 public override string GetSignatureForError()
4030 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4033 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4035 Report.Error (17, location,
4036 "Program `{0}' has more than one entry point defined: `{1}'",
4037 CodeGen.FileName, TypeManager.CSharpSignature(b));
4040 bool IsEntryPoint (Parameters pinfo)
4042 if (ReturnType != TypeManager.void_type &&
4043 ReturnType != TypeManager.int32_type)
4046 if (pinfo.Count == 0)
4049 if (pinfo.Count > 1)
4052 Type t = pinfo.ParameterType (0);
4054 (t.GetArrayRank () == 1) &&
4055 (TypeManager.GetElementType (t) == TypeManager.string_type) &&
4056 (pinfo.ParameterModifier (0) == Parameter.Modifier.NONE))
4062 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4064 if (a.Type == TypeManager.conditional_attribute_type) {
4065 if (IsExplicitImpl) {
4066 Error_ConditionalAttributeIsNotValid ();
4070 if (ReturnType != TypeManager.void_type) {
4071 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4075 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4076 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4081 Report.Error (582, Location, "Conditional not valid on interface members");
4085 if (MethodData.implementing != null) {
4086 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4087 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4091 for (int i = 0; i < ParameterInfo.Count; ++i) {
4092 if ((ParameterInfo.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4093 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4099 base.ApplyAttributeBuilder (a, cb);
4102 protected override bool CheckForDuplications ()
4104 ArrayList ar = Parent.PartialContainer.Methods;
4106 int arLen = ar.Count;
4108 for (int i = 0; i < arLen; i++) {
4109 Method m = (Method) ar [i];
4110 if (IsDuplicateImplementation (m))
4115 ar = Parent.PartialContainer.Properties;
4117 for (int i = 0; i < ar.Count; ++i) {
4118 PropertyBase pb = (PropertyBase) ar [i];
4119 if (pb.AreAccessorsDuplicateImplementation (this))
4124 ar = Parent.PartialContainer.Indexers;
4126 for (int i = 0; i < ar.Count; ++i) {
4127 PropertyBase pb = (PropertyBase) ar [i];
4128 if (pb.AreAccessorsDuplicateImplementation (this))
4133 ar = Parent.PartialContainer.Events;
4135 for (int i = 0; i < ar.Count; ++i) {
4136 Event ev = (Event) ar [i];
4137 if (ev.AreAccessorsDuplicateImplementation (this))
4148 public override bool Define ()
4150 if (!base.Define ())
4153 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4154 Error1599 (Location, ReturnType);
4158 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4159 Name == "Finalize" && !(this is Destructor)) {
4160 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4164 // Setup iterator if we are one
4166 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4167 Iterator iterator = new Iterator (
4168 this, Parent, GenericMethod, ModFlags);
4170 if (!iterator.DefineIterator ())
4175 // This is used to track the Entry Point,
4177 if (RootContext.NeedsEntryPoint && ((ModFlags & Modifiers.STATIC) != 0) &&
4179 (RootContext.MainClass == null ||
4180 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4181 if (IsEntryPoint (ParameterInfo)) {
4183 if (RootContext.EntryPoint == null) {
4184 if (Parent.IsGeneric || MemberName.IsGeneric) {
4185 Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4186 GetSignatureForError ());
4188 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4189 md.SetMemberIsUsed ();
4191 RootContext.EntryPoint = MethodBuilder;
4192 RootContext.EntryPointLocation = Location;
4195 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4196 Error_DuplicateEntryPoint (MethodBuilder, Location);
4199 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4200 GetSignatureForError ());
4210 public override void Emit ()
4212 MethodData.Emit (Parent);
4219 public static void Error1599 (Location loc, Type t)
4221 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4224 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4226 MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4227 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4232 if (mi.IsSpecialName)
4235 base_ret_type = mi.ReturnType;
4239 protected override bool VerifyClsCompliance ()
4241 if (!base.VerifyClsCompliance ())
4244 if (ParameterInfo.Count > 0) {
4245 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4247 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4254 public abstract class ConstructorInitializer {
4255 ArrayList argument_list;
4256 protected ConstructorInfo base_constructor;
4259 public ConstructorInitializer (ArrayList argument_list, Location loc)
4261 this.argument_list = argument_list;
4265 public ArrayList Arguments {
4267 return argument_list;
4271 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4273 Expression base_constructor_group;
4277 ec.CurrentBlock = block;
4279 if (argument_list != null){
4280 foreach (Argument a in argument_list){
4281 if (!a.Resolve (ec, loc))
4285 ec.CurrentBlock = null;
4287 if (this is ConstructorBaseInitializer) {
4288 if (ec.ContainerType.BaseType == null)
4291 t = ec.ContainerType.BaseType;
4292 if (ec.ContainerType.IsValueType) {
4293 Report.Error (522, loc,
4294 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4298 t = ec.ContainerType;
4300 base_constructor_group = Expression.MemberLookup (
4301 ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
4302 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4305 if (base_constructor_group == null){
4307 base_constructor_group = Expression.MemberLookup (
4308 t, null, t, ".ctor", MemberTypes.Constructor,
4309 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4313 int errors = Report.Errors;
4314 if (base_constructor_group != null)
4315 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4316 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4319 if (base_constructor == null) {
4320 if (errors == Report.Errors)
4321 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4322 argument_list == null ? 0 : argument_list.Count);
4327 Report.SymbolRelatedToPreviousError (base_constructor);
4328 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4329 base_constructor = null;
4333 if (base_constructor == caller_builder){
4334 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4341 public virtual void Emit (EmitContext ec)
4343 if (base_constructor != null){
4344 ec.Mark (loc, false);
4346 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4348 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4353 public class ConstructorBaseInitializer : ConstructorInitializer {
4354 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4355 base (argument_list, l)
4360 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4361 public GeneratedBaseInitializer (Location loc):
4367 public class ConstructorThisInitializer : ConstructorInitializer {
4368 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4369 base (argument_list, l)
4374 public class Constructor : MethodCore, IMethodData {
4375 public ConstructorBuilder ConstructorBuilder;
4376 public ConstructorInitializer Initializer;
4377 ListDictionary declarative_security;
4380 // Modifiers allowed for a constructor.
4382 public const int AllowedModifiers =
4384 Modifiers.PROTECTED |
4385 Modifiers.INTERNAL |
4391 static string[] attribute_targets = new string [] { "method" };
4393 bool has_compliant_args = false;
4395 // The spec claims that static is not permitted, but
4396 // my very own code has static constructors.
4398 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4399 ConstructorInitializer init, Location loc)
4400 : base (parent, null, null, mod, AllowedModifiers, false,
4401 new MemberName (name, loc), null, args)
4406 public bool HasCompliantArgs {
4407 get { return has_compliant_args; }
4410 public override AttributeTargets AttributeTargets {
4411 get { return AttributeTargets.Constructor; }
4416 // Returns true if this is a default constructor
4418 public bool IsDefault ()
4420 if ((ModFlags & Modifiers.STATIC) != 0)
4421 return Parameters.Empty;
4423 return Parameters.Empty &&
4424 (Initializer is ConstructorBaseInitializer) &&
4425 (Initializer.Arguments == null);
4428 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4430 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4431 if (declarative_security == null) {
4432 declarative_security = new ListDictionary ();
4434 a.ExtractSecurityPermissionSet (declarative_security);
4438 if (a.Type == TypeManager.methodimpl_attr_type &&
4439 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4440 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4443 ConstructorBuilder.SetCustomAttribute (cb);
4446 protected override bool CheckForDuplications ()
4448 ArrayList ar = Parent.PartialContainer.InstanceConstructors;
4450 int arLen = ar.Count;
4452 for (int i = 0; i < arLen; i++) {
4453 Constructor m = (Constructor) ar [i];
4454 if (IsDuplicateImplementation (m))
4461 protected override bool CheckBase ()
4463 if ((ModFlags & Modifiers.STATIC) != 0) {
4464 if (!Parameters.Empty) {
4465 Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4466 GetSignatureForError ());
4470 // the rest can be ignored
4474 // Check whether arguments were correct.
4475 if (!DoDefineParameters ())
4478 if (!CheckForDuplications ())
4481 if (Parent.PartialContainer.Kind == Kind.Struct) {
4482 if (ParameterTypes.Length == 0) {
4483 Report.Error (568, Location,
4484 "Structs cannot contain explicit parameterless constructors");
4488 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4489 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4494 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4495 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4502 // Creates the ConstructorBuilder
4504 public override bool Define ()
4506 if (ConstructorBuilder != null)
4509 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4510 MethodAttributes.SpecialName);
4512 if ((ModFlags & Modifiers.STATIC) != 0) {
4513 ca |= MethodAttributes.Static | MethodAttributes.Private;
4515 ca |= MethodAttributes.HideBySig;
4517 if ((ModFlags & Modifiers.PUBLIC) != 0)
4518 ca |= MethodAttributes.Public;
4519 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4520 if ((ModFlags & Modifiers.INTERNAL) != 0)
4521 ca |= MethodAttributes.FamORAssem;
4523 ca |= MethodAttributes.Family;
4524 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4525 ca |= MethodAttributes.Assembly;
4527 ca |= MethodAttributes.Private;
4530 if (!CheckAbstractAndExtern (block != null))
4533 // Check if arguments were correct.
4537 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4538 ca, CallingConventions,
4541 if ((ModFlags & Modifiers.UNSAFE) != 0)
4542 ConstructorBuilder.InitLocals = false;
4544 if (Parent.PartialContainer.IsComImport) {
4545 if (!IsDefault ()) {
4546 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4547 Parent.GetSignatureForError ());
4550 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4553 TypeManager.AddMethod (ConstructorBuilder, this);
4561 public override void Emit ()
4563 if (OptAttributes != null)
4564 OptAttributes.Emit ();
4566 EmitContext ec = CreateEmitContext (null, null);
4568 if (block != null) {
4569 // If this is a non-static `struct' constructor and doesn't have any
4570 // initializer, it must initialize all of the struct's fields.
4571 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4572 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4573 block.AddThisVariable (Parent, Location);
4575 if (!block.ResolveMeta (ec, ParameterInfo))
4579 if ((ModFlags & Modifiers.STATIC) == 0){
4580 if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4581 Initializer = new GeneratedBaseInitializer (Location);
4585 // Spec mandates that Initializers will not have
4589 if ((Initializer != null) &&
4590 !Initializer.Resolve (ConstructorBuilder, block, ec))
4592 ec.IsStatic = false;
4595 Parameters.ApplyAttributes (ConstructorBuilder);
4597 SourceMethod source = SourceMethod.Create (
4598 Parent, ConstructorBuilder, block);
4601 // Classes can have base initializers and instance field initializers.
4603 if (Parent.PartialContainer.Kind == Kind.Class){
4604 if ((ModFlags & Modifiers.STATIC) == 0){
4607 // If we use a "this (...)" constructor initializer, then
4608 // do not emit field initializers, they are initialized in the other constructor
4610 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4611 Parent.PartialContainer.EmitFieldInitializers (ec);
4614 if (Initializer != null) {
4615 Initializer.Emit (ec);
4618 if ((ModFlags & Modifiers.STATIC) != 0)
4619 Parent.PartialContainer.EmitFieldInitializers (ec);
4621 ec.EmitTopBlock (this, block);
4624 source.CloseMethod ();
4628 if (declarative_security != null) {
4629 foreach (DictionaryEntry de in declarative_security) {
4630 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4637 // Is never override
4638 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4643 public override string GetSignatureForError()
4645 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4648 public override string[] ValidAttributeTargets {
4650 return attribute_targets;
4654 protected override bool VerifyClsCompliance ()
4656 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4660 if (ParameterInfo.Count > 0) {
4661 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4663 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4665 if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4666 foreach (Type param in ParameterTypes) {
4667 if (param.IsArray) {
4673 has_compliant_args = true;
4677 #region IMethodData Members
4679 public System.Reflection.CallingConventions CallingConventions {
4681 CallingConventions cc = Parameters.CallingConvention;
4683 if (Parent.PartialContainer.Kind == Kind.Class)
4684 if ((ModFlags & Modifiers.STATIC) == 0)
4685 cc |= CallingConventions.HasThis;
4687 // FIXME: How is `ExplicitThis' used in C#?
4693 public new Location Location {
4695 return base.Location;
4699 public MemberName MethodName {
4705 public Type ReturnType {
4711 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4713 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4714 return new EmitContext (this, Parent, Location, ig_, null, ModFlags, true);
4717 public bool IsExcluded()
4722 GenericMethod IMethodData.GenericMethod {
4732 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4734 public interface IMethodData
4736 CallingConventions CallingConventions { get; }
4737 Location Location { get; }
4738 MemberName MethodName { get; }
4739 Type ReturnType { get; }
4740 GenericMethod GenericMethod { get; }
4741 Parameters ParameterInfo { get; }
4743 Attributes OptAttributes { get; }
4744 ToplevelBlock Block { get; set; }
4746 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4747 ObsoleteAttribute GetObsoleteAttribute ();
4748 string GetSignatureForError ();
4750 bool IsClsComplianceRequired ();
4751 void SetMemberIsUsed ();
4755 // Encapsulates most of the Method's state
4757 public class MethodData {
4759 readonly IMethodData method;
4761 public readonly GenericMethod GenericMethod;
4764 // Are we implementing an interface ?
4766 public MethodInfo implementing;
4771 protected MemberBase member;
4772 protected int modifiers;
4773 protected MethodAttributes flags;
4774 protected Type declaring_type;
4775 protected MethodInfo parent_method;
4777 MethodBuilder builder = null;
4778 public MethodBuilder MethodBuilder {
4784 public Type DeclaringType {
4786 return declaring_type;
4790 public MethodData (MemberBase member,
4791 int modifiers, MethodAttributes flags, IMethodData method)
4793 this.member = member;
4794 this.modifiers = modifiers;
4797 this.method = method;
4800 public MethodData (MemberBase member,
4801 int modifiers, MethodAttributes flags,
4802 IMethodData method, MethodBuilder builder,
4803 GenericMethod generic, MethodInfo parent_method)
4804 : this (member, modifiers, flags, method)
4806 this.builder = builder;
4807 this.GenericMethod = generic;
4808 this.parent_method = parent_method;
4811 public bool Define (DeclSpace parent)
4813 string name = method.MethodName.Basename;
4814 string method_name = method.MethodName.FullName;
4816 TypeContainer container = parent.PartialContainer;
4818 PendingImplementation pending = container.PendingImplementations;
4819 if (pending != null){
4820 if (member is Indexer) // TODO: test it, but it should work without this IF
4821 implementing = pending.IsInterfaceIndexer (
4822 member.InterfaceType, method.ReturnType, method.ParameterInfo);
4824 implementing = pending.IsInterfaceMethod (
4825 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
4827 if (member.InterfaceType != null){
4828 if (implementing == null){
4829 if (member is PropertyBase) {
4830 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4831 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4832 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4835 Report.Error (539, method.Location,
4836 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4837 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4841 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4842 Report.SymbolRelatedToPreviousError (implementing);
4843 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4844 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4848 method_name = TypeManager.GetFullName (member.InterfaceType) +
4851 if (implementing != null) {
4852 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4853 if (prop_method == null) {
4854 if (implementing.IsSpecialName) {
4855 Report.SymbolRelatedToPreviousError (implementing);
4856 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4857 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4858 implementing.Name.StartsWith ("get_") ? "get" : "set");
4861 } else if (implementing.DeclaringType.IsInterface) {
4862 if (!implementing.IsSpecialName) {
4863 Report.SymbolRelatedToPreviousError (implementing);
4864 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4865 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4868 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4869 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4870 Report.SymbolRelatedToPreviousError (implementing);
4871 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4872 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4881 // For implicit implementations, make sure we are public, for
4882 // explicit implementations, make sure we are private.
4884 if (implementing != null){
4886 // Setting null inside this block will trigger a more
4887 // verbose error reporting for missing interface implementations
4889 // The "candidate" function has been flagged already
4890 // but it wont get cleared
4892 if (member.IsExplicitImpl){
4893 if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
4894 Report.SymbolRelatedToPreviousError (implementing);
4895 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
4896 method.GetSignatureForError ());
4899 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4900 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4902 // If this is an interface method implementation,
4903 // check for public accessibility
4905 implementing = null;
4906 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4907 // We may never be private.
4908 implementing = null;
4909 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4911 // We may be protected if we're overriding something.
4913 implementing = null;
4918 // Static is not allowed
4920 if ((modifiers & Modifiers.STATIC) != 0){
4921 implementing = null;
4926 // If implementing is still valid, set flags
4928 if (implementing != null){
4930 // When implementing interface methods, set NewSlot
4931 // unless, we are overwriting a method.
4933 if (implementing.DeclaringType.IsInterface){
4934 if ((modifiers & Modifiers.OVERRIDE) == 0)
4935 flags |= MethodAttributes.NewSlot;
4938 MethodAttributes.Virtual |
4939 MethodAttributes.HideBySig;
4941 // Set Final unless we're virtual, abstract or already overriding a method.
4942 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4943 flags |= MethodAttributes.Final;
4946 EmitContext ec = method.CreateEmitContext (container, null);
4948 DefineMethodBuilder (container, method_name, method.ParameterInfo.Types);
4950 if (builder == null)
4953 if (container.CurrentType != null)
4954 declaring_type = container.CurrentType;
4956 declaring_type = container.TypeBuilder;
4958 if ((modifiers & Modifiers.UNSAFE) != 0)
4959 builder.InitLocals = false;
4961 if (implementing != null){
4963 // clear the pending implemntation flag
4965 if (member is Indexer) {
4966 pending.ImplementIndexer (
4967 member.InterfaceType, builder, method.ReturnType,
4968 method.ParameterInfo, member.IsExplicitImpl);
4970 pending.ImplementMethod (
4971 member.InterfaceType, name, method.ReturnType,
4972 method.ParameterInfo, member.IsExplicitImpl);
4974 if (member.IsExplicitImpl)
4975 container.TypeBuilder.DefineMethodOverride (
4976 builder, implementing);
4980 TypeManager.AddMethod (builder, method);
4982 if (GenericMethod != null) {
4983 bool is_override = member.IsExplicitImpl |
4984 ((modifiers & Modifiers.OVERRIDE) != 0);
4986 if (implementing != null)
4987 parent_method = implementing;
4989 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
4998 /// Create the MethodBuilder for the method
5000 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
5002 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
5004 if ((modifiers & extern_static) == extern_static) {
5006 if (method.OptAttributes != null) {
5007 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type);
5008 if (dllimport_attribute != null) {
5009 flags |= MethodAttributes.PinvokeImpl;
5010 builder = dllimport_attribute.DefinePInvokeMethod (
5011 container.TypeBuilder, method_name, flags,
5012 method.ReturnType, ParameterTypes);
5018 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5019 // We are more strict than Microsoft and report CS0626 like error
5020 if (method.OptAttributes == null ||
5021 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type)) {
5022 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",
5023 method.GetSignatureForError ());
5028 if (builder == null) {
5029 builder = container.TypeBuilder.DefineMethod (
5030 method_name, flags, method.CallingConventions,
5031 method.ReturnType, ParameterTypes);
5035 #if GMCS_SOURCE && !MS_COMPATIBLE
5036 builder.SetGenericMethodSignature (
5037 flags, method.CallingConventions,
5038 method.ReturnType, ParameterTypes);
5045 public void Emit (DeclSpace parent)
5048 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5049 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5051 ec = method.CreateEmitContext (parent, null);
5053 method.ParameterInfo.ApplyAttributes (MethodBuilder);
5055 if (GenericMethod != null)
5056 GenericMethod.EmitAttributes ();
5058 ToplevelBlock block = method.Block;
5060 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5063 // Handle destructors specially
5065 // FIXME: This code generates buggy code
5067 if (member is Destructor)
5068 EmitDestructor (ec, block);
5070 ec.EmitTopBlock (method, block);
5073 source.CloseMethod ();
5076 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5078 ILGenerator ig = ec.ig;
5080 Label finish = ig.DefineLabel ();
5082 block.SetDestructor ();
5084 ig.BeginExceptionBlock ();
5085 ec.ReturnLabel = finish;
5086 ec.HasReturnLabel = true;
5087 ec.EmitTopBlock (method, block);
5089 // ig.MarkLabel (finish);
5090 ig.BeginFinallyBlock ();
5092 if (ec.ContainerType.BaseType != null) {
5093 Expression member_lookup = Expression.MemberLookup (
5094 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5095 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5097 if (member_lookup != null){
5098 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5100 ig.Emit (OpCodes.Ldarg_0);
5101 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5105 ig.EndExceptionBlock ();
5106 //ig.MarkLabel (ec.ReturnLabel);
5107 ig.Emit (OpCodes.Ret);
5111 // TODO: Should derive from MethodCore
5112 public class Destructor : Method {
5114 static string[] attribute_targets = new string [] { "method" };
5116 public Destructor (DeclSpace parent, Expression return_type, int mod,
5117 string name, Parameters parameters, Attributes attrs,
5119 : base (parent, null, return_type, mod, false, new MemberName (name, l),
5123 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5125 if (a.Type == TypeManager.conditional_attribute_type) {
5126 Error_ConditionalAttributeIsNotValid ();
5130 base.ApplyAttributeBuilder (a, cb);
5133 public override string GetSignatureForError ()
5135 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5138 public override string[] ValidAttributeTargets {
5140 return attribute_targets;
5145 abstract public class MemberBase : MemberCore {
5146 public Expression Type;
5148 public MethodAttributes flags;
5149 public readonly DeclSpace ds;
5150 public readonly GenericMethod GenericMethod;
5152 protected readonly int explicit_mod_flags;
5155 // The "short" name of this property / indexer / event. This is the
5156 // name without the explicit interface.
5158 public string ShortName {
5159 get { return MemberName.Name; }
5160 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
5164 // The type of this property / indexer / event
5166 protected Type member_type;
5167 public Type MemberType {
5169 if (member_type == null && Type != null) {
5170 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
5171 Type = Type.ResolveAsTypeTerminal (rc, false);
5173 member_type = Type.Type;
5181 // Whether this is an interface member.
5183 public bool IsInterface;
5186 // If true, this is an explicit interface implementation
5188 public bool IsExplicitImpl;
5191 // The interface type we are explicitly implementing
5193 public Type InterfaceType = null;
5196 // The constructor is only exposed to our children
5198 protected MemberBase (DeclSpace parent, GenericMethod generic,
5199 Expression type, int mod, int allowed_mod, int def_mod,
5200 MemberName name, Attributes attrs)
5201 : base (parent, name, attrs)
5203 this.ds = generic != null ? generic : (DeclSpace) parent;
5204 explicit_mod_flags = mod;
5206 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5207 IsExplicitImpl = (MemberName.Left != null);
5208 GenericMethod = generic;
5209 if (GenericMethod != null)
5210 GenericMethod.ModFlags = ModFlags;
5213 protected virtual bool CheckBase ()
5215 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.PartialContainer.Kind == Kind.Struct) {
5216 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5220 if ((RootContext.WarningLevel >= 4) &&
5221 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5222 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5223 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5224 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5229 protected virtual bool DoDefineBase ()
5232 throw new InternalErrorException ();
5235 ModFlags = Modifiers.PUBLIC |
5236 Modifiers.ABSTRACT |
5237 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5239 flags = MethodAttributes.Public |
5240 MethodAttributes.Abstract |
5241 MethodAttributes.HideBySig |
5242 MethodAttributes.NewSlot |
5243 MethodAttributes.Virtual;
5245 if (!Parent.PartialContainer.MethodModifiersValid (this))
5248 flags = Modifiers.MethodAttr (ModFlags);
5251 if (IsExplicitImpl) {
5252 Expression expr = MemberName.Left.GetTypeExpression ();
5253 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (this, false);
5254 if (iface_texpr == null)
5257 InterfaceType = iface_texpr.Type;
5259 if (!InterfaceType.IsInterface) {
5260 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5264 if (!Parent.PartialContainer.VerifyImplements (this))
5267 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5273 protected virtual bool DoDefine ()
5275 if (MemberType == null)
5278 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5279 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5280 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5281 GetSignatureForError (), Parent.GetSignatureForError ());
5285 // verify accessibility
5286 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5287 Report.SymbolRelatedToPreviousError (MemberType);
5288 if (this is Property)
5289 Report.Error (53, Location,
5290 "Inconsistent accessibility: property type `" +
5291 TypeManager.CSharpName (MemberType) + "' is less " +
5292 "accessible than property `" + GetSignatureForError () + "'");
5293 else if (this is Indexer)
5294 Report.Error (54, Location,
5295 "Inconsistent accessibility: indexer return type `" +
5296 TypeManager.CSharpName (MemberType) + "' is less " +
5297 "accessible than indexer `" + GetSignatureForError () + "'");
5298 else if (this is MethodCore) {
5299 if (this is Operator)
5300 Report.Error (56, Location,
5301 "Inconsistent accessibility: return type `" +
5302 TypeManager.CSharpName (MemberType) + "' is less " +
5303 "accessible than operator `" + GetSignatureForError () + "'");
5305 Report.Error (50, Location,
5306 "Inconsistent accessibility: return type `" +
5307 TypeManager.CSharpName (MemberType) + "' is less " +
5308 "accessible than method `" + GetSignatureForError () + "'");
5310 Report.Error (52, Location,
5311 "Inconsistent accessibility: field type `" +
5312 TypeManager.CSharpName (MemberType) + "' is less " +
5313 "accessible than field `" + GetSignatureForError () + "'");
5318 if (IsExplicitImpl) {
5319 Expression expr = MemberName.Left.GetTypeExpression ();
5320 TypeExpr texpr = expr.ResolveAsTypeTerminal (this, false);
5324 InterfaceType = texpr.Type;
5326 if (!InterfaceType.IsInterface) {
5327 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5331 if (!Parent.PartialContainer.VerifyImplements (this))
5339 protected bool IsTypePermitted ()
5341 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5342 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5348 protected override bool VerifyClsCompliance()
5350 if (base.VerifyClsCompliance ()) {
5351 if (GenericMethod != null)
5352 GenericMethod.VerifyClsCompliance ();
5357 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
5358 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5366 // Fields and Events both generate FieldBuilders, we use this to share
5367 // their common bits. This is also used to flag usage of the field
5369 abstract public class FieldBase : MemberBase {
5370 public FieldBuilder FieldBuilder;
5371 public Status status;
5372 protected Expression initializer;
5373 ExpressionStatement initializerStatement;
5376 public enum Status : byte {
5377 HAS_OFFSET = 4 // Used by FieldMember.
5380 static string[] attribute_targets = new string [] { "field" };
5383 /// Symbol with same name in base class/struct
5385 public MemberInfo conflict_symbol;
5387 protected FieldBase (DeclSpace parent, Expression type, int mod,
5388 int allowed_mod, MemberName name, Attributes attrs)
5389 : base (parent, null, type, mod, allowed_mod, Modifiers.PRIVATE,
5394 public override AttributeTargets AttributeTargets {
5396 return AttributeTargets.Field;
5400 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5402 if (a.Type == TypeManager.marshal_as_attr_type) {
5403 UnmanagedMarshal marshal = a.GetMarshal (this);
5404 if (marshal != null) {
5405 FieldBuilder.SetMarshal (marshal);
5410 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5411 a.Error_InvalidSecurityParent ();
5415 FieldBuilder.SetCustomAttribute (cb);
5418 public void EmitInitializer (EmitContext ec)
5420 initializerStatement.EmitStatement (ec);
5423 protected override bool CheckBase ()
5425 if (!base.CheckBase ())
5432 conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5433 if (conflict_symbol == null) {
5434 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5435 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5440 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5441 Report.SymbolRelatedToPreviousError (conflict_symbol);
5442 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5443 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5449 public Expression Initializer {
5451 if (value != null) {
5452 this.initializer = value;
5453 Parent.PartialContainer.RegisterFieldForInitialization (this);
5458 protected virtual bool IsFieldClsCompliant {
5460 if (FieldBuilder == null)
5463 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5467 public Expression ResolveInitializer ()
5469 // TODO: again it's too heavy-weight
5470 EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
5471 ec.IsFieldInitializer = true;
5472 initializer = initializer.Resolve (ec);
5473 if (initializer == null)
5475 if (FieldBuilder == null)
5478 FieldExpr fe = new FieldExpr (FieldBuilder, Location, true);
5479 if ((ModFlags & Modifiers.STATIC) == 0)
5481 fe.InstanceExpression = CompilerGeneratedThis.Instance;
5484 initializerStatement = new Assign (fe, initializer, Location).ResolveStatement (ec);
5488 public bool HasDefaultInitializer
5492 Constant c = initializer as Constant;
5496 return c.IsDefaultInitializer (MemberType);
5500 public override string[] ValidAttributeTargets
5503 return attribute_targets;
5507 protected override bool VerifyClsCompliance ()
5509 if (!base.VerifyClsCompliance ())
5512 if (!IsFieldClsCompliant) {
5513 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5519 public void SetAssigned ()
5521 caching_flags |= Flags.IsAssigned;
5525 public abstract class FieldMember : FieldBase
5527 protected FieldMember (DeclSpace parent, Expression type, int mod,
5528 int allowed_mod, MemberName name, Attributes attrs)
5529 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, attrs)
5531 if ((mod & Modifiers.ABSTRACT) != 0)
5532 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5535 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5537 if (a.Type == TypeManager.field_offset_attribute_type)
5539 status |= Status.HAS_OFFSET;
5541 if (!Parent.PartialContainer.HasExplicitLayout) {
5542 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5546 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5547 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5553 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5554 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5559 base.ApplyAttributeBuilder (a, cb);
5562 public override bool Define()
5564 if (MemberType == null || Type == null)
5567 if (MemberType == TypeManager.void_type) {
5568 // TODO: wrong location
5569 Expression.Error_VoidInvalidInTheContext (Location);
5573 if (MemberType.IsSealed && MemberType.IsAbstract) {
5574 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5581 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5582 Report.Error (52, Location,
5583 "Inconsistent accessibility: field type `" +
5584 TypeManager.CSharpName (MemberType) + "' is less " +
5585 "accessible than field `" + GetSignatureForError () + "'");
5589 if (!IsTypePermitted ())
5595 public override void Emit ()
5597 if (OptAttributes != null) {
5598 OptAttributes.Emit ();
5601 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5602 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5608 public static void Error_VariableOfStaticClass (Location loc, string variableName, Type staticClass)
5610 Report.SymbolRelatedToPreviousError (staticClass);
5611 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5616 // Represents header string for documentation comment.
5618 public override string DocCommentHeader {
5619 get { return "F:"; }
5623 interface IFixedBuffer
5625 FieldInfo Element { get; }
5626 Type ElementType { get; }
5629 public class FixedFieldExternal: IFixedBuffer
5631 FieldInfo element_field;
5633 public FixedFieldExternal (FieldInfo fi)
5635 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5638 #region IFixedField Members
5640 public FieldInfo Element {
5642 return element_field;
5646 public Type ElementType {
5648 return element_field.FieldType;
5656 /// Fixed buffer implementation
5658 public class FixedField : FieldMember, IFixedBuffer
5660 public const string FixedElementName = "FixedElementField";
5661 static int GlobalCounter = 0;
5662 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5663 static FieldInfo[] fi;
5665 TypeBuilder fixed_buffer_type;
5666 FieldBuilder element;
5667 Expression size_expr;
5670 const int AllowedModifiers =
5673 Modifiers.PROTECTED |
5674 Modifiers.INTERNAL |
5677 public FixedField (DeclSpace parent, Expression type, int mod, string name,
5678 Expression size_expr, Attributes attrs, Location loc):
5679 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5681 if (RootContext.Version == LanguageVersion.ISO_1)
5682 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5684 this.size_expr = size_expr;
5687 public override bool Define()
5690 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5691 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5694 if (Parent.PartialContainer.Kind != Kind.Struct) {
5695 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5696 GetSignatureForError ());
5700 if (!base.Define ())
5703 if (!TypeManager.IsPrimitiveType (MemberType)) {
5704 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",
5705 GetSignatureForError ());
5709 EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
5710 Constant c = size_expr.ResolveAsConstant (ec, this);
5714 IntConstant buffer_size_const = c.ToInt (Location);
5715 if (buffer_size_const == null)
5718 buffer_size = buffer_size_const.Value;
5720 if (buffer_size <= 0) {
5721 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5725 int type_size = Expression.GetTypeSize (MemberType);
5727 if (buffer_size > int.MaxValue / type_size) {
5728 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5729 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5733 buffer_size *= type_size;
5736 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5738 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5739 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5740 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5741 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5743 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5744 TypeManager.RegisterFieldBase (FieldBuilder, this);
5749 public override void Emit()
5752 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5754 object[] fi_val = new object[1];
5755 fi_val [0] = buffer_size;
5757 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5758 ctor_args, fi, fi_val);
5759 fixed_buffer_type.SetCustomAttribute (cab);
5762 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5763 FieldBuilder.SetCustomAttribute (cab);
5768 protected override bool IsFieldClsCompliant {
5774 #region IFixedField Members
5776 public FieldInfo Element {
5782 public Type ElementType {
5792 // The Field class is used to represents class/struct fields during parsing.
5794 public class Field : FieldMember {
5796 // Modifiers allowed in a class declaration
5798 const int AllowedModifiers =
5801 Modifiers.PROTECTED |
5802 Modifiers.INTERNAL |
5805 Modifiers.VOLATILE |
5809 public Field (DeclSpace parent, Expression type, int mod, string name,
5810 Attributes attrs, Location loc)
5811 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5816 public override bool Define ()
5818 if (!base.Define ())
5821 if (RootContext.WarningLevel > 1){
5822 Type ptype = Parent.TypeBuilder.BaseType;
5824 // ptype is only null for System.Object while compiling corlib.
5826 TypeContainer.FindMembers (
5827 ptype, MemberTypes.Method,
5828 BindingFlags.Public |
5829 BindingFlags.Static | BindingFlags.Instance,
5830 System.Type.FilterName, Name);
5834 if ((ModFlags & Modifiers.VOLATILE) != 0){
5835 if (!MemberType.IsClass){
5836 Type vt = MemberType;
5838 if (TypeManager.IsEnumType (vt))
5839 vt = TypeManager.EnumToUnderlying (MemberType);
5841 if (!((vt == TypeManager.bool_type) ||
5842 (vt == TypeManager.sbyte_type) ||
5843 (vt == TypeManager.byte_type) ||
5844 (vt == TypeManager.short_type) ||
5845 (vt == TypeManager.ushort_type) ||
5846 (vt == TypeManager.int32_type) ||
5847 (vt == TypeManager.uint32_type) ||
5848 (vt == TypeManager.char_type) ||
5849 (vt == TypeManager.float_type) ||
5850 (!vt.IsValueType))){
5851 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5852 GetSignatureForError (), TypeManager.CSharpName (vt));
5857 if ((ModFlags & Modifiers.READONLY) != 0){
5858 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5859 GetSignatureForError ());
5864 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5866 if (Parent.PartialContainer.Kind == Kind.Struct &&
5867 ((fa & FieldAttributes.Static) == 0) &&
5868 MemberType == Parent.TypeBuilder &&
5869 !TypeManager.IsBuiltinType (MemberType)){
5870 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5871 "' causes a cycle in the structure layout");
5876 FieldBuilder = Parent.TypeBuilder.DefineField (
5877 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5879 TypeManager.RegisterFieldBase (FieldBuilder, this);
5881 catch (ArgumentException) {
5882 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5889 protected override bool VerifyClsCompliance ()
5891 if (!base.VerifyClsCompliance ())
5894 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5895 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5903 // `set' and `get' accessors are represented with an Accessor.
5905 public class Accessor : IIteratorContainer {
5907 // Null if the accessor is empty, or a Block if not
5909 public const int AllowedModifiers =
5911 Modifiers.PROTECTED |
5912 Modifiers.INTERNAL |
5915 public ToplevelBlock Block;
5916 public Attributes Attributes;
5917 public Location Location;
5918 public int ModFlags;
5921 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5926 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5929 public void SetYields ()
5935 // Ooouh Martin, templates are missing here.
5936 // When it will be possible move here a lot of child code and template method type.
5937 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5938 protected MethodData method_data;
5939 protected ToplevelBlock block;
5940 protected ListDictionary declarative_security;
5942 // The accessor are created event if they are not wanted.
5943 // But we need them because their names are reserved.
5944 // Field says whether accessor will be emited or not
5945 public readonly bool IsDummy;
5947 protected readonly string prefix;
5949 ReturnParameter return_attributes;
5951 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5952 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5954 this.prefix = prefix;
5958 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5960 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5961 accessor.Attributes)
5963 this.prefix = prefix;
5964 this.block = accessor.Block;
5967 static MemberName SetupName (string prefix, MemberBase member, Location loc)
5969 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5972 public void UpdateName (MemberBase member)
5974 SetMemberName (SetupName (prefix, member, Location));
5977 #region IMethodData Members
5979 public ToplevelBlock Block {
5989 public CallingConventions CallingConventions {
5991 return CallingConventions.Standard;
5995 public bool IsExcluded ()
6000 GenericMethod IMethodData.GenericMethod {
6006 public MemberName MethodName {
6012 public Type[] ParameterTypes {
6014 return ParameterInfo.Types;
6018 public abstract Parameters ParameterInfo { get ; }
6019 public abstract Type ReturnType { get; }
6020 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6024 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6026 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6027 a.Type == TypeManager.conditional_attribute_type) {
6028 Report.Error (1667, a.Location,
6029 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6030 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6034 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6035 if (declarative_security == null)
6036 declarative_security = new ListDictionary ();
6037 a.ExtractSecurityPermissionSet (declarative_security);
6041 if (a.Target == AttributeTargets.Method) {
6042 method_data.MethodBuilder.SetCustomAttribute (cb);
6046 if (a.Target == AttributeTargets.ReturnValue) {
6047 if (return_attributes == null)
6048 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6050 return_attributes.ApplyAttributeBuilder (a, cb);
6054 ApplyToExtraTarget (a, cb);
6057 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6059 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6062 public override bool Define()
6064 throw new NotSupportedException ();
6067 public void Emit (DeclSpace parent)
6069 EmitMethod (parent);
6071 if (OptAttributes != null)
6072 OptAttributes.Emit ();
6074 if (declarative_security != null) {
6075 foreach (DictionaryEntry de in declarative_security) {
6076 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6083 protected virtual void EmitMethod (DeclSpace parent)
6085 method_data.Emit (parent);
6088 public override bool IsClsComplianceRequired()
6093 public bool IsDuplicateImplementation (MethodCore method)
6095 if (!MemberName.Equals (method.MemberName))
6098 Type[] param_types = method.ParameterTypes;
6100 if (param_types.Length != ParameterTypes.Length)
6103 for (int i = 0; i < param_types.Length; i++)
6104 if (param_types [i] != ParameterTypes [i])
6107 Report.SymbolRelatedToPreviousError (method);
6108 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
6112 public override bool IsUsed
6122 public new Location Location {
6124 return base.Location;
6129 // Represents header string for documentation comment.
6131 public override string DocCommentHeader {
6132 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6138 // Properties and Indexers both generate PropertyBuilders, we use this to share
6139 // their common bits.
6141 abstract public class PropertyBase : MethodCore {
6143 public class GetMethod : PropertyMethod
6145 static string[] attribute_targets = new string [] { "method", "return" };
6147 public GetMethod (MethodCore method):
6148 base (method, "get_")
6152 public GetMethod (MethodCore method, Accessor accessor):
6153 base (method, accessor, "get_")
6157 public override MethodBuilder Define (DeclSpace parent)
6159 base.Define (parent);
6161 method_data = new MethodData (method, ModFlags, flags, this);
6163 if (!method_data.Define (parent))
6166 return method_data.MethodBuilder;
6169 public override Type ReturnType {
6171 return method.MemberType;
6175 public override Parameters ParameterInfo {
6177 return Parameters.EmptyReadOnlyParameters;
6181 public override string[] ValidAttributeTargets {
6183 return attribute_targets;
6188 public class SetMethod : PropertyMethod {
6190 static string[] attribute_targets = new string [] { "method", "param", "return" };
6191 ImplicitParameter param_attr;
6192 protected Parameters parameters;
6194 public SetMethod (MethodCore method):
6195 base (method, "set_")
6199 public SetMethod (MethodCore method, Accessor accessor):
6200 base (method, accessor, "set_")
6204 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6206 if (a.Target == AttributeTargets.Parameter) {
6207 if (param_attr == null)
6208 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6210 param_attr.ApplyAttributeBuilder (a, cb);
6214 base.ApplyAttributeBuilder (a, cb);
6217 public override Parameters ParameterInfo {
6223 protected virtual void DefineParameters ()
6225 parameters = new Parameters (
6226 new Parameter[] { new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location) },
6227 new Type[] { method.MemberType });
6230 public override MethodBuilder Define (DeclSpace parent)
6232 DefineParameters ();
6236 base.Define (parent);
6238 method_data = new MethodData (method, ModFlags, flags, this);
6240 if (!method_data.Define (parent))
6243 return method_data.MethodBuilder;
6246 public override Type ReturnType {
6248 return TypeManager.void_type;
6252 public override string[] ValidAttributeTargets {
6254 return attribute_targets;
6259 static string[] attribute_targets = new string [] { "property" };
6261 public abstract class PropertyMethod : AbstractPropertyEventMethod
6263 protected readonly MethodCore method;
6264 protected MethodAttributes flags;
6267 public PropertyMethod (MethodCore method, string prefix)
6268 : base (method, prefix)
6270 this.method = method;
6273 public PropertyMethod (MethodCore method, Accessor accessor,
6275 : base (method, accessor, prefix)
6277 this.method = method;
6278 this.ModFlags = accessor.ModFlags;
6279 yields = accessor.Yields;
6281 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6282 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6286 public override AttributeTargets AttributeTargets {
6288 return AttributeTargets.Method;
6292 public override bool IsClsComplianceRequired ()
6294 return method.IsClsComplianceRequired ();
6297 public virtual MethodBuilder Define (DeclSpace parent)
6299 if (!method.CheckAbstractAndExtern (block != null))
6302 TypeContainer container = parent.PartialContainer;
6305 // Check for custom access modifier
6307 if (ModFlags == 0) {
6308 ModFlags = method.ModFlags;
6309 flags = method.flags;
6311 if (container.Kind == Kind.Interface)
6312 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6313 GetSignatureForError ());
6315 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6316 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6319 CheckModifiers (ModFlags);
6320 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6321 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6322 flags = Modifiers.MethodAttr (ModFlags);
6323 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6327 // Setup iterator if we are one
6330 Iterator iterator = new Iterator (this, Parent as TypeContainer, null, ModFlags);
6332 if (!iterator.DefineIterator ())
6339 public bool HasCustomAccessModifier
6342 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6346 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6348 return new EmitContext (method,
6349 ds, method.ds, method.Location, ig, ReturnType,
6350 method.ModFlags, false);
6353 public override ObsoleteAttribute GetObsoleteAttribute ()
6355 return method.GetObsoleteAttribute ();
6358 public override string GetSignatureForError()
6360 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6363 void CheckModifiers (int modflags)
6366 int mflags = method.ModFlags & Modifiers.Accessibility;
6368 if ((mflags & Modifiers.PUBLIC) != 0) {
6369 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6371 else if ((mflags & Modifiers.PROTECTED) != 0) {
6372 if ((mflags & Modifiers.INTERNAL) != 0)
6373 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6375 flags |= Modifiers.PRIVATE;
6377 else if ((mflags & Modifiers.INTERNAL) != 0)
6378 flags |= Modifiers.PRIVATE;
6380 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6381 Report.Error (273, Location,
6382 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6383 GetSignatureForError (), method.GetSignatureForError ());
6387 public override bool MarkForDuplicationCheck ()
6389 caching_flags |= Flags.TestMethodDuplication;
6394 public PropertyMethod Get, Set;
6395 public PropertyBuilder PropertyBuilder;
6396 public MethodBuilder GetBuilder, SetBuilder;
6398 protected EmitContext ec;
6400 public PropertyBase (DeclSpace parent, Expression type, int mod_flags,
6401 int allowed_mod, bool is_iface, MemberName name,
6402 Parameters parameters, Attributes attrs)
6403 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6408 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6410 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6411 a.Error_InvalidSecurityParent ();
6415 PropertyBuilder.SetCustomAttribute (cb);
6418 public override AttributeTargets AttributeTargets {
6420 return AttributeTargets.Property;
6424 public override bool Define ()
6429 if (!IsTypePermitted ())
6435 protected override bool DoDefine ()
6437 if (!base.DoDefine ())
6441 // Accessors modifiers check
6443 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6444 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6445 GetSignatureForError ());
6449 if ((Get.IsDummy || Set.IsDummy)
6450 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6451 Report.Error (276, Location,
6452 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6453 GetSignatureForError ());
6457 if (MemberType.IsAbstract && MemberType.IsSealed) {
6458 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6462 ec = new EmitContext (this, Parent, Location, null, MemberType, ModFlags);
6466 protected override bool CheckForDuplications ()
6468 ArrayList ar = Parent.PartialContainer.Indexers;
6470 int arLen = ar.Count;
6472 for (int i = 0; i < arLen; i++) {
6473 Indexer m = (Indexer) ar [i];
6474 if (IsDuplicateImplementation (m))
6479 ar = Parent.PartialContainer.Properties;
6481 int arLen = ar.Count;
6483 for (int i = 0; i < arLen; i++) {
6484 Property m = (Property) ar [i];
6485 if (IsDuplicateImplementation (m))
6493 // TODO: rename to Resolve......
6494 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6496 PropertyInfo base_property = Parent.PartialContainer.BaseCache.FindMemberToOverride (
6497 Parent.TypeBuilder, Name, ParameterTypes, null, true) as PropertyInfo;
6499 if (base_property == null)
6502 base_ret_type = base_property.PropertyType;
6503 MethodInfo get_accessor = base_property.GetGetMethod (true);
6504 MethodInfo set_accessor = base_property.GetSetMethod (true);
6505 MethodAttributes get_accessor_access, set_accessor_access;
6507 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6508 if (Get != null && !Get.IsDummy && get_accessor == null) {
6509 Report.SymbolRelatedToPreviousError (base_property);
6510 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6513 if (Set != null && !Set.IsDummy && set_accessor == null) {
6514 Report.SymbolRelatedToPreviousError (base_property);
6515 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6520 // Check base class accessors access
6523 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6524 get_accessor_access = set_accessor_access = 0;
6525 if ((ModFlags & Modifiers.NEW) == 0) {
6526 if (get_accessor != null) {
6527 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6528 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6530 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6531 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6534 if (set_accessor != null) {
6535 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6536 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6538 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6539 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6544 // Get the less restrictive access
6546 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6549 public override void Emit ()
6552 // The PropertyBuilder can be null for explicit implementations, in that
6553 // case, we do not actually emit the ".property", so there is nowhere to
6554 // put the attribute
6556 if (PropertyBuilder != null && OptAttributes != null)
6557 OptAttributes.Emit ();
6569 /// Tests whether accessors are not in collision with some method (CS0111)
6571 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6573 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6576 public override bool IsUsed
6582 return Get.IsUsed | Set.IsUsed;
6586 protected override void SetMemberName (MemberName new_name)
6588 base.SetMemberName (new_name);
6590 Get.UpdateName (this);
6591 Set.UpdateName (this);
6594 public override string[] ValidAttributeTargets {
6596 return attribute_targets;
6601 // Represents header string for documentation comment.
6603 public override string DocCommentHeader {
6604 get { return "P:"; }
6608 public class Property : PropertyBase {
6609 const int AllowedModifiers =
6612 Modifiers.PROTECTED |
6613 Modifiers.INTERNAL |
6617 Modifiers.OVERRIDE |
6618 Modifiers.ABSTRACT |
6621 Modifiers.METHOD_YIELDS |
6624 const int AllowedInterfaceModifiers =
6627 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6628 MemberName name, Attributes attrs, Accessor get_block,
6630 : base (parent, type, mod,
6631 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6632 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6634 if (get_block == null)
6635 Get = new GetMethod (this);
6637 Get = new GetMethod (this, get_block);
6639 if (set_block == null)
6640 Set = new SetMethod (this);
6642 Set = new SetMethod (this, set_block);
6645 public override bool Define ()
6647 if (!DoDefineBase ())
6650 if (!base.Define ())
6656 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6659 GetBuilder = Get.Define (Parent);
6660 if (GetBuilder == null)
6664 SetBuilder = Set.Define (Parent);
6666 if (SetBuilder == null)
6670 // FIXME - PropertyAttributes.HasDefault ?
6672 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6673 MemberName.ToString (), PropertyAttributes.None, MemberType, null);
6676 PropertyBuilder.SetGetMethod (GetBuilder);
6679 PropertyBuilder.SetSetMethod (SetBuilder);
6681 TypeManager.RegisterProperty (PropertyBuilder, this);
6687 /// Gigantic workaround for lameness in SRE follows :
6688 /// This class derives from EventInfo and attempts to basically
6689 /// wrap around the EventBuilder so that FindMembers can quickly
6690 /// return this in it search for members
6692 public class MyEventBuilder : EventInfo {
6695 // We use this to "point" to our Builder which is
6696 // not really a MemberInfo
6698 EventBuilder MyBuilder;
6701 // We "catch" and wrap these methods
6703 MethodInfo raise, remove, add;
6705 EventAttributes attributes;
6706 Type declaring_type, reflected_type, event_type;
6711 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6713 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6715 // And now store the values in our own fields.
6717 declaring_type = type_builder;
6719 reflected_type = type_builder;
6721 attributes = event_attr;
6724 this.event_type = event_type;
6728 // Methods that you have to override. Note that you only need
6729 // to "implement" the variants that take the argument (those are
6730 // the "abstract" methods, the others (GetAddMethod()) are
6733 public override MethodInfo GetAddMethod (bool nonPublic)
6738 public override MethodInfo GetRemoveMethod (bool nonPublic)
6743 public override MethodInfo GetRaiseMethod (bool nonPublic)
6749 // These methods make "MyEventInfo" look like a Builder
6751 public void SetRaiseMethod (MethodBuilder raiseMethod)
6753 raise = raiseMethod;
6754 MyBuilder.SetRaiseMethod (raiseMethod);
6757 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6759 remove = removeMethod;
6760 MyBuilder.SetRemoveOnMethod (removeMethod);
6763 public void SetAddOnMethod (MethodBuilder addMethod)
6766 MyBuilder.SetAddOnMethod (addMethod);
6769 public void SetCustomAttribute (CustomAttributeBuilder cb)
6771 MyBuilder.SetCustomAttribute (cb);
6774 public override object [] GetCustomAttributes (bool inherit)
6776 // FIXME : There's nothing which can be seemingly done here because
6777 // we have no way of getting at the custom attribute objects of the
6782 public override object [] GetCustomAttributes (Type t, bool inherit)
6784 // FIXME : Same here !
6788 public override bool IsDefined (Type t, bool b)
6793 public override EventAttributes Attributes {
6799 public override string Name {
6805 public override Type DeclaringType {
6807 return declaring_type;
6811 public override Type ReflectedType {
6813 return reflected_type;
6817 public Type EventType {
6823 public void SetUsed ()
6825 if (my_event != null) {
6826 my_event.SetAssigned ();
6827 my_event.SetMemberIsUsed ();
6833 /// For case when event is declared like property (with add and remove accessors).
6835 public class EventProperty: Event {
6837 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6839 public EventProperty (DeclSpace parent, Expression type, int mod_flags,
6840 bool is_iface, MemberName name,
6841 Attributes attrs, Accessor add, Accessor remove)
6842 : base (parent, type, mod_flags, is_iface, name, attrs)
6844 Add = new AddDelegateMethod (this, add);
6845 Remove = new RemoveDelegateMethod (this, remove);
6847 // For this event syntax we don't report error CS0067
6848 // because it is hard to do it.
6852 public override string[] ValidAttributeTargets {
6854 return attribute_targets;
6860 /// Event is declared like field.
6862 public class EventField : Event {
6864 static string[] attribute_targets = new string [] { "event", "field", "method" };
6865 static string[] attribute_targets_interface = new string[] { "event", "method" };
6867 public EventField (DeclSpace parent, Expression type, int mod_flags,
6868 bool is_iface, MemberName name,
6870 : base (parent, type, mod_flags, is_iface, name, attrs)
6872 Add = new AddDelegateMethod (this);
6873 Remove = new RemoveDelegateMethod (this);
6876 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6878 if (a.Target == AttributeTargets.Field) {
6879 FieldBuilder.SetCustomAttribute (cb);
6883 if (a.Target == AttributeTargets.Method) {
6884 int errors = Report.Errors;
6885 Add.ApplyAttributeBuilder (a, cb);
6886 if (errors == Report.Errors)
6887 Remove.ApplyAttributeBuilder (a, cb);
6891 base.ApplyAttributeBuilder (a, cb);
6894 public override bool Define()
6896 if (!base.Define ())
6899 if (initializer != null) {
6900 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
6901 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
6902 GetSignatureForError ());
6910 public override string[] ValidAttributeTargets {
6912 return IsInterface ? attribute_targets_interface : attribute_targets;
6917 public abstract class Event : FieldBase {
6919 protected sealed class AddDelegateMethod: DelegateMethod
6922 public AddDelegateMethod (Event method):
6923 base (method, "add_")
6927 public AddDelegateMethod (Event method, Accessor accessor):
6928 base (method, accessor, "add_")
6932 protected override MethodInfo DelegateMethodInfo {
6934 return TypeManager.delegate_combine_delegate_delegate;
6940 protected sealed class RemoveDelegateMethod: DelegateMethod
6942 public RemoveDelegateMethod (Event method):
6943 base (method, "remove_")
6947 public RemoveDelegateMethod (Event method, Accessor accessor):
6948 base (method, accessor, "remove_")
6952 protected override MethodInfo DelegateMethodInfo {
6954 return TypeManager.delegate_remove_delegate_delegate;
6960 public abstract class DelegateMethod : AbstractPropertyEventMethod
6962 protected readonly Event method;
6963 ImplicitParameter param_attr;
6965 static string[] attribute_targets = new string [] { "method", "param", "return" };
6967 public DelegateMethod (Event method, string prefix)
6968 : base (method, prefix)
6970 this.method = method;
6973 public DelegateMethod (Event method, Accessor accessor, string prefix)
6974 : base (method, accessor, prefix)
6976 this.method = method;
6979 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6981 if (a.Target == AttributeTargets.Parameter) {
6982 if (param_attr == null)
6983 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6985 param_attr.ApplyAttributeBuilder (a, cb);
6989 base.ApplyAttributeBuilder (a, cb);
6992 public override AttributeTargets AttributeTargets {
6994 return AttributeTargets.Method;
6998 public override bool IsClsComplianceRequired ()
7000 return method.IsClsComplianceRequired ();
7003 public MethodBuilder Define (DeclSpace parent)
7005 method_data = new MethodData (method, method.ModFlags,
7006 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7008 if (!method_data.Define (parent))
7011 MethodBuilder mb = method_data.MethodBuilder;
7012 ParameterInfo.ApplyAttributes (mb);
7017 protected override void EmitMethod (DeclSpace parent)
7019 if (block != null) {
7020 base.EmitMethod (parent);
7024 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7027 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
7028 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
7030 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
7031 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7032 ig.Emit (OpCodes.Ldsfld, field_info);
7033 ig.Emit (OpCodes.Ldarg_0);
7034 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7035 ig.Emit (OpCodes.Castclass, method.MemberType);
7036 ig.Emit (OpCodes.Stsfld, field_info);
7038 ig.Emit (OpCodes.Ldarg_0);
7039 ig.Emit (OpCodes.Ldarg_0);
7040 ig.Emit (OpCodes.Ldfld, field_info);
7041 ig.Emit (OpCodes.Ldarg_1);
7042 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7043 ig.Emit (OpCodes.Castclass, method.MemberType);
7044 ig.Emit (OpCodes.Stfld, field_info);
7046 ig.Emit (OpCodes.Ret);
7049 protected abstract MethodInfo DelegateMethodInfo { get; }
7051 public override Type ReturnType {
7053 return TypeManager.void_type;
7057 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7059 return new EmitContext (
7060 ds, method.Parent, Location, ig, ReturnType,
7061 method.ModFlags, false);
7064 public override ObsoleteAttribute GetObsoleteAttribute ()
7066 return method.GetObsoleteAttribute ();
7069 public override string[] ValidAttributeTargets {
7071 return attribute_targets;
7075 public override Parameters ParameterInfo {
7077 return method.parameters;
7084 const int AllowedModifiers =
7087 Modifiers.PROTECTED |
7088 Modifiers.INTERNAL |
7093 Modifiers.OVERRIDE |
7097 const int AllowedInterfaceModifiers =
7100 public DelegateMethod Add, Remove;
7101 public MyEventBuilder EventBuilder;
7102 public MethodBuilder AddBuilder, RemoveBuilder;
7103 Parameters parameters;
7105 protected Event (DeclSpace parent, Expression type, int mod_flags,
7106 bool is_iface, MemberName name, Attributes attrs)
7107 : base (parent, type, mod_flags,
7108 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7111 IsInterface = is_iface;
7114 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7116 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7117 a.Error_InvalidSecurityParent ();
7121 EventBuilder.SetCustomAttribute (cb);
7124 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7126 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7129 public override AttributeTargets AttributeTargets {
7131 return AttributeTargets.Event;
7135 public override bool Define ()
7137 EventAttributes e_attr;
7138 e_attr = EventAttributes.None;
7140 if (!DoDefineBase ())
7146 if (!TypeManager.IsDelegateType (MemberType)) {
7147 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7151 parameters = new Parameters (
7152 new Parameter[] { new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location) },
7153 new Type[] { MemberType } );
7159 // Now define the accessors
7162 AddBuilder = Add.Define (Parent);
7163 if (AddBuilder == null)
7166 RemoveBuilder = Remove.Define (Parent);
7167 if (RemoveBuilder == null)
7170 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7172 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7173 FieldBuilder = Parent.TypeBuilder.DefineField (
7175 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7176 TypeManager.RegisterPrivateFieldOfEvent (
7177 (EventInfo) EventBuilder, FieldBuilder);
7178 TypeManager.RegisterFieldBase (FieldBuilder, this);
7181 EventBuilder.SetAddOnMethod (AddBuilder);
7182 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7184 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7188 protected override bool CheckBase ()
7190 if (!base.CheckBase ())
7193 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7194 if (!(conflict_symbol is EventInfo)) {
7195 Report.SymbolRelatedToPreviousError (conflict_symbol);
7196 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
7204 public override void Emit ()
7206 if (OptAttributes != null) {
7207 OptAttributes.Emit ();
7211 Remove.Emit (Parent);
7216 public override string GetSignatureForError ()
7218 return base.GetSignatureForError ();
7222 // Represents header string for documentation comment.
7224 public override string DocCommentHeader {
7225 get { return "E:"; }
7230 public class Indexer : PropertyBase, IIteratorContainer {
7232 class GetIndexerMethod : GetMethod
7234 public GetIndexerMethod (MethodCore method):
7239 public GetIndexerMethod (MethodCore method, Accessor accessor):
7240 base (method, accessor)
7244 public override Parameters ParameterInfo {
7246 return method.ParameterInfo;
7251 class SetIndexerMethod: SetMethod
7253 public SetIndexerMethod (MethodCore method):
7258 public SetIndexerMethod (MethodCore method, Accessor accessor):
7259 base (method, accessor)
7263 protected override void DefineParameters ()
7265 parameters = Parameters.MergeGenerated (method.Parameters,
7266 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7270 const int AllowedModifiers =
7273 Modifiers.PROTECTED |
7274 Modifiers.INTERNAL |
7278 Modifiers.OVERRIDE |
7283 const int AllowedInterfaceModifiers =
7287 public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
7288 bool is_iface, Parameters parameters, Attributes attrs,
7289 Accessor get_block, Accessor set_block)
7290 : base (parent, type, mod,
7291 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7292 is_iface, name, parameters, attrs)
7294 if (get_block == null)
7295 Get = new GetIndexerMethod (this);
7297 Get = new GetIndexerMethod (this, get_block);
7299 if (set_block == null)
7300 Set = new SetIndexerMethod (this);
7302 Set = new SetIndexerMethod (this, set_block);
7305 public override bool Define ()
7307 if (!DoDefineBase ())
7310 if (!base.Define ())
7313 if (MemberType == TypeManager.void_type) {
7314 Report.Error (620, Location, "Indexers cannot have void type");
7318 if (OptAttributes != null) {
7319 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7320 if (indexer_attr != null) {
7321 // Remove the attribute from the list because it is not emitted
7322 OptAttributes.Attrs.Remove (indexer_attr);
7324 string name = indexer_attr.GetIndexerAttributeValue ();
7330 if (IsExplicitImpl) {
7331 Report.Error (415, indexer_attr.Location,
7332 "The `IndexerName' attribute is valid only on an " +
7333 "indexer that is not an explicit interface member declaration");
7337 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7338 Report.Error (609, indexer_attr.Location,
7339 "Cannot set the `IndexerName' attribute on an indexer marked override");
7345 if (InterfaceType != null) {
7346 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7347 if (base_IndexerName != Name)
7348 ShortName = base_IndexerName;
7351 if (!Parent.PartialContainer.AddMember (this) ||
7352 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7358 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7360 GetBuilder = Get.Define (Parent);
7361 if (GetBuilder == null)
7365 // Setup iterator if we are one
7367 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7368 Iterator iterator = new Iterator (
7369 Get, Parent, null, ModFlags);
7371 if (!iterator.DefineIterator ())
7376 SetBuilder = Set.Define (Parent);
7378 if (SetBuilder == null)
7383 // Now name the parameters
7385 Parameter [] p = Parameters.FixedParameters;
7387 // TODO: should be done in parser and it needs to do cycle
7388 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7389 Report.Error (631, Location, "ref and out are not valid in this context");
7394 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7395 Name, PropertyAttributes.None, MemberType, ParameterTypes);
7398 PropertyBuilder.SetGetMethod (GetBuilder);
7401 PropertyBuilder.SetSetMethod (SetBuilder);
7403 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7408 public override string GetSignatureForError ()
7410 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7411 if (MemberName.Left != null) {
7413 sb.Append (MemberName.Left);
7416 sb.Append (".this");
7417 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7418 return sb.ToString ();
7421 public override bool MarkForDuplicationCheck ()
7423 caching_flags |= Flags.TestMethodDuplication;
7428 public class Operator : MethodOrOperator, IIteratorContainer {
7430 const int AllowedModifiers =
7436 public enum OpType : byte {
7446 // Unary and Binary operators
7469 // Implicit and Explicit
7473 // Just because of enum
7477 public readonly OpType OperatorType;
7479 public Operator (DeclSpace parent, OpType type, Expression ret_type,
7480 int mod_flags, Parameters parameters,
7481 ToplevelBlock block, Attributes attrs, Location loc)
7482 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7483 new MemberName ("op_" + type, loc), attrs, parameters)
7485 OperatorType = type;
7489 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7491 if (a.Type == TypeManager.conditional_attribute_type) {
7492 Error_ConditionalAttributeIsNotValid ();
7496 base.ApplyAttributeBuilder (a, cb);
7499 protected override bool CheckForDuplications ()
7501 ArrayList ar = Parent.PartialContainer.Operators;
7503 int arLen = ar.Count;
7505 for (int i = 0; i < arLen; i++) {
7506 Operator o = (Operator) ar [i];
7507 if (IsDuplicateImplementation (o))
7512 ar = Parent.PartialContainer.Methods;
7514 int arLen = ar.Count;
7516 for (int i = 0; i < arLen; i++) {
7517 Method m = (Method) ar [i];
7518 if (IsDuplicateImplementation (m))
7526 public override bool Define ()
7528 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7529 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7530 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7534 if (!base.Define ())
7537 if (MemberType == TypeManager.void_type) {
7538 Report.Error (590, Location, "User-defined operators cannot return void");
7542 Type declaring_type = MethodData.DeclaringType;
7543 Type return_type = MemberType;
7544 Type first_arg_type = ParameterTypes [0];
7546 // Rules for conversion operators
7548 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7549 if (first_arg_type == return_type && first_arg_type == declaring_type){
7550 Report.Error (555, Location,
7551 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7555 if ((first_arg_type != declaring_type) && (return_type != declaring_type) &&
7556 !TypeManager.IsNullableTypeOf (first_arg_type, declaring_type) &&
7557 !TypeManager.IsNullableTypeOf (return_type, declaring_type)) {
7560 "User-defined conversion must convert to or from the " +
7565 if (first_arg_type.IsInterface || return_type.IsInterface){
7566 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7567 GetSignatureForError ());
7571 if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type)) {
7572 if (declaring_type.IsSubclassOf (return_type) || declaring_type.IsSubclassOf (first_arg_type)) {
7573 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7574 GetSignatureForError ());
7577 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7578 GetSignatureForError ());
7581 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7582 if (first_arg_type != declaring_type || ParameterTypes [1] != TypeManager.int32_type) {
7583 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");
7586 } else if (Parameters.Count == 1) {
7587 // Checks for Unary operators
7589 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7590 if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7591 Report.Error (448, Location,
7592 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7595 if (first_arg_type != declaring_type) {
7597 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7602 if (first_arg_type != declaring_type){
7605 "The parameter of a unary operator must be the " +
7610 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7611 if (return_type != TypeManager.bool_type){
7614 "The return type of operator True or False " +
7621 // Checks for Binary operators
7623 if (first_arg_type != declaring_type &&
7624 ParameterTypes [1] != declaring_type){
7627 "One of the parameters of a binary operator must " +
7628 "be the containing type");
7636 protected override bool DoDefine ()
7638 if (!base.DoDefine ())
7641 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7645 public override void Emit ()
7649 Parameters.ApplyAttributes (MethodBuilder);
7652 // abstract or extern methods have no bodies
7654 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7658 if ((flags & MethodAttributes.PinvokeImpl) == 0)
7659 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7661 ec = CreateEmitContext (Parent, null);
7663 SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7664 ec.EmitTopBlock (this, Block);
7667 source.CloseMethod ();
7672 // Operator cannot be override
7673 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7678 public static string GetName (OpType ot)
7681 case OpType.LogicalNot:
7683 case OpType.OnesComplement:
7685 case OpType.Increment:
7687 case OpType.Decrement:
7693 case OpType.Addition:
7695 case OpType.Subtraction:
7697 case OpType.UnaryPlus:
7699 case OpType.UnaryNegation:
7701 case OpType.Multiply:
7703 case OpType.Division:
7705 case OpType.Modulus:
7707 case OpType.BitwiseAnd:
7709 case OpType.BitwiseOr:
7711 case OpType.ExclusiveOr:
7713 case OpType.LeftShift:
7715 case OpType.RightShift:
7717 case OpType.Equality:
7719 case OpType.Inequality:
7721 case OpType.GreaterThan:
7723 case OpType.LessThan:
7725 case OpType.GreaterThanOrEqual:
7727 case OpType.LessThanOrEqual:
7729 case OpType.Implicit:
7731 case OpType.Explicit:
7737 public static OpType GetOperatorType (string name)
7739 if (name.StartsWith ("op_")){
7740 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7741 if (Unary.oper_names [i] == name)
7745 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7746 if (Binary.oper_names [i] == name)
7753 public override string GetSignatureForError ()
7755 StringBuilder sb = new StringBuilder ();
7756 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7757 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7760 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7763 sb.Append (Parameters.GetSignatureForError ());
7764 return sb.ToString ();
7769 // This is used to compare method signatures
7771 struct MethodSignature {
7773 public Type RetType;
7774 public Type [] Parameters;
7777 /// This delegate is used to extract methods which have the
7778 /// same signature as the argument
7780 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7782 public MethodSignature (string name, Type ret_type, Type [] parameters)
7787 if (parameters == null)
7788 Parameters = Type.EmptyTypes;
7790 Parameters = parameters;
7793 public override string ToString ()
7796 if (Parameters.Length != 0){
7797 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7798 for (int i = 0; i < Parameters.Length; i++){
7799 sb.Append (Parameters [i]);
7800 if (i+1 < Parameters.Length)
7803 pars = sb.ToString ();
7806 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7809 public override int GetHashCode ()
7811 return Name.GetHashCode ();
7814 public override bool Equals (Object o)
7816 MethodSignature other = (MethodSignature) o;
7818 if (other.Name != Name)
7821 if (other.RetType != RetType)
7824 if (Parameters == null){
7825 if (other.Parameters == null)
7830 if (other.Parameters == null)
7833 int c = Parameters.Length;
7834 if (other.Parameters.Length != c)
7837 for (int i = 0; i < c; i++)
7838 if (other.Parameters [i] != Parameters [i])
7844 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7846 MethodSignature sig = (MethodSignature) filter_criteria;
7848 if (m.Name != sig.Name)
7852 MethodInfo mi = m as MethodInfo;
7853 PropertyInfo pi = m as PropertyInfo;
7856 ReturnType = mi.ReturnType;
7857 else if (pi != null)
7858 ReturnType = pi.PropertyType;
7863 // we use sig.RetType == null to mean `do not check the
7864 // method return value.
7866 if (sig.RetType != null)
7867 if (ReturnType != sig.RetType)
7872 args = TypeManager.GetParameterData (mi).Types;
7874 args = TypeManager.GetArgumentTypes (pi);
7875 Type [] sigp = sig.Parameters;
7877 if (args.Length != sigp.Length)
7880 for (int i = args.Length; i > 0; ){
7882 if (args [i] != sigp [i])