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.
36 using System.Collections;
37 using System.Collections.Specialized;
38 using System.Reflection;
39 using System.Reflection.Emit;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42 using System.Security;
43 using System.Security.Permissions;
46 using Mono.CompilerServices.SymbolWriter;
48 namespace Mono.CSharp {
58 /// This is the base class for structs and classes.
60 public abstract class TypeContainer : DeclSpace, IMemberContainer {
62 public class MemberCoreArrayList: ArrayList
65 /// Defines the MemberCore objects that are in this array
67 public virtual void DefineContainerMembers ()
69 foreach (MemberCore mc in this) {
74 public virtual void Emit ()
76 foreach (MemberCore mc in this)
81 public class MethodArrayList : MemberCoreArrayList
89 CachedMethods cached_method;
90 TypeContainer container;
92 public MethodArrayList (TypeContainer container)
94 this.container = container;
98 /// Method container contains Equals method
100 public bool HasEquals {
102 cached_method |= CachedMethods.Equals;
106 return (cached_method & CachedMethods.Equals) != 0;
111 /// Method container contains GetHashCode method
113 public bool HasGetHashCode {
115 cached_method |= CachedMethods.GetHashCode;
119 return (cached_method & CachedMethods.GetHashCode) != 0;
123 public override void DefineContainerMembers ()
125 base.DefineContainerMembers ();
127 if (HasEquals && !HasGetHashCode) {
128 Report.Warning (659, 3, container.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
134 public sealed class IndexerArrayList : MemberCoreArrayList
137 /// The indexer name for this container
139 public string IndexerName = DefaultIndexerName;
141 bool seen_normal_indexers = false;
143 TypeContainer container;
145 public IndexerArrayList (TypeContainer container)
147 this.container = container;
151 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
152 /// class is consistent. Either it is `Item' or it is the name defined by all the
153 /// indexers with the `IndexerName' attribute.
155 /// Turns out that the IndexerNameAttribute is applied to each indexer,
156 /// but it is never emitted, instead a DefaultMember attribute is attached
159 public override void DefineContainerMembers()
161 base.DefineContainerMembers ();
163 string class_indexer_name = null;
166 // If there's both an explicit and an implicit interface implementation, the
167 // explicit one actually implements the interface while the other one is just
168 // a normal indexer. See bug #37714.
171 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
172 foreach (Indexer i in this) {
173 if (i.InterfaceType != null) {
174 if (seen_normal_indexers)
175 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
179 seen_normal_indexers = true;
181 if (class_indexer_name == null) {
182 class_indexer_name = i.ShortName;
186 if (i.ShortName != class_indexer_name)
187 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");
190 if (class_indexer_name != null)
191 IndexerName = class_indexer_name;
194 public override void Emit ()
198 if (!seen_normal_indexers)
201 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
202 container.TypeBuilder.SetCustomAttribute (cb);
206 public class OperatorArrayList: MemberCoreArrayList
208 TypeContainer container;
210 public OperatorArrayList (TypeContainer container)
212 this.container = container;
216 // Operator pair checking
221 public Type ret_type;
222 public Type type1, type2;
224 public Operator.OpType ot;
226 public OperatorEntry (int f, Operator o)
230 ret_type = o.OperatorMethod.ReturnType;
231 Type [] pt = o.OperatorMethod.ParameterTypes;
238 public override int GetHashCode ()
240 return ret_type.GetHashCode ();
243 public override bool Equals (object o)
245 OperatorEntry other = (OperatorEntry) o;
247 if (other.ret_type != ret_type)
249 if (other.type1 != type1)
251 if (other.type2 != type2)
258 // Checks that some operators come in pairs:
264 // They are matched based on the return type and the argument types
266 void CheckPairedOperators ()
268 IDictionary pairs = new HybridDictionary ();
269 Operator true_op = null;
270 Operator false_op = null;
271 bool has_equality_or_inequality = false;
273 // Register all the operators we care about.
274 foreach (Operator op in this){
277 // Skip erroneous code.
278 if (op.OperatorMethod == null)
281 switch (op.OperatorType){
282 case Operator.OpType.Equality:
284 has_equality_or_inequality = true;
286 case Operator.OpType.Inequality:
288 has_equality_or_inequality = true;
291 case Operator.OpType.True:
294 case Operator.OpType.False:
298 case Operator.OpType.GreaterThan:
300 case Operator.OpType.LessThan:
303 case Operator.OpType.GreaterThanOrEqual:
305 case Operator.OpType.LessThanOrEqual:
311 OperatorEntry oe = new OperatorEntry (reg, op);
313 object o = pairs [oe];
317 oe = (OperatorEntry) o;
322 if (true_op != null){
323 if (false_op == null)
324 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
325 true_op.GetSignatureForError ());
326 } else if (false_op != null)
327 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
328 false_op.GetSignatureForError ());
331 // Look for the mistakes.
333 foreach (DictionaryEntry de in pairs){
334 OperatorEntry oe = (OperatorEntry) de.Key;
341 case Operator.OpType.Equality:
344 case Operator.OpType.Inequality:
347 case Operator.OpType.GreaterThan:
350 case Operator.OpType.LessThan:
353 case Operator.OpType.GreaterThanOrEqual:
356 case Operator.OpType.LessThanOrEqual:
360 Report.Error (216, oe.op.Location,
361 "The operator `{0}' requires a matching operator `{1}' to also be defined",
362 oe.op.GetSignatureForError (), s);
365 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
366 if (container.Methods == null || !container.Methods.HasEquals)
367 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
369 if (container.Methods == null || !container.Methods.HasGetHashCode)
370 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
374 public override void DefineContainerMembers ()
376 base.DefineContainerMembers ();
377 CheckPairedOperators ();
382 // Whether this is a struct, class or interface
383 public readonly Kind Kind;
385 // Holds a list of classes and structures
388 // Holds the list of properties
389 MemberCoreArrayList properties;
391 // Holds the list of enumerations
392 MemberCoreArrayList enums;
394 // Holds the list of delegates
395 MemberCoreArrayList delegates;
397 // Holds the list of constructors
398 protected MemberCoreArrayList instance_constructors;
400 // Holds the list of fields
401 MemberCoreArrayList fields;
403 // Holds a list of fields that have initializers
404 protected ArrayList initialized_fields;
406 // Holds a list of static fields that have initializers
407 protected ArrayList initialized_static_fields;
409 // Holds the list of constants
410 MemberCoreArrayList constants;
413 MemberCoreArrayList interfaces;
415 // Holds the methods.
416 MethodArrayList methods;
419 protected MemberCoreArrayList events;
421 // Holds the indexers
422 IndexerArrayList indexers;
424 // Holds the operators
425 MemberCoreArrayList operators;
427 // Holds the iterators
430 // Holds the parts of a partial class;
434 // Pointers to the default constructor and the default static constructor
436 protected Constructor default_constructor;
437 protected Constructor default_static_constructor;
440 // Points to the first non-static field added to the container.
442 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
443 // and the first one's as good as any.
445 FieldBase first_nonstatic_field = null;
448 // This one is computed after we can distinguish interfaces
449 // from classes from the arraylist `type_bases'
451 string base_class_name;
453 TypeExpr[] iface_exprs;
455 ArrayList type_bases;
457 bool members_defined;
458 bool members_defined_ok;
460 // The interfaces we implement.
461 protected Type[] ifaces;
462 protected Type ptype;
464 // The base member cache and our member cache
465 MemberCache base_cache;
466 MemberCache member_cache;
468 public const string DefaultIndexerName = "Item";
471 GenericTypeParameterBuilder[] gen_params;
473 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
474 Attributes attrs, Kind kind)
475 : base (ns, parent, name, attrs)
477 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
478 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
482 types = new ArrayList ();
484 base_class_name = null;
487 public bool AddToMemberContainer (MemberCore symbol)
489 return AddToContainer (symbol, symbol.Name);
492 protected virtual bool AddToTypeContainer (DeclSpace ds)
494 return AddToContainer (ds, ds.Basename);
497 public void AddConstant (Const constant)
499 if (!AddToMemberContainer (constant))
502 if (constants == null)
503 constants = new MemberCoreArrayList ();
505 constants.Add (constant);
508 public void AddEnum (Mono.CSharp.Enum e)
510 if (!AddToTypeContainer (e))
514 enums = new MemberCoreArrayList ();
519 public bool AddClassOrStruct (TypeContainer c)
521 if (!AddToTypeContainer (c))
528 public void AddDelegate (Delegate d)
530 if (!AddToTypeContainer (d))
533 if (delegates == null)
534 delegates = new MemberCoreArrayList ();
539 public void AddMethod (Method method)
541 if (!AddToMemberContainer (method))
545 methods = new MethodArrayList (this);
547 if (method.MemberName.Left != null)
548 methods.Insert (0, method);
550 methods.Add (method);
553 public void AddConstructor (Constructor c)
555 if (c.Name != MemberName.Name) {
556 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
559 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
562 if (default_static_constructor != null) {
563 Report.SymbolRelatedToPreviousError (default_static_constructor);
564 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
568 default_static_constructor = c;
571 if (default_constructor != null) {
572 Report.SymbolRelatedToPreviousError (default_constructor);
573 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
576 default_constructor = c;
579 if (instance_constructors == null)
580 instance_constructors = new MemberCoreArrayList ();
582 instance_constructors.Add (c);
586 internal static string Error111 {
588 return "`{0}' is already defined. Rename this member or use different parameter types";
592 public bool AddInterface (TypeContainer iface)
594 if (!AddToTypeContainer (iface))
597 if (interfaces == null) {
598 interfaces = new MemberCoreArrayList ();
601 interfaces.Add (iface);
605 public void AddField (FieldMember field)
607 if (!AddToMemberContainer (field))
611 fields = new MemberCoreArrayList ();
615 if (field.HasInitializer)
616 RegisterFieldForInitialization (field);
618 if ((field.ModFlags & Modifiers.STATIC) != 0)
621 if (first_nonstatic_field == null) {
622 first_nonstatic_field = field;
626 if (Kind == Kind.Struct &&
627 first_nonstatic_field.Parent != field.Parent &&
628 RootContext.WarningLevel >= 3) {
629 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
630 Report.Warning (282, 3, field.Location,
631 "struct instance field `{0}' found in different declaration from instance field `{1}'",
632 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
636 public void AddProperty (Property prop)
638 if (!AddToMemberContainer (prop) ||
639 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
642 if (properties == null)
643 properties = new MemberCoreArrayList ();
645 if (prop.MemberName.Left != null)
646 properties.Insert (0, prop);
648 properties.Add (prop);
651 public void AddEvent (Event e)
653 if (!AddToMemberContainer (e))
656 if (e is EventProperty) {
657 if (!AddToMemberContainer (e.Add))
660 if (!AddToMemberContainer (e.Remove))
665 events = new MemberCoreArrayList ();
671 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
673 public void AddIndexer (Indexer i)
675 if (indexers == null)
676 indexers = new IndexerArrayList (this);
678 if (i.IsExplicitImpl)
679 indexers.Insert (0, i);
684 public void AddOperator (Operator op)
686 if (!AddToMemberContainer (op))
689 if (operators == null)
690 operators = new OperatorArrayList (this);
695 public void AddIterator (Iterator i)
697 if (iterators == null)
698 iterators = new ArrayList ();
703 public void AddType (TypeContainer tc)
708 public void AddPart (ClassPart part)
711 parts = new ArrayList ();
716 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
718 if (a.Type == TypeManager.default_member_type) {
719 if (Indexers != null) {
720 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
725 base.ApplyAttributeBuilder (a, cb);
728 public override AttributeTargets AttributeTargets {
732 return AttributeTargets.Class;
734 return AttributeTargets.Struct;
736 return AttributeTargets.Interface;
738 throw new NotSupportedException ();
743 public ArrayList Types {
749 public MethodArrayList Methods {
755 public ArrayList Constants {
761 public ArrayList Interfaces {
767 public ArrayList Iterators {
775 return base_class_name;
779 public ArrayList Bases {
789 public ArrayList Fields {
795 public ArrayList InstanceConstructors {
797 return instance_constructors;
801 public ArrayList Properties {
807 public ArrayList Events {
813 public ArrayList Enums {
819 public ArrayList Indexers {
825 public ArrayList Operators {
831 public ArrayList Delegates {
837 public ArrayList Parts {
843 protected override TypeAttributes TypeAttr {
845 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
849 public string IndexerName {
851 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
855 public bool IsComImport {
857 if (OptAttributes == null)
860 return OptAttributes.Contains (TypeManager.comimport_attr_type, EmitContext);
864 public virtual void RegisterFieldForInitialization (FieldMember field)
866 if ((field.ModFlags & Modifiers.STATIC) != 0){
867 if (initialized_static_fields == null)
868 initialized_static_fields = new ArrayList ();
870 initialized_static_fields.Add (field);
872 if (initialized_fields == null)
873 initialized_fields = new ArrayList ();
875 initialized_fields.Add (field);
879 bool CanElideInitializer (Type field_type, Constant c)
881 if (field_type == c.Type)
883 if (TypeManager.IsValueType (field_type) || TypeManager.HasElementType (field_type))
885 // Reference type with null initializer.
886 return c.Type == TypeManager.null_type;
890 // Emits the instance field initializers
892 public virtual bool EmitFieldInitializers (EmitContext ec)
895 Expression instance_expr;
898 fields = initialized_static_fields;
899 instance_expr = null;
901 fields = initialized_fields;
902 instance_expr = new This (Location.Null).Resolve (ec);
908 foreach (FieldMember f in fields){
909 Expression e = f.GetInitializerExpression (ec);
913 Location l = f.Location;
914 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
915 fe.InstanceExpression = instance_expr;
917 ExpressionStatement a = new Assign (fe, e, l);
919 a = a.ResolveStatement (ec);
923 Constant c = e as Constant;
924 if (c != null && c.IsDefaultValue && CanElideInitializer (f.MemberType, c))
927 a.EmitStatement (ec);
934 // Defines the default constructors
936 protected void DefineDefaultConstructor (bool is_static)
940 // The default constructor is public
941 // If the class is abstract, the default constructor is protected
942 // The default static constructor is private
944 int mods = Modifiers.PUBLIC;
946 mods = Modifiers.STATIC | Modifiers.PRIVATE;
947 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
948 mods = Modifiers.PROTECTED;
950 TypeContainer constructor_parent = this;
952 constructor_parent = (TypeContainer) Parts [0];
954 c = new Constructor (constructor_parent, MemberName.Name, mods,
955 Parameters.EmptyReadOnlyParameters,
956 new GeneratedBaseInitializer (Location),
961 c.Block = new ToplevelBlock (null, Location);
966 /// The pending methods that need to be implemented
967 // (interfaces or abstract methods)
969 public PendingImplementation Pending;
971 public abstract PendingImplementation GetPendingImplementations ();
973 TypeExpr[] GetPartialBases (out TypeExpr base_class)
975 ArrayList ifaces = new ArrayList ();
979 foreach (ClassPart part in parts) {
980 TypeExpr new_base_class;
981 TypeExpr[] new_ifaces;
983 new_ifaces = part.GetClassBases (out new_base_class);
984 if (new_ifaces == null && new_base_class != null)
987 if ((base_class != null) && (new_base_class != null) &&
988 !base_class.Equals (new_base_class)) {
989 Report.SymbolRelatedToPreviousError (base_class.Location, "");
990 Report.Error (263, part.Location,
991 "Partial declarations of `{0}' must " +
992 "not specify different base classes",
998 if ((base_class == null) && (new_base_class != null)) {
999 base_class = new_base_class;
1002 if (new_ifaces == null)
1005 foreach (TypeExpr iface in new_ifaces) {
1007 foreach (TypeExpr old_iface in ifaces) {
1008 if (old_iface.Equals (iface)) {
1019 TypeExpr[] retval = new TypeExpr [ifaces.Count];
1020 ifaces.CopyTo (retval, 0);
1024 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1028 int count = Bases.Count;
1029 int start = 0, i, j;
1031 if (Kind == Kind.Class){
1032 TypeExpr name = ResolveBaseTypeExpr (
1033 (Expression) Bases [0], false, Location);
1039 if (!name.IsInterface) {
1040 // base_class could be a class, struct, enum, delegate.
1041 // This is validated in GetClassBases.
1047 TypeExpr [] ifaces = new TypeExpr [count-start];
1049 for (i = start, j = 0; i < count; i++, j++){
1050 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1051 if (resolved == null) {
1055 ifaces [j] = resolved;
1062 /// This function computes the Base class and also the
1063 /// list of interfaces that the class or struct @c implements.
1065 /// The return value is an array (might be null) of
1066 /// interfaces implemented (as Types).
1068 /// The @base_class argument is set to the base object or null
1069 /// if this is `System.Object'.
1071 protected virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1078 ifaces = GetPartialBases (out base_class);
1079 else if (Bases == null){
1083 ifaces = GetNormalBases (out base_class);
1088 if ((base_class != null) && (Kind == Kind.Class)){
1089 if (base_class is TypeParameterExpr){
1091 689, base_class.Location,
1092 "Cannot derive from `{0}' because it is a type parameter",
1093 base_class.GetSignatureForError ());
1098 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1099 Report.Error (1521, base_class.Location, "Invalid base type");
1103 if (base_class.IsSealed){
1104 Report.SymbolRelatedToPreviousError (base_class.Type);
1105 if (base_class.Type.IsAbstract) {
1106 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
1107 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1109 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
1110 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1115 if (!base_class.CanInheritFrom ()){
1116 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
1117 GetSignatureForError (), base_class.GetSignatureForError ());
1121 if (!base_class.AsAccessible (this, ModFlags)) {
1122 Report.SymbolRelatedToPreviousError (base_class.Type);
1123 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
1124 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1128 if (base_class != null)
1129 base_class_name = base_class.Name;
1134 int count = ifaces != null ? ifaces.Length : 0;
1136 for (i = 0; i < count; i++) {
1137 TypeExpr iface = (TypeExpr) ifaces [i];
1139 if (!iface.IsInterface) {
1140 if (Kind != Kind.Class) {
1141 // TODO: location of symbol related ....
1142 Error_TypeInListIsNotInterface (Location, iface.FullName);
1144 else if (base_class != null)
1145 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1146 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1148 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1149 GetSignatureForError (), iface.GetSignatureForError ());
1154 for (int x = 0; x < i; x++) {
1155 if (iface.Equals (ifaces [x])) {
1156 Report.Error (528, Location,
1157 "`{0}' is already listed in " +
1158 "interface list", iface.Name);
1163 if ((Kind == Kind.Interface) &&
1164 !iface.AsAccessible (Parent, ModFlags)) {
1165 Report.Error (61, Location,
1166 "Inconsistent accessibility: base " +
1167 "interface `{0}' is less accessible " +
1168 "than interface `{1}'", iface.Name,
1176 bool CheckGenericInterfaces (Type[] ifaces)
1178 ArrayList already_checked = new ArrayList ();
1180 for (int i = 0; i < ifaces.Length; i++) {
1181 Type iface = ifaces [i];
1182 foreach (Type t in already_checked) {
1186 Type[] infered = new Type [CountTypeParameters];
1187 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1190 Report.Error (695, Location,
1191 "`{0}' cannot implement both `{1}' and `{2}' " +
1192 "because they may unify for some type parameter substitutions",
1193 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1194 TypeManager.CSharpName (t));
1198 already_checked.Add (iface);
1206 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1208 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1212 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1214 public override TypeBuilder DefineType ()
1219 if (TypeBuilder != null)
1222 TypeAttributes type_attributes = TypeAttr;
1226 if (TypeManager.NamespaceClash (Name, Location)) {
1231 ModuleBuilder builder = CodeGen.Module.Builder;
1232 TypeBuilder = builder.DefineType (
1233 Name, type_attributes, null, null);
1235 TypeBuilder builder = Parent.TypeBuilder;
1236 if (builder == null) {
1241 TypeBuilder = builder.DefineNestedType (
1242 Basename, type_attributes, ptype, null);
1244 } catch (ArgumentException) {
1245 Report.RuntimeMissingSupport (Location, "static classes");
1250 TypeManager.AddUserType (this);
1252 if (Parts != null) {
1254 foreach (ClassPart part in Parts) {
1255 part.TypeBuilder = TypeBuilder;
1256 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1257 part.ec.ContainerType = TypeBuilder;
1261 // Normally, we create the EmitContext here.
1262 // The only exception is if we're an Iterator - in this case,
1263 // we already have the `ec', so we don't want to create a new one.
1266 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1267 ec.ContainerType = TypeBuilder;
1271 string[] param_names = new string [TypeParameters.Length];
1272 for (int i = 0; i < TypeParameters.Length; i++)
1273 param_names [i] = TypeParameters [i].Name;
1275 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1277 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1278 for (int i = offset; i < gen_params.Length; i++)
1279 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1282 iface_exprs = GetClassBases (out base_type);
1283 if (iface_exprs == null && base_type != null) {
1289 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1290 // which in turn should have called DefineType()s on base types if necessary.
1292 // None of the code below should trigger DefineType()s on classes that we depend on.
1293 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1295 // Let's do it as soon as possible, since code below can call DefineType() on classes
1296 // that depend on us to be populated before they are.
1298 if (!(this is Iterator))
1299 RootContext.RegisterOrder (this);
1301 if (base_type == null) {
1302 if (Kind == Kind.Class){
1303 if (RootContext.StdLib)
1304 base_type = TypeManager.system_object_expr;
1305 else if (Name != "System.Object")
1306 base_type = TypeManager.system_object_expr;
1307 } else if (Kind == Kind.Struct){
1309 // If we are compiling our runtime,
1310 // and we are defining ValueType, then our
1311 // base is `System.Object'.
1313 if (!RootContext.StdLib && Name == "System.ValueType")
1314 base_type = TypeManager.system_object_expr;
1315 else if (Kind == Kind.Struct)
1316 base_type = TypeManager.system_valuetype_expr;
1320 // Avoid attributes check when parent is not set
1321 TypeResolveEmitContext.TestObsoleteMethodUsage = false;
1323 if (base_type != null) {
1324 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1325 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1326 FullNamedExpression fne = base_type.ResolveAsTypeStep (TypeResolveEmitContext);
1327 if ((fne == null) || (fne.Type == null)) {
1334 if (IsGeneric && TypeManager.IsAttributeType (ptype)) {
1335 Report.Error (698, base_type.Location,
1336 "A generic type cannot derive from `{0}' " +
1337 "because it is an attribute class",
1344 if (!CheckRecursiveDefinition (this)) {
1349 if (ptype != null) {
1350 TypeBuilder.SetParent (ptype);
1353 // Attribute is undefined at the begining of corlib compilation
1354 if (TypeManager.obsolete_attribute_type != null) {
1355 TypeResolveEmitContext.TestObsoleteMethodUsage = GetObsoleteAttribute () == null;
1356 if (ptype != null && TypeResolveEmitContext.TestObsoleteMethodUsage) {
1357 CheckObsoleteType (base_type);
1361 // add interfaces that were not added at type creation
1362 if (iface_exprs != null) {
1363 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1364 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1365 TypeResolveEmitContext.ContainerType = TypeBuilder;
1366 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1367 if (ifaces == null) {
1372 foreach (Type itype in ifaces)
1373 TypeBuilder.AddInterfaceImplementation (itype);
1375 if (!CheckGenericInterfaces (ifaces)) {
1380 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1383 if (this is Iterator && !ResolveType ()) {
1388 if (!DefineNestedTypes ()) {
1396 public bool ResolveType ()
1398 if ((base_type != null) &&
1399 (base_type.ResolveType (TypeResolveEmitContext) == null)) {
1407 TypeExpr current_type = null;
1408 if (Parts != null) {
1409 foreach (ClassPart part in Parts) {
1410 if (!part.DefineTypeParameters ()) {
1416 foreach (TypeParameter type_param in CurrentTypeParameters) {
1417 if (!type_param.Resolve (this)) {
1423 foreach (TypeParameter type_param in TypeParameters) {
1424 if (!type_param.DefineType (ec)) {
1430 current_type = new ConstructedType (
1431 TypeBuilder, TypeParameters, Location);
1434 foreach (TypeParameter type_param in TypeParameters)
1435 if (!type_param.CheckDependencies (ec)) {
1440 if (current_type != null) {
1441 current_type = current_type.ResolveAsTypeTerminal (ec);
1442 if (current_type == null) {
1447 CurrentType = current_type.ResolveType (ec);
1453 protected virtual bool DefineNestedTypes ()
1455 if (Interfaces != null) {
1456 foreach (TypeContainer iface in Interfaces)
1457 if (iface.DefineType () == null)
1461 if (Types != null) {
1462 foreach (TypeContainer tc in Types)
1463 if (tc.DefineType () == null)
1467 if (Delegates != null) {
1468 foreach (Delegate d in Delegates)
1469 if (d.DefineType () == null)
1473 if (Enums != null) {
1474 foreach (Enum en in Enums)
1475 if (en.DefineType () == null)
1482 TypeContainer InTransit;
1484 protected bool CheckRecursiveDefinition (TypeContainer tc)
1486 if (InTransit != null) {
1487 Report.SymbolRelatedToPreviousError (this);
1488 if (this is Interface)
1490 529, tc.Location, "Inherited interface `{0}' causes a " +
1491 "cycle in the interface hierarchy of `{1}'",
1492 GetSignatureForError (), tc.GetSignatureForError ());
1495 146, tc.Location, "Circular base class dependency " +
1496 "involving `{0}' and `{1}'",
1497 tc.GetSignatureForError (), GetSignatureForError ());
1503 Type parent = ptype;
1504 if (parent != null) {
1505 if (parent.IsGenericInstance)
1506 parent = parent.GetGenericTypeDefinition ();
1508 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1509 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1513 if (iface_exprs != null) {
1514 foreach (TypeExpr iface in iface_exprs) {
1515 Type itype = iface.Type;
1517 if (itype.IsGenericInstance)
1518 itype = itype.GetGenericTypeDefinition ();
1520 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1521 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1530 public static void Error_KeywordNotAllowed (Location loc)
1532 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1536 /// Populates our TypeBuilder with fields and methods
1538 public override bool DefineMembers (TypeContainer container)
1540 if (members_defined)
1541 return members_defined_ok;
1543 if (!base.DefineMembers (container))
1546 members_defined_ok = DoDefineMembers ();
1547 members_defined = true;
1549 return members_defined_ok;
1552 protected virtual bool DoDefineMembers ()
1554 if (iface_exprs != null) {
1555 foreach (TypeExpr iface in iface_exprs) {
1556 ConstructedType ct = iface as ConstructedType;
1557 if ((ct != null) && !ct.CheckConstraints (ec))
1562 if (base_type != null) {
1563 ConstructedType ct = base_type as ConstructedType;
1564 if ((ct != null) && !ct.CheckConstraints (ec))
1569 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1570 if (conflict_symbol == null) {
1571 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1572 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1574 if ((ModFlags & Modifiers.NEW) == 0) {
1575 Report.SymbolRelatedToPreviousError (conflict_symbol);
1576 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1577 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1582 DefineContainerMembers (constants);
1583 DefineContainerMembers (fields);
1585 if ((Kind == Kind.Class) && !(this is ClassPart)){
1586 if ((instance_constructors == null) &&
1587 !(this is StaticClass)) {
1588 if (default_constructor == null)
1589 DefineDefaultConstructor (false);
1592 if (initialized_static_fields != null &&
1593 default_static_constructor == null)
1594 DefineDefaultConstructor (true);
1597 if (Kind == Kind.Struct){
1599 // Structs can not have initialized instance
1602 if (initialized_static_fields != null &&
1603 default_static_constructor == null)
1604 DefineDefaultConstructor (true);
1606 if (initialized_fields != null)
1607 ReportStructInitializedInstanceError ();
1610 Pending = GetPendingImplementations ();
1612 if (parts != null) {
1613 foreach (ClassPart part in parts) {
1614 if (!part.DefineMembers (this))
1620 // Constructors are not in the defined_names array
1622 DefineContainerMembers (instance_constructors);
1624 if (default_static_constructor != null)
1625 default_static_constructor.Define ();
1627 DefineContainerMembers (properties);
1628 DefineContainerMembers (events);
1629 DefineContainerMembers (indexers);
1630 DefineContainerMembers (methods);
1631 DefineContainerMembers (operators);
1632 DefineContainerMembers (enums);
1633 DefineContainerMembers (delegates);
1635 if (CurrentType != null) {
1636 GenericType = CurrentType;
1638 ec.ContainerType = GenericType;
1643 if (!(this is ClassPart))
1644 member_cache = new MemberCache (this);
1647 if (parts != null) {
1648 foreach (ClassPart part in parts)
1649 part.member_cache = member_cache;
1652 if (iterators != null) {
1653 foreach (Iterator iterator in iterators) {
1654 if (iterator.DefineType () == null)
1658 foreach (Iterator iterator in iterators) {
1659 if (!iterator.DefineMembers (this))
1667 void ReportStructInitializedInstanceError ()
1669 foreach (Field f in initialized_fields){
1670 Report.Error (573, Location,
1671 "`{0}': Structs cannot have instance field initializers",
1672 f.GetSignatureForError ());
1676 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1679 mcal.DefineContainerMembers ();
1682 public override bool Define ()
1684 if (parts != null) {
1685 foreach (ClassPart part in parts) {
1686 if (!part.Define ())
1691 if (iterators != null) {
1692 foreach (Iterator iterator in iterators) {
1693 if (!iterator.Define ())
1701 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1703 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1707 /// This function is based by a delegate to the FindMembers routine
1709 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1715 /// This filter is used by FindMembers, and we just keep
1716 /// a global for the filter to `AlwaysAccept'
1718 static MemberFilter accepting_filter;
1721 static TypeContainer ()
1723 accepting_filter = new MemberFilter (AlwaysAccept);
1726 public MethodInfo[] GetMethods ()
1728 ArrayList members = new ArrayList ();
1730 DefineMembers (null);
1732 if (methods != null) {
1733 int len = methods.Count;
1734 for (int i = 0; i < len; i++) {
1735 Method m = (Method) methods [i];
1737 members.Add (m.MethodBuilder);
1741 if (operators != null) {
1742 int len = operators.Count;
1743 for (int i = 0; i < len; i++) {
1744 Operator o = (Operator) operators [i];
1746 members.Add (o.OperatorMethodBuilder);
1750 if (properties != null) {
1751 int len = properties.Count;
1752 for (int i = 0; i < len; i++) {
1753 Property p = (Property) properties [i];
1755 if (p.GetBuilder != null)
1756 members.Add (p.GetBuilder);
1757 if (p.SetBuilder != null)
1758 members.Add (p.SetBuilder);
1762 if (indexers != null) {
1763 int len = indexers.Count;
1764 for (int i = 0; i < len; i++) {
1765 Indexer ix = (Indexer) indexers [i];
1767 if (ix.GetBuilder != null)
1768 members.Add (ix.GetBuilder);
1769 if (ix.SetBuilder != null)
1770 members.Add (ix.SetBuilder);
1774 if (events != null) {
1775 int len = events.Count;
1776 for (int i = 0; i < len; i++) {
1777 Event e = (Event) events [i];
1779 if (e.AddBuilder != null)
1780 members.Add (e.AddBuilder);
1781 if (e.RemoveBuilder != null)
1782 members.Add (e.RemoveBuilder);
1786 MethodInfo[] retMethods = new MethodInfo [members.Count];
1787 members.CopyTo (retMethods, 0);
1791 // Indicated whether container has StructLayout attribute set Explicit
1792 public virtual bool HasExplicitLayout {
1798 public override Type FindNestedType (string name)
1800 ArrayList [] lists = { types, enums, delegates, interfaces };
1802 for (int j = 0; j < lists.Length; ++j) {
1803 ArrayList list = lists [j];
1807 int len = list.Count;
1808 for (int i = 0; i < len; ++i) {
1809 DeclSpace ds = (DeclSpace) list [i];
1810 if (ds.Basename == name) {
1812 return ds.TypeBuilder;
1820 private void FindMembers_NestedTypes (int modflags,
1821 BindingFlags bf, MemberFilter filter, object criteria,
1822 ref ArrayList members)
1824 ArrayList [] lists = { types, enums, delegates, interfaces };
1826 for (int j = 0; j < lists.Length; ++j) {
1827 ArrayList list = lists [j];
1831 int len = list.Count;
1832 for (int i = 0; i < len; i++) {
1833 DeclSpace ds = (DeclSpace) list [i];
1835 if ((ds.ModFlags & modflags) == 0)
1838 TypeBuilder tb = ds.TypeBuilder;
1840 if (!(criteria is string) || ds.Basename.Equals (criteria))
1841 tb = ds.DefineType ();
1844 if (tb != null && (filter (tb, criteria) == true)) {
1845 if (members == null)
1846 members = new ArrayList ();
1855 /// This method returns the members of this type just like Type.FindMembers would
1856 /// Only, we need to use this for types which are _being_ defined because MS'
1857 /// implementation can't take care of that.
1860 // FIXME: return an empty static array instead of null, that cleans up
1861 // some code and is consistent with some coding conventions I just found
1865 // Notice that in various cases we check if our field is non-null,
1866 // something that would normally mean that there was a bug elsewhere.
1868 // The problem happens while we are defining p-invoke methods, as those
1869 // will trigger a FindMembers, but this happens before things are defined
1871 // Since the whole process is a no-op, it is fine to check for null here.
1873 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1874 MemberFilter filter, object criteria)
1876 ArrayList members = null;
1879 if ((bf & BindingFlags.Public) != 0)
1880 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1882 if ((bf & BindingFlags.NonPublic) != 0)
1883 modflags |= Modifiers.PRIVATE;
1885 int static_mask = 0, static_flags = 0;
1886 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1887 case BindingFlags.Static:
1888 static_mask = static_flags = Modifiers.STATIC;
1891 case BindingFlags.Instance:
1892 static_mask = Modifiers.STATIC;
1897 static_mask = static_flags = 0;
1901 Timer.StartTimer (TimerType.TcFindMembers);
1904 filter = accepting_filter;
1906 if ((mt & MemberTypes.Field) != 0) {
1907 if (fields != null) {
1908 int len = fields.Count;
1909 for (int i = 0; i < len; i++) {
1910 FieldMember f = (FieldMember) fields [i];
1912 if ((f.ModFlags & modflags) == 0)
1914 if ((f.ModFlags & static_mask) != static_flags)
1917 FieldBuilder fb = f.FieldBuilder;
1918 if (fb != null && filter (fb, criteria) == true) {
1919 if (members == null)
1920 members = new ArrayList ();
1927 if (constants != null) {
1928 int len = constants.Count;
1929 for (int i = 0; i < len; i++) {
1930 Const con = (Const) constants [i];
1932 if ((con.ModFlags & modflags) == 0)
1934 if ((con.ModFlags & static_mask) != static_flags)
1937 FieldBuilder fb = con.FieldBuilder;
1940 fb = con.FieldBuilder;
1942 if (fb != null && filter (fb, criteria) == true) {
1943 if (members == null)
1944 members = new ArrayList ();
1952 if ((mt & MemberTypes.Method) != 0) {
1953 if (methods != null) {
1954 int len = methods.Count;
1955 for (int i = 0; i < len; i++) {
1956 Method m = (Method) methods [i];
1958 if ((m.ModFlags & modflags) == 0)
1960 if ((m.ModFlags & static_mask) != static_flags)
1963 MethodBuilder mb = m.MethodBuilder;
1965 if (mb != null && filter (mb, criteria) == true) {
1966 if (members == null)
1967 members = new ArrayList ();
1974 if (operators != null) {
1975 int len = operators.Count;
1976 for (int i = 0; i < len; i++) {
1977 Operator o = (Operator) operators [i];
1979 if ((o.ModFlags & modflags) == 0)
1981 if ((o.ModFlags & static_mask) != static_flags)
1984 MethodBuilder ob = o.OperatorMethodBuilder;
1985 if (ob != null && filter (ob, criteria) == true) {
1986 if (members == null)
1987 members = new ArrayList ();
1994 if (properties != null) {
1995 int len = properties.Count;
1996 for (int i = 0; i < len; i++) {
1997 Property p = (Property) properties [i];
1999 if ((p.ModFlags & modflags) == 0)
2001 if ((p.ModFlags & static_mask) != static_flags)
2007 if (b != null && filter (b, criteria) == true) {
2008 if (members == null)
2009 members = new ArrayList ();
2015 if (b != null && filter (b, criteria) == true) {
2016 if (members == null)
2017 members = new ArrayList ();
2024 if (indexers != null) {
2025 int len = indexers.Count;
2026 for (int i = 0; i < len; i++) {
2027 Indexer ix = (Indexer) indexers [i];
2029 if ((ix.ModFlags & modflags) == 0)
2031 if ((ix.ModFlags & static_mask) != static_flags)
2037 if (b != null && filter (b, criteria) == true) {
2038 if (members == null)
2039 members = new ArrayList ();
2045 if (b != null && filter (b, criteria) == true) {
2046 if (members == null)
2047 members = new ArrayList ();
2055 if ((mt & MemberTypes.Event) != 0) {
2056 if (events != null) {
2057 int len = events.Count;
2058 for (int i = 0; i < len; i++) {
2059 Event e = (Event) events [i];
2061 if ((e.ModFlags & modflags) == 0)
2063 if ((e.ModFlags & static_mask) != static_flags)
2066 MemberInfo eb = e.EventBuilder;
2067 if (eb != null && filter (eb, criteria) == true) {
2068 if (members == null)
2069 members = new ArrayList ();
2071 members.Add (e.EventBuilder);
2077 if ((mt & MemberTypes.Property) != 0){
2078 if (properties != null) {
2079 int len = properties.Count;
2080 for (int i = 0; i < len; i++) {
2081 Property p = (Property) properties [i];
2083 if ((p.ModFlags & modflags) == 0)
2085 if ((p.ModFlags & static_mask) != static_flags)
2088 MemberInfo pb = p.PropertyBuilder;
2089 if (pb != null && filter (pb, criteria) == true) {
2090 if (members == null)
2091 members = new ArrayList ();
2093 members.Add (p.PropertyBuilder);
2098 if (indexers != null) {
2099 int len = indexers.Count;
2100 for (int i = 0; i < len; i++) {
2101 Indexer ix = (Indexer) indexers [i];
2103 if ((ix.ModFlags & modflags) == 0)
2105 if ((ix.ModFlags & static_mask) != static_flags)
2108 MemberInfo ib = ix.PropertyBuilder;
2109 if (ib != null && filter (ib, criteria) == true) {
2110 if (members == null)
2111 members = new ArrayList ();
2113 members.Add (ix.PropertyBuilder);
2119 if ((mt & MemberTypes.NestedType) != 0)
2120 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2122 if ((mt & MemberTypes.Constructor) != 0){
2123 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2124 int len = instance_constructors.Count;
2125 for (int i = 0; i < len; i++) {
2126 Constructor c = (Constructor) instance_constructors [i];
2128 ConstructorBuilder cb = c.ConstructorBuilder;
2129 if (cb != null && filter (cb, criteria) == true) {
2130 if (members == null)
2131 members = new ArrayList ();
2138 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2139 ConstructorBuilder cb =
2140 default_static_constructor.ConstructorBuilder;
2142 if (cb != null && filter (cb, criteria) == true) {
2143 if (members == null)
2144 members = new ArrayList ();
2152 // Lookup members in base if requested.
2154 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2155 if (TypeBuilder.BaseType != null) {
2156 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2157 if (list.Count > 0) {
2158 if (members == null)
2159 members = new ArrayList ();
2161 members.AddRange (list);
2167 Timer.StopTimer (TimerType.TcFindMembers);
2169 if (members == null)
2170 return MemberList.Empty;
2172 return new MemberList (members);
2175 public override MemberCache MemberCache {
2177 return member_cache;
2181 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2182 MemberFilter filter, object criteria)
2184 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2187 return ds.FindMembers (mt, bf, filter, criteria);
2189 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2193 // FindMethods will look for methods not only in the type `t', but in
2194 // any interfaces implemented by the type.
2196 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2197 MemberFilter filter, object criteria)
2203 /// Emits the values for the constants
2205 public void EmitConstants ()
2207 if (constants != null)
2208 foreach (Const con in constants)
2213 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2218 foreach (MemberCore mc in al) {
2219 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2223 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2228 public virtual void VerifyMembers ()
2231 // Check for internal or private fields that were never assigned
2233 if (RootContext.WarningLevel >= 3) {
2234 CheckMemberUsage (properties, "property");
2235 CheckMemberUsage (methods, "method");
2236 CheckMemberUsage (constants, "constant");
2238 if (fields != null){
2239 foreach (FieldMember f in fields) {
2240 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2244 if ((f.caching_flags & Flags.IsAssigned) == 0)
2245 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2248 const int error_code = 414;
2250 const int error_code = 169;
2252 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2253 f.GetSignatureForError ());
2259 // Only report 649 on level 4
2261 if (RootContext.WarningLevel < 4)
2264 if ((f.caching_flags & Flags.IsAssigned) != 0)
2267 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2268 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2275 /// Emits the code, this step is performed after all
2276 /// the types, enumerations, constructors
2278 public virtual void EmitType ()
2280 if (OptAttributes != null)
2281 OptAttributes.Emit (ec, this);
2284 // Structs with no fields need to have at least one byte.
2285 // The right thing would be to set the PackingSize in a DefineType
2286 // but there are no functions that allow interfaces *and* the size to
2290 if (Kind == Kind.Struct && first_nonstatic_field == null){
2291 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2292 FieldAttributes.Private);
2294 if (HasExplicitLayout){
2295 object [] ctor_args = new object [1];
2298 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2299 TypeManager.field_offset_attribute_ctor, ctor_args);
2300 fb.SetCustomAttribute (cba);
2306 if (instance_constructors != null) {
2307 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired (this)) {
2308 bool has_compliant_args = false;
2310 foreach (Constructor c in instance_constructors) {
2313 if (has_compliant_args)
2316 has_compliant_args = c.HasCompliantArgs;
2318 if (!has_compliant_args)
2319 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2321 foreach (Constructor c in instance_constructors)
2326 // Can not continue if constants are broken
2328 if (Report.Errors > 0)
2331 if (default_static_constructor != null)
2332 default_static_constructor.Emit ();
2334 if (methods != null)
2335 foreach (Method m in methods)
2338 if (operators != null)
2339 foreach (Operator o in operators)
2342 if (properties != null)
2343 foreach (Property p in properties)
2346 if (indexers != null){
2351 foreach (FieldMember f in fields)
2354 if (events != null){
2355 foreach (Event e in Events)
2359 if (delegates != null) {
2360 foreach (Delegate d in Delegates) {
2365 if (enums != null) {
2366 foreach (Enum e in enums) {
2371 if (parts != null) {
2372 foreach (ClassPart part in parts)
2376 if ((Pending != null) && !(this is ClassPart))
2377 if (Pending.VerifyPendingMethods ())
2380 if (iterators != null)
2381 foreach (Iterator iterator in iterators)
2382 iterator.EmitType ();
2384 // if (types != null)
2385 // foreach (TypeContainer tc in types)
2389 public override void CloseType ()
2391 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2395 caching_flags |= Flags.CloseTypeCreated;
2396 TypeBuilder.CreateType ();
2397 } catch (TypeLoadException){
2399 // This is fine, the code still created the type
2401 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2402 // Console.WriteLine (e.Message);
2404 Console.WriteLine ("In type: " + Name);
2409 foreach (Enum en in Enums)
2413 foreach (TypeContainer tc in Types)
2414 if (tc.Kind == Kind.Struct)
2417 foreach (TypeContainer tc in Types)
2418 if (tc.Kind != Kind.Struct)
2422 if (Delegates != null)
2423 foreach (Delegate d in Delegates)
2426 if (Iterators != null)
2427 foreach (Iterator i in Iterators)
2435 initialized_fields = null;
2436 initialized_static_fields = null;
2445 default_constructor = null;
2446 default_static_constructor = null;
2448 OptAttributes = null;
2451 member_cache = null;
2455 // Performs the validation on a Method's modifiers (properties have
2456 // the same properties).
2458 public bool MethodModifiersValid (MemberCore mc)
2460 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2461 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2462 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2464 int flags = mc.ModFlags;
2467 // At most one of static, virtual or override
2469 if ((flags & Modifiers.STATIC) != 0){
2470 if ((flags & vao) != 0){
2471 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2472 mc.GetSignatureForError ());
2477 if (Kind == Kind.Struct){
2478 if ((flags & va) != 0){
2479 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2484 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2485 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2486 mc.GetSignatureForError ());
2491 // If the declaration includes the abstract modifier, then the
2492 // declaration does not include static, virtual or extern
2494 if ((flags & Modifiers.ABSTRACT) != 0){
2495 if ((flags & Modifiers.EXTERN) != 0){
2497 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2501 if ((flags & Modifiers.SEALED) != 0) {
2502 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2506 if ((flags & Modifiers.VIRTUAL) != 0){
2507 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2511 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2512 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2517 if ((flags & Modifiers.PRIVATE) != 0){
2518 if ((flags & vao) != 0){
2519 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2524 if ((flags & Modifiers.SEALED) != 0){
2525 if ((flags & Modifiers.OVERRIDE) == 0){
2526 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2534 public bool UserDefinedStaticConstructor {
2536 return default_static_constructor != null;
2540 public Constructor DefaultStaticConstructor {
2541 get { return default_static_constructor; }
2544 protected override bool VerifyClsCompliance (DeclSpace ds)
2546 if (!base.VerifyClsCompliance (ds))
2551 Type base_type = TypeBuilder.BaseType;
2552 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2553 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2556 if (!Parent.IsClsComplianceRequired (ds)) {
2557 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
2558 GetSignatureForError (), Parent.GetSignatureForError ());
2565 /// Checks whether container name is CLS Compliant
2567 void VerifyClsName ()
2569 Hashtable base_members = base_cache == null ?
2571 base_cache.GetPublicMembers ();
2572 Hashtable this_members = new Hashtable ();
2574 foreach (DictionaryEntry entry in defined_names) {
2575 MemberCore mc = (MemberCore)entry.Value;
2576 if (!mc.IsClsComplianceRequired (mc.Parent))
2579 string name = (string) entry.Key;
2580 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2582 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2583 object found = base_members [lcase];
2584 if (found == null) {
2585 found = this_members [lcase];
2586 if (found == null) {
2587 this_members.Add (lcase, mc);
2592 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2595 if (found is MemberInfo) {
2596 if (basename == ((MemberInfo) found).Name)
2598 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2600 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2602 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2608 /// Performs checks for an explicit interface implementation. First it
2609 /// checks whether the `interface_type' is a base inteface implementation.
2610 /// Then it checks whether `name' exists in the interface type.
2612 public virtual bool VerifyImplements (MemberBase mb)
2614 if (ifaces != null) {
2615 foreach (Type t in ifaces){
2616 if (t == mb.InterfaceType)
2621 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2622 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2630 string IMemberContainer.Name {
2636 Type IMemberContainer.Type {
2642 MemberCache IMemberContainer.MemberCache {
2644 return member_cache;
2648 bool IMemberContainer.IsInterface {
2650 return Kind == Kind.Interface;
2654 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2656 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2658 if (GenericType != null)
2659 return TypeManager.FindMembers (GenericType, mt, new_bf,
2662 return FindMembers (mt, new_bf, null, null);
2666 // Generates xml doc comments (if any), and if required,
2667 // handle warning report.
2669 internal override void GenerateDocComment (DeclSpace ds)
2671 DocUtil.GenerateTypeDocComment (this, ds);
2674 public override string DocCommentHeader {
2675 get { return "T:"; }
2678 public virtual MemberCache BaseCache {
2680 if (base_cache != null)
2682 if (TypeBuilder.BaseType != null)
2683 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2684 if (TypeBuilder.IsInterface)
2685 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2692 public class PartialContainer : TypeContainer {
2694 public readonly Namespace Namespace;
2695 public readonly int OriginalModFlags;
2696 public readonly int AllowedModifiers;
2697 public readonly TypeAttributes DefaultTypeAttributes;
2698 public ListDictionary DeclarativeSecurity;
2700 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2701 MemberName member_name, int mod_flags, Kind kind)
2704 if (!CheckModFlags (0, mod_flags, member_name))
2707 PartialContainer pc = RootContext.Tree.GetDecl (member_name) as PartialContainer;
2709 if (pc.Kind != kind) {
2711 261, member_name.Location,
2712 "Partial declarations of `{0}' must be all classes, " +
2713 "all structs or all interfaces",
2714 member_name.GetTypeName ());
2718 if (!CheckModFlags (pc.OriginalModFlags, mod_flags, member_name))
2720 pc.ModFlags |= (mod_flags & pc.AllowedModifiers);
2723 if (pc.CountTypeParameters != member_name.CountTypeArguments) {
2725 264, member_name.Location,
2726 "Partial declarations of `{0}' must have the " +
2727 "same type parameter names in the same order",
2728 member_name.GetTypeName ());
2732 string[] pc_names = pc.MemberName.TypeArguments.GetDeclarations ();
2733 string[] names = member_name.TypeArguments.GetDeclarations ();
2735 for (int i = 0; i < pc.CountTypeParameters; i++) {
2736 if (pc_names [i] == names [i])
2740 264, member_name.Location,
2741 "Partial declarations of `{0}' must have the " +
2742 "same type parameter names in the same order",
2743 member_name.GetTypeName ());
2751 if (parent is ClassPart)
2752 parent = ((ClassPart) parent).PartialContainer;
2754 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind);
2756 if (kind == Kind.Interface) {
2757 if (!parent.AddInterface (pc))
2759 } else if (kind == Kind.Class || kind == Kind.Struct) {
2760 if (!parent.AddClassOrStruct (pc))
2763 throw new InvalidOperationException ();
2765 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2766 // This is needed to define our type parameters; we define the constraints later.
2767 pc.SetParameterInfo (null);
2771 static bool CheckModFlags (int flags_org, int flags, MemberName member_name)
2773 // Check (abstract|static|sealed) sanity.
2774 int tmp = (flags_org | flags) & (Modifiers.ABSTRACT | Modifiers.SEALED | Modifiers.STATIC);
2775 if ((tmp & Modifiers.ABSTRACT) != 0) {
2776 if ((tmp & (Modifiers.STATIC | Modifiers.SEALED)) != 0) {
2778 418, member_name.Location,
2779 "`{0}': an abstract class cannot be sealed or static", member_name.ToString ());
2782 } else if (tmp == (Modifiers.SEALED | Modifiers.STATIC)) {
2783 Report.Error (441, member_name.Location, "`{0}': a class cannot be both static and sealed", member_name.ToString ());
2791 if (0 != ((flags_org ^ flags) & (0xFFFFFFFF ^ (Modifiers.SEALED | Modifiers.ABSTRACT)))) {
2793 262, member_name.Location, "Partial declarations of `{0}' " +
2794 "have conflicting accessibility modifiers",
2795 member_name.GetName ());
2801 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2802 MemberName name, int mod, Attributes attrs,
2803 Kind kind, Location loc)
2805 PartialContainer pc = Create (ns, parent, name, mod, kind);
2807 // An error occured; create a dummy container, but don't
2809 pc = new PartialContainer (ns.NS, parent, name, mod, kind);
2812 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind);
2817 protected PartialContainer (Namespace ns, TypeContainer parent,
2818 MemberName name, int mod, Kind kind)
2819 : base (null, parent, name, null, kind)
2821 this.Namespace = ns;
2825 AllowedModifiers = Class.AllowedModifiers;
2826 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2830 AllowedModifiers = Struct.AllowedModifiers;
2831 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2834 case Kind.Interface:
2835 AllowedModifiers = Interface.AllowedModifiers;
2836 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2840 throw new InvalidOperationException ();
2844 if (parent.Parent == null)
2845 accmods = Modifiers.INTERNAL;
2847 accmods = Modifiers.PRIVATE;
2849 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2850 this.OriginalModFlags = mod;
2853 public override void EmitType ()
2857 if (DeclarativeSecurity != null) {
2858 foreach (DictionaryEntry de in DeclarativeSecurity) {
2859 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2864 public override PendingImplementation GetPendingImplementations ()
2866 return PendingImplementation.GetPendingImplementations (this);
2869 public override bool MarkForDuplicationCheck ()
2874 protected override TypeAttributes TypeAttr {
2876 return base.TypeAttr | DefaultTypeAttributes;
2881 public class ClassPart : TypeContainer, IMemberContainer {
2882 public readonly PartialContainer PartialContainer;
2883 public readonly bool IsPartial;
2885 Constraints[] constraints;
2887 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2888 int mod, Attributes attrs, Kind kind)
2889 : base (ns, parent, pc.MemberName, attrs, kind)
2891 this.PartialContainer = pc;
2892 this.IsPartial = true;
2895 if (parent == null || parent == RootContext.Tree.Types)
2896 accmods = Modifiers.INTERNAL;
2898 accmods = Modifiers.PRIVATE;
2900 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, pc.MemberName.Location);
2903 constraints = new Constraints [pc.CountCurrentTypeParameters];
2906 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2908 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2909 if (PartialContainer.DeclarativeSecurity == null)
2910 PartialContainer.DeclarativeSecurity = new ListDictionary ();
2912 a.ExtractSecurityPermissionSet (PartialContainer.DeclarativeSecurity);
2916 base.ApplyAttributeBuilder (a, cb);
2919 public override PendingImplementation GetPendingImplementations ()
2921 return PartialContainer.Pending;
2924 public override bool VerifyImplements (MemberBase mb)
2926 return PartialContainer.VerifyImplements (mb);
2929 public override void SetParameterInfo (ArrayList constraints_list)
2931 if (constraints_list == null)
2934 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2935 for (int i = 0; i < constraints.Length; i++) {
2936 foreach (Constraints constraint in constraints_list) {
2937 if (constraint.TypeParameter == current_params [i].Name) {
2938 constraints [i] = constraint;
2945 public bool DefineTypeParameters ()
2947 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2949 for (int i = 0; i < current_params.Length; i++) {
2950 Constraints new_constraints = constraints [i];
2951 if (new_constraints == null)
2954 if (!current_params [i].UpdateConstraints (ec, new_constraints)) {
2955 Report.Error (265, Location, "Partial declarations of `{0}' have " +
2956 "inconsistent constraints for type parameter `{1}'.",
2957 MemberName.GetTypeName (), current_params [i].Name);
2962 for (int i = 0; i < current_params.Length; i++) {
2963 if (!current_params [i].Resolve (this))
2967 foreach (TypeParameter type_param in PartialContainer.TypeParameters) {
2968 if (!type_param.DefineType (ec))
2975 public override void RegisterFieldForInitialization (FieldMember field)
2977 PartialContainer.RegisterFieldForInitialization (field);
2980 public override bool EmitFieldInitializers (EmitContext ec)
2982 return PartialContainer.EmitFieldInitializers (ec);
2985 public override Type FindNestedType (string name)
2987 return PartialContainer.FindNestedType (name);
2990 public override MemberCache BaseCache {
2992 return PartialContainer.BaseCache;
2996 public override TypeBuilder DefineType ()
2998 throw new InternalErrorException ("Should not get here");
3003 public abstract class ClassOrStruct : TypeContainer {
3004 bool has_explicit_layout = false;
3005 ListDictionary declarative_security;
3007 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
3008 MemberName name, Attributes attrs, Kind kind)
3009 : base (ns, parent, name, attrs, kind)
3013 public override PendingImplementation GetPendingImplementations ()
3015 return PendingImplementation.GetPendingImplementations (this);
3018 public override bool HasExplicitLayout {
3020 return has_explicit_layout;
3024 public override void VerifyMembers ()
3026 base.VerifyMembers ();
3028 if ((events != null) && (RootContext.WarningLevel >= 3)) {
3029 foreach (Event e in events){
3030 if ((e.caching_flags & Flags.IsAssigned) == 0)
3031 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
3036 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3038 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3039 if (declarative_security == null)
3040 declarative_security = new ListDictionary ();
3042 a.ExtractSecurityPermissionSet (declarative_security);
3046 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
3047 has_explicit_layout = true;
3049 base.ApplyAttributeBuilder (a, cb);
3052 public override void Emit()
3056 if (declarative_security != null) {
3057 foreach (DictionaryEntry de in declarative_security) {
3058 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3065 /// Class handles static classes declaration
3067 public sealed class StaticClass: Class {
3068 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3070 : base (ns, parent, name, mod, attrs)
3072 if (RootContext.Version == LanguageVersion.ISO_1) {
3073 Report.FeatureIsNotStandardized (Location, "static classes");
3077 protected override int AllowedModifiersProp {
3079 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
3080 Modifiers.STATIC | Modifiers.UNSAFE;
3084 protected override void DefineContainerMembers (MemberCoreArrayList list)
3089 foreach (MemberCore m in list) {
3090 if (m is Operator) {
3091 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
3095 if (m is Destructor) {
3096 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
3100 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
3101 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
3106 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
3110 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
3113 if (m is Constructor) {
3114 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
3118 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
3121 base.DefineContainerMembers (list);
3124 public override TypeBuilder DefineType()
3126 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
3127 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
3131 TypeBuilder tb = base.DefineType ();
3135 if (ptype != TypeManager.object_type) {
3136 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
3140 if (ifaces != null) {
3141 foreach (Type t in ifaces)
3142 Report.SymbolRelatedToPreviousError (t);
3143 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
3148 protected override TypeAttributes TypeAttr {
3150 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
3155 public class Class : ClassOrStruct {
3156 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
3157 public const int AllowedModifiers =
3160 Modifiers.PROTECTED |
3161 Modifiers.INTERNAL |
3163 Modifiers.ABSTRACT |
3167 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3169 : base (ns, parent, name, attrs, Kind.Class)
3171 this.ModFlags = mod;
3174 virtual protected int AllowedModifiersProp {
3176 return AllowedModifiers;
3180 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
3182 if (a.Type == TypeManager.attribute_usage_type) {
3183 if (ptype != TypeManager.attribute_type &&
3184 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
3185 TypeBuilder.FullName != "System.Attribute") {
3186 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
3190 if (a.Type == TypeManager.conditional_attribute_type &&
3191 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
3192 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
3196 if (AttributeTester.IsAttributeExcluded (a.Type))
3199 base.ApplyAttributeBuilder (a, cb);
3202 public const TypeAttributes DefaultTypeAttributes =
3203 TypeAttributes.AutoLayout | TypeAttributes.Class;
3205 public override TypeBuilder DefineType()
3207 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
3208 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
3212 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
3213 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
3215 return base.DefineType ();
3218 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3219 /// Valid only for attribute classes.
3220 public bool IsExcluded ()
3222 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3223 return (caching_flags & Flags.Excluded) != 0;
3225 caching_flags &= ~Flags.Excluded_Undetected;
3227 if (OptAttributes == null)
3230 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3235 foreach (Attribute a in attrs) {
3236 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3237 if (RootContext.AllDefines.Contains (condition))
3241 caching_flags |= Flags.Excluded;
3246 // FIXME: How do we deal with the user specifying a different
3249 protected override TypeAttributes TypeAttr {
3251 return base.TypeAttr | DefaultTypeAttributes;
3256 public class Struct : ClassOrStruct {
3258 // Modifiers allowed in a struct declaration
3260 public const int AllowedModifiers =
3263 Modifiers.PROTECTED |
3264 Modifiers.INTERNAL |
3268 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
3269 int mod, Attributes attrs)
3270 : base (ns, parent, name, attrs, Kind.Struct)
3274 if (parent.Parent == null)
3275 accmods = Modifiers.INTERNAL;
3277 accmods = Modifiers.PRIVATE;
3279 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3281 this.ModFlags |= Modifiers.SEALED;
3284 public const TypeAttributes DefaultTypeAttributes =
3285 TypeAttributes.SequentialLayout |
3286 TypeAttributes.Sealed |
3287 TypeAttributes.BeforeFieldInit;
3290 // FIXME: Allow the user to specify a different set of attributes
3291 // in some cases (Sealed for example is mandatory for a class,
3292 // but what SequentialLayout can be changed
3294 protected override TypeAttributes TypeAttr {
3296 return base.TypeAttr | DefaultTypeAttributes;
3304 public class Interface : TypeContainer, IMemberContainer {
3307 /// Modifiers allowed in a class declaration
3309 public const int AllowedModifiers =
3312 Modifiers.PROTECTED |
3313 Modifiers.INTERNAL |
3317 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3319 : base (ns, parent, name, attrs, Kind.Interface)
3323 if (parent.Parent == null)
3324 accmods = Modifiers.INTERNAL;
3326 accmods = Modifiers.PRIVATE;
3328 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3331 public override PendingImplementation GetPendingImplementations ()
3336 public const TypeAttributes DefaultTypeAttributes =
3337 TypeAttributes.AutoLayout |
3338 TypeAttributes.Abstract |
3339 TypeAttributes.Interface;
3341 protected override TypeAttributes TypeAttr {
3343 return base.TypeAttr | DefaultTypeAttributes;
3347 protected override bool VerifyClsCompliance (DeclSpace ds)
3349 if (!base.VerifyClsCompliance (ds))
3352 if (ifaces != null) {
3353 foreach (Type t in ifaces) {
3354 if (AttributeTester.IsClsCompliant (t))
3357 Report.SymbolRelatedToPreviousError (t);
3358 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3359 GetSignatureForError (), TypeManager.CSharpName (t));
3367 public abstract class MethodCore : MemberBase {
3368 public readonly Parameters Parameters;
3369 protected ToplevelBlock block;
3372 // Parameters, cached for semantic analysis.
3374 protected InternalParameters parameter_info;
3375 protected Type [] parameter_types;
3377 // Whether this is an operator method.
3378 public Operator IsOperator;
3381 // The method we're overriding if this is an override method.
3383 protected MethodInfo base_method = null;
3385 static string[] attribute_targets = new string [] { "method", "return" };
3387 public MethodCore (TypeContainer parent, GenericMethod generic,
3388 Expression type, int mod, int allowed_mod, bool is_iface,
3389 MemberName name, Attributes attrs, Parameters parameters)
3390 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3393 Parameters = parameters;
3394 IsInterface = is_iface;
3398 // Returns the System.Type array for the parameters of this method
3400 public Type [] ParameterTypes {
3402 return parameter_types;
3406 public InternalParameters ParameterInfo
3409 return parameter_info;
3413 public override EmitContext EmitContext {
3414 get { return ds.EmitContext; }
3417 public ToplevelBlock Block {
3427 public void SetYields ()
3429 ModFlags |= Modifiers.METHOD_YIELDS;
3432 protected override bool CheckBase ()
3434 if (!base.CheckBase ())
3437 // Check whether arguments were correct.
3438 if (!DoDefineParameters ())
3441 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3447 // Is null for System.Object while compiling corlib and base interfaces
3448 if (Parent.BaseCache == null) {
3449 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3450 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3455 Type base_ret_type = null;
3456 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3458 // method is override
3459 if (base_method != null) {
3461 if (!CheckMethodAgainstBase ())
3464 if ((ModFlags & Modifiers.NEW) == 0) {
3465 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_ret_type))) {
3466 Report.SymbolRelatedToPreviousError (base_method);
3467 if (this is PropertyBase) {
3468 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3469 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3472 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3473 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3478 if (base_method.IsAbstract && !IsInterface) {
3479 Report.SymbolRelatedToPreviousError (base_method);
3480 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3481 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3486 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3487 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3491 if (RootContext.WarningLevel > 2) {
3492 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3493 Parent.Methods.HasEquals = true;
3494 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3495 Parent.Methods.HasGetHashCode = true;
3498 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3499 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3501 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3502 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3503 Report.SymbolRelatedToPreviousError (base_method);
3504 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3505 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3512 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3513 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3514 if (conflict_symbol != null) {
3515 Report.SymbolRelatedToPreviousError (conflict_symbol);
3516 if (this is PropertyBase)
3517 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3519 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3521 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3525 if (conflict_symbol == null) {
3526 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3527 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3532 if ((ModFlags & Modifiers.NEW) == 0) {
3533 if (this is Method && conflict_symbol is MethodBase)
3536 Report.SymbolRelatedToPreviousError (conflict_symbol);
3537 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3538 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3545 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3546 // that have been defined.
3548 // `name' is the user visible name for reporting errors (this is used to
3549 // provide the right name regarding method names and properties)
3551 bool CheckMethodAgainstBase ()
3555 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3556 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3557 Report.Error (506, Location,
3558 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3559 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3563 // Now we check that the overriden method is not final
3565 if (base_method.IsFinal) {
3566 Report.SymbolRelatedToPreviousError (base_method);
3567 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3568 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3572 // Check that the permissions are not being changed
3574 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3575 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3577 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3578 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3583 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3584 ModFlags |= Modifiers.NEW;
3585 Report.SymbolRelatedToPreviousError (base_method);
3586 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3587 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",
3588 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3590 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3591 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3598 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3600 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3602 // when overriding protected internal, the method can be declared
3603 // protected internal only within the same assembly
3606 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3607 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3609 // assemblies differ - report an error
3613 } else if (thisp != base_classp) {
3615 // same assembly, but other attributes differ - report an error
3620 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3622 // if it's not "protected internal", it must be "protected"
3626 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3628 // protected within the same assembly - an error
3631 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3632 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3634 // protected ok, but other attributes differ - report an error
3640 return (thisp == base_classp);
3644 public bool CheckAbstractAndExtern (bool has_block)
3646 if (Parent.Kind == Kind.Interface)
3650 if ((ModFlags & Modifiers.EXTERN) != 0) {
3651 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3652 GetSignatureForError ());
3656 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3657 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3658 GetSignatureForError ());
3662 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3663 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3664 GetSignatureForError ());
3672 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3674 Report.SymbolRelatedToPreviousError (base_method);
3675 string base_name = TypeManager.GetFullNameSignature (base_method);
3676 string this_name = GetSignatureForError ();
3677 if (suffix != null) {
3678 base_name += suffix;
3679 this_name += suffix;
3682 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3683 this_name, Modifiers.GetDescription (ma), base_name);
3686 protected static string Error722 {
3688 return "`{0}': static types cannot be used as return types";
3693 /// For custom member duplication search in a container
3695 protected abstract bool CheckForDuplications ();
3698 /// Gets base method and its return type
3700 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3702 protected virtual bool DoDefineParameters ()
3704 EmitContext ec = ds.EmitContext;
3706 throw new InternalErrorException ("DoDefineParameters invoked too early");
3708 bool old_unsafe = ec.InUnsafe;
3709 ec.InUnsafe = InUnsafe;
3710 ec.ResolvingGenericMethod = GenericMethod != null;
3711 // Check if arguments were correct
3712 parameter_types = Parameters.GetParameterInfo (ec);
3713 ec.ResolvingGenericMethod = false;
3714 ec.InUnsafe = old_unsafe;
3716 if ((parameter_types == null) ||
3717 !CheckParameters (ds, parameter_types))
3720 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3721 parameter_info = new InternalParameters (parameter_types, Parameters, tparam);
3723 Parameter array_param = Parameters.ArrayParameter;
3724 if ((array_param != null) &&
3725 (!array_param.ParameterType.IsArray ||
3726 (array_param.ParameterType.GetArrayRank () != 1))) {
3727 Report.Error (225, Location, "The params parameter must be a single dimensional array");
3734 void error_425 (Type old, Type t, string name)
3736 Report.Error (425, Location,
3737 "The constraints of type parameter `{0}' " +
3738 "of method `{1}' must match the constraints for " +
3739 "type parameter `{2}' of method `{3}'",
3740 TypeManager.CSharpName (old), Name,
3741 TypeManager.CSharpName (t), name);
3744 protected override bool CheckGenericOverride (MethodInfo method, string name)
3746 ParameterData pd = TypeManager.GetParameterData (method);
3748 for (int i = 0; i < ParameterTypes.Length; i++) {
3749 GenericConstraints ogc = pd.GenericConstraints (i);
3750 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3752 if ((gc == null) && (ogc == null))
3755 Type ot = pd.ParameterType (i);
3756 Type t = ParameterTypes [i];
3758 if (!((gc != null) && (ogc != null))) {
3759 error_425 (ot, t, name);
3763 if ((gc.Attributes != ogc.Attributes) ||
3764 (gc.HasClassConstraint != ogc.HasClassConstraint)) {
3765 error_425 (ot, t, name);
3769 if (ogc.HasClassConstraint &&
3770 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3771 error_425 (ot, t, name);
3775 Type[] oct = ogc.InterfaceConstraints;
3776 Type[] ct = gc.InterfaceConstraints;
3778 if (oct.Length != ct.Length) {
3779 error_425 (ot, t, name);
3783 for (int j = 0; j < oct.Length; j++)
3784 if (!oct [j].Equals (ct [j])) {
3785 error_425 (ot, t, name);
3793 public override string[] ValidAttributeTargets {
3795 return attribute_targets;
3799 protected override bool VerifyClsCompliance (DeclSpace ds)
3801 if (!base.VerifyClsCompliance (ds)) {
3802 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsComplianceRequired (ds)) {
3803 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3808 if (Parameters.HasArglist) {
3809 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3812 if (!AttributeTester.IsClsCompliant (MemberType)) {
3813 if (this is PropertyBase)
3814 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3815 GetSignatureForError ());
3817 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3818 GetSignatureForError ());
3821 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3826 bool MayUnify (MethodCore first, MethodCore second)
3828 int a_type_params = 0;
3829 if (first.GenericMethod != null)
3830 a_type_params = first.GenericMethod.CountTypeParameters;
3832 int b_type_params = 0;
3833 if (second.GenericMethod != null)
3834 b_type_params = second.GenericMethod.CountTypeParameters;
3836 if (a_type_params != b_type_params)
3839 Type[] class_infered, method_infered;
3840 if (Parent.CountTypeParameters > 0)
3841 class_infered = new Type [Parent.CountTypeParameters];
3843 class_infered = null;
3845 if (a_type_params > 0)
3846 method_infered = new Type [a_type_params];
3848 method_infered = null;
3850 return TypeManager.MayBecomeEqualGenericInstances (
3851 first.ParameterTypes, second.ParameterTypes, class_infered, method_infered);
3854 protected bool IsDuplicateImplementation (MethodCore method)
3856 if (method == this || !(method.MemberName.Equals (MemberName)))
3859 Type[] param_types = method.ParameterTypes;
3860 if (param_types == null && ParameterTypes == null)
3862 if (param_types == null || ParameterTypes == null)
3865 if (param_types.Length != ParameterTypes.Length)
3869 bool may_unify = MayUnify (this, method);
3871 for (int i = 0; i < param_types.Length; i++) {
3872 if (param_types [i] != ParameterTypes [i])
3876 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3877 equal = may_unify = false;
3879 // TODO: make operator compatible with MethodCore to avoid this
3880 if (this is Operator && method is Operator) {
3881 if (MemberType != method.MemberType)
3882 equal = may_unify = false;
3887 // Try to report 663: method only differs on out/ref
3889 ParameterData info = ParameterInfo;
3890 ParameterData other_info = method.ParameterInfo;
3891 for (int i = 0; i < info.Count; i++){
3892 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3893 Report.SymbolRelatedToPreviousError (method);
3894 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3895 GetSignatureForError ());
3900 Report.SymbolRelatedToPreviousError (method);
3901 if (this is Operator && method is Operator)
3902 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3904 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3907 } else if (may_unify) {
3908 Report.Error (408, Location,
3909 "`{0}' cannot define overload members that " +
3910 "may unify for some type parameter substitutions",
3911 Parent.MemberName.ToString ());
3918 public override bool IsUsed {
3919 get { return IsExplicitImpl || base.IsUsed; }
3923 // Returns a string that represents the signature for this
3924 // member which should be used in XML documentation.
3926 public override string GetDocCommentName (DeclSpace ds)
3928 return DocUtil.GetMethodDocCommentName (this, ds);
3932 // Raised (and passed an XmlElement that contains the comment)
3933 // when GenerateDocComment is writing documentation expectedly.
3935 // FIXME: with a few effort, it could be done with XmlReader,
3936 // that means removal of DOM use.
3938 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3940 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3944 // Represents header string for documentation comment.
3946 public override string DocCommentHeader {
3947 get { return "M:"; }
3952 public class SourceMethod : ISourceMethod
3954 TypeContainer container;
3957 protected SourceMethod (TypeContainer container, MethodBase builder,
3958 ISourceFile file, Location start, Location end)
3960 this.container = container;
3961 this.builder = builder;
3963 CodeGen.SymbolWriter.OpenMethod (
3964 file, this, start.Row, start.Column, end.Row, start.Column);
3967 public string Name {
3968 get { return builder.Name; }
3971 public int NamespaceID {
3972 get { return container.NamespaceEntry.SymbolFileID; }
3977 if (builder is MethodBuilder)
3978 return ((MethodBuilder) builder).GetToken ().Token;
3979 else if (builder is ConstructorBuilder)
3980 return ((ConstructorBuilder) builder).GetToken ().Token;
3982 throw new NotSupportedException ();
3986 public void CloseMethod ()
3988 if (CodeGen.SymbolWriter != null)
3989 CodeGen.SymbolWriter.CloseMethod ();
3992 public static SourceMethod Create (TypeContainer parent,
3993 MethodBase builder, Block block)
3995 if (CodeGen.SymbolWriter == null)
4000 Location start_loc = block.StartLocation;
4001 if (start_loc.IsNull)
4004 Location end_loc = block.EndLocation;
4008 ISourceFile file = start_loc.SourceFile;
4012 return new SourceMethod (
4013 parent, builder, file, start_loc, end_loc);
4017 public class Method : MethodCore, IIteratorContainer, IMethodData {
4018 public MethodBuilder MethodBuilder;
4019 public MethodData MethodData;
4020 ReturnParameter return_attributes;
4021 ListDictionary declarative_security;
4024 /// Modifiers allowed in a class declaration
4026 const int AllowedModifiers =
4029 Modifiers.PROTECTED |
4030 Modifiers.INTERNAL |
4035 Modifiers.OVERRIDE |
4036 Modifiers.ABSTRACT |
4038 Modifiers.METHOD_YIELDS |
4041 const int AllowedInterfaceModifiers =
4042 Modifiers.NEW | Modifiers.UNSAFE;
4045 // return_type can be "null" for VOID values.
4047 public Method (TypeContainer parent, GenericMethod generic,
4048 Expression return_type, int mod, bool is_iface,
4049 MemberName name, Parameters parameters, Attributes attrs)
4050 : base (parent, generic, return_type, mod,
4051 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4052 is_iface, name, attrs, parameters)
4056 public override AttributeTargets AttributeTargets {
4058 return AttributeTargets.Method;
4062 public override string GetSignatureForError()
4064 if (IsOperator != null)
4065 return IsOperator.GetSignatureForError ();
4067 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4070 void DuplicateEntryPoint (MethodInfo b, Location location)
4074 "Program `" + CodeGen.FileName +
4075 "' has more than one entry point defined: `" +
4076 TypeManager.CSharpSignature(b) + "'");
4079 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
4081 if (b.ReturnType != TypeManager.void_type &&
4082 b.ReturnType != TypeManager.int32_type)
4085 if (pinfo.Count == 0)
4088 if (pinfo.Count > 1)
4091 Type t = pinfo.ParameterType(0);
4093 (t.GetArrayRank() == 1) &&
4094 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
4095 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
4101 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4103 if (a.Target == AttributeTargets.ReturnValue) {
4104 if (return_attributes == null)
4105 return_attributes = new ReturnParameter (MethodBuilder, Location);
4107 return_attributes.ApplyAttributeBuilder (a, cb);
4111 if (a.Type == TypeManager.methodimpl_attr_type &&
4112 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4113 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4116 if (a.Type == TypeManager.dllimport_type) {
4117 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4118 if ((ModFlags & extern_static) != extern_static) {
4119 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
4125 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4126 if (declarative_security == null)
4127 declarative_security = new ListDictionary ();
4128 a.ExtractSecurityPermissionSet (declarative_security);
4132 if (a.Type == TypeManager.conditional_attribute_type) {
4133 if (IsOperator != null || IsExplicitImpl) {
4134 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4135 GetSignatureForError ());
4139 if (ReturnType != TypeManager.void_type) {
4140 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4144 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4145 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4150 Report.Error (582, Location, "Conditional not valid on interface members");
4154 if (MethodData.implementing != null) {
4155 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4156 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4160 for (int i = 0; i < parameter_info.Count; ++i) {
4161 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
4162 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4168 MethodBuilder.SetCustomAttribute (cb);
4171 protected override bool CheckForDuplications ()
4173 ArrayList ar = Parent.Methods;
4175 int arLen = ar.Count;
4177 for (int i = 0; i < arLen; i++) {
4178 Method m = (Method) ar [i];
4179 if (IsDuplicateImplementation (m))
4184 ar = Parent.Properties;
4186 for (int i = 0; i < ar.Count; ++i) {
4187 PropertyBase pb = (PropertyBase) ar [i];
4188 if (pb.AreAccessorsDuplicateImplementation (this))
4193 ar = Parent.Indexers;
4195 for (int i = 0; i < ar.Count; ++i) {
4196 PropertyBase pb = (PropertyBase) ar [i];
4197 if (pb.AreAccessorsDuplicateImplementation (this))
4204 for (int i = 0; i < ar.Count; ++i) {
4205 Event ev = (Event) ar [i];
4206 if (ev.AreAccessorsDuplicateImplementation (this))
4217 public override bool Define ()
4219 if (!DoDefineBase ())
4222 MethodBuilder mb = null;
4223 if (GenericMethod != null) {
4224 string method_name = MemberName.Name;
4226 if (IsExplicitImpl) {
4227 string iname = InterfaceType.FullName;
4229 iname = InterfaceType.Name;
4230 method_name = SimpleName.RemoveGenericArity (iname) + "." + method_name;
4233 mb = Parent.TypeBuilder.DefineGenericMethod (method_name, flags);
4234 if (!GenericMethod.Define (mb))
4241 if (!CheckAbstractAndExtern (block != null))
4244 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4245 Error1599 (Location, ReturnType);
4252 if (IsOperator != null)
4253 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
4255 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
4256 this, mb, GenericMethod, base_method);
4258 if (!MethodData.Define (Parent))
4261 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4262 Name == "Finalize" && !(this is Destructor)) {
4263 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4267 // Setup iterator if we are one
4269 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4270 Iterator iterator = new Iterator (
4271 this, Parent, GenericMethod, ParameterInfo, ModFlags);
4273 if (!iterator.DefineIterator ())
4277 MethodBuilder = MethodData.MethodBuilder;
4280 // This is used to track the Entry Point,
4282 if (Name == "Main" &&
4283 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
4284 (RootContext.MainClass == null ||
4285 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4286 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
4287 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4288 md.SetMemberIsUsed ();
4290 if (RootContext.EntryPoint == null) {
4291 if (Parent.IsGeneric){
4292 Report.Error (-201, Location,
4293 "Entry point can not be defined in a generic class");
4296 RootContext.EntryPoint = MethodBuilder;
4297 RootContext.EntryPointLocation = Location;
4299 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4300 DuplicateEntryPoint (MethodBuilder, Location);
4303 if (RootContext.WarningLevel >= 4)
4304 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
4308 if (MemberType.IsAbstract && MemberType.IsSealed) {
4309 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4319 public override void Emit ()
4321 MethodData.Emit (Parent, this);
4324 if (declarative_security != null) {
4325 foreach (DictionaryEntry de in declarative_security) {
4326 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4334 public static void Error1599 (Location loc, Type t)
4336 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4339 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4341 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
4342 container.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4347 base_ret_type = mi.ReturnType;
4351 public override bool MarkForDuplicationCheck ()
4353 caching_flags |= Flags.TestMethodDuplication;
4357 protected override bool VerifyClsCompliance(DeclSpace ds)
4359 if (!base.VerifyClsCompliance (ds))
4362 if (parameter_types.Length > 0) {
4363 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
4365 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4371 #region IMethodData Members
4373 public CallingConventions CallingConventions {
4375 CallingConventions cc = Parameters.GetCallingConvention ();
4376 if (Parameters.HasArglist)
4377 block.HasVarargs = true;
4380 if ((ModFlags & Modifiers.STATIC) == 0)
4381 cc |= CallingConventions.HasThis;
4383 // FIXME: How is `ExplicitThis' used in C#?
4389 public Type ReturnType {
4395 public MemberName MethodName {
4401 public new Location Location {
4403 return base.Location;
4407 protected override bool CheckBase() {
4408 if (!base.CheckBase ())
4411 // TODO: Destructor should derive from MethodCore
4412 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4413 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4414 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4421 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4423 EmitContext ec = new EmitContext (
4424 tc, ds, Location, ig, ReturnType, ModFlags, false);
4426 Iterator iterator = tc as Iterator;
4427 if (iterator != null)
4428 ec.CurrentAnonymousMethod = iterator.Host;
4434 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4436 public bool IsExcluded (EmitContext ec)
4438 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4439 return (caching_flags & Flags.Excluded) != 0;
4441 caching_flags &= ~Flags.Excluded_Undetected;
4443 if (base_method == null) {
4444 if (OptAttributes == null)
4447 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4452 foreach (Attribute a in attrs) {
4453 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4454 if (RootContext.AllDefines.Contains (condition))
4458 caching_flags |= Flags.Excluded;
4462 IMethodData md = TypeManager.GetMethod (base_method);
4464 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4465 caching_flags |= Flags.Excluded;
4471 if (md.IsExcluded (ec)) {
4472 caching_flags |= Flags.Excluded;
4478 GenericMethod IMethodData.GenericMethod {
4480 return GenericMethod;
4487 public abstract class ConstructorInitializer {
4488 ArrayList argument_list;
4489 protected ConstructorInfo base_constructor;
4492 public ConstructorInitializer (ArrayList argument_list, Location loc)
4494 this.argument_list = argument_list;
4498 public ArrayList Arguments {
4500 return argument_list;
4504 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4506 Expression base_constructor_group;
4510 ec.CurrentBlock = block;
4512 if (argument_list != null){
4513 foreach (Argument a in argument_list){
4514 if (!a.Resolve (ec, loc))
4518 ec.CurrentBlock = null;
4520 if (this is ConstructorBaseInitializer) {
4521 if (ec.ContainerType.BaseType == null)
4524 t = ec.ContainerType.BaseType;
4525 if (ec.ContainerType.IsValueType) {
4526 Report.Error (522, loc,
4527 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4531 t = ec.ContainerType;
4533 base_constructor_group = Expression.MemberLookup (
4534 ec, t, ".ctor", MemberTypes.Constructor,
4535 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4538 if (base_constructor_group == null){
4540 base_constructor_group = Expression.MemberLookup (
4541 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4542 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4546 int errors = Report.Errors;
4547 if (base_constructor_group != null)
4548 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4549 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4552 if (base_constructor == null) {
4553 if (errors == Report.Errors)
4554 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4555 argument_list.Count);
4560 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4561 base_constructor = null;
4565 if (base_constructor == caller_builder){
4566 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4573 public virtual void Emit (EmitContext ec)
4575 if (base_constructor != null){
4576 ec.Mark (loc, false);
4578 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4580 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4585 public class ConstructorBaseInitializer : ConstructorInitializer {
4586 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4587 base (argument_list, l)
4592 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4593 public GeneratedBaseInitializer (Location loc):
4598 public override void Emit(EmitContext ec)
4600 bool old = ec.TestObsoleteMethodUsage;
4601 ec.TestObsoleteMethodUsage = false;
4603 ec.TestObsoleteMethodUsage = old;
4607 public class ConstructorThisInitializer : ConstructorInitializer {
4608 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4609 base (argument_list, l)
4614 public class Constructor : MethodCore, IMethodData {
4615 public ConstructorBuilder ConstructorBuilder;
4616 public ConstructorInitializer Initializer;
4617 ListDictionary declarative_security;
4620 // Modifiers allowed for a constructor.
4622 public const int AllowedModifiers =
4624 Modifiers.PROTECTED |
4625 Modifiers.INTERNAL |
4631 bool has_compliant_args = false;
4633 // The spec claims that static is not permitted, but
4634 // my very own code has static constructors.
4636 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4637 ConstructorInitializer init, Location loc)
4638 : base (ds, null, null, mod, AllowedModifiers, false,
4639 new MemberName (name, loc), null, args)
4644 public bool HasCompliantArgs {
4646 return has_compliant_args;
4650 public override AttributeTargets AttributeTargets {
4652 return AttributeTargets.Constructor;
4658 // Returns true if this is a default constructor
4660 public bool IsDefault ()
4662 if ((ModFlags & Modifiers.STATIC) != 0)
4663 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4664 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4667 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4668 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4669 (Initializer is ConstructorBaseInitializer) &&
4670 (Initializer.Arguments == null);
4673 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4675 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4676 if (declarative_security == null) {
4677 declarative_security = new ListDictionary ();
4679 a.ExtractSecurityPermissionSet (declarative_security);
4683 ConstructorBuilder.SetCustomAttribute (cb);
4686 protected override bool CheckForDuplications ()
4688 ArrayList ar = Parent.InstanceConstructors;
4690 int arLen = ar.Count;
4692 for (int i = 0; i < arLen; i++) {
4693 Constructor m = (Constructor) ar [i];
4694 if (IsDuplicateImplementation (m))
4701 protected override bool CheckBase ()
4703 // Check whether arguments were correct.
4704 if (!DoDefineParameters ())
4707 // TODO: skip the rest for generated ctor
4708 if ((ModFlags & Modifiers.STATIC) != 0)
4711 if (!CheckForDuplications ())
4714 if (Parent.Kind == Kind.Struct) {
4715 if (ParameterTypes.Length == 0) {
4716 Report.Error (568, Location,
4717 "Structs cannot contain explicit parameterless constructors");
4721 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4722 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4727 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4728 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4735 // Creates the ConstructorBuilder
4737 public override bool Define ()
4739 if (ConstructorBuilder != null)
4742 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4743 MethodAttributes.SpecialName);
4745 if ((ModFlags & Modifiers.STATIC) != 0){
4746 ca |= MethodAttributes.Static | MethodAttributes.Private;
4748 ca |= MethodAttributes.HideBySig;
4750 if ((ModFlags & Modifiers.PUBLIC) != 0)
4751 ca |= MethodAttributes.Public;
4752 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4753 if ((ModFlags & Modifiers.INTERNAL) != 0)
4754 ca |= MethodAttributes.FamORAssem;
4756 ca |= MethodAttributes.Family;
4757 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4758 ca |= MethodAttributes.Assembly;
4759 else if (IsDefault ())
4760 ca |= MethodAttributes.Public;
4762 ca |= MethodAttributes.Private;
4765 if (!CheckAbstractAndExtern (block != null))
4768 // Check if arguments were correct.
4772 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4773 ca, CallingConventions,
4776 if ((ModFlags & Modifiers.UNSAFE) != 0)
4777 ConstructorBuilder.InitLocals = false;
4779 if (Parent.IsComImport) {
4780 if (!IsDefault ()) {
4781 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4782 Parent.GetSignatureForError ());
4785 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4788 TypeManager.AddMethod (ConstructorBuilder, this);
4791 // HACK because System.Reflection.Emit is lame
4793 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4801 public override void Emit ()
4803 EmitContext ec = CreateEmitContext (null, null);
4805 // If this is a non-static `struct' constructor and doesn't have any
4806 // initializer, it must initialize all of the struct's fields.
4807 if ((Parent.Kind == Kind.Struct) &&
4808 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4809 Block.AddThisVariable (Parent, Location);
4811 if (block != null) {
4812 if (!block.ResolveMeta (ec, ParameterInfo))
4816 if ((ModFlags & Modifiers.STATIC) == 0){
4817 if (Parent.Kind == Kind.Class && Initializer == null)
4818 Initializer = new GeneratedBaseInitializer (Location);
4822 // Spec mandates that Initializers will not have
4826 if ((Initializer != null) &&
4827 !Initializer.Resolve (ConstructorBuilder, block, ec))
4829 ec.IsStatic = false;
4832 Parameters.LabelParameters (ec, ConstructorBuilder);
4834 SourceMethod source = SourceMethod.Create (
4835 Parent, ConstructorBuilder, block);
4838 // Classes can have base initializers and instance field initializers.
4840 if (Parent.Kind == Kind.Class){
4841 if ((ModFlags & Modifiers.STATIC) == 0){
4844 // If we use a "this (...)" constructor initializer, then
4845 // do not emit field initializers, they are initialized in the other constructor
4847 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4848 Parent.EmitFieldInitializers (ec);
4851 if (Initializer != null) {
4852 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute () != null)
4853 ec.TestObsoleteMethodUsage = false;
4855 Initializer.Emit (ec);
4858 if ((ModFlags & Modifiers.STATIC) != 0)
4859 Parent.EmitFieldInitializers (ec);
4861 if (OptAttributes != null)
4862 OptAttributes.Emit (ec, this);
4864 ec.EmitTopBlock (this, block, ParameterInfo);
4867 source.CloseMethod ();
4871 if (declarative_security != null) {
4872 foreach (DictionaryEntry de in declarative_security) {
4873 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4880 // Is never override
4881 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4886 public override string GetSignatureForError()
4888 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4891 protected override bool VerifyClsCompliance (DeclSpace ds)
4893 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4897 if (parameter_types.Length > 0) {
4898 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4900 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4902 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4903 foreach (Type param in parameter_types) {
4904 if (param.IsArray) {
4910 has_compliant_args = true;
4914 #region IMethodData Members
4916 public System.Reflection.CallingConventions CallingConventions {
4918 CallingConventions cc = Parameters.GetCallingConvention ();
4920 if (Parent.Kind == Kind.Class)
4921 if ((ModFlags & Modifiers.STATIC) == 0)
4922 cc |= CallingConventions.HasThis;
4924 // FIXME: How is `ExplicitThis' used in C#?
4930 public new Location Location {
4932 return base.Location;
4936 public MemberName MethodName {
4942 public Type ReturnType {
4948 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4950 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4951 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4954 public bool IsExcluded(EmitContext ec)
4959 GenericMethod IMethodData.GenericMethod {
4969 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4971 public interface IMethodData
4973 CallingConventions CallingConventions { get; }
4974 Location Location { get; }
4975 MemberName MethodName { get; }
4976 Type[] ParameterTypes { get; }
4977 Type ReturnType { get; }
4978 GenericMethod GenericMethod { get; }
4980 Attributes OptAttributes { get; }
4981 ToplevelBlock Block { get; set; }
4983 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4984 ObsoleteAttribute GetObsoleteAttribute ();
4985 string GetSignatureForError ();
4986 bool IsExcluded (EmitContext ec);
4987 bool IsClsComplianceRequired (DeclSpace ds);
4988 void SetMemberIsUsed ();
4992 // Encapsulates most of the Method's state
4994 public class MethodData {
4996 readonly IMethodData method;
4999 // The return type of this method
5001 public readonly GenericMethod GenericMethod;
5002 public readonly InternalParameters ParameterInfo;
5005 // Are we implementing an interface ?
5007 public MethodInfo implementing;
5012 protected MemberBase member;
5013 protected int modifiers;
5014 protected MethodAttributes flags;
5015 protected Type declaring_type;
5016 protected MethodInfo parent_method;
5018 MethodBuilder builder = null;
5019 public MethodBuilder MethodBuilder {
5025 public Type DeclaringType {
5027 return declaring_type;
5031 public MethodData (MemberBase member, InternalParameters parameters,
5032 int modifiers, MethodAttributes flags, IMethodData method)
5034 this.member = member;
5035 this.ParameterInfo = parameters;
5036 this.modifiers = modifiers;
5039 this.method = method;
5042 public MethodData (MemberBase member, InternalParameters parameters,
5043 int modifiers, MethodAttributes flags,
5044 IMethodData method, MethodBuilder builder,
5045 GenericMethod generic, MethodInfo parent_method)
5046 : this (member, parameters, modifiers, flags, method)
5048 this.builder = builder;
5049 this.GenericMethod = generic;
5050 this.parent_method = parent_method;
5053 public bool Define (TypeContainer container)
5055 string name = method.MethodName.Basename;
5056 string method_name = method.MethodName.FullName;
5058 Type[] ParameterTypes = method.ParameterTypes;
5060 if (container.Pending != null){
5061 if (member is Indexer) // TODO: test it, but it should work without this IF
5062 implementing = container.Pending.IsInterfaceIndexer (
5063 member.InterfaceType, method.ReturnType, ParameterInfo);
5065 implementing = container.Pending.IsInterfaceMethod (
5066 member.InterfaceType, name, method.ReturnType, ParameterInfo);
5068 if (member.InterfaceType != null){
5069 if (implementing == null){
5070 if (member is PropertyBase) {
5071 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5072 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5073 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5076 Report.Error (539, method.Location,
5077 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5078 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5082 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5083 Report.SymbolRelatedToPreviousError (implementing);
5084 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5085 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5089 string iname = member.InterfaceType.FullName;
5091 iname = member.InterfaceType.Name;
5092 method_name = SimpleName.RemoveGenericArity (iname) + '.' + method_name;
5094 if (implementing != null) {
5095 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5096 if (prop_method != null) {
5097 if (!implementing.IsSpecialName) {
5098 Report.SymbolRelatedToPreviousError (implementing);
5099 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5100 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5103 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5104 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5105 Report.SymbolRelatedToPreviousError (implementing);
5106 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5107 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5116 // For implicit implementations, make sure we are public, for
5117 // explicit implementations, make sure we are private.
5119 if (implementing != null){
5121 // Setting null inside this block will trigger a more
5122 // verbose error reporting for missing interface implementations
5124 // The "candidate" function has been flagged already
5125 // but it wont get cleared
5127 if (member.IsExplicitImpl){
5128 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
5129 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
5130 implementing = null;
5132 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
5133 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
5135 // If this is an interface method implementation,
5136 // check for public accessibility
5138 implementing = null;
5139 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5140 // We may never be private.
5141 implementing = null;
5142 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5144 // We may be protected if we're overriding something.
5146 implementing = null;
5151 // Static is not allowed
5153 if ((modifiers & Modifiers.STATIC) != 0){
5154 implementing = null;
5159 // If implementing is still valid, set flags
5161 if (implementing != null){
5163 // When implementing interface methods, set NewSlot
5164 // unless, we are overwriting a method.
5166 if (implementing.DeclaringType.IsInterface){
5167 if ((modifiers & Modifiers.OVERRIDE) == 0)
5168 flags |= MethodAttributes.NewSlot;
5171 MethodAttributes.Virtual |
5172 MethodAttributes.HideBySig;
5174 // Set Final unless we're virtual, abstract or already overriding a method.
5175 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5176 flags |= MethodAttributes.Final;
5179 EmitContext ec = method.CreateEmitContext (container, null);
5181 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
5183 if (builder == null)
5186 if (container.CurrentType != null)
5187 declaring_type = container.CurrentType;
5189 declaring_type = container.TypeBuilder;
5191 if ((modifiers & Modifiers.UNSAFE) != 0)
5192 builder.InitLocals = false;
5194 if (implementing != null){
5196 // clear the pending implemntation flag
5198 if (member is Indexer) {
5199 container.Pending.ImplementIndexer (
5200 member.InterfaceType, builder, method.ReturnType,
5201 ParameterInfo, member.IsExplicitImpl);
5203 container.Pending.ImplementMethod (
5204 member.InterfaceType, name, method.ReturnType,
5205 ParameterInfo, member.IsExplicitImpl);
5207 if (member.IsExplicitImpl)
5208 container.TypeBuilder.DefineMethodOverride (
5209 builder, implementing);
5212 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
5213 TypeManager.AddMethod (builder, method);
5215 if (GenericMethod != null) {
5216 bool is_override = member.IsExplicitImpl |
5217 ((modifiers & Modifiers.OVERRIDE) != 0);
5219 if (implementing != null)
5220 parent_method = implementing;
5222 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5230 /// Create the MethodBuilder for the method
5232 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
5234 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
5236 if ((modifiers & extern_static) == extern_static) {
5238 if (method.OptAttributes != null) {
5239 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
5240 if (dllimport_attribute != null) {
5241 flags |= MethodAttributes.PinvokeImpl;
5242 builder = dllimport_attribute.DefinePInvokeMethod (
5243 ec, container.TypeBuilder, method_name, flags,
5244 method.ReturnType, ParameterTypes);
5250 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5251 // We are more strict than Microsoft and report CS0626 like error
5252 if (method.OptAttributes == null ||
5253 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
5254 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",
5255 method.GetSignatureForError ());
5260 if (builder == null)
5261 builder = container.TypeBuilder.DefineMethod (
5262 method_name, flags, method.CallingConventions,
5263 method.ReturnType, ParameterTypes);
5265 builder.SetGenericMethodSignature (
5266 flags, method.CallingConventions,
5267 method.ReturnType, ParameterTypes);
5273 public void Emit (TypeContainer container, Attributable kind)
5276 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5277 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
5279 ec = method.CreateEmitContext (container, null);
5281 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute () != null)
5282 ec.TestObsoleteMethodUsage = false;
5284 Attributes OptAttributes = method.OptAttributes;
5286 if (OptAttributes != null)
5287 OptAttributes.Emit (ec, kind);
5289 if (member is MethodCore)
5290 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
5292 ToplevelBlock block = method.Block;
5294 SourceMethod source = SourceMethod.Create (
5295 container, MethodBuilder, method.Block);
5298 // Handle destructors specially
5300 // FIXME: This code generates buggy code
5302 if (member is Destructor)
5303 EmitDestructor (ec, block);
5305 ec.EmitTopBlock (method, block, ParameterInfo);
5308 source.CloseMethod ();
5311 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5313 ILGenerator ig = ec.ig;
5315 Label finish = ig.DefineLabel ();
5317 block.SetDestructor ();
5319 ig.BeginExceptionBlock ();
5320 ec.ReturnLabel = finish;
5321 ec.HasReturnLabel = true;
5322 ec.EmitTopBlock (method, block, null);
5324 // ig.MarkLabel (finish);
5325 ig.BeginFinallyBlock ();
5327 if (ec.ContainerType.BaseType != null) {
5328 Expression member_lookup = Expression.MemberLookup (
5329 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5330 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5332 if (member_lookup != null){
5333 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5335 ig.Emit (OpCodes.Ldarg_0);
5336 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5340 ig.EndExceptionBlock ();
5341 //ig.MarkLabel (ec.ReturnLabel);
5342 ig.Emit (OpCodes.Ret);
5346 // TODO: Should derive from MethodCore
5347 public class Destructor : Method {
5349 public Destructor (TypeContainer ds, Expression return_type, int mod,
5350 string name, Parameters parameters, Attributes attrs,
5352 : base (ds, null, return_type, mod, false, new MemberName (name, l),
5356 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5358 if (a.Type == TypeManager.conditional_attribute_type) {
5359 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
5360 GetSignatureForError ());
5364 base.ApplyAttributeBuilder (a, cb);
5367 public override string GetSignatureForError ()
5369 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5374 abstract public class MemberBase : MemberCore {
5375 public Expression Type;
5377 public MethodAttributes flags;
5378 public readonly DeclSpace ds;
5379 public readonly GenericMethod GenericMethod;
5381 protected readonly int explicit_mod_flags;
5384 // The "short" name of this property / indexer / event. This is the
5385 // name without the explicit interface.
5387 public string ShortName {
5388 get { return MemberName.Name; }
5390 SetMemberName (new MemberName (MemberName.Left, value, Location));
5395 // The type of this property / indexer / event
5397 protected Type member_type;
5398 public Type MemberType {
5400 if (member_type == null && Type != null) {
5401 EmitContext ec = ds.EmitContext;
5402 bool old_unsafe = ec.InUnsafe;
5403 ec.InUnsafe = InUnsafe;
5404 ec.ResolvingGenericMethod = GenericMethod != null;
5405 Type = Type.ResolveAsTypeTerminal (ec);
5406 ec.ResolvingGenericMethod = false;
5407 ec.InUnsafe = old_unsafe;
5409 member_type = Type.Type;
5417 // Whether this is an interface member.
5419 public bool IsInterface;
5422 // If true, this is an explicit interface implementation
5424 public bool IsExplicitImpl;
5427 // The interface type we are explicitly implementing
5429 public Type InterfaceType = null;
5432 // The constructor is only exposed to our children
5434 protected MemberBase (TypeContainer parent, GenericMethod generic,
5435 Expression type, int mod, int allowed_mod, int def_mod,
5436 MemberName name, Attributes attrs)
5437 : base (parent, name, attrs)
5439 this.ds = generic != null ? generic : (DeclSpace) parent;
5440 explicit_mod_flags = mod;
5442 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5443 IsExplicitImpl = (MemberName.Left != null);
5444 GenericMethod = generic;
5447 protected virtual bool CheckBase ()
5449 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5450 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5454 if ((RootContext.WarningLevel >= 4) &&
5455 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5456 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5457 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5458 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5463 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5465 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5469 foreach (Type partype in parameters){
5470 if (partype == TypeManager.void_type) {
5472 1547, Location, "Keyword 'void' cannot " +
5473 "be used in this context");
5477 if (partype.IsPointer){
5480 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5484 if (ds.AsAccessible (partype, ModFlags))
5487 if (this is Indexer)
5488 Report.Error (55, Location,
5489 "Inconsistent accessibility: parameter type `" +
5490 TypeManager.CSharpName (partype) + "' is less " +
5491 "accessible than indexer `" + GetSignatureForError () + "'");
5492 else if ((this is Method) && ((Method) this).IsOperator != null)
5493 Report.Error (57, Location,
5494 "Inconsistent accessibility: parameter type `" +
5495 TypeManager.CSharpName (partype) + "' is less " +
5496 "accessible than operator `" + GetSignatureForError () + "'");
5498 Report.Error (51, Location,
5499 "Inconsistent accessibility: parameter type `" +
5500 TypeManager.CSharpName (partype) + "' is less " +
5501 "accessible than method `" + GetSignatureForError () + "'");
5508 protected virtual bool DoDefineBase ()
5510 EmitContext ec = Parent.EmitContext;
5512 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5515 throw new InternalErrorException ();
5518 ModFlags = Modifiers.PUBLIC |
5519 Modifiers.ABSTRACT |
5520 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5522 flags = MethodAttributes.Public |
5523 MethodAttributes.Abstract |
5524 MethodAttributes.HideBySig |
5525 MethodAttributes.NewSlot |
5526 MethodAttributes.Virtual;
5528 if (!Parent.MethodModifiersValid (this))
5531 flags = Modifiers.MethodAttr (ModFlags);
5534 if (IsExplicitImpl) {
5535 Expression expr = MemberName.Left.GetTypeExpression ();
5536 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5537 if (iface_texpr == null)
5540 InterfaceType = iface_texpr.ResolveType (ec);
5542 if (!InterfaceType.IsInterface) {
5543 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5547 if (!Parent.VerifyImplements (this))
5550 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5556 protected virtual bool DoDefine ()
5558 EmitContext ec = ds.EmitContext;
5560 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5562 ec.InUnsafe = InUnsafe;
5564 if (MemberType == null)
5567 CheckObsoleteType (Type);
5569 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5570 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5571 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5572 GetSignatureForError (), Parent.GetSignatureForError ());
5576 // verify accessibility
5577 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5578 Report.SymbolRelatedToPreviousError (MemberType);
5579 if (this is Property)
5580 Report.Error (53, Location,
5581 "Inconsistent accessibility: property type `" +
5582 TypeManager.CSharpName (MemberType) + "' is less " +
5583 "accessible than property `" + GetSignatureForError () + "'");
5584 else if (this is Indexer)
5585 Report.Error (54, Location,
5586 "Inconsistent accessibility: indexer return type `" +
5587 TypeManager.CSharpName (MemberType) + "' is less " +
5588 "accessible than indexer `" + GetSignatureForError () + "'");
5589 else if (this is MethodCore) {
5590 if (this is Operator)
5591 Report.Error (56, Location,
5592 "Inconsistent accessibility: return type `" +
5593 TypeManager.CSharpName (MemberType) + "' is less " +
5594 "accessible than operator `" + GetSignatureForError () + "'");
5596 Report.Error (50, Location,
5597 "Inconsistent accessibility: return type `" +
5598 TypeManager.CSharpName (MemberType) + "' is less " +
5599 "accessible than method `" + GetSignatureForError () + "'");
5601 Report.Error (52, Location,
5602 "Inconsistent accessibility: field type `" +
5603 TypeManager.CSharpName (MemberType) + "' is less " +
5604 "accessible than field `" + GetSignatureForError () + "'");
5609 if (MemberType.IsPointer && !UnsafeOK (Parent))
5612 if (IsExplicitImpl) {
5613 Expression expr = MemberName.Left.GetTypeExpression ();
5614 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
5618 InterfaceType = texpr.ResolveType (ec);
5620 if (!InterfaceType.IsInterface) {
5621 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5625 if (!Parent.VerifyImplements (this))
5628 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5634 protected bool IsTypePermitted ()
5636 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5637 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5643 protected override bool VerifyClsCompliance(DeclSpace ds)
5645 if (base.VerifyClsCompliance (ds)) {
5649 if (IsInterface && HasClsCompliantAttribute && ds.IsClsComplianceRequired (ds)) {
5650 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5658 // Fields and Events both generate FieldBuilders, we use this to share
5659 // their common bits. This is also used to flag usage of the field
5661 abstract public class FieldBase : MemberBase {
5662 public FieldBuilder FieldBuilder;
5663 public Status status;
5666 public enum Status : byte {
5667 HAS_OFFSET = 4 // Used by FieldMember.
5670 static string[] attribute_targets = new string [] { "field" };
5673 /// Symbol with same name in base class/struct
5675 public MemberInfo conflict_symbol;
5678 // The constructor is only exposed to our children
5680 protected FieldBase (TypeContainer parent, Expression type, int mod,
5681 int allowed_mod, MemberName name, object init,
5683 : base (parent, null, type, mod, allowed_mod, Modifiers.PRIVATE,
5689 public override AttributeTargets AttributeTargets {
5691 return AttributeTargets.Field;
5695 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5697 if (a.Type == TypeManager.marshal_as_attr_type) {
5698 UnmanagedMarshal marshal = a.GetMarshal (this);
5699 if (marshal != null) {
5700 FieldBuilder.SetMarshal (marshal);
5705 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5706 a.Error_InvalidSecurityParent ();
5710 FieldBuilder.SetCustomAttribute (cb);
5714 // Whether this field has an initializer.
5716 public bool HasInitializer {
5718 return init != null;
5722 protected readonly Object init;
5724 Expression init_expr;
5725 bool init_expr_initialized = false;
5727 protected override bool CheckGenericOverride (MethodInfo method, string name)
5733 // Resolves and returns the field initializer.
5735 public Expression GetInitializerExpression (EmitContext ec)
5737 if (init_expr_initialized)
5741 if (init is Expression)
5742 e = (Expression) init;
5744 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5746 // TODO: Any reason why we are using parent EC ?
5747 EmitContext parent_ec = Parent.EmitContext;
5749 bool old_is_static = parent_ec.IsStatic;
5750 bool old_is_ctor = parent_ec.IsConstructor;
5751 parent_ec.IsStatic = ec.IsStatic;
5752 parent_ec.IsConstructor = ec.IsConstructor;
5753 parent_ec.IsFieldInitializer = true;
5754 e = e.DoResolve (parent_ec);
5755 parent_ec.IsFieldInitializer = false;
5756 parent_ec.IsStatic = old_is_static;
5757 parent_ec.IsConstructor = old_is_ctor;
5760 init_expr_initialized = true;
5765 protected override bool CheckBase ()
5767 if (!base.CheckBase ())
5774 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5775 if (conflict_symbol == null) {
5776 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5777 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5782 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5783 Report.SymbolRelatedToPreviousError (conflict_symbol);
5784 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5785 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5791 protected virtual bool IsFieldClsCompliant {
5793 if (FieldBuilder == null)
5796 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5800 public override string[] ValidAttributeTargets {
5802 return attribute_targets;
5806 protected override bool VerifyClsCompliance (DeclSpace ds)
5808 if (!base.VerifyClsCompliance (ds))
5811 if (!IsFieldClsCompliant) {
5812 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5818 public void SetAssigned ()
5820 caching_flags |= Flags.IsAssigned;
5824 public abstract class FieldMember: FieldBase
5826 protected FieldMember (TypeContainer parent, Expression type, int mod,
5827 int allowed_mod, MemberName name, object init, Attributes attrs)
5828 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs)
5830 if ((mod & Modifiers.ABSTRACT) != 0)
5831 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5834 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5836 if (a.Type == TypeManager.field_offset_attribute_type)
5838 status |= Status.HAS_OFFSET;
5840 if (!Parent.HasExplicitLayout) {
5841 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5845 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5846 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5851 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5852 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5856 base.ApplyAttributeBuilder (a, cb);
5860 public override bool Define()
5862 EmitContext ec = Parent.EmitContext;
5864 throw new InternalErrorException ("FieldMember.Define called too early");
5866 if (MemberType == null || Type == null)
5869 CheckObsoleteType (Type);
5871 if (MemberType == TypeManager.void_type) {
5872 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5879 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5880 Report.Error (52, Location,
5881 "Inconsistent accessibility: field type `" +
5882 TypeManager.CSharpName (MemberType) + "' is less " +
5883 "accessible than field `" + GetSignatureForError () + "'");
5887 if (!IsTypePermitted ())
5890 if (MemberType.IsPointer && !UnsafeOK (Parent))
5896 public override void Emit ()
5898 if (OptAttributes != null) {
5899 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5900 OptAttributes.Emit (ec, this);
5903 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5904 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5911 // Represents header string for documentation comment.
5913 public override string DocCommentHeader {
5914 get { return "F:"; }
5918 interface IFixedBuffer
5920 FieldInfo Element { get; }
5921 Type ElementType { get; }
5924 public class FixedFieldExternal: IFixedBuffer
5926 FieldInfo element_field;
5928 public FixedFieldExternal (FieldInfo fi)
5930 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5933 #region IFixedField Members
5935 public FieldInfo Element {
5937 return element_field;
5941 public Type ElementType {
5943 return element_field.FieldType;
5951 /// Fixed buffer implementation
5953 public class FixedField: FieldMember, IFixedBuffer
5955 public const string FixedElementName = "FixedElementField";
5956 static int GlobalCounter = 0;
5957 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5958 static FieldInfo[] fi;
5960 TypeBuilder fixed_buffer_type;
5961 FieldBuilder element;
5962 Expression size_expr;
5965 const int AllowedModifiers =
5968 Modifiers.PROTECTED |
5969 Modifiers.INTERNAL |
5972 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5973 Expression size_expr, Attributes attrs, Location loc):
5974 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), null, attrs)
5976 if (RootContext.Version == LanguageVersion.ISO_1)
5977 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5979 this.size_expr = size_expr;
5982 public override bool Define()
5985 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5986 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5989 if (Parent.Kind != Kind.Struct) {
5990 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5991 GetSignatureForError ());
5995 if (!base.Define ())
5998 if (!TypeManager.IsPrimitiveType (MemberType)) {
5999 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",
6000 GetSignatureForError ());
6004 Constant c = size_expr.ResolveAsConstant (Parent.EmitContext, this);
6008 IntConstant buffer_size_const = c.ToInt (Location);
6009 if (buffer_size_const == null)
6012 buffer_size = buffer_size_const.Value;
6014 if (buffer_size <= 0) {
6015 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
6019 int type_size = Expression.GetTypeSize (MemberType);
6021 if (buffer_size > int.MaxValue / type_size) {
6022 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
6023 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
6027 buffer_size *= type_size;
6030 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
6032 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
6033 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
6034 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
6035 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
6037 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
6038 TypeManager.RegisterFieldBase (FieldBuilder, this);
6043 public override void Emit()
6046 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
6048 object[] fi_val = new object[1];
6049 fi_val [0] = buffer_size;
6051 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
6052 ctor_args, fi, fi_val);
6053 fixed_buffer_type.SetCustomAttribute (cab);
6055 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
6056 FieldBuilder.SetCustomAttribute (cab);
6060 protected override bool IsFieldClsCompliant {
6066 #region IFixedField Members
6068 public FieldInfo Element {
6074 public Type ElementType {
6084 // The Field class is used to represents class/struct fields during parsing.
6086 public class Field : FieldMember {
6088 // Modifiers allowed in a class declaration
6090 const int AllowedModifiers =
6093 Modifiers.PROTECTED |
6094 Modifiers.INTERNAL |
6097 Modifiers.VOLATILE |
6101 public Field (TypeContainer parent, Expression type, int mod, string name,
6102 Object expr_or_array_init, Attributes attrs, Location loc)
6103 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
6104 expr_or_array_init, attrs)
6108 public override bool Define ()
6110 if (!base.Define ())
6113 if (RootContext.WarningLevel > 1){
6114 Type ptype = Parent.TypeBuilder.BaseType;
6116 // ptype is only null for System.Object while compiling corlib.
6118 TypeContainer.FindMembers (
6119 ptype, MemberTypes.Method,
6120 BindingFlags.Public |
6121 BindingFlags.Static | BindingFlags.Instance,
6122 System.Type.FilterName, Name);
6126 if ((ModFlags & Modifiers.VOLATILE) != 0){
6127 if (!MemberType.IsClass){
6128 Type vt = MemberType;
6130 if (TypeManager.IsEnumType (vt))
6131 vt = TypeManager.EnumToUnderlying (MemberType);
6133 if (!((vt == TypeManager.bool_type) ||
6134 (vt == TypeManager.sbyte_type) ||
6135 (vt == TypeManager.byte_type) ||
6136 (vt == TypeManager.short_type) ||
6137 (vt == TypeManager.ushort_type) ||
6138 (vt == TypeManager.int32_type) ||
6139 (vt == TypeManager.uint32_type) ||
6140 (vt == TypeManager.char_type) ||
6141 (vt == TypeManager.float_type) ||
6142 (!vt.IsValueType))){
6143 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
6144 GetSignatureForError (), TypeManager.CSharpName (vt));
6149 if ((ModFlags & Modifiers.READONLY) != 0){
6150 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
6151 GetSignatureForError ());
6156 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6158 if (Parent.Kind == Kind.Struct &&
6159 ((fa & FieldAttributes.Static) == 0) &&
6160 MemberType == Parent.TypeBuilder &&
6161 !TypeManager.IsBuiltinType (MemberType)){
6162 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6163 "' causes a cycle in the structure layout");
6168 FieldBuilder = Parent.TypeBuilder.DefineField (
6169 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6171 TypeManager.RegisterFieldBase (FieldBuilder, this);
6173 catch (ArgumentException) {
6174 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6181 protected override bool VerifyClsCompliance (DeclSpace ds)
6183 if (!base.VerifyClsCompliance (ds))
6186 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6187 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6195 // `set' and `get' accessors are represented with an Accessor.
6197 public class Accessor : IIteratorContainer {
6199 // Null if the accessor is empty, or a Block if not
6201 public const int AllowedModifiers =
6203 Modifiers.PROTECTED |
6204 Modifiers.INTERNAL |
6207 public ToplevelBlock Block;
6208 public Attributes Attributes;
6209 public Location Location;
6210 public int ModFlags;
6213 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6218 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6221 public void SetYields ()
6227 // Ooouh Martin, templates are missing here.
6228 // When it will be possible move here a lot of child code and template method type.
6229 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6230 protected MethodData method_data;
6231 protected ToplevelBlock block;
6232 protected ListDictionary declarative_security;
6234 // The accessor are created event if they are not wanted.
6235 // But we need them because their names are reserved.
6236 // Field says whether accessor will be emited or not
6237 public readonly bool IsDummy;
6239 protected readonly string prefix;
6241 ReturnParameter return_attributes;
6243 public AbstractPropertyEventMethod (MemberBase member, string prefix)
6244 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6246 this.prefix = prefix;
6250 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
6252 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6253 accessor.Attributes)
6255 this.prefix = prefix;
6256 this.block = accessor.Block;
6259 static MemberName SetupName (string prefix, MemberBase member, Location loc)
6261 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6264 public void UpdateName (MemberBase member)
6266 SetMemberName (SetupName (prefix, member, Location));
6269 #region IMethodData Members
6271 public ToplevelBlock Block {
6281 public CallingConventions CallingConventions {
6283 return CallingConventions.Standard;
6287 public bool IsExcluded (EmitContext ec)
6292 GenericMethod IMethodData.GenericMethod {
6298 public MemberName MethodName {
6304 public abstract Type[] ParameterTypes { get; }
6305 public abstract Type ReturnType { get; }
6306 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
6310 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6312 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6313 a.Type == TypeManager.conditional_attribute_type) {
6314 Report.Error (1667, a.Location,
6315 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6316 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6320 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6321 if (declarative_security == null)
6322 declarative_security = new ListDictionary ();
6323 a.ExtractSecurityPermissionSet (declarative_security);
6327 if (a.Target == AttributeTargets.Method) {
6328 method_data.MethodBuilder.SetCustomAttribute (cb);
6332 if (a.Target == AttributeTargets.ReturnValue) {
6333 if (return_attributes == null)
6334 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6336 return_attributes.ApplyAttributeBuilder (a, cb);
6340 ApplyToExtraTarget (a, cb);
6343 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6345 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6348 public override bool Define()
6350 throw new NotSupportedException ();
6353 public virtual void Emit (TypeContainer container)
6355 EmitMethod (container);
6357 if (declarative_security != null) {
6358 foreach (DictionaryEntry de in declarative_security) {
6359 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6366 protected virtual void EmitMethod (TypeContainer container)
6368 method_data.Emit (container, this);
6371 public override bool IsClsComplianceRequired(DeclSpace ds)
6376 public bool IsDuplicateImplementation (MethodCore method)
6378 if (!MemberName.Equals (method.MemberName))
6381 Type[] param_types = method.ParameterTypes;
6383 if (param_types.Length != ParameterTypes.Length)
6386 for (int i = 0; i < param_types.Length; i++)
6387 if (param_types [i] != ParameterTypes [i])
6390 Report.SymbolRelatedToPreviousError (method);
6391 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
6395 public override bool IsUsed
6405 public new Location Location {
6407 return base.Location;
6412 // Represents header string for documentation comment.
6414 public override string DocCommentHeader {
6415 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6421 // Properties and Indexers both generate PropertyBuilders, we use this to share
6422 // their common bits.
6424 abstract public class PropertyBase : MethodCore {
6426 public class GetMethod: PropertyMethod
6428 static string[] attribute_targets = new string [] { "method", "return" };
6430 public GetMethod (MethodCore method):
6431 base (method, "get_")
6435 public GetMethod (MethodCore method, Accessor accessor):
6436 base (method, accessor, "get_")
6440 public override MethodBuilder Define(TypeContainer container)
6442 base.Define (container);
6444 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
6446 if (!method_data.Define (container))
6449 return method_data.MethodBuilder;
6452 public override Type ReturnType {
6454 return method.MemberType;
6458 public override string[] ValidAttributeTargets {
6460 return attribute_targets;
6465 public class SetMethod: PropertyMethod {
6467 static string[] attribute_targets = new string [] { "method", "param", "return" };
6468 ImplicitParameter param_attr;
6470 public SetMethod (MethodCore method):
6471 base (method, "set_")
6475 public SetMethod (MethodCore method, Accessor accessor):
6476 base (method, accessor, "set_")
6480 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6482 if (a.Target == AttributeTargets.Parameter) {
6483 if (param_attr == null)
6484 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6486 param_attr.ApplyAttributeBuilder (a, cb);
6490 base.ApplyAttributeBuilder (a, cb);
6493 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
6495 Parameter [] parms = new Parameter [1];
6496 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
6497 Parameters parameters = new Parameters (parms, null);
6499 bool old_unsafe = ec.InUnsafe;
6500 ec.InUnsafe = InUnsafe;
6501 Type [] types = parameters.GetParameterInfo (ec);
6502 ec.InUnsafe = old_unsafe;
6504 return new InternalParameters (types, parameters);
6507 public override MethodBuilder Define (TypeContainer container)
6509 if (container.EmitContext == null)
6510 throw new InternalErrorException ("SetMethod.Define called too early");
6512 base.Define (container);
6514 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6516 if (!method_data.Define (container))
6519 return method_data.MethodBuilder;
6522 public override Type[] ParameterTypes {
6524 return new Type[] { method.MemberType };
6528 public override Type ReturnType {
6530 return TypeManager.void_type;
6534 public override string[] ValidAttributeTargets {
6536 return attribute_targets;
6541 static string[] attribute_targets = new string [] { "property" };
6543 public abstract class PropertyMethod: AbstractPropertyEventMethod {
6544 protected readonly MethodCore method;
6545 protected MethodAttributes flags;
6548 public PropertyMethod (MethodCore method, string prefix)
6549 : base (method, prefix)
6551 this.method = method;
6554 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6555 : base (method, accessor, prefix)
6557 this.method = method;
6558 this.ModFlags = accessor.ModFlags;
6559 yields = accessor.Yields;
6561 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6562 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6566 public override AttributeTargets AttributeTargets {
6568 return AttributeTargets.Method;
6572 public override bool IsClsComplianceRequired(DeclSpace ds)
6574 return method.IsClsComplianceRequired (ds);
6577 public InternalParameters ParameterInfo
6580 return method_data.ParameterInfo;
6584 public virtual MethodBuilder Define (TypeContainer container)
6586 if (!method.CheckAbstractAndExtern (block != null))
6590 // Check for custom access modifier
6592 if (ModFlags == 0) {
6593 ModFlags = method.ModFlags;
6594 flags = method.flags;
6596 if (container.Kind == Kind.Interface)
6597 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6598 GetSignatureForError ());
6600 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6601 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6604 CheckModifiers (container, ModFlags);
6605 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6606 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6607 flags = Modifiers.MethodAttr (ModFlags);
6608 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6612 // Setup iterator if we are one
6615 Iterator iterator = new Iterator (
6616 this, Parent, null, method.ParameterInfo, ModFlags);
6618 if (!iterator.DefineIterator ())
6625 public bool HasCustomAccessModifier
6628 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6632 public override Type[] ParameterTypes {
6634 return TypeManager.NoTypes;
6638 public override EmitContext CreateEmitContext (TypeContainer tc,
6641 return new EmitContext (
6642 tc, method.ds, method.Location, ig, ReturnType,
6643 method.ModFlags, false);
6646 public override ObsoleteAttribute GetObsoleteAttribute ()
6648 return method.GetObsoleteAttribute ();
6651 public override string GetSignatureForError()
6653 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6656 void CheckModifiers (TypeContainer container, int modflags)
6659 int mflags = method.ModFlags & Modifiers.Accessibility;
6661 if ((mflags & Modifiers.PUBLIC) != 0) {
6662 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6664 else if ((mflags & Modifiers.PROTECTED) != 0) {
6665 if ((mflags & Modifiers.INTERNAL) != 0)
6666 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6668 flags |= Modifiers.PRIVATE;
6670 else if ((mflags & Modifiers.INTERNAL) != 0)
6671 flags |= Modifiers.PRIVATE;
6673 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6674 Report.Error (273, Location,
6675 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6676 GetSignatureForError (), method.GetSignatureForError ());
6680 public override bool MarkForDuplicationCheck ()
6682 caching_flags |= Flags.TestMethodDuplication;
6687 public PropertyMethod Get, Set;
6688 public PropertyBuilder PropertyBuilder;
6689 public MethodBuilder GetBuilder, SetBuilder;
6691 protected EmitContext ec;
6693 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6694 int allowed_mod, bool is_iface, MemberName name,
6695 Parameters parameters, Attributes attrs)
6696 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6701 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6703 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6704 a.Error_InvalidSecurityParent ();
6708 PropertyBuilder.SetCustomAttribute (cb);
6711 public override AttributeTargets AttributeTargets {
6713 return AttributeTargets.Property;
6717 public override bool Define ()
6722 if (!IsTypePermitted ())
6728 protected override bool DoDefine ()
6730 if (!base.DoDefine ())
6734 // Accessors modifiers check
6736 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6737 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6738 GetSignatureForError ());
6742 if ((Get.IsDummy || Set.IsDummy)
6743 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6744 Report.Error (276, Location,
6745 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6746 GetSignatureForError ());
6750 if (MemberType.IsAbstract && MemberType.IsSealed) {
6751 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6755 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6759 protected override bool CheckForDuplications ()
6761 ArrayList ar = Parent.Indexers;
6763 int arLen = ar.Count;
6765 for (int i = 0; i < arLen; i++) {
6766 Indexer m = (Indexer) ar [i];
6767 if (IsDuplicateImplementation (m))
6772 ar = Parent.Properties;
6774 int arLen = ar.Count;
6776 for (int i = 0; i < arLen; i++) {
6777 Property m = (Property) ar [i];
6778 if (IsDuplicateImplementation (m))
6786 // TODO: rename to Resolve......
6787 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6789 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6790 container.TypeBuilder, Name, ParameterTypes, null, true) as PropertyInfo;
6792 if (base_property == null)
6795 base_ret_type = base_property.PropertyType;
6796 MethodInfo get_accessor = base_property.GetGetMethod (true);
6797 MethodInfo set_accessor = base_property.GetSetMethod (true);
6798 MethodAttributes get_accessor_access, set_accessor_access;
6800 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6801 if (Get != null && !Get.IsDummy && get_accessor == null) {
6802 Report.SymbolRelatedToPreviousError (base_property);
6803 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6806 if (Set != null && !Set.IsDummy && set_accessor == null) {
6807 Report.SymbolRelatedToPreviousError (base_property);
6808 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6813 // Check base class accessors access
6816 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6817 get_accessor_access = set_accessor_access = 0;
6818 if ((ModFlags & Modifiers.NEW) == 0) {
6819 if (get_accessor != null) {
6820 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6821 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6823 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6824 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6827 if (set_accessor != null) {
6828 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6829 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6831 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6832 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6837 // Get the less restrictive access
6839 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6842 public override void Emit ()
6845 // The PropertyBuilder can be null for explicit implementations, in that
6846 // case, we do not actually emit the ".property", so there is nowhere to
6847 // put the attribute
6849 if (PropertyBuilder != null && OptAttributes != null)
6850 OptAttributes.Emit (ec, this);
6862 /// Tests whether accessors are not in collision with some method (CS0111)
6864 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6866 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6869 public override bool IsUsed
6875 return Get.IsUsed | Set.IsUsed;
6879 protected override void SetMemberName (MemberName new_name)
6881 base.SetMemberName (new_name);
6883 Get.UpdateName (this);
6884 Set.UpdateName (this);
6887 public override string[] ValidAttributeTargets {
6889 return attribute_targets;
6894 // Represents header string for documentation comment.
6896 public override string DocCommentHeader {
6897 get { return "P:"; }
6901 public class Property : PropertyBase {
6902 const int AllowedModifiers =
6905 Modifiers.PROTECTED |
6906 Modifiers.INTERNAL |
6910 Modifiers.OVERRIDE |
6911 Modifiers.ABSTRACT |
6914 Modifiers.METHOD_YIELDS |
6917 const int AllowedInterfaceModifiers =
6920 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6921 MemberName name, Attributes attrs, Accessor get_block,
6923 : base (ds, type, mod,
6924 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6925 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6927 if (get_block == null)
6928 Get = new GetMethod (this);
6930 Get = new GetMethod (this, get_block);
6932 if (set_block == null)
6933 Set = new SetMethod (this);
6935 Set = new SetMethod (this, set_block);
6938 public override bool Define ()
6940 if (!DoDefineBase ())
6943 if (!base.Define ())
6949 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6952 GetBuilder = Get.Define (Parent);
6953 if (GetBuilder == null)
6958 SetBuilder = Set.Define (Parent);
6959 if (SetBuilder == null)
6962 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6965 // FIXME - PropertyAttributes.HasDefault ?
6967 PropertyAttributes prop_attr = PropertyAttributes.None;
6969 prop_attr |= PropertyAttributes.RTSpecialName |
6970 PropertyAttributes.SpecialName;
6972 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6973 Name, prop_attr, MemberType, null);
6976 PropertyBuilder.SetGetMethod (GetBuilder);
6979 PropertyBuilder.SetSetMethod (SetBuilder);
6986 /// Gigantic workaround for lameness in SRE follows :
6987 /// This class derives from EventInfo and attempts to basically
6988 /// wrap around the EventBuilder so that FindMembers can quickly
6989 /// return this in it search for members
6991 public class MyEventBuilder : EventInfo {
6994 // We use this to "point" to our Builder which is
6995 // not really a MemberInfo
6997 EventBuilder MyBuilder;
7000 // We "catch" and wrap these methods
7002 MethodInfo raise, remove, add;
7004 EventAttributes attributes;
7005 Type declaring_type, reflected_type, event_type;
7010 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
7012 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
7014 // And now store the values in our own fields.
7016 declaring_type = type_builder;
7018 reflected_type = type_builder;
7020 attributes = event_attr;
7023 this.event_type = event_type;
7027 // Methods that you have to override. Note that you only need
7028 // to "implement" the variants that take the argument (those are
7029 // the "abstract" methods, the others (GetAddMethod()) are
7032 public override MethodInfo GetAddMethod (bool nonPublic)
7037 public override MethodInfo GetRemoveMethod (bool nonPublic)
7042 public override MethodInfo GetRaiseMethod (bool nonPublic)
7048 // These methods make "MyEventInfo" look like a Builder
7050 public void SetRaiseMethod (MethodBuilder raiseMethod)
7052 raise = raiseMethod;
7053 MyBuilder.SetRaiseMethod (raiseMethod);
7056 public void SetRemoveOnMethod (MethodBuilder removeMethod)
7058 remove = removeMethod;
7059 MyBuilder.SetRemoveOnMethod (removeMethod);
7062 public void SetAddOnMethod (MethodBuilder addMethod)
7065 MyBuilder.SetAddOnMethod (addMethod);
7068 public void SetCustomAttribute (CustomAttributeBuilder cb)
7070 MyBuilder.SetCustomAttribute (cb);
7073 public override object [] GetCustomAttributes (bool inherit)
7075 // FIXME : There's nothing which can be seemingly done here because
7076 // we have no way of getting at the custom attribute objects of the
7081 public override object [] GetCustomAttributes (Type t, bool inherit)
7083 // FIXME : Same here !
7087 public override bool IsDefined (Type t, bool b)
7092 public override EventAttributes Attributes {
7098 public override string Name {
7104 public override Type DeclaringType {
7106 return declaring_type;
7110 public override Type ReflectedType {
7112 return reflected_type;
7116 public Type EventType {
7122 public void SetUsed ()
7124 if (my_event != null) {
7125 my_event.SetAssigned ();
7126 my_event.SetMemberIsUsed ();
7132 /// For case when event is declared like property (with add and remove accessors).
7134 public class EventProperty: Event {
7136 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7138 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
7139 bool is_iface, MemberName name, Object init,
7140 Attributes attrs, Accessor add, Accessor remove)
7141 : base (parent, type, mod_flags, is_iface, name, init, attrs)
7143 Add = new AddDelegateMethod (this, add);
7144 Remove = new RemoveDelegateMethod (this, remove);
7146 // For this event syntax we don't report error CS0067
7147 // because it is hard to do it.
7151 public override string[] ValidAttributeTargets {
7153 return attribute_targets;
7159 /// Event is declared like field.
7161 public class EventField: Event {
7163 static string[] attribute_targets = new string [] { "event", "field", "method" };
7164 static string[] attribute_targets_interface = new string[] { "event", "method" };
7166 public EventField (TypeContainer parent, Expression type, int mod_flags,
7167 bool is_iface, MemberName name, Object init,
7169 : base (parent, type, mod_flags, is_iface, name, init, attrs)
7171 Add = new AddDelegateMethod (this);
7172 Remove = new RemoveDelegateMethod (this);
7175 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7177 if (a.Target == AttributeTargets.Field) {
7178 FieldBuilder.SetCustomAttribute (cb);
7182 if (a.Target == AttributeTargets.Method) {
7183 Add.ApplyAttributeBuilder (a, cb);
7184 Remove.ApplyAttributeBuilder (a, cb);
7188 base.ApplyAttributeBuilder (a, cb);
7191 public override string[] ValidAttributeTargets {
7193 return IsInterface ? attribute_targets_interface : attribute_targets;
7198 public abstract class Event : FieldBase {
7200 protected sealed class AddDelegateMethod: DelegateMethod
7203 public AddDelegateMethod (Event method):
7204 base (method, "add_")
7208 public AddDelegateMethod (Event method, Accessor accessor):
7209 base (method, accessor, "add_")
7213 protected override MethodInfo DelegateMethodInfo {
7215 return TypeManager.delegate_combine_delegate_delegate;
7221 protected sealed class RemoveDelegateMethod: DelegateMethod
7223 public RemoveDelegateMethod (Event method):
7224 base (method, "remove_")
7228 public RemoveDelegateMethod (Event method, Accessor accessor):
7229 base (method, accessor, "remove_")
7233 protected override MethodInfo DelegateMethodInfo {
7235 return TypeManager.delegate_remove_delegate_delegate;
7241 public abstract class DelegateMethod: AbstractPropertyEventMethod
7243 protected readonly Event method;
7244 ImplicitParameter param_attr;
7246 static string[] attribute_targets = new string [] { "method", "param", "return" };
7248 public DelegateMethod (Event method, string prefix)
7249 : base (method, prefix)
7251 this.method = method;
7254 public DelegateMethod (Event method, Accessor accessor, string prefix)
7255 : base (method, accessor, prefix)
7257 this.method = method;
7260 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7262 if (a.Target == AttributeTargets.Parameter) {
7263 if (param_attr == null)
7264 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
7266 param_attr.ApplyAttributeBuilder (a, cb);
7270 base.ApplyAttributeBuilder (a, cb);
7273 public override AttributeTargets AttributeTargets {
7275 return AttributeTargets.Method;
7279 public override bool IsClsComplianceRequired(DeclSpace ds)
7281 return method.IsClsComplianceRequired (ds);
7284 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
7286 method_data = new MethodData (method, ip, method.ModFlags,
7287 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7289 if (!method_data.Define (container))
7292 MethodBuilder mb = method_data.MethodBuilder;
7293 mb.DefineParameter (1, ParameterAttributes.None, "value");
7298 protected override void EmitMethod (TypeContainer tc)
7300 if (block != null) {
7301 base.EmitMethod (tc);
7305 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7308 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
7309 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
7311 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
7312 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7313 ig.Emit (OpCodes.Ldsfld, field_info);
7314 ig.Emit (OpCodes.Ldarg_0);
7315 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7316 ig.Emit (OpCodes.Castclass, method.MemberType);
7317 ig.Emit (OpCodes.Stsfld, field_info);
7319 ig.Emit (OpCodes.Ldarg_0);
7320 ig.Emit (OpCodes.Ldarg_0);
7321 ig.Emit (OpCodes.Ldfld, field_info);
7322 ig.Emit (OpCodes.Ldarg_1);
7323 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7324 ig.Emit (OpCodes.Castclass, method.MemberType);
7325 ig.Emit (OpCodes.Stfld, field_info);
7327 ig.Emit (OpCodes.Ret);
7330 protected abstract MethodInfo DelegateMethodInfo { get; }
7332 public override Type[] ParameterTypes {
7334 return new Type[] { method.MemberType };
7338 public override Type ReturnType {
7340 return TypeManager.void_type;
7344 public override EmitContext CreateEmitContext (TypeContainer tc,
7347 return new EmitContext (
7348 tc, method.Parent, Location, ig, ReturnType,
7349 method.ModFlags, false);
7352 public override ObsoleteAttribute GetObsoleteAttribute ()
7354 return method.GetObsoleteAttribute ();
7357 public override string[] ValidAttributeTargets {
7359 return attribute_targets;
7365 const int AllowedModifiers =
7368 Modifiers.PROTECTED |
7369 Modifiers.INTERNAL |
7374 Modifiers.OVERRIDE |
7378 const int AllowedInterfaceModifiers =
7381 public DelegateMethod Add, Remove;
7382 public MyEventBuilder EventBuilder;
7383 public MethodBuilder AddBuilder, RemoveBuilder;
7385 public Event (TypeContainer parent, Expression type, int mod_flags,
7386 bool is_iface, MemberName name, Object init, Attributes attrs)
7387 : base (parent, type, mod_flags,
7388 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7391 IsInterface = is_iface;
7394 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7396 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7397 a.Error_InvalidSecurityParent ();
7401 EventBuilder.SetCustomAttribute (cb);
7404 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7406 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7409 public override AttributeTargets AttributeTargets {
7411 return AttributeTargets.Event;
7415 public override bool Define ()
7417 EventAttributes e_attr;
7418 e_attr = EventAttributes.None;
7420 if (!DoDefineBase ())
7426 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
7427 Report.Error (74, Location, "`" + GetSignatureForError () +
7428 "': abstract event cannot have an initializer");
7432 if (!TypeManager.IsDelegateType (MemberType)) {
7433 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7437 EmitContext ec = Parent.EmitContext;
7439 throw new InternalErrorException ("Event.Define called too early?");
7440 bool old_unsafe = ec.InUnsafe;
7441 ec.InUnsafe = InUnsafe;
7443 Parameter [] parms = new Parameter [1];
7444 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
7445 Parameters parameters = new Parameters (parms, null);
7446 Type [] types = parameters.GetParameterInfo (ec);
7447 InternalParameters ip = new InternalParameters (types, parameters);
7449 ec.InUnsafe = old_unsafe;
7455 // Now define the accessors
7458 AddBuilder = Add.Define (Parent, ip);
7459 if (AddBuilder == null)
7462 RemoveBuilder = Remove.Define (Parent, ip);
7463 if (RemoveBuilder == null)
7466 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7468 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7469 FieldBuilder = Parent.TypeBuilder.DefineField (
7471 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7472 TypeManager.RegisterPrivateFieldOfEvent (
7473 (EventInfo) EventBuilder, FieldBuilder);
7474 TypeManager.RegisterFieldBase (FieldBuilder, this);
7477 EventBuilder.SetAddOnMethod (AddBuilder);
7478 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7480 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7484 protected override bool CheckBase ()
7486 if (!base.CheckBase ())
7489 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7490 if (!(conflict_symbol is EventInfo)) {
7491 Report.SymbolRelatedToPreviousError (conflict_symbol);
7492 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
7500 public override void Emit ()
7502 if (OptAttributes != null) {
7503 EmitContext ec = new EmitContext (
7504 Parent, Location, null, MemberType, ModFlags);
7505 OptAttributes.Emit (ec, this);
7509 Remove.Emit (Parent);
7514 public override string GetSignatureForError ()
7516 return base.GetSignatureForError ();
7520 // Represents header string for documentation comment.
7522 public override string DocCommentHeader {
7523 get { return "E:"; }
7528 public class Indexer : PropertyBase, IIteratorContainer {
7530 class GetIndexerMethod: GetMethod
7532 public GetIndexerMethod (MethodCore method):
7537 public GetIndexerMethod (MethodCore method, Accessor accessor):
7538 base (method, accessor)
7542 public override Type[] ParameterTypes {
7544 return method.ParameterTypes;
7549 class SetIndexerMethod: SetMethod
7551 readonly Parameters parameters;
7553 public SetIndexerMethod (MethodCore method):
7558 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7559 base (method, accessor)
7561 this.parameters = parameters;
7564 public override Type[] ParameterTypes {
7566 int top = method.ParameterTypes.Length;
7567 Type [] set_pars = new Type [top + 1];
7568 method.ParameterTypes.CopyTo (set_pars, 0);
7569 set_pars [top] = method.MemberType;
7574 protected override InternalParameters GetParameterInfo (EmitContext ec)
7576 Parameter [] fixed_parms = parameters.FixedParameters;
7578 if (fixed_parms == null){
7579 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7580 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7581 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7583 // Here is the problem: the `value' parameter has
7584 // to come *after* the array parameter in the declaration
7586 // X (object [] x, Type value)
7589 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7590 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7594 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7596 fixed_parms.CopyTo (tmp, 0);
7597 tmp [fixed_parms.Length] = new Parameter (
7598 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7600 Parameters set_formal_params = new Parameters (tmp, null);
7601 Type [] types = set_formal_params.GetParameterInfo (ec);
7603 return new InternalParameters (types, set_formal_params);
7607 const int AllowedModifiers =
7610 Modifiers.PROTECTED |
7611 Modifiers.INTERNAL |
7615 Modifiers.OVERRIDE |
7620 const int AllowedInterfaceModifiers =
7624 // Are we implementing an interface ?
7626 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7627 bool is_iface, Parameters parameters, Attributes attrs,
7628 Accessor get_block, Accessor set_block)
7629 : base (parent, type, mod,
7630 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7631 is_iface, name, parameters, attrs)
7633 if (get_block == null)
7634 Get = new GetIndexerMethod (this);
7636 Get = new GetIndexerMethod (this, get_block);
7638 if (set_block == null)
7639 Set = new SetIndexerMethod (this);
7641 Set = new SetIndexerMethod (this, parameters, set_block);
7644 public override bool Define ()
7646 PropertyAttributes prop_attr =
7647 PropertyAttributes.RTSpecialName |
7648 PropertyAttributes.SpecialName;
7650 if (!DoDefineBase ())
7653 if (!base.Define ())
7656 if (MemberType == TypeManager.void_type) {
7657 Report.Error (620, Location, "Indexers cannot have void type");
7661 if (OptAttributes != null) {
7662 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7663 if (indexer_attr != null) {
7664 // Remove the attribute from the list because it is not emitted
7665 OptAttributes.Attrs.Remove (indexer_attr);
7667 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7669 if (IsExplicitImpl) {
7670 Report.Error (415, indexer_attr.Location,
7671 "The `IndexerName' attribute is valid only on an " +
7672 "indexer that is not an explicit interface member declaration");
7676 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7677 Report.Error (609, indexer_attr.Location,
7678 "Cannot set the `IndexerName' attribute on an indexer marked override");
7682 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7683 Report.Error (633, indexer_attr.Location,
7684 "The argument to the `IndexerName' attribute must be a valid identifier");
7690 if (InterfaceType != null) {
7691 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7692 if (base_IndexerName != Name)
7693 ShortName = base_IndexerName;
7696 if (!Parent.AddToMemberContainer (this) ||
7697 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7703 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7705 GetBuilder = Get.Define (Parent);
7706 if (GetBuilder == null)
7710 // Setup iterator if we are one
7712 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7713 Iterator iterator = new Iterator (
7714 Get, Parent, null, Get.ParameterInfo, ModFlags);
7716 if (!iterator.DefineIterator ())
7722 SetBuilder = Set.Define (Parent);
7723 if (SetBuilder == null)
7728 // Now name the parameters
7730 Parameter [] p = Parameters.FixedParameters;
7732 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7733 Report.Error (631, Location, "ref and out are not valid in this context");
7739 for (i = 0; i < p.Length; ++i) {
7741 GetBuilder.DefineParameter (
7742 i + 1, p [i].Attributes, p [i].Name);
7745 SetBuilder.DefineParameter (
7746 i + 1, p [i].Attributes, p [i].Name);
7750 SetBuilder.DefineParameter (
7751 i + 1, ParameterAttributes.None, "value");
7753 if (i != ParameterTypes.Length) {
7754 Parameter array_param = Parameters.ArrayParameter;
7756 SetBuilder.DefineParameter (
7757 i + 1, array_param.Attributes, array_param.Name);
7761 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7762 Name, prop_attr, MemberType, ParameterTypes);
7765 PropertyBuilder.SetGetMethod (GetBuilder);
7768 PropertyBuilder.SetSetMethod (SetBuilder);
7770 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7775 public override string GetSignatureForError ()
7777 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7778 if (MemberName.Left != null) {
7780 sb.Append (MemberName.Left);
7783 sb.Append (".this");
7784 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7785 return sb.ToString ();
7788 public override bool MarkForDuplicationCheck ()
7790 caching_flags |= Flags.TestMethodDuplication;
7795 public class Operator : MethodCore, IIteratorContainer {
7797 const int AllowedModifiers =
7803 public enum OpType : byte {
7813 // Unary and Binary operators
7836 // Implicit and Explicit
7840 // Just because of enum
7844 public readonly OpType OperatorType;
7845 public MethodBuilder OperatorMethodBuilder;
7847 public Method OperatorMethod;
7849 static string[] attribute_targets = new string [] { "method", "return" };
7851 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7852 int mod_flags, Parameters parameters,
7853 ToplevelBlock block, Attributes attrs, Location loc)
7854 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7855 new MemberName ("op_" + type, loc), attrs, parameters)
7857 OperatorType = type;
7861 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7863 OperatorMethod.ApplyAttributeBuilder (a, cb);
7866 public override AttributeTargets AttributeTargets {
7868 return AttributeTargets.Method;
7872 protected override bool CheckGenericOverride (MethodInfo method, string name)
7877 protected override bool CheckForDuplications()
7879 ArrayList ar = Parent.Operators;
7881 int arLen = ar.Count;
7883 for (int i = 0; i < arLen; i++) {
7884 Operator o = (Operator) ar [i];
7885 if (IsDuplicateImplementation (o))
7890 ar = Parent.Methods;
7892 int arLen = ar.Count;
7894 for (int i = 0; i < arLen; i++) {
7895 Method m = (Method) ar [i];
7896 if (IsDuplicateImplementation (m))
7904 public override bool Define ()
7906 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7907 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7908 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7915 if (MemberType == TypeManager.void_type) {
7916 Report.Error (590, Location, "User-defined operators cannot return void");
7920 OperatorMethod = new Method (
7921 Parent, null, Type, ModFlags, false, MemberName,
7922 Parameters, OptAttributes);
7924 OperatorMethod.Block = Block;
7925 OperatorMethod.IsOperator = this;
7926 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7927 OperatorMethod.Define ();
7929 if (OperatorMethod.MethodBuilder == null)
7932 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7934 parameter_types = OperatorMethod.ParameterTypes;
7935 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7936 Type return_type = OperatorMethod.ReturnType;
7937 Type first_arg_type = parameter_types [0];
7942 // Rules for conversion operators
7944 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7945 if (first_arg_type == return_type && first_arg_type == declaring_type){
7946 Report.Error (555, Location,
7947 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7951 if (first_arg_type != declaring_type && return_type != declaring_type){
7954 "User-defined conversion must convert to or from the " +
7959 if (first_arg_type == TypeManager.object_type ||
7960 return_type == TypeManager.object_type){
7963 "User-defined conversion cannot convert to or from " +
7968 if (first_arg_type.IsInterface || return_type.IsInterface){
7969 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7970 GetSignatureForError ());
7974 if (first_arg_type.IsSubclassOf (return_type)
7975 || return_type.IsSubclassOf (first_arg_type)){
7976 if (declaring_type.IsSubclassOf (return_type)) {
7977 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7978 GetSignatureForError ());
7981 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7982 GetSignatureForError ());
7985 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7986 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7987 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");
7990 } else if (Parameters.FixedParameters.Length == 1) {
7991 // Checks for Unary operators
7993 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7994 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7995 Report.Error (448, Location,
7996 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7999 if (first_arg_type != declaring_type){
8001 559, Location, "The parameter type for ++ or -- operator must be the containing type");
8006 if (first_arg_type != declaring_type){
8009 "The parameter of a unary operator must be the " +
8014 if (OperatorType == OpType.True || OperatorType == OpType.False) {
8015 if (return_type != TypeManager.bool_type){
8018 "The return type of operator True or False " +
8025 // Checks for Binary operators
8027 if (first_arg_type != declaring_type &&
8028 parameter_types [1] != declaring_type){
8031 "One of the parameters of a binary operator must " +
8032 "be the containing type");
8040 public override void Emit ()
8043 // abstract or extern methods have no bodies
8045 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
8048 OperatorMethod.Emit ();
8052 // Operator cannot be override
8053 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
8058 public static string GetName (OpType ot)
8061 case OpType.LogicalNot:
8063 case OpType.OnesComplement:
8065 case OpType.Increment:
8067 case OpType.Decrement:
8073 case OpType.Addition:
8075 case OpType.Subtraction:
8077 case OpType.UnaryPlus:
8079 case OpType.UnaryNegation:
8081 case OpType.Multiply:
8083 case OpType.Division:
8085 case OpType.Modulus:
8087 case OpType.BitwiseAnd:
8089 case OpType.BitwiseOr:
8091 case OpType.ExclusiveOr:
8093 case OpType.LeftShift:
8095 case OpType.RightShift:
8097 case OpType.Equality:
8099 case OpType.Inequality:
8101 case OpType.GreaterThan:
8103 case OpType.LessThan:
8105 case OpType.GreaterThanOrEqual:
8107 case OpType.LessThanOrEqual:
8109 case OpType.Implicit:
8111 case OpType.Explicit:
8117 public static OpType GetOperatorType (string name)
8119 if (name.StartsWith ("op_")){
8120 for (int i = 0; i < Unary.oper_names.Length; ++i) {
8121 if (Unary.oper_names [i] == name)
8125 for (int i = 0; i < Binary.oper_names.Length; ++i) {
8126 if (Binary.oper_names [i] == name)
8133 public override string GetSignatureForError ()
8135 StringBuilder sb = new StringBuilder ();
8136 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8137 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
8140 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
8143 sb.Append (Parameters.GetSignatureForError ());
8144 return sb.ToString ();
8147 public override bool MarkForDuplicationCheck ()
8149 caching_flags |= Flags.TestMethodDuplication;
8153 public override string[] ValidAttributeTargets {
8155 return attribute_targets;
8161 // This is used to compare method signatures
8163 struct MethodSignature {
8165 public Type RetType;
8166 public Type [] Parameters;
8169 /// This delegate is used to extract methods which have the
8170 /// same signature as the argument
8172 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8174 public MethodSignature (string name, Type ret_type, Type [] parameters)
8179 if (parameters == null)
8180 Parameters = TypeManager.NoTypes;
8182 Parameters = parameters;
8185 public override string ToString ()
8188 if (Parameters.Length != 0){
8189 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8190 for (int i = 0; i < Parameters.Length; i++){
8191 sb.Append (Parameters [i]);
8192 if (i+1 < Parameters.Length)
8195 pars = sb.ToString ();
8198 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8201 public override int GetHashCode ()
8203 return Name.GetHashCode ();
8206 public override bool Equals (Object o)
8208 MethodSignature other = (MethodSignature) o;
8210 if (other.Name != Name)
8213 if (other.RetType != RetType)
8216 if (Parameters == null){
8217 if (other.Parameters == null)
8222 if (other.Parameters == null)
8225 int c = Parameters.Length;
8226 if (other.Parameters.Length != c)
8229 for (int i = 0; i < c; i++)
8230 if (other.Parameters [i] != Parameters [i])
8236 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8238 MethodSignature sig = (MethodSignature) filter_criteria;
8240 if (m.Name != sig.Name)
8244 MethodInfo mi = m as MethodInfo;
8245 PropertyInfo pi = m as PropertyInfo;
8248 ReturnType = mi.ReturnType;
8249 else if (pi != null)
8250 ReturnType = pi.PropertyType;
8255 // we use sig.RetType == null to mean `do not check the
8256 // method return value.
8258 if (sig.RetType != null)
8259 if (ReturnType != sig.RetType)
8264 args = TypeManager.GetArgumentTypes (mi);
8266 args = TypeManager.GetArgumentTypes (pi);
8267 Type [] sigp = sig.Parameters;
8269 if (args.Length != sigp.Length)
8272 for (int i = args.Length; i > 0; ){
8274 if (args [i] != sigp [i])