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 protected class CircularDepException: Exception
64 public TypeContainer Container;
65 public CircularDepException (TypeContainer tc)
71 public class MemberCoreArrayList: ArrayList
74 /// Defines the MemberCore objects that are in this array
76 public virtual void DefineContainerMembers ()
78 foreach (MemberCore mc in this) {
83 public virtual void Emit ()
85 foreach (MemberCore mc in this)
90 public class MethodArrayList: MemberCoreArrayList
98 CachedMethods cached_method;
99 TypeContainer container;
101 public MethodArrayList (TypeContainer container)
103 this.container = container;
107 /// Method container contains Equals method
109 public bool HasEquals {
111 cached_method |= CachedMethods.Equals;
115 return (cached_method & CachedMethods.Equals) != 0;
120 /// Method container contains GetHashCode method
122 public bool HasGetHashCode {
124 cached_method |= CachedMethods.GetHashCode;
128 return (cached_method & CachedMethods.GetHashCode) != 0;
132 public override void DefineContainerMembers ()
134 base.DefineContainerMembers ();
136 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
137 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
143 public sealed class IndexerArrayList: MemberCoreArrayList
146 /// The indexer name for this container
148 public string IndexerName = DefaultIndexerName;
150 bool seen_normal_indexers = false;
152 TypeContainer container;
154 public IndexerArrayList (TypeContainer container)
156 this.container = container;
160 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
161 /// class is consistent. Either it is `Item' or it is the name defined by all the
162 /// indexers with the `IndexerName' attribute.
164 /// Turns out that the IndexerNameAttribute is applied to each indexer,
165 /// but it is never emitted, instead a DefaultMember attribute is attached
168 public override void DefineContainerMembers()
170 base.DefineContainerMembers ();
172 string class_indexer_name = null;
175 // If there's both an explicit and an implicit interface implementation, the
176 // explicit one actually implements the interface while the other one is just
177 // a normal indexer. See bug #37714.
180 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
181 foreach (Indexer i in this) {
182 if (i.InterfaceType != null) {
183 if (seen_normal_indexers)
184 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
188 seen_normal_indexers = true;
190 if (class_indexer_name == null) {
191 class_indexer_name = i.ShortName;
195 if (i.ShortName != class_indexer_name)
196 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");
199 if (class_indexer_name != null)
200 IndexerName = class_indexer_name;
203 public override void Emit ()
207 if (!seen_normal_indexers)
210 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
211 container.TypeBuilder.SetCustomAttribute (cb);
215 public class OperatorArrayList: MemberCoreArrayList
217 TypeContainer container;
219 public OperatorArrayList (TypeContainer container)
221 this.container = container;
225 // Operator pair checking
230 public Type ret_type;
231 public Type type1, type2;
233 public Operator.OpType ot;
235 public OperatorEntry (int f, Operator o)
239 ret_type = o.OperatorMethod.ReturnType;
240 Type [] pt = o.OperatorMethod.ParameterTypes;
247 public override int GetHashCode ()
249 return ret_type.GetHashCode ();
252 public override bool Equals (object o)
254 OperatorEntry other = (OperatorEntry) o;
256 if (other.ret_type != ret_type)
258 if (other.type1 != type1)
260 if (other.type2 != type2)
267 // Checks that some operators come in pairs:
273 // They are matched based on the return type and the argument types
275 void CheckPairedOperators ()
277 Hashtable pairs = new Hashtable (null, null);
278 Operator true_op = null;
279 Operator false_op = null;
280 bool has_equality_or_inequality = false;
282 // Register all the operators we care about.
283 foreach (Operator op in this){
286 // Skip erroneous code.
287 if (op.OperatorMethod == null)
290 switch (op.OperatorType){
291 case Operator.OpType.Equality:
293 has_equality_or_inequality = true;
295 case Operator.OpType.Inequality:
297 has_equality_or_inequality = true;
300 case Operator.OpType.True:
303 case Operator.OpType.False:
307 case Operator.OpType.GreaterThan:
309 case Operator.OpType.LessThan:
312 case Operator.OpType.GreaterThanOrEqual:
314 case Operator.OpType.LessThanOrEqual:
320 OperatorEntry oe = new OperatorEntry (reg, op);
322 object o = pairs [oe];
326 oe = (OperatorEntry) o;
331 if (true_op != null){
332 if (false_op == null)
333 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
334 } else if (false_op != null)
335 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
338 // Look for the mistakes.
340 foreach (DictionaryEntry de in pairs){
341 OperatorEntry oe = (OperatorEntry) de.Key;
348 case Operator.OpType.Equality:
351 case Operator.OpType.Inequality:
354 case Operator.OpType.GreaterThan:
357 case Operator.OpType.LessThan:
360 case Operator.OpType.GreaterThanOrEqual:
363 case Operator.OpType.LessThanOrEqual:
367 Report.Error (216, oe.op.Location,
368 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
371 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
372 if (container.Methods == null || !container.Methods.HasEquals)
373 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
375 if (container.Methods == null || !container.Methods.HasGetHashCode)
376 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
380 public override void DefineContainerMembers ()
382 base.DefineContainerMembers ();
383 CheckPairedOperators ();
388 // Whether this is a struct, class or interface
389 public readonly Kind Kind;
391 // Holds a list of classes and structures
394 // Holds the list of properties
395 MemberCoreArrayList properties;
397 // Holds the list of enumerations
398 MemberCoreArrayList enums;
400 // Holds the list of delegates
401 MemberCoreArrayList delegates;
403 // Holds the list of constructors
404 protected MemberCoreArrayList instance_constructors;
406 // Holds the list of fields
407 MemberCoreArrayList fields;
409 // Holds a list of fields that have initializers
410 protected ArrayList initialized_fields;
412 // Holds a list of static fields that have initializers
413 protected ArrayList initialized_static_fields;
415 // Holds the list of constants
416 MemberCoreArrayList constants;
419 MemberCoreArrayList interfaces;
421 // Holds the methods.
422 MethodArrayList methods;
425 protected MemberCoreArrayList events;
427 // Holds the indexers
428 IndexerArrayList indexers;
430 // Holds the operators
431 MemberCoreArrayList operators;
433 // Holds the iterators
436 // Holds the parts of a partial class;
440 // Pointers to the default constructor and the default static constructor
442 protected Constructor default_constructor;
443 protected Constructor default_static_constructor;
446 // Whether we have at least one non-static field
448 bool have_nonstatic_fields = false;
451 // This one is computed after we can distinguish interfaces
452 // from classes from the arraylist `type_bases'
454 string base_class_name;
457 ArrayList type_bases;
459 bool members_defined;
460 bool members_defined_ok;
462 // The interfaces we implement.
463 protected Type[] ifaces;
464 protected Type ptype;
466 // The base member cache and our member cache
467 MemberCache base_cache;
468 MemberCache member_cache;
470 public const string DefaultIndexerName = "Item";
474 // This is used to catch recursive definitions in declarations.
475 protected bool InTransit;
477 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
478 Attributes attrs, Kind kind, Location l)
479 : base (ns, parent, name, attrs, l)
481 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
482 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
486 types = new ArrayList ();
488 base_class_name = null;
491 public bool AddToMemberContainer (MemberCore symbol)
493 return AddToContainer (symbol, symbol.Name);
496 bool AddToTypeContainer (DeclSpace ds)
498 // Parent == null ==> this == RootContext.Tree.Types
499 return AddToContainer (ds, (Parent == null) ? ds.Name : ds.Basename);
502 public void AddConstant (Const constant)
504 if (!AddToMemberContainer (constant))
507 if (constants == null)
508 constants = new MemberCoreArrayList ();
510 constants.Add (constant);
513 public void AddEnum (Mono.CSharp.Enum e)
515 if (!AddToTypeContainer (e))
519 enums = new MemberCoreArrayList ();
524 public void AddClassOrStruct (TypeContainer c)
526 if (!AddToTypeContainer (c))
532 public void AddDelegate (Delegate d)
534 if (!AddToTypeContainer (d))
537 if (delegates == null)
538 delegates = new MemberCoreArrayList ();
543 public void AddMethod (Method method)
545 if (!AddToMemberContainer (method))
549 methods = new MethodArrayList (this);
551 if (method.MemberName.Left != null)
552 methods.Insert (0, method);
554 methods.Add (method);
557 public void AddConstructor (Constructor c)
559 if (c.Name != MemberName.Name) {
560 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
563 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
566 if (default_static_constructor != null) {
567 Report.SymbolRelatedToPreviousError (default_static_constructor);
568 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
569 "called '{1}' with the same parameter types", Name, c.Name);
573 default_static_constructor = c;
576 if (default_constructor != null) {
577 Report.SymbolRelatedToPreviousError (default_constructor);
578 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
579 "called '{1}' with the same parameter types", Name, c.Name);
582 default_constructor = c;
585 if (instance_constructors == null)
586 instance_constructors = new MemberCoreArrayList ();
588 instance_constructors.Add (c);
592 public void AddInterface (TypeContainer iface)
594 if (!AddToTypeContainer (iface))
597 if (interfaces == null) {
598 interfaces = new MemberCoreArrayList ();
601 interfaces.Add (iface);
604 public void AddField (FieldMember field)
606 if (!AddToMemberContainer (field))
610 fields = new MemberCoreArrayList ();
614 if (field.HasInitializer){
615 if ((field.ModFlags & Modifiers.STATIC) != 0){
616 if (initialized_static_fields == null)
617 initialized_static_fields = new ArrayList ();
619 initialized_static_fields.Add (field);
622 if (initialized_fields == null)
623 initialized_fields = new ArrayList ();
625 initialized_fields.Add (field);
629 if ((field.ModFlags & Modifiers.STATIC) == 0)
630 have_nonstatic_fields = true;
633 public void AddProperty (Property prop)
635 if (!AddToMemberContainer (prop) ||
636 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
639 if (properties == null)
640 properties = new MemberCoreArrayList ();
642 if (prop.MemberName.Left != null)
643 properties.Insert (0, prop);
645 properties.Add (prop);
648 public void AddEvent (Event e)
650 if (!AddToMemberContainer (e))
653 if (e is EventProperty) {
654 if (!AddToMemberContainer (e.Add))
657 if (!AddToMemberContainer (e.Remove))
662 events = new MemberCoreArrayList ();
668 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
670 public void AddIndexer (Indexer i)
672 if (indexers == null)
673 indexers = new IndexerArrayList (this);
675 if (i.IsExplicitImpl)
676 indexers.Insert (0, i);
681 public void AddOperator (Operator op)
683 if (!AddToMemberContainer (op))
686 if (operators == null)
687 operators = new OperatorArrayList (this);
692 public void AddIterator (Iterator i)
694 if (iterators == null)
695 iterators = new ArrayList ();
700 public void AddType (TypeContainer tc)
705 public void AddPart (ClassPart part)
708 parts = new ArrayList ();
713 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
715 if (a.Type == TypeManager.default_member_type) {
716 if (Indexers != null) {
717 Report.Error (646, a.Location,
718 "Cannot specify the DefaultMember attribute on" +
719 " a type containing an indexer");
724 base.ApplyAttributeBuilder (a, cb);
727 public override AttributeTargets AttributeTargets {
731 return AttributeTargets.Class;
733 return AttributeTargets.Struct;
735 return AttributeTargets.Interface;
737 throw new NotSupportedException ();
742 public ArrayList Types {
748 public MethodArrayList Methods {
754 public ArrayList Constants {
760 public ArrayList Interfaces {
766 public ArrayList Iterators {
774 return base_class_name;
778 public ArrayList Bases {
788 public ArrayList Fields {
794 public ArrayList InstanceConstructors {
796 return instance_constructors;
800 public ArrayList Properties {
806 public ArrayList Events {
812 public ArrayList Enums {
818 public ArrayList Indexers {
824 public ArrayList Operators {
830 public ArrayList Delegates {
836 public ArrayList Parts {
842 protected override TypeAttributes TypeAttr {
844 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
848 public string IndexerName {
850 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
855 // Emits the instance field initializers
857 public virtual bool EmitFieldInitializers (EmitContext ec)
860 Expression instance_expr;
863 fields = initialized_static_fields;
864 instance_expr = null;
866 fields = initialized_fields;
867 instance_expr = new This (Location.Null).Resolve (ec);
873 foreach (Field f in fields){
874 Expression e = f.GetInitializerExpression (ec);
878 Location l = f.Location;
879 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
880 fe.InstanceExpression = instance_expr;
882 ExpressionStatement a = new Assign (fe, e, l);
884 a = a.ResolveStatement (ec);
888 Constant c = e as Constant;
890 if (c.IsDefaultValue)
894 a.EmitStatement (ec);
901 // Defines the default constructors
903 protected void DefineDefaultConstructor (bool is_static)
907 // The default constructor is public
908 // If the class is abstract, the default constructor is protected
909 // The default static constructor is private
911 int mods = Modifiers.PUBLIC;
913 mods = Modifiers.STATIC | Modifiers.PRIVATE;
914 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
915 mods = Modifiers.PROTECTED;
917 TypeContainer constructor_parent = this;
919 constructor_parent = (TypeContainer) Parts [0];
921 c = new Constructor (constructor_parent, MemberName.Name, mods,
922 Parameters.EmptyReadOnlyParameters,
923 new ConstructorBaseInitializer (
924 null, Parameters.EmptyReadOnlyParameters,
930 c.Block = new ToplevelBlock (null, Location);
935 /// The pending methods that need to be implemented
936 // (interfaces or abstract methods)
938 public PendingImplementation Pending;
940 public abstract PendingImplementation GetPendingImplementations ();
942 TypeExpr[] GetPartialBases (out TypeExpr base_class)
944 ArrayList ifaces = new ArrayList ();
947 Location base_loc = Location.Null;
949 foreach (ClassPart part in parts) {
950 TypeExpr new_base_class;
951 TypeExpr[] new_ifaces;
953 new_ifaces = part.GetClassBases (out new_base_class);
954 if (new_ifaces == null && base_type != null)
957 if ((base_class != null) && (new_base_class != null) &&
958 !base_class.Equals (new_base_class)) {
959 Report.Error (263, part.Location,
960 "Partial declarations of `{0}' must " +
961 "not specify different base classes",
964 if (!Location.IsNull (base_loc))
965 Report.LocationOfPreviousError (base_loc);
970 if ((base_class == null) && (new_base_class != null)) {
971 base_class = new_base_class;
972 base_loc = part.Location;
975 if (new_ifaces == null)
978 foreach (TypeExpr iface in new_ifaces) {
980 foreach (TypeExpr old_iface in ifaces) {
981 if (old_iface.Equals (iface)) {
992 TypeExpr[] retval = new TypeExpr [ifaces.Count];
993 ifaces.CopyTo (retval, 0);
997 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1001 int count = Bases.Count;
1002 int start = 0, i, j;
1004 if (Kind == Kind.Class){
1005 TypeExpr name = ResolveBaseTypeExpr (
1006 (Expression) Bases [0], false, Location);
1012 if (!name.IsInterface) {
1013 // base_class could be a class, struct, enum, delegate.
1014 // This is validated in GetClassBases.
1020 TypeExpr [] ifaces = new TypeExpr [count-start];
1022 for (i = start, j = 0; i < count; i++, j++){
1023 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1024 if (resolved == null) {
1028 ifaces [j] = resolved;
1035 /// This function computes the Base class and also the
1036 /// list of interfaces that the class or struct @c implements.
1038 /// The return value is an array (might be null) of
1039 /// interfaces implemented (as Types).
1041 /// The @base_class argument is set to the base object or null
1042 /// if this is `System.Object'.
1044 TypeExpr [] GetClassBases (out TypeExpr base_class)
1051 ifaces = GetPartialBases (out base_class);
1052 else if (Bases == null){
1056 ifaces = GetNormalBases (out base_class);
1061 if ((base_class != null) && (Kind == Kind.Class)){
1062 if (base_class is TypeParameterExpr){
1064 689, base_class.Location,
1065 "Type parameter `{0}' can not be used as a " +
1066 "base class or interface", base_class.Name);
1071 if (IsGeneric && base_class.Type.IsSubclassOf (TypeManager.attribute_type)){
1073 698, base_class.Location,
1074 "A generic type cannot derive from `{0}' " +
1075 "because it is an attribute class",
1081 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1082 Report.Error (1521, base_class.Location, "Invalid base type");
1086 if (base_class.IsSealed){
1087 Report.SymbolRelatedToPreviousError (base_class.Type);
1088 if (base_class.Type.IsAbstract) {
1089 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1091 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1096 if (!base_class.CanInheritFrom ()){
1097 Report.Error (644, Location,
1098 "`{0}' cannot inherit from special class `{1}'",
1099 Name, base_class.Name);
1103 if (!base_class.AsAccessible (this, ModFlags)) {
1104 Report.SymbolRelatedToPreviousError (base_class.Type);
1105 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1106 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1110 if (base_class != null)
1111 base_class_name = base_class.Name;
1116 int count = ifaces != null ? ifaces.Length : 0;
1118 for (i = 0; i < count; i++) {
1119 TypeExpr iface = (TypeExpr) ifaces [i];
1121 if (!iface.IsInterface) {
1122 if (Kind != Kind.Class) {
1123 // TODO: location of symbol related ....
1124 Error_TypeInListIsNotInterface (Location, iface.FullName);
1126 else if (base_class != null)
1127 Report.Error (1721, Location,
1128 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1131 Report.Error (1722, Location,
1132 "In Class `{0}', `{1}' is not " +
1133 "an interface, a base class must be listed first", Name, iface.Name);
1138 for (int x = 0; x < i; x++) {
1139 if (iface.Equals (ifaces [x])) {
1140 Report.Error (528, Location,
1141 "`{0}' is already listed in " +
1142 "interface list", iface.Name);
1147 if ((Kind == Kind.Interface) &&
1148 !iface.AsAccessible (Parent, ModFlags)) {
1149 Report.Error (61, Location,
1150 "Inconsistent accessibility: base " +
1151 "interface `{0}' is less accessible " +
1152 "than interface `{1}'", iface.Name,
1160 bool CheckGenericInterfaces (Type[] ifaces)
1162 ArrayList already_checked = new ArrayList ();
1164 for (int i = 0; i < ifaces.Length; i++) {
1165 Type iface = ifaces [i];
1166 foreach (Type t in already_checked) {
1170 Type[] infered = new Type [CountTypeParameters];
1171 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1176 "`{0}' cannot implement both `{1}' and `{2}' " +
1177 "because they may unify for some type " +
1178 "parameter substitutions",
1179 TypeManager.GetFullName (TypeBuilder),
1184 already_checked.Add (iface);
1192 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1194 Report.Error (527, loc, "'{0}': type in interface list is not an interface", type);
1198 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1200 public override TypeBuilder DefineType ()
1205 if (TypeBuilder != null)
1208 TypeAttributes type_attributes = TypeAttr;
1212 if (TypeManager.NamespaceClash (Name, Location)) {
1217 ModuleBuilder builder = CodeGen.Module.Builder;
1218 TypeBuilder = builder.DefineType (
1219 Name, type_attributes, null, null);
1221 TypeBuilder builder = Parent.TypeBuilder;
1222 if (builder == null) {
1227 TypeBuilder = builder.DefineNestedType (
1228 Basename, type_attributes, ptype, null);
1230 } catch (ArgumentException) {
1231 Report.RuntimeMissingSupport (Location, "static classes");
1236 TypeManager.AddUserType (Name, TypeBuilder, this);
1238 if (Parts != null) {
1240 foreach (ClassPart part in Parts) {
1241 part.TypeBuilder = TypeBuilder;
1243 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1244 part.ec.ContainerType = TypeBuilder;
1247 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1248 ec.ContainerType = TypeBuilder;
1251 Expression current_type = null;
1254 string[] param_names = new string [TypeParameters.Length];
1255 for (int i = 0; i < TypeParameters.Length; i++)
1256 param_names [i] = TypeParameters [i].Name;
1258 GenericTypeParameterBuilder[] gen_params;
1259 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1261 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1262 for (int i = offset; i < gen_params.Length; i++)
1263 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1265 if (Parts != null) {
1266 foreach (ClassPart part in Parts) {
1267 if (!part.DefineTypeParameters ()) {
1273 foreach (TypeParameter type_param in CurrentTypeParameters) {
1274 if (!type_param.Resolve (this)) {
1280 for (int i = offset; i < gen_params.Length; i++)
1281 CurrentTypeParameters [i - offset].DefineConstraints ();
1283 foreach (TypeParameter type_param in TypeParameters) {
1284 if (!type_param.DefineType (ec)) {
1290 current_type = new ConstructedType (
1291 TypeBuilder, TypeParameters, Location);
1295 if (!CheckConstraints (ec)) {
1300 TypeExpr[] iface_exprs = GetClassBases (out base_type);
1301 if (iface_exprs == null && base_type != null) {
1306 if (base_type == null) {
1307 if (Kind == Kind.Class){
1308 if (RootContext.StdLib)
1309 base_type = TypeManager.system_object_expr;
1310 else if (Name != "System.Object")
1311 base_type = TypeManager.system_object_expr;
1312 } else if (Kind == Kind.Struct){
1314 // If we are compiling our runtime,
1315 // and we are defining ValueType, then our
1316 // base is `System.Object'.
1318 if (!RootContext.StdLib && Name == "System.ValueType")
1319 base_type = TypeManager.system_object_expr;
1320 else if (Kind == Kind.Struct)
1321 base_type = TypeManager.system_valuetype_expr;
1325 if (base_type != null) {
1326 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1327 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1328 ptype = base_type.ResolveType (TypeResolveEmitContext);
1329 if (ptype == null) {
1334 ptype = base_type.Type;
1337 if (!CheckRecursiveDefinition ()) {
1343 TypeBuilder.SetParent (ptype);
1345 // add interfaces that were not added at type creation
1346 if (iface_exprs != null) {
1347 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1348 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1349 TypeResolveEmitContext.ContainerType = TypeBuilder;
1350 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1351 if (ifaces == null) {
1356 foreach (Type itype in ifaces)
1357 TypeBuilder.AddInterfaceImplementation (itype);
1359 if (!CheckGenericInterfaces (ifaces)) {
1364 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1368 foreach (TypeParameter type_param in TypeParameters)
1369 if (!type_param.CheckDependencies (ec)) {
1375 if (current_type != null) {
1376 current_type = current_type.ResolveAsTypeTerminal (ec);
1377 if (current_type == null) {
1382 CurrentType = current_type.Type;
1385 if (!(this is Iterator))
1386 RootContext.RegisterOrder (this);
1390 if (!DefineNestedTypes ()) {
1397 protected virtual bool CheckConstraints (EmitContext ec)
1402 protected virtual bool DefineNestedTypes ()
1404 if (Interfaces != null) {
1405 foreach (TypeContainer iface in Interfaces)
1406 if (iface.DefineType () == null)
1410 if (Types != null) {
1411 foreach (TypeContainer tc in Types)
1412 if (tc.DefineType () == null)
1416 if (Delegates != null) {
1417 foreach (Delegate d in Delegates)
1418 if (d.DefineType () == null)
1422 if (Enums != null) {
1423 foreach (Enum en in Enums)
1424 if (en.DefineType () == null)
1431 protected bool CheckRecursiveDefinition ()
1434 Report.Error (146, Location,
1435 "Class definition is circular: `{0}'",
1436 GetSignatureForError ());
1443 Type parent = ptype;
1444 if (parent != null) {
1445 if (parent.IsGenericInstance)
1446 parent = parent.GetGenericTypeDefinition ();
1448 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1449 if ((ptc != null) && !ptc.CheckRecursiveDefinition ())
1457 static void Error_KeywordNotAllowed (Location loc)
1459 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1463 /// Populates our TypeBuilder with fields and methods
1465 public override bool DefineMembers (TypeContainer container)
1467 if (members_defined)
1468 return members_defined_ok;
1470 members_defined_ok = DoDefineMembers ();
1471 members_defined = true;
1473 return members_defined_ok;
1476 protected virtual bool DoDefineMembers ()
1479 if ((ModFlags & Modifiers.NEW) != 0)
1480 Error_KeywordNotAllowed (Location);
1482 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1483 if (conflict_symbol == null) {
1484 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1485 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1487 if ((ModFlags & Modifiers.NEW) == 0) {
1488 Report.SymbolRelatedToPreviousError (conflict_symbol);
1489 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1494 DefineContainerMembers (constants);
1495 DefineContainerMembers (fields);
1497 if ((Kind == Kind.Class) && !(this is ClassPart)){
1498 if ((instance_constructors == null) &&
1499 !(this is StaticClass)) {
1500 if (default_constructor == null)
1501 DefineDefaultConstructor (false);
1504 if (initialized_static_fields != null &&
1505 default_static_constructor == null)
1506 DefineDefaultConstructor (true);
1509 if (Kind == Kind.Struct){
1511 // Structs can not have initialized instance
1514 if (initialized_static_fields != null &&
1515 default_static_constructor == null)
1516 DefineDefaultConstructor (true);
1518 if (initialized_fields != null)
1519 ReportStructInitializedInstanceError ();
1522 Pending = GetPendingImplementations ();
1524 if (parts != null) {
1525 foreach (ClassPart part in parts) {
1526 if (!part.DefineMembers (this))
1532 // Constructors are not in the defined_names array
1534 DefineContainerMembers (instance_constructors);
1536 if (default_static_constructor != null)
1537 default_static_constructor.Define ();
1539 DefineContainerMembers (properties);
1540 DefineContainerMembers (events);
1541 DefineContainerMembers (indexers);
1542 DefineContainerMembers (methods);
1543 DefineContainerMembers (operators);
1544 DefineContainerMembers (enums);
1545 DefineContainerMembers (delegates);
1547 if (CurrentType != null) {
1548 GenericType = CurrentType;
1550 ec.ContainerType = GenericType;
1555 if (!(this is ClassPart))
1556 member_cache = new MemberCache (this);
1559 if (parts != null) {
1560 foreach (ClassPart part in parts)
1561 part.member_cache = member_cache;
1564 if (iterators != null) {
1565 foreach (Iterator iterator in iterators) {
1566 if (iterator.DefineType () == null)
1570 foreach (Iterator iterator in iterators) {
1571 if (!iterator.DefineMembers (this))
1579 void ReportStructInitializedInstanceError ()
1581 string n = TypeBuilder.FullName;
1583 foreach (Field f in initialized_fields){
1586 "`" + n + "." + f.Name + "': can not have " +
1587 "instance field initializers in structs");
1591 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1594 mcal.DefineContainerMembers ();
1597 public override bool Define ()
1599 if (parts != null) {
1600 foreach (ClassPart part in parts) {
1601 if (!part.Define ())
1609 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1611 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1615 /// This function is based by a delegate to the FindMembers routine
1617 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1623 /// This filter is used by FindMembers, and we just keep
1624 /// a global for the filter to `AlwaysAccept'
1626 static MemberFilter accepting_filter;
1629 static TypeContainer ()
1631 accepting_filter = new MemberFilter (AlwaysAccept);
1634 public MethodInfo[] GetMethods ()
1636 ArrayList members = new ArrayList ();
1638 DefineMembers (null);
1640 if (methods != null) {
1641 int len = methods.Count;
1642 for (int i = 0; i < len; i++) {
1643 Method m = (Method) methods [i];
1645 members.Add (m.MethodBuilder);
1649 if (operators != null) {
1650 int len = operators.Count;
1651 for (int i = 0; i < len; i++) {
1652 Operator o = (Operator) operators [i];
1654 members.Add (o.OperatorMethodBuilder);
1658 if (properties != null) {
1659 int len = properties.Count;
1660 for (int i = 0; i < len; i++) {
1661 Property p = (Property) properties [i];
1663 if (p.GetBuilder != null)
1664 members.Add (p.GetBuilder);
1665 if (p.SetBuilder != null)
1666 members.Add (p.SetBuilder);
1670 if (indexers != null) {
1671 int len = indexers.Count;
1672 for (int i = 0; i < len; i++) {
1673 Indexer ix = (Indexer) indexers [i];
1675 if (ix.GetBuilder != null)
1676 members.Add (ix.GetBuilder);
1677 if (ix.SetBuilder != null)
1678 members.Add (ix.SetBuilder);
1682 if (events != null) {
1683 int len = events.Count;
1684 for (int i = 0; i < len; i++) {
1685 Event e = (Event) events [i];
1687 if (e.AddBuilder != null)
1688 members.Add (e.AddBuilder);
1689 if (e.RemoveBuilder != null)
1690 members.Add (e.RemoveBuilder);
1694 MethodInfo[] retMethods = new MethodInfo [members.Count];
1695 members.CopyTo (retMethods, 0);
1699 // Indicated whether container has StructLayout attribute set Explicit
1700 public virtual bool HasExplicitLayout {
1706 public override Type FindNestedType (string name)
1708 ArrayList [] lists = { types, enums, delegates, interfaces };
1710 for (int j = 0; j < lists.Length; ++j) {
1711 ArrayList list = lists [j];
1715 int len = list.Count;
1716 for (int i = 0; i < len; ++i) {
1717 DeclSpace ds = (DeclSpace) list [i];
1718 if (ds.Basename == name) {
1720 return ds.TypeBuilder;
1728 private void FindMembers_NestedTypes (int modflags,
1729 BindingFlags bf, MemberFilter filter, object criteria,
1730 ref ArrayList members)
1732 ArrayList [] lists = { types, enums, delegates, interfaces };
1734 for (int j = 0; j < lists.Length; ++j) {
1735 ArrayList list = lists [j];
1739 int len = list.Count;
1740 for (int i = 0; i < len; i++) {
1741 DeclSpace ds = (DeclSpace) list [i];
1743 if ((ds.ModFlags & modflags) == 0)
1746 TypeBuilder tb = ds.TypeBuilder;
1748 if (!(criteria is string) || ds.Basename.Equals (criteria))
1749 tb = ds.DefineType ();
1752 if (tb != null && (filter (tb, criteria) == true)) {
1753 if (members == null)
1754 members = new ArrayList ();
1763 /// This method returns the members of this type just like Type.FindMembers would
1764 /// Only, we need to use this for types which are _being_ defined because MS'
1765 /// implementation can't take care of that.
1768 // FIXME: return an empty static array instead of null, that cleans up
1769 // some code and is consistent with some coding conventions I just found
1773 // Notice that in various cases we check if our field is non-null,
1774 // something that would normally mean that there was a bug elsewhere.
1776 // The problem happens while we are defining p-invoke methods, as those
1777 // will trigger a FindMembers, but this happens before things are defined
1779 // Since the whole process is a no-op, it is fine to check for null here.
1781 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1782 MemberFilter filter, object criteria)
1784 ArrayList members = null;
1787 if ((bf & BindingFlags.Public) != 0)
1788 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1790 if ((bf & BindingFlags.NonPublic) != 0)
1791 modflags |= Modifiers.PRIVATE;
1793 int static_mask = 0, static_flags = 0;
1794 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1795 case BindingFlags.Static:
1796 static_mask = static_flags = Modifiers.STATIC;
1799 case BindingFlags.Instance:
1800 static_mask = Modifiers.STATIC;
1805 static_mask = static_flags = 0;
1809 Timer.StartTimer (TimerType.TcFindMembers);
1812 filter = accepting_filter;
1814 if ((mt & MemberTypes.Field) != 0) {
1815 if (fields != null) {
1816 int len = fields.Count;
1817 for (int i = 0; i < len; i++) {
1818 FieldMember f = (FieldMember) fields [i];
1820 if ((f.ModFlags & modflags) == 0)
1822 if ((f.ModFlags & static_mask) != static_flags)
1825 FieldBuilder fb = f.FieldBuilder;
1826 if (fb != null && filter (fb, criteria) == true) {
1827 if (members == null)
1828 members = new ArrayList ();
1835 if (constants != null) {
1836 int len = constants.Count;
1837 for (int i = 0; i < len; i++) {
1838 Const con = (Const) constants [i];
1840 if ((con.ModFlags & modflags) == 0)
1842 if ((con.ModFlags & static_mask) != static_flags)
1845 FieldBuilder fb = con.FieldBuilder;
1848 fb = con.FieldBuilder;
1850 if (fb != null && filter (fb, criteria) == true) {
1851 if (members == null)
1852 members = new ArrayList ();
1860 if ((mt & MemberTypes.Method) != 0) {
1861 if (methods != null) {
1862 int len = methods.Count;
1863 for (int i = 0; i < len; i++) {
1864 Method m = (Method) methods [i];
1866 if ((m.ModFlags & modflags) == 0)
1868 if ((m.ModFlags & static_mask) != static_flags)
1871 MethodBuilder mb = m.MethodBuilder;
1873 if (mb != null && filter (mb, criteria) == true) {
1874 if (members == null)
1875 members = new ArrayList ();
1882 if (operators != null) {
1883 int len = operators.Count;
1884 for (int i = 0; i < len; i++) {
1885 Operator o = (Operator) operators [i];
1887 if ((o.ModFlags & modflags) == 0)
1889 if ((o.ModFlags & static_mask) != static_flags)
1892 MethodBuilder ob = o.OperatorMethodBuilder;
1893 if (ob != null && filter (ob, criteria) == true) {
1894 if (members == null)
1895 members = new ArrayList ();
1902 if (properties != null) {
1903 int len = properties.Count;
1904 for (int i = 0; i < len; i++) {
1905 Property p = (Property) properties [i];
1907 if ((p.ModFlags & modflags) == 0)
1909 if ((p.ModFlags & static_mask) != static_flags)
1915 if (b != null && filter (b, criteria) == true) {
1916 if (members == null)
1917 members = new ArrayList ();
1923 if (b != null && filter (b, criteria) == true) {
1924 if (members == null)
1925 members = new ArrayList ();
1932 if (indexers != null) {
1933 int len = indexers.Count;
1934 for (int i = 0; i < len; i++) {
1935 Indexer ix = (Indexer) indexers [i];
1937 if ((ix.ModFlags & modflags) == 0)
1939 if ((ix.ModFlags & static_mask) != static_flags)
1945 if (b != null && filter (b, criteria) == true) {
1946 if (members == null)
1947 members = new ArrayList ();
1953 if (b != null && filter (b, criteria) == true) {
1954 if (members == null)
1955 members = new ArrayList ();
1963 if ((mt & MemberTypes.Event) != 0) {
1964 if (events != null) {
1965 int len = events.Count;
1966 for (int i = 0; i < len; i++) {
1967 Event e = (Event) events [i];
1969 if ((e.ModFlags & modflags) == 0)
1971 if ((e.ModFlags & static_mask) != static_flags)
1974 MemberInfo eb = e.EventBuilder;
1975 if (eb != null && filter (eb, criteria) == true) {
1976 if (members == null)
1977 members = new ArrayList ();
1979 members.Add (e.EventBuilder);
1985 if ((mt & MemberTypes.Property) != 0){
1986 if (properties != null) {
1987 int len = properties.Count;
1988 for (int i = 0; i < len; i++) {
1989 Property p = (Property) properties [i];
1991 if ((p.ModFlags & modflags) == 0)
1993 if ((p.ModFlags & static_mask) != static_flags)
1996 MemberInfo pb = p.PropertyBuilder;
1997 if (pb != null && filter (pb, criteria) == true) {
1998 if (members == null)
1999 members = new ArrayList ();
2001 members.Add (p.PropertyBuilder);
2006 if (indexers != null) {
2007 int len = indexers.Count;
2008 for (int i = 0; i < len; i++) {
2009 Indexer ix = (Indexer) indexers [i];
2011 if ((ix.ModFlags & modflags) == 0)
2013 if ((ix.ModFlags & static_mask) != static_flags)
2016 MemberInfo ib = ix.PropertyBuilder;
2017 if (ib != null && filter (ib, criteria) == true) {
2018 if (members == null)
2019 members = new ArrayList ();
2021 members.Add (ix.PropertyBuilder);
2027 if ((mt & MemberTypes.NestedType) != 0)
2028 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2030 if ((mt & MemberTypes.Constructor) != 0){
2031 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2032 int len = instance_constructors.Count;
2033 for (int i = 0; i < len; i++) {
2034 Constructor c = (Constructor) instance_constructors [i];
2036 ConstructorBuilder cb = c.ConstructorBuilder;
2037 if (cb != null && filter (cb, criteria) == true) {
2038 if (members == null)
2039 members = new ArrayList ();
2046 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2047 ConstructorBuilder cb =
2048 default_static_constructor.ConstructorBuilder;
2050 if (cb != null && filter (cb, criteria) == true) {
2051 if (members == null)
2052 members = new ArrayList ();
2060 // Lookup members in base if requested.
2062 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2063 if (TypeBuilder.BaseType != null) {
2064 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2065 if (list.Count > 0) {
2066 if (members == null)
2067 members = new ArrayList ();
2069 members.AddRange (list);
2075 Timer.StopTimer (TimerType.TcFindMembers);
2077 if (members == null)
2078 return MemberList.Empty;
2080 return new MemberList (members);
2083 public override MemberCache MemberCache {
2085 return member_cache;
2089 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2090 MemberFilter filter, object criteria)
2092 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2095 return ds.FindMembers (mt, bf, filter, criteria);
2097 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2101 // FindMethods will look for methods not only in the type `t', but in
2102 // any interfaces implemented by the type.
2104 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2105 MemberFilter filter, object criteria)
2111 /// Emits the values for the constants
2113 public void EmitConstants ()
2115 if (constants != null)
2116 foreach (Const con in constants)
2121 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2126 foreach (MemberCore mc in al) {
2127 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2131 Report.Warning (169, mc.Location, "The private {0} '{1}' is never used", member_type, mc.GetSignatureForError ());
2136 public virtual void VerifyMembers ()
2139 // Check for internal or private fields that were never assigned
2141 if (RootContext.WarningLevel >= 3) {
2142 CheckMemberUsage (properties, "property");
2143 CheckMemberUsage (methods, "method");
2144 CheckMemberUsage (constants, "constant");
2146 if (fields != null){
2147 foreach (FieldMember f in fields) {
2148 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2152 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2157 // Only report 649 on level 4
2159 if (RootContext.WarningLevel < 4)
2162 if ((f.status & Field.Status.ASSIGNED) != 0)
2165 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2172 /// Emits the code, this step is performed after all
2173 /// the types, enumerations, constructors
2175 public void EmitType ()
2177 if (OptAttributes != null)
2178 OptAttributes.Emit (ec, this);
2181 // Structs with no fields need to have at least one byte.
2182 // The right thing would be to set the PackingSize in a DefineType
2183 // but there are no functions that allow interfaces *and* the size to
2187 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
2188 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2189 FieldAttributes.Private);
2191 if (HasExplicitLayout){
2192 object [] ctor_args = new object [1];
2195 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2196 TypeManager.field_offset_attribute_ctor, ctor_args);
2197 fb.SetCustomAttribute (cba);
2203 if (instance_constructors != null) {
2204 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2205 bool has_compliant_args = false;
2207 foreach (Constructor c in instance_constructors) {
2210 if (has_compliant_args)
2213 has_compliant_args = c.HasCompliantArgs;
2215 if (!has_compliant_args)
2216 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2218 foreach (Constructor c in instance_constructors)
2225 if (default_static_constructor != null)
2226 default_static_constructor.Emit ();
2228 if (methods != null)
2229 foreach (Method m in methods)
2232 if (operators != null)
2233 foreach (Operator o in operators)
2236 if (properties != null)
2237 foreach (Property p in properties)
2240 if (indexers != null){
2245 foreach (FieldMember f in fields)
2248 if (events != null){
2249 foreach (Event e in Events)
2253 if (delegates != null) {
2254 foreach (Delegate d in Delegates) {
2259 if (enums != null) {
2260 foreach (Enum e in enums) {
2265 if (parts != null) {
2266 foreach (ClassPart part in parts)
2270 if ((Pending != null) && !(this is ClassPart))
2271 if (Pending.VerifyPendingMethods ())
2274 if (iterators != null)
2275 foreach (Iterator iterator in iterators)
2276 iterator.EmitType ();
2278 // if (types != null)
2279 // foreach (TypeContainer tc in types)
2283 public override void CloseType ()
2285 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2289 caching_flags |= Flags.CloseTypeCreated;
2290 TypeBuilder.CreateType ();
2291 } catch (TypeLoadException){
2293 // This is fine, the code still created the type
2295 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2296 // Console.WriteLine (e.Message);
2298 Console.WriteLine ("In type: " + Name);
2303 foreach (Enum en in Enums)
2307 foreach (TypeContainer tc in Types)
2308 if (tc.Kind == Kind.Struct)
2311 foreach (TypeContainer tc in Types)
2312 if (tc.Kind != Kind.Struct)
2316 if (Delegates != null)
2317 foreach (Delegate d in Delegates)
2320 if (Iterators != null)
2321 foreach (Iterator i in Iterators)
2329 initialized_fields = null;
2330 initialized_static_fields = null;
2339 default_constructor = null;
2340 default_static_constructor = null;
2342 OptAttributes = null;
2345 member_cache = null;
2348 // TODO: make it obsolete and use GetSignatureForError
2349 public string MakeName (string n)
2351 return "`" + Name + "." + n + "'";
2355 // Performs the validation on a Method's modifiers (properties have
2356 // the same properties).
2358 public bool MethodModifiersValid (MemberCore mc)
2360 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2361 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2362 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2364 int flags = mc.ModFlags;
2367 // At most one of static, virtual or override
2369 if ((flags & Modifiers.STATIC) != 0){
2370 if ((flags & vao) != 0){
2371 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2372 GetSignatureForError ());
2377 if (Kind == Kind.Struct){
2378 if ((flags & va) != 0){
2379 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2384 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2385 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2390 // If the declaration includes the abstract modifier, then the
2391 // declaration does not include static, virtual or extern
2393 if ((flags & Modifiers.ABSTRACT) != 0){
2394 if ((flags & Modifiers.EXTERN) != 0){
2396 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2400 if ((flags & Modifiers.SEALED) != 0) {
2401 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2405 if ((flags & Modifiers.VIRTUAL) != 0){
2406 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2410 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2411 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2416 if ((flags & Modifiers.PRIVATE) != 0){
2417 if ((flags & vao) != 0){
2418 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2423 if ((flags & Modifiers.SEALED) != 0){
2424 if ((flags & Modifiers.OVERRIDE) == 0){
2425 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2433 public bool UserDefinedStaticConstructor {
2435 return default_static_constructor != null;
2439 public Constructor DefaultStaticConstructor {
2440 get { return default_static_constructor; }
2443 protected override bool VerifyClsCompliance (DeclSpace ds)
2445 if (!base.VerifyClsCompliance (ds))
2450 Type base_type = TypeBuilder.BaseType;
2451 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2452 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2455 if (!Parent.IsClsCompliaceRequired (ds)) {
2456 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2457 GetSignatureForError (), Parent.GetSignatureForError ());
2464 /// Checks whether container name is CLS Compliant
2466 void VerifyClsName ()
2468 Hashtable base_members = base_cache == null ?
2470 base_cache.GetPublicMembers ();
2471 Hashtable this_members = new Hashtable ();
2473 foreach (DictionaryEntry entry in defined_names) {
2474 MemberCore mc = (MemberCore)entry.Value;
2475 if (!mc.IsClsCompliaceRequired (this))
2478 string name = (string)entry.Key;
2479 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2481 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2482 object found = base_members [lcase];
2483 if (found == null) {
2484 found = this_members [lcase];
2485 if (found == null) {
2486 this_members.Add (lcase, mc);
2491 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2494 if (found is MemberInfo) {
2495 if (basename == ((MemberInfo)found).Name)
2497 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2499 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2501 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2507 /// Performs checks for an explicit interface implementation. First it
2508 /// checks whether the `interface_type' is a base inteface implementation.
2509 /// Then it checks whether `name' exists in the interface type.
2511 public virtual bool VerifyImplements (Type interface_type, string full,
2512 string name, Location loc)
2516 if (ifaces != null){
2517 foreach (Type t in ifaces){
2518 if (t == interface_type){
2526 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2527 full, interface_type.FullName);
2534 protected override void VerifyObsoleteAttribute()
2536 CheckUsageOfObsoleteAttribute (TypeBuilder.BaseType);
2541 foreach (Type iface in ifaces) {
2542 CheckUsageOfObsoleteAttribute (iface);
2550 string IMemberContainer.Name {
2556 Type IMemberContainer.Type {
2562 MemberCache IMemberContainer.MemberCache {
2564 return member_cache;
2568 bool IMemberContainer.IsInterface {
2570 return Kind == Kind.Interface;
2574 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2576 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2578 if (GenericType != null)
2579 return TypeManager.FindMembers (GenericType, mt, new_bf,
2582 return FindMembers (mt, new_bf, null, null);
2586 // Generates xml doc comments (if any), and if required,
2587 // handle warning report.
2589 internal override void GenerateDocComment (DeclSpace ds)
2591 DocUtil.GenerateTypeDocComment (this, ds);
2594 public override string DocCommentHeader {
2595 get { return "T:"; }
2598 public virtual MemberCache BaseCache {
2600 if (base_cache != null)
2602 if (TypeBuilder.BaseType != null)
2603 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2604 if (TypeBuilder.IsInterface)
2605 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2612 public class PartialContainer : TypeContainer {
2614 public readonly Namespace Namespace;
2615 public readonly int OriginalModFlags;
2616 public readonly int AllowedModifiers;
2617 public readonly TypeAttributes DefaultTypeAttributes;
2619 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2620 MemberName member_name, int mod_flags, Kind kind,
2623 PartialContainer pc;
2624 DeclSpace ds = RootContext.Tree.GetDecl (member_name);
2626 pc = ds as PartialContainer;
2630 260, ds.Location, "Missing partial modifier " +
2631 "on declaration of type `{0}'; another " +
2632 "partial implementation of this type exists",
2633 member_name.GetTypeName());
2635 Report.LocationOfPreviousError (loc);
2639 if (pc.Kind != kind) {
2641 261, loc, "Partial declarations of `{0}' " +
2642 "must be all classes, all structs or " +
2643 "all interfaces", member_name.GetTypeName ());
2647 if (pc.OriginalModFlags != mod_flags) {
2649 262, loc, "Partial declarations of `{0}' " +
2650 "have conflicting accessibility modifiers",
2651 member_name.GetTypeName ());
2656 if (pc.CountTypeParameters != member_name.CountTypeArguments) {
2658 264, loc, "Partial declarations of `{0}' " +
2659 "must have the same type parameter names in " +
2660 "the same order", member_name.GetTypeName ());
2664 string[] pc_names = pc.MemberName.TypeArguments.GetDeclarations ();
2665 string[] names = member_name.TypeArguments.GetDeclarations ();
2667 for (int i = 0; i < pc.CountTypeParameters; i++) {
2668 if (pc_names [i] == names [i])
2672 264, loc, "Partial declarations of `{0}' " +
2673 "must have the same type parameter names in " +
2674 "the same order", member_name.GetTypeName ());
2682 if (parent is ClassPart)
2683 parent = ((ClassPart) parent).PartialContainer;
2685 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2686 RootContext.Tree.RecordDecl (member_name, pc);
2688 if (kind == Kind.Interface)
2689 parent.AddInterface (pc);
2690 else if (kind == Kind.Class || kind == Kind.Struct)
2691 parent.AddClassOrStruct (pc);
2693 throw new InvalidOperationException ();
2695 // This is needed to define our type parameters; we define the constraints later.
2696 pc.SetParameterInfo (null);
2700 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2701 MemberName name, int mod, Attributes attrs,
2702 Kind kind, Location loc)
2704 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2706 // An error occured; create a dummy container, but don't
2708 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2711 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2716 protected PartialContainer (Namespace ns, TypeContainer parent,
2717 MemberName name, int mod, Kind kind, Location l)
2718 : base (null, parent, name, null, kind, l)
2720 this.Namespace = ns;
2724 AllowedModifiers = Class.AllowedModifiers;
2725 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2729 AllowedModifiers = Struct.AllowedModifiers;
2730 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2733 case Kind.Interface:
2734 AllowedModifiers = Interface.AllowedModifiers;
2735 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2739 throw new InvalidOperationException ();
2743 if (parent.Parent == null)
2744 accmods = Modifiers.INTERNAL;
2746 accmods = Modifiers.PRIVATE;
2748 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2749 this.OriginalModFlags = mod;
2752 public override PendingImplementation GetPendingImplementations ()
2754 return PendingImplementation.GetPendingImplementations (this);
2757 protected override TypeAttributes TypeAttr {
2759 return base.TypeAttr | DefaultTypeAttributes;
2764 public class ClassPart : TypeContainer, IMemberContainer {
2765 public readonly PartialContainer PartialContainer;
2766 public readonly bool IsPartial;
2768 Constraints[] constraints;
2770 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2771 int mod, Attributes attrs, Kind kind, Location l)
2772 : base (ns, parent, pc.MemberName, attrs, kind, l)
2774 this.PartialContainer = pc;
2775 this.IsPartial = true;
2778 if (parent == null || parent == RootContext.Tree.Types)
2779 accmods = Modifiers.INTERNAL;
2781 accmods = Modifiers.PRIVATE;
2783 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2786 constraints = new Constraints [pc.CountCurrentTypeParameters];
2789 public override PendingImplementation GetPendingImplementations ()
2791 return PartialContainer.Pending;
2794 public override bool VerifyImplements (Type interface_type, string full,
2795 string name, Location loc)
2797 return PartialContainer.VerifyImplements (
2798 interface_type, full, name, loc);
2801 public override void SetParameterInfo (ArrayList constraints_list)
2803 if (constraints_list == null)
2806 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2807 for (int i = 0; i < constraints.Length; i++) {
2808 foreach (Constraints constraint in constraints_list) {
2809 if (constraint.TypeParameter == current_params [i].Name) {
2810 constraints [i] = constraint;
2817 public bool DefineTypeParameters ()
2819 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2821 for (int i = 0; i < current_params.Length; i++) {
2822 Constraints new_constraints = constraints [i];
2823 if (new_constraints == null)
2826 if (!current_params [i].UpdateConstraints (ec, new_constraints)) {
2827 Report.Error (265, Location, "Partial declarations of `{0}' have " +
2828 "inconsistent constraints for type parameter `{1}'.",
2829 MemberName.GetTypeName (), current_params [i].Name);
2834 for (int i = 0; i < current_params.Length; i++) {
2835 if (!current_params [i].Resolve (this))
2839 for (int i = 0; i < current_params.Length; i++)
2840 current_params [i].DefineConstraints ();
2842 foreach (TypeParameter type_param in PartialContainer.TypeParameters) {
2843 if (!type_param.DefineType (ec))
2850 public override bool EmitFieldInitializers (EmitContext ec)
2852 return PartialContainer.EmitFieldInitializers (ec);
2855 public override Type FindNestedType (string name)
2857 return PartialContainer.FindNestedType (name);
2860 public override MemberCache BaseCache {
2862 return PartialContainer.BaseCache;
2867 public abstract class ClassOrStruct : TypeContainer {
2868 bool has_explicit_layout = false;
2869 ListDictionary declarative_security;
2871 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2872 MemberName name, Attributes attrs, Kind kind,
2874 : base (ns, parent, name, attrs, kind, l)
2878 public override PendingImplementation GetPendingImplementations ()
2880 return PendingImplementation.GetPendingImplementations (this);
2883 public override bool HasExplicitLayout {
2885 return has_explicit_layout;
2889 public override void VerifyMembers ()
2891 base.VerifyMembers ();
2893 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2894 foreach (Event e in events){
2896 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2901 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2903 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2904 if (declarative_security == null)
2905 declarative_security = new ListDictionary ();
2907 a.ExtractSecurityPermissionSet (declarative_security);
2911 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2912 has_explicit_layout = true;
2914 base.ApplyAttributeBuilder (a, cb);
2917 public override void Emit()
2921 if (declarative_security != null) {
2922 foreach (DictionaryEntry de in declarative_security) {
2923 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2930 /// Class handles static classes declaration
2932 public sealed class StaticClass: Class {
2933 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2934 Attributes attrs, Location l)
2935 : base (ns, parent, name, mod, attrs, l)
2937 if (RootContext.Version == LanguageVersion.ISO_1) {
2938 Report.FeatureIsNotStandardized (l, "static classes");
2942 protected override int AllowedModifiersProp {
2944 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2945 Modifiers.STATIC | Modifiers.UNSAFE;
2949 protected override void DefineContainerMembers (MemberCoreArrayList list)
2954 foreach (MemberCore m in list) {
2955 if (m is Operator) {
2956 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2960 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2961 Report.Warning (628, 4, m.Location, "'{0}': new protected member declared in static class", m.GetSignatureForError (this));
2964 Report.Error (720, m.Location, "'{0}': cannot declare indexers in a static class", m.GetSignatureForError (this));
2968 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2971 if (m is Constructor) {
2972 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2976 if (m is Destructor) {
2977 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2980 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2983 base.DefineContainerMembers (list);
2986 public override TypeBuilder DefineType()
2988 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2989 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2993 TypeBuilder tb = base.DefineType ();
2997 if ((ptype != null) && (ptype != TypeManager.object_type)) {
3000 "Static class '{0}' cannot derive from type '{1}'. " +
3001 "Static classes must derive from object",
3002 GetSignatureForError (), ptype);
3006 if (ifaces != null) {
3007 foreach (Type t in ifaces)
3008 Report.SymbolRelatedToPreviousError (t);
3011 "'{0}': static classes cannot implement interfaces",
3012 GetSignatureForError ());
3017 protected override TypeAttributes TypeAttr {
3019 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
3024 public class Class : ClassOrStruct {
3025 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
3026 public const int AllowedModifiers =
3029 Modifiers.PROTECTED |
3030 Modifiers.INTERNAL |
3032 Modifiers.ABSTRACT |
3036 bool WasTransitError;
3038 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3039 Attributes attrs, Location l)
3040 : base (ns, parent, name, attrs, Kind.Class, l)
3042 this.ModFlags = mod;
3045 virtual protected int AllowedModifiersProp {
3047 return AllowedModifiers;
3051 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
3053 if (a.Type == TypeManager.attribute_usage_type) {
3054 if (ptype != TypeManager.attribute_type &&
3055 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
3056 TypeBuilder.FullName != "System.Attribute") {
3057 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
3061 if (a.Type == TypeManager.conditional_attribute_type &&
3062 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
3063 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
3067 if (AttributeTester.IsAttributeExcluded (a.Type))
3070 base.ApplyAttributeBuilder (a, cb);
3073 public const TypeAttributes DefaultTypeAttributes =
3074 TypeAttributes.AutoLayout | TypeAttributes.Class;
3076 public override TypeBuilder DefineType()
3079 if (WasTransitError)
3081 throw new CircularDepException (this);
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);
3093 return base.DefineType ();
3095 catch (CircularDepException e) {
3096 Report.SymbolRelatedToPreviousError (e.Container);
3097 Report.Error (146, Location, "Circular base class dependency involving '{0}' and '{1}'",
3098 GetSignatureForError (), e.Container.GetSignatureForError ());
3099 WasTransitError = true;
3104 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3105 /// Valid only for attribute classes.
3106 public bool IsExcluded ()
3108 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3109 return (caching_flags & Flags.Excluded) != 0;
3111 caching_flags &= ~Flags.Excluded_Undetected;
3113 if (OptAttributes == null)
3116 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3121 foreach (Attribute a in attrs) {
3122 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3123 if (RootContext.AllDefines.Contains (condition))
3127 caching_flags |= Flags.Excluded;
3132 // FIXME: How do we deal with the user specifying a different
3135 protected override TypeAttributes TypeAttr {
3137 return base.TypeAttr | DefaultTypeAttributes;
3142 public class Struct : ClassOrStruct {
3144 // Modifiers allowed in a struct declaration
3146 public const int AllowedModifiers =
3149 Modifiers.PROTECTED |
3150 Modifiers.INTERNAL |
3154 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
3155 int mod, Attributes attrs, Location l)
3156 : base (ns, parent, name, attrs, Kind.Struct, l)
3160 if (parent.Parent == null)
3161 accmods = Modifiers.INTERNAL;
3163 accmods = Modifiers.PRIVATE;
3165 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3167 this.ModFlags |= Modifiers.SEALED;
3170 public const TypeAttributes DefaultTypeAttributes =
3171 TypeAttributes.SequentialLayout |
3172 TypeAttributes.Sealed |
3173 TypeAttributes.BeforeFieldInit;
3176 // FIXME: Allow the user to specify a different set of attributes
3177 // in some cases (Sealed for example is mandatory for a class,
3178 // but what SequentialLayout can be changed
3180 protected override TypeAttributes TypeAttr {
3182 return base.TypeAttr | DefaultTypeAttributes;
3186 public override TypeBuilder DefineType()
3190 throw new CircularDepException (this);
3194 return base.DefineType ();
3196 catch (CircularDepException e) {
3198 Report.SymbolRelatedToPreviousError (this);
3199 Error_TypeInListIsNotInterface (e.Container.Location, GetSignatureForError ());
3208 public class Interface : TypeContainer, IMemberContainer {
3210 bool WasTransitError;
3213 /// Modifiers allowed in a class declaration
3215 public const int AllowedModifiers =
3218 Modifiers.PROTECTED |
3219 Modifiers.INTERNAL |
3223 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name,
3224 int mod, Attributes attrs, Location l)
3225 : base (ns, parent, name, attrs, Kind.Interface, l)
3229 if (parent.Parent == null)
3230 accmods = Modifiers.INTERNAL;
3232 accmods = Modifiers.PRIVATE;
3234 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3237 public override PendingImplementation GetPendingImplementations ()
3242 public const TypeAttributes DefaultTypeAttributes =
3243 TypeAttributes.AutoLayout |
3244 TypeAttributes.Abstract |
3245 TypeAttributes.Interface;
3247 protected override TypeAttributes TypeAttr {
3249 return base.TypeAttr | DefaultTypeAttributes;
3253 public override TypeBuilder DefineType()
3256 if (WasTransitError)
3258 throw new CircularDepException (this);
3262 return base.DefineType ();
3264 catch (CircularDepException e) {
3265 Report.SymbolRelatedToPreviousError (e.Container);
3266 Report.Error (529, Location, "Inherited interface '{0}' causes a cycle in the interface hierarchy of '{1}'",
3267 e.Container.GetSignatureForError (), GetSignatureForError ());
3268 WasTransitError = true;
3273 protected override bool VerifyClsCompliance (DeclSpace ds)
3275 if (!base.VerifyClsCompliance (ds))
3278 if (ifaces != null) {
3279 foreach (Type t in ifaces) {
3280 if (AttributeTester.IsClsCompliant (t))
3283 Report.SymbolRelatedToPreviousError (t);
3284 Report.Warning (3027, 1, Location, "'{0}' is not CLS-compliant because base interface '{1}' is not CLS-compliant",
3285 GetSignatureForError (), TypeManager.CSharpName (t));
3293 public abstract class MethodCore : MemberBase {
3294 public readonly Parameters Parameters;
3295 public readonly GenericMethod GenericMethod;
3296 protected ToplevelBlock block;
3299 // Parameters, cached for semantic analysis.
3301 protected InternalParameters parameter_info;
3302 protected Type [] parameter_types;
3304 // Whether this is an operator method.
3305 public bool IsOperator;
3308 // The method we're overriding if this is an override method.
3310 protected MethodInfo base_method = null;
3312 static string[] attribute_targets = new string [] { "method", "return" };
3314 public MethodCore (TypeContainer parent, GenericMethod generic,
3315 Expression type, int mod, int allowed_mod, bool is_iface,
3316 MemberName name, Attributes attrs, Parameters parameters,
3318 : base (parent, generic != null ? generic : (DeclSpace) parent,
3319 type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
3321 Parameters = parameters;
3322 IsInterface = is_iface;
3323 this.GenericMethod = generic;
3327 // Returns the System.Type array for the parameters of this method
3329 public Type [] ParameterTypes {
3331 return parameter_types;
3335 public InternalParameters ParameterInfo
3338 return parameter_info;
3342 public ToplevelBlock Block {
3352 protected override bool CheckBase ()
3354 if (!base.CheckBase ())
3357 // Check whether arguments were correct.
3358 if (!DoDefineParameters ())
3361 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3367 // Is null for System.Object while compiling corlib and base interfaces
3368 if (Parent.BaseCache == null) {
3369 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3370 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3375 Type base_ret_type = null;
3376 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3378 // method is override
3379 if (base_method != null) {
3381 if (!CheckMethodAgainstBase ())
3384 if ((ModFlags & Modifiers.NEW) == 0) {
3385 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3386 Report.SymbolRelatedToPreviousError (base_method);
3387 if (this is PropertyBase) {
3388 Report.Error (1715, Location, "'{0}': type must be '{1}' to match overridden member '{2}'",
3389 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3392 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3393 "change return type when overriding inherited member");
3398 if (base_method.IsAbstract && !IsInterface) {
3399 Report.SymbolRelatedToPreviousError (base_method);
3400 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3405 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3406 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3410 if (RootContext.WarningLevel > 2) {
3411 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3412 Parent.Methods.HasEquals = true;
3413 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3414 Parent.Methods.HasGetHashCode = true;
3417 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3418 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3420 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3421 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3422 Report.SymbolRelatedToPreviousError (base_method);
3423 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3430 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3431 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3432 if (conflict_symbol != null) {
3433 Report.SymbolRelatedToPreviousError (conflict_symbol);
3434 if (this is PropertyBase)
3435 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3437 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3439 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3443 if (conflict_symbol == null) {
3444 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3445 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3450 if ((ModFlags & Modifiers.NEW) == 0) {
3451 if (this is Method && conflict_symbol is MethodBase)
3454 Report.SymbolRelatedToPreviousError (conflict_symbol);
3455 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3463 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3464 // that have been defined.
3466 // `name' is the user visible name for reporting errors (this is used to
3467 // provide the right name regarding method names and properties)
3469 bool CheckMethodAgainstBase ()
3473 // TODO: replace with GetSignatureForError
3474 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3476 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3477 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3479 506, Location, Parent.MakeName (Name) +
3480 ": cannot override inherited member `" +
3481 name + "' because it is not " +
3482 "virtual, abstract or override");
3486 // Now we check that the overriden method is not final
3488 if (base_method.IsFinal) {
3489 Report.SymbolRelatedToPreviousError (base_method);
3490 Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
3491 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3495 // Check that the permissions are not being changed
3497 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3498 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3500 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3501 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3506 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3507 ModFlags |= Modifiers.NEW;
3508 Report.SymbolRelatedToPreviousError (base_method);
3509 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3510 if (RootContext.WarningLevel >= 2)
3511 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));
3513 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3519 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3521 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3523 // when overriding protected internal, the method can be declared
3524 // protected internal only within the same assembly
3527 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3528 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3530 // assemblies differ - report an error
3534 } else if (thisp != base_classp) {
3536 // same assembly, but other attributes differ - report an error
3541 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3543 // if it's not "protected internal", it must be "protected"
3547 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3549 // protected within the same assembly - an error
3552 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3553 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3555 // protected ok, but other attributes differ - report an error
3561 return (thisp == base_classp);
3565 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3568 // FIXME: report the old/new permissions?
3571 507, Location, parent.MakeName (Name) +
3572 ": can't change the access modifiers when overriding inherited " +
3573 "member `" + name + "'");
3576 protected static string Error722 {
3578 return "'{0}': static types cannot be used as return types";
3583 /// For custom member duplication search in a container
3585 protected abstract bool CheckForDuplications ();
3588 /// Gets base method and its return type
3590 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3592 protected virtual bool DoDefineParameters ()
3594 EmitContext ec = ds.EmitContext;
3596 throw new InternalErrorException ("DoDefineParameters invoked too early");
3598 bool old_unsafe = ec.InUnsafe;
3599 ec.InUnsafe = InUnsafe;
3600 // Check if arguments were correct
3601 parameter_types = Parameters.GetParameterInfo (ec);
3602 ec.InUnsafe = old_unsafe;
3604 if ((parameter_types == null) ||
3605 !CheckParameters (ds, parameter_types))
3608 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3609 parameter_info = new InternalParameters (parameter_types, Parameters, tparam);
3611 Parameter array_param = Parameters.ArrayParameter;
3612 if ((array_param != null) &&
3613 (!array_param.ParameterType.IsArray ||
3614 (array_param.ParameterType.GetArrayRank () != 1))) {
3615 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3622 void error_425 (Type old, Type t, string name)
3624 Report.Error (425, Location,
3625 "The constraints of type parameter `{0}' " +
3626 "of method `{1}' must match the constraints for " +
3627 "type parameter `{2}' of method `{3}'",
3628 TypeManager.CSharpName (old), Name,
3629 TypeManager.CSharpName (t), name);
3632 protected override bool CheckGenericOverride (MethodInfo method, string name)
3634 ParameterData pd = TypeManager.GetParameterData (method);
3636 for (int i = 0; i < ParameterTypes.Length; i++) {
3637 GenericConstraints ogc = pd.GenericConstraints (i);
3638 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3640 if ((gc == null) && (ogc == null))
3643 Type ot = pd.ParameterType (i);
3644 Type t = ParameterTypes [i];
3646 if (!((gc != null) && (ogc != null))) {
3647 error_425 (ot, t, name);
3651 if ((gc.Attributes != ogc.Attributes) ||
3652 (gc.HasClassConstraint != ogc.HasClassConstraint)) {
3653 error_425 (ot, t, name);
3657 if (ogc.HasClassConstraint &&
3658 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3659 error_425 (ot, t, name);
3663 Type[] oct = ogc.InterfaceConstraints;
3664 Type[] ct = gc.InterfaceConstraints;
3666 if (oct.Length != ct.Length) {
3667 error_425 (ot, t, name);
3671 for (int j = 0; j < oct.Length; j++)
3672 if (!oct [j].Equals (ct [j])) {
3673 error_425 (ot, t, name);
3681 public override string[] ValidAttributeTargets {
3683 return attribute_targets;
3687 protected override bool VerifyClsCompliance (DeclSpace ds)
3689 if (!base.VerifyClsCompliance (ds)) {
3690 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3691 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3696 if (Parameters.HasArglist) {
3697 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3700 if (!AttributeTester.IsClsCompliant (MemberType)) {
3701 if (this is PropertyBase)
3702 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3703 GetSignatureForError ());
3705 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3706 GetSignatureForError ());
3709 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3714 bool MayUnify (MethodCore first, MethodCore second)
3716 int a_type_params = 0;
3717 if (first.GenericMethod != null)
3718 a_type_params = first.GenericMethod.CountTypeParameters;
3720 int b_type_params = 0;
3721 if (second.GenericMethod != null)
3722 b_type_params = second.GenericMethod.CountTypeParameters;
3724 if (a_type_params != b_type_params)
3727 Type[] class_infered, method_infered;
3728 if (Parent.CountTypeParameters > 0)
3729 class_infered = new Type [Parent.CountTypeParameters];
3731 class_infered = null;
3733 if (a_type_params > 0)
3734 method_infered = new Type [a_type_params];
3736 method_infered = null;
3738 return TypeManager.MayBecomeEqualGenericInstances (
3739 first.ParameterTypes, second.ParameterTypes, class_infered, method_infered);
3742 protected bool IsDuplicateImplementation (MethodCore method)
3744 if ((method == this) ||
3745 (method.MemberName.GetTypeName () != MemberName.GetTypeName ()))
3748 Type[] param_types = method.ParameterTypes;
3749 if (param_types == null)
3752 if (param_types.Length != ParameterTypes.Length)
3756 bool may_unify = MayUnify (this, method);
3758 for (int i = 0; i < param_types.Length; i++) {
3759 if (param_types [i] != ParameterTypes [i])
3763 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3764 equal = may_unify = false;
3766 // TODO: make operator compatible with MethodCore to avoid this
3767 if (this is Operator && method is Operator) {
3768 if (MemberType != method.MemberType)
3769 equal = may_unify = false;
3774 // Try to report 663: method only differs on out/ref
3776 ParameterData info = ParameterInfo;
3777 ParameterData other_info = method.ParameterInfo;
3778 for (int i = 0; i < info.Count; i++){
3779 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3780 Report.Error (663, Location,
3781 "Overload method only differs " +
3782 "in parameter modifier");
3787 Report.SymbolRelatedToPreviousError (method);
3788 if (this is Operator && method is Operator)
3789 Report.Error (557, Location,
3790 "Duplicate user-defined conversion in type '{0}'",
3793 Report.Error (111, Location,
3794 "Type '{0}' already defines a member called '{1}' " +
3795 "with the same parameter types", Parent.Name, Name);
3797 } else if (may_unify) {
3798 Report.Error (408, Location,
3799 "`{0}' cannot define overload members that " +
3800 "may unify for some type parameter substitutions",
3807 public override bool IsUsed
3818 // Returns a string that represents the signature for this
3819 // member which should be used in XML documentation.
3821 public override string GetDocCommentName (DeclSpace ds)
3823 return DocUtil.GetMethodDocCommentName (this, ds);
3827 // Raised (and passed an XmlElement that contains the comment)
3828 // when GenerateDocComment is writing documentation expectedly.
3830 // FIXME: with a few effort, it could be done with XmlReader,
3831 // that means removal of DOM use.
3833 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3835 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3839 // Represents header string for documentation comment.
3841 public override string DocCommentHeader {
3842 get { return "M:"; }
3845 protected override void VerifyObsoleteAttribute()
3847 base.VerifyObsoleteAttribute ();
3849 if (parameter_types == null)
3852 foreach (Type type in parameter_types) {
3853 CheckUsageOfObsoleteAttribute (type);
3858 public class SourceMethod : ISourceMethod
3860 TypeContainer container;
3863 protected SourceMethod (TypeContainer container, MethodBase builder,
3864 ISourceFile file, Location start, Location end)
3866 this.container = container;
3867 this.builder = builder;
3869 CodeGen.SymbolWriter.OpenMethod (
3870 file, this, start.Row, 0, end.Row, 0);
3873 public string Name {
3874 get { return builder.Name; }
3877 public int NamespaceID {
3878 get { return container.NamespaceEntry.SymbolFileID; }
3883 if (builder is MethodBuilder)
3884 return ((MethodBuilder) builder).GetToken ().Token;
3885 else if (builder is ConstructorBuilder)
3886 return ((ConstructorBuilder) builder).GetToken ().Token;
3888 throw new NotSupportedException ();
3892 public void CloseMethod ()
3894 if (CodeGen.SymbolWriter != null)
3895 CodeGen.SymbolWriter.CloseMethod ();
3898 public static SourceMethod Create (TypeContainer parent,
3899 MethodBase builder, Block block)
3901 if (CodeGen.SymbolWriter == null)
3906 Location start_loc = block.StartLocation;
3907 if (Location.IsNull (start_loc))
3910 Location end_loc = block.EndLocation;
3911 if (Location.IsNull (end_loc))
3914 ISourceFile file = start_loc.SourceFile;
3918 return new SourceMethod (
3919 parent, builder, file, start_loc, end_loc);
3923 public class Method : MethodCore, IIteratorContainer, IMethodData {
3924 public MethodBuilder MethodBuilder;
3925 public MethodData MethodData;
3926 ReturnParameter return_attributes;
3927 ListDictionary declarative_security;
3930 /// Modifiers allowed in a class declaration
3932 const int AllowedModifiers =
3935 Modifiers.PROTECTED |
3936 Modifiers.INTERNAL |
3941 Modifiers.OVERRIDE |
3942 Modifiers.ABSTRACT |
3944 Modifiers.METHOD_YIELDS |
3947 const int AllowedInterfaceModifiers =
3948 Modifiers.NEW | Modifiers.UNSAFE;
3951 // return_type can be "null" for VOID values.
3953 public Method (TypeContainer parent, GenericMethod generic,
3954 Expression return_type, int mod, bool is_iface,
3955 MemberName name, Parameters parameters, Attributes attrs,
3957 : base (parent, generic, return_type, mod,
3958 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3959 is_iface, name, attrs, parameters, l)
3963 public override AttributeTargets AttributeTargets {
3965 return AttributeTargets.Method;
3969 public override string GetSignatureForError()
3971 if (MethodBuilder == null) {
3972 return GetSignatureForError (Parent);
3974 return TypeManager.CSharpSignature (MethodBuilder);
3978 /// Use this method when MethodBuilder is null
3980 public override string GetSignatureForError (TypeContainer tc)
3982 // TODO: get params from somewhere
3983 if (parameter_info == null)
3984 return base.GetSignatureForError (tc);
3986 // TODO: move to parameters
3987 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3988 if (parameter_info.Parameters.FixedParameters != null) {
3989 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3990 Parameter p = parameter_info.Parameters.FixedParameters [i];
3991 args.Append (p.GetSignatureForError ());
3993 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3998 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
4001 void DuplicateEntryPoint (MethodInfo b, Location location)
4005 "Program `" + CodeGen.FileName +
4006 "' has more than one entry point defined: `" +
4007 TypeManager.CSharpSignature(b) + "'");
4010 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
4012 if (b.ReturnType != TypeManager.void_type &&
4013 b.ReturnType != TypeManager.int32_type)
4016 if (pinfo.Count == 0)
4019 if (pinfo.Count > 1)
4022 Type t = pinfo.ParameterType(0);
4024 (t.GetArrayRank() == 1) &&
4025 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
4026 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
4032 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4034 if (a.Target == AttributeTargets.ReturnValue) {
4035 if (return_attributes == null)
4036 return_attributes = new ReturnParameter (MethodBuilder, Location);
4038 return_attributes.ApplyAttributeBuilder (a, cb);
4042 if (a.Type == TypeManager.methodimpl_attr_type &&
4043 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4044 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4047 if (a.Type == TypeManager.dllimport_type) {
4048 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4049 if ((ModFlags & extern_static) != extern_static) {
4050 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
4056 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4057 if (declarative_security == null)
4058 declarative_security = new ListDictionary ();
4059 a.ExtractSecurityPermissionSet (declarative_security);
4063 if (a.Type == TypeManager.conditional_attribute_type) {
4064 if (IsOperator || IsExplicitImpl) {
4065 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4069 if (ReturnType != TypeManager.void_type) {
4070 Report.Error (578, Location, "Conditional not valid on '{0}' because its return type is not void", GetSignatureForError ());
4074 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4075 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
4080 Report.Error (582, Location, "Conditional not valid on interface members");
4084 if (MethodData.IsImplementing) {
4085 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
4089 for (int i = 0; i < parameter_info.Count; ++i) {
4090 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
4091 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
4097 MethodBuilder.SetCustomAttribute (cb);
4100 protected override bool CheckForDuplications ()
4102 ArrayList ar = Parent.Methods;
4104 int arLen = ar.Count;
4106 for (int i = 0; i < arLen; i++) {
4107 Method m = (Method) ar [i];
4108 if (IsDuplicateImplementation (m))
4113 ar = Parent.Properties;
4115 for (int i = 0; i < ar.Count; ++i) {
4116 PropertyBase pb = (PropertyBase) ar [i];
4117 if (pb.AreAccessorsDuplicateImplementation (this))
4122 ar = Parent.Indexers;
4124 for (int i = 0; i < ar.Count; ++i) {
4125 PropertyBase pb = (PropertyBase) ar [i];
4126 if (pb.AreAccessorsDuplicateImplementation (this))
4133 for (int i = 0; i < ar.Count; ++i) {
4134 Event ev = (Event) ar [i];
4135 if (ev.AreAccessorsDuplicateImplementation (this))
4146 public override bool Define ()
4148 if (!DoDefineBase ())
4151 MethodBuilder mb = null;
4152 if (GenericMethod != null) {
4153 string method_name = MemberName.Name;
4156 method_name = TypeManager.GetFullName (InterfaceType) + "." + method_name;
4158 mb = Parent.TypeBuilder.DefineGenericMethod (method_name, flags);
4159 if (!GenericMethod.Define (mb))
4166 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4167 Error1599 (Location, ReturnType);
4175 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
4177 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
4178 this, mb, GenericMethod, base_method);
4180 if (!MethodData.Define (Parent))
4184 // Setup iterator if we are one
4186 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4187 Iterator iterator = new Iterator (
4188 Parent, Name, MemberType,
4189 ParameterInfo, ModFlags, block, Location);
4191 if (!iterator.DefineIterator ())
4194 block = iterator.Block;
4197 MethodBuilder = MethodData.MethodBuilder;
4200 // This is used to track the Entry Point,
4202 if (Name == "Main" &&
4203 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
4204 (RootContext.MainClass == null ||
4205 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4206 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
4207 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4208 md.SetMemberIsUsed ();
4210 if (RootContext.EntryPoint == null) {
4211 if (Parent.IsGeneric){
4212 Report.Error (-201, Location,
4213 "Entry point can not be defined in a generic class");
4216 RootContext.EntryPoint = MethodBuilder;
4217 RootContext.EntryPointLocation = Location;
4219 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4220 DuplicateEntryPoint (MethodBuilder, Location);
4223 if (RootContext.WarningLevel >= 4)
4224 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder) );
4228 if (MemberType.IsAbstract && MemberType.IsSealed) {
4229 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4239 public override void Emit ()
4241 MethodData.Emit (Parent, this);
4244 if (declarative_security != null) {
4245 foreach (DictionaryEntry de in declarative_security) {
4246 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4254 public static void Error1599 (Location loc, Type t)
4256 Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
4259 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4261 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
4262 container.TypeBuilder, Name, ParameterTypes, false);
4267 base_ret_type = mi.ReturnType;
4271 public override bool MarkForDuplicationCheck ()
4273 caching_flags |= Flags.TestMethodDuplication;
4277 protected override bool VerifyClsCompliance(DeclSpace ds)
4279 if (!base.VerifyClsCompliance (ds))
4282 if (parameter_types.Length > 0) {
4283 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
4285 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4292 void IIteratorContainer.SetYields ()
4294 ModFlags |= Modifiers.METHOD_YIELDS;
4297 #region IMethodData Members
4299 public CallingConventions CallingConventions {
4301 CallingConventions cc = Parameters.GetCallingConvention ();
4302 if (Parameters.HasArglist)
4303 block.HasVarargs = true;
4306 if ((ModFlags & Modifiers.STATIC) == 0)
4307 cc |= CallingConventions.HasThis;
4309 // FIXME: How is `ExplicitThis' used in C#?
4315 public Type ReturnType {
4321 public MemberName MethodName {
4327 public new Location Location {
4329 return base.Location;
4333 protected override bool CheckBase() {
4334 if (!base.CheckBase ())
4337 // TODO: Destructor should derive from MethodCore
4338 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4339 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4340 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4347 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4349 return new EmitContext (
4350 tc, ds, Location, ig, ReturnType, ModFlags, false);
4353 public ObsoleteAttribute GetObsoleteAttribute ()
4355 return GetObsoleteAttribute (ds);
4359 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4361 public bool IsExcluded (EmitContext ec)
4363 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4364 return (caching_flags & Flags.Excluded) != 0;
4366 caching_flags &= ~Flags.Excluded_Undetected;
4368 if (base_method == null) {
4369 if (OptAttributes == null)
4372 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4377 foreach (Attribute a in attrs) {
4378 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4379 if (RootContext.AllDefines.Contains (condition))
4383 caching_flags |= Flags.Excluded;
4387 IMethodData md = TypeManager.GetMethod (base_method);
4389 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4390 caching_flags |= Flags.Excluded;
4396 if (md.IsExcluded (ec)) {
4397 caching_flags |= Flags.Excluded;
4403 GenericMethod IMethodData.GenericMethod {
4405 return GenericMethod;
4412 public abstract class ConstructorInitializer {
4413 ArrayList argument_list;
4414 protected ConstructorInfo base_constructor;
4415 Parameters parameters;
4418 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4421 this.argument_list = argument_list;
4422 this.parameters = parameters;
4426 public ArrayList Arguments {
4428 return argument_list;
4432 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4434 Expression base_constructor_group;
4438 ec.CurrentBlock = block;
4440 if (argument_list != null){
4441 foreach (Argument a in argument_list){
4442 if (!a.Resolve (ec, loc))
4446 ec.CurrentBlock = null;
4448 if (this is ConstructorBaseInitializer) {
4449 if (ec.ContainerType.BaseType == null)
4452 t = ec.ContainerType.BaseType;
4453 if (ec.ContainerType.IsValueType) {
4454 Report.Error (522, loc,
4455 "structs cannot call base class constructors");
4459 t = ec.ContainerType;
4461 base_constructor_group = Expression.MemberLookup (
4462 ec, t, ".ctor", MemberTypes.Constructor,
4463 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4466 if (base_constructor_group == null){
4468 base_constructor_group = Expression.MemberLookup (
4469 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4470 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4474 int errors = Report.Errors;
4475 if (base_constructor_group != null)
4476 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4477 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4480 if (base_constructor == null) {
4481 if (errors == Report.Errors)
4482 Report.Error (1501, loc, "Can not find a constructor for this argument list");
4487 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
4488 TypeManager.CSharpSignature (base_constructor));
4489 base_constructor = null;
4493 if (base_constructor == caller_builder){
4494 Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
4501 public void Emit (EmitContext ec)
4503 if (base_constructor != null){
4504 ec.Mark (loc, false);
4506 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4508 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4513 /// Method search for base ctor. (We do not cache it).
4515 Constructor GetOverloadedConstructor (TypeContainer tc)
4517 if (tc.InstanceConstructors == null)
4520 foreach (Constructor c in tc.InstanceConstructors) {
4521 if (Arguments == null) {
4522 if (c.ParameterTypes.Length == 0)
4530 int count = c.ParameterInfo.Count;
4532 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4533 for (int i = 0; i < count-1; i++)
4534 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4539 if (c.ParameterTypes.Length != Arguments.Count)
4542 for (int i = 0; i < Arguments.Count; ++i)
4543 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4558 //TODO: implement caching when it will be necessary
4559 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4561 Constructor ctor = GetOverloadedConstructor (tc);
4565 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4569 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4573 public class ConstructorBaseInitializer : ConstructorInitializer {
4574 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4575 base (argument_list, pars, l)
4579 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4580 if (base_constructor == null)
4583 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4584 if (type_ds == null) {
4585 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (base_constructor);
4588 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (base_constructor), loc);
4593 base.CheckObsoleteAttribute (type_ds, loc);
4598 public class ConstructorThisInitializer : ConstructorInitializer {
4599 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4600 base (argument_list, pars, l)
4605 public class Constructor : MethodCore, IMethodData {
4606 public ConstructorBuilder ConstructorBuilder;
4607 public ConstructorInitializer Initializer;
4608 ListDictionary declarative_security;
4611 // Modifiers allowed for a constructor.
4613 public const int AllowedModifiers =
4615 Modifiers.PROTECTED |
4616 Modifiers.INTERNAL |
4622 bool has_compliant_args = false;
4624 // The spec claims that static is not permitted, but
4625 // my very own code has static constructors.
4627 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4628 ConstructorInitializer init, Location l)
4629 : base (ds, null, null, mod, AllowedModifiers, false,
4630 new MemberName (name), null, args, l)
4635 public override string GetSignatureForError()
4637 if (ConstructorBuilder == null)
4638 return GetSignatureForError (Parent);
4640 return TypeManager.CSharpSignature (ConstructorBuilder);
4643 public bool HasCompliantArgs {
4645 return has_compliant_args;
4649 public override AttributeTargets AttributeTargets {
4651 return AttributeTargets.Constructor;
4657 // Returns true if this is a default constructor
4659 public bool IsDefault ()
4661 if ((ModFlags & Modifiers.STATIC) != 0)
4662 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4663 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4666 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4667 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4668 (Initializer is ConstructorBaseInitializer) &&
4669 (Initializer.Arguments == null);
4672 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4674 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4675 if (declarative_security == null) {
4676 declarative_security = new ListDictionary ();
4678 a.ExtractSecurityPermissionSet (declarative_security);
4682 ConstructorBuilder.SetCustomAttribute (cb);
4685 protected override bool CheckForDuplications ()
4687 ArrayList ar = Parent.InstanceConstructors;
4689 int arLen = ar.Count;
4691 for (int i = 0; i < arLen; i++) {
4692 Constructor m = (Constructor) ar [i];
4693 if (IsDuplicateImplementation (m))
4700 protected override bool CheckBase ()
4702 // Check whether arguments were correct.
4703 if (!DoDefineParameters ())
4706 // TODO: skip the rest for generated ctor
4707 if ((ModFlags & Modifiers.STATIC) != 0)
4710 if (!CheckForDuplications ())
4713 if (Parent.Kind == Kind.Struct) {
4714 if (ParameterTypes.Length == 0) {
4715 Report.Error (568, Location,
4716 "Structs can not contain explicit parameterless " +
4721 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4722 Report.Error (666, Location, "Protected member in struct declaration");
4727 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4728 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4735 // Creates the ConstructorBuilder
4737 public override bool Define ()
4739 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4740 MethodAttributes.SpecialName);
4742 if ((ModFlags & Modifiers.STATIC) != 0){
4743 ca |= MethodAttributes.Static | MethodAttributes.Private;
4745 ca |= MethodAttributes.HideBySig;
4747 if ((ModFlags & Modifiers.PUBLIC) != 0)
4748 ca |= MethodAttributes.Public;
4749 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4750 if ((ModFlags & Modifiers.INTERNAL) != 0)
4751 ca |= MethodAttributes.FamORAssem;
4753 ca |= MethodAttributes.Family;
4754 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4755 ca |= MethodAttributes.Assembly;
4756 else if (IsDefault ())
4757 ca |= MethodAttributes.Public;
4759 ca |= MethodAttributes.Private;
4762 // Check if arguments were correct.
4766 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4767 ca, CallingConventions,
4770 if ((ModFlags & Modifiers.UNSAFE) != 0)
4771 ConstructorBuilder.InitLocals = false;
4773 TypeManager.AddMethod (ConstructorBuilder, this);
4776 // HACK because System.Reflection.Emit is lame
4778 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4786 public override void Emit ()
4788 EmitContext ec = CreateEmitContext (null, null);
4791 // extern methods have no bodies
4793 if ((ModFlags & Modifiers.EXTERN) != 0) {
4794 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4796 179, Location, "External constructor `" +
4797 TypeManager.CSharpSignature (ConstructorBuilder) +
4798 "' can not have a body");
4801 } else if (block == null) {
4803 501, Location, "Constructor `" +
4804 TypeManager.CSharpSignature (ConstructorBuilder) +
4805 "' must declare a body since it is not marked extern");
4809 // If this is a non-static `struct' constructor and doesn't have any
4810 // initializer, it must initialize all of the struct's fields.
4811 if ((Parent.Kind == Kind.Struct) &&
4812 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4813 Block.AddThisVariable (Parent, Location);
4816 block.ResolveMeta (ec, ParameterInfo);
4818 if ((ModFlags & Modifiers.STATIC) == 0){
4819 if (Parent.Kind == Kind.Class && Initializer == null)
4820 Initializer = new ConstructorBaseInitializer (
4821 null, Parameters.EmptyReadOnlyParameters, Location);
4825 // Spec mandates that Initializers will not have
4829 if ((Initializer != null) &&
4830 !Initializer.Resolve (ConstructorBuilder, block, ec))
4832 ec.IsStatic = false;
4835 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4837 SourceMethod source = SourceMethod.Create (
4838 Parent, ConstructorBuilder, block);
4841 // Classes can have base initializers and instance field initializers.
4843 if (Parent.Kind == Kind.Class){
4844 if ((ModFlags & Modifiers.STATIC) == 0){
4847 // If we use a "this (...)" constructor initializer, then
4848 // do not emit field initializers, they are initialized in the other constructor
4850 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4851 Parent.EmitFieldInitializers (ec);
4854 if (Initializer != null) {
4855 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null)
4856 Initializer.CheckObsoleteAttribute (Parent, Location);
4858 ec.TestObsoleteMethodUsage = false;
4859 Initializer.Emit (ec);
4862 if ((ModFlags & Modifiers.STATIC) != 0)
4863 Parent.EmitFieldInitializers (ec);
4865 if (OptAttributes != null)
4866 OptAttributes.Emit (ec, this);
4868 ec.EmitTopBlock (block, ParameterInfo, Location);
4871 source.CloseMethod ();
4875 if (declarative_security != null) {
4876 foreach (DictionaryEntry de in declarative_security) {
4877 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4884 // Is never override
4885 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4890 protected override bool VerifyClsCompliance (DeclSpace ds)
4892 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4896 if (parameter_types.Length > 0) {
4897 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4899 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4901 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4902 foreach (Type param in parameter_types) {
4903 if (param.IsArray) {
4909 has_compliant_args = true;
4913 #region IMethodData Members
4915 public System.Reflection.CallingConventions CallingConventions {
4917 CallingConventions cc = Parameters.GetCallingConvention ();
4919 if (Parent.Kind == Kind.Class)
4920 if ((ModFlags & Modifiers.STATIC) == 0)
4921 cc |= CallingConventions.HasThis;
4923 // FIXME: How is `ExplicitThis' used in C#?
4929 public new Location Location {
4931 return base.Location;
4935 public MemberName MethodName {
4941 public Type ReturnType {
4947 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4949 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4950 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4953 public ObsoleteAttribute GetObsoleteAttribute ()
4958 public bool IsExcluded(EmitContext ec)
4963 GenericMethod IMethodData.GenericMethod {
4973 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4975 public interface IMethodData
4977 CallingConventions CallingConventions { get; }
4978 Location Location { get; }
4979 MemberName MethodName { get; }
4980 Type[] ParameterTypes { get; }
4981 Type ReturnType { get; }
4982 GenericMethod GenericMethod { get; }
4984 Attributes OptAttributes { get; }
4985 ToplevelBlock Block { get; }
4987 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4988 ObsoleteAttribute GetObsoleteAttribute ();
4989 string GetSignatureForError (TypeContainer tc);
4990 bool IsExcluded (EmitContext ec);
4991 bool IsClsCompliaceRequired (DeclSpace ds);
4992 void SetMemberIsUsed ();
4996 // Encapsulates most of the Method's state
4998 public class MethodData {
5000 readonly IMethodData method;
5003 // The return type of this method
5005 public readonly GenericMethod GenericMethod;
5006 public readonly InternalParameters ParameterInfo;
5009 // Are we implementing an interface ?
5011 public bool IsImplementing = false;
5016 protected MemberBase member;
5017 protected int modifiers;
5018 protected MethodAttributes flags;
5019 protected Type declaring_type;
5020 protected MethodInfo parent_method;
5024 MethodBuilder builder = null;
5025 public MethodBuilder MethodBuilder {
5031 public Type DeclaringType {
5033 return declaring_type;
5037 public MethodData (MemberBase member, InternalParameters parameters,
5038 int modifiers, MethodAttributes flags, IMethodData method)
5040 this.member = member;
5041 this.ParameterInfo = parameters;
5042 this.modifiers = modifiers;
5045 this.method = method;
5048 public MethodData (MemberBase member, InternalParameters parameters,
5049 int modifiers, MethodAttributes flags,
5050 IMethodData method, MethodBuilder builder,
5051 GenericMethod generic, MethodInfo parent_method)
5052 : this (member, parameters, modifiers, flags, method)
5054 this.builder = builder;
5055 this.GenericMethod = generic;
5056 this.parent_method = parent_method;
5059 public bool Define (TypeContainer container)
5061 MethodInfo implementing = null;
5063 string name = method.MethodName.Basename;
5064 string method_name = method.MethodName.FullName;
5066 Type[] ParameterTypes = method.ParameterTypes;
5068 if (container.Pending != null){
5069 if (member is Indexer) // TODO: test it, but it should work without this IF
5070 implementing = container.Pending.IsInterfaceIndexer (
5071 member.InterfaceType, method.ReturnType, ParameterInfo);
5073 implementing = container.Pending.IsInterfaceMethod (
5074 member.InterfaceType, name, method.ReturnType, ParameterInfo);
5076 if (member.InterfaceType != null){
5077 if (implementing == null){
5078 if (member is PropertyBase) {
5079 Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
5080 method.GetSignatureForError (container), member.Name);
5083 Report.Error (539, method.Location, "'{0}' in explicit interface " +
5084 "declaration is not a member of interface",
5089 if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
5090 Report.SymbolRelatedToPreviousError (implementing);
5091 Report.Error (683, method.Location, "'{0}' explicit method implementation cannot implement '{1}' because it is an accessor",
5092 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5096 method_name = TypeManager.GetFullName (member.InterfaceType) + "." + method_name;
5098 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
5099 Report.SymbolRelatedToPreviousError (implementing);
5100 Report.Error (686, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
5101 method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5108 // For implicit implementations, make sure we are public, for
5109 // explicit implementations, make sure we are private.
5111 if (implementing != null){
5113 // Setting null inside this block will trigger a more
5114 // verbose error reporting for missing interface implementations
5116 // The "candidate" function has been flagged already
5117 // but it wont get cleared
5119 if (member.IsExplicitImpl){
5120 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
5121 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
5122 implementing = null;
5124 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
5125 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
5127 // If this is an interface method implementation,
5128 // check for public accessibility
5130 implementing = null;
5131 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5132 // We may never be private.
5133 implementing = null;
5134 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5136 // We may be protected if we're overriding something.
5138 implementing = null;
5143 // Static is not allowed
5145 if ((modifiers & Modifiers.STATIC) != 0){
5146 implementing = null;
5147 Modifiers.Error_InvalidModifier (method.Location, "static");
5152 // If implementing is still valid, set flags
5154 if (implementing != null){
5156 // When implementing interface methods, set NewSlot
5157 // unless, we are overwriting a method.
5159 if (implementing.DeclaringType.IsInterface){
5160 if ((modifiers & Modifiers.OVERRIDE) == 0)
5161 flags |= MethodAttributes.NewSlot;
5164 MethodAttributes.Virtual |
5165 MethodAttributes.HideBySig;
5167 // Set Final unless we're virtual, abstract or already overriding a method.
5168 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5169 flags |= MethodAttributes.Final;
5171 IsImplementing = true;
5174 EmitContext ec = method.CreateEmitContext (container, null);
5176 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
5178 if (builder == null)
5181 if (container.CurrentType != null)
5182 declaring_type = container.CurrentType;
5184 declaring_type = container.TypeBuilder;
5186 if ((modifiers & Modifiers.UNSAFE) != 0)
5187 builder.InitLocals = false;
5189 if (IsImplementing){
5191 // clear the pending implemntation flag
5193 if (member is Indexer) {
5194 container.Pending.ImplementIndexer (
5195 member.InterfaceType, builder, method.ReturnType,
5196 ParameterInfo, member.IsExplicitImpl);
5198 container.Pending.ImplementMethod (
5199 member.InterfaceType, name, method.ReturnType,
5200 ParameterInfo, member.IsExplicitImpl);
5202 if (member.IsExplicitImpl)
5203 container.TypeBuilder.DefineMethodOverride (
5204 builder, implementing);
5207 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
5208 TypeManager.AddMethod (builder, method);
5210 if (GenericMethod != null) {
5211 bool is_override = member.IsExplicitImpl |
5212 ((modifiers & Modifiers.OVERRIDE) != 0);
5214 if (implementing != null)
5215 parent_method = implementing;
5217 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5225 /// Create the MethodBuilder for the method
5227 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
5229 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
5231 if ((modifiers & extern_static) == extern_static) {
5233 if (method.OptAttributes != null) {
5234 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
5235 if (dllimport_attribute != null) {
5236 flags |= MethodAttributes.PinvokeImpl;
5237 builder = dllimport_attribute.DefinePInvokeMethod (
5238 ec, container.TypeBuilder, method_name, flags,
5239 method.ReturnType, ParameterTypes);
5245 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5246 // We are more strict than Microsoft and report CS0626 like error
5247 if (method.OptAttributes == null ||
5248 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
5249 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));
5254 if (builder == null)
5255 builder = container.TypeBuilder.DefineMethod (
5256 method_name, flags, method.CallingConventions,
5257 method.ReturnType, ParameterTypes);
5259 builder.SetGenericMethodSignature (
5260 flags, method.CallingConventions,
5261 method.ReturnType, ParameterTypes);
5267 public void Emit (TypeContainer container, Attributable kind)
5270 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5271 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
5273 ec = method.CreateEmitContext (container, null);
5275 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
5276 ec.TestObsoleteMethodUsage = false;
5278 Location loc = method.Location;
5279 Attributes OptAttributes = method.OptAttributes;
5281 if (OptAttributes != null)
5282 OptAttributes.Emit (ec, kind);
5284 if (member is MethodCore)
5285 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
5287 ToplevelBlock block = method.Block;
5290 // abstract or extern methods have no bodies
5292 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
5297 // abstract or extern methods have no bodies.
5299 if ((modifiers & Modifiers.ABSTRACT) != 0)
5301 500, method.Location, "Abstract method `" +
5302 TypeManager.CSharpSignature (builder) +
5303 "' can not have a body");
5305 if ((modifiers & Modifiers.EXTERN) != 0)
5307 179, method.Location, "External method `" +
5308 TypeManager.CSharpSignature (builder) +
5309 "' can not have a body");
5315 // Methods must have a body unless they're extern or abstract
5317 if (block == null) {
5319 501, method.Location, "Method `" +
5320 TypeManager.CSharpSignature (builder) +
5321 "' must declare a body since it is not marked " +
5322 "abstract or extern");
5326 SourceMethod source = SourceMethod.Create (
5327 container, MethodBuilder, method.Block);
5330 // Handle destructors specially
5332 // FIXME: This code generates buggy code
5334 if (member is Destructor)
5335 EmitDestructor (ec, block);
5337 ec.EmitTopBlock (block, ParameterInfo, loc);
5340 source.CloseMethod ();
5343 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5345 ILGenerator ig = ec.ig;
5347 Label finish = ig.DefineLabel ();
5349 block.SetDestructor ();
5351 ig.BeginExceptionBlock ();
5352 ec.ReturnLabel = finish;
5353 ec.HasReturnLabel = true;
5354 ec.EmitTopBlock (block, null, method.Location);
5356 // ig.MarkLabel (finish);
5357 ig.BeginFinallyBlock ();
5359 if (ec.ContainerType.BaseType != null) {
5360 Expression member_lookup = Expression.MemberLookup (
5361 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5362 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5364 if (member_lookup != null){
5365 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5367 ig.Emit (OpCodes.Ldarg_0);
5368 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5372 ig.EndExceptionBlock ();
5373 //ig.MarkLabel (ec.ReturnLabel);
5374 ig.Emit (OpCodes.Ret);
5378 // Should derive from MethodCore
5379 public class Destructor : Method {
5381 public Destructor (TypeContainer ds, Expression return_type, int mod, string name,
5382 Parameters parameters, Attributes attrs, Location l)
5383 : base (ds, null, return_type, mod, false, new MemberName (name),
5384 parameters, attrs, l)
5387 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5389 if (a.Type == TypeManager.conditional_attribute_type) {
5390 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
5394 base.ApplyAttributeBuilder (a, cb);
5398 abstract public class MemberBase : MemberCore {
5399 public Expression Type;
5401 public MethodAttributes flags;
5402 public readonly DeclSpace ds;
5404 protected readonly int explicit_mod_flags;
5407 // The "short" name of this property / indexer / event. This is the
5408 // name without the explicit interface.
5410 public string ShortName {
5411 get { return MemberName.Name; }
5413 SetMemberName (new MemberName (MemberName.Left, value));
5418 // The type of this property / indexer / event
5420 protected Type member_type;
5421 public Type MemberType {
5423 if (member_type == null && Type != null) {
5424 EmitContext ec = ds.EmitContext;
5425 bool old_unsafe = ec.InUnsafe;
5426 ec.InUnsafe = InUnsafe;
5427 Type = Type.ResolveAsTypeTerminal (ec);
5428 ec.InUnsafe = old_unsafe;
5430 member_type = Type == null ? null : Type.Type;
5437 // Whether this is an interface member.
5439 public bool IsInterface;
5442 // If true, this is an explicit interface implementation
5444 public bool IsExplicitImpl;
5447 // The interface type we are explicitly implementing
5449 public Type InterfaceType = null;
5452 // The constructor is only exposed to our children
5454 protected MemberBase (TypeContainer parent, DeclSpace ds, Expression type, int mod,
5455 int allowed_mod, int def_mod, MemberName name,
5456 Attributes attrs, Location loc)
5457 : base (parent, name, attrs, loc)
5460 explicit_mod_flags = mod;
5462 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
5463 IsExplicitImpl = (MemberName.Left != null);
5466 protected virtual bool CheckBase ()
5468 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5469 Report.Error (666, Location, "Protected member in struct declaration");
5473 if ((RootContext.WarningLevel >= 4) &&
5474 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5475 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5476 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5477 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
5483 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5485 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5489 foreach (Type partype in parameters){
5490 if (partype == TypeManager.void_type) {
5492 1547, Location, "Keyword 'void' cannot " +
5493 "be used in this context");
5497 if (partype.IsPointer){
5500 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5504 if (ds.AsAccessible (partype, ModFlags))
5507 if (this is Indexer)
5508 Report.Error (55, Location,
5509 "Inconsistent accessibility: parameter type `" +
5510 TypeManager.CSharpName (partype) + "' is less " +
5511 "accessible than indexer `" + Name + "'");
5512 else if ((this is Method) && ((Method) this).IsOperator)
5513 Report.Error (57, Location,
5514 "Inconsistent accessibility: parameter type `" +
5515 TypeManager.CSharpName (partype) + "' is less " +
5516 "accessible than operator `" + Name + "'");
5518 Report.Error (51, Location,
5519 "Inconsistent accessibility: parameter type `" +
5520 TypeManager.CSharpName (partype) + "' is less " +
5521 "accessible than method `" + Name + "'");
5528 protected virtual bool DoDefineBase ()
5530 EmitContext ec = Parent.EmitContext;
5532 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5535 throw new InternalErrorException ();
5538 ModFlags = Modifiers.PUBLIC |
5539 Modifiers.ABSTRACT |
5540 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5542 flags = MethodAttributes.Public |
5543 MethodAttributes.Abstract |
5544 MethodAttributes.HideBySig |
5545 MethodAttributes.NewSlot |
5546 MethodAttributes.Virtual;
5548 if (!Parent.MethodModifiersValid (this))
5551 flags = Modifiers.MethodAttr (ModFlags);
5554 if (IsExplicitImpl) {
5555 Expression expr = MemberName.Left.GetTypeExpression (Location);
5556 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5557 if (iface_texpr == null)
5560 InterfaceType = iface_texpr.Type;
5562 if (!InterfaceType.IsInterface) {
5563 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5567 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5570 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5576 protected virtual bool DoDefine ()
5578 EmitContext ec = ds.EmitContext;
5580 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5582 ec.InUnsafe = InUnsafe;
5584 if (MemberType == null)
5587 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5588 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5589 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5594 // verify accessibility
5595 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5596 Report.SymbolRelatedToPreviousError (MemberType);
5597 if (this is Property)
5598 Report.Error (53, Location,
5599 "Inconsistent accessibility: property type `" +
5600 TypeManager.CSharpName (MemberType) + "' is less " +
5601 "accessible than property `" + GetSignatureForError () + "'");
5602 else if (this is Indexer)
5603 Report.Error (54, Location,
5604 "Inconsistent accessibility: indexer return type `" +
5605 TypeManager.CSharpName (MemberType) + "' is less " +
5606 "accessible than indexer `" + Name + "'");
5607 else if (this is MethodCore) {
5608 if (this is Operator)
5609 Report.Error (56, Location,
5610 "Inconsistent accessibility: return type `" +
5611 TypeManager.CSharpName (MemberType) + "' is less " +
5612 "accessible than operator `" + Name + "'");
5614 Report.Error (50, Location,
5615 "Inconsistent accessibility: return type `" +
5616 TypeManager.CSharpName (MemberType) + "' is less " +
5617 "accessible than method `" + Name + "'");
5619 Report.Error (52, Location,
5620 "Inconsistent accessibility: field type `" +
5621 TypeManager.CSharpName (MemberType) + "' is less " +
5622 "accessible than field `" + Name + "'");
5627 if (MemberType.IsPointer && !UnsafeOK (Parent))
5633 public override string GetSignatureForError (TypeContainer tc)
5635 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5638 protected bool IsTypePermitted ()
5640 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5641 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5647 protected override bool VerifyClsCompliance(DeclSpace ds)
5649 if (base.VerifyClsCompliance (ds)) {
5653 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5654 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5659 protected override void VerifyObsoleteAttribute()
5661 CheckUsageOfObsoleteAttribute (MemberType);
5666 // Fields and Events both generate FieldBuilders, we use this to share
5667 // their common bits. This is also used to flag usage of the field
5669 abstract public class FieldBase : MemberBase {
5670 public FieldBuilder FieldBuilder;
5671 public Status status;
5674 public enum Status : byte {
5676 HAS_OFFSET = 4 // Used by FieldMember.
5679 static string[] attribute_targets = new string [] { "field" };
5682 /// Symbol with same name in base class/struct
5684 public MemberInfo conflict_symbol;
5687 // The constructor is only exposed to our children
5689 protected FieldBase (TypeContainer parent, Expression type, int mod,
5690 int allowed_mod, MemberName name, object init,
5691 Attributes attrs, Location loc)
5692 : base (parent, parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5698 public override AttributeTargets AttributeTargets {
5700 return AttributeTargets.Field;
5704 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5706 if (a.Type == TypeManager.marshal_as_attr_type) {
5707 UnmanagedMarshal marshal = a.GetMarshal (this);
5708 if (marshal != null) {
5709 FieldBuilder.SetMarshal (marshal);
5714 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5715 a.Error_InvalidSecurityParent ();
5719 FieldBuilder.SetCustomAttribute (cb);
5723 // Whether this field has an initializer.
5725 public bool HasInitializer {
5727 return init != null;
5731 protected readonly Object init;
5733 Expression init_expr;
5734 bool init_expr_initialized = false;
5736 protected override bool CheckGenericOverride (MethodInfo method, string name)
5742 // Resolves and returns the field initializer.
5744 public Expression GetInitializerExpression (EmitContext ec)
5746 if (init_expr_initialized)
5750 if (init is Expression)
5751 e = (Expression) init;
5753 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5755 EmitContext parent_ec = Parent.EmitContext;
5757 bool old_is_static = parent_ec.IsStatic;
5758 parent_ec.IsStatic = ec.IsStatic;
5759 parent_ec.IsFieldInitializer = true;
5760 e = e.DoResolve (parent_ec);
5761 parent_ec.IsFieldInitializer = false;
5762 parent_ec.IsStatic = old_is_static;
5765 init_expr_initialized = true;
5770 protected override bool CheckBase ()
5772 if (!base.CheckBase ())
5779 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5780 if (conflict_symbol == null) {
5781 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5782 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5787 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5788 Report.SymbolRelatedToPreviousError (conflict_symbol);
5789 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5795 protected override bool DoDefine ()
5797 if (!base.DoDefine ())
5800 if (MemberType == TypeManager.void_type) {
5801 Report.Error (1547, Location,
5802 "Keyword 'void' cannot be used in this context");
5808 public override string GetSignatureForError ()
5810 if (FieldBuilder == null) {
5811 return base.GetSignatureForError (Parent);
5813 return TypeManager.GetFullNameSignature (FieldBuilder);
5816 protected virtual bool IsFieldClsCompliant {
5818 if (FieldBuilder == null)
5821 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5825 public override string[] ValidAttributeTargets {
5827 return attribute_targets;
5831 protected override bool VerifyClsCompliance (DeclSpace ds)
5833 if (!base.VerifyClsCompliance (ds))
5836 if (!IsFieldClsCompliant) {
5837 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5843 public void SetAssigned ()
5845 status |= Status.ASSIGNED;
5849 public abstract class FieldMember: FieldBase
5851 protected FieldMember (TypeContainer parent, Expression type, int mod,
5852 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5853 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5855 if ((mod & Modifiers.ABSTRACT) != 0)
5856 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5859 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5861 if (a.Type == TypeManager.field_offset_attribute_type)
5863 status |= Status.HAS_OFFSET;
5865 if (!Parent.HasExplicitLayout) {
5866 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5870 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5871 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5876 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5877 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5881 base.ApplyAttributeBuilder (a, cb);
5885 public override bool Define()
5887 EmitContext ec = Parent.EmitContext;
5889 throw new InternalErrorException ("FieldMember.Define called too early");
5891 if (MemberType == null)
5894 if (MemberType == TypeManager.void_type) {
5895 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5902 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5903 Report.Error (52, Location,
5904 "Inconsistent accessibility: field type `" +
5905 TypeManager.CSharpName (MemberType) + "' is less " +
5906 "accessible than field `" + Name + "'");
5910 if (!IsTypePermitted ())
5913 if (MemberType.IsPointer && !UnsafeOK (Parent))
5919 public override void Emit ()
5921 if (OptAttributes != null) {
5922 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5923 OptAttributes.Emit (ec, this);
5926 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5927 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5934 // Represents header string for documentation comment.
5936 public override string DocCommentHeader {
5937 get { return "F:"; }
5941 interface IFixedBuffer
5943 FieldInfo Element { get; }
5944 Type ElementType { get; }
5947 public class FixedFieldExternal: IFixedBuffer
5949 FieldInfo element_field;
5951 public FixedFieldExternal (FieldInfo fi)
5953 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5956 #region IFixedField Members
5958 public FieldInfo Element {
5960 return element_field;
5964 public Type ElementType {
5966 return element_field.FieldType;
5974 /// Fixed buffer implementation
5976 public class FixedField: FieldMember, IFixedBuffer
5978 public const string FixedElementName = "FixedElementField";
5979 static int GlobalCounter = 0;
5980 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5981 static FieldInfo[] fi;
5983 TypeBuilder fixed_buffer_type;
5984 FieldBuilder element;
5985 Expression size_expr;
5988 const int AllowedModifiers =
5991 Modifiers.PROTECTED |
5992 Modifiers.INTERNAL |
5995 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5996 Expression size_expr, Attributes attrs, Location loc):
5997 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5999 if (RootContext.Version == LanguageVersion.ISO_1)
6000 Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
6002 this.size_expr = size_expr;
6005 public override bool Define()
6007 if (Parent.Kind != Kind.Struct) {
6008 Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
6012 if (!base.Define ())
6015 if (!TypeManager.IsPrimitiveType (MemberType)) {
6016 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");
6020 Expression e = size_expr.Resolve (Parent.EmitContext);
6024 Constant c = e as Constant;
6026 Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
6030 IntConstant buffer_size_const = c.ToInt (Location);
6031 if (buffer_size_const == null)
6034 buffer_size = buffer_size_const.Value;
6036 if (buffer_size <= 0) {
6037 Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
6041 int type_size = Expression.GetTypeSize (MemberType);
6043 if (buffer_size > int.MaxValue / type_size) {
6044 Report.Error (1664, Location, "Fixed sized buffer of length '{0}' and type '{1}' exceeded 2^31 limit",
6045 buffer_size.ToString (), TypeManager.CSharpName (MemberType));
6049 buffer_size *= type_size;
6052 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
6054 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
6055 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
6056 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
6057 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
6059 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
6060 TypeManager.RegisterFieldBase (FieldBuilder, this);
6065 public override void Emit()
6068 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
6070 object[] fi_val = new object[1];
6071 fi_val [0] = buffer_size;
6073 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
6074 ctor_args, fi, fi_val);
6075 fixed_buffer_type.SetCustomAttribute (cab);
6077 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
6078 FieldBuilder.SetCustomAttribute (cab);
6082 protected override bool IsFieldClsCompliant {
6088 #region IFixedField Members
6090 public FieldInfo Element {
6096 public Type ElementType {
6106 // The Field class is used to represents class/struct fields during parsing.
6108 public class Field : FieldMember {
6110 // Modifiers allowed in a class declaration
6112 const int AllowedModifiers =
6115 Modifiers.PROTECTED |
6116 Modifiers.INTERNAL |
6119 Modifiers.VOLATILE |
6123 public Field (TypeContainer parent, Expression type, int mod, string name,
6124 Object expr_or_array_init, Attributes attrs, Location loc)
6125 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
6126 expr_or_array_init, attrs, loc)
6130 public override bool Define ()
6132 if (!base.Define ())
6135 if (RootContext.WarningLevel > 1){
6136 Type ptype = Parent.TypeBuilder.BaseType;
6138 // ptype is only null for System.Object while compiling corlib.
6140 TypeContainer.FindMembers (
6141 ptype, MemberTypes.Method,
6142 BindingFlags.Public |
6143 BindingFlags.Static | BindingFlags.Instance,
6144 System.Type.FilterName, Name);
6148 if ((ModFlags & Modifiers.VOLATILE) != 0){
6149 if (!MemberType.IsClass){
6150 Type vt = MemberType;
6152 if (TypeManager.IsEnumType (vt))
6153 vt = TypeManager.EnumToUnderlying (MemberType);
6155 if (!((vt == TypeManager.bool_type) ||
6156 (vt == TypeManager.sbyte_type) ||
6157 (vt == TypeManager.byte_type) ||
6158 (vt == TypeManager.short_type) ||
6159 (vt == TypeManager.ushort_type) ||
6160 (vt == TypeManager.int32_type) ||
6161 (vt == TypeManager.uint32_type) ||
6162 (vt == TypeManager.char_type) ||
6163 (vt == TypeManager.float_type) ||
6164 (!vt.IsValueType))){
6166 677, Location, Parent.MakeName (Name) +
6167 " A volatile field can not be of type `" +
6168 TypeManager.CSharpName (vt) + "'");
6173 if ((ModFlags & Modifiers.READONLY) != 0){
6176 "A field can not be both volatile and readonly");
6181 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6183 if (Parent.Kind == Kind.Struct &&
6184 ((fa & FieldAttributes.Static) == 0) &&
6185 MemberType == Parent.TypeBuilder &&
6186 !TypeManager.IsBuiltinType (MemberType)){
6187 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6188 "' causes a cycle in the structure layout");
6193 FieldBuilder = Parent.TypeBuilder.DefineField (
6194 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6196 TypeManager.RegisterFieldBase (FieldBuilder, this);
6198 catch (ArgumentException) {
6199 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6206 protected override bool VerifyClsCompliance (DeclSpace ds)
6208 if (!base.VerifyClsCompliance (ds))
6211 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6212 Report.Warning (3026, 1, Location, "CLS-compliant field '{0}' cannot be volatile", GetSignatureForError ());
6220 // `set' and `get' accessors are represented with an Accessor.
6222 public class Accessor {
6224 // Null if the accessor is empty, or a Block if not
6226 public const int AllowedModifiers =
6228 Modifiers.PROTECTED |
6229 Modifiers.INTERNAL |
6232 public ToplevelBlock Block;
6233 public Attributes Attributes;
6234 public Location Location;
6235 public int ModFlags;
6237 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6242 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6247 // Ooouh Martin, templates are missing here.
6248 // When it will be possible move here a lot of child code and template method type.
6249 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
6250 protected MethodData method_data;
6251 protected ToplevelBlock block;
6252 protected ListDictionary declarative_security;
6254 // The accessor are created event if they are not wanted.
6255 // But we need them because their names are reserved.
6256 // Field says whether accessor will be emited or not
6257 public readonly bool IsDummy;
6259 protected readonly string prefix;
6261 ReturnParameter return_attributes;
6263 public AbstractPropertyEventMethod (MemberBase member, string prefix)
6264 : base (null, SetupName (prefix, member), null, member.Location)
6266 this.prefix = prefix;
6270 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
6272 : base (null, SetupName (prefix, member),
6273 accessor.Attributes, accessor.Location)
6275 this.prefix = prefix;
6276 this.block = accessor.Block;
6279 static MemberName SetupName (string prefix, MemberBase member)
6281 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
6284 public void UpdateName (MemberBase member)
6286 SetMemberName (SetupName (prefix, member));
6289 #region IMethodData Members
6291 public ToplevelBlock Block {
6301 public CallingConventions CallingConventions {
6303 return CallingConventions.Standard;
6307 public bool IsExcluded (EmitContext ec)
6312 GenericMethod IMethodData.GenericMethod {
6318 public MemberName MethodName {
6324 public abstract ObsoleteAttribute GetObsoleteAttribute ();
6325 public abstract Type[] ParameterTypes { get; }
6326 public abstract Type ReturnType { get; }
6327 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
6331 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6333 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6334 a.Type == TypeManager.conditional_attribute_type) {
6335 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 ());
6339 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6340 if (declarative_security == null)
6341 declarative_security = new ListDictionary ();
6342 a.ExtractSecurityPermissionSet (declarative_security);
6346 if (a.Target == AttributeTargets.Method) {
6347 method_data.MethodBuilder.SetCustomAttribute (cb);
6351 if (a.Target == AttributeTargets.ReturnValue) {
6352 if (return_attributes == null)
6353 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6355 return_attributes.ApplyAttributeBuilder (a, cb);
6359 ApplyToExtraTarget (a, cb);
6362 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6364 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6367 public override bool Define()
6369 throw new NotSupportedException ();
6372 public virtual void Emit (TypeContainer container)
6374 EmitMethod (container);
6376 if (declarative_security != null) {
6377 foreach (DictionaryEntry de in declarative_security) {
6378 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6385 protected virtual void EmitMethod (TypeContainer container)
6387 method_data.Emit (container, this);
6390 public override bool IsClsCompliaceRequired(DeclSpace ds)
6395 public bool IsDuplicateImplementation (MethodCore method)
6397 if (Name != method.Name)
6400 Type[] param_types = method.ParameterTypes;
6402 if (param_types.Length != ParameterTypes.Length)
6405 for (int i = 0; i < param_types.Length; i++)
6406 if (param_types [i] != ParameterTypes [i])
6409 Report.SymbolRelatedToPreviousError (method);
6410 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with " +
6411 "the same parameter types", Parent.Name, Name);
6415 public override bool IsUsed
6425 public new Location Location {
6427 return base.Location;
6432 // Represents header string for documentation comment.
6434 public override string DocCommentHeader {
6435 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6438 protected override void VerifyObsoleteAttribute()
6445 // Properties and Indexers both generate PropertyBuilders, we use this to share
6446 // their common bits.
6448 abstract public class PropertyBase : MethodCore {
6450 public class GetMethod: PropertyMethod
6452 static string[] attribute_targets = new string [] { "method", "return" };
6454 public GetMethod (MethodCore method):
6455 base (method, "get_")
6459 public GetMethod (MethodCore method, Accessor accessor):
6460 base (method, accessor, "get_")
6464 public override MethodBuilder Define(TypeContainer container)
6466 base.Define (container);
6468 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
6470 if (!method_data.Define (container))
6473 return method_data.MethodBuilder;
6476 public override string GetSignatureForError (TypeContainer tc)
6478 return String.Concat (base.GetSignatureForError (tc), ".get");
6481 public override Type ReturnType {
6483 return method.MemberType;
6487 public override string[] ValidAttributeTargets {
6489 return attribute_targets;
6494 public class SetMethod: PropertyMethod {
6496 static string[] attribute_targets = new string [] { "method", "param", "return" };
6497 ImplicitParameter param_attr;
6499 public SetMethod (MethodCore method):
6500 base (method, "set_")
6504 public SetMethod (MethodCore method, Accessor accessor):
6505 base (method, accessor, "set_")
6509 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6511 if (a.Target == AttributeTargets.Parameter) {
6512 if (param_attr == null)
6513 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6515 param_attr.ApplyAttributeBuilder (a, cb);
6519 base.ApplyAttributeBuilder (a, cb);
6522 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
6524 Parameter [] parms = new Parameter [1];
6525 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
6526 Parameters parameters = new Parameters (parms, null, method.Location);
6528 bool old_unsafe = ec.InUnsafe;
6529 ec.InUnsafe = InUnsafe;
6530 Type [] types = parameters.GetParameterInfo (ec);
6531 ec.InUnsafe = old_unsafe;
6533 return new InternalParameters (types, parameters);
6536 public override MethodBuilder Define (TypeContainer container)
6538 if (container.EmitContext == null)
6539 throw new InternalErrorException ("SetMethod.Define called too early");
6541 base.Define (container);
6543 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6545 if (!method_data.Define (container))
6548 return method_data.MethodBuilder;
6551 public override string GetSignatureForError (TypeContainer tc)
6553 return String.Concat (base.GetSignatureForError (tc), ".set");
6556 public override Type[] ParameterTypes {
6558 return new Type[] { method.MemberType };
6562 public override Type ReturnType {
6564 return TypeManager.void_type;
6568 public override string[] ValidAttributeTargets {
6570 return attribute_targets;
6575 static string[] attribute_targets = new string [] { "property" };
6577 public abstract class PropertyMethod: AbstractPropertyEventMethod {
6578 protected readonly MethodCore method;
6579 protected MethodAttributes flags;
6581 public PropertyMethod (MethodCore method, string prefix)
6582 : base (method, prefix)
6584 this.method = method;
6585 Parent = method.Parent;
6588 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6589 : base (method, accessor, prefix)
6591 this.method = method;
6592 Parent = method.Parent;
6593 this.ModFlags = accessor.ModFlags;
6595 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6596 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
6600 public override AttributeTargets AttributeTargets {
6602 return AttributeTargets.Method;
6606 public override bool IsClsCompliaceRequired(DeclSpace ds)
6608 return method.IsClsCompliaceRequired (ds);
6611 public InternalParameters ParameterInfo
6614 return method_data.ParameterInfo;
6618 public virtual MethodBuilder Define (TypeContainer container)
6621 // Check for custom access modifier
6623 if (ModFlags == 0) {
6624 ModFlags = method.ModFlags;
6625 flags = method.flags;
6627 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6628 Report.Error (442, Location, "{0}': abstract properties cannot have private accessors", GetSignatureForError (container));
6631 CheckModifiers (container, ModFlags);
6632 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6633 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6634 flags = Modifiers.MethodAttr (ModFlags);
6635 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6642 public bool HasCustomAccessModifier
6645 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6649 public override Type[] ParameterTypes {
6651 return TypeManager.NoTypes;
6655 public override EmitContext CreateEmitContext (TypeContainer tc,
6658 return new EmitContext (
6659 tc, method.ds, method.Location, ig, ReturnType,
6660 method.ModFlags, false);
6663 public override ObsoleteAttribute GetObsoleteAttribute ()
6665 return method.GetObsoleteAttribute (method.ds);
6668 public override string GetSignatureForError (TypeContainer tc)
6670 return String.Concat (tc.Name, '.', method.Name);
6673 void CheckModifiers (TypeContainer container, int modflags)
6676 int mflags = method.ModFlags & Modifiers.Accessibility;
6678 if ((mflags & Modifiers.PUBLIC) != 0) {
6679 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6681 else if ((mflags & Modifiers.PROTECTED) != 0) {
6682 if ((mflags & Modifiers.INTERNAL) != 0)
6683 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6685 flags |= Modifiers.PRIVATE;
6687 else if ((mflags & Modifiers.INTERNAL) != 0)
6688 flags |= Modifiers.PRIVATE;
6690 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6691 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6692 GetSignatureForError (container));
6695 public override bool MarkForDuplicationCheck ()
6697 caching_flags |= Flags.TestMethodDuplication;
6702 public PropertyMethod Get, Set;
6703 public PropertyBuilder PropertyBuilder;
6704 public MethodBuilder GetBuilder, SetBuilder;
6706 protected EmitContext ec;
6708 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6709 int allowed_mod, bool is_iface, MemberName name,
6710 Parameters parameters, Attributes attrs,
6712 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6713 attrs, parameters, loc)
6717 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6719 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6720 a.Error_InvalidSecurityParent ();
6724 PropertyBuilder.SetCustomAttribute (cb);
6727 public override AttributeTargets AttributeTargets {
6729 return AttributeTargets.Property;
6733 public override bool Define ()
6738 if (!IsTypePermitted ())
6744 protected override bool DoDefine ()
6746 if (!base.DoDefine ())
6750 // Accessors modifiers check
6752 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6753 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6754 GetSignatureForError ());
6758 if ((Get.IsDummy || Set.IsDummy)
6759 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6760 Report.Error (276, Location,
6761 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6762 GetSignatureForError ());
6766 if (MemberType.IsAbstract && MemberType.IsSealed) {
6767 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6771 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6775 public override string GetSignatureForError()
6777 if (PropertyBuilder == null)
6778 return GetSignatureForError (Parent);
6780 return TypeManager.CSharpSignature (PropertyBuilder, false);
6783 protected override bool CheckForDuplications ()
6785 ArrayList ar = Parent.Indexers;
6787 int arLen = ar.Count;
6789 for (int i = 0; i < arLen; i++) {
6790 Indexer m = (Indexer) ar [i];
6791 if (IsDuplicateImplementation (m))
6796 ar = Parent.Properties;
6798 int arLen = ar.Count;
6800 for (int i = 0; i < arLen; i++) {
6801 Property m = (Property) ar [i];
6802 if (IsDuplicateImplementation (m))
6810 // TODO: rename to Resolve......
6811 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6813 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6814 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6816 if (base_property == null)
6819 base_ret_type = base_property.PropertyType;
6820 MethodInfo get_accessor = base_property.GetGetMethod (true);
6821 MethodInfo set_accessor = base_property.GetSetMethod (true);
6822 MethodAttributes get_accessor_access, set_accessor_access;
6824 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6825 if (Get != null && !Get.IsDummy && get_accessor == null) {
6826 Report.SymbolRelatedToPreviousError (base_property);
6827 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6830 if (Set != null && !Set.IsDummy && set_accessor == null) {
6831 Report.SymbolRelatedToPreviousError (base_property);
6832 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6837 // Check base class accessors access
6839 get_accessor_access = set_accessor_access = 0;
6840 if ((ModFlags & Modifiers.NEW) == 0) {
6841 if (get_accessor != null) {
6842 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6843 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6845 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6846 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6847 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6850 if (set_accessor != null) {
6851 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6852 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6854 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6855 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6856 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6861 // Get the less restrictive access
6863 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6866 public override void Emit ()
6869 // The PropertyBuilder can be null for explicit implementations, in that
6870 // case, we do not actually emit the ".property", so there is nowhere to
6871 // put the attribute
6873 if (PropertyBuilder != null && OptAttributes != null)
6874 OptAttributes.Emit (ec, this);
6886 /// Tests whether accessors are not in collision with some method (CS0111)
6888 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6890 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6893 public override bool IsUsed
6899 return Get.IsUsed | Set.IsUsed;
6903 protected override void SetMemberName (MemberName new_name)
6905 base.SetMemberName (new_name);
6907 Get.UpdateName (this);
6908 Set.UpdateName (this);
6911 public override string[] ValidAttributeTargets {
6913 return attribute_targets;
6918 // Represents header string for documentation comment.
6920 public override string DocCommentHeader {
6921 get { return "P:"; }
6925 public class Property : PropertyBase, IIteratorContainer {
6926 const int AllowedModifiers =
6929 Modifiers.PROTECTED |
6930 Modifiers.INTERNAL |
6934 Modifiers.OVERRIDE |
6935 Modifiers.ABSTRACT |
6938 Modifiers.METHOD_YIELDS |
6941 const int AllowedInterfaceModifiers =
6944 public Property (TypeContainer parent, Expression type, int mod_flags,
6945 bool is_iface, MemberName name, Attributes attrs,
6946 Accessor get_block, Accessor set_block, Location loc)
6947 : base (parent, type, mod_flags,
6948 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6949 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6952 if (get_block == null)
6953 Get = new GetMethod (this);
6955 Get = new GetMethod (this, get_block);
6957 if (set_block == null)
6958 Set = new SetMethod (this);
6960 Set = new SetMethod (this, set_block);
6963 public override bool Define ()
6965 if (!DoDefineBase ())
6968 if (!base.Define ())
6974 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6978 GetBuilder = Get.Define (Parent);
6979 if (GetBuilder == null)
6983 // Setup iterator if we are one
6985 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6986 Iterator iterator = new Iterator (
6987 Parent, "get", MemberType,
6989 ModFlags, Get.Block, Location);
6991 if (!iterator.DefineIterator ())
6993 Get.Block = iterator.Block;
6998 SetBuilder = Set.Define (Parent);
6999 if (SetBuilder == null)
7002 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
7005 // FIXME - PropertyAttributes.HasDefault ?
7007 PropertyAttributes prop_attr = PropertyAttributes.None;
7009 prop_attr |= PropertyAttributes.RTSpecialName |
7010 PropertyAttributes.SpecialName;
7012 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7013 Name, prop_attr, MemberType, null);
7016 PropertyBuilder.SetGetMethod (GetBuilder);
7019 PropertyBuilder.SetSetMethod (SetBuilder);
7021 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
7025 public void SetYields ()
7027 ModFlags |= Modifiers.METHOD_YIELDS;
7032 /// Gigantic workaround for lameness in SRE follows :
7033 /// This class derives from EventInfo and attempts to basically
7034 /// wrap around the EventBuilder so that FindMembers can quickly
7035 /// return this in it search for members
7037 public class MyEventBuilder : EventInfo {
7040 // We use this to "point" to our Builder which is
7041 // not really a MemberInfo
7043 EventBuilder MyBuilder;
7046 // We "catch" and wrap these methods
7048 MethodInfo raise, remove, add;
7050 EventAttributes attributes;
7051 Type declaring_type, reflected_type, event_type;
7056 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
7058 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
7060 // And now store the values in our own fields.
7062 declaring_type = type_builder;
7064 reflected_type = type_builder;
7066 attributes = event_attr;
7069 this.event_type = event_type;
7073 // Methods that you have to override. Note that you only need
7074 // to "implement" the variants that take the argument (those are
7075 // the "abstract" methods, the others (GetAddMethod()) are
7078 public override MethodInfo GetAddMethod (bool nonPublic)
7083 public override MethodInfo GetRemoveMethod (bool nonPublic)
7088 public override MethodInfo GetRaiseMethod (bool nonPublic)
7094 // These methods make "MyEventInfo" look like a Builder
7096 public void SetRaiseMethod (MethodBuilder raiseMethod)
7098 raise = raiseMethod;
7099 MyBuilder.SetRaiseMethod (raiseMethod);
7102 public void SetRemoveOnMethod (MethodBuilder removeMethod)
7104 remove = removeMethod;
7105 MyBuilder.SetRemoveOnMethod (removeMethod);
7108 public void SetAddOnMethod (MethodBuilder addMethod)
7111 MyBuilder.SetAddOnMethod (addMethod);
7114 public void SetCustomAttribute (CustomAttributeBuilder cb)
7116 MyBuilder.SetCustomAttribute (cb);
7119 public override object [] GetCustomAttributes (bool inherit)
7121 // FIXME : There's nothing which can be seemingly done here because
7122 // we have no way of getting at the custom attribute objects of the
7127 public override object [] GetCustomAttributes (Type t, bool inherit)
7129 // FIXME : Same here !
7133 public override bool IsDefined (Type t, bool b)
7138 public override EventAttributes Attributes {
7144 public override string Name {
7150 public override Type DeclaringType {
7152 return declaring_type;
7156 public override Type ReflectedType {
7158 return reflected_type;
7162 public Type EventType {
7168 public void SetUsed ()
7170 if (my_event != null) {
7171 my_event.status = FieldBase.Status.ASSIGNED;
7172 my_event.SetMemberIsUsed ();
7178 /// For case when event is declared like property (with add and remove accessors).
7180 public class EventProperty: Event {
7182 static string[] attribute_targets = new string [] { "event", "property" };
7184 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
7185 bool is_iface, MemberName name, Object init,
7186 Attributes attrs, Accessor add, Accessor remove,
7188 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
7190 Add = new AddDelegateMethod (this, add);
7191 Remove = new RemoveDelegateMethod (this, remove);
7193 // For this event syntax we don't report error CS0067
7194 // because it is hard to do it.
7198 public override string[] ValidAttributeTargets {
7200 return attribute_targets;
7206 /// Event is declared like field.
7208 public class EventField: Event {
7210 static string[] attribute_targets = new string [] { "event", "field", "method" };
7211 static string[] attribute_targets_interface = new string[] { "event", "method" };
7213 public EventField (TypeContainer parent, Expression type, int mod_flags,
7214 bool is_iface, MemberName name, Object init,
7215 Attributes attrs, Location loc)
7216 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
7218 Add = new AddDelegateMethod (this);
7219 Remove = new RemoveDelegateMethod (this);
7222 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7224 if (a.Target == AttributeTargets.Field) {
7225 FieldBuilder.SetCustomAttribute (cb);
7229 if (a.Target == AttributeTargets.Method) {
7230 Add.ApplyAttributeBuilder (a, cb);
7231 Remove.ApplyAttributeBuilder (a, cb);
7235 base.ApplyAttributeBuilder (a, cb);
7238 public override string[] ValidAttributeTargets {
7240 return IsInterface ? attribute_targets_interface : attribute_targets;
7245 public abstract class Event : FieldBase {
7247 protected sealed class AddDelegateMethod: DelegateMethod
7250 public AddDelegateMethod (Event method):
7251 base (method, "add_")
7255 public AddDelegateMethod (Event method, Accessor accessor):
7256 base (method, accessor, "add_")
7260 protected override MethodInfo DelegateMethodInfo {
7262 return TypeManager.delegate_combine_delegate_delegate;
7268 protected sealed class RemoveDelegateMethod: DelegateMethod
7270 public RemoveDelegateMethod (Event method):
7271 base (method, "remove_")
7275 public RemoveDelegateMethod (Event method, Accessor accessor):
7276 base (method, accessor, "remove_")
7280 protected override MethodInfo DelegateMethodInfo {
7282 return TypeManager.delegate_remove_delegate_delegate;
7288 public abstract class DelegateMethod: AbstractPropertyEventMethod
7290 protected readonly Event method;
7291 ImplicitParameter param_attr;
7293 static string[] attribute_targets = new string [] { "method", "param", "return" };
7295 public DelegateMethod (Event method, string prefix)
7296 : base (method, prefix)
7298 this.method = method;
7301 public DelegateMethod (Event method, Accessor accessor, string prefix)
7302 : base (method, accessor, prefix)
7304 this.method = method;
7307 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7309 if (a.Target == AttributeTargets.Parameter) {
7310 if (param_attr == null)
7311 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7313 param_attr.ApplyAttributeBuilder (a, cb);
7317 base.ApplyAttributeBuilder (a, cb);
7320 public override AttributeTargets AttributeTargets {
7322 return AttributeTargets.Method;
7326 public override bool IsClsCompliaceRequired(DeclSpace ds)
7328 return method.IsClsCompliaceRequired (ds);
7331 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
7333 method_data = new MethodData (method, ip, method.ModFlags,
7334 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7336 if (!method_data.Define (container))
7339 MethodBuilder mb = method_data.MethodBuilder;
7340 mb.DefineParameter (1, ParameterAttributes.None, "value");
7345 protected override void EmitMethod (TypeContainer tc)
7347 if (block != null) {
7348 base.EmitMethod (tc);
7352 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7355 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
7356 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
7358 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
7359 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7360 ig.Emit (OpCodes.Ldsfld, field_info);
7361 ig.Emit (OpCodes.Ldarg_0);
7362 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7363 ig.Emit (OpCodes.Castclass, method.MemberType);
7364 ig.Emit (OpCodes.Stsfld, field_info);
7366 ig.Emit (OpCodes.Ldarg_0);
7367 ig.Emit (OpCodes.Ldarg_0);
7368 ig.Emit (OpCodes.Ldfld, field_info);
7369 ig.Emit (OpCodes.Ldarg_1);
7370 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7371 ig.Emit (OpCodes.Castclass, method.MemberType);
7372 ig.Emit (OpCodes.Stfld, field_info);
7374 ig.Emit (OpCodes.Ret);
7377 protected abstract MethodInfo DelegateMethodInfo { get; }
7379 public override Type[] ParameterTypes {
7381 return new Type[] { method.MemberType };
7385 public override Type ReturnType {
7387 return TypeManager.void_type;
7391 public override EmitContext CreateEmitContext (TypeContainer tc,
7394 return new EmitContext (
7395 tc, method.Parent, Location, ig, ReturnType,
7396 method.ModFlags, false);
7399 public override string GetSignatureForError (TypeContainer tc)
7401 return String.Concat (tc.Name, '.', method.Name);
7404 public override ObsoleteAttribute GetObsoleteAttribute ()
7406 return method.GetObsoleteAttribute (method.Parent);
7409 public override string[] ValidAttributeTargets {
7411 return attribute_targets;
7417 const int AllowedModifiers =
7420 Modifiers.PROTECTED |
7421 Modifiers.INTERNAL |
7426 Modifiers.OVERRIDE |
7430 const int AllowedInterfaceModifiers =
7433 public DelegateMethod Add, Remove;
7434 public MyEventBuilder EventBuilder;
7435 public MethodBuilder AddBuilder, RemoveBuilder;
7437 MethodData AddData, RemoveData;
7439 public Event (TypeContainer parent, Expression type, int mod_flags,
7440 bool is_iface, MemberName name, Object init, Attributes attrs,
7442 : base (parent, type, mod_flags,
7443 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7444 name, init, attrs, loc)
7446 IsInterface = is_iface;
7449 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7451 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7452 a.Error_InvalidSecurityParent ();
7456 EventBuilder.SetCustomAttribute (cb);
7459 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7461 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7464 public override AttributeTargets AttributeTargets {
7466 return AttributeTargets.Event;
7470 public override bool Define ()
7472 EventAttributes e_attr;
7473 e_attr = EventAttributes.None;
7475 if (!DoDefineBase ())
7481 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
7482 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
7483 "': abstract event can not have an initializer");
7487 if (!TypeManager.IsDelegateType (MemberType)) {
7488 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
7489 "' : event must be of a delegate type");
7493 EmitContext ec = Parent.EmitContext;
7495 throw new InternalErrorException ("Event.Define called too early?");
7496 bool old_unsafe = ec.InUnsafe;
7497 ec.InUnsafe = InUnsafe;
7499 Parameter [] parms = new Parameter [1];
7500 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
7501 Parameters parameters = new Parameters (parms, null, Location);
7502 Type [] types = parameters.GetParameterInfo (ec);
7503 InternalParameters ip = new InternalParameters (types, parameters);
7505 ec.InUnsafe = old_unsafe;
7511 // Now define the accessors
7514 AddBuilder = Add.Define (Parent, ip);
7515 if (AddBuilder == null)
7518 RemoveBuilder = Remove.Define (Parent, ip);
7519 if (RemoveBuilder == null)
7522 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7524 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7525 FieldBuilder = Parent.TypeBuilder.DefineField (
7527 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7528 TypeManager.RegisterPrivateFieldOfEvent (
7529 (EventInfo) EventBuilder, FieldBuilder);
7530 TypeManager.RegisterFieldBase (FieldBuilder, this);
7533 EventBuilder.SetAddOnMethod (AddBuilder);
7534 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7536 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7540 protected override bool CheckBase ()
7542 if (!base.CheckBase ())
7545 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7546 if (!(conflict_symbol is EventInfo)) {
7547 Report.SymbolRelatedToPreviousError (conflict_symbol);
7548 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
7556 public override void Emit ()
7558 if (OptAttributes != null) {
7559 EmitContext ec = new EmitContext (
7560 Parent, Location, null, MemberType, ModFlags);
7561 OptAttributes.Emit (ec, this);
7565 Remove.Emit (Parent);
7570 public override string GetSignatureForError ()
7572 if (EventBuilder == null)
7573 return base.GetSignatureForError (Parent);
7575 return TypeManager.GetFullNameSignature (EventBuilder);
7579 // Represents header string for documentation comment.
7581 public override string DocCommentHeader {
7582 get { return "E:"; }
7587 public class Indexer : PropertyBase {
7589 class GetIndexerMethod: GetMethod
7591 public GetIndexerMethod (MethodCore method):
7596 public GetIndexerMethod (MethodCore method, Accessor accessor):
7597 base (method, accessor)
7601 // TODO: one GetSignatureForError is enough (reuse Parent member)
7602 public override string GetSignatureForError (TypeContainer tc)
7604 string core = base.GetSignatureForError (tc);
7605 return core.Replace (TypeContainer.DefaultIndexerName,
7606 String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
7609 public override Type[] ParameterTypes {
7611 return method.ParameterTypes;
7616 class SetIndexerMethod: SetMethod
7618 readonly Parameters parameters;
7620 public SetIndexerMethod (MethodCore method):
7625 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7626 base (method, accessor)
7628 this.parameters = parameters;
7631 public override Type[] ParameterTypes {
7633 int top = method.ParameterTypes.Length;
7634 Type [] set_pars = new Type [top + 1];
7635 method.ParameterTypes.CopyTo (set_pars, 0);
7636 set_pars [top] = method.MemberType;
7641 protected override InternalParameters GetParameterInfo (EmitContext ec)
7643 Parameter [] fixed_parms = parameters.FixedParameters;
7645 if (fixed_parms == null){
7646 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7647 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7648 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7650 // Here is the problem: the `value' parameter has
7651 // to come *after* the array parameter in the declaration
7653 // X (object [] x, Type value)
7656 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7657 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7661 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7663 fixed_parms.CopyTo (tmp, 0);
7664 tmp [fixed_parms.Length] = new Parameter (
7665 method.Type, "value", Parameter.Modifier.NONE, null);
7667 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7668 Type [] types = set_formal_params.GetParameterInfo (ec);
7670 return new InternalParameters (types, set_formal_params);
7674 const int AllowedModifiers =
7677 Modifiers.PROTECTED |
7678 Modifiers.INTERNAL |
7682 Modifiers.OVERRIDE |
7687 const int AllowedInterfaceModifiers =
7691 // Are we implementing an interface ?
7693 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7694 bool is_iface, Parameters parameters, Attributes attrs,
7695 Accessor get_block, Accessor set_block, Location loc)
7696 : base (parent, type, mod,
7697 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7698 is_iface, name, parameters, attrs, loc)
7700 if (get_block == null)
7701 Get = new GetIndexerMethod (this);
7703 Get = new GetIndexerMethod (this, get_block);
7705 if (set_block == null)
7706 Set = new SetIndexerMethod (this);
7708 Set = new SetIndexerMethod (this, parameters, set_block);
7711 public override bool Define ()
7713 PropertyAttributes prop_attr =
7714 PropertyAttributes.RTSpecialName |
7715 PropertyAttributes.SpecialName;
7717 if (!DoDefineBase ())
7720 if (!base.Define ())
7723 if (MemberType == TypeManager.void_type) {
7724 Report.Error (620, Location, "Indexers cannot have void type");
7728 if (OptAttributes != null) {
7729 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7730 if (indexer_attr != null) {
7731 // Remove the attribute from the list because it is not emitted
7732 OptAttributes.Attrs.Remove (indexer_attr);
7734 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7736 if (IsExplicitImpl) {
7737 Report.Error (415, indexer_attr.Location,
7738 "The 'IndexerName' attribute is valid only on an " +
7739 "indexer that is not an explicit interface member declaration");
7743 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7744 Report.Error (609, indexer_attr.Location,
7745 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7749 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7750 Report.Error (633, indexer_attr.Location,
7751 "The argument to the 'IndexerName' attribute must be a valid identifier");
7757 if (InterfaceType != null) {
7758 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7759 if (base_IndexerName != Name)
7760 ShortName = base_IndexerName;
7763 if (!Parent.AddToMemberContainer (this) ||
7764 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7770 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7772 GetBuilder = Get.Define (Parent);
7773 if (GetBuilder == null)
7778 SetBuilder = Set.Define (Parent);
7779 if (SetBuilder == null)
7784 // Now name the parameters
7786 Parameter [] p = Parameters.FixedParameters;
7788 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7789 Report.Error (631, Location, "ref and out are not valid in this context");
7795 for (i = 0; i < p.Length; ++i) {
7797 GetBuilder.DefineParameter (
7798 i + 1, p [i].Attributes, p [i].Name);
7801 SetBuilder.DefineParameter (
7802 i + 1, p [i].Attributes, p [i].Name);
7806 SetBuilder.DefineParameter (
7807 i + 1, ParameterAttributes.None, "value");
7809 if (i != ParameterTypes.Length) {
7810 Parameter array_param = Parameters.ArrayParameter;
7812 SetBuilder.DefineParameter (
7813 i + 1, array_param.Attributes, array_param.Name);
7817 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7818 Name, prop_attr, MemberType, ParameterTypes);
7821 PropertyBuilder.SetGetMethod (GetBuilder);
7824 PropertyBuilder.SetSetMethod (SetBuilder);
7826 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7831 public override string GetSignatureForError ()
7833 if (PropertyBuilder == null)
7834 return GetSignatureForError (Parent);
7836 return TypeManager.CSharpSignature (PropertyBuilder, true);
7839 public override string GetSignatureForError(TypeContainer tc)
7841 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7844 public override bool MarkForDuplicationCheck ()
7846 caching_flags |= Flags.TestMethodDuplication;
7852 public class Operator : MethodCore, IIteratorContainer {
7854 const int AllowedModifiers =
7860 public enum OpType : byte {
7870 // Unary and Binary operators
7893 // Implicit and Explicit
7898 public readonly OpType OperatorType;
7899 public MethodBuilder OperatorMethodBuilder;
7901 public Method OperatorMethod;
7903 static string[] attribute_targets = new string [] { "method", "return" };
7905 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7906 int mod_flags, Parameters parameters,
7907 ToplevelBlock block, Attributes attrs, Location loc)
7908 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7909 new MemberName ("op_" + type), attrs, parameters, loc)
7911 OperatorType = type;
7915 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7917 OperatorMethod.ApplyAttributeBuilder (a, cb);
7920 public override AttributeTargets AttributeTargets {
7922 return AttributeTargets.Method;
7926 protected override bool CheckGenericOverride (MethodInfo method, string name)
7931 protected override bool CheckForDuplications()
7933 ArrayList ar = Parent.Operators;
7935 int arLen = ar.Count;
7937 for (int i = 0; i < arLen; i++) {
7938 Operator o = (Operator) ar [i];
7939 if (IsDuplicateImplementation (o))
7944 ar = Parent.Methods;
7946 int arLen = ar.Count;
7948 for (int i = 0; i < arLen; i++) {
7949 Method m = (Method) ar [i];
7950 if (IsDuplicateImplementation (m))
7958 public override bool Define ()
7960 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7961 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7962 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7969 if (MemberType == TypeManager.void_type) {
7970 Report.Error (590, Location, "User-defined operators cannot return void");
7974 OperatorMethod = new Method (
7975 Parent, null, Type, ModFlags, false, MemberName,
7976 Parameters, OptAttributes, Location);
7978 OperatorMethod.Block = Block;
7979 OperatorMethod.IsOperator = true;
7980 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7981 OperatorMethod.Define ();
7983 if (OperatorMethod.MethodBuilder == null)
7986 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7988 parameter_types = OperatorMethod.ParameterTypes;
7989 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7990 Type return_type = OperatorMethod.ReturnType;
7991 Type first_arg_type = parameter_types [0];
7996 // Rules for conversion operators
7998 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7999 if (first_arg_type == return_type && first_arg_type == declaring_type){
8002 "User-defined conversion cannot take an object of the " +
8003 "enclosing type and convert to an object of the enclosing" +
8008 if (first_arg_type != declaring_type && return_type != declaring_type){
8011 "User-defined conversion must convert to or from the " +
8016 if (first_arg_type == TypeManager.object_type ||
8017 return_type == TypeManager.object_type){
8020 "User-defined conversion cannot convert to or from " +
8025 if (first_arg_type.IsInterface || return_type.IsInterface){
8028 "User-defined conversion cannot convert to or from an " +
8033 if (first_arg_type.IsSubclassOf (return_type)
8034 || return_type.IsSubclassOf (first_arg_type)){
8035 if (declaring_type.IsSubclassOf (return_type)) {
8036 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
8039 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
8042 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
8043 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
8044 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");
8047 } else if (Parameters.FixedParameters.Length == 1) {
8048 // Checks for Unary operators
8050 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
8051 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
8052 Report.Error (448, Location,
8053 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
8056 if (first_arg_type != declaring_type){
8058 559, Location, "The parameter type for ++ or -- operator must be the containing type");
8063 if (first_arg_type != declaring_type){
8066 "The parameter of a unary operator must be the " +
8071 if (OperatorType == OpType.True || OperatorType == OpType.False) {
8072 if (return_type != TypeManager.bool_type){
8075 "The return type of operator True or False " +
8082 if (OperatorType == OpType.BitwiseAnd &&
8083 (first_arg_type != return_type || first_arg_type != parameter_types [1])) {
8084 Report.Error (217, Location, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
8085 "must have the same return type as the type of its 2 parameters", GetSignatureForError ());
8089 // Checks for Binary operators
8091 if (first_arg_type != declaring_type &&
8092 parameter_types [1] != declaring_type){
8095 "One of the parameters of a binary operator must " +
8096 "be the containing type");
8104 public override void Emit ()
8107 // abstract or extern methods have no bodies
8109 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
8112 OperatorMethod.Emit ();
8116 // Operator cannot be override
8117 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
8122 public static string GetName (OpType ot)
8125 case OpType.LogicalNot:
8127 case OpType.OnesComplement:
8129 case OpType.Increment:
8131 case OpType.Decrement:
8137 case OpType.Addition:
8139 case OpType.Subtraction:
8141 case OpType.UnaryPlus:
8143 case OpType.UnaryNegation:
8145 case OpType.Multiply:
8147 case OpType.Division:
8149 case OpType.Modulus:
8151 case OpType.BitwiseAnd:
8153 case OpType.BitwiseOr:
8155 case OpType.ExclusiveOr:
8157 case OpType.LeftShift:
8159 case OpType.RightShift:
8161 case OpType.Equality:
8163 case OpType.Inequality:
8165 case OpType.GreaterThan:
8167 case OpType.LessThan:
8169 case OpType.GreaterThanOrEqual:
8171 case OpType.LessThanOrEqual:
8173 case OpType.Implicit:
8175 case OpType.Explicit:
8181 public override string GetSignatureForError (TypeContainer tc)
8183 StringBuilder sb = new StringBuilder ();
8184 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
8185 Parameters.FixedParameters [0].GetSignatureForError ());
8187 if (Parameters.FixedParameters.Length > 1) {
8189 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
8192 return sb.ToString ();
8195 public override string GetSignatureForError ()
8200 public override bool MarkForDuplicationCheck ()
8202 caching_flags |= Flags.TestMethodDuplication;
8206 public override string ToString ()
8208 if (OperatorMethod == null)
8211 Type return_type = OperatorMethod.ReturnType;
8212 Type [] param_types = OperatorMethod.ParameterTypes;
8214 if (Parameters.FixedParameters.Length == 1)
8215 return String.Format (
8216 "{0} operator {1}({2})",
8217 TypeManager.CSharpName (return_type),
8218 GetName (OperatorType),
8221 return String.Format (
8222 "{0} operator {1}({2}, {3})",
8223 TypeManager.CSharpName (return_type),
8224 GetName (OperatorType),
8225 param_types [0], param_types [1]);
8228 public override string[] ValidAttributeTargets {
8230 return attribute_targets;
8234 public void SetYields ()
8236 ModFlags |= Modifiers.METHOD_YIELDS;
8241 // This is used to compare method signatures
8243 struct MethodSignature {
8245 public Type RetType;
8246 public Type [] Parameters;
8249 /// This delegate is used to extract methods which have the
8250 /// same signature as the argument
8252 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8254 public MethodSignature (string name, Type ret_type, Type [] parameters)
8259 if (parameters == null)
8260 Parameters = TypeManager.NoTypes;
8262 Parameters = parameters;
8265 public override string ToString ()
8268 if (Parameters.Length != 0){
8269 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8270 for (int i = 0; i < Parameters.Length; i++){
8271 sb.Append (Parameters [i]);
8272 if (i+1 < Parameters.Length)
8275 pars = sb.ToString ();
8278 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8281 public override int GetHashCode ()
8283 return Name.GetHashCode ();
8286 public override bool Equals (Object o)
8288 MethodSignature other = (MethodSignature) o;
8290 if (other.Name != Name)
8293 if (other.RetType != RetType)
8296 if (Parameters == null){
8297 if (other.Parameters == null)
8302 if (other.Parameters == null)
8305 int c = Parameters.Length;
8306 if (other.Parameters.Length != c)
8309 for (int i = 0; i < c; i++)
8310 if (other.Parameters [i] != Parameters [i])
8316 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8318 MethodSignature sig = (MethodSignature) filter_criteria;
8320 if (m.Name != sig.Name)
8324 MethodInfo mi = m as MethodInfo;
8325 PropertyInfo pi = m as PropertyInfo;
8328 ReturnType = mi.ReturnType;
8329 else if (pi != null)
8330 ReturnType = pi.PropertyType;
8335 // we use sig.RetType == null to mean `do not check the
8336 // method return value.
8338 if (sig.RetType != null)
8339 if (ReturnType != sig.RetType)
8344 args = TypeManager.GetArgumentTypes (mi);
8346 args = TypeManager.GetArgumentTypes (pi);
8347 Type [] sigp = sig.Parameters;
8349 if (args.Length != sigp.Length)
8352 for (int i = args.Length; i > 0; ){
8354 if (args [i] != sigp [i])