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 ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
128 Report.Warning (659, 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 Hashtable pairs = new Hashtable (null, null);
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 switch (op.OperatorType){
278 case Operator.OpType.Equality:
280 has_equality_or_inequality = true;
282 case Operator.OpType.Inequality:
284 has_equality_or_inequality = true;
287 case Operator.OpType.True:
290 case Operator.OpType.False:
294 case Operator.OpType.GreaterThan:
296 case Operator.OpType.LessThan:
299 case Operator.OpType.GreaterThanOrEqual:
301 case Operator.OpType.LessThanOrEqual:
307 OperatorEntry oe = new OperatorEntry (reg, op);
309 object o = pairs [oe];
313 oe = (OperatorEntry) o;
318 if (true_op != null){
319 if (false_op == null)
320 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
321 } else if (false_op != null)
322 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
325 // Look for the mistakes.
327 foreach (DictionaryEntry de in pairs){
328 OperatorEntry oe = (OperatorEntry) de.Key;
335 case Operator.OpType.Equality:
338 case Operator.OpType.Inequality:
341 case Operator.OpType.GreaterThan:
344 case Operator.OpType.LessThan:
347 case Operator.OpType.GreaterThanOrEqual:
350 case Operator.OpType.LessThanOrEqual:
354 Report.Error (216, oe.op.Location,
355 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
358 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
359 if (container.Methods == null || !container.Methods.HasEquals)
360 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
362 if (container.Methods == null || !container.Methods.HasGetHashCode)
363 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
367 public override void DefineContainerMembers ()
369 base.DefineContainerMembers ();
370 CheckPairedOperators ();
375 // Whether this is a struct, class or interface
376 public readonly Kind Kind;
378 // Holds a list of classes and structures
381 // Holds the list of properties
382 MemberCoreArrayList properties;
384 // Holds the list of enumerations
385 MemberCoreArrayList enums;
387 // Holds the list of delegates
388 MemberCoreArrayList delegates;
390 // Holds the list of constructors
391 protected MemberCoreArrayList instance_constructors;
393 // Holds the list of fields
394 MemberCoreArrayList fields;
396 // Holds a list of fields that have initializers
397 protected ArrayList initialized_fields;
399 // Holds a list of static fields that have initializers
400 protected ArrayList initialized_static_fields;
402 // Holds the list of constants
403 MemberCoreArrayList constants;
406 MemberCoreArrayList interfaces;
408 // Holds the methods.
409 MethodArrayList methods;
412 protected MemberCoreArrayList events;
414 // Holds the indexers
415 IndexerArrayList indexers;
417 // Holds the operators
418 MemberCoreArrayList operators;
420 // Holds the iterators
423 // Holds the parts of a partial class;
427 // Pointers to the default constructor and the default static constructor
429 protected Constructor default_constructor;
430 protected Constructor default_static_constructor;
433 // Whether we have at least one non-static field
435 bool have_nonstatic_fields = false;
438 // This one is computed after we can distinguish interfaces
439 // from classes from the arraylist `type_bases'
441 string base_class_name;
444 ArrayList type_bases;
446 bool members_defined;
447 bool members_defined_ok;
449 // The interfaces we implement.
450 protected Type[] ifaces;
451 protected Type ptype;
453 // The base member cache and our member cache
454 MemberCache base_cache;
455 MemberCache member_cache;
457 public const string DefaultIndexerName = "Item";
461 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
462 Attributes attrs, Kind kind, Location l)
463 : base (ns, parent, name, attrs, l)
467 types = new ArrayList ();
469 base_class_name = null;
472 public bool AddToMemberContainer (MemberCore symbol)
474 return AddToContainer (symbol, String.Concat (Name, '.', symbol.Name), symbol.Name);
477 bool AddToTypeContainer (DeclSpace ds)
479 return AddToContainer (ds, ds.Name, ds.Basename);
482 public void AddConstant (Const constant)
484 if (!AddToMemberContainer (constant))
487 if (constants == null)
488 constants = new MemberCoreArrayList ();
490 constants.Add (constant);
493 public void AddEnum (Mono.CSharp.Enum e)
495 if (!AddToTypeContainer (e))
499 enums = new MemberCoreArrayList ();
504 public void AddClassOrStruct (TypeContainer c)
506 if (!AddToTypeContainer (c))
512 public void AddDelegate (Delegate d)
514 if (!AddToTypeContainer (d))
517 if (delegates == null)
518 delegates = new MemberCoreArrayList ();
523 public void AddMethod (Method method)
525 if (!AddToMemberContainer (method))
529 methods = new MethodArrayList (this);
531 if (method.Name.IndexOf ('.') != -1)
532 methods.Insert (0, method);
534 methods.Add (method);
537 public void AddConstructor (Constructor c)
539 if (c.Name != Basename) {
540 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
543 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
546 if (default_static_constructor != null) {
547 Report.SymbolRelatedToPreviousError (default_static_constructor);
548 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
549 "called '{1}' with the same parameter types", Name, c.Name);
553 default_static_constructor = c;
556 if (default_constructor != null) {
557 Report.SymbolRelatedToPreviousError (default_constructor);
558 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
559 "called '{1}' with the same parameter types", Name, c.Name);
562 default_constructor = c;
565 if (instance_constructors == null)
566 instance_constructors = new MemberCoreArrayList ();
568 instance_constructors.Add (c);
572 public void AddInterface (TypeContainer iface)
574 if (!AddToTypeContainer (iface))
577 if (interfaces == null) {
578 interfaces = new MemberCoreArrayList ();
581 interfaces.Add (iface);
584 public void AddField (FieldMember field)
586 if (!AddToMemberContainer (field))
590 fields = new MemberCoreArrayList ();
594 if (field.HasInitializer){
595 if ((field.ModFlags & Modifiers.STATIC) != 0){
596 if (initialized_static_fields == null)
597 initialized_static_fields = new ArrayList ();
599 initialized_static_fields.Add (field);
602 if (initialized_fields == null)
603 initialized_fields = new ArrayList ();
605 initialized_fields.Add (field);
609 if ((field.ModFlags & Modifiers.STATIC) == 0)
610 have_nonstatic_fields = true;
613 public void AddProperty (Property prop)
615 if (!AddToMemberContainer (prop) ||
616 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
619 if (properties == null)
620 properties = new MemberCoreArrayList ();
622 if (prop.Name.IndexOf ('.') != -1)
623 properties.Insert (0, prop);
625 properties.Add (prop);
628 public void AddEvent (Event e)
630 if (!AddToMemberContainer (e))
633 if (e is EventProperty) {
634 if (!AddToMemberContainer (e.Add))
637 if (!AddToMemberContainer (e.Remove))
642 events = new MemberCoreArrayList ();
648 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
650 public void AddIndexer (Indexer i)
652 if (indexers == null)
653 indexers = new IndexerArrayList (this);
655 if (i.IsExplicitImpl)
656 indexers.Insert (0, i);
661 public void AddOperator (Operator op)
663 if (!AddToMemberContainer (op))
666 if (operators == null)
667 operators = new OperatorArrayList (this);
672 public void AddIterator (Iterator i)
674 if (iterators == null)
675 iterators = new ArrayList ();
680 public void AddType (TypeContainer tc)
685 public void AddPart (ClassPart part)
688 parts = new ArrayList ();
693 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
695 if (a.Type == TypeManager.default_member_type) {
696 if (Indexers != null) {
697 Report.Error (646, a.Location,
698 "Cannot specify the DefaultMember attribute on" +
699 " a type containing an indexer");
704 base.ApplyAttributeBuilder (a, cb);
707 public override AttributeTargets AttributeTargets {
711 return AttributeTargets.Class;
713 return AttributeTargets.Struct;
715 return AttributeTargets.Interface;
717 throw new NotSupportedException ();
722 public ArrayList Types {
728 public MethodArrayList Methods {
734 public ArrayList Constants {
740 public ArrayList Interfaces {
746 public ArrayList Iterators {
754 return base_class_name;
758 public ArrayList Bases {
768 public ArrayList Fields {
774 public ArrayList InstanceConstructors {
776 return instance_constructors;
780 public ArrayList Properties {
786 public ArrayList Events {
792 public ArrayList Enums {
798 public ArrayList Indexers {
804 public ArrayList Operators {
810 public ArrayList Delegates {
816 public ArrayList Parts {
822 public virtual TypeAttributes TypeAttr {
824 return Modifiers.TypeAttr (ModFlags, this);
828 public string IndexerName {
830 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
835 // Emits the instance field initializers
837 public bool EmitFieldInitializers (EmitContext ec)
840 Expression instance_expr;
843 fields = initialized_static_fields;
844 instance_expr = null;
846 fields = initialized_fields;
847 instance_expr = new This (Location.Null).Resolve (ec);
853 foreach (Field f in fields){
854 Expression e = f.GetInitializerExpression (ec);
858 Location l = f.Location;
859 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
860 fe.InstanceExpression = instance_expr;
861 fe.IsFieldInitializer = true;
863 ExpressionStatement a = new Assign (fe, e, l);
865 a = a.ResolveStatement (ec);
869 if (RootContext.Optimize) {
870 Constant c = e as Constant;
872 if (c.IsDefaultValue)
877 a.EmitStatement (ec);
884 // Defines the default constructors
886 protected void DefineDefaultConstructor (bool is_static)
890 // The default constructor is public
891 // If the class is abstract, the default constructor is protected
892 // The default static constructor is private
894 int mods = Modifiers.PUBLIC;
896 mods = Modifiers.STATIC | Modifiers.PRIVATE;
897 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
898 mods = Modifiers.PROTECTED;
900 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
901 new ConstructorBaseInitializer (
902 null, Parameters.EmptyReadOnlyParameters,
908 c.Block = new ToplevelBlock (null, Location);
913 /// The pending methods that need to be implemented
914 // (interfaces or abstract methods)
916 public PendingImplementation Pending;
918 public abstract void Register ();
920 public abstract PendingImplementation GetPendingImplementations ();
922 TypeExpr[] GetPartialBases (out TypeExpr base_class, out bool error)
924 ArrayList ifaces = new ArrayList ();
927 Location base_loc = Location.Null;
929 foreach (ClassPart part in parts) {
930 TypeExpr new_base_class;
931 TypeExpr[] new_ifaces;
933 new_ifaces = part.GetClassBases (out new_base_class, out error);
937 if ((base_class != null) && (new_base_class != null) &&
938 !base_class.Equals (new_base_class)) {
939 Report.Error (263, part.Location,
940 "Partial declarations of `{0}' must " +
941 "not specify different base classes",
944 if (!Location.IsNull (base_loc))
945 Report.LocationOfPreviousError (base_loc);
951 if ((base_class == null) && (new_base_class != null)) {
952 base_class = new_base_class;
953 base_loc = part.Location;
956 if (new_ifaces == null)
959 foreach (TypeExpr iface in new_ifaces) {
961 foreach (TypeExpr old_iface in ifaces) {
962 if (old_iface.Equals (iface)) {
975 TypeExpr[] retval = new TypeExpr [ifaces.Count];
976 ifaces.CopyTo (retval, 0);
980 TypeExpr[] GetNormalBases (out TypeExpr base_class, out bool error)
984 int count = Bases.Count;
987 if (Kind == Kind.Class){
988 TypeExpr name = ResolveBaseTypeExpr (
989 (Expression) Bases [0], false, Location);
996 if (!name.IsInterface) {
997 // base_class could be a class, struct, enum, delegate.
998 // This is validated in GetClassBases.
1004 TypeExpr [] ifaces = new TypeExpr [count-start];
1006 for (i = start, j = 0; i < count; i++, j++){
1007 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1008 if (resolved == null) {
1013 ifaces [j] = resolved;
1021 /// This function computes the Base class and also the
1022 /// list of interfaces that the class or struct @c implements.
1024 /// The return value is an array (might be null) of
1025 /// interfaces implemented (as Types).
1027 /// The @base_class argument is set to the base object or null
1028 /// if this is `System.Object'.
1030 TypeExpr [] GetClassBases (out TypeExpr base_class, out bool error)
1039 ifaces = GetPartialBases (out base_class, out error);
1040 else if (Bases == null){
1044 ifaces = GetNormalBases (out base_class, out error);
1049 if ((base_class != null) && (Kind == Kind.Class)){
1050 if (base_class is TypeParameterExpr){
1052 689, base_class.Location,
1053 "Type parameter `{0}' can not be used as a " +
1054 "base class or interface", base_class.Name);
1059 if (IsGeneric && base_class.Type.IsSubclassOf (TypeManager.attribute_type)){
1061 698, base_class.Location,
1062 "A generic type cannot derive from `{0}' " +
1063 "because it is an attribute class",
1069 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1070 Report.Error (1521, base_class.Location, "Invalid base type");
1075 if (base_class.IsSealed){
1077 Report.SymbolRelatedToPreviousError (base_class.Type);
1078 if (base_class.Type.IsAbstract) {
1079 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1081 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1086 if (!base_class.CanInheritFrom ()){
1087 Report.Error (644, Location,
1088 "`{0}' cannot inherit from special class `{1}'",
1089 Name, base_class.Name);
1094 if (!base_class.AsAccessible (this, ModFlags)) {
1095 Report.SymbolRelatedToPreviousError (base_class.Type);
1096 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1097 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1101 if (base_class != null)
1102 base_class_name = base_class.Name;
1107 int count = ifaces != null ? ifaces.Length : 0;
1109 for (i = 0; i < count; i++) {
1110 TypeExpr iface = (TypeExpr) ifaces [i];
1112 if (!iface.IsInterface) {
1114 if (Kind != Kind.Class) {
1115 string what = Kind == Kind.Struct ? "Struct" : "Interface";
1117 Report.Error (527, Location,
1118 "In {0} `{1}', type `{2}' is not "+
1119 "an interface", what, Name, iface.Name);
1121 else if (base_class != null)
1122 Report.Error (1721, Location,
1123 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1126 Report.Error (1722, Location,
1127 "In Class `{0}', `{1}' is not " +
1128 "an interface, a base class must be listed first", Name, iface.Name);
1133 for (int x = 0; x < i; x++) {
1134 if (iface.Equals (ifaces [x])) {
1135 Report.Error (528, Location,
1136 "`{0}' is already listed in " +
1137 "interface list", iface.Name);
1142 if ((Kind == Kind.Interface) &&
1143 !iface.AsAccessible (Parent, ModFlags)) {
1144 Report.Error (61, Location,
1145 "Inconsistent accessibility: base " +
1146 "interface `{0}' is less accessible " +
1147 "than interface `{1}'", iface.Name,
1159 bool CheckGenericInterfaces (Type[] ifaces)
1161 ArrayList already_checked = new ArrayList ();
1163 for (int i = 0; i < ifaces.Length; i++) {
1164 Type iface = ifaces [i];
1165 foreach (Type t in already_checked) {
1169 Type[] infered = new Type [CountTypeParameters];
1170 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1175 "`{0}' cannot implement both `{1}' and `{2}' " +
1176 "because they may unify for some type " +
1177 "parameter substitutions",
1178 TypeManager.GetFullName (TypeBuilder),
1183 already_checked.Add (iface);
1192 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1194 public override TypeBuilder DefineType ()
1199 if (TypeBuilder != null)
1202 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1204 TypeAttributes type_attributes = TypeAttr;
1208 if (TypeManager.NamespaceClash (Name, Location)) {
1213 ModuleBuilder builder = CodeGen.Module.Builder;
1214 TypeBuilder = builder.DefineType (
1215 Name, type_attributes, null, null);
1217 TypeBuilder builder;
1218 if (Parent.TypeBuilder != null)
1219 builder = Parent.TypeBuilder;
1221 builder = Parent.DefineType ();
1223 if (builder == null) {
1228 TypeBuilder = builder.DefineNestedType (
1229 MemberName.Basename, type_attributes,
1233 catch (ArgumentException) {
1234 Report.RuntimeMissingSupport (Location, "static classes");
1238 TypeManager.AddUserType (Name, TypeBuilder, this);
1240 Expression current_type = null;
1243 string[] param_names = new string [TypeParameters.Length];
1244 for (int i = 0; i < TypeParameters.Length; i++)
1245 param_names [i] = TypeParameters [i].Name;
1247 GenericTypeParameterBuilder[] gen_params;
1248 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1250 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1251 for (int i = offset; i < gen_params.Length; i++)
1252 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1254 foreach (TypeParameter type_param in CurrentTypeParameters) {
1255 if (!type_param.Resolve (this)) {
1261 for (int i = offset; i < gen_params.Length; i++)
1262 CurrentTypeParameters [i - offset].DefineConstraints ();
1264 current_type = new SimpleName (Name, TypeParameters, Location);
1266 foreach (TypeParameter type_param in TypeParameters) {
1267 if (!type_param.DefineType (ec)) {
1273 if (!CheckConstraints (ec)) {
1279 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1280 throw new Exception ();
1282 TypeExpr[] iface_exprs = GetClassBases (out base_type, out error);
1286 if (base_type == null) {
1287 if (Kind == Kind.Class){
1288 if (RootContext.StdLib)
1289 base_type = TypeManager.system_object_expr;
1290 else if (Name != "System.Object")
1291 base_type = TypeManager.system_object_expr;
1292 } else if (Kind == Kind.Struct){
1294 // If we are compiling our runtime,
1295 // and we are defining ValueType, then our
1296 // base is `System.Object'.
1298 if (!RootContext.StdLib && Name == "System.ValueType")
1299 base_type = TypeManager.system_object_expr;
1300 else if (Kind == Kind.Struct)
1301 base_type = TypeManager.system_valuetype_expr;
1305 if (base_type != null) {
1306 base_type = base_type.ResolveAsTypeTerminal (ec);
1307 if (base_type == null) {
1312 ptype = base_type.Type;
1315 if (!CheckRecursiveDefinition ()) {
1321 TypeBuilder.SetParent (ptype);
1324 // Structs with no fields need to have at least one byte.
1325 // The right thing would be to set the PackingSize in a DefineType
1326 // but there are no functions that allow interfaces *and* the size to
1330 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1331 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1332 FieldAttributes.Private);
1335 // add interfaces that were not added at type creation
1336 if (iface_exprs != null) {
1337 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1338 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1339 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1340 if (ifaces == null) {
1345 foreach (Type itype in ifaces)
1346 TypeBuilder.AddInterfaceImplementation (itype);
1348 if (!CheckGenericInterfaces (ifaces)) {
1353 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1357 foreach (TypeParameter type_param in TypeParameters)
1358 if (!type_param.CheckDependencies (ec)) {
1364 if (current_type != null) {
1365 current_type = current_type.ResolveAsTypeTerminal (ec);
1366 if (current_type == null) {
1371 CurrentType = current_type.Type;
1375 // Finish the setup for the EmitContext
1377 ec.ContainerType = TypeBuilder;
1379 if (!(this is Iterator))
1380 RootContext.RegisterOrder (this);
1382 if (!DefineNestedTypes ()) {
1390 protected virtual bool CheckConstraints (EmitContext ec)
1395 protected virtual bool DefineNestedTypes ()
1397 if (Interfaces != null) {
1398 foreach (TypeContainer iface in Interfaces)
1399 if (iface.DefineType () == null)
1403 if (Types != null) {
1404 foreach (TypeContainer tc in Types)
1405 if (tc.DefineType () == null)
1409 if (Delegates != null) {
1410 foreach (Delegate d in Delegates)
1411 if (d.DefineType () == null)
1415 if (Enums != null) {
1416 foreach (Enum en in Enums)
1417 if (en.DefineType () == null)
1421 if (Parts != null) {
1422 foreach (ClassPart part in Parts) {
1423 part.TypeBuilder = TypeBuilder;
1424 part.base_type = base_type;
1425 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1432 protected bool CheckRecursiveDefinition ()
1435 Report.Error (146, Location,
1436 "Class definition is circular: `{0}'",
1437 GetSignatureForError ());
1444 Type parent = ptype;
1445 if (parent != null) {
1446 if (parent.IsGenericInstance)
1447 parent = parent.GetGenericTypeDefinition ();
1449 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1450 if ((ptc != null) && !ptc.CheckRecursiveDefinition ())
1458 static void Error_KeywordNotAllowed (Location loc)
1460 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1464 /// Populates our TypeBuilder with fields and methods
1466 public override bool DefineMembers (TypeContainer container)
1468 if (members_defined)
1469 return members_defined_ok;
1471 members_defined_ok = DoDefineMembers ();
1472 members_defined = true;
1474 return members_defined_ok;
1477 protected virtual bool DoDefineMembers ()
1480 if ((ModFlags & Modifiers.NEW) != 0)
1481 Error_KeywordNotAllowed (Location);
1483 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1484 if (conflict_symbol == null) {
1485 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1486 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1488 if ((ModFlags & Modifiers.NEW) == 0) {
1489 Report.SymbolRelatedToPreviousError (conflict_symbol);
1490 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1495 DefineContainerMembers (constants);
1496 DefineContainerMembers (fields);
1498 if ((Kind == Kind.Class) && !(this is ClassPart)){
1499 if ((instance_constructors == null) &&
1500 !(this is StaticClass)) {
1501 if (default_constructor == null)
1502 DefineDefaultConstructor (false);
1505 if (initialized_static_fields != null &&
1506 default_static_constructor == null)
1507 DefineDefaultConstructor (true);
1510 if (Kind == Kind.Struct){
1512 // Structs can not have initialized instance
1515 if (initialized_static_fields != null &&
1516 default_static_constructor == null)
1517 DefineDefaultConstructor (true);
1519 if (initialized_fields != null)
1520 ReportStructInitializedInstanceError ();
1523 Pending = GetPendingImplementations ();
1525 if (parts != null) {
1526 foreach (ClassPart part in parts) {
1527 if (!part.DefineMembers (this))
1533 // Constructors are not in the defined_names array
1535 DefineContainerMembers (instance_constructors);
1537 if (default_static_constructor != null)
1538 default_static_constructor.Define ();
1540 DefineContainerMembers (properties);
1541 DefineContainerMembers (events);
1542 DefineContainerMembers (indexers);
1543 DefineContainerMembers (methods);
1544 DefineContainerMembers (operators);
1545 DefineContainerMembers (enums);
1546 DefineContainerMembers (delegates);
1548 if (CurrentType != null) {
1549 GenericType = CurrentType;
1551 ec.ContainerType = GenericType;
1556 if (!(this is ClassPart))
1557 member_cache = new MemberCache (this);
1560 if (parts != null) {
1561 foreach (ClassPart part in parts)
1562 part.member_cache = member_cache;
1565 if (iterators != null) {
1566 foreach (Iterator iterator in iterators) {
1567 if (iterator.DefineType () == null)
1571 foreach (Iterator iterator in iterators) {
1572 if (!iterator.DefineMembers (this))
1580 void ReportStructInitializedInstanceError ()
1582 string n = TypeBuilder.FullName;
1584 foreach (Field f in initialized_fields){
1587 "`" + n + "." + f.Name + "': can not have " +
1588 "instance field initializers in structs");
1592 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1595 mcal.DefineContainerMembers ();
1598 public override bool Define ()
1600 if (parts != null) {
1601 foreach (ClassPart part in parts) {
1602 if (!part.Define ())
1610 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1612 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1616 /// This function is based by a delegate to the FindMembers routine
1618 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1624 /// This filter is used by FindMembers, and we just keep
1625 /// a global for the filter to `AlwaysAccept'
1627 static MemberFilter accepting_filter;
1630 static TypeContainer ()
1632 accepting_filter = new MemberFilter (AlwaysAccept);
1635 public MethodInfo[] GetMethods ()
1637 ArrayList members = new ArrayList ();
1639 DefineMembers (null);
1641 if (methods != null) {
1642 int len = methods.Count;
1643 for (int i = 0; i < len; i++) {
1644 Method m = (Method) methods [i];
1646 members.Add (m.MethodBuilder);
1650 if (operators != null) {
1651 int len = operators.Count;
1652 for (int i = 0; i < len; i++) {
1653 Operator o = (Operator) operators [i];
1655 members.Add (o.OperatorMethodBuilder);
1659 if (properties != null) {
1660 int len = properties.Count;
1661 for (int i = 0; i < len; i++) {
1662 Property p = (Property) properties [i];
1664 if (p.GetBuilder != null)
1665 members.Add (p.GetBuilder);
1666 if (p.SetBuilder != null)
1667 members.Add (p.SetBuilder);
1671 if (indexers != null) {
1672 int len = indexers.Count;
1673 for (int i = 0; i < len; i++) {
1674 Indexer ix = (Indexer) indexers [i];
1676 if (ix.GetBuilder != null)
1677 members.Add (ix.GetBuilder);
1678 if (ix.SetBuilder != null)
1679 members.Add (ix.SetBuilder);
1683 if (events != null) {
1684 int len = events.Count;
1685 for (int i = 0; i < len; i++) {
1686 Event e = (Event) events [i];
1688 if (e.AddBuilder != null)
1689 members.Add (e.AddBuilder);
1690 if (e.RemoveBuilder != null)
1691 members.Add (e.RemoveBuilder);
1695 MethodInfo[] retMethods = new MethodInfo [members.Count];
1696 members.CopyTo (retMethods, 0);
1700 // Indicated whether container has StructLayout attribute set Explicit
1701 public virtual bool HasExplicitLayout {
1707 public override Type FindNestedType (string name)
1709 ArrayList [] lists = { types, enums, delegates, interfaces };
1711 for (int j = 0; j < lists.Length; ++j) {
1712 ArrayList list = lists [j];
1716 int len = list.Count;
1717 for (int i = 0; i < len; ++i) {
1718 DeclSpace ds = (DeclSpace) list [i];
1719 if (ds.Basename_with_arity == name) {
1721 return ds.TypeBuilder;
1726 if (Parts != null) {
1727 foreach (ClassPart cp in Parts) {
1728 Type t = cp.PartFindNestedType (name);
1737 private void FindMembers_NestedTypes (int modflags,
1738 BindingFlags bf, MemberFilter filter, object criteria,
1739 ref ArrayList members)
1741 ArrayList [] lists = { types, enums, delegates, interfaces };
1743 for (int j = 0; j < lists.Length; ++j) {
1744 ArrayList list = lists [j];
1748 int len = list.Count;
1749 for (int i = 0; i < len; i++) {
1750 DeclSpace ds = (DeclSpace) list [i];
1752 if ((ds.ModFlags & modflags) == 0)
1755 TypeBuilder tb = ds.TypeBuilder;
1757 if (!(criteria is string) || ds.Basename.Equals (criteria))
1758 tb = ds.DefineType ();
1761 if (tb != null && (filter (tb, criteria) == true)) {
1762 if (members == null)
1763 members = new ArrayList ();
1772 /// This method returns the members of this type just like Type.FindMembers would
1773 /// Only, we need to use this for types which are _being_ defined because MS'
1774 /// implementation can't take care of that.
1777 // FIXME: return an empty static array instead of null, that cleans up
1778 // some code and is consistent with some coding conventions I just found
1782 // Notice that in various cases we check if our field is non-null,
1783 // something that would normally mean that there was a bug elsewhere.
1785 // The problem happens while we are defining p-invoke methods, as those
1786 // will trigger a FindMembers, but this happens before things are defined
1788 // Since the whole process is a no-op, it is fine to check for null here.
1790 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1791 MemberFilter filter, object criteria)
1793 ArrayList members = null;
1796 if ((bf & BindingFlags.Public) != 0)
1797 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1799 if ((bf & BindingFlags.NonPublic) != 0)
1800 modflags |= Modifiers.PRIVATE;
1802 int static_mask = 0, static_flags = 0;
1803 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1804 case BindingFlags.Static:
1805 static_mask = static_flags = Modifiers.STATIC;
1808 case BindingFlags.Instance:
1809 static_mask = Modifiers.STATIC;
1814 static_mask = static_flags = 0;
1818 Timer.StartTimer (TimerType.TcFindMembers);
1821 filter = accepting_filter;
1823 if ((mt & MemberTypes.Field) != 0) {
1824 if (fields != null) {
1825 int len = fields.Count;
1826 for (int i = 0; i < len; i++) {
1827 FieldMember f = (FieldMember) fields [i];
1829 if ((f.ModFlags & modflags) == 0)
1831 if ((f.ModFlags & static_mask) != static_flags)
1834 FieldBuilder fb = f.FieldBuilder;
1835 if (fb != null && filter (fb, criteria) == true) {
1836 if (members == null)
1837 members = new ArrayList ();
1844 if (constants != null) {
1845 int len = constants.Count;
1846 for (int i = 0; i < len; i++) {
1847 Const con = (Const) constants [i];
1849 if ((con.ModFlags & modflags) == 0)
1851 if ((con.ModFlags & static_mask) != static_flags)
1854 FieldBuilder fb = con.FieldBuilder;
1857 fb = con.FieldBuilder;
1859 if (fb != null && filter (fb, criteria) == true) {
1860 if (members == null)
1861 members = new ArrayList ();
1869 if ((mt & MemberTypes.Method) != 0) {
1870 if (methods != null) {
1871 int len = methods.Count;
1872 for (int i = 0; i < len; i++) {
1873 Method m = (Method) methods [i];
1875 if ((m.ModFlags & modflags) == 0)
1877 if ((m.ModFlags & static_mask) != static_flags)
1880 MethodBuilder mb = m.MethodBuilder;
1882 if (mb != null && filter (mb, criteria) == true) {
1883 if (members == null)
1884 members = new ArrayList ();
1891 if (operators != null) {
1892 int len = operators.Count;
1893 for (int i = 0; i < len; i++) {
1894 Operator o = (Operator) operators [i];
1896 if ((o.ModFlags & modflags) == 0)
1898 if ((o.ModFlags & static_mask) != static_flags)
1901 MethodBuilder ob = o.OperatorMethodBuilder;
1902 if (ob != null && filter (ob, criteria) == true) {
1903 if (members == null)
1904 members = new ArrayList ();
1911 if (properties != null) {
1912 int len = properties.Count;
1913 for (int i = 0; i < len; i++) {
1914 Property p = (Property) properties [i];
1916 if ((p.ModFlags & modflags) == 0)
1918 if ((p.ModFlags & static_mask) != static_flags)
1924 if (b != null && filter (b, criteria) == true) {
1925 if (members == null)
1926 members = new ArrayList ();
1932 if (b != null && filter (b, criteria) == true) {
1933 if (members == null)
1934 members = new ArrayList ();
1941 if (indexers != null) {
1942 int len = indexers.Count;
1943 for (int i = 0; i < len; i++) {
1944 Indexer ix = (Indexer) indexers [i];
1946 if ((ix.ModFlags & modflags) == 0)
1948 if ((ix.ModFlags & static_mask) != static_flags)
1954 if (b != null && filter (b, criteria) == true) {
1955 if (members == null)
1956 members = new ArrayList ();
1962 if (b != null && filter (b, criteria) == true) {
1963 if (members == null)
1964 members = new ArrayList ();
1972 if ((mt & MemberTypes.Event) != 0) {
1973 if (events != null) {
1974 int len = events.Count;
1975 for (int i = 0; i < len; i++) {
1976 Event e = (Event) events [i];
1978 if ((e.ModFlags & modflags) == 0)
1980 if ((e.ModFlags & static_mask) != static_flags)
1983 MemberInfo eb = e.EventBuilder;
1984 if (eb != null && filter (eb, criteria) == true) {
1985 if (members == null)
1986 members = new ArrayList ();
1988 members.Add (e.EventBuilder);
1994 if ((mt & MemberTypes.Property) != 0){
1995 if (properties != null) {
1996 int len = properties.Count;
1997 for (int i = 0; i < len; i++) {
1998 Property p = (Property) properties [i];
2000 if ((p.ModFlags & modflags) == 0)
2002 if ((p.ModFlags & static_mask) != static_flags)
2005 MemberInfo pb = p.PropertyBuilder;
2006 if (pb != null && filter (pb, criteria) == true) {
2007 if (members == null)
2008 members = new ArrayList ();
2010 members.Add (p.PropertyBuilder);
2015 if (indexers != null) {
2016 int len = indexers.Count;
2017 for (int i = 0; i < len; i++) {
2018 Indexer ix = (Indexer) indexers [i];
2020 if ((ix.ModFlags & modflags) == 0)
2022 if ((ix.ModFlags & static_mask) != static_flags)
2025 MemberInfo ib = ix.PropertyBuilder;
2026 if (ib != null && filter (ib, criteria) == true) {
2027 if (members == null)
2028 members = new ArrayList ();
2030 members.Add (ix.PropertyBuilder);
2036 if ((mt & MemberTypes.NestedType) != 0)
2037 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2039 if ((mt & MemberTypes.Constructor) != 0){
2040 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2041 int len = instance_constructors.Count;
2042 for (int i = 0; i < len; i++) {
2043 Constructor c = (Constructor) instance_constructors [i];
2045 ConstructorBuilder cb = c.ConstructorBuilder;
2046 if (cb != null && filter (cb, criteria) == true) {
2047 if (members == null)
2048 members = new ArrayList ();
2055 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2056 ConstructorBuilder cb =
2057 default_static_constructor.ConstructorBuilder;
2059 if (cb != null && filter (cb, criteria) == true) {
2060 if (members == null)
2061 members = new ArrayList ();
2069 // Lookup members in base if requested.
2071 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2072 if (TypeBuilder.BaseType != null) {
2073 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2074 if (list.Count > 0) {
2075 if (members == null)
2076 members = new ArrayList ();
2078 members.AddRange (list);
2084 Timer.StopTimer (TimerType.TcFindMembers);
2086 if (members == null)
2087 return MemberList.Empty;
2089 return new MemberList (members);
2092 public override MemberCache MemberCache {
2094 return member_cache;
2098 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2099 MemberFilter filter, object criteria)
2101 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2104 return ds.FindMembers (mt, bf, filter, criteria);
2106 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2110 // FindMethods will look for methods not only in the type `t', but in
2111 // any interfaces implemented by the type.
2113 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2114 MemberFilter filter, object criteria)
2120 /// Emits the values for the constants
2122 public void EmitConstants ()
2124 if (constants != null)
2125 foreach (Const con in constants)
2130 protected virtual void VerifyMembers (EmitContext ec)
2133 // Check for internal or private fields that were never assigned
2135 if (RootContext.WarningLevel >= 4) {
2136 if (fields != null){
2137 foreach (Field f in fields) {
2138 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2141 if ((f.status & Field.Status.USED) == 0){
2142 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2147 // Only report 649 on level 4
2149 if (RootContext.WarningLevel < 4)
2152 if ((f.status & Field.Status.ASSIGNED) != 0)
2155 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2162 /// Emits the code, this step is performed after all
2163 /// the types, enumerations, constructors
2165 public void EmitType ()
2167 if (OptAttributes != null)
2168 OptAttributes.Emit (ec, this);
2172 if (instance_constructors != null) {
2173 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2174 bool has_compliant_args = false;
2176 foreach (Constructor c in instance_constructors) {
2179 if (has_compliant_args)
2182 has_compliant_args = c.HasCompliantArgs;
2184 if (!has_compliant_args)
2185 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2187 foreach (Constructor c in instance_constructors)
2194 if (default_static_constructor != null)
2195 default_static_constructor.Emit ();
2197 if (methods != null)
2198 foreach (Method m in methods)
2201 if (operators != null)
2202 foreach (Operator o in operators)
2205 if (properties != null)
2206 foreach (Property p in properties)
2209 if (indexers != null){
2214 foreach (FieldMember f in fields)
2217 if (events != null){
2218 foreach (Event e in Events)
2222 if (delegates != null) {
2223 foreach (Delegate d in Delegates) {
2228 if (enums != null) {
2229 foreach (Enum e in enums) {
2234 if (parts != null) {
2235 foreach (ClassPart part in parts)
2239 if ((Pending != null) && !(this is ClassPart))
2240 if (Pending.VerifyPendingMethods ())
2245 if (iterators != null)
2246 foreach (Iterator iterator in iterators)
2247 iterator.EmitType ();
2249 // if (types != null)
2250 // foreach (TypeContainer tc in types)
2254 public override void CloseType ()
2256 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2260 caching_flags |= Flags.CloseTypeCreated;
2261 TypeBuilder.CreateType ();
2262 } catch (TypeLoadException){
2264 // This is fine, the code still created the type
2266 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2267 // Console.WriteLine (e.Message);
2269 Console.WriteLine ("In type: " + Name);
2274 foreach (Enum en in Enums)
2278 foreach (TypeContainer tc in Types)
2279 if (tc.Kind == Kind.Struct)
2282 foreach (TypeContainer tc in Types)
2283 if (tc.Kind != Kind.Struct)
2287 if (Delegates != null)
2288 foreach (Delegate d in Delegates)
2291 if (Iterators != null)
2292 foreach (Iterator i in Iterators)
2300 initialized_fields = null;
2301 initialized_static_fields = null;
2310 default_constructor = null;
2311 default_static_constructor = null;
2313 OptAttributes = null;
2316 member_cache = null;
2319 // TODO: make it obsolete and use GetSignatureForError
2320 public string MakeName (string n)
2322 return "`" + Name + "." + n + "'";
2326 // Performs the validation on a Method's modifiers (properties have
2327 // the same properties).
2329 public bool MethodModifiersValid (MemberCore mc)
2331 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2332 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2333 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2335 int flags = mc.ModFlags;
2338 // At most one of static, virtual or override
2340 if ((flags & Modifiers.STATIC) != 0){
2341 if ((flags & vao) != 0){
2342 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2343 GetSignatureForError ());
2348 if (Kind == Kind.Struct){
2349 if ((flags & va) != 0){
2350 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2355 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2356 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2361 // If the declaration includes the abstract modifier, then the
2362 // declaration does not include static, virtual or extern
2364 if ((flags & Modifiers.ABSTRACT) != 0){
2365 if ((flags & Modifiers.EXTERN) != 0){
2367 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2371 if ((flags & Modifiers.SEALED) != 0) {
2372 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2376 if ((flags & Modifiers.VIRTUAL) != 0){
2377 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2381 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2382 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2387 if ((flags & Modifiers.PRIVATE) != 0){
2388 if ((flags & vao) != 0){
2389 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2394 if ((flags & Modifiers.SEALED) != 0){
2395 if ((flags & Modifiers.OVERRIDE) == 0){
2396 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2404 public bool UserDefinedStaticConstructor {
2406 return default_static_constructor != null;
2410 public Constructor DefaultStaticConstructor {
2411 get { return default_static_constructor; }
2414 protected override bool VerifyClsCompliance (DeclSpace ds)
2416 if (!base.VerifyClsCompliance (ds))
2422 Report.Error (3024, Location, "'{0}': type parameters are not CLS-compliant",
2423 GetSignatureForError ());
2427 Type base_type = TypeBuilder.BaseType;
2428 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2429 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2432 if (!Parent.IsClsCompliaceRequired (ds)) {
2433 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2434 GetSignatureForError (), Parent.GetSignatureForError ());
2441 /// Checks whether container name is CLS Compliant
2443 void VerifyClsName ()
2445 Hashtable base_members = base_cache == null ?
2447 base_cache.GetPublicMembers ();
2448 Hashtable this_members = new Hashtable ();
2450 foreach (DictionaryEntry entry in defined_names) {
2451 MemberCore mc = (MemberCore)entry.Value;
2452 if (!mc.IsClsCompliaceRequired (this))
2455 string name = (string)entry.Key;
2456 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2458 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2459 object found = base_members [lcase];
2460 if (found == null) {
2461 found = this_members [lcase];
2462 if (found == null) {
2463 this_members.Add (lcase, mc);
2468 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2471 if (found is MemberInfo) {
2472 if (basename == ((MemberInfo)found).Name)
2474 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2476 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2478 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2484 /// Performs checks for an explicit interface implementation. First it
2485 /// checks whether the `interface_type' is a base inteface implementation.
2486 /// Then it checks whether `name' exists in the interface type.
2488 public virtual bool VerifyImplements (Type interface_type, string full,
2489 string name, Location loc)
2493 if (ifaces != null){
2494 foreach (Type t in ifaces){
2495 if (t == interface_type){
2503 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2504 full, interface_type.FullName);
2511 protected override void VerifyObsoleteAttribute()
2513 CheckUsageOfObsoleteAttribute (TypeBuilder.BaseType);
2518 foreach (Type iface in ifaces) {
2519 CheckUsageOfObsoleteAttribute (iface);
2527 string IMemberContainer.Name {
2533 Type IMemberContainer.Type {
2539 MemberCache IMemberContainer.MemberCache {
2541 return member_cache;
2545 bool IMemberContainer.IsInterface {
2547 return Kind == Kind.Interface;
2551 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2553 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2555 if (GenericType != null)
2556 return TypeManager.FindMembers (GenericType, mt, new_bf,
2559 return FindMembers (mt, new_bf, null, null);
2563 // Generates xml doc comments (if any), and if required,
2564 // handle warning report.
2566 internal override void GenerateDocComment (DeclSpace ds)
2568 DocUtil.GenerateTypeDocComment (this, ds);
2571 public override string DocCommentHeader {
2572 get { return "T:"; }
2575 public virtual MemberCache BaseCache {
2577 if (base_cache != null)
2579 if (TypeBuilder.BaseType != null)
2580 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2581 if (TypeBuilder.IsInterface)
2582 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2589 public class PartialContainer : TypeContainer {
2591 public readonly Namespace Namespace;
2592 public readonly int OriginalModFlags;
2593 public readonly int AllowedModifiers;
2594 public readonly TypeAttributes DefaultTypeAttributes;
2596 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2597 MemberName member_name, int mod_flags, Kind kind,
2600 PartialContainer pc;
2601 string full_name = member_name.GetName (true);
2602 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2604 pc = ds as PartialContainer;
2608 260, ds.Location, "Missing partial modifier " +
2609 "on declaration of type `{0}'; another " +
2610 "partial implementation of this type exists",
2611 member_name.GetTypeName());
2613 Report.LocationOfPreviousError (loc);
2617 if (pc.Kind != kind) {
2619 261, loc, "Partial declarations of `{0}' " +
2620 "must be all classes, all structs or " +
2621 "all interfaces", member_name.GetTypeName ());
2625 if (pc.OriginalModFlags != mod_flags) {
2627 262, loc, "Partial declarations of `{0}' " +
2628 "have conflicting accessibility modifiers",
2629 member_name.GetTypeName ());
2634 if (pc.CountTypeParameters != member_name.CountTypeArguments) {
2636 264, loc, "Partial declarations of `{0}' " +
2637 "must have the same type parameter names in " +
2638 "the same order", member_name.GetTypeName ());
2642 string[] pc_names = pc.MemberName.TypeArguments.GetDeclarations ();
2643 string[] names = member_name.TypeArguments.GetDeclarations ();
2645 for (int i = 0; i < pc.CountTypeParameters; i++) {
2646 if (pc_names [i] == names [i])
2650 264, loc, "Partial declarations of `{0}' " +
2651 "must have the same type parameter names in " +
2652 "the same order", member_name.GetTypeName ());
2660 pc = new PartialContainer (ns, parent, member_name, mod_flags, kind, loc);
2661 RootContext.Tree.RecordDecl (full_name, pc);
2662 parent.AddType (pc);
2664 // This is needed to define our type parameters; we define the constraints later.
2665 pc.SetParameterInfo (null);
2669 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2670 MemberName name, int mod, Attributes attrs,
2671 Kind kind, Location loc)
2673 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2675 // An error occured; create a dummy container, but don't
2677 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2680 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2685 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2686 MemberName name, int mod, Kind kind, Location l)
2687 : base (ns, parent, name, null, kind, l)
2689 this.Namespace = ns.NS;
2693 AllowedModifiers = Class.AllowedModifiers;
2694 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2698 AllowedModifiers = Struct.AllowedModifiers;
2699 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2702 case Kind.Interface:
2703 AllowedModifiers = Interface.AllowedModifiers;
2704 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2708 throw new InvalidOperationException ();
2712 if (parent.Parent == null)
2713 accmods = Modifiers.INTERNAL;
2715 accmods = Modifiers.PRIVATE;
2717 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2718 this.OriginalModFlags = mod;
2721 public override void Register ()
2723 if (Kind == Kind.Interface)
2724 Parent.AddInterface (this);
2725 else if (Kind == Kind.Class || Kind == Kind.Struct)
2726 Parent.AddClassOrStruct (this);
2728 throw new InvalidOperationException ();
2731 public override PendingImplementation GetPendingImplementations ()
2733 return PendingImplementation.GetPendingImplementations (this);
2736 ArrayList constraints_lists;
2738 public void UpdateConstraints (ArrayList constraints_list)
2741 // This is called for each ClassPart in a partial generic type declaration.
2743 // If no constraints were specified for the part, just return.
2744 // Otherwise, if we're called with constraints for the first time, they become
2745 // the type's constraint. If we're called with constraints again, we just
2746 // store them somewhere so we can later check whether there are no conflicts.
2748 if (constraints_list == null)
2751 if (constraints_lists != null) {
2752 constraints_lists.Add (constraints_list);
2756 DoUpdateConstraints (null, constraints_list, false);
2758 constraints_lists = new ArrayList ();
2761 protected bool DoUpdateConstraints (EmitContext ec, ArrayList constraints_list, bool check)
2763 for (int i = 0; i < TypeParameters.Length; i++) {
2764 string name = TypeParameters [i].Name;
2766 Constraints constraints = null;
2767 if (constraints_list != null) {
2768 foreach (Constraints constraint in constraints_list) {
2769 if (constraint.TypeParameter == name) {
2770 constraints = constraint;
2776 if (!TypeParameters [i].UpdateConstraints (ec, constraints, check)) {
2777 Report.Error (265, Location, "Partial declarations of `{0}' have " +
2778 "inconsistent constraints for type parameter `{1}'.",
2779 MemberName.GetTypeName (), name);
2787 protected override bool CheckConstraints (EmitContext ec)
2789 if (constraints_lists == null)
2793 // If constraints were specified in more than one part of a
2794 // partial generic type definition, they must be identical.
2796 // Note that we must resolve them and then compute the fully
2797 // resolved types since different parts may have different
2798 // `using' aliases. See gen-129.cs for an example.
2800 foreach (ArrayList constraints_list in constraints_lists) {
2801 if (!DoUpdateConstraints (ec, constraints_list, true))
2808 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2811 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2816 public override TypeAttributes TypeAttr {
2818 return base.TypeAttr | DefaultTypeAttributes;
2823 public class ClassPart : TypeContainer, IMemberContainer {
2824 public readonly PartialContainer PartialContainer;
2825 public readonly bool IsPartial;
2827 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2828 int mod, Attributes attrs, Kind kind, Location l)
2829 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2831 this.PartialContainer = parent;
2832 this.IsPartial = true;
2835 if (parent.Parent == null)
2836 accmods = Modifiers.INTERNAL;
2838 accmods = Modifiers.PRIVATE;
2840 this.ModFlags = Modifiers.Check (
2841 parent.AllowedModifiers, mod, accmods, l);
2844 public override void Register ()
2848 public override PendingImplementation GetPendingImplementations ()
2850 return PartialContainer.Pending;
2853 public override bool VerifyImplements (Type interface_type, string full,
2854 string name, Location loc)
2856 return PartialContainer.VerifyImplements (
2857 interface_type, full, name, loc);
2860 public override void SetParameterInfo (ArrayList constraints_list)
2862 PartialContainer.UpdateConstraints (constraints_list);
2865 public override Type FindNestedType (string name)
2867 return PartialContainer.FindNestedType (name);
2870 public Type PartFindNestedType (string name)
2872 return base.FindNestedType (name);
2875 public override MemberCache BaseCache {
2877 return PartialContainer.BaseCache;
2882 public abstract class ClassOrStruct : TypeContainer {
2883 bool hasExplicitLayout = false;
2884 ListDictionary declarative_security;
2886 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2887 MemberName name, Attributes attrs, Kind kind,
2889 : base (ns, parent, name, attrs, kind, l)
2893 public override PendingImplementation GetPendingImplementations ()
2895 return PendingImplementation.GetPendingImplementations (this);
2898 public override bool HasExplicitLayout {
2900 return hasExplicitLayout;
2904 protected override void VerifyMembers (EmitContext ec)
2906 base.VerifyMembers (ec);
2908 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2909 foreach (Event e in events){
2911 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2916 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2918 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2919 if (declarative_security == null)
2920 declarative_security = new ListDictionary ();
2922 a.ExtractSecurityPermissionSet (declarative_security);
2926 if (a.Type == TypeManager.struct_layout_attribute_type &&
2927 a.GetLayoutKindValue () == LayoutKind.Explicit)
2928 hasExplicitLayout = true;
2930 base.ApplyAttributeBuilder (a, cb);
2933 public override void Emit()
2937 if (declarative_security != null) {
2938 foreach (DictionaryEntry de in declarative_security) {
2939 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2944 public override void Register ()
2946 Parent.AddClassOrStruct (this);
2951 /// Class handles static classes declaration
2953 public sealed class StaticClass: Class {
2954 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2955 Attributes attrs, Location l)
2956 : base (ns, parent, name, mod, attrs, l)
2958 if (RootContext.Version == LanguageVersion.ISO_1) {
2959 Report.FeatureIsNotStandardized (l, "static classes");
2960 Environment.Exit (1);
2964 protected override int AllowedModifiersProp {
2966 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2967 Modifiers.STATIC | Modifiers.UNSAFE;
2971 protected override void DefineContainerMembers (MemberCoreArrayList list)
2976 foreach (MemberCore m in list) {
2977 if (m is Operator) {
2978 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2982 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2983 Report.Warning (628, 4, m.Location, "'{0}': new protected member declared in static class", m.GetSignatureForError (this));
2985 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2988 if (m is Constructor) {
2989 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2993 if (m is Destructor) {
2994 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2997 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
3000 base.DefineContainerMembers (list);
3003 public override TypeBuilder DefineType()
3005 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
3006 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
3010 TypeBuilder tb = base.DefineType ();
3014 if ((ptype != null) && (ptype != TypeManager.object_type)) {
3017 "Static class '{0}' cannot derive from type '{1}'. " +
3018 "Static classes must derive from object",
3019 GetSignatureForError (), ptype);
3023 if (ifaces != null) {
3024 foreach (Type t in ifaces)
3025 Report.SymbolRelatedToPreviousError (t);
3028 "'{0}': static classes cannot implement interfaces",
3029 GetSignatureForError ());
3034 public override TypeAttributes TypeAttr {
3036 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
3041 public class Class : ClassOrStruct {
3042 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
3043 public const int AllowedModifiers =
3046 Modifiers.PROTECTED |
3047 Modifiers.INTERNAL |
3049 Modifiers.ABSTRACT |
3053 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3054 Attributes attrs, Location l)
3055 : base (ns, parent, name, attrs, Kind.Class, l)
3057 this.ModFlags = mod;
3060 virtual protected int AllowedModifiersProp {
3062 return AllowedModifiers;
3066 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
3068 if (a.Type == TypeManager.attribute_usage_type) {
3069 if (ptype != TypeManager.attribute_type &&
3070 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
3071 TypeBuilder.FullName != "System.Attribute") {
3072 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
3076 base.ApplyAttributeBuilder (a, cb);
3079 public const TypeAttributes DefaultTypeAttributes =
3080 TypeAttributes.AutoLayout | TypeAttributes.Class;
3082 public override TypeBuilder DefineType()
3084 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
3085 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
3089 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
3090 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
3092 return base.DefineType ();
3096 // FIXME: How do we deal with the user specifying a different
3099 public override TypeAttributes TypeAttr {
3101 return base.TypeAttr | DefaultTypeAttributes;
3106 public class Struct : ClassOrStruct {
3108 // Modifiers allowed in a struct declaration
3110 public const int AllowedModifiers =
3113 Modifiers.PROTECTED |
3114 Modifiers.INTERNAL |
3118 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
3119 int mod, Attributes attrs, Location l)
3120 : base (ns, parent, name, attrs, Kind.Struct, l)
3124 if (parent.Parent == null)
3125 accmods = Modifiers.INTERNAL;
3127 accmods = Modifiers.PRIVATE;
3129 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3131 this.ModFlags |= Modifiers.SEALED;
3134 public const TypeAttributes DefaultTypeAttributes =
3135 TypeAttributes.SequentialLayout |
3136 TypeAttributes.Sealed |
3137 TypeAttributes.BeforeFieldInit;
3140 // FIXME: Allow the user to specify a different set of attributes
3141 // in some cases (Sealed for example is mandatory for a class,
3142 // but what SequentialLayout can be changed
3144 public override TypeAttributes TypeAttr {
3146 return base.TypeAttr | DefaultTypeAttributes;
3154 public class Interface : TypeContainer, IMemberContainer {
3156 /// Modifiers allowed in a class declaration
3158 public const int AllowedModifiers =
3161 Modifiers.PROTECTED |
3162 Modifiers.INTERNAL |
3166 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name,
3167 int mod, Attributes attrs, Location l)
3168 : base (ns, parent, name, attrs, Kind.Interface, l)
3172 if (parent.Parent == null)
3173 accmods = Modifiers.INTERNAL;
3175 accmods = Modifiers.PRIVATE;
3177 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3180 public override void Register ()
3182 Parent.AddInterface (this);
3185 public override PendingImplementation GetPendingImplementations ()
3190 public const TypeAttributes DefaultTypeAttributes =
3191 TypeAttributes.AutoLayout |
3192 TypeAttributes.Abstract |
3193 TypeAttributes.Interface;
3195 public override TypeAttributes TypeAttr {
3197 return base.TypeAttr | DefaultTypeAttributes;
3202 public abstract class MethodCore : MemberBase {
3203 public readonly Parameters Parameters;
3204 public readonly GenericMethod GenericMethod;
3205 public readonly DeclSpace ds;
3206 protected ToplevelBlock block;
3209 // Parameters, cached for semantic analysis.
3211 protected InternalParameters parameter_info;
3212 protected Type [] parameter_types;
3214 // Whether this is an operator method.
3215 public bool IsOperator;
3218 // The method we're overriding if this is an override method.
3220 protected MethodInfo base_method = null;
3222 static string[] attribute_targets = new string [] { "method", "return" };
3224 public MethodCore (TypeContainer parent, GenericMethod generic,
3225 Expression type, int mod, int allowed_mod, bool is_iface,
3226 MemberName name, Attributes attrs, Parameters parameters,
3228 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3231 Parameters = parameters;
3232 IsInterface = is_iface;
3233 this.GenericMethod = generic;
3235 if (generic != null)
3242 // Returns the System.Type array for the parameters of this method
3244 public Type [] ParameterTypes {
3246 return parameter_types;
3250 public InternalParameters ParameterInfo
3253 return parameter_info;
3257 public ToplevelBlock Block {
3267 protected override bool CheckBase ()
3269 if (!base.CheckBase ())
3272 // Check whether arguments were correct.
3273 if (!DoDefineParameters ())
3276 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3282 // Is null for System.Object while compiling corlib and base interfaces
3283 if (Parent.BaseCache == null) {
3284 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3285 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3290 Type base_ret_type = null;
3291 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3293 // method is override
3294 if (base_method != null) {
3296 if (!CheckMethodAgainstBase ())
3299 if ((ModFlags & Modifiers.NEW) == 0) {
3300 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3301 Report.SymbolRelatedToPreviousError (base_method);
3302 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3303 "change return type when overriding inherited member");
3307 if (base_method.IsAbstract && !IsInterface) {
3308 Report.SymbolRelatedToPreviousError (base_method);
3309 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3314 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3315 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3319 if (RootContext.WarningLevel > 2) {
3320 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3321 Parent.Methods.HasEquals = true;
3322 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3323 Parent.Methods.HasGetHashCode = true;
3326 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3327 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3329 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3330 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3331 Report.SymbolRelatedToPreviousError (base_method);
3332 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3339 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3340 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3341 if (conflict_symbol != null) {
3342 Report.SymbolRelatedToPreviousError (conflict_symbol);
3343 if (this is PropertyBase)
3344 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3346 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3348 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3352 if (conflict_symbol == null) {
3353 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3354 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3359 if ((ModFlags & Modifiers.NEW) == 0) {
3360 if (this is Method && conflict_symbol is MethodBase)
3363 Report.SymbolRelatedToPreviousError (conflict_symbol);
3364 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3372 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3373 // that have been defined.
3375 // `name' is the user visible name for reporting errors (this is used to
3376 // provide the right name regarding method names and properties)
3378 bool CheckMethodAgainstBase ()
3382 // TODO: replace with GetSignatureForError
3383 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3385 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3386 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3388 506, Location, Parent.MakeName (Name) +
3389 ": cannot override inherited member `" +
3390 name + "' because it is not " +
3391 "virtual, abstract or override");
3395 // Now we check that the overriden method is not final
3397 if (base_method.IsFinal) {
3398 Report.SymbolRelatedToPreviousError (base_method);
3399 Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
3400 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3404 // Check that the permissions are not being changed
3406 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3407 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3409 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3410 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3415 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3416 ModFlags |= Modifiers.NEW;
3417 Report.SymbolRelatedToPreviousError (base_method);
3418 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3419 if (RootContext.WarningLevel >= 2)
3420 Report.Warning (114, Location, "'{0}' hides inherited member '{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword", GetSignatureForError (Parent), TypeManager.CSharpSignature (base_method));
3422 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3428 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3430 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3432 // when overriding protected internal, the method can be declared
3433 // protected internal only within the same assembly
3436 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3437 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3439 // assemblies differ - report an error
3443 } else if (thisp != base_classp) {
3445 // same assembly, but other attributes differ - report an error
3450 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3452 // if it's not "protected internal", it must be "protected"
3456 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3458 // protected within the same assembly - an error
3461 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3462 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3464 // protected ok, but other attributes differ - report an error
3470 return (thisp == base_classp);
3474 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3477 // FIXME: report the old/new permissions?
3480 507, Location, parent.MakeName (Name) +
3481 ": can't change the access modifiers when overriding inherited " +
3482 "member `" + name + "'");
3485 protected static string Error722 {
3487 return "'{0}': static types cannot be used as return types";
3492 /// For custom member duplication search in a container
3494 protected abstract bool CheckForDuplications ();
3497 /// Gets base method and its return type
3499 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3501 protected virtual bool DoDefineParameters ()
3503 EmitContext ec = ds.EmitContext;
3505 throw new InternalErrorException ("DoDefineParameters invoked too early");
3507 bool old_unsafe = ec.InUnsafe;
3508 ec.InUnsafe = InUnsafe;
3509 // Check if arguments were correct
3510 parameter_types = Parameters.GetParameterInfo (ec);
3511 ec.InUnsafe = old_unsafe;
3513 if ((parameter_types == null) ||
3514 !CheckParameters (ds, parameter_types))
3517 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3518 parameter_info = new InternalParameters (parameter_types, Parameters, tparam);
3520 Parameter array_param = Parameters.ArrayParameter;
3521 if ((array_param != null) &&
3522 (!array_param.ParameterType.IsArray ||
3523 (array_param.ParameterType.GetArrayRank () != 1))) {
3524 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3531 void error_425 (Type old, Type t, string name)
3533 Report.Error (425, Location,
3534 "The constraints of type parameter `{0}' " +
3535 "of method `{1}' must match the constraints for " +
3536 "type parameter `{2}' of method `{3}'",
3537 TypeManager.CSharpName (old), Name,
3538 TypeManager.CSharpName (t), name);
3541 protected override bool CheckGenericOverride (MethodInfo method, string name)
3543 ParameterData pd = TypeManager.GetParameterData (method);
3545 for (int i = 0; i < ParameterTypes.Length; i++) {
3546 GenericConstraints ogc = pd.GenericConstraints (i);
3547 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3549 if ((gc == null) && (ogc == null))
3552 Type ot = pd.ParameterType (i);
3553 Type t = ParameterTypes [i];
3555 if (!((gc != null) && (ogc != null))) {
3556 error_425 (ot, t, name);
3560 if ((gc.Attributes != ogc.Attributes) ||
3561 (gc.HasClassConstraint != ogc.HasClassConstraint)) {
3562 error_425 (ot, t, name);
3566 if (ogc.HasClassConstraint &&
3567 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3568 error_425 (ot, t, name);
3572 Type[] oct = ogc.InterfaceConstraints;
3573 Type[] ct = gc.InterfaceConstraints;
3575 if (oct.Length != ct.Length) {
3576 error_425 (ot, t, name);
3580 for (int j = 0; j < oct.Length; j++)
3581 if (!oct [j].Equals (ct [j])) {
3582 error_425 (ot, t, name);
3590 public override string[] ValidAttributeTargets {
3592 return attribute_targets;
3596 protected override bool VerifyClsCompliance (DeclSpace ds)
3598 if (!base.VerifyClsCompliance (ds)) {
3599 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3600 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3605 if (Parameters.HasArglist) {
3606 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3609 if (!AttributeTester.IsClsCompliant (MemberType)) {
3610 if (this is PropertyBase)
3611 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3612 GetSignatureForError ());
3614 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3615 GetSignatureForError ());
3618 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3623 bool MayUnify (MethodCore first, MethodCore second)
3625 int a_type_params = 0;
3626 if (first.GenericMethod != null)
3627 a_type_params = first.GenericMethod.CountTypeParameters;
3629 int b_type_params = 0;
3630 if (second.GenericMethod != null)
3631 b_type_params = second.GenericMethod.CountTypeParameters;
3633 if (a_type_params != b_type_params)
3636 Type[] class_infered, method_infered;
3637 if (Parent.CountTypeParameters > 0)
3638 class_infered = new Type [Parent.CountTypeParameters];
3640 class_infered = null;
3642 if (a_type_params > 0)
3643 method_infered = new Type [a_type_params];
3645 method_infered = null;
3647 return TypeManager.MayBecomeEqualGenericInstances (
3648 first.ParameterTypes, second.ParameterTypes, class_infered, method_infered);
3651 protected bool IsDuplicateImplementation (MethodCore method)
3653 if ((method == this) ||
3654 (method.MemberName.GetTypeName () != MemberName.GetTypeName ()))
3657 Type[] param_types = method.ParameterTypes;
3658 if (param_types == null)
3661 if (param_types.Length != ParameterTypes.Length)
3665 bool may_unify = MayUnify (this, method);
3667 for (int i = 0; i < param_types.Length; i++) {
3668 if (param_types [i] != ParameterTypes [i])
3672 // TODO: make operator compatible with MethodCore to avoid this
3673 if (this is Operator && method is Operator) {
3674 if (MemberType != method.MemberType)
3675 equal = may_unify = false;
3680 // Try to report 663: method only differs on out/ref
3682 ParameterData info = ParameterInfo;
3683 ParameterData other_info = method.ParameterInfo;
3684 for (int i = 0; i < info.Count; i++){
3685 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3686 Report.Error (663, Location,
3687 "Overload method only differs " +
3688 "in parameter modifier");
3693 Report.SymbolRelatedToPreviousError (method);
3694 if (this is Operator && method is Operator)
3695 Report.Error (557, Location,
3696 "Duplicate user-defined conversion in type '{0}'",
3699 Report.Error (111, Location,
3700 "Type '{0}' already defines a member called '{1}' " +
3701 "with the same parameter types", Parent.Name, Name);
3703 } else if (may_unify) {
3704 Report.Error (408, Location,
3705 "`{0}' cannot define overload members that " +
3706 "may unify for some type parameter substitutions",
3714 // Returns a string that represents the signature for this
3715 // member which should be used in XML documentation.
3717 public override string GetDocCommentName (DeclSpace ds)
3719 return DocUtil.GetMethodDocCommentName (this, ds);
3723 // Raised (and passed an XmlElement that contains the comment)
3724 // when GenerateDocComment is writing documentation expectedly.
3726 // FIXME: with a few effort, it could be done with XmlReader,
3727 // that means removal of DOM use.
3729 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3731 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3735 // Represents header string for documentation comment.
3737 public override string DocCommentHeader {
3738 get { return "M:"; }
3741 protected override void VerifyObsoleteAttribute()
3743 base.VerifyObsoleteAttribute ();
3745 if (parameter_types == null)
3748 foreach (Type type in parameter_types) {
3749 CheckUsageOfObsoleteAttribute (type);
3754 public class SourceMethod : ISourceMethod
3756 TypeContainer container;
3759 protected SourceMethod (TypeContainer container, MethodBase builder,
3760 ISourceFile file, Location start, Location end)
3762 this.container = container;
3763 this.builder = builder;
3765 CodeGen.SymbolWriter.OpenMethod (
3766 file, this, start.Row, 0, end.Row, 0);
3769 public string Name {
3770 get { return builder.Name; }
3773 public int NamespaceID {
3774 get { return container.NamespaceEntry.SymbolFileID; }
3779 if (builder is MethodBuilder)
3780 return ((MethodBuilder) builder).GetToken ().Token;
3781 else if (builder is ConstructorBuilder)
3782 return ((ConstructorBuilder) builder).GetToken ().Token;
3784 throw new NotSupportedException ();
3788 public void CloseMethod ()
3790 if (CodeGen.SymbolWriter != null)
3791 CodeGen.SymbolWriter.CloseMethod ();
3794 public static SourceMethod Create (TypeContainer parent,
3795 MethodBase builder, Block block)
3797 if (CodeGen.SymbolWriter == null)
3802 Location start_loc = block.StartLocation;
3803 if (Location.IsNull (start_loc))
3806 Location end_loc = block.EndLocation;
3807 if (Location.IsNull (end_loc))
3810 ISourceFile file = start_loc.SourceFile;
3814 return new SourceMethod (
3815 parent, builder, file, start_loc, end_loc);
3819 public class Method : MethodCore, IIteratorContainer, IMethodData {
3820 public MethodBuilder MethodBuilder;
3821 public MethodData MethodData;
3822 ReturnParameter return_attributes;
3823 ListDictionary declarative_security;
3826 /// Modifiers allowed in a class declaration
3828 const int AllowedModifiers =
3831 Modifiers.PROTECTED |
3832 Modifiers.INTERNAL |
3837 Modifiers.OVERRIDE |
3838 Modifiers.ABSTRACT |
3840 Modifiers.METHOD_YIELDS |
3843 const int AllowedInterfaceModifiers =
3844 Modifiers.NEW | Modifiers.UNSAFE;
3847 // return_type can be "null" for VOID values.
3849 public Method (TypeContainer parent, GenericMethod generic,
3850 Expression return_type, int mod, bool is_iface,
3851 MemberName name, Parameters parameters, Attributes attrs,
3853 : base (parent, generic, return_type, mod,
3854 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3855 is_iface, name, attrs, parameters, l)
3859 public override AttributeTargets AttributeTargets {
3861 return AttributeTargets.Method;
3865 public override string GetSignatureForError()
3867 if (MethodBuilder == null) {
3868 return GetSignatureForError (Parent);
3870 return TypeManager.CSharpSignature (MethodBuilder);
3874 /// Use this method when MethodBuilder is null
3876 public override string GetSignatureForError (TypeContainer tc)
3878 // TODO: get params from somewhere
3879 if (parameter_info == null)
3880 return base.GetSignatureForError (tc);
3882 // TODO: move to parameters
3883 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3884 if (parameter_info.Parameters.FixedParameters != null) {
3885 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3886 Parameter p = parameter_info.Parameters.FixedParameters [i];
3887 args.Append (p.GetSignatureForError ());
3889 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3894 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3897 void DuplicateEntryPoint (MethodInfo b, Location location)
3901 "Program `" + CodeGen.FileName +
3902 "' has more than one entry point defined: `" +
3903 TypeManager.CSharpSignature(b) + "'");
3906 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3908 if (b.ReturnType != TypeManager.void_type &&
3909 b.ReturnType != TypeManager.int32_type)
3912 if (pinfo.Count == 0)
3915 if (pinfo.Count > 1)
3918 Type t = pinfo.ParameterType(0);
3920 (t.GetArrayRank() == 1) &&
3921 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3922 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3928 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3930 if (a.Target == AttributeTargets.ReturnValue) {
3931 if (return_attributes == null)
3932 return_attributes = new ReturnParameter (MethodBuilder, Location);
3934 return_attributes.ApplyAttributeBuilder (a, cb);
3938 if (a.Type == TypeManager.methodimpl_attr_type &&
3939 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3940 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3943 if (a.Type == TypeManager.dllimport_type) {
3944 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3945 if ((ModFlags & extern_static) != extern_static) {
3946 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3952 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3953 if (declarative_security == null)
3954 declarative_security = new ListDictionary ();
3955 a.ExtractSecurityPermissionSet (declarative_security);
3959 if (a.Type == TypeManager.conditional_attribute_type) {
3960 if (IsOperator || IsExplicitImpl) {
3961 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3965 if (ReturnType != TypeManager.void_type) {
3966 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3970 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3971 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3976 Report.Error (582, Location, "Conditional not valid on interface members");
3980 if (MethodData.IsImplementing) {
3981 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3985 for (int i = 0; i < parameter_info.Count; ++i) {
3986 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3987 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3993 MethodBuilder.SetCustomAttribute (cb);
3996 protected override bool CheckForDuplications ()
3998 ArrayList ar = Parent.Methods;
4000 int arLen = ar.Count;
4002 for (int i = 0; i < arLen; i++) {
4003 Method m = (Method) ar [i];
4004 if (IsDuplicateImplementation (m))
4009 ar = Parent.Properties;
4011 for (int i = 0; i < ar.Count; ++i) {
4012 PropertyBase pb = (PropertyBase) ar [i];
4013 if (pb.AreAccessorsDuplicateImplementation (this))
4018 ar = Parent.Indexers;
4020 for (int i = 0; i < ar.Count; ++i) {
4021 PropertyBase pb = (PropertyBase) ar [i];
4022 if (pb.AreAccessorsDuplicateImplementation (this))
4029 for (int i = 0; i < ar.Count; ++i) {
4030 Event ev = (Event) ar [i];
4031 if (ev.AreAccessorsDuplicateImplementation (this))
4042 public override bool Define ()
4044 if (!DoDefineBase ())
4047 MethodBuilder mb = null;
4048 if (GenericMethod != null) {
4049 string mname = MemberName.GetMethodName ();
4050 mb = Parent.TypeBuilder.DefineGenericMethod (mname, flags);
4051 if (!GenericMethod.Define (mb, ReturnType))
4058 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4059 Error1599 (Location, ReturnType);
4067 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
4069 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
4070 this, mb, GenericMethod, base_method);
4072 if (!MethodData.Define (Parent))
4076 // Setup iterator if we are one
4078 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4079 Iterator iterator = new Iterator (
4080 Parent, Name, MemberType, ParameterTypes,
4081 ParameterInfo, ModFlags, block, Location);
4083 if (!iterator.DefineIterator ())
4086 block = iterator.Block;
4089 MethodBuilder = MethodData.MethodBuilder;
4092 // This is used to track the Entry Point,
4094 if (Name == "Main" &&
4095 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
4096 (RootContext.MainClass == null ||
4097 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4098 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
4099 if (RootContext.EntryPoint == null) {
4100 if (Parent.IsGeneric){
4101 Report.Error (-201, Location,
4102 "Entry point can not be defined in a generic class");
4105 RootContext.EntryPoint = MethodBuilder;
4106 RootContext.EntryPointLocation = Location;
4108 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4109 DuplicateEntryPoint (MethodBuilder, Location);
4112 if (RootContext.WarningLevel >= 4)
4113 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder) );
4117 if (MemberType.IsAbstract && MemberType.IsSealed) {
4118 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4128 public override void Emit ()
4130 MethodData.Emit (Parent, this);
4133 if (declarative_security != null) {
4134 foreach (DictionaryEntry de in declarative_security) {
4135 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4143 public static void Error1599 (Location loc, Type t)
4145 Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
4148 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4150 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
4151 container.TypeBuilder, Name, ParameterTypes, false);
4156 base_ret_type = mi.ReturnType;
4160 public override bool MarkForDuplicationCheck ()
4162 caching_flags |= Flags.TestMethodDuplication;
4166 protected override bool VerifyClsCompliance(DeclSpace ds)
4168 if (!base.VerifyClsCompliance (ds))
4171 if (parameter_types.Length > 0) {
4172 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
4174 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4181 void IIteratorContainer.SetYields ()
4183 ModFlags |= Modifiers.METHOD_YIELDS;
4186 #region IMethodData Members
4188 public CallingConventions CallingConventions {
4190 CallingConventions cc = Parameters.GetCallingConvention ();
4191 if (Parameters.HasArglist)
4192 block.HasVarargs = true;
4195 if ((ModFlags & Modifiers.STATIC) == 0)
4196 cc |= CallingConventions.HasThis;
4198 // FIXME: How is `ExplicitThis' used in C#?
4204 public Type ReturnType {
4210 public MemberName MethodName {
4216 public new Location Location {
4218 return base.Location;
4222 protected override bool CheckBase() {
4223 if (!base.CheckBase ())
4226 // TODO: Destructor should derive from MethodCore
4227 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4228 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4229 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4236 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4238 return new EmitContext (
4239 tc, ds, Location, ig, ReturnType, ModFlags, false);
4242 public ObsoleteAttribute GetObsoleteAttribute ()
4244 return GetObsoleteAttribute (ds);
4248 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4250 public bool IsExcluded (EmitContext ec)
4252 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4253 return (caching_flags & Flags.Excluded) != 0;
4255 caching_flags &= ~Flags.Excluded_Undetected;
4257 if (base_method == null) {
4258 if (OptAttributes == null)
4261 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4266 foreach (Attribute a in attrs) {
4267 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4268 if (RootContext.AllDefines.Contains (condition))
4272 caching_flags |= Flags.Excluded;
4276 IMethodData md = TypeManager.GetMethod (base_method);
4278 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4279 caching_flags |= Flags.Excluded;
4285 if (md.IsExcluded (ec)) {
4286 caching_flags |= Flags.Excluded;
4292 GenericMethod IMethodData.GenericMethod {
4294 return GenericMethod;
4301 public abstract class ConstructorInitializer {
4302 ArrayList argument_list;
4303 protected ConstructorInfo base_constructor;
4304 Parameters parameters;
4307 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4310 this.argument_list = argument_list;
4311 this.parameters = parameters;
4315 public ArrayList Arguments {
4317 return argument_list;
4321 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4323 Expression base_constructor_group;
4327 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
4329 if (argument_list != null){
4330 foreach (Argument a in argument_list){
4331 if (!a.Resolve (ec, loc))
4335 ec.CurrentBlock = null;
4337 if (this is ConstructorBaseInitializer) {
4338 if (ec.ContainerType.BaseType == null)
4341 t = ec.ContainerType.BaseType;
4342 if (ec.ContainerType.IsValueType) {
4343 Report.Error (522, loc,
4344 "structs cannot call base class constructors");
4348 t = ec.ContainerType;
4350 base_constructor_group = Expression.MemberLookup (
4351 ec, t, ".ctor", MemberTypes.Constructor,
4352 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4355 if (base_constructor_group == null){
4357 base_constructor_group = Expression.MemberLookup (
4358 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4359 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4363 int errors = Report.Errors;
4364 if (base_constructor_group != null)
4365 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4366 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4369 if (base_constructor == null) {
4370 if (errors == Report.Errors)
4371 Report.Error (1501, loc, "Can not find a constructor for this argument list");
4376 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
4377 TypeManager.CSharpSignature (base_constructor));
4378 base_constructor = null;
4382 if (base_constructor == caller_builder){
4383 Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
4390 public void Emit (EmitContext ec)
4392 if (base_constructor != null){
4393 ec.Mark (loc, false);
4395 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4397 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4402 /// Method search for base ctor. (We do not cache it).
4404 Constructor GetOverloadedConstructor (TypeContainer tc)
4406 if (tc.InstanceConstructors == null)
4409 foreach (Constructor c in tc.InstanceConstructors) {
4410 if (Arguments == null) {
4411 if (c.ParameterTypes.Length == 0)
4419 int count = c.ParameterInfo.Count;
4421 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4422 for (int i = 0; i < count-1; i++)
4423 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4428 if (c.ParameterTypes.Length != Arguments.Count)
4431 for (int i = 0; i < Arguments.Count; ++i)
4432 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4447 //TODO: implement caching when it will be necessary
4448 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4450 Constructor ctor = GetOverloadedConstructor (tc);
4454 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4458 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4462 public class ConstructorBaseInitializer : ConstructorInitializer {
4463 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4464 base (argument_list, pars, l)
4468 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4469 if (base_constructor == null)
4472 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4473 if (type_ds == null) {
4474 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (base_constructor);
4477 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (base_constructor), loc);
4482 base.CheckObsoleteAttribute (type_ds, loc);
4487 public class ConstructorThisInitializer : ConstructorInitializer {
4488 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4489 base (argument_list, pars, l)
4494 public class Constructor : MethodCore, IMethodData {
4495 public ConstructorBuilder ConstructorBuilder;
4496 public ConstructorInitializer Initializer;
4497 ListDictionary declarative_security;
4500 // Modifiers allowed for a constructor.
4502 public const int AllowedModifiers =
4504 Modifiers.PROTECTED |
4505 Modifiers.INTERNAL |
4511 bool has_compliant_args = false;
4513 // The spec claims that static is not permitted, but
4514 // my very own code has static constructors.
4516 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4517 ConstructorInitializer init, Location l)
4518 : base (ds, null, null, mod, AllowedModifiers, false,
4519 new MemberName (name), null, args, l)
4524 public override string GetSignatureForError()
4526 if (ConstructorBuilder == null)
4527 return GetSignatureForError (Parent);
4529 return TypeManager.CSharpSignature (ConstructorBuilder);
4532 public bool HasCompliantArgs {
4534 return has_compliant_args;
4538 public override AttributeTargets AttributeTargets {
4540 return AttributeTargets.Constructor;
4546 // Returns true if this is a default constructor
4548 public bool IsDefault ()
4550 if ((ModFlags & Modifiers.STATIC) != 0)
4551 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4552 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4555 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4556 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4557 (Initializer is ConstructorBaseInitializer) &&
4558 (Initializer.Arguments == null);
4561 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4563 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4564 if (declarative_security == null) {
4565 declarative_security = new ListDictionary ();
4567 a.ExtractSecurityPermissionSet (declarative_security);
4571 ConstructorBuilder.SetCustomAttribute (cb);
4574 protected override bool CheckForDuplications ()
4576 ArrayList ar = Parent.InstanceConstructors;
4578 int arLen = ar.Count;
4580 for (int i = 0; i < arLen; i++) {
4581 Constructor m = (Constructor) ar [i];
4582 if (IsDuplicateImplementation (m))
4589 protected override bool CheckBase ()
4591 // Check whether arguments were correct.
4592 if (!DoDefineParameters ())
4595 // TODO: skip the rest for generated ctor
4596 if ((ModFlags & Modifiers.STATIC) != 0)
4599 if (!CheckForDuplications ())
4602 if (Parent.Kind == Kind.Struct) {
4603 if (ParameterTypes.Length == 0) {
4604 Report.Error (568, Location,
4605 "Structs can not contain explicit parameterless " +
4610 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4611 Report.Error (666, Location, "Protected member in struct declaration");
4616 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4617 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4624 // Creates the ConstructorBuilder
4626 public override bool Define ()
4628 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4629 MethodAttributes.SpecialName);
4631 if ((ModFlags & Modifiers.STATIC) != 0){
4632 ca |= MethodAttributes.Static | MethodAttributes.Private;
4634 ca |= MethodAttributes.HideBySig;
4636 if ((ModFlags & Modifiers.PUBLIC) != 0)
4637 ca |= MethodAttributes.Public;
4638 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4639 if ((ModFlags & Modifiers.INTERNAL) != 0)
4640 ca |= MethodAttributes.FamORAssem;
4642 ca |= MethodAttributes.Family;
4643 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4644 ca |= MethodAttributes.Assembly;
4645 else if (IsDefault ())
4646 ca |= MethodAttributes.Public;
4648 ca |= MethodAttributes.Private;
4651 // Check if arguments were correct.
4655 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4656 ca, CallingConventions,
4659 if ((ModFlags & Modifiers.UNSAFE) != 0)
4660 ConstructorBuilder.InitLocals = false;
4662 TypeManager.AddMethod (ConstructorBuilder, this);
4665 // HACK because System.Reflection.Emit is lame
4667 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4675 public override void Emit ()
4677 EmitContext ec = CreateEmitContext (null, null);
4680 // extern methods have no bodies
4682 if ((ModFlags & Modifiers.EXTERN) != 0) {
4683 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4685 179, Location, "External constructor `" +
4686 TypeManager.CSharpSignature (ConstructorBuilder) +
4687 "' can not have a body");
4690 } else if (block == null) {
4692 501, Location, "Constructor `" +
4693 TypeManager.CSharpSignature (ConstructorBuilder) +
4694 "' must declare a body since it is not marked extern");
4698 if ((ModFlags & Modifiers.STATIC) == 0){
4699 if (Parent.Kind == Kind.Class && Initializer == null)
4700 Initializer = new ConstructorBaseInitializer (
4701 null, Parameters.EmptyReadOnlyParameters, Location);
4705 // Spec mandates that Initializers will not have
4709 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4711 ec.IsStatic = false;
4714 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4716 SourceMethod source = SourceMethod.Create (
4717 Parent, ConstructorBuilder, block);
4720 // Classes can have base initializers and instance field initializers.
4722 if (Parent.Kind == Kind.Class){
4723 if ((ModFlags & Modifiers.STATIC) == 0){
4726 // If we use a "this (...)" constructor initializer, then
4727 // do not emit field initializers, they are initialized in the other constructor
4729 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4730 Parent.EmitFieldInitializers (ec);
4733 if (Initializer != null) {
4734 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4735 Initializer.CheckObsoleteAttribute (Parent, Location);
4737 ec.TestObsoleteMethodUsage = false;
4738 Initializer.Emit (ec);
4741 if ((ModFlags & Modifiers.STATIC) != 0)
4742 Parent.EmitFieldInitializers (ec);
4744 if (OptAttributes != null)
4745 OptAttributes.Emit (ec, this);
4747 // If this is a non-static `struct' constructor and doesn't have any
4748 // initializer, it must initialize all of the struct's fields.
4749 if ((Parent.Kind == Kind.Struct) &&
4750 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4751 Block.AddThisVariable (Parent, Location);
4753 ec.EmitTopBlock (block, ParameterInfo, Location);
4756 source.CloseMethod ();
4760 if (declarative_security != null) {
4761 foreach (DictionaryEntry de in declarative_security) {
4762 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4769 // Is never override
4770 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4775 protected override bool VerifyClsCompliance (DeclSpace ds)
4777 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4781 if (parameter_types.Length > 0) {
4782 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4784 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4786 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4787 foreach (Type param in parameter_types) {
4788 if (param.IsArray) {
4794 has_compliant_args = true;
4798 #region IMethodData Members
4800 public System.Reflection.CallingConventions CallingConventions {
4802 CallingConventions cc = Parameters.GetCallingConvention ();
4804 if (Parent.Kind == Kind.Class)
4805 if ((ModFlags & Modifiers.STATIC) == 0)
4806 cc |= CallingConventions.HasThis;
4808 // FIXME: How is `ExplicitThis' used in C#?
4814 public new Location Location {
4816 return base.Location;
4820 public MemberName MethodName {
4826 public Type ReturnType {
4832 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4834 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4835 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4838 public ObsoleteAttribute GetObsoleteAttribute ()
4843 public bool IsExcluded(EmitContext ec)
4848 GenericMethod IMethodData.GenericMethod {
4858 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4860 public interface IMethodData
4862 CallingConventions CallingConventions { get; }
4863 Location Location { get; }
4864 MemberName MethodName { get; }
4865 Type[] ParameterTypes { get; }
4866 Type ReturnType { get; }
4867 GenericMethod GenericMethod { get; }
4869 Attributes OptAttributes { get; }
4870 ToplevelBlock Block { get; }
4872 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4873 ObsoleteAttribute GetObsoleteAttribute ();
4874 string GetSignatureForError (TypeContainer tc);
4875 bool IsExcluded (EmitContext ec);
4876 bool IsClsCompliaceRequired (DeclSpace ds);
4880 // Encapsulates most of the Method's state
4882 public class MethodData {
4884 readonly IMethodData method;
4887 // The return type of this method
4889 public readonly GenericMethod GenericMethod;
4890 public readonly InternalParameters ParameterInfo;
4893 // Are we implementing an interface ?
4895 public bool IsImplementing = false;
4900 protected MemberBase member;
4901 protected int modifiers;
4902 protected MethodAttributes flags;
4903 protected Type declaring_type;
4904 protected MethodInfo parent_method;
4908 MethodBuilder builder = null;
4909 public MethodBuilder MethodBuilder {
4915 public Type DeclaringType {
4917 return declaring_type;
4921 public MethodData (MemberBase member, InternalParameters parameters,
4922 int modifiers, MethodAttributes flags, IMethodData method)
4924 this.member = member;
4925 this.ParameterInfo = parameters;
4926 this.modifiers = modifiers;
4929 this.method = method;
4932 public MethodData (MemberBase member, InternalParameters parameters,
4933 int modifiers, MethodAttributes flags,
4934 IMethodData method, MethodBuilder builder,
4935 GenericMethod generic, MethodInfo parent_method)
4936 : this (member, parameters, modifiers, flags, method)
4938 this.builder = builder;
4939 this.GenericMethod = generic;
4940 this.parent_method = parent_method;
4943 public bool Define (TypeContainer container)
4945 MethodInfo implementing = null;
4948 if (member.IsExplicitImpl)
4949 prefix = member.InterfaceType.FullName + ".";
4953 string name = method.MethodName.Basename;
4954 string method_name = prefix + name;
4956 Type[] ParameterTypes = method.ParameterTypes;
4958 if (container.Pending != null){
4959 if (member is Indexer) // TODO: test it, but it should work without this IF
4960 implementing = container.Pending.IsInterfaceIndexer (
4961 member.InterfaceType, method.ReturnType, ParameterTypes);
4963 implementing = container.Pending.IsInterfaceMethod (
4964 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4966 if (member.InterfaceType != null){
4967 if (implementing == null){
4968 if (member is PropertyBase) {
4969 Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
4970 method.GetSignatureForError (container), member.ExplicitInterfaceName);
4973 Report.Error (539, method.Location,
4974 "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
4979 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
4980 Report.SymbolRelatedToPreviousError (implementing);
4981 Report.Error (688, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
4982 method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4989 // For implicit implementations, make sure we are public, for
4990 // explicit implementations, make sure we are private.
4992 if (implementing != null){
4994 // Setting null inside this block will trigger a more
4995 // verbose error reporting for missing interface implementations
4997 // The "candidate" function has been flagged already
4998 // but it wont get cleared
5000 if (member.IsExplicitImpl){
5001 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
5002 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
5003 implementing = null;
5005 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
5006 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
5008 // If this is an interface method implementation,
5009 // check for public accessibility
5011 implementing = null;
5012 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5013 // We may never be private.
5014 implementing = null;
5015 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5017 // We may be protected if we're overriding something.
5019 implementing = null;
5024 // Static is not allowed
5026 if ((modifiers & Modifiers.STATIC) != 0){
5027 implementing = null;
5028 Modifiers.Error_InvalidModifier (method.Location, "static");
5033 // If implementing is still valid, set flags
5035 if (implementing != null){
5037 // When implementing interface methods, set NewSlot
5038 // unless, we are overwriting a method.
5040 if (implementing.DeclaringType.IsInterface){
5041 if ((modifiers & Modifiers.OVERRIDE) == 0)
5042 flags |= MethodAttributes.NewSlot;
5045 MethodAttributes.Virtual |
5046 MethodAttributes.HideBySig;
5048 // Set Final unless we're virtual, abstract or already overriding a method.
5049 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5050 flags |= MethodAttributes.Final;
5052 IsImplementing = true;
5055 EmitContext ec = method.CreateEmitContext (container, null);
5057 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
5059 if (builder == null)
5062 if (container.CurrentType != null)
5063 declaring_type = container.CurrentType;
5065 declaring_type = container.TypeBuilder;
5067 if ((modifiers & Modifiers.UNSAFE) != 0)
5068 builder.InitLocals = false;
5070 if (IsImplementing){
5072 // clear the pending implemntation flag
5074 if (member is Indexer) {
5075 container.Pending.ImplementIndexer (
5076 member.InterfaceType, builder, method.ReturnType,
5077 ParameterTypes, member.IsExplicitImpl);
5079 container.Pending.ImplementMethod (
5080 member.InterfaceType, name, method.ReturnType,
5081 ParameterTypes, member.IsExplicitImpl);
5083 if (member.IsExplicitImpl)
5084 container.TypeBuilder.DefineMethodOverride (
5085 builder, implementing);
5089 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
5090 TypeManager.AddMethod (builder, method);
5092 if (GenericMethod != null) {
5093 bool is_override = member.IsExplicitImpl |
5094 ((modifiers & Modifiers.OVERRIDE) != 0);
5096 if (implementing != null)
5097 parent_method = implementing;
5099 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5107 /// Create the MethodBuilder for the method
5109 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
5111 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
5113 if ((modifiers & extern_static) == extern_static) {
5115 if (method.OptAttributes != null) {
5116 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
5117 if (dllimport_attribute != null) {
5118 flags |= MethodAttributes.PinvokeImpl;
5119 builder = dllimport_attribute.DefinePInvokeMethod (
5120 ec, container.TypeBuilder, method_name, flags,
5121 method.ReturnType, ParameterTypes);
5127 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5128 // We are more strict than Microsoft and report CS0626 like error
5129 if (method.OptAttributes == null ||
5130 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
5131 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", method.GetSignatureForError (container));
5136 if (builder == null)
5137 builder = container.TypeBuilder.DefineMethod (
5138 method_name, flags, method.CallingConventions,
5139 method.ReturnType, ParameterTypes);
5141 builder.SetGenericMethodSignature (
5142 flags, method.CallingConventions,
5143 method.ReturnType, ParameterTypes);
5149 public void Emit (TypeContainer container, Attributable kind)
5152 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5153 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
5155 ec = method.CreateEmitContext (container, null);
5157 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
5158 ec.TestObsoleteMethodUsage = false;
5160 Location loc = method.Location;
5161 Attributes OptAttributes = method.OptAttributes;
5163 if (OptAttributes != null)
5164 OptAttributes.Emit (ec, kind);
5166 if (member is MethodCore)
5167 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
5169 ToplevelBlock block = method.Block;
5172 // abstract or extern methods have no bodies
5174 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
5179 // abstract or extern methods have no bodies.
5181 if ((modifiers & Modifiers.ABSTRACT) != 0)
5183 500, method.Location, "Abstract method `" +
5184 TypeManager.CSharpSignature (builder) +
5185 "' can not have a body");
5187 if ((modifiers & Modifiers.EXTERN) != 0)
5189 179, method.Location, "External method `" +
5190 TypeManager.CSharpSignature (builder) +
5191 "' can not have a body");
5197 // Methods must have a body unless they're extern or abstract
5199 if (block == null) {
5201 501, method.Location, "Method `" +
5202 TypeManager.CSharpSignature (builder) +
5203 "' must declare a body since it is not marked " +
5204 "abstract or extern");
5208 SourceMethod source = SourceMethod.Create (
5209 container, MethodBuilder, method.Block);
5212 // Handle destructors specially
5214 // FIXME: This code generates buggy code
5216 if (member is Destructor)
5217 EmitDestructor (ec, block);
5219 ec.EmitTopBlock (block, ParameterInfo, loc);
5222 source.CloseMethod ();
5225 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5227 ILGenerator ig = ec.ig;
5229 Label finish = ig.DefineLabel ();
5231 block.SetDestructor ();
5233 ig.BeginExceptionBlock ();
5234 ec.ReturnLabel = finish;
5235 ec.HasReturnLabel = true;
5236 ec.EmitTopBlock (block, null, method.Location);
5238 // ig.MarkLabel (finish);
5239 ig.BeginFinallyBlock ();
5241 if (ec.ContainerType.BaseType != null) {
5242 Expression member_lookup = Expression.MemberLookup (
5243 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5244 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5246 if (member_lookup != null){
5247 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5249 ig.Emit (OpCodes.Ldarg_0);
5250 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5254 ig.EndExceptionBlock ();
5255 //ig.MarkLabel (ec.ReturnLabel);
5256 ig.Emit (OpCodes.Ret);
5260 // Should derive from MethodCore
5261 public class Destructor : Method {
5263 public Destructor (TypeContainer ds, Expression return_type, int mod, string name,
5264 Parameters parameters, Attributes attrs, Location l)
5265 : base (ds, null, return_type, mod, false, new MemberName (name),
5266 parameters, attrs, l)
5269 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5271 if (a.Type == TypeManager.conditional_attribute_type) {
5272 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
5276 base.ApplyAttributeBuilder (a, cb);
5280 abstract public class MemberBase : MemberCore {
5281 public Expression Type;
5283 public MethodAttributes flags;
5285 protected readonly int explicit_mod_flags;
5288 // The "short" name of this property / indexer / event. This is the
5289 // name without the explicit interface.
5291 public string ShortName;
5294 // The type of this property / indexer / event
5296 public Type MemberType;
5299 // If true, this is an explicit interface implementation
5301 public bool IsExplicitImpl = false;
5304 // The name of the interface we are explicitly implementing
5306 public MemberName ExplicitInterfaceName = null;
5309 // Whether this is an interface member.
5311 public bool IsInterface;
5314 // If true, the interface type we are explicitly implementing
5316 public Type InterfaceType = null;
5319 // The constructor is only exposed to our children
5321 protected MemberBase (TypeContainer parent, Expression type, int mod,
5322 int allowed_mod, int def_mod, MemberName name,
5323 Attributes attrs, Location loc)
5324 : base (parent, name, attrs, loc)
5326 explicit_mod_flags = mod;
5328 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
5330 // Check for explicit interface implementation
5331 if (MemberName.Left != null) {
5332 ExplicitInterfaceName = MemberName.Left;
5333 ShortName = MemberName.Name;
5334 IsExplicitImpl = true;
5339 protected virtual bool CheckBase ()
5341 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5342 Report.Error (666, Location, "Protected member in struct declaration");
5346 if ((RootContext.WarningLevel >= 4) &&
5347 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5348 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5349 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5350 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
5356 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5358 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5362 foreach (Type partype in parameters){
5363 if (partype == TypeManager.void_type) {
5365 1547, Location, "Keyword 'void' cannot " +
5366 "be used in this context");
5370 if (partype.IsPointer){
5373 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5377 if (ds.AsAccessible (partype, ModFlags))
5380 if (this is Indexer)
5381 Report.Error (55, Location,
5382 "Inconsistent accessibility: parameter type `" +
5383 TypeManager.CSharpName (partype) + "' is less " +
5384 "accessible than indexer `" + Name + "'");
5385 else if ((this is Method) && ((Method) this).IsOperator)
5386 Report.Error (57, Location,
5387 "Inconsistent accessibility: parameter type `" +
5388 TypeManager.CSharpName (partype) + "' is less " +
5389 "accessible than operator `" + Name + "'");
5391 Report.Error (51, Location,
5392 "Inconsistent accessibility: parameter type `" +
5393 TypeManager.CSharpName (partype) + "' is less " +
5394 "accessible than method `" + Name + "'");
5401 protected virtual bool DoDefineBase ()
5403 EmitContext ec = Parent.EmitContext;
5405 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5408 throw new InternalErrorException ();
5411 ModFlags = Modifiers.PUBLIC |
5412 Modifiers.ABSTRACT |
5413 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5415 flags = MethodAttributes.Public |
5416 MethodAttributes.Abstract |
5417 MethodAttributes.HideBySig |
5418 MethodAttributes.NewSlot |
5419 MethodAttributes.Virtual;
5421 if (!Parent.MethodModifiersValid (this))
5424 flags = Modifiers.MethodAttr (ModFlags);
5430 protected virtual bool DoDefine (DeclSpace decl)
5432 EmitContext ec = decl.EmitContext;
5434 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5436 ec.InUnsafe = InUnsafe;
5438 // Lookup Type, verify validity
5439 bool old_unsafe = ec.InUnsafe;
5440 ec.InUnsafe = InUnsafe;
5441 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
5442 ec.InUnsafe = old_unsafe;
5447 MemberType = texpr.Type;
5449 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5450 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5451 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5456 // verify accessibility
5457 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5458 Report.SymbolRelatedToPreviousError (MemberType);
5459 if (this is Property)
5460 Report.Error (53, Location,
5461 "Inconsistent accessibility: property type `" +
5462 TypeManager.CSharpName (MemberType) + "' is less " +
5463 "accessible than property `" + GetSignatureForError () + "'");
5464 else if (this is Indexer)
5465 Report.Error (54, Location,
5466 "Inconsistent accessibility: indexer return type `" +
5467 TypeManager.CSharpName (MemberType) + "' is less " +
5468 "accessible than indexer `" + Name + "'");
5469 else if (this is MethodCore) {
5470 if (this is Operator)
5471 Report.Error (56, Location,
5472 "Inconsistent accessibility: return type `" +
5473 TypeManager.CSharpName (MemberType) + "' is less " +
5474 "accessible than operator `" + Name + "'");
5476 Report.Error (50, Location,
5477 "Inconsistent accessibility: return type `" +
5478 TypeManager.CSharpName (MemberType) + "' is less " +
5479 "accessible than method `" + Name + "'");
5481 Report.Error (52, Location,
5482 "Inconsistent accessibility: field type `" +
5483 TypeManager.CSharpName (MemberType) + "' is less " +
5484 "accessible than field `" + Name + "'");
5489 if (MemberType.IsPointer && !UnsafeOK (Parent))
5492 if (IsExplicitImpl) {
5493 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
5494 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5495 if (iface_texpr == null)
5498 InterfaceType = iface_texpr.Type;
5500 if (!InterfaceType.IsInterface) {
5501 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5505 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5508 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5515 /// The name of the member can be changed during definition (see IndexerName attribute)
5517 protected virtual void UpdateMemberName ()
5519 MemberName.Name = ShortName;
5522 public override string GetSignatureForError (TypeContainer tc)
5524 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5527 protected bool IsTypePermitted ()
5529 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5530 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5536 protected override bool VerifyClsCompliance(DeclSpace ds)
5538 if (base.VerifyClsCompliance (ds)) {
5542 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5543 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5548 protected override void VerifyObsoleteAttribute()
5550 CheckUsageOfObsoleteAttribute (MemberType);
5555 // Fields and Events both generate FieldBuilders, we use this to share
5556 // their common bits. This is also used to flag usage of the field
5558 abstract public class FieldBase : MemberBase {
5559 public FieldBuilder FieldBuilder;
5560 public Status status;
5563 public enum Status : byte {
5566 HAS_OFFSET = 4 // Used by FieldMember.
5569 static string[] attribute_targets = new string [] { "field" };
5572 /// Symbol with same name in base class/struct
5574 public MemberInfo conflict_symbol;
5577 // The constructor is only exposed to our children
5579 protected FieldBase (TypeContainer parent, Expression type, int mod,
5580 int allowed_mod, MemberName name, object init,
5581 Attributes attrs, Location loc)
5582 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5588 public override AttributeTargets AttributeTargets {
5590 return AttributeTargets.Field;
5594 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5596 if (a.Type == TypeManager.marshal_as_attr_type) {
5597 UnmanagedMarshal marshal = a.GetMarshal (this);
5598 if (marshal != null) {
5599 FieldBuilder.SetMarshal (marshal);
5604 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5605 a.Error_InvalidSecurityParent ();
5609 FieldBuilder.SetCustomAttribute (cb);
5613 // Whether this field has an initializer.
5615 public bool HasInitializer {
5617 return init != null;
5621 protected readonly Object init;
5623 Expression init_expr;
5624 bool init_expr_initialized = false;
5626 protected override bool CheckGenericOverride (MethodInfo method, string name)
5632 // Resolves and returns the field initializer.
5634 public Expression GetInitializerExpression (EmitContext ec)
5636 if (init_expr_initialized)
5640 if (init is Expression)
5641 e = (Expression) init;
5643 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5645 ec.IsFieldInitializer = true;
5646 e = e.DoResolve (ec);
5647 ec.IsFieldInitializer = false;
5650 init_expr_initialized = true;
5655 protected override bool CheckBase ()
5657 if (!base.CheckBase ())
5664 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5665 if (conflict_symbol == null) {
5666 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5667 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5672 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5673 Report.SymbolRelatedToPreviousError (conflict_symbol);
5674 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5680 protected override bool DoDefine (DeclSpace ds)
5682 if (!base.DoDefine (ds))
5685 if (MemberType == TypeManager.void_type) {
5686 Report.Error (1547, Location,
5687 "Keyword 'void' cannot be used in this context");
5693 public override string GetSignatureForError ()
5695 if (FieldBuilder == null) {
5696 return base.GetSignatureForError (Parent);
5698 return TypeManager.GetFullNameSignature (FieldBuilder);
5701 protected virtual bool IsFieldClsCompliant {
5703 if (FieldBuilder == null)
5706 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5710 public override string[] ValidAttributeTargets {
5712 return attribute_targets;
5716 protected override bool VerifyClsCompliance (DeclSpace ds)
5718 if (!base.VerifyClsCompliance (ds))
5721 if (!IsFieldClsCompliant) {
5722 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5728 public void SetAssigned ()
5730 status |= Status.ASSIGNED;
5734 public abstract class FieldMember: FieldBase
5738 protected FieldMember (TypeContainer parent, Expression type, int mod,
5739 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5740 : base (parent, type, mod, allowed_mod, name, init, attrs, loc)
5744 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5746 if (a.Type == TypeManager.field_offset_attribute_type)
5748 status |= Status.HAS_OFFSET;
5750 if (!Parent.HasExplicitLayout) {
5751 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5755 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5756 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5760 base.ApplyAttributeBuilder (a, cb);
5764 public override bool Define()
5766 EmitContext ec = Parent.EmitContext;
5768 throw new InternalErrorException ("FieldMember.Define called too early");
5770 bool old_unsafe = ec.InUnsafe;
5771 ec.InUnsafe = InUnsafe;
5772 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
5773 ec.InUnsafe = old_unsafe;
5777 MemberType = texpr.Type;
5779 ec.InUnsafe = old_unsafe;
5781 if (MemberType == TypeManager.void_type) {
5782 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5789 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5790 Report.Error (52, Location,
5791 "Inconsistent accessibility: field type `" +
5792 TypeManager.CSharpName (MemberType) + "' is less " +
5793 "accessible than field `" + Name + "'");
5797 if (!IsTypePermitted ())
5800 if (MemberType.IsPointer && !UnsafeOK (Parent))
5806 public override void Emit ()
5808 if (OptAttributes != null) {
5809 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5810 OptAttributes.Emit (ec, this);
5813 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5814 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5821 // Represents header string for documentation comment.
5823 public override string DocCommentHeader {
5824 get { return "F:"; }
5828 interface IFixedBuffer
5830 FieldInfo Element { get; }
5831 Type ElementType { get; }
5834 public class FixedFieldExternal: IFixedBuffer
5836 FieldInfo element_field;
5838 public FixedFieldExternal (FieldInfo fi)
5840 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5843 #region IFixedField Members
5845 public FieldInfo Element {
5847 return element_field;
5851 public Type ElementType {
5853 return element_field.FieldType;
5861 /// Fixed buffer implementation
5863 public class FixedField: FieldMember, IFixedBuffer
5865 public const string FixedElementName = "FixedElementField";
5866 static int GlobalCounter = 0;
5867 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5868 static FieldInfo[] fi;
5870 TypeBuilder fixed_buffer_type;
5871 FieldBuilder element;
5872 Expression size_expr;
5875 const int AllowedModifiers =
5878 Modifiers.PROTECTED |
5879 Modifiers.INTERNAL |
5882 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5883 Expression size_expr, Attributes attrs, Location loc):
5884 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5886 if (RootContext.Version == LanguageVersion.ISO_1)
5887 Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
5889 this.size_expr = size_expr;
5892 public override bool Define()
5894 if (Parent.Kind != Kind.Struct) {
5895 Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
5899 if (!base.Define ())
5902 if (!MemberType.IsPrimitive) {
5903 Report.Error (1663, Location, "Fixed sized buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double");
5907 Expression e = size_expr.Resolve (Parent.EmitContext);
5911 Constant c = e as Constant;
5913 Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
5917 buffer_size = (int)c.GetValue ();
5918 if (buffer_size <= 0) {
5919 Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
5922 buffer_size *= Expression.GetTypeSize (MemberType);
5925 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5927 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5928 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5929 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5930 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5932 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5933 TypeManager.RegisterFieldBase (FieldBuilder, this);
5938 public override void Emit()
5941 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5943 object[] fi_val = new object[1];
5944 fi_val [0] = buffer_size;
5946 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5947 ctor_args, fi, fi_val);
5948 fixed_buffer_type.SetCustomAttribute (cab);
5950 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5951 FieldBuilder.SetCustomAttribute (cab);
5955 protected override bool IsFieldClsCompliant {
5961 #region IFixedField Members
5963 public FieldInfo Element {
5969 public Type ElementType {
5979 // The Field class is used to represents class/struct fields during parsing.
5981 public class Field : FieldMember {
5983 // Modifiers allowed in a class declaration
5985 const int AllowedModifiers =
5988 Modifiers.PROTECTED |
5989 Modifiers.INTERNAL |
5992 Modifiers.VOLATILE |
5996 public Field (TypeContainer parent, Expression type, int mod, string name,
5997 Object expr_or_array_init, Attributes attrs, Location loc)
5998 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5999 expr_or_array_init, attrs, loc)
6003 public override bool Define ()
6005 if (!base.Define ())
6008 if (RootContext.WarningLevel > 1){
6009 Type ptype = Parent.TypeBuilder.BaseType;
6011 // ptype is only null for System.Object while compiling corlib.
6013 TypeContainer.FindMembers (
6014 ptype, MemberTypes.Method,
6015 BindingFlags.Public |
6016 BindingFlags.Static | BindingFlags.Instance,
6017 System.Type.FilterName, Name);
6021 if ((ModFlags & Modifiers.VOLATILE) != 0){
6022 if (!MemberType.IsClass){
6023 Type vt = MemberType;
6025 if (TypeManager.IsEnumType (vt))
6026 vt = TypeManager.EnumToUnderlying (MemberType);
6028 if (!((vt == TypeManager.bool_type) ||
6029 (vt == TypeManager.sbyte_type) ||
6030 (vt == TypeManager.byte_type) ||
6031 (vt == TypeManager.short_type) ||
6032 (vt == TypeManager.ushort_type) ||
6033 (vt == TypeManager.int32_type) ||
6034 (vt == TypeManager.uint32_type) ||
6035 (vt == TypeManager.char_type) ||
6036 (vt == TypeManager.float_type) ||
6037 (!vt.IsValueType))){
6039 677, Location, Parent.MakeName (Name) +
6040 " A volatile field can not be of type `" +
6041 TypeManager.CSharpName (vt) + "'");
6046 if ((ModFlags & Modifiers.READONLY) != 0){
6049 "A field can not be both volatile and readonly");
6054 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6056 if (Parent.Kind == Kind.Struct &&
6057 ((fa & FieldAttributes.Static) == 0) &&
6058 MemberType == Parent.TypeBuilder &&
6059 !TypeManager.IsBuiltinType (MemberType)){
6060 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6061 "' causes a cycle in the structure layout");
6066 FieldBuilder = Parent.TypeBuilder.DefineField (
6067 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6069 TypeManager.RegisterFieldBase (FieldBuilder, this);
6071 catch (ArgumentException) {
6072 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6081 // `set' and `get' accessors are represented with an Accessor.
6083 public class Accessor {
6085 // Null if the accessor is empty, or a Block if not
6087 public const int AllowedModifiers =
6089 Modifiers.PROTECTED |
6090 Modifiers.INTERNAL |
6093 public ToplevelBlock Block;
6094 public Attributes Attributes;
6095 public Location Location;
6096 public int ModFlags;
6098 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6103 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6108 // Ooouh Martin, templates are missing here.
6109 // When it will be possible move here a lot of child code and template method type.
6110 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
6111 protected MethodData method_data;
6112 protected ToplevelBlock block;
6113 protected ListDictionary declarative_security;
6115 // The accessor are created event if they are not wanted.
6116 // But we need them because their names are reserved.
6117 // Field says whether accessor will be emited or not
6118 public readonly bool IsDummy;
6120 protected readonly string prefix;
6122 ReturnParameter return_attributes;
6124 public AbstractPropertyEventMethod (MemberBase member, string prefix)
6125 : base (null, SetupName (prefix, member), null, member.Location)
6127 this.prefix = prefix;
6131 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
6133 : base (null, SetupName (prefix, member),
6134 accessor.Attributes, accessor.Location)
6136 this.prefix = prefix;
6137 this.block = accessor.Block;
6140 static MemberName SetupName (string prefix, MemberBase member)
6142 MemberName name = member.MemberName.Clone ();
6143 name.Name = prefix + member.ShortName;
6147 public void UpdateName (MemberBase member)
6149 MemberName.Name = prefix + member.ShortName;
6152 #region IMethodData Members
6154 public ToplevelBlock Block {
6164 public CallingConventions CallingConventions {
6166 return CallingConventions.Standard;
6170 public bool IsExcluded (EmitContext ec)
6175 GenericMethod IMethodData.GenericMethod {
6181 public MemberName MethodName {
6187 public abstract ObsoleteAttribute GetObsoleteAttribute ();
6188 public abstract Type[] ParameterTypes { get; }
6189 public abstract Type ReturnType { get; }
6190 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
6194 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6196 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6197 a.Type == TypeManager.conditional_attribute_type) {
6198 Report.Error (1667, a.Location, "'{0}' is not valid on property or event accessors. It is valid on {1} declarations only", TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6202 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6203 if (declarative_security == null)
6204 declarative_security = new ListDictionary ();
6205 a.ExtractSecurityPermissionSet (declarative_security);
6209 if (a.Target == AttributeTargets.Method) {
6210 method_data.MethodBuilder.SetCustomAttribute (cb);
6214 if (a.Target == AttributeTargets.ReturnValue) {
6215 if (return_attributes == null)
6216 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6218 return_attributes.ApplyAttributeBuilder (a, cb);
6222 ApplyToExtraTarget (a, cb);
6225 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6227 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6230 public override bool Define()
6232 throw new NotSupportedException ();
6235 public virtual void Emit (TypeContainer container)
6237 method_data.Emit (container, this);
6239 if (declarative_security != null) {
6240 foreach (DictionaryEntry de in declarative_security) {
6241 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6248 public override bool IsClsCompliaceRequired(DeclSpace ds)
6253 public bool IsDuplicateImplementation (MethodCore method)
6255 if (Name != method.Name)
6258 Type[] param_types = method.ParameterTypes;
6260 if (param_types.Length != ParameterTypes.Length)
6263 for (int i = 0; i < param_types.Length; i++)
6264 if (param_types [i] != ParameterTypes [i])
6267 Report.SymbolRelatedToPreviousError (method);
6268 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with " +
6269 "the same parameter types", Parent.Name, Name);
6273 public new Location Location {
6275 return base.Location;
6280 // Represents header string for documentation comment.
6282 public override string DocCommentHeader {
6283 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6286 protected override void VerifyObsoleteAttribute()
6293 // Properties and Indexers both generate PropertyBuilders, we use this to share
6294 // their common bits.
6296 abstract public class PropertyBase : MethodCore {
6298 public class GetMethod: PropertyMethod
6300 static string[] attribute_targets = new string [] { "method", "return" };
6302 public GetMethod (MethodCore method):
6303 base (method, "get_")
6307 public GetMethod (MethodCore method, Accessor accessor):
6308 base (method, accessor, "get_")
6312 public override MethodBuilder Define(TypeContainer container)
6314 base.Define (container);
6316 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
6318 if (!method_data.Define (container))
6321 return method_data.MethodBuilder;
6324 public override string GetSignatureForError (TypeContainer tc)
6326 return String.Concat (base.GetSignatureForError (tc), ".get");
6329 public override Type ReturnType {
6331 return method.MemberType;
6335 public override string[] ValidAttributeTargets {
6337 return attribute_targets;
6342 public class SetMethod: PropertyMethod {
6344 static string[] attribute_targets = new string [] { "method", "param", "return" };
6345 ImplicitParameter param_attr;
6347 public SetMethod (MethodCore method):
6348 base (method, "set_")
6352 public SetMethod (MethodCore method, Accessor accessor):
6353 base (method, accessor, "set_")
6357 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6359 if (a.Target == AttributeTargets.Parameter) {
6360 if (param_attr == null)
6361 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6363 param_attr.ApplyAttributeBuilder (a, cb);
6367 base.ApplyAttributeBuilder (a, cb);
6370 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
6372 Parameter [] parms = new Parameter [1];
6373 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
6374 Parameters parameters = new Parameters (parms, null, method.Location);
6376 bool old_unsafe = ec.InUnsafe;
6377 ec.InUnsafe = InUnsafe;
6378 Type [] types = parameters.GetParameterInfo (ec);
6379 ec.InUnsafe = old_unsafe;
6381 return new InternalParameters (types, parameters);
6384 public override MethodBuilder Define (TypeContainer container)
6386 if (container.EmitContext == null)
6387 throw new InternalErrorException ("SetMethod.Define called too early");
6389 base.Define (container);
6391 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6393 if (!method_data.Define (container))
6396 return method_data.MethodBuilder;
6399 public override string GetSignatureForError (TypeContainer tc)
6401 return String.Concat (base.GetSignatureForError (tc), ".set");
6404 public override Type[] ParameterTypes {
6406 return new Type[] { method.MemberType };
6410 public override Type ReturnType {
6412 return TypeManager.void_type;
6416 public override string[] ValidAttributeTargets {
6418 return attribute_targets;
6423 static string[] attribute_targets = new string [] { "property" };
6425 public abstract class PropertyMethod: AbstractPropertyEventMethod {
6426 protected readonly MethodCore method;
6427 protected MethodAttributes flags;
6429 public PropertyMethod (MethodCore method, string prefix)
6430 : base (method, prefix)
6432 this.method = method;
6433 Parent = method.Parent;
6436 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6437 : base (method, accessor, prefix)
6439 this.method = method;
6440 Parent = method.Parent;
6441 this.ModFlags = accessor.ModFlags;
6443 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6444 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
6445 Environment.Exit (1);
6449 public override AttributeTargets AttributeTargets {
6451 return AttributeTargets.Method;
6455 public override bool IsClsCompliaceRequired(DeclSpace ds)
6457 return method.IsClsCompliaceRequired (ds);
6460 public InternalParameters ParameterInfo
6463 return method_data.ParameterInfo;
6467 public virtual MethodBuilder Define (TypeContainer container)
6470 // Check for custom access modifier
6472 if (ModFlags == 0) {
6473 ModFlags = method.ModFlags;
6474 flags = method.flags;
6476 CheckModifiers (container, ModFlags);
6477 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6478 flags = Modifiers.MethodAttr (ModFlags);
6479 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6486 public override Type[] ParameterTypes {
6488 return TypeManager.NoTypes;
6492 public override EmitContext CreateEmitContext (TypeContainer tc,
6495 return new EmitContext (
6496 tc, method.ds, method.Location, ig, ReturnType,
6497 method.ModFlags, false);
6500 public override ObsoleteAttribute GetObsoleteAttribute ()
6502 return method.GetObsoleteAttribute (method.ds);
6505 public override string GetSignatureForError (TypeContainer tc)
6507 return String.Concat (tc.Name, '.', method.Name);
6510 void CheckModifiers (TypeContainer container, int modflags)
6513 int mflags = method.ModFlags & Modifiers.Accessibility;
6515 if ((mflags & Modifiers.PUBLIC) != 0) {
6516 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6518 else if ((mflags & Modifiers.PROTECTED) != 0) {
6519 if ((mflags & Modifiers.INTERNAL) != 0)
6520 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6522 flags |= Modifiers.PRIVATE;
6524 else if ((mflags & Modifiers.INTERNAL) != 0)
6525 flags |= Modifiers.PRIVATE;
6527 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6528 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6529 GetSignatureForError (container));
6532 public override bool MarkForDuplicationCheck ()
6534 caching_flags |= Flags.TestMethodDuplication;
6539 public PropertyMethod Get, Set;
6540 public PropertyBuilder PropertyBuilder;
6541 public MethodBuilder GetBuilder, SetBuilder;
6543 protected EmitContext ec;
6545 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6546 int allowed_mod, bool is_iface, MemberName name,
6547 Parameters parameters, Attributes attrs,
6549 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6550 attrs, parameters, loc)
6554 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6556 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6557 a.Error_InvalidSecurityParent ();
6561 PropertyBuilder.SetCustomAttribute (cb);
6564 public override AttributeTargets AttributeTargets {
6566 return AttributeTargets.Property;
6570 public override bool Define ()
6572 if (!DoDefine (Parent))
6575 if (!IsTypePermitted ())
6581 protected override bool DoDefine (DeclSpace ds)
6583 if (!base.DoDefine (ds))
6587 // Accessors modifiers check
6589 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6590 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6591 GetSignatureForError ());
6595 if ((Get.IsDummy || Set.IsDummy)
6596 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6597 Report.Error (276, Location,
6598 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6599 GetSignatureForError ());
6603 if (MemberType.IsAbstract && MemberType.IsSealed) {
6604 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6608 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6612 public override string GetSignatureForError()
6614 if (PropertyBuilder == null)
6615 return GetSignatureForError (Parent);
6617 return TypeManager.CSharpSignature (PropertyBuilder, false);
6620 protected override bool CheckForDuplications ()
6622 ArrayList ar = Parent.Indexers;
6624 int arLen = ar.Count;
6626 for (int i = 0; i < arLen; i++) {
6627 Indexer m = (Indexer) ar [i];
6628 if (IsDuplicateImplementation (m))
6633 ar = Parent.Properties;
6635 int arLen = ar.Count;
6637 for (int i = 0; i < arLen; i++) {
6638 Property m = (Property) ar [i];
6639 if (IsDuplicateImplementation (m))
6647 // TODO: rename to Resolve......
6648 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6650 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6651 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6653 if (base_property == null)
6656 base_ret_type = base_property.PropertyType;
6657 MethodInfo get_accessor = base_property.GetGetMethod (true);
6658 MethodInfo set_accessor = base_property.GetSetMethod (true);
6659 MethodAttributes get_accessor_access, set_accessor_access;
6661 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6662 if (Get != null && !Get.IsDummy && get_accessor == null) {
6663 Report.SymbolRelatedToPreviousError (base_property);
6664 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6667 if (Set != null && !Set.IsDummy && set_accessor == null) {
6668 Report.SymbolRelatedToPreviousError (base_property);
6669 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6674 // Check base class accessors access
6676 get_accessor_access = set_accessor_access = 0;
6677 if ((ModFlags & Modifiers.NEW) == 0) {
6678 if (get_accessor != null) {
6679 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6680 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6682 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6683 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6684 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6687 if (set_accessor != null) {
6688 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6689 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6691 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6692 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6693 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6698 // Get the less restrictive access
6700 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6703 public override void Emit ()
6706 // The PropertyBuilder can be null for explicit implementations, in that
6707 // case, we do not actually emit the ".property", so there is nowhere to
6708 // put the attribute
6710 if (PropertyBuilder != null && OptAttributes != null)
6711 OptAttributes.Emit (ec, this);
6723 /// Tests whether accessors are not in collision with some method (CS0111)
6725 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6727 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6730 protected override void UpdateMemberName ()
6732 base.UpdateMemberName ();
6734 Get.UpdateName (this);
6735 Set.UpdateName (this);
6738 protected override bool VerifyClsCompliance (DeclSpace ds)
6740 if (!base.VerifyClsCompliance (ds))
6743 if ((Get.ModFlags != ModFlags && !Get.IsDummy) || (Set.ModFlags != ModFlags && !Set.IsDummy)) {
6744 Report.Error (3025, Get.ModFlags != ModFlags ? Get.Location : Set.Location,
6745 "CLS-compliant accessors must have the same accessibility as their property");
6750 public override string[] ValidAttributeTargets {
6752 return attribute_targets;
6757 // Represents header string for documentation comment.
6759 public override string DocCommentHeader {
6760 get { return "P:"; }
6764 public class Property : PropertyBase, IIteratorContainer {
6765 const int AllowedModifiers =
6768 Modifiers.PROTECTED |
6769 Modifiers.INTERNAL |
6773 Modifiers.OVERRIDE |
6774 Modifiers.ABSTRACT |
6777 Modifiers.METHOD_YIELDS |
6780 const int AllowedInterfaceModifiers =
6783 public Property (TypeContainer parent, Expression type, int mod_flags,
6784 bool is_iface, MemberName name, Attributes attrs,
6785 Accessor get_block, Accessor set_block, Location loc)
6786 : base (parent, type, mod_flags,
6787 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6788 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6791 if (get_block == null)
6792 Get = new GetMethod (this);
6794 Get = new GetMethod (this, get_block);
6796 if (set_block == null)
6797 Set = new SetMethod (this);
6799 Set = new SetMethod (this, set_block);
6802 public override bool Define ()
6804 if (!DoDefineBase ())
6807 if (!base.Define ())
6813 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6817 GetBuilder = Get.Define (Parent);
6818 if (GetBuilder == null)
6822 // Setup iterator if we are one
6824 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6825 Iterator iterator = new Iterator (
6826 Parent, "get", MemberType,
6827 TypeManager.NoTypes, Get.ParameterInfo,
6828 ModFlags, Get.Block, Location);
6830 if (!iterator.DefineIterator ())
6832 Get.Block = iterator.Block;
6837 SetBuilder = Set.Define (Parent);
6838 if (SetBuilder == null)
6841 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6844 // FIXME - PropertyAttributes.HasDefault ?
6846 PropertyAttributes prop_attr = PropertyAttributes.None;
6848 prop_attr |= PropertyAttributes.RTSpecialName |
6849 PropertyAttributes.SpecialName;
6851 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6852 Name, prop_attr, MemberType, null);
6855 PropertyBuilder.SetGetMethod (GetBuilder);
6858 PropertyBuilder.SetSetMethod (SetBuilder);
6860 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6864 public void SetYields ()
6866 ModFlags |= Modifiers.METHOD_YIELDS;
6871 /// Gigantic workaround for lameness in SRE follows :
6872 /// This class derives from EventInfo and attempts to basically
6873 /// wrap around the EventBuilder so that FindMembers can quickly
6874 /// return this in it search for members
6876 public class MyEventBuilder : EventInfo {
6879 // We use this to "point" to our Builder which is
6880 // not really a MemberInfo
6882 EventBuilder MyBuilder;
6885 // We "catch" and wrap these methods
6887 MethodInfo raise, remove, add;
6889 EventAttributes attributes;
6890 Type declaring_type, reflected_type, event_type;
6895 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6897 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6899 // And now store the values in our own fields.
6901 declaring_type = type_builder;
6903 reflected_type = type_builder;
6905 attributes = event_attr;
6908 this.event_type = event_type;
6912 // Methods that you have to override. Note that you only need
6913 // to "implement" the variants that take the argument (those are
6914 // the "abstract" methods, the others (GetAddMethod()) are
6917 public override MethodInfo GetAddMethod (bool nonPublic)
6922 public override MethodInfo GetRemoveMethod (bool nonPublic)
6927 public override MethodInfo GetRaiseMethod (bool nonPublic)
6933 // These methods make "MyEventInfo" look like a Builder
6935 public void SetRaiseMethod (MethodBuilder raiseMethod)
6937 raise = raiseMethod;
6938 MyBuilder.SetRaiseMethod (raiseMethod);
6941 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6943 remove = removeMethod;
6944 MyBuilder.SetRemoveOnMethod (removeMethod);
6947 public void SetAddOnMethod (MethodBuilder addMethod)
6950 MyBuilder.SetAddOnMethod (addMethod);
6953 public void SetCustomAttribute (CustomAttributeBuilder cb)
6955 MyBuilder.SetCustomAttribute (cb);
6958 public override object [] GetCustomAttributes (bool inherit)
6960 // FIXME : There's nothing which can be seemingly done here because
6961 // we have no way of getting at the custom attribute objects of the
6966 public override object [] GetCustomAttributes (Type t, bool inherit)
6968 // FIXME : Same here !
6972 public override bool IsDefined (Type t, bool b)
6977 public override EventAttributes Attributes {
6983 public override string Name {
6989 public override Type DeclaringType {
6991 return declaring_type;
6995 public override Type ReflectedType {
6997 return reflected_type;
7001 public Type EventType {
7007 public void SetUsed ()
7009 if (my_event != null)
7010 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
7015 /// For case when event is declared like property (with add and remove accessors).
7017 public class EventProperty: Event {
7019 static string[] attribute_targets = new string [] { "event", "property" };
7021 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
7022 bool is_iface, MemberName name, Object init,
7023 Attributes attrs, Accessor add, Accessor remove,
7025 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
7027 Add = new AddDelegateMethod (this, add);
7028 Remove = new RemoveDelegateMethod (this, remove);
7030 // For this event syntax we don't report error CS0067
7031 // because it is hard to do it.
7035 public override string[] ValidAttributeTargets {
7037 return attribute_targets;
7043 /// Event is declared like field.
7045 public class EventField: Event {
7047 static string[] attribute_targets = new string [] { "event", "field", "method" };
7048 static string[] attribute_targets_interface = new string[] { "event", "method" };
7050 public EventField (TypeContainer parent, Expression type, int mod_flags,
7051 bool is_iface, MemberName name, Object init,
7052 Attributes attrs, Location loc)
7053 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
7055 Add = new AddDelegateMethod (this);
7056 Remove = new RemoveDelegateMethod (this);
7059 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7061 if (a.Target == AttributeTargets.Field) {
7062 FieldBuilder.SetCustomAttribute (cb);
7066 if (a.Target == AttributeTargets.Method) {
7067 Add.ApplyAttributeBuilder (a, cb);
7068 Remove.ApplyAttributeBuilder (a, cb);
7072 base.ApplyAttributeBuilder (a, cb);
7075 public override string[] ValidAttributeTargets {
7077 return IsInterface ? attribute_targets_interface : attribute_targets;
7082 public abstract class Event : FieldBase {
7084 protected sealed class AddDelegateMethod: DelegateMethod
7087 public AddDelegateMethod (Event method):
7088 base (method, "add_")
7092 public AddDelegateMethod (Event method, Accessor accessor):
7093 base (method, accessor, "add_")
7097 protected override MethodInfo DelegateMethodInfo {
7099 return TypeManager.delegate_combine_delegate_delegate;
7105 protected sealed class RemoveDelegateMethod: DelegateMethod
7107 public RemoveDelegateMethod (Event method):
7108 base (method, "remove_")
7112 public RemoveDelegateMethod (Event method, Accessor accessor):
7113 base (method, accessor, "remove_")
7117 protected override MethodInfo DelegateMethodInfo {
7119 return TypeManager.delegate_remove_delegate_delegate;
7125 public abstract class DelegateMethod: AbstractPropertyEventMethod
7127 protected readonly Event method;
7128 ImplicitParameter param_attr;
7130 static string[] attribute_targets = new string [] { "method", "param", "return" };
7132 public DelegateMethod (Event method, string prefix)
7133 : base (method, prefix)
7135 this.method = method;
7138 public DelegateMethod (Event method, Accessor accessor, string prefix)
7139 : base (method, accessor, prefix)
7141 this.method = method;
7144 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7146 if (a.Target == AttributeTargets.Parameter) {
7147 if (param_attr == null)
7148 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7150 param_attr.ApplyAttributeBuilder (a, cb);
7154 base.ApplyAttributeBuilder (a, cb);
7157 public override AttributeTargets AttributeTargets {
7159 return AttributeTargets.Method;
7163 public override bool IsClsCompliaceRequired(DeclSpace ds)
7165 return method.IsClsCompliaceRequired (ds);
7168 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
7170 method_data = new MethodData (method, ip, method.ModFlags,
7171 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7173 if (!method_data.Define (container))
7176 MethodBuilder mb = method_data.MethodBuilder;
7177 mb.DefineParameter (1, ParameterAttributes.None, "value");
7182 public override void Emit (TypeContainer tc)
7184 if (block != null) {
7189 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
7190 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
7192 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
7193 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7194 ig.Emit (OpCodes.Ldsfld, field_info);
7195 ig.Emit (OpCodes.Ldarg_0);
7196 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7197 ig.Emit (OpCodes.Castclass, method.MemberType);
7198 ig.Emit (OpCodes.Stsfld, field_info);
7200 ig.Emit (OpCodes.Ldarg_0);
7201 ig.Emit (OpCodes.Ldarg_0);
7202 ig.Emit (OpCodes.Ldfld, field_info);
7203 ig.Emit (OpCodes.Ldarg_1);
7204 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7205 ig.Emit (OpCodes.Castclass, method.MemberType);
7206 ig.Emit (OpCodes.Stfld, field_info);
7208 ig.Emit (OpCodes.Ret);
7211 protected abstract MethodInfo DelegateMethodInfo { get; }
7213 public override Type[] ParameterTypes {
7215 return new Type[] { method.MemberType };
7219 public override Type ReturnType {
7221 return TypeManager.void_type;
7225 public override EmitContext CreateEmitContext (TypeContainer tc,
7228 return new EmitContext (
7229 tc, method.Parent, Location, ig, ReturnType,
7230 method.ModFlags, false);
7233 public override string GetSignatureForError (TypeContainer tc)
7235 return String.Concat (tc.Name, '.', method.Name);
7238 public override ObsoleteAttribute GetObsoleteAttribute ()
7240 return method.GetObsoleteAttribute (method.Parent);
7243 public override string[] ValidAttributeTargets {
7245 return attribute_targets;
7251 const int AllowedModifiers =
7254 Modifiers.PROTECTED |
7255 Modifiers.INTERNAL |
7260 Modifiers.OVERRIDE |
7264 const int AllowedInterfaceModifiers =
7267 public DelegateMethod Add, Remove;
7268 public MyEventBuilder EventBuilder;
7269 public MethodBuilder AddBuilder, RemoveBuilder;
7271 MethodData AddData, RemoveData;
7273 public Event (TypeContainer parent, Expression type, int mod_flags,
7274 bool is_iface, MemberName name, Object init, Attributes attrs,
7276 : base (parent, type, mod_flags,
7277 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7278 name, init, attrs, loc)
7280 IsInterface = is_iface;
7283 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7285 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7286 a.Error_InvalidSecurityParent ();
7290 EventBuilder.SetCustomAttribute (cb);
7293 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7295 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7298 public override AttributeTargets AttributeTargets {
7300 return AttributeTargets.Event;
7304 public override bool Define ()
7306 EventAttributes e_attr;
7307 e_attr = EventAttributes.None;
7309 if (!DoDefineBase ())
7312 if (!DoDefine (Parent))
7315 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
7316 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
7317 "': abstract event can not have an initializer");
7321 if (!TypeManager.IsDelegateType (MemberType)) {
7322 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
7323 "' : event must be of a delegate type");
7327 EmitContext ec = Parent.EmitContext;
7329 throw new InternalErrorException ("Event.Define called too early?");
7330 bool old_unsafe = ec.InUnsafe;
7331 ec.InUnsafe = InUnsafe;
7333 Parameter [] parms = new Parameter [1];
7334 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
7335 Parameters parameters = new Parameters (parms, null, Location);
7336 Type [] types = parameters.GetParameterInfo (ec);
7337 InternalParameters ip = new InternalParameters (types, parameters);
7339 ec.InUnsafe = old_unsafe;
7345 // Now define the accessors
7348 AddBuilder = Add.Define (Parent, ip);
7349 if (AddBuilder == null)
7352 RemoveBuilder = Remove.Define (Parent, ip);
7353 if (RemoveBuilder == null)
7356 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7358 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7359 FieldBuilder = Parent.TypeBuilder.DefineField (
7361 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7362 TypeManager.RegisterPrivateFieldOfEvent (
7363 (EventInfo) EventBuilder, FieldBuilder);
7364 TypeManager.RegisterFieldBase (FieldBuilder, this);
7367 EventBuilder.SetAddOnMethod (AddBuilder);
7368 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7370 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7374 protected override bool CheckBase ()
7376 if (!base.CheckBase ())
7379 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7380 if (!(conflict_symbol is EventInfo)) {
7381 Report.SymbolRelatedToPreviousError (conflict_symbol);
7382 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
7390 public override void Emit ()
7392 if (OptAttributes != null) {
7393 EmitContext ec = new EmitContext (
7394 Parent, Location, null, MemberType, ModFlags);
7395 OptAttributes.Emit (ec, this);
7400 Remove.Emit (Parent);
7406 public override string GetSignatureForError ()
7408 if (EventBuilder == null)
7409 return base.GetSignatureForError (Parent);
7411 return TypeManager.GetFullNameSignature (EventBuilder);
7415 // Represents header string for documentation comment.
7417 public override string DocCommentHeader {
7418 get { return "E:"; }
7423 public class Indexer : PropertyBase {
7425 class GetIndexerMethod: GetMethod
7427 public GetIndexerMethod (MethodCore method):
7432 public GetIndexerMethod (MethodCore method, Accessor accessor):
7433 base (method, accessor)
7437 // TODO: one GetSignatureForError is enough (reuse Parent member)
7438 public override string GetSignatureForError (TypeContainer tc)
7440 string core = base.GetSignatureForError (tc);
7441 return core.Replace (TypeContainer.DefaultIndexerName,
7442 String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
7445 public override Type[] ParameterTypes {
7447 return method.ParameterTypes;
7452 class SetIndexerMethod: SetMethod
7454 readonly Parameters parameters;
7456 public SetIndexerMethod (MethodCore method):
7461 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7462 base (method, accessor)
7464 this.parameters = parameters;
7467 public override Type[] ParameterTypes {
7469 int top = method.ParameterTypes.Length;
7470 Type [] set_pars = new Type [top + 1];
7471 method.ParameterTypes.CopyTo (set_pars, 0);
7472 set_pars [top] = method.MemberType;
7477 protected override InternalParameters GetParameterInfo (EmitContext ec)
7479 Parameter [] fixed_parms = parameters.FixedParameters;
7481 if (fixed_parms == null){
7482 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7483 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7484 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7486 // Here is the problem: the `value' parameter has
7487 // to come *after* the array parameter in the declaration
7489 // X (object [] x, Type value)
7492 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7493 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7497 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7499 fixed_parms.CopyTo (tmp, 0);
7500 tmp [fixed_parms.Length] = new Parameter (
7501 method.Type, "value", Parameter.Modifier.NONE, null);
7503 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7504 Type [] types = set_formal_params.GetParameterInfo (ec);
7506 return new InternalParameters (types, set_formal_params);
7510 const int AllowedModifiers =
7513 Modifiers.PROTECTED |
7514 Modifiers.INTERNAL |
7518 Modifiers.OVERRIDE |
7523 const int AllowedInterfaceModifiers =
7527 // Are we implementing an interface ?
7529 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7530 bool is_iface, Parameters parameters, Attributes attrs,
7531 Accessor get_block, Accessor set_block, Location loc)
7532 : base (parent, type, mod,
7533 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7534 is_iface, name, parameters, attrs, loc)
7536 if (get_block == null)
7537 Get = new GetIndexerMethod (this);
7539 Get = new GetIndexerMethod (this, get_block);
7541 if (set_block == null)
7542 Set = new SetIndexerMethod (this);
7544 Set = new SetIndexerMethod (this, parameters, set_block);
7547 public override bool Define ()
7549 PropertyAttributes prop_attr =
7550 PropertyAttributes.RTSpecialName |
7551 PropertyAttributes.SpecialName;
7553 if (!DoDefineBase ())
7556 if (!base.Define ())
7559 if (MemberType == TypeManager.void_type) {
7560 Report.Error (620, Location, "Indexers cannot have void type");
7564 if (OptAttributes != null) {
7565 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7566 if (indexer_attr != null) {
7567 // Remove the attribute from the list because it is not emitted
7568 OptAttributes.Attrs.Remove (indexer_attr);
7570 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7572 if (IsExplicitImpl) {
7573 Report.Error (415, indexer_attr.Location,
7574 "The 'IndexerName' attribute is valid only on an " +
7575 "indexer that is not an explicit interface member declaration");
7579 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7580 Report.Error (609, indexer_attr.Location,
7581 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7585 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7586 Report.Error (633, indexer_attr.Location,
7587 "The argument to the 'IndexerName' attribute must be a valid identifier");
7591 UpdateMemberName ();
7595 if (InterfaceType != null) {
7596 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7597 if (base_IndexerName != Name)
7598 ShortName = base_IndexerName;
7599 UpdateMemberName ();
7602 if (!Parent.AddToMemberContainer (this) ||
7603 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7609 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7611 GetBuilder = Get.Define (Parent);
7612 if (GetBuilder == null)
7617 SetBuilder = Set.Define (Parent);
7618 if (SetBuilder == null)
7623 // Now name the parameters
7625 Parameter [] p = Parameters.FixedParameters;
7627 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7628 Report.Error (631, Location, "ref and out are not valid in this context");
7634 for (i = 0; i < p.Length; ++i) {
7636 GetBuilder.DefineParameter (
7637 i + 1, p [i].Attributes, p [i].Name);
7640 SetBuilder.DefineParameter (
7641 i + 1, p [i].Attributes, p [i].Name);
7645 SetBuilder.DefineParameter (
7646 i + 1, ParameterAttributes.None, "value");
7648 if (i != ParameterTypes.Length) {
7649 Parameter array_param = Parameters.ArrayParameter;
7651 SetBuilder.DefineParameter (
7652 i + 1, array_param.Attributes, array_param.Name);
7656 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7657 Name, prop_attr, MemberType, ParameterTypes);
7660 PropertyBuilder.SetGetMethod (GetBuilder);
7663 PropertyBuilder.SetSetMethod (SetBuilder);
7665 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7670 public override string GetSignatureForError ()
7672 if (PropertyBuilder == null)
7673 return GetSignatureForError (Parent);
7675 return TypeManager.CSharpSignature (PropertyBuilder, true);
7678 public override string GetSignatureForError(TypeContainer tc)
7680 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7683 public override bool MarkForDuplicationCheck ()
7685 caching_flags |= Flags.TestMethodDuplication;
7691 public class Operator : MethodCore, IIteratorContainer {
7693 const int AllowedModifiers =
7699 public enum OpType : byte {
7709 // Unary and Binary operators
7732 // Implicit and Explicit
7737 public readonly OpType OperatorType;
7738 public MethodBuilder OperatorMethodBuilder;
7740 public Method OperatorMethod;
7742 static string[] attribute_targets = new string [] { "method", "return" };
7744 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7745 int mod_flags, Parameters parameters,
7746 ToplevelBlock block, Attributes attrs, Location loc)
7747 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7748 new MemberName ("op_" + type), attrs, parameters, loc)
7750 OperatorType = type;
7754 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7756 OperatorMethod.ApplyAttributeBuilder (a, cb);
7759 public override AttributeTargets AttributeTargets {
7761 return AttributeTargets.Method;
7765 protected override bool CheckGenericOverride (MethodInfo method, string name)
7770 protected override bool CheckForDuplications()
7772 ArrayList ar = Parent.Operators;
7774 int arLen = ar.Count;
7776 for (int i = 0; i < arLen; i++) {
7777 Operator o = (Operator) ar [i];
7778 if (IsDuplicateImplementation (o))
7783 ar = Parent.Methods;
7785 int arLen = ar.Count;
7787 for (int i = 0; i < arLen; i++) {
7788 Method m = (Method) ar [i];
7789 if (IsDuplicateImplementation (m))
7797 public override bool Define ()
7799 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7800 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7801 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7808 if (MemberType == TypeManager.void_type) {
7809 Report.Error (590, Location, "User-defined operators cannot return void");
7813 OperatorMethod = new Method (
7814 Parent, null, Type, ModFlags, false, MemberName,
7815 Parameters, OptAttributes, Location);
7817 OperatorMethod.Block = Block;
7818 OperatorMethod.IsOperator = true;
7819 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7820 OperatorMethod.Define ();
7822 if (OperatorMethod.MethodBuilder == null)
7825 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7827 parameter_types = OperatorMethod.ParameterTypes;
7828 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7829 Type return_type = OperatorMethod.ReturnType;
7830 Type first_arg_type = parameter_types [0];
7835 // Rules for conversion operators
7837 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7838 if (first_arg_type == return_type && first_arg_type == declaring_type){
7841 "User-defined conversion cannot take an object of the " +
7842 "enclosing type and convert to an object of the enclosing" +
7847 if (first_arg_type != declaring_type && return_type != declaring_type){
7850 "User-defined conversion must convert to or from the " +
7855 if (first_arg_type == TypeManager.object_type ||
7856 return_type == TypeManager.object_type){
7859 "User-defined conversion cannot convert to or from " +
7864 if (first_arg_type.IsInterface || return_type.IsInterface){
7867 "User-defined conversion cannot convert to or from an " +
7872 if (first_arg_type.IsSubclassOf (return_type)
7873 || return_type.IsSubclassOf (first_arg_type)){
7874 if (declaring_type.IsSubclassOf (return_type)) {
7875 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7878 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7881 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7882 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7883 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");
7886 } else if (Parameters.FixedParameters.Length == 1) {
7887 // Checks for Unary operators
7889 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7890 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7891 Report.Error (448, Location,
7892 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7895 if (first_arg_type != declaring_type){
7897 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7902 if (first_arg_type != declaring_type){
7905 "The parameter of a unary operator must be the " +
7910 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7911 if (return_type != TypeManager.bool_type){
7914 "The return type of operator True or False " +
7921 if (OperatorType == OpType.BitwiseAnd &&
7922 (first_arg_type != return_type || first_arg_type != parameter_types [1])) {
7923 Report.Error (217, Location, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
7924 "must have the same return type as the type of its 2 parameters", GetSignatureForError ());
7928 // Checks for Binary operators
7930 if (first_arg_type != declaring_type &&
7931 parameter_types [1] != declaring_type){
7934 "One of the parameters of a binary operator must " +
7935 "be the containing type");
7943 public override void Emit ()
7946 // abstract or extern methods have no bodies
7948 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7951 OperatorMethod.Emit ();
7955 // Operator cannot be override
7956 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7961 public static string GetName (OpType ot)
7964 case OpType.LogicalNot:
7966 case OpType.OnesComplement:
7968 case OpType.Increment:
7970 case OpType.Decrement:
7976 case OpType.Addition:
7978 case OpType.Subtraction:
7980 case OpType.UnaryPlus:
7982 case OpType.UnaryNegation:
7984 case OpType.Multiply:
7986 case OpType.Division:
7988 case OpType.Modulus:
7990 case OpType.BitwiseAnd:
7992 case OpType.BitwiseOr:
7994 case OpType.ExclusiveOr:
7996 case OpType.LeftShift:
7998 case OpType.RightShift:
8000 case OpType.Equality:
8002 case OpType.Inequality:
8004 case OpType.GreaterThan:
8006 case OpType.LessThan:
8008 case OpType.GreaterThanOrEqual:
8010 case OpType.LessThanOrEqual:
8012 case OpType.Implicit:
8014 case OpType.Explicit:
8020 public override string GetSignatureForError (TypeContainer tc)
8022 StringBuilder sb = new StringBuilder ();
8023 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
8024 Parameters.FixedParameters [0].GetSignatureForError ());
8026 if (Parameters.FixedParameters.Length > 1) {
8028 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
8031 return sb.ToString ();
8034 public override string GetSignatureForError ()
8039 public override bool MarkForDuplicationCheck ()
8041 caching_flags |= Flags.TestMethodDuplication;
8045 public override string ToString ()
8047 if (OperatorMethod == null)
8050 Type return_type = OperatorMethod.ReturnType;
8051 Type [] param_types = OperatorMethod.ParameterTypes;
8053 if (Parameters.FixedParameters.Length == 1)
8054 return String.Format (
8055 "{0} operator {1}({2})",
8056 TypeManager.CSharpName (return_type),
8057 GetName (OperatorType),
8060 return String.Format (
8061 "{0} operator {1}({2}, {3})",
8062 TypeManager.CSharpName (return_type),
8063 GetName (OperatorType),
8064 param_types [0], param_types [1]);
8067 public override string[] ValidAttributeTargets {
8069 return attribute_targets;
8073 public void SetYields ()
8075 ModFlags |= Modifiers.METHOD_YIELDS;
8080 // This is used to compare method signatures
8082 struct MethodSignature {
8084 public Type RetType;
8085 public Type [] Parameters;
8088 /// This delegate is used to extract methods which have the
8089 /// same signature as the argument
8091 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8093 public MethodSignature (string name, Type ret_type, Type [] parameters)
8098 if (parameters == null)
8099 Parameters = TypeManager.NoTypes;
8101 Parameters = parameters;
8104 public override string ToString ()
8107 if (Parameters.Length != 0){
8108 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8109 for (int i = 0; i < Parameters.Length; i++){
8110 sb.Append (Parameters [i]);
8111 if (i+1 < Parameters.Length)
8114 pars = sb.ToString ();
8117 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8120 public override int GetHashCode ()
8122 return Name.GetHashCode ();
8125 public override bool Equals (Object o)
8127 MethodSignature other = (MethodSignature) o;
8129 if (other.Name != Name)
8132 if (other.RetType != RetType)
8135 if (Parameters == null){
8136 if (other.Parameters == null)
8141 if (other.Parameters == null)
8144 int c = Parameters.Length;
8145 if (other.Parameters.Length != c)
8148 for (int i = 0; i < c; i++)
8149 if (other.Parameters [i] != Parameters [i])
8155 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8157 MethodSignature sig = (MethodSignature) filter_criteria;
8159 if (m.Name != sig.Name)
8163 MethodInfo mi = m as MethodInfo;
8164 PropertyInfo pi = m as PropertyInfo;
8167 ReturnType = mi.ReturnType;
8168 else if (pi != null)
8169 ReturnType = pi.PropertyType;
8174 // we use sig.RetType == null to mean `do not check the
8175 // method return value.
8177 if (sig.RetType != null)
8178 if (ReturnType != sig.RetType)
8183 args = TypeManager.GetArgumentTypes (mi);
8185 args = TypeManager.GetArgumentTypes (pi);
8186 Type [] sigp = sig.Parameters;
8188 if (args.Length != sigp.Length)
8191 for (int i = args.Length; i > 0; ){
8193 if (args [i] != sigp [i])