2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
36 using System.Collections;
37 using System.Collections.Specialized;
38 using System.Reflection;
39 using System.Reflection.Emit;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42 using System.Security;
43 using System.Security.Permissions;
46 using Mono.CompilerServices.SymbolWriter;
48 namespace Mono.CSharp {
58 /// This is the base class for structs and classes.
60 public abstract class TypeContainer : DeclSpace, IMemberContainer {
62 public class MemberCoreArrayList: ArrayList
65 /// Defines the MemberCore objects that are in this array
67 public virtual void DefineContainerMembers ()
69 foreach (MemberCore mc in this) {
74 public virtual void Emit ()
76 foreach (MemberCore mc in this)
81 public class MethodArrayList: MemberCoreArrayList
89 CachedMethods cached_method;
90 TypeContainer container;
92 public MethodArrayList (TypeContainer container)
94 this.container = container;
98 /// Method container contains Equals method
100 public bool HasEquals {
102 cached_method |= CachedMethods.Equals;
106 return (cached_method & CachedMethods.Equals) != 0;
111 /// Method container contains GetHashCode method
113 public bool HasGetHashCode {
115 cached_method |= CachedMethods.GetHashCode;
119 return (cached_method & CachedMethods.GetHashCode) != 0;
123 public override void DefineContainerMembers ()
125 base.DefineContainerMembers ();
127 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
128 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
134 public sealed class IndexerArrayList: MemberCoreArrayList
137 /// The indexer name for this container
139 public string IndexerName = DefaultIndexerName;
141 bool seen_normal_indexers = false;
143 TypeContainer container;
145 public IndexerArrayList (TypeContainer container)
147 this.container = container;
151 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
152 /// class is consistent. Either it is `Item' or it is the name defined by all the
153 /// indexers with the `IndexerName' attribute.
155 /// Turns out that the IndexerNameAttribute is applied to each indexer,
156 /// but it is never emitted, instead a DefaultMember attribute is attached
159 public override void DefineContainerMembers()
161 base.DefineContainerMembers ();
163 string class_indexer_name = null;
166 // If there's both an explicit and an implicit interface implementation, the
167 // explicit one actually implements the interface while the other one is just
168 // a normal indexer. See bug #37714.
171 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
172 foreach (Indexer i in this) {
173 if (i.InterfaceType != null) {
174 if (seen_normal_indexers)
175 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
179 seen_normal_indexers = true;
181 if (class_indexer_name == null) {
182 class_indexer_name = i.ShortName;
186 if (i.ShortName != class_indexer_name)
187 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
190 if (class_indexer_name != null)
191 IndexerName = class_indexer_name;
194 public override void Emit ()
198 if (!seen_normal_indexers)
201 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
202 container.TypeBuilder.SetCustomAttribute (cb);
206 public class OperatorArrayList: MemberCoreArrayList
208 TypeContainer container;
210 public OperatorArrayList (TypeContainer container)
212 this.container = container;
216 // Operator pair checking
221 public Type ret_type;
222 public Type type1, type2;
224 public Operator.OpType ot;
226 public OperatorEntry (int f, Operator o)
230 ret_type = o.OperatorMethod.ReturnType;
231 Type [] pt = o.OperatorMethod.ParameterTypes;
238 public override int GetHashCode ()
240 return ret_type.GetHashCode ();
243 public override bool Equals (object o)
245 OperatorEntry other = (OperatorEntry) o;
247 if (other.ret_type != ret_type)
249 if (other.type1 != type1)
251 if (other.type2 != type2)
258 // Checks that some operators come in pairs:
264 // They are matched based on the return type and the argument types
266 void CheckPairedOperators ()
268 Hashtable pairs = new Hashtable (null, null);
269 Operator true_op = null;
270 Operator false_op = null;
271 bool has_equality_or_inequality = false;
273 // Register all the operators we care about.
274 foreach (Operator op in this){
277 // Skip erroneous code.
278 if (op.OperatorMethod == null)
281 switch (op.OperatorType){
282 case Operator.OpType.Equality:
284 has_equality_or_inequality = true;
286 case Operator.OpType.Inequality:
288 has_equality_or_inequality = true;
291 case Operator.OpType.True:
294 case Operator.OpType.False:
298 case Operator.OpType.GreaterThan:
300 case Operator.OpType.LessThan:
303 case Operator.OpType.GreaterThanOrEqual:
305 case Operator.OpType.LessThanOrEqual:
311 OperatorEntry oe = new OperatorEntry (reg, op);
313 object o = pairs [oe];
317 oe = (OperatorEntry) o;
322 if (true_op != null){
323 if (false_op == null)
324 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
325 } else if (false_op != null)
326 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
329 // Look for the mistakes.
331 foreach (DictionaryEntry de in pairs){
332 OperatorEntry oe = (OperatorEntry) de.Key;
339 case Operator.OpType.Equality:
342 case Operator.OpType.Inequality:
345 case Operator.OpType.GreaterThan:
348 case Operator.OpType.LessThan:
351 case Operator.OpType.GreaterThanOrEqual:
354 case Operator.OpType.LessThanOrEqual:
358 Report.Error (216, oe.op.Location,
359 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
362 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
363 if (container.Methods == null || !container.Methods.HasEquals)
364 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
366 if (container.Methods == null || !container.Methods.HasGetHashCode)
367 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
371 public override void DefineContainerMembers ()
373 base.DefineContainerMembers ();
374 CheckPairedOperators ();
379 // Whether this is a struct, class or interface
380 public readonly Kind Kind;
382 // Holds a list of classes and structures
385 // Holds the list of properties
386 MemberCoreArrayList properties;
388 // Holds the list of enumerations
389 MemberCoreArrayList enums;
391 // Holds the list of delegates
392 MemberCoreArrayList delegates;
394 // Holds the list of constructors
395 protected MemberCoreArrayList instance_constructors;
397 // Holds the list of fields
398 MemberCoreArrayList fields;
400 // Holds a list of fields that have initializers
401 protected ArrayList initialized_fields;
403 // Holds a list of static fields that have initializers
404 protected ArrayList initialized_static_fields;
406 // Holds the list of constants
407 MemberCoreArrayList constants;
410 MemberCoreArrayList interfaces;
412 // Holds the methods.
413 MethodArrayList methods;
416 protected MemberCoreArrayList events;
418 // Holds the indexers
419 IndexerArrayList indexers;
421 // Holds the operators
422 MemberCoreArrayList operators;
424 // Holds the iterators
427 // Holds the parts of a partial class;
431 // Pointers to the default constructor and the default static constructor
433 protected Constructor default_constructor;
434 protected Constructor default_static_constructor;
437 // Whether we have at least one non-static field
439 bool have_nonstatic_fields = false;
442 // This one is computed after we can distinguish interfaces
443 // from classes from the arraylist `type_bases'
445 string base_class_name;
447 TypeExpr[] iface_exprs;
449 ArrayList type_bases;
451 bool members_defined;
452 bool members_defined_ok;
454 // The interfaces we implement.
455 protected Type[] ifaces;
456 protected Type ptype;
458 // The base member cache and our member cache
459 MemberCache base_cache;
460 MemberCache member_cache;
462 public const string DefaultIndexerName = "Item";
465 GenericTypeParameterBuilder[] gen_params;
467 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
468 Attributes attrs, Kind kind, Location l)
469 : base (ns, parent, name, attrs, l)
471 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
472 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
476 types = new ArrayList ();
478 base_class_name = null;
481 public bool AddToMemberContainer (MemberCore symbol)
483 return AddToContainer (symbol, symbol.Name);
486 bool AddToTypeContainer (DeclSpace ds)
488 // Parent == null ==> this == RootContext.Tree.Types
489 return AddToContainer (ds, (Parent == null) ? ds.Name : ds.Basename);
492 public void AddConstant (Const constant)
494 if (!AddToMemberContainer (constant))
497 if (constants == null)
498 constants = new MemberCoreArrayList ();
500 constants.Add (constant);
503 public void AddEnum (Mono.CSharp.Enum e)
505 if (!AddToTypeContainer (e))
509 enums = new MemberCoreArrayList ();
514 public void AddClassOrStruct (TypeContainer c)
516 if (!AddToTypeContainer (c))
522 public void AddDelegate (Delegate d)
524 if (!AddToTypeContainer (d))
527 if (delegates == null)
528 delegates = new MemberCoreArrayList ();
533 public void AddMethod (Method method)
535 if (!AddToMemberContainer (method))
539 methods = new MethodArrayList (this);
541 if (method.MemberName.Left != null)
542 methods.Insert (0, method);
544 methods.Add (method);
547 public void AddConstructor (Constructor c)
549 if (c.Name != MemberName.Name) {
550 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
553 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
556 if (default_static_constructor != null) {
557 Report.SymbolRelatedToPreviousError (default_static_constructor);
558 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
559 "called '{1}' with the same parameter types", Name, c.Name);
563 default_static_constructor = c;
566 if (default_constructor != null) {
567 Report.SymbolRelatedToPreviousError (default_constructor);
568 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
569 "called '{1}' with the same parameter types", Name, c.Name);
572 default_constructor = c;
575 if (instance_constructors == null)
576 instance_constructors = new MemberCoreArrayList ();
578 instance_constructors.Add (c);
582 public void AddInterface (TypeContainer iface)
584 if (!AddToTypeContainer (iface))
587 if (interfaces == null) {
588 interfaces = new MemberCoreArrayList ();
591 interfaces.Add (iface);
594 public void AddField (FieldMember field)
596 if (!AddToMemberContainer (field))
600 fields = new MemberCoreArrayList ();
604 if (field.HasInitializer)
605 RegisterFieldForInitialization (field);
607 if ((field.ModFlags & Modifiers.STATIC) == 0)
608 have_nonstatic_fields = true;
611 public void AddProperty (Property prop)
613 if (!AddToMemberContainer (prop) ||
614 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
617 if (properties == null)
618 properties = new MemberCoreArrayList ();
620 if (prop.MemberName.Left != null)
621 properties.Insert (0, prop);
623 properties.Add (prop);
626 public void AddEvent (Event e)
628 if (!AddToMemberContainer (e))
631 if (e is EventProperty) {
632 if (!AddToMemberContainer (e.Add))
635 if (!AddToMemberContainer (e.Remove))
640 events = new MemberCoreArrayList ();
646 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
648 public void AddIndexer (Indexer i)
650 if (indexers == null)
651 indexers = new IndexerArrayList (this);
653 if (i.IsExplicitImpl)
654 indexers.Insert (0, i);
659 public void AddOperator (Operator op)
661 if (!AddToMemberContainer (op))
664 if (operators == null)
665 operators = new OperatorArrayList (this);
670 public void AddIterator (Iterator i)
672 if (iterators == null)
673 iterators = new ArrayList ();
678 public void AddType (TypeContainer tc)
683 public void AddPart (ClassPart part)
686 parts = new ArrayList ();
691 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
693 if (a.Type == TypeManager.default_member_type) {
694 if (Indexers != null) {
695 Report.Error (646, a.Location,
696 "Cannot specify the DefaultMember attribute on" +
697 " a type containing an indexer");
702 base.ApplyAttributeBuilder (a, cb);
705 public override AttributeTargets AttributeTargets {
709 return AttributeTargets.Class;
711 return AttributeTargets.Struct;
713 return AttributeTargets.Interface;
715 throw new NotSupportedException ();
720 public ArrayList Types {
726 public MethodArrayList Methods {
732 public ArrayList Constants {
738 public ArrayList Interfaces {
744 public ArrayList Iterators {
752 return base_class_name;
756 public ArrayList Bases {
766 public ArrayList Fields {
772 public ArrayList InstanceConstructors {
774 return instance_constructors;
778 public ArrayList Properties {
784 public ArrayList Events {
790 public ArrayList Enums {
796 public ArrayList Indexers {
802 public ArrayList Operators {
808 public ArrayList Delegates {
814 public ArrayList Parts {
820 protected override TypeAttributes TypeAttr {
822 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
826 public string IndexerName {
828 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
832 public virtual void RegisterFieldForInitialization (FieldMember field)
834 if ((field.ModFlags & Modifiers.STATIC) != 0){
835 if (initialized_static_fields == null)
836 initialized_static_fields = new ArrayList ();
838 initialized_static_fields.Add (field);
840 if (initialized_fields == null)
841 initialized_fields = new ArrayList ();
843 initialized_fields.Add (field);
848 // Emits the instance field initializers
850 public virtual bool EmitFieldInitializers (EmitContext ec)
853 Expression instance_expr;
856 fields = initialized_static_fields;
857 instance_expr = null;
859 fields = initialized_fields;
860 instance_expr = new This (Location.Null).Resolve (ec);
866 foreach (FieldMember f in fields){
867 Expression e = f.GetInitializerExpression (ec);
871 Location l = f.Location;
872 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
873 fe.InstanceExpression = instance_expr;
875 ExpressionStatement a = new Assign (fe, e, l);
877 a = a.ResolveStatement (ec);
881 Constant c = e as Constant;
883 if (c.IsDefaultValue)
887 a.EmitStatement (ec);
894 // Defines the default constructors
896 protected void DefineDefaultConstructor (bool is_static)
900 // The default constructor is public
901 // If the class is abstract, the default constructor is protected
902 // The default static constructor is private
904 int mods = Modifiers.PUBLIC;
906 mods = Modifiers.STATIC | Modifiers.PRIVATE;
907 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
908 mods = Modifiers.PROTECTED;
910 TypeContainer constructor_parent = this;
912 constructor_parent = (TypeContainer) Parts [0];
914 c = new Constructor (constructor_parent, MemberName.Name, mods,
915 Parameters.EmptyReadOnlyParameters,
916 new ConstructorBaseInitializer (null, Location),
921 c.Block = new ToplevelBlock (null, Location);
926 /// The pending methods that need to be implemented
927 // (interfaces or abstract methods)
929 public PendingImplementation Pending;
931 public abstract PendingImplementation GetPendingImplementations ();
933 TypeExpr[] GetPartialBases (out TypeExpr base_class)
935 ArrayList ifaces = new ArrayList ();
938 Location base_loc = Location.Null;
940 foreach (ClassPart part in parts) {
941 TypeExpr new_base_class;
942 TypeExpr[] new_ifaces;
944 new_ifaces = part.GetClassBases (out new_base_class);
945 if (new_ifaces == null && base_type != null)
948 if ((base_class != null) && (new_base_class != null) &&
949 !base_class.Equals (new_base_class)) {
950 Report.Error (263, part.Location,
951 "Partial declarations of `{0}' must " +
952 "not specify different base classes",
955 if (!Location.IsNull (base_loc))
956 Report.LocationOfPreviousError (base_loc);
961 if ((base_class == null) && (new_base_class != null)) {
962 base_class = new_base_class;
963 base_loc = part.Location;
966 if (new_ifaces == null)
969 foreach (TypeExpr iface in new_ifaces) {
971 foreach (TypeExpr old_iface in ifaces) {
972 if (old_iface.Equals (iface)) {
983 TypeExpr[] retval = new TypeExpr [ifaces.Count];
984 ifaces.CopyTo (retval, 0);
988 TypeExpr[] GetNormalBases (out TypeExpr base_class)
992 int count = Bases.Count;
995 if (Kind == Kind.Class){
996 TypeExpr name = ResolveBaseTypeExpr (
997 (Expression) Bases [0], false, Location);
1003 if (!name.IsInterface) {
1004 // base_class could be a class, struct, enum, delegate.
1005 // This is validated in GetClassBases.
1011 TypeExpr [] ifaces = new TypeExpr [count-start];
1013 for (i = start, j = 0; i < count; i++, j++){
1014 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1015 if (resolved == null) {
1019 ifaces [j] = resolved;
1026 /// This function computes the Base class and also the
1027 /// list of interfaces that the class or struct @c implements.
1029 /// The return value is an array (might be null) of
1030 /// interfaces implemented (as Types).
1032 /// The @base_class argument is set to the base object or null
1033 /// if this is `System.Object'.
1035 TypeExpr [] GetClassBases (out TypeExpr base_class)
1042 ifaces = GetPartialBases (out base_class);
1043 else if (Bases == null){
1047 ifaces = GetNormalBases (out base_class);
1052 if ((base_class != null) && (Kind == Kind.Class)){
1053 if (base_class is TypeParameterExpr){
1055 689, base_class.Location,
1056 "Type parameter `{0}' can not be used as a " +
1057 "base class or interface", base_class.Name);
1062 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1063 Report.Error (1521, base_class.Location, "Invalid base type");
1067 if (base_class.IsSealed){
1068 Report.SymbolRelatedToPreviousError (base_class.Type);
1069 if (base_class.Type.IsAbstract) {
1070 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1072 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1077 if (!base_class.CanInheritFrom ()){
1078 Report.Error (644, Location,
1079 "`{0}' cannot inherit from special class `{1}'",
1080 Name, base_class.Name);
1084 if (!base_class.AsAccessible (this, ModFlags)) {
1085 Report.SymbolRelatedToPreviousError (base_class.Type);
1086 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1087 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1091 if (base_class != null)
1092 base_class_name = base_class.Name;
1097 int count = ifaces != null ? ifaces.Length : 0;
1099 for (i = 0; i < count; i++) {
1100 TypeExpr iface = (TypeExpr) ifaces [i];
1102 if (!iface.IsInterface) {
1103 if (Kind != Kind.Class) {
1104 // TODO: location of symbol related ....
1105 Error_TypeInListIsNotInterface (Location, iface.FullName);
1107 else if (base_class != null)
1108 Report.Error (1721, Location,
1109 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1112 Report.Error (1722, Location,
1113 "In Class `{0}', `{1}' is not " +
1114 "an interface, a base class must be listed first", Name, iface.Name);
1119 for (int x = 0; x < i; x++) {
1120 if (iface.Equals (ifaces [x])) {
1121 Report.Error (528, Location,
1122 "`{0}' is already listed in " +
1123 "interface list", iface.Name);
1128 if ((Kind == Kind.Interface) &&
1129 !iface.AsAccessible (Parent, ModFlags)) {
1130 Report.Error (61, Location,
1131 "Inconsistent accessibility: base " +
1132 "interface `{0}' is less accessible " +
1133 "than interface `{1}'", iface.Name,
1141 bool CheckGenericInterfaces (Type[] ifaces)
1143 ArrayList already_checked = new ArrayList ();
1145 for (int i = 0; i < ifaces.Length; i++) {
1146 Type iface = ifaces [i];
1147 foreach (Type t in already_checked) {
1151 Type[] infered = new Type [CountTypeParameters];
1152 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1157 "`{0}' cannot implement both `{1}' and `{2}' " +
1158 "because they may unify for some type " +
1159 "parameter substitutions",
1160 TypeManager.GetFullName (TypeBuilder),
1165 already_checked.Add (iface);
1173 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1175 Report.Error (527, loc, "'{0}': type in interface list is not an interface", type);
1179 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1181 public override TypeBuilder DefineType ()
1186 if (TypeBuilder != null)
1189 TypeAttributes type_attributes = TypeAttr;
1193 if (TypeManager.NamespaceClash (Name, Location)) {
1198 ModuleBuilder builder = CodeGen.Module.Builder;
1199 TypeBuilder = builder.DefineType (
1200 Name, type_attributes, null, null);
1202 TypeBuilder builder = Parent.TypeBuilder;
1203 if (builder == null) {
1208 TypeBuilder = builder.DefineNestedType (
1209 Basename, type_attributes, ptype, null);
1211 } catch (ArgumentException) {
1212 Report.RuntimeMissingSupport (Location, "static classes");
1217 TypeManager.AddUserType (Name, TypeBuilder, this);
1219 if (Parts != null) {
1221 foreach (ClassPart part in Parts) {
1222 part.TypeBuilder = TypeBuilder;
1224 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1225 part.ec.ContainerType = TypeBuilder;
1229 // Normally, we create the EmitContext here.
1230 // The only exception is if we're an Iterator - in this case,
1231 // we already have the `ec', so we don't want to create a new one.
1234 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1235 ec.ContainerType = TypeBuilder;
1239 string[] param_names = new string [TypeParameters.Length];
1240 for (int i = 0; i < TypeParameters.Length; i++)
1241 param_names [i] = TypeParameters [i].Name;
1243 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1245 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1246 for (int i = offset; i < gen_params.Length; i++)
1247 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1250 iface_exprs = GetClassBases (out base_type);
1251 if (iface_exprs == null && base_type != null) {
1256 if (base_type == null) {
1257 if (Kind == Kind.Class){
1258 if (RootContext.StdLib)
1259 base_type = TypeManager.system_object_expr;
1260 else if (Name != "System.Object")
1261 base_type = TypeManager.system_object_expr;
1262 } else if (Kind == Kind.Struct){
1264 // If we are compiling our runtime,
1265 // and we are defining ValueType, then our
1266 // base is `System.Object'.
1268 if (!RootContext.StdLib && Name == "System.ValueType")
1269 base_type = TypeManager.system_object_expr;
1270 else if (Kind == Kind.Struct)
1271 base_type = TypeManager.system_valuetype_expr;
1275 if (base_type != null) {
1276 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1277 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1278 ptype = base_type.ResolveType (TypeResolveEmitContext);
1279 if (ptype == null) {
1284 ptype = base_type.Type;
1286 if (IsGeneric && TypeManager.IsAttributeType (ptype)) {
1287 Report.Error (698, base_type.Location,
1288 "A generic type cannot derive from `{0}' " +
1289 "because it is an attribute class",
1296 if (!CheckRecursiveDefinition (this)) {
1302 TypeBuilder.SetParent (ptype);
1304 // add interfaces that were not added at type creation
1305 if (iface_exprs != null) {
1306 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1307 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1308 TypeResolveEmitContext.ContainerType = TypeBuilder;
1309 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1310 if (ifaces == null) {
1315 foreach (Type itype in ifaces)
1316 TypeBuilder.AddInterfaceImplementation (itype);
1318 if (!CheckGenericInterfaces (ifaces)) {
1323 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1326 if (!(this is Iterator))
1327 RootContext.RegisterOrder (this);
1328 else if (!ResolveType ()) {
1333 if (!DefineNestedTypes ()) {
1341 public bool ResolveType ()
1346 TypeExpr current_type = null;
1347 if (Parts != null) {
1348 foreach (ClassPart part in Parts) {
1349 if (!part.DefineTypeParameters ()) {
1355 foreach (TypeParameter type_param in CurrentTypeParameters) {
1356 if (!type_param.Resolve (this)) {
1362 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1363 for (int i = offset; i < gen_params.Length; i++)
1364 CurrentTypeParameters [i - offset].DefineConstraints ();
1366 foreach (TypeParameter type_param in TypeParameters) {
1367 if (!type_param.DefineType (ec)) {
1373 current_type = new ConstructedType (
1374 TypeBuilder, TypeParameters, Location);
1377 foreach (TypeParameter type_param in TypeParameters)
1378 if (!type_param.CheckDependencies (ec)) {
1383 if (current_type != null) {
1384 current_type = current_type.ResolveAsTypeTerminal (ec);
1385 if (current_type == null) {
1390 CurrentType = current_type.Type;
1396 protected virtual bool DefineNestedTypes ()
1398 if (Interfaces != null) {
1399 foreach (TypeContainer iface in Interfaces)
1400 if (iface.DefineType () == null)
1404 if (Types != null) {
1405 foreach (TypeContainer tc in Types)
1406 if (tc.DefineType () == null)
1410 if (Delegates != null) {
1411 foreach (Delegate d in Delegates)
1412 if (d.DefineType () == null)
1416 if (Enums != null) {
1417 foreach (Enum en in Enums)
1418 if (en.DefineType () == null)
1425 TypeContainer InTransit;
1427 protected bool CheckRecursiveDefinition (TypeContainer tc)
1429 if (InTransit != null) {
1430 Report.SymbolRelatedToPreviousError (this);
1431 if (this is Interface)
1433 529, tc.Location, "Inherited interface '{0}' causes a " +
1434 "cycle in the interface hierarchy of '{1}'",
1435 GetSignatureForError (), tc.GetSignatureForError ());
1438 146, tc.Location, "Circular base class dependency " +
1439 "involving '{0}' and '{1}'",
1440 tc.GetSignatureForError (), GetSignatureForError ());
1446 Type parent = ptype;
1447 if (parent != null) {
1448 if (parent.IsGenericInstance)
1449 parent = parent.GetGenericTypeDefinition ();
1451 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1452 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1456 if (iface_exprs != null) {
1457 foreach (TypeExpr iface in iface_exprs) {
1458 Type itype = iface.Type;
1460 if (itype.IsGenericInstance)
1461 itype = itype.GetGenericTypeDefinition ();
1463 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1464 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1473 static void Error_KeywordNotAllowed (Location loc)
1475 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1479 /// Populates our TypeBuilder with fields and methods
1481 public override bool DefineMembers (TypeContainer container)
1483 if (members_defined)
1484 return members_defined_ok;
1486 members_defined_ok = DoDefineMembers ();
1487 members_defined = true;
1489 return members_defined_ok;
1492 protected virtual bool DoDefineMembers ()
1494 if (iface_exprs != null) {
1495 foreach (TypeExpr iface in iface_exprs) {
1496 ConstructedType ct = iface as ConstructedType;
1497 if ((ct != null) && !ct.CheckConstraints (ec))
1502 if (base_type != null) {
1503 ConstructedType ct = base_type as ConstructedType;
1504 if ((ct != null) && !ct.CheckConstraints (ec))
1509 if ((ModFlags & Modifiers.NEW) != 0)
1510 Error_KeywordNotAllowed (Location);
1512 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1513 if (conflict_symbol == null) {
1514 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1515 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1517 if ((ModFlags & Modifiers.NEW) == 0) {
1518 Report.SymbolRelatedToPreviousError (conflict_symbol);
1519 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1524 DefineContainerMembers (constants);
1525 DefineContainerMembers (fields);
1527 if ((Kind == Kind.Class) && !(this is ClassPart)){
1528 if ((instance_constructors == null) &&
1529 !(this is StaticClass)) {
1530 if (default_constructor == null)
1531 DefineDefaultConstructor (false);
1534 if (initialized_static_fields != null &&
1535 default_static_constructor == null)
1536 DefineDefaultConstructor (true);
1539 if (Kind == Kind.Struct){
1541 // Structs can not have initialized instance
1544 if (initialized_static_fields != null &&
1545 default_static_constructor == null)
1546 DefineDefaultConstructor (true);
1548 if (initialized_fields != null)
1549 ReportStructInitializedInstanceError ();
1552 Pending = GetPendingImplementations ();
1554 if (parts != null) {
1555 foreach (ClassPart part in parts) {
1556 if (!part.DefineMembers (this))
1562 // Constructors are not in the defined_names array
1564 DefineContainerMembers (instance_constructors);
1566 if (default_static_constructor != null)
1567 default_static_constructor.Define ();
1569 DefineContainerMembers (properties);
1570 DefineContainerMembers (events);
1571 DefineContainerMembers (indexers);
1572 DefineContainerMembers (methods);
1573 DefineContainerMembers (operators);
1574 DefineContainerMembers (enums);
1575 DefineContainerMembers (delegates);
1577 if (CurrentType != null) {
1578 GenericType = CurrentType;
1580 ec.ContainerType = GenericType;
1585 if (!(this is ClassPart))
1586 member_cache = new MemberCache (this);
1589 if (parts != null) {
1590 foreach (ClassPart part in parts)
1591 part.member_cache = member_cache;
1594 if (iterators != null) {
1595 foreach (Iterator iterator in iterators) {
1596 if (iterator.DefineType () == null)
1600 foreach (Iterator iterator in iterators) {
1601 if (!iterator.DefineMembers (this))
1609 void ReportStructInitializedInstanceError ()
1611 string n = TypeBuilder.FullName;
1613 foreach (Field f in initialized_fields){
1616 "`" + n + "." + f.Name + "': can not have " +
1617 "instance field initializers in structs");
1621 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1624 mcal.DefineContainerMembers ();
1627 public override bool Define ()
1629 if (parts != null) {
1630 foreach (ClassPart part in parts) {
1631 if (!part.Define ())
1636 if (iterators != null) {
1637 foreach (Iterator iterator in iterators) {
1638 if (!iterator.Define ())
1646 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1648 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1652 /// This function is based by a delegate to the FindMembers routine
1654 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1660 /// This filter is used by FindMembers, and we just keep
1661 /// a global for the filter to `AlwaysAccept'
1663 static MemberFilter accepting_filter;
1666 static TypeContainer ()
1668 accepting_filter = new MemberFilter (AlwaysAccept);
1671 public MethodInfo[] GetMethods ()
1673 ArrayList members = new ArrayList ();
1675 DefineMembers (null);
1677 if (methods != null) {
1678 int len = methods.Count;
1679 for (int i = 0; i < len; i++) {
1680 Method m = (Method) methods [i];
1682 members.Add (m.MethodBuilder);
1686 if (operators != null) {
1687 int len = operators.Count;
1688 for (int i = 0; i < len; i++) {
1689 Operator o = (Operator) operators [i];
1691 members.Add (o.OperatorMethodBuilder);
1695 if (properties != null) {
1696 int len = properties.Count;
1697 for (int i = 0; i < len; i++) {
1698 Property p = (Property) properties [i];
1700 if (p.GetBuilder != null)
1701 members.Add (p.GetBuilder);
1702 if (p.SetBuilder != null)
1703 members.Add (p.SetBuilder);
1707 if (indexers != null) {
1708 int len = indexers.Count;
1709 for (int i = 0; i < len; i++) {
1710 Indexer ix = (Indexer) indexers [i];
1712 if (ix.GetBuilder != null)
1713 members.Add (ix.GetBuilder);
1714 if (ix.SetBuilder != null)
1715 members.Add (ix.SetBuilder);
1719 if (events != null) {
1720 int len = events.Count;
1721 for (int i = 0; i < len; i++) {
1722 Event e = (Event) events [i];
1724 if (e.AddBuilder != null)
1725 members.Add (e.AddBuilder);
1726 if (e.RemoveBuilder != null)
1727 members.Add (e.RemoveBuilder);
1731 MethodInfo[] retMethods = new MethodInfo [members.Count];
1732 members.CopyTo (retMethods, 0);
1736 // Indicated whether container has StructLayout attribute set Explicit
1737 public virtual bool HasExplicitLayout {
1743 public override Type FindNestedType (string name)
1745 ArrayList [] lists = { types, enums, delegates, interfaces };
1747 for (int j = 0; j < lists.Length; ++j) {
1748 ArrayList list = lists [j];
1752 int len = list.Count;
1753 for (int i = 0; i < len; ++i) {
1754 DeclSpace ds = (DeclSpace) list [i];
1755 if (ds.Basename == name) {
1757 return ds.TypeBuilder;
1765 private void FindMembers_NestedTypes (int modflags,
1766 BindingFlags bf, MemberFilter filter, object criteria,
1767 ref ArrayList members)
1769 ArrayList [] lists = { types, enums, delegates, interfaces };
1771 for (int j = 0; j < lists.Length; ++j) {
1772 ArrayList list = lists [j];
1776 int len = list.Count;
1777 for (int i = 0; i < len; i++) {
1778 DeclSpace ds = (DeclSpace) list [i];
1780 if ((ds.ModFlags & modflags) == 0)
1783 TypeBuilder tb = ds.TypeBuilder;
1785 if (!(criteria is string) || ds.Basename.Equals (criteria))
1786 tb = ds.DefineType ();
1789 if (tb != null && (filter (tb, criteria) == true)) {
1790 if (members == null)
1791 members = new ArrayList ();
1800 /// This method returns the members of this type just like Type.FindMembers would
1801 /// Only, we need to use this for types which are _being_ defined because MS'
1802 /// implementation can't take care of that.
1805 // FIXME: return an empty static array instead of null, that cleans up
1806 // some code and is consistent with some coding conventions I just found
1810 // Notice that in various cases we check if our field is non-null,
1811 // something that would normally mean that there was a bug elsewhere.
1813 // The problem happens while we are defining p-invoke methods, as those
1814 // will trigger a FindMembers, but this happens before things are defined
1816 // Since the whole process is a no-op, it is fine to check for null here.
1818 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1819 MemberFilter filter, object criteria)
1821 ArrayList members = null;
1824 if ((bf & BindingFlags.Public) != 0)
1825 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1827 if ((bf & BindingFlags.NonPublic) != 0)
1828 modflags |= Modifiers.PRIVATE;
1830 int static_mask = 0, static_flags = 0;
1831 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1832 case BindingFlags.Static:
1833 static_mask = static_flags = Modifiers.STATIC;
1836 case BindingFlags.Instance:
1837 static_mask = Modifiers.STATIC;
1842 static_mask = static_flags = 0;
1846 Timer.StartTimer (TimerType.TcFindMembers);
1849 filter = accepting_filter;
1851 if ((mt & MemberTypes.Field) != 0) {
1852 if (fields != null) {
1853 int len = fields.Count;
1854 for (int i = 0; i < len; i++) {
1855 FieldMember f = (FieldMember) fields [i];
1857 if ((f.ModFlags & modflags) == 0)
1859 if ((f.ModFlags & static_mask) != static_flags)
1862 FieldBuilder fb = f.FieldBuilder;
1863 if (fb != null && filter (fb, criteria) == true) {
1864 if (members == null)
1865 members = new ArrayList ();
1872 if (constants != null) {
1873 int len = constants.Count;
1874 for (int i = 0; i < len; i++) {
1875 Const con = (Const) constants [i];
1877 if ((con.ModFlags & modflags) == 0)
1879 if ((con.ModFlags & static_mask) != static_flags)
1882 FieldBuilder fb = con.FieldBuilder;
1885 fb = con.FieldBuilder;
1887 if (fb != null && filter (fb, criteria) == true) {
1888 if (members == null)
1889 members = new ArrayList ();
1897 if ((mt & MemberTypes.Method) != 0) {
1898 if (methods != null) {
1899 int len = methods.Count;
1900 for (int i = 0; i < len; i++) {
1901 Method m = (Method) methods [i];
1903 if ((m.ModFlags & modflags) == 0)
1905 if ((m.ModFlags & static_mask) != static_flags)
1908 MethodBuilder mb = m.MethodBuilder;
1910 if (mb != null && filter (mb, criteria) == true) {
1911 if (members == null)
1912 members = new ArrayList ();
1919 if (operators != null) {
1920 int len = operators.Count;
1921 for (int i = 0; i < len; i++) {
1922 Operator o = (Operator) operators [i];
1924 if ((o.ModFlags & modflags) == 0)
1926 if ((o.ModFlags & static_mask) != static_flags)
1929 MethodBuilder ob = o.OperatorMethodBuilder;
1930 if (ob != null && filter (ob, criteria) == true) {
1931 if (members == null)
1932 members = new ArrayList ();
1939 if (properties != null) {
1940 int len = properties.Count;
1941 for (int i = 0; i < len; i++) {
1942 Property p = (Property) properties [i];
1944 if ((p.ModFlags & modflags) == 0)
1946 if ((p.ModFlags & static_mask) != static_flags)
1952 if (b != null && filter (b, criteria) == true) {
1953 if (members == null)
1954 members = new ArrayList ();
1960 if (b != null && filter (b, criteria) == true) {
1961 if (members == null)
1962 members = new ArrayList ();
1969 if (indexers != null) {
1970 int len = indexers.Count;
1971 for (int i = 0; i < len; i++) {
1972 Indexer ix = (Indexer) indexers [i];
1974 if ((ix.ModFlags & modflags) == 0)
1976 if ((ix.ModFlags & static_mask) != static_flags)
1982 if (b != null && filter (b, criteria) == true) {
1983 if (members == null)
1984 members = new ArrayList ();
1990 if (b != null && filter (b, criteria) == true) {
1991 if (members == null)
1992 members = new ArrayList ();
2000 if ((mt & MemberTypes.Event) != 0) {
2001 if (events != null) {
2002 int len = events.Count;
2003 for (int i = 0; i < len; i++) {
2004 Event e = (Event) events [i];
2006 if ((e.ModFlags & modflags) == 0)
2008 if ((e.ModFlags & static_mask) != static_flags)
2011 MemberInfo eb = e.EventBuilder;
2012 if (eb != null && filter (eb, criteria) == true) {
2013 if (members == null)
2014 members = new ArrayList ();
2016 members.Add (e.EventBuilder);
2022 if ((mt & MemberTypes.Property) != 0){
2023 if (properties != null) {
2024 int len = properties.Count;
2025 for (int i = 0; i < len; i++) {
2026 Property p = (Property) properties [i];
2028 if ((p.ModFlags & modflags) == 0)
2030 if ((p.ModFlags & static_mask) != static_flags)
2033 MemberInfo pb = p.PropertyBuilder;
2034 if (pb != null && filter (pb, criteria) == true) {
2035 if (members == null)
2036 members = new ArrayList ();
2038 members.Add (p.PropertyBuilder);
2043 if (indexers != null) {
2044 int len = indexers.Count;
2045 for (int i = 0; i < len; i++) {
2046 Indexer ix = (Indexer) indexers [i];
2048 if ((ix.ModFlags & modflags) == 0)
2050 if ((ix.ModFlags & static_mask) != static_flags)
2053 MemberInfo ib = ix.PropertyBuilder;
2054 if (ib != null && filter (ib, criteria) == true) {
2055 if (members == null)
2056 members = new ArrayList ();
2058 members.Add (ix.PropertyBuilder);
2064 if ((mt & MemberTypes.NestedType) != 0)
2065 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2067 if ((mt & MemberTypes.Constructor) != 0){
2068 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2069 int len = instance_constructors.Count;
2070 for (int i = 0; i < len; i++) {
2071 Constructor c = (Constructor) instance_constructors [i];
2073 ConstructorBuilder cb = c.ConstructorBuilder;
2074 if (cb != null && filter (cb, criteria) == true) {
2075 if (members == null)
2076 members = new ArrayList ();
2083 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2084 ConstructorBuilder cb =
2085 default_static_constructor.ConstructorBuilder;
2087 if (cb != null && filter (cb, criteria) == true) {
2088 if (members == null)
2089 members = new ArrayList ();
2097 // Lookup members in base if requested.
2099 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2100 if (TypeBuilder.BaseType != null) {
2101 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2102 if (list.Count > 0) {
2103 if (members == null)
2104 members = new ArrayList ();
2106 members.AddRange (list);
2112 Timer.StopTimer (TimerType.TcFindMembers);
2114 if (members == null)
2115 return MemberList.Empty;
2117 return new MemberList (members);
2120 public override MemberCache MemberCache {
2122 return member_cache;
2126 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2127 MemberFilter filter, object criteria)
2129 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2132 return ds.FindMembers (mt, bf, filter, criteria);
2134 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2138 // FindMethods will look for methods not only in the type `t', but in
2139 // any interfaces implemented by the type.
2141 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2142 MemberFilter filter, object criteria)
2148 /// Emits the values for the constants
2150 public void EmitConstants ()
2152 if (constants != null)
2153 foreach (Const con in constants)
2158 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2163 foreach (MemberCore mc in al) {
2164 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2168 Report.Warning (169, mc.Location, "The private {0} '{1}' is never used", member_type, mc.GetSignatureForError ());
2173 public virtual void VerifyMembers ()
2176 // Check for internal or private fields that were never assigned
2178 if (RootContext.WarningLevel >= 3) {
2179 CheckMemberUsage (properties, "property");
2180 CheckMemberUsage (methods, "method");
2181 CheckMemberUsage (constants, "constant");
2183 if (fields != null){
2184 foreach (FieldMember f in fields) {
2185 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2189 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2194 // Only report 649 on level 4
2196 if (RootContext.WarningLevel < 4)
2199 if ((f.status & Field.Status.ASSIGNED) != 0)
2202 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2209 /// Emits the code, this step is performed after all
2210 /// the types, enumerations, constructors
2212 public void EmitType ()
2214 if (OptAttributes != null)
2215 OptAttributes.Emit (ec, this);
2218 // Structs with no fields need to have at least one byte.
2219 // The right thing would be to set the PackingSize in a DefineType
2220 // but there are no functions that allow interfaces *and* the size to
2224 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
2225 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2226 FieldAttributes.Private);
2228 if (HasExplicitLayout){
2229 object [] ctor_args = new object [1];
2232 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2233 TypeManager.field_offset_attribute_ctor, ctor_args);
2234 fb.SetCustomAttribute (cba);
2240 if (instance_constructors != null) {
2241 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired (this)) {
2242 bool has_compliant_args = false;
2244 foreach (Constructor c in instance_constructors) {
2247 if (has_compliant_args)
2250 has_compliant_args = c.HasCompliantArgs;
2252 if (!has_compliant_args)
2253 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2255 foreach (Constructor c in instance_constructors)
2262 if (default_static_constructor != null)
2263 default_static_constructor.Emit ();
2265 if (methods != null)
2266 foreach (Method m in methods)
2269 if (operators != null)
2270 foreach (Operator o in operators)
2273 if (properties != null)
2274 foreach (Property p in properties)
2277 if (indexers != null){
2282 foreach (FieldMember f in fields)
2285 if (events != null){
2286 foreach (Event e in Events)
2290 if (delegates != null) {
2291 foreach (Delegate d in Delegates) {
2296 if (enums != null) {
2297 foreach (Enum e in enums) {
2302 if (parts != null) {
2303 foreach (ClassPart part in parts)
2307 if ((Pending != null) && !(this is ClassPart))
2308 if (Pending.VerifyPendingMethods ())
2311 if (iterators != null)
2312 foreach (Iterator iterator in iterators)
2313 iterator.EmitType ();
2315 // if (types != null)
2316 // foreach (TypeContainer tc in types)
2320 public override void CloseType ()
2322 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2326 caching_flags |= Flags.CloseTypeCreated;
2327 TypeBuilder.CreateType ();
2328 } catch (TypeLoadException){
2330 // This is fine, the code still created the type
2332 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2333 // Console.WriteLine (e.Message);
2335 Console.WriteLine ("In type: " + Name);
2340 foreach (Enum en in Enums)
2344 foreach (TypeContainer tc in Types)
2345 if (tc.Kind == Kind.Struct)
2348 foreach (TypeContainer tc in Types)
2349 if (tc.Kind != Kind.Struct)
2353 if (Delegates != null)
2354 foreach (Delegate d in Delegates)
2357 if (Iterators != null)
2358 foreach (Iterator i in Iterators)
2366 initialized_fields = null;
2367 initialized_static_fields = null;
2376 default_constructor = null;
2377 default_static_constructor = null;
2379 OptAttributes = null;
2382 member_cache = null;
2385 // TODO: make it obsolete and use GetSignatureForError
2386 public string MakeName (string n)
2388 return "`" + Name + "." + n + "'";
2392 // Performs the validation on a Method's modifiers (properties have
2393 // the same properties).
2395 public bool MethodModifiersValid (MemberCore mc)
2397 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2398 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2399 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2401 int flags = mc.ModFlags;
2404 // At most one of static, virtual or override
2406 if ((flags & Modifiers.STATIC) != 0){
2407 if ((flags & vao) != 0){
2408 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2409 GetSignatureForError ());
2414 if (Kind == Kind.Struct){
2415 if ((flags & va) != 0){
2416 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2421 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2422 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2427 // If the declaration includes the abstract modifier, then the
2428 // declaration does not include static, virtual or extern
2430 if ((flags & Modifiers.ABSTRACT) != 0){
2431 if ((flags & Modifiers.EXTERN) != 0){
2433 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2437 if ((flags & Modifiers.SEALED) != 0) {
2438 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2442 if ((flags & Modifiers.VIRTUAL) != 0){
2443 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2447 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2448 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2453 if ((flags & Modifiers.PRIVATE) != 0){
2454 if ((flags & vao) != 0){
2455 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2460 if ((flags & Modifiers.SEALED) != 0){
2461 if ((flags & Modifiers.OVERRIDE) == 0){
2462 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2470 public bool UserDefinedStaticConstructor {
2472 return default_static_constructor != null;
2476 public Constructor DefaultStaticConstructor {
2477 get { return default_static_constructor; }
2480 protected override bool VerifyClsCompliance (DeclSpace ds)
2482 if (!base.VerifyClsCompliance (ds))
2487 Type base_type = TypeBuilder.BaseType;
2488 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2489 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2492 if (!Parent.IsClsComplianceRequired (ds)) {
2493 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2494 GetSignatureForError (), Parent.GetSignatureForError ());
2501 /// Checks whether container name is CLS Compliant
2503 void VerifyClsName ()
2505 Hashtable base_members = base_cache == null ?
2507 base_cache.GetPublicMembers ();
2508 Hashtable this_members = new Hashtable ();
2510 foreach (DictionaryEntry entry in defined_names) {
2511 MemberCore mc = (MemberCore)entry.Value;
2512 if (!mc.IsClsComplianceRequired (this))
2515 string name = (string)entry.Key;
2516 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2518 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2519 object found = base_members [lcase];
2520 if (found == null) {
2521 found = this_members [lcase];
2522 if (found == null) {
2523 this_members.Add (lcase, mc);
2528 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2531 if (found is MemberInfo) {
2532 if (basename == ((MemberInfo)found).Name)
2534 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2536 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2538 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2544 /// Performs checks for an explicit interface implementation. First it
2545 /// checks whether the `interface_type' is a base inteface implementation.
2546 /// Then it checks whether `name' exists in the interface type.
2548 public virtual bool VerifyImplements (Type interface_type, string full,
2549 string name, Location loc)
2553 if (ifaces != null){
2554 foreach (Type t in ifaces){
2555 if (t == interface_type){
2563 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2564 full, interface_type.FullName);
2571 protected override void VerifyObsoleteAttribute()
2573 CheckUsageOfObsoleteAttribute (TypeBuilder.BaseType);
2578 foreach (Type iface in ifaces) {
2579 CheckUsageOfObsoleteAttribute (iface);
2587 string IMemberContainer.Name {
2593 Type IMemberContainer.Type {
2599 MemberCache IMemberContainer.MemberCache {
2601 return member_cache;
2605 bool IMemberContainer.IsInterface {
2607 return Kind == Kind.Interface;
2611 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2613 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2615 if (GenericType != null)
2616 return TypeManager.FindMembers (GenericType, mt, new_bf,
2619 return FindMembers (mt, new_bf, null, null);
2623 // Generates xml doc comments (if any), and if required,
2624 // handle warning report.
2626 internal override void GenerateDocComment (DeclSpace ds)
2628 DocUtil.GenerateTypeDocComment (this, ds);
2631 public override string DocCommentHeader {
2632 get { return "T:"; }
2635 public virtual MemberCache BaseCache {
2637 if (base_cache != null)
2639 if (TypeBuilder.BaseType != null)
2640 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2641 if (TypeBuilder.IsInterface)
2642 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2649 public class PartialContainer : TypeContainer {
2651 public readonly Namespace Namespace;
2652 public readonly int OriginalModFlags;
2653 public readonly int AllowedModifiers;
2654 public readonly TypeAttributes DefaultTypeAttributes;
2656 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2657 MemberName member_name, int mod_flags, Kind kind,
2660 PartialContainer pc;
2661 DeclSpace ds = RootContext.Tree.GetDecl (member_name);
2663 pc = ds as PartialContainer;
2667 260, ds.Location, "Missing partial modifier " +
2668 "on declaration of type `{0}'; another " +
2669 "partial implementation of this type exists",
2670 member_name.GetTypeName());
2672 Report.LocationOfPreviousError (loc);
2676 if (pc.Kind != kind) {
2678 261, loc, "Partial declarations of `{0}' " +
2679 "must be all classes, all structs or " +
2680 "all interfaces", member_name.GetTypeName ());
2684 if (pc.OriginalModFlags != mod_flags) {
2686 262, loc, "Partial declarations of `{0}' " +
2687 "have conflicting accessibility modifiers",
2688 member_name.GetTypeName ());
2693 if (pc.CountTypeParameters != member_name.CountTypeArguments) {
2695 264, loc, "Partial declarations of `{0}' " +
2696 "must have the same type parameter names in " +
2697 "the same order", member_name.GetTypeName ());
2701 string[] pc_names = pc.MemberName.TypeArguments.GetDeclarations ();
2702 string[] names = member_name.TypeArguments.GetDeclarations ();
2704 for (int i = 0; i < pc.CountTypeParameters; i++) {
2705 if (pc_names [i] == names [i])
2709 264, loc, "Partial declarations of `{0}' " +
2710 "must have the same type parameter names in " +
2711 "the same order", member_name.GetTypeName ());
2719 if (parent is ClassPart)
2720 parent = ((ClassPart) parent).PartialContainer;
2722 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2723 RootContext.Tree.RecordDecl (member_name, pc);
2725 if (kind == Kind.Interface)
2726 parent.AddInterface (pc);
2727 else if (kind == Kind.Class || kind == Kind.Struct)
2728 parent.AddClassOrStruct (pc);
2730 throw new InvalidOperationException ();
2732 // This is needed to define our type parameters; we define the constraints later.
2733 pc.SetParameterInfo (null);
2737 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2738 MemberName name, int mod, Attributes attrs,
2739 Kind kind, Location loc)
2741 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2743 // An error occured; create a dummy container, but don't
2745 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2748 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2753 protected PartialContainer (Namespace ns, TypeContainer parent,
2754 MemberName name, int mod, Kind kind, Location l)
2755 : base (null, parent, name, null, kind, l)
2757 this.Namespace = ns;
2761 AllowedModifiers = Class.AllowedModifiers;
2762 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2766 AllowedModifiers = Struct.AllowedModifiers;
2767 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2770 case Kind.Interface:
2771 AllowedModifiers = Interface.AllowedModifiers;
2772 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2776 throw new InvalidOperationException ();
2780 if (parent.Parent == null)
2781 accmods = Modifiers.INTERNAL;
2783 accmods = Modifiers.PRIVATE;
2785 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2786 this.OriginalModFlags = mod;
2789 public override PendingImplementation GetPendingImplementations ()
2791 return PendingImplementation.GetPendingImplementations (this);
2794 protected override TypeAttributes TypeAttr {
2796 return base.TypeAttr | DefaultTypeAttributes;
2801 public class ClassPart : TypeContainer, IMemberContainer {
2802 public readonly PartialContainer PartialContainer;
2803 public readonly bool IsPartial;
2805 Constraints[] constraints;
2807 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2808 int mod, Attributes attrs, Kind kind, Location l)
2809 : base (ns, parent, pc.MemberName, attrs, kind, l)
2811 this.PartialContainer = pc;
2812 this.IsPartial = true;
2815 if (parent == null || parent == RootContext.Tree.Types)
2816 accmods = Modifiers.INTERNAL;
2818 accmods = Modifiers.PRIVATE;
2820 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2823 constraints = new Constraints [pc.CountCurrentTypeParameters];
2826 public override PendingImplementation GetPendingImplementations ()
2828 return PartialContainer.Pending;
2831 public override bool VerifyImplements (Type interface_type, string full,
2832 string name, Location loc)
2834 return PartialContainer.VerifyImplements (
2835 interface_type, full, name, loc);
2838 public override void SetParameterInfo (ArrayList constraints_list)
2840 if (constraints_list == null)
2843 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2844 for (int i = 0; i < constraints.Length; i++) {
2845 foreach (Constraints constraint in constraints_list) {
2846 if (constraint.TypeParameter == current_params [i].Name) {
2847 constraints [i] = constraint;
2854 public bool DefineTypeParameters ()
2856 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2858 for (int i = 0; i < current_params.Length; i++) {
2859 Constraints new_constraints = constraints [i];
2860 if (new_constraints == null)
2863 if (!current_params [i].UpdateConstraints (ec, new_constraints)) {
2864 Report.Error (265, Location, "Partial declarations of `{0}' have " +
2865 "inconsistent constraints for type parameter `{1}'.",
2866 MemberName.GetTypeName (), current_params [i].Name);
2871 for (int i = 0; i < current_params.Length; i++) {
2872 if (!current_params [i].Resolve (this))
2876 for (int i = 0; i < current_params.Length; i++)
2877 current_params [i].DefineConstraints ();
2879 foreach (TypeParameter type_param in PartialContainer.TypeParameters) {
2880 if (!type_param.DefineType (ec))
2887 public override void RegisterFieldForInitialization (FieldMember field)
2889 PartialContainer.RegisterFieldForInitialization (field);
2892 public override bool EmitFieldInitializers (EmitContext ec)
2894 return PartialContainer.EmitFieldInitializers (ec);
2897 public override Type FindNestedType (string name)
2899 return PartialContainer.FindNestedType (name);
2902 public override MemberCache BaseCache {
2904 return PartialContainer.BaseCache;
2909 public abstract class ClassOrStruct : TypeContainer {
2910 bool has_explicit_layout = false;
2911 ListDictionary declarative_security;
2913 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2914 MemberName name, Attributes attrs, Kind kind,
2916 : base (ns, parent, name, attrs, kind, l)
2920 public override PendingImplementation GetPendingImplementations ()
2922 return PendingImplementation.GetPendingImplementations (this);
2925 public override bool HasExplicitLayout {
2927 return has_explicit_layout;
2931 public override void VerifyMembers ()
2933 base.VerifyMembers ();
2935 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2936 foreach (Event e in events){
2938 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2943 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2945 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2946 if (declarative_security == null)
2947 declarative_security = new ListDictionary ();
2949 a.ExtractSecurityPermissionSet (declarative_security);
2953 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2954 has_explicit_layout = true;
2956 base.ApplyAttributeBuilder (a, cb);
2959 public override void Emit()
2963 if (declarative_security != null) {
2964 foreach (DictionaryEntry de in declarative_security) {
2965 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2972 /// Class handles static classes declaration
2974 public sealed class StaticClass: Class {
2975 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2976 Attributes attrs, Location l)
2977 : base (ns, parent, name, mod, attrs, l)
2979 if (RootContext.Version == LanguageVersion.ISO_1) {
2980 Report.FeatureIsNotStandardized (l, "static classes");
2984 protected override int AllowedModifiersProp {
2986 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2987 Modifiers.STATIC | Modifiers.UNSAFE;
2991 protected override void DefineContainerMembers (MemberCoreArrayList list)
2996 foreach (MemberCore m in list) {
2997 if (m is Operator) {
2998 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
3002 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
3003 Report.Warning (628, 4, m.Location, "'{0}': new protected member declared in static class", m.GetSignatureForError (this));
3006 Report.Error (720, m.Location, "'{0}': cannot declare indexers in a static class", m.GetSignatureForError (this));
3010 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
3013 if (m is Constructor) {
3014 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
3018 if (m is Destructor) {
3019 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
3022 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
3025 base.DefineContainerMembers (list);
3028 public override TypeBuilder DefineType()
3030 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
3031 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
3035 TypeBuilder tb = base.DefineType ();
3039 if ((ptype != null) && (ptype != TypeManager.object_type)) {
3042 "Static class '{0}' cannot derive from type '{1}'. " +
3043 "Static classes must derive from object",
3044 GetSignatureForError (), ptype);
3048 if (ifaces != null) {
3049 foreach (Type t in ifaces)
3050 Report.SymbolRelatedToPreviousError (t);
3053 "'{0}': static classes cannot implement interfaces",
3054 GetSignatureForError ());
3059 protected override TypeAttributes TypeAttr {
3061 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
3066 public class Class : ClassOrStruct {
3067 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
3068 public const int AllowedModifiers =
3071 Modifiers.PROTECTED |
3072 Modifiers.INTERNAL |
3074 Modifiers.ABSTRACT |
3078 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3079 Attributes attrs, Location l)
3080 : base (ns, parent, name, attrs, Kind.Class, l)
3082 this.ModFlags = mod;
3085 virtual protected int AllowedModifiersProp {
3087 return AllowedModifiers;
3091 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
3093 if (a.Type == TypeManager.attribute_usage_type) {
3094 if (ptype != TypeManager.attribute_type &&
3095 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
3096 TypeBuilder.FullName != "System.Attribute") {
3097 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
3101 if (a.Type == TypeManager.conditional_attribute_type &&
3102 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
3103 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
3107 if (AttributeTester.IsAttributeExcluded (a.Type))
3110 base.ApplyAttributeBuilder (a, cb);
3113 public const TypeAttributes DefaultTypeAttributes =
3114 TypeAttributes.AutoLayout | TypeAttributes.Class;
3116 public override TypeBuilder DefineType()
3118 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
3119 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
3123 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
3124 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
3126 return base.DefineType ();
3129 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3130 /// Valid only for attribute classes.
3131 public bool IsExcluded ()
3133 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3134 return (caching_flags & Flags.Excluded) != 0;
3136 caching_flags &= ~Flags.Excluded_Undetected;
3138 if (OptAttributes == null)
3141 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3146 foreach (Attribute a in attrs) {
3147 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3148 if (RootContext.AllDefines.Contains (condition))
3152 caching_flags |= Flags.Excluded;
3157 // FIXME: How do we deal with the user specifying a different
3160 protected override TypeAttributes TypeAttr {
3162 return base.TypeAttr | DefaultTypeAttributes;
3167 public class Struct : ClassOrStruct {
3169 // Modifiers allowed in a struct declaration
3171 public const int AllowedModifiers =
3174 Modifiers.PROTECTED |
3175 Modifiers.INTERNAL |
3179 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
3180 int mod, Attributes attrs, Location l)
3181 : base (ns, parent, name, attrs, Kind.Struct, l)
3185 if (parent.Parent == null)
3186 accmods = Modifiers.INTERNAL;
3188 accmods = Modifiers.PRIVATE;
3190 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3192 this.ModFlags |= Modifiers.SEALED;
3195 public const TypeAttributes DefaultTypeAttributes =
3196 TypeAttributes.SequentialLayout |
3197 TypeAttributes.Sealed |
3198 TypeAttributes.BeforeFieldInit;
3201 // FIXME: Allow the user to specify a different set of attributes
3202 // in some cases (Sealed for example is mandatory for a class,
3203 // but what SequentialLayout can be changed
3205 protected override TypeAttributes TypeAttr {
3207 return base.TypeAttr | DefaultTypeAttributes;
3215 public class Interface : TypeContainer, IMemberContainer {
3218 /// Modifiers allowed in a class declaration
3220 public const int AllowedModifiers =
3223 Modifiers.PROTECTED |
3224 Modifiers.INTERNAL |
3228 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name,
3229 int mod, Attributes attrs, Location l)
3230 : base (ns, parent, name, attrs, Kind.Interface, l)
3234 if (parent.Parent == null)
3235 accmods = Modifiers.INTERNAL;
3237 accmods = Modifiers.PRIVATE;
3239 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3242 public override PendingImplementation GetPendingImplementations ()
3247 public const TypeAttributes DefaultTypeAttributes =
3248 TypeAttributes.AutoLayout |
3249 TypeAttributes.Abstract |
3250 TypeAttributes.Interface;
3252 protected override TypeAttributes TypeAttr {
3254 return base.TypeAttr | DefaultTypeAttributes;
3258 protected override bool VerifyClsCompliance (DeclSpace ds)
3260 if (!base.VerifyClsCompliance (ds))
3263 if (ifaces != null) {
3264 foreach (Type t in ifaces) {
3265 if (AttributeTester.IsClsCompliant (t))
3268 Report.SymbolRelatedToPreviousError (t);
3269 Report.Warning (3027, 1, Location, "'{0}' is not CLS-compliant because base interface '{1}' is not CLS-compliant",
3270 GetSignatureForError (), TypeManager.CSharpName (t));
3278 public abstract class MethodCore : MemberBase {
3279 public readonly Parameters Parameters;
3280 public readonly GenericMethod GenericMethod;
3281 protected ToplevelBlock block;
3284 // Parameters, cached for semantic analysis.
3286 protected InternalParameters parameter_info;
3287 protected Type [] parameter_types;
3289 // Whether this is an operator method.
3290 public bool IsOperator;
3293 // The method we're overriding if this is an override method.
3295 protected MethodInfo base_method = null;
3297 static string[] attribute_targets = new string [] { "method", "return" };
3299 public MethodCore (TypeContainer parent, GenericMethod generic,
3300 Expression type, int mod, int allowed_mod, bool is_iface,
3301 MemberName name, Attributes attrs, Parameters parameters,
3303 : base (parent, generic != null ? generic : (DeclSpace) parent,
3304 type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
3306 Parameters = parameters;
3307 IsInterface = is_iface;
3308 this.GenericMethod = generic;
3312 // Returns the System.Type array for the parameters of this method
3314 public Type [] ParameterTypes {
3316 return parameter_types;
3320 public InternalParameters ParameterInfo
3323 return parameter_info;
3327 public ToplevelBlock Block {
3337 protected override bool CheckBase ()
3339 if (!base.CheckBase ())
3342 // Check whether arguments were correct.
3343 if (!DoDefineParameters ())
3346 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3352 // Is null for System.Object while compiling corlib and base interfaces
3353 if (Parent.BaseCache == null) {
3354 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3355 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3360 Type base_ret_type = null;
3361 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3363 // method is override
3364 if (base_method != null) {
3366 if (!CheckMethodAgainstBase ())
3369 if ((ModFlags & Modifiers.NEW) == 0) {
3370 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_ret_type))) {
3371 Report.SymbolRelatedToPreviousError (base_method);
3372 if (this is PropertyBase) {
3373 Report.Error (1715, Location, "'{0}': type must be '{1}' to match overridden member '{2}'",
3374 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3377 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3378 "change return type when overriding inherited member");
3383 if (base_method.IsAbstract && !IsInterface) {
3384 Report.SymbolRelatedToPreviousError (base_method);
3385 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3390 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3391 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3395 if (RootContext.WarningLevel > 2) {
3396 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3397 Parent.Methods.HasEquals = true;
3398 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3399 Parent.Methods.HasGetHashCode = true;
3402 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3403 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3405 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3406 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3407 Report.SymbolRelatedToPreviousError (base_method);
3408 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3415 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3416 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3417 if (conflict_symbol != null) {
3418 Report.SymbolRelatedToPreviousError (conflict_symbol);
3419 if (this is PropertyBase)
3420 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3422 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3424 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3428 if (conflict_symbol == null) {
3429 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3430 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3435 if ((ModFlags & Modifiers.NEW) == 0) {
3436 if (this is Method && conflict_symbol is MethodBase)
3439 Report.SymbolRelatedToPreviousError (conflict_symbol);
3440 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3448 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3449 // that have been defined.
3451 // `name' is the user visible name for reporting errors (this is used to
3452 // provide the right name regarding method names and properties)
3454 bool CheckMethodAgainstBase ()
3458 // TODO: replace with GetSignatureForError
3459 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3461 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3462 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3464 506, Location, Parent.MakeName (Name) +
3465 ": cannot override inherited member `" +
3466 name + "' because it is not " +
3467 "virtual, abstract or override");
3471 // Now we check that the overriden method is not final
3473 if (base_method.IsFinal) {
3474 Report.SymbolRelatedToPreviousError (base_method);
3475 Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
3476 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3480 // Check that the permissions are not being changed
3482 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3483 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3485 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3486 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3491 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3492 ModFlags |= Modifiers.NEW;
3493 Report.SymbolRelatedToPreviousError (base_method);
3494 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3495 if (RootContext.WarningLevel >= 2)
3496 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));
3498 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3504 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3506 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3508 // when overriding protected internal, the method can be declared
3509 // protected internal only within the same assembly
3512 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3513 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3515 // assemblies differ - report an error
3519 } else if (thisp != base_classp) {
3521 // same assembly, but other attributes differ - report an error
3526 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3528 // if it's not "protected internal", it must be "protected"
3532 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3534 // protected within the same assembly - an error
3537 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3538 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3540 // protected ok, but other attributes differ - report an error
3546 return (thisp == base_classp);
3550 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3553 // FIXME: report the old/new permissions?
3556 507, Location, parent.MakeName (Name) +
3557 ": can't change the access modifiers when overriding inherited " +
3558 "member `" + name + "'");
3561 protected static string Error722 {
3563 return "'{0}': static types cannot be used as return types";
3568 /// For custom member duplication search in a container
3570 protected abstract bool CheckForDuplications ();
3573 /// Gets base method and its return type
3575 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3577 protected virtual bool DoDefineParameters ()
3579 EmitContext ec = ds.EmitContext;
3581 throw new InternalErrorException ("DoDefineParameters invoked too early");
3583 bool old_unsafe = ec.InUnsafe;
3584 ec.InUnsafe = InUnsafe;
3585 // Check if arguments were correct
3586 parameter_types = Parameters.GetParameterInfo (ec);
3587 ec.InUnsafe = old_unsafe;
3589 if ((parameter_types == null) ||
3590 !CheckParameters (ds, parameter_types))
3593 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3594 parameter_info = new InternalParameters (parameter_types, Parameters, tparam);
3596 Parameter array_param = Parameters.ArrayParameter;
3597 if ((array_param != null) &&
3598 (!array_param.ParameterType.IsArray ||
3599 (array_param.ParameterType.GetArrayRank () != 1))) {
3600 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3607 void error_425 (Type old, Type t, string name)
3609 Report.Error (425, Location,
3610 "The constraints of type parameter `{0}' " +
3611 "of method `{1}' must match the constraints for " +
3612 "type parameter `{2}' of method `{3}'",
3613 TypeManager.CSharpName (old), Name,
3614 TypeManager.CSharpName (t), name);
3617 protected override bool CheckGenericOverride (MethodInfo method, string name)
3619 ParameterData pd = TypeManager.GetParameterData (method);
3621 for (int i = 0; i < ParameterTypes.Length; i++) {
3622 GenericConstraints ogc = pd.GenericConstraints (i);
3623 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3625 if ((gc == null) && (ogc == null))
3628 Type ot = pd.ParameterType (i);
3629 Type t = ParameterTypes [i];
3631 if (!((gc != null) && (ogc != null))) {
3632 error_425 (ot, t, name);
3636 if ((gc.Attributes != ogc.Attributes) ||
3637 (gc.HasClassConstraint != ogc.HasClassConstraint)) {
3638 error_425 (ot, t, name);
3642 if (ogc.HasClassConstraint &&
3643 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3644 error_425 (ot, t, name);
3648 Type[] oct = ogc.InterfaceConstraints;
3649 Type[] ct = gc.InterfaceConstraints;
3651 if (oct.Length != ct.Length) {
3652 error_425 (ot, t, name);
3656 for (int j = 0; j < oct.Length; j++)
3657 if (!oct [j].Equals (ct [j])) {
3658 error_425 (ot, t, name);
3666 public override string[] ValidAttributeTargets {
3668 return attribute_targets;
3672 protected override bool VerifyClsCompliance (DeclSpace ds)
3674 if (!base.VerifyClsCompliance (ds)) {
3675 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsComplianceRequired (ds)) {
3676 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3681 if (Parameters.HasArglist) {
3682 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3685 if (!AttributeTester.IsClsCompliant (MemberType)) {
3686 if (this is PropertyBase)
3687 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3688 GetSignatureForError ());
3690 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3691 GetSignatureForError ());
3694 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3699 bool MayUnify (MethodCore first, MethodCore second)
3701 int a_type_params = 0;
3702 if (first.GenericMethod != null)
3703 a_type_params = first.GenericMethod.CountTypeParameters;
3705 int b_type_params = 0;
3706 if (second.GenericMethod != null)
3707 b_type_params = second.GenericMethod.CountTypeParameters;
3709 if (a_type_params != b_type_params)
3712 Type[] class_infered, method_infered;
3713 if (Parent.CountTypeParameters > 0)
3714 class_infered = new Type [Parent.CountTypeParameters];
3716 class_infered = null;
3718 if (a_type_params > 0)
3719 method_infered = new Type [a_type_params];
3721 method_infered = null;
3723 return TypeManager.MayBecomeEqualGenericInstances (
3724 first.ParameterTypes, second.ParameterTypes, class_infered, method_infered);
3727 protected bool IsDuplicateImplementation (MethodCore method)
3729 if ((method == this) ||
3730 (method.MemberName.GetTypeName () != MemberName.GetTypeName ()))
3733 Type[] param_types = method.ParameterTypes;
3734 if (param_types == null)
3737 if (param_types.Length != ParameterTypes.Length)
3741 bool may_unify = MayUnify (this, method);
3743 for (int i = 0; i < param_types.Length; i++) {
3744 if (param_types [i] != ParameterTypes [i])
3748 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3749 equal = may_unify = false;
3751 // TODO: make operator compatible with MethodCore to avoid this
3752 if (this is Operator && method is Operator) {
3753 if (MemberType != method.MemberType)
3754 equal = may_unify = false;
3759 // Try to report 663: method only differs on out/ref
3761 ParameterData info = ParameterInfo;
3762 ParameterData other_info = method.ParameterInfo;
3763 for (int i = 0; i < info.Count; i++){
3764 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3765 Report.Error (663, Location,
3766 "Overload method only differs " +
3767 "in parameter modifier");
3772 Report.SymbolRelatedToPreviousError (method);
3773 if (this is Operator && method is Operator)
3774 Report.Error (557, Location,
3775 "Duplicate user-defined conversion in type '{0}'",
3778 Report.Error (111, Location,
3779 "Type '{0}' already defines a member called '{1}' " +
3780 "with the same parameter types", Parent.Name, Name);
3782 } else if (may_unify) {
3783 Report.Error (408, Location,
3784 "`{0}' cannot define overload members that " +
3785 "may unify for some type parameter substitutions",
3792 public override bool IsUsed
3803 // Returns a string that represents the signature for this
3804 // member which should be used in XML documentation.
3806 public override string GetDocCommentName (DeclSpace ds)
3808 return DocUtil.GetMethodDocCommentName (this, ds);
3812 // Raised (and passed an XmlElement that contains the comment)
3813 // when GenerateDocComment is writing documentation expectedly.
3815 // FIXME: with a few effort, it could be done with XmlReader,
3816 // that means removal of DOM use.
3818 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3820 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3824 // Represents header string for documentation comment.
3826 public override string DocCommentHeader {
3827 get { return "M:"; }
3830 protected override void VerifyObsoleteAttribute()
3832 base.VerifyObsoleteAttribute ();
3834 if (parameter_types == null)
3837 foreach (Type type in parameter_types) {
3838 CheckUsageOfObsoleteAttribute (type);
3843 public class SourceMethod : ISourceMethod
3845 TypeContainer container;
3848 protected SourceMethod (TypeContainer container, MethodBase builder,
3849 ISourceFile file, Location start, Location end)
3851 this.container = container;
3852 this.builder = builder;
3854 CodeGen.SymbolWriter.OpenMethod (
3855 file, this, start.Row, 0, end.Row, 0);
3858 public string Name {
3859 get { return builder.Name; }
3862 public int NamespaceID {
3863 get { return container.NamespaceEntry.SymbolFileID; }
3868 if (builder is MethodBuilder)
3869 return ((MethodBuilder) builder).GetToken ().Token;
3870 else if (builder is ConstructorBuilder)
3871 return ((ConstructorBuilder) builder).GetToken ().Token;
3873 throw new NotSupportedException ();
3877 public void CloseMethod ()
3879 if (CodeGen.SymbolWriter != null)
3880 CodeGen.SymbolWriter.CloseMethod ();
3883 public static SourceMethod Create (TypeContainer parent,
3884 MethodBase builder, Block block)
3886 if (CodeGen.SymbolWriter == null)
3891 Location start_loc = block.StartLocation;
3892 if (Location.IsNull (start_loc))
3895 Location end_loc = block.EndLocation;
3896 if (Location.IsNull (end_loc))
3899 ISourceFile file = start_loc.SourceFile;
3903 return new SourceMethod (
3904 parent, builder, file, start_loc, end_loc);
3908 public class Method : MethodCore, IIteratorContainer, IMethodData {
3909 public MethodBuilder MethodBuilder;
3910 public MethodData MethodData;
3911 ReturnParameter return_attributes;
3912 ListDictionary declarative_security;
3915 /// Modifiers allowed in a class declaration
3917 const int AllowedModifiers =
3920 Modifiers.PROTECTED |
3921 Modifiers.INTERNAL |
3926 Modifiers.OVERRIDE |
3927 Modifiers.ABSTRACT |
3929 Modifiers.METHOD_YIELDS |
3932 const int AllowedInterfaceModifiers =
3933 Modifiers.NEW | Modifiers.UNSAFE;
3936 // return_type can be "null" for VOID values.
3938 public Method (TypeContainer parent, GenericMethod generic,
3939 Expression return_type, int mod, bool is_iface,
3940 MemberName name, Parameters parameters, Attributes attrs,
3942 : base (parent, generic, return_type, mod,
3943 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3944 is_iface, name, attrs, parameters, l)
3948 public override AttributeTargets AttributeTargets {
3950 return AttributeTargets.Method;
3954 public override string GetSignatureForError()
3956 if (MethodBuilder == null) {
3957 return GetSignatureForError (Parent);
3959 return TypeManager.CSharpSignature (MethodBuilder);
3963 /// Use this method when MethodBuilder is null
3965 public override string GetSignatureForError (TypeContainer tc)
3967 // TODO: get params from somewhere
3968 if (parameter_info == null)
3969 return base.GetSignatureForError (tc);
3971 // TODO: move to parameters
3972 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3973 if (parameter_info.Parameters.FixedParameters != null) {
3974 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3975 Parameter p = parameter_info.Parameters.FixedParameters [i];
3976 args.Append (p.GetSignatureForError ());
3978 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3983 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3986 void DuplicateEntryPoint (MethodInfo b, Location location)
3990 "Program `" + CodeGen.FileName +
3991 "' has more than one entry point defined: `" +
3992 TypeManager.CSharpSignature(b) + "'");
3995 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3997 if (b.ReturnType != TypeManager.void_type &&
3998 b.ReturnType != TypeManager.int32_type)
4001 if (pinfo.Count == 0)
4004 if (pinfo.Count > 1)
4007 Type t = pinfo.ParameterType(0);
4009 (t.GetArrayRank() == 1) &&
4010 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
4011 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
4017 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4019 if (a.Target == AttributeTargets.ReturnValue) {
4020 if (return_attributes == null)
4021 return_attributes = new ReturnParameter (MethodBuilder, Location);
4023 return_attributes.ApplyAttributeBuilder (a, cb);
4027 if (a.Type == TypeManager.methodimpl_attr_type &&
4028 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4029 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4032 if (a.Type == TypeManager.dllimport_type) {
4033 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4034 if ((ModFlags & extern_static) != extern_static) {
4035 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
4041 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4042 if (declarative_security == null)
4043 declarative_security = new ListDictionary ();
4044 a.ExtractSecurityPermissionSet (declarative_security);
4048 if (a.Type == TypeManager.conditional_attribute_type) {
4049 if (IsOperator || IsExplicitImpl) {
4050 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4054 if (ReturnType != TypeManager.void_type) {
4055 Report.Error (578, Location, "Conditional not valid on '{0}' because its return type is not void", GetSignatureForError ());
4059 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4060 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
4065 Report.Error (582, Location, "Conditional not valid on interface members");
4069 if (MethodData.IsImplementing) {
4070 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
4074 for (int i = 0; i < parameter_info.Count; ++i) {
4075 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
4076 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
4082 MethodBuilder.SetCustomAttribute (cb);
4085 protected override bool CheckForDuplications ()
4087 ArrayList ar = Parent.Methods;
4089 int arLen = ar.Count;
4091 for (int i = 0; i < arLen; i++) {
4092 Method m = (Method) ar [i];
4093 if (IsDuplicateImplementation (m))
4098 ar = Parent.Properties;
4100 for (int i = 0; i < ar.Count; ++i) {
4101 PropertyBase pb = (PropertyBase) ar [i];
4102 if (pb.AreAccessorsDuplicateImplementation (this))
4107 ar = Parent.Indexers;
4109 for (int i = 0; i < ar.Count; ++i) {
4110 PropertyBase pb = (PropertyBase) ar [i];
4111 if (pb.AreAccessorsDuplicateImplementation (this))
4118 for (int i = 0; i < ar.Count; ++i) {
4119 Event ev = (Event) ar [i];
4120 if (ev.AreAccessorsDuplicateImplementation (this))
4131 public override bool Define ()
4133 if (!DoDefineBase ())
4136 MethodBuilder mb = null;
4137 if (GenericMethod != null) {
4138 string method_name = MemberName.Name;
4141 method_name = TypeManager.GetFullName (InterfaceType) + "." + method_name;
4143 mb = Parent.TypeBuilder.DefineGenericMethod (method_name, flags);
4144 if (!GenericMethod.Define (mb))
4151 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4152 Error1599 (Location, ReturnType);
4160 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
4162 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
4163 this, mb, GenericMethod, base_method);
4165 if (!MethodData.Define (Parent))
4168 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4169 Name == "Finalize" && !(this is Destructor)) {
4170 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4174 // Setup iterator if we are one
4176 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4177 Iterator iterator = new Iterator (
4178 Parent, Name, MemberType,
4179 ParameterInfo, ModFlags, block, Location);
4181 if (!iterator.DefineIterator ())
4184 block = iterator.Block;
4187 MethodBuilder = MethodData.MethodBuilder;
4190 // This is used to track the Entry Point,
4192 if (Name == "Main" &&
4193 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
4194 (RootContext.MainClass == null ||
4195 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4196 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
4197 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4198 md.SetMemberIsUsed ();
4200 if (RootContext.EntryPoint == null) {
4201 if (Parent.IsGeneric){
4202 Report.Error (-201, Location,
4203 "Entry point can not be defined in a generic class");
4206 RootContext.EntryPoint = MethodBuilder;
4207 RootContext.EntryPointLocation = Location;
4209 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4210 DuplicateEntryPoint (MethodBuilder, Location);
4213 if (RootContext.WarningLevel >= 4)
4214 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder) );
4218 if (MemberType.IsAbstract && MemberType.IsSealed) {
4219 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4229 public override void Emit ()
4231 MethodData.Emit (Parent, this);
4234 if (declarative_security != null) {
4235 foreach (DictionaryEntry de in declarative_security) {
4236 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4244 public static void Error1599 (Location loc, Type t)
4246 Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
4249 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4251 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
4252 container.TypeBuilder, Name, ParameterTypes, false);
4257 base_ret_type = mi.ReturnType;
4261 public override bool MarkForDuplicationCheck ()
4263 caching_flags |= Flags.TestMethodDuplication;
4267 protected override bool VerifyClsCompliance(DeclSpace ds)
4269 if (!base.VerifyClsCompliance (ds))
4272 if (parameter_types.Length > 0) {
4273 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
4275 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4282 void IIteratorContainer.SetYields ()
4284 ModFlags |= Modifiers.METHOD_YIELDS;
4287 #region IMethodData Members
4289 public CallingConventions CallingConventions {
4291 CallingConventions cc = Parameters.GetCallingConvention ();
4292 if (Parameters.HasArglist)
4293 block.HasVarargs = true;
4296 if ((ModFlags & Modifiers.STATIC) == 0)
4297 cc |= CallingConventions.HasThis;
4299 // FIXME: How is `ExplicitThis' used in C#?
4305 public Type ReturnType {
4311 public MemberName MethodName {
4317 public new Location Location {
4319 return base.Location;
4323 protected override bool CheckBase() {
4324 if (!base.CheckBase ())
4327 // TODO: Destructor should derive from MethodCore
4328 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4329 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4330 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4337 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4339 EmitContext ec = new EmitContext (
4340 tc, ds, Location, ig, ReturnType, ModFlags, false);
4342 ec.CurrentIterator = tc as Iterator;
4343 if (ec.CurrentIterator != null)
4344 ec.CurrentAnonymousMethod = ec.CurrentIterator.Host;
4349 public ObsoleteAttribute GetObsoleteAttribute ()
4351 return GetObsoleteAttribute (ds);
4355 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4357 public bool IsExcluded (EmitContext ec)
4359 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4360 return (caching_flags & Flags.Excluded) != 0;
4362 caching_flags &= ~Flags.Excluded_Undetected;
4364 if (base_method == null) {
4365 if (OptAttributes == null)
4368 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4373 foreach (Attribute a in attrs) {
4374 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4375 if (RootContext.AllDefines.Contains (condition))
4379 caching_flags |= Flags.Excluded;
4383 IMethodData md = TypeManager.GetMethod (base_method);
4385 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4386 caching_flags |= Flags.Excluded;
4392 if (md.IsExcluded (ec)) {
4393 caching_flags |= Flags.Excluded;
4399 GenericMethod IMethodData.GenericMethod {
4401 return GenericMethod;
4408 public abstract class ConstructorInitializer {
4409 ArrayList argument_list;
4410 protected ConstructorInfo base_constructor;
4413 public ConstructorInitializer (ArrayList argument_list, Location loc)
4415 this.argument_list = argument_list;
4419 public ArrayList Arguments {
4421 return argument_list;
4425 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4427 Expression base_constructor_group;
4431 ec.CurrentBlock = block;
4433 if (argument_list != null){
4434 foreach (Argument a in argument_list){
4435 if (!a.Resolve (ec, loc))
4439 ec.CurrentBlock = null;
4441 if (this is ConstructorBaseInitializer) {
4442 if (ec.ContainerType.BaseType == null)
4445 t = ec.ContainerType.BaseType;
4446 if (ec.ContainerType.IsValueType) {
4447 Report.Error (522, loc,
4448 "structs cannot call base class constructors");
4452 t = ec.ContainerType;
4454 base_constructor_group = Expression.MemberLookup (
4455 ec, t, ".ctor", MemberTypes.Constructor,
4456 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4459 if (base_constructor_group == null){
4461 base_constructor_group = Expression.MemberLookup (
4462 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4463 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4467 int errors = Report.Errors;
4468 if (base_constructor_group != null)
4469 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4470 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4473 if (base_constructor == null) {
4474 if (errors == Report.Errors)
4475 Report.Error (1501, loc, "Can not find a constructor for this argument list");
4480 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
4481 TypeManager.CSharpSignature (base_constructor));
4482 base_constructor = null;
4486 if (base_constructor == caller_builder){
4487 Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
4494 public void Emit (EmitContext ec)
4496 if (base_constructor != null){
4497 ec.Mark (loc, false);
4499 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4501 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4506 public class ConstructorBaseInitializer : ConstructorInitializer {
4507 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4508 base (argument_list, l)
4513 public class ConstructorThisInitializer : ConstructorInitializer {
4514 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4515 base (argument_list, l)
4520 public class Constructor : MethodCore, IMethodData {
4521 public ConstructorBuilder ConstructorBuilder;
4522 public ConstructorInitializer Initializer;
4523 ListDictionary declarative_security;
4526 // Modifiers allowed for a constructor.
4528 public const int AllowedModifiers =
4530 Modifiers.PROTECTED |
4531 Modifiers.INTERNAL |
4537 bool has_compliant_args = false;
4539 // The spec claims that static is not permitted, but
4540 // my very own code has static constructors.
4542 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4543 ConstructorInitializer init, Location l)
4544 : base (ds, null, null, mod, AllowedModifiers, false,
4545 new MemberName (name), null, args, l)
4550 public override string GetSignatureForError()
4552 if (ConstructorBuilder == null)
4553 return GetSignatureForError (Parent);
4555 return TypeManager.CSharpSignature (ConstructorBuilder);
4558 public bool HasCompliantArgs {
4560 return has_compliant_args;
4564 public override AttributeTargets AttributeTargets {
4566 return AttributeTargets.Constructor;
4572 // Returns true if this is a default constructor
4574 public bool IsDefault ()
4576 if ((ModFlags & Modifiers.STATIC) != 0)
4577 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4578 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4581 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4582 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4583 (Initializer is ConstructorBaseInitializer) &&
4584 (Initializer.Arguments == null);
4587 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4589 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4590 if (declarative_security == null) {
4591 declarative_security = new ListDictionary ();
4593 a.ExtractSecurityPermissionSet (declarative_security);
4597 ConstructorBuilder.SetCustomAttribute (cb);
4600 protected override bool CheckForDuplications ()
4602 ArrayList ar = Parent.InstanceConstructors;
4604 int arLen = ar.Count;
4606 for (int i = 0; i < arLen; i++) {
4607 Constructor m = (Constructor) ar [i];
4608 if (IsDuplicateImplementation (m))
4615 protected override bool CheckBase ()
4617 // Check whether arguments were correct.
4618 if (!DoDefineParameters ())
4621 // TODO: skip the rest for generated ctor
4622 if ((ModFlags & Modifiers.STATIC) != 0)
4625 if (!CheckForDuplications ())
4628 if (Parent.Kind == Kind.Struct) {
4629 if (ParameterTypes.Length == 0) {
4630 Report.Error (568, Location,
4631 "Structs can not contain explicit parameterless " +
4636 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4637 Report.Error (666, Location, "Protected member in struct declaration");
4642 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4643 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4650 // Creates the ConstructorBuilder
4652 public override bool Define ()
4654 if (ConstructorBuilder != null)
4657 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4658 MethodAttributes.SpecialName);
4660 if ((ModFlags & Modifiers.STATIC) != 0){
4661 ca |= MethodAttributes.Static | MethodAttributes.Private;
4663 ca |= MethodAttributes.HideBySig;
4665 if ((ModFlags & Modifiers.PUBLIC) != 0)
4666 ca |= MethodAttributes.Public;
4667 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4668 if ((ModFlags & Modifiers.INTERNAL) != 0)
4669 ca |= MethodAttributes.FamORAssem;
4671 ca |= MethodAttributes.Family;
4672 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4673 ca |= MethodAttributes.Assembly;
4674 else if (IsDefault ())
4675 ca |= MethodAttributes.Public;
4677 ca |= MethodAttributes.Private;
4680 // Check if arguments were correct.
4684 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4685 ca, CallingConventions,
4688 if ((ModFlags & Modifiers.UNSAFE) != 0)
4689 ConstructorBuilder.InitLocals = false;
4691 TypeManager.AddMethod (ConstructorBuilder, this);
4694 // HACK because System.Reflection.Emit is lame
4696 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4704 public override void Emit ()
4706 EmitContext ec = CreateEmitContext (null, null);
4709 // extern methods have no bodies
4711 if ((ModFlags & Modifiers.EXTERN) != 0) {
4712 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4714 179, Location, "External constructor `" +
4715 TypeManager.CSharpSignature (ConstructorBuilder) +
4716 "' can not have a body");
4719 } else if (block == null) {
4721 501, Location, "Constructor `" +
4722 TypeManager.CSharpSignature (ConstructorBuilder) +
4723 "' must declare a body since it is not marked extern");
4727 // If this is a non-static `struct' constructor and doesn't have any
4728 // initializer, it must initialize all of the struct's fields.
4729 if ((Parent.Kind == Kind.Struct) &&
4730 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4731 Block.AddThisVariable (Parent, Location);
4734 block.ResolveMeta (ec, ParameterInfo);
4736 if ((ModFlags & Modifiers.STATIC) == 0){
4737 if (Parent.Kind == Kind.Class && Initializer == null)
4738 Initializer = new ConstructorBaseInitializer (
4743 // Spec mandates that Initializers will not have
4747 if ((Initializer != null) &&
4748 !Initializer.Resolve (ConstructorBuilder, block, ec))
4750 ec.IsStatic = false;
4753 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4755 SourceMethod source = SourceMethod.Create (
4756 Parent, ConstructorBuilder, block);
4759 // Classes can have base initializers and instance field initializers.
4761 if (Parent.Kind == Kind.Class){
4762 if ((ModFlags & Modifiers.STATIC) == 0){
4765 // If we use a "this (...)" constructor initializer, then
4766 // do not emit field initializers, they are initialized in the other constructor
4768 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4769 Parent.EmitFieldInitializers (ec);
4772 if (Initializer != null) {
4773 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4774 ec.TestObsoleteMethodUsage = false;
4776 Initializer.Emit (ec);
4779 if ((ModFlags & Modifiers.STATIC) != 0)
4780 Parent.EmitFieldInitializers (ec);
4782 if (OptAttributes != null)
4783 OptAttributes.Emit (ec, this);
4785 ec.EmitTopBlock (block, ParameterInfo, Location);
4788 source.CloseMethod ();
4792 if (declarative_security != null) {
4793 foreach (DictionaryEntry de in declarative_security) {
4794 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4801 // Is never override
4802 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4807 protected override bool VerifyClsCompliance (DeclSpace ds)
4809 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4813 if (parameter_types.Length > 0) {
4814 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4816 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4818 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4819 foreach (Type param in parameter_types) {
4820 if (param.IsArray) {
4826 has_compliant_args = true;
4830 #region IMethodData Members
4832 public System.Reflection.CallingConventions CallingConventions {
4834 CallingConventions cc = Parameters.GetCallingConvention ();
4836 if (Parent.Kind == Kind.Class)
4837 if ((ModFlags & Modifiers.STATIC) == 0)
4838 cc |= CallingConventions.HasThis;
4840 // FIXME: How is `ExplicitThis' used in C#?
4846 public new Location Location {
4848 return base.Location;
4852 public MemberName MethodName {
4858 public Type ReturnType {
4864 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4866 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4867 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4870 public ObsoleteAttribute GetObsoleteAttribute ()
4872 return GetObsoleteAttribute (Parent);
4875 public bool IsExcluded(EmitContext ec)
4880 GenericMethod IMethodData.GenericMethod {
4890 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4892 public interface IMethodData
4894 CallingConventions CallingConventions { get; }
4895 Location Location { get; }
4896 MemberName MethodName { get; }
4897 Type[] ParameterTypes { get; }
4898 Type ReturnType { get; }
4899 GenericMethod GenericMethod { get; }
4901 Attributes OptAttributes { get; }
4902 ToplevelBlock Block { get; }
4904 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4905 ObsoleteAttribute GetObsoleteAttribute ();
4906 string GetSignatureForError (TypeContainer tc);
4907 bool IsExcluded (EmitContext ec);
4908 bool IsClsComplianceRequired (DeclSpace ds);
4909 void SetMemberIsUsed ();
4913 // Encapsulates most of the Method's state
4915 public class MethodData {
4917 readonly IMethodData method;
4920 // The return type of this method
4922 public readonly GenericMethod GenericMethod;
4923 public readonly InternalParameters ParameterInfo;
4926 // Are we implementing an interface ?
4928 public bool IsImplementing = false;
4933 protected MemberBase member;
4934 protected int modifiers;
4935 protected MethodAttributes flags;
4936 protected Type declaring_type;
4937 protected MethodInfo parent_method;
4939 MethodBuilder builder = null;
4940 public MethodBuilder MethodBuilder {
4946 public Type DeclaringType {
4948 return declaring_type;
4952 public MethodData (MemberBase member, InternalParameters parameters,
4953 int modifiers, MethodAttributes flags, IMethodData method)
4955 this.member = member;
4956 this.ParameterInfo = parameters;
4957 this.modifiers = modifiers;
4960 this.method = method;
4963 public MethodData (MemberBase member, InternalParameters parameters,
4964 int modifiers, MethodAttributes flags,
4965 IMethodData method, MethodBuilder builder,
4966 GenericMethod generic, MethodInfo parent_method)
4967 : this (member, parameters, modifiers, flags, method)
4969 this.builder = builder;
4970 this.GenericMethod = generic;
4971 this.parent_method = parent_method;
4974 public bool Define (TypeContainer container)
4976 MethodInfo implementing = null;
4978 string name = method.MethodName.Basename;
4979 string method_name = method.MethodName.FullName;
4981 Type[] ParameterTypes = method.ParameterTypes;
4983 if (container.Pending != null){
4984 if (member is Indexer) // TODO: test it, but it should work without this IF
4985 implementing = container.Pending.IsInterfaceIndexer (
4986 member.InterfaceType, method.ReturnType, ParameterInfo);
4988 implementing = container.Pending.IsInterfaceMethod (
4989 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4991 if (member.InterfaceType != null){
4992 if (implementing == null){
4993 if (member is PropertyBase) {
4994 Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
4995 method.GetSignatureForError (container), member.Name);
4998 Report.Error (539, method.Location, "'{0}' in explicit interface " +
4999 "declaration is not a member of interface",
5004 if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
5005 Report.SymbolRelatedToPreviousError (implementing);
5006 Report.Error (683, method.Location, "'{0}' explicit method implementation cannot implement '{1}' because it is an accessor",
5007 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5011 method_name = TypeManager.GetFullName (member.InterfaceType) + "." + method_name;
5013 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
5014 Report.SymbolRelatedToPreviousError (implementing);
5015 Report.Error (686, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
5016 method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5023 // For implicit implementations, make sure we are public, for
5024 // explicit implementations, make sure we are private.
5026 if (implementing != null){
5028 // Setting null inside this block will trigger a more
5029 // verbose error reporting for missing interface implementations
5031 // The "candidate" function has been flagged already
5032 // but it wont get cleared
5034 if (member.IsExplicitImpl){
5035 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
5036 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
5037 implementing = null;
5039 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
5040 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
5042 // If this is an interface method implementation,
5043 // check for public accessibility
5045 implementing = null;
5046 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5047 // We may never be private.
5048 implementing = null;
5049 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5051 // We may be protected if we're overriding something.
5053 implementing = null;
5058 // Static is not allowed
5060 if ((modifiers & Modifiers.STATIC) != 0){
5061 implementing = null;
5062 Modifiers.Error_InvalidModifier (method.Location, "static");
5067 // If implementing is still valid, set flags
5069 if (implementing != null){
5071 // When implementing interface methods, set NewSlot
5072 // unless, we are overwriting a method.
5074 if (implementing.DeclaringType.IsInterface){
5075 if ((modifiers & Modifiers.OVERRIDE) == 0)
5076 flags |= MethodAttributes.NewSlot;
5079 MethodAttributes.Virtual |
5080 MethodAttributes.HideBySig;
5082 // Set Final unless we're virtual, abstract or already overriding a method.
5083 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5084 flags |= MethodAttributes.Final;
5086 IsImplementing = true;
5089 EmitContext ec = method.CreateEmitContext (container, null);
5091 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
5093 if (builder == null)
5096 if (container.CurrentType != null)
5097 declaring_type = container.CurrentType;
5099 declaring_type = container.TypeBuilder;
5101 if ((modifiers & Modifiers.UNSAFE) != 0)
5102 builder.InitLocals = false;
5104 if (IsImplementing){
5106 // clear the pending implemntation flag
5108 if (member is Indexer) {
5109 container.Pending.ImplementIndexer (
5110 member.InterfaceType, builder, method.ReturnType,
5111 ParameterInfo, member.IsExplicitImpl);
5113 container.Pending.ImplementMethod (
5114 member.InterfaceType, name, method.ReturnType,
5115 ParameterInfo, member.IsExplicitImpl);
5117 if (member.IsExplicitImpl)
5118 container.TypeBuilder.DefineMethodOverride (
5119 builder, implementing);
5122 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
5123 TypeManager.AddMethod (builder, method);
5125 if (GenericMethod != null) {
5126 bool is_override = member.IsExplicitImpl |
5127 ((modifiers & Modifiers.OVERRIDE) != 0);
5129 if (implementing != null)
5130 parent_method = implementing;
5132 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5140 /// Create the MethodBuilder for the method
5142 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
5144 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
5146 if ((modifiers & extern_static) == extern_static) {
5148 if (method.OptAttributes != null) {
5149 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
5150 if (dllimport_attribute != null) {
5151 flags |= MethodAttributes.PinvokeImpl;
5152 builder = dllimport_attribute.DefinePInvokeMethod (
5153 ec, container.TypeBuilder, method_name, flags,
5154 method.ReturnType, ParameterTypes);
5160 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5161 // We are more strict than Microsoft and report CS0626 like error
5162 if (method.OptAttributes == null ||
5163 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
5164 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));
5169 if (builder == null)
5170 builder = container.TypeBuilder.DefineMethod (
5171 method_name, flags, method.CallingConventions,
5172 method.ReturnType, ParameterTypes);
5174 builder.SetGenericMethodSignature (
5175 flags, method.CallingConventions,
5176 method.ReturnType, ParameterTypes);
5182 public void Emit (TypeContainer container, Attributable kind)
5185 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5186 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
5188 ec = method.CreateEmitContext (container, null);
5190 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
5191 ec.TestObsoleteMethodUsage = false;
5193 Location loc = method.Location;
5194 Attributes OptAttributes = method.OptAttributes;
5196 if (OptAttributes != null)
5197 OptAttributes.Emit (ec, kind);
5199 if (member is MethodCore)
5200 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
5202 ToplevelBlock block = method.Block;
5205 // abstract or extern methods have no bodies
5207 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
5212 // abstract or extern methods have no bodies.
5214 if ((modifiers & Modifiers.ABSTRACT) != 0)
5216 500, method.Location, "Abstract method `" +
5217 TypeManager.CSharpSignature (builder) +
5218 "' can not have a body");
5220 if ((modifiers & Modifiers.EXTERN) != 0)
5222 179, method.Location, "External method `" +
5223 TypeManager.CSharpSignature (builder) +
5224 "' can not have a body");
5230 // Methods must have a body unless they're extern or abstract
5232 if (block == null) {
5234 501, method.Location, "Method `" +
5235 TypeManager.CSharpSignature (builder) +
5236 "' must declare a body since it is not marked " +
5237 "abstract or extern");
5241 SourceMethod source = SourceMethod.Create (
5242 container, MethodBuilder, method.Block);
5245 // Handle destructors specially
5247 // FIXME: This code generates buggy code
5249 if (member is Destructor)
5250 EmitDestructor (ec, block);
5252 ec.EmitTopBlock (block, ParameterInfo, loc);
5255 source.CloseMethod ();
5258 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5260 ILGenerator ig = ec.ig;
5262 Label finish = ig.DefineLabel ();
5264 block.SetDestructor ();
5266 ig.BeginExceptionBlock ();
5267 ec.ReturnLabel = finish;
5268 ec.HasReturnLabel = true;
5269 ec.EmitTopBlock (block, null, method.Location);
5271 // ig.MarkLabel (finish);
5272 ig.BeginFinallyBlock ();
5274 if (ec.ContainerType.BaseType != null) {
5275 Expression member_lookup = Expression.MemberLookup (
5276 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5277 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5279 if (member_lookup != null){
5280 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5282 ig.Emit (OpCodes.Ldarg_0);
5283 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5287 ig.EndExceptionBlock ();
5288 //ig.MarkLabel (ec.ReturnLabel);
5289 ig.Emit (OpCodes.Ret);
5293 // Should derive from MethodCore
5294 public class Destructor : Method {
5296 public Destructor (TypeContainer ds, Expression return_type, int mod, string name,
5297 Parameters parameters, Attributes attrs, Location l)
5298 : base (ds, null, return_type, mod, false, new MemberName (name),
5299 parameters, attrs, l)
5302 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5304 if (a.Type == TypeManager.conditional_attribute_type) {
5305 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
5309 base.ApplyAttributeBuilder (a, cb);
5313 abstract public class MemberBase : MemberCore {
5314 public Expression Type;
5316 public MethodAttributes flags;
5317 public readonly DeclSpace ds;
5319 protected readonly int explicit_mod_flags;
5322 // The "short" name of this property / indexer / event. This is the
5323 // name without the explicit interface.
5325 public string ShortName {
5326 get { return MemberName.Name; }
5328 SetMemberName (new MemberName (MemberName.Left, value));
5333 // The type of this property / indexer / event
5335 protected Type member_type;
5336 public Type MemberType {
5338 if (member_type == null && Type != null) {
5339 EmitContext ec = ds.EmitContext;
5340 bool old_unsafe = ec.InUnsafe;
5341 ec.InUnsafe = InUnsafe;
5342 Type = Type.ResolveAsTypeTerminal (ec);
5343 ec.InUnsafe = old_unsafe;
5345 member_type = Type == null ? null : Type.Type;
5352 // Whether this is an interface member.
5354 public bool IsInterface;
5357 // If true, this is an explicit interface implementation
5359 public bool IsExplicitImpl;
5362 // The interface type we are explicitly implementing
5364 public Type InterfaceType = null;
5367 // The constructor is only exposed to our children
5369 protected MemberBase (TypeContainer parent, DeclSpace ds, Expression type, int mod,
5370 int allowed_mod, int def_mod, MemberName name,
5371 Attributes attrs, Location loc)
5372 : base (parent, name, attrs, loc)
5375 explicit_mod_flags = mod;
5377 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
5378 IsExplicitImpl = (MemberName.Left != null);
5381 protected virtual bool CheckBase ()
5383 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5384 Report.Error (666, Location, "Protected member in struct declaration");
5388 if ((RootContext.WarningLevel >= 4) &&
5389 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5390 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5391 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5392 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
5398 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5400 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5404 foreach (Type partype in parameters){
5405 if (partype == TypeManager.void_type) {
5407 1547, Location, "Keyword 'void' cannot " +
5408 "be used in this context");
5412 if (partype.IsPointer){
5415 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5419 if (ds.AsAccessible (partype, ModFlags))
5422 if (this is Indexer)
5423 Report.Error (55, Location,
5424 "Inconsistent accessibility: parameter type `" +
5425 TypeManager.CSharpName (partype) + "' is less " +
5426 "accessible than indexer `" + Name + "'");
5427 else if ((this is Method) && ((Method) this).IsOperator)
5428 Report.Error (57, Location,
5429 "Inconsistent accessibility: parameter type `" +
5430 TypeManager.CSharpName (partype) + "' is less " +
5431 "accessible than operator `" + Name + "'");
5433 Report.Error (51, Location,
5434 "Inconsistent accessibility: parameter type `" +
5435 TypeManager.CSharpName (partype) + "' is less " +
5436 "accessible than method `" + Name + "'");
5443 protected virtual bool DoDefineBase ()
5445 EmitContext ec = Parent.EmitContext;
5447 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5450 throw new InternalErrorException ();
5453 ModFlags = Modifiers.PUBLIC |
5454 Modifiers.ABSTRACT |
5455 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5457 flags = MethodAttributes.Public |
5458 MethodAttributes.Abstract |
5459 MethodAttributes.HideBySig |
5460 MethodAttributes.NewSlot |
5461 MethodAttributes.Virtual;
5463 if (!Parent.MethodModifiersValid (this))
5466 flags = Modifiers.MethodAttr (ModFlags);
5469 if (IsExplicitImpl) {
5470 Expression expr = MemberName.Left.GetTypeExpression (Location);
5471 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5472 if (iface_texpr == null)
5475 InterfaceType = iface_texpr.Type;
5477 if (!InterfaceType.IsInterface) {
5478 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5482 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5485 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5491 protected virtual bool DoDefine ()
5493 EmitContext ec = ds.EmitContext;
5495 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5497 ec.InUnsafe = InUnsafe;
5499 if (MemberType == null)
5502 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5503 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5504 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5509 // verify accessibility
5510 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5511 Report.SymbolRelatedToPreviousError (MemberType);
5512 if (this is Property)
5513 Report.Error (53, Location,
5514 "Inconsistent accessibility: property type `" +
5515 TypeManager.CSharpName (MemberType) + "' is less " +
5516 "accessible than property `" + GetSignatureForError () + "'");
5517 else if (this is Indexer)
5518 Report.Error (54, Location,
5519 "Inconsistent accessibility: indexer return type `" +
5520 TypeManager.CSharpName (MemberType) + "' is less " +
5521 "accessible than indexer `" + Name + "'");
5522 else if (this is MethodCore) {
5523 if (this is Operator)
5524 Report.Error (56, Location,
5525 "Inconsistent accessibility: return type `" +
5526 TypeManager.CSharpName (MemberType) + "' is less " +
5527 "accessible than operator `" + Name + "'");
5529 Report.Error (50, Location,
5530 "Inconsistent accessibility: return type `" +
5531 TypeManager.CSharpName (MemberType) + "' is less " +
5532 "accessible than method `" + Name + "'");
5534 Report.Error (52, Location,
5535 "Inconsistent accessibility: field type `" +
5536 TypeManager.CSharpName (MemberType) + "' is less " +
5537 "accessible than field `" + Name + "'");
5542 if (MemberType.IsPointer && !UnsafeOK (Parent))
5548 public override string GetSignatureForError (TypeContainer tc)
5550 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5553 protected bool IsTypePermitted ()
5555 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5556 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5562 protected override bool VerifyClsCompliance(DeclSpace ds)
5564 if (base.VerifyClsCompliance (ds)) {
5568 if (IsInterface && HasClsCompliantAttribute && ds.IsClsComplianceRequired (ds)) {
5569 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5574 protected override void VerifyObsoleteAttribute()
5576 CheckUsageOfObsoleteAttribute (MemberType);
5581 // Fields and Events both generate FieldBuilders, we use this to share
5582 // their common bits. This is also used to flag usage of the field
5584 abstract public class FieldBase : MemberBase {
5585 public FieldBuilder FieldBuilder;
5586 public Status status;
5589 public enum Status : byte {
5591 HAS_OFFSET = 4 // Used by FieldMember.
5594 static string[] attribute_targets = new string [] { "field" };
5597 /// Symbol with same name in base class/struct
5599 public MemberInfo conflict_symbol;
5602 // The constructor is only exposed to our children
5604 protected FieldBase (TypeContainer parent, Expression type, int mod,
5605 int allowed_mod, MemberName name, object init,
5606 Attributes attrs, Location loc)
5607 : base (parent, parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5613 public override AttributeTargets AttributeTargets {
5615 return AttributeTargets.Field;
5619 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5621 if (a.Type == TypeManager.marshal_as_attr_type) {
5622 UnmanagedMarshal marshal = a.GetMarshal (this);
5623 if (marshal != null) {
5624 FieldBuilder.SetMarshal (marshal);
5629 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5630 a.Error_InvalidSecurityParent ();
5634 FieldBuilder.SetCustomAttribute (cb);
5638 // Whether this field has an initializer.
5640 public bool HasInitializer {
5642 return init != null;
5646 protected readonly Object init;
5648 Expression init_expr;
5649 bool init_expr_initialized = false;
5651 protected override bool CheckGenericOverride (MethodInfo method, string name)
5657 // Resolves and returns the field initializer.
5659 public Expression GetInitializerExpression (EmitContext ec)
5661 if (init_expr_initialized)
5665 if (init is Expression)
5666 e = (Expression) init;
5668 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5670 EmitContext parent_ec = Parent.EmitContext;
5672 bool old_is_static = parent_ec.IsStatic;
5673 parent_ec.IsStatic = ec.IsStatic;
5674 parent_ec.IsFieldInitializer = true;
5675 e = e.DoResolve (parent_ec);
5676 parent_ec.IsFieldInitializer = false;
5677 parent_ec.IsStatic = old_is_static;
5680 init_expr_initialized = true;
5685 protected override bool CheckBase ()
5687 if (!base.CheckBase ())
5694 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5695 if (conflict_symbol == null) {
5696 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5697 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5702 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5703 Report.SymbolRelatedToPreviousError (conflict_symbol);
5704 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5710 protected override bool DoDefine ()
5712 if (!base.DoDefine ())
5715 if (MemberType == TypeManager.void_type) {
5716 Report.Error (1547, Location,
5717 "Keyword 'void' cannot be used in this context");
5723 public override string GetSignatureForError ()
5725 if (FieldBuilder == null) {
5726 return base.GetSignatureForError (Parent);
5728 return TypeManager.GetFullNameSignature (FieldBuilder);
5731 protected virtual bool IsFieldClsCompliant {
5733 if (FieldBuilder == null)
5736 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5740 public override string[] ValidAttributeTargets {
5742 return attribute_targets;
5746 protected override bool VerifyClsCompliance (DeclSpace ds)
5748 if (!base.VerifyClsCompliance (ds))
5751 if (!IsFieldClsCompliant) {
5752 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5758 public void SetAssigned ()
5760 status |= Status.ASSIGNED;
5764 public abstract class FieldMember: FieldBase
5766 protected FieldMember (TypeContainer parent, Expression type, int mod,
5767 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5768 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5770 if ((mod & Modifiers.ABSTRACT) != 0)
5771 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5774 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5776 if (a.Type == TypeManager.field_offset_attribute_type)
5778 status |= Status.HAS_OFFSET;
5780 if (!Parent.HasExplicitLayout) {
5781 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5785 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5786 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5791 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5792 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5796 base.ApplyAttributeBuilder (a, cb);
5800 public override bool Define()
5802 EmitContext ec = Parent.EmitContext;
5804 throw new InternalErrorException ("FieldMember.Define called too early");
5806 if (MemberType == null)
5809 if (MemberType == TypeManager.void_type) {
5810 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5817 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5818 Report.Error (52, Location,
5819 "Inconsistent accessibility: field type `" +
5820 TypeManager.CSharpName (MemberType) + "' is less " +
5821 "accessible than field `" + Name + "'");
5825 if (!IsTypePermitted ())
5828 if (MemberType.IsPointer && !UnsafeOK (Parent))
5834 public override void Emit ()
5836 if (OptAttributes != null) {
5837 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5838 OptAttributes.Emit (ec, this);
5841 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5842 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5849 // Represents header string for documentation comment.
5851 public override string DocCommentHeader {
5852 get { return "F:"; }
5856 interface IFixedBuffer
5858 FieldInfo Element { get; }
5859 Type ElementType { get; }
5862 public class FixedFieldExternal: IFixedBuffer
5864 FieldInfo element_field;
5866 public FixedFieldExternal (FieldInfo fi)
5868 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5871 #region IFixedField Members
5873 public FieldInfo Element {
5875 return element_field;
5879 public Type ElementType {
5881 return element_field.FieldType;
5889 /// Fixed buffer implementation
5891 public class FixedField: FieldMember, IFixedBuffer
5893 public const string FixedElementName = "FixedElementField";
5894 static int GlobalCounter = 0;
5895 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5896 static FieldInfo[] fi;
5898 TypeBuilder fixed_buffer_type;
5899 FieldBuilder element;
5900 Expression size_expr;
5903 const int AllowedModifiers =
5906 Modifiers.PROTECTED |
5907 Modifiers.INTERNAL |
5910 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5911 Expression size_expr, Attributes attrs, Location loc):
5912 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5914 if (RootContext.Version == LanguageVersion.ISO_1)
5915 Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
5917 this.size_expr = size_expr;
5920 public override bool Define()
5922 if (Parent.Kind != Kind.Struct) {
5923 Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
5927 if (!base.Define ())
5930 if (!TypeManager.IsPrimitiveType (MemberType)) {
5931 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");
5935 Expression e = size_expr.Resolve (Parent.EmitContext);
5939 Constant c = e as Constant;
5941 Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
5945 IntConstant buffer_size_const = c.ToInt (Location);
5946 if (buffer_size_const == null)
5949 buffer_size = buffer_size_const.Value;
5951 if (buffer_size <= 0) {
5952 Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
5956 int type_size = Expression.GetTypeSize (MemberType);
5958 if (buffer_size > int.MaxValue / type_size) {
5959 Report.Error (1664, Location, "Fixed sized buffer of length '{0}' and type '{1}' exceeded 2^31 limit",
5960 buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5964 buffer_size *= type_size;
5967 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5969 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5970 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5971 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5972 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5974 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5975 TypeManager.RegisterFieldBase (FieldBuilder, this);
5980 public override void Emit()
5983 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5985 object[] fi_val = new object[1];
5986 fi_val [0] = buffer_size;
5988 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5989 ctor_args, fi, fi_val);
5990 fixed_buffer_type.SetCustomAttribute (cab);
5992 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5993 FieldBuilder.SetCustomAttribute (cab);
5997 protected override bool IsFieldClsCompliant {
6003 #region IFixedField Members
6005 public FieldInfo Element {
6011 public Type ElementType {
6021 // The Field class is used to represents class/struct fields during parsing.
6023 public class Field : FieldMember {
6025 // Modifiers allowed in a class declaration
6027 const int AllowedModifiers =
6030 Modifiers.PROTECTED |
6031 Modifiers.INTERNAL |
6034 Modifiers.VOLATILE |
6038 public Field (TypeContainer parent, Expression type, int mod, string name,
6039 Object expr_or_array_init, Attributes attrs, Location loc)
6040 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
6041 expr_or_array_init, attrs, loc)
6045 public override bool Define ()
6047 if (!base.Define ())
6050 if (RootContext.WarningLevel > 1){
6051 Type ptype = Parent.TypeBuilder.BaseType;
6053 // ptype is only null for System.Object while compiling corlib.
6055 TypeContainer.FindMembers (
6056 ptype, MemberTypes.Method,
6057 BindingFlags.Public |
6058 BindingFlags.Static | BindingFlags.Instance,
6059 System.Type.FilterName, Name);
6063 if ((ModFlags & Modifiers.VOLATILE) != 0){
6064 if (!MemberType.IsClass){
6065 Type vt = MemberType;
6067 if (TypeManager.IsEnumType (vt))
6068 vt = TypeManager.EnumToUnderlying (MemberType);
6070 if (!((vt == TypeManager.bool_type) ||
6071 (vt == TypeManager.sbyte_type) ||
6072 (vt == TypeManager.byte_type) ||
6073 (vt == TypeManager.short_type) ||
6074 (vt == TypeManager.ushort_type) ||
6075 (vt == TypeManager.int32_type) ||
6076 (vt == TypeManager.uint32_type) ||
6077 (vt == TypeManager.char_type) ||
6078 (vt == TypeManager.float_type) ||
6079 (!vt.IsValueType))){
6081 677, Location, Parent.MakeName (Name) +
6082 " A volatile field can not be of type `" +
6083 TypeManager.CSharpName (vt) + "'");
6088 if ((ModFlags & Modifiers.READONLY) != 0){
6091 "A field can not be both volatile and readonly");
6096 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6098 if (Parent.Kind == Kind.Struct &&
6099 ((fa & FieldAttributes.Static) == 0) &&
6100 MemberType == Parent.TypeBuilder &&
6101 !TypeManager.IsBuiltinType (MemberType)){
6102 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6103 "' causes a cycle in the structure layout");
6108 FieldBuilder = Parent.TypeBuilder.DefineField (
6109 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6111 TypeManager.RegisterFieldBase (FieldBuilder, this);
6113 catch (ArgumentException) {
6114 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6121 protected override bool VerifyClsCompliance (DeclSpace ds)
6123 if (!base.VerifyClsCompliance (ds))
6126 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6127 Report.Warning (3026, 1, Location, "CLS-compliant field '{0}' cannot be volatile", GetSignatureForError ());
6135 // `set' and `get' accessors are represented with an Accessor.
6137 public class Accessor {
6139 // Null if the accessor is empty, or a Block if not
6141 public const int AllowedModifiers =
6143 Modifiers.PROTECTED |
6144 Modifiers.INTERNAL |
6147 public ToplevelBlock Block;
6148 public Attributes Attributes;
6149 public Location Location;
6150 public int ModFlags;
6152 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6157 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6162 // Ooouh Martin, templates are missing here.
6163 // When it will be possible move here a lot of child code and template method type.
6164 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
6165 protected MethodData method_data;
6166 protected ToplevelBlock block;
6167 protected ListDictionary declarative_security;
6169 // The accessor are created event if they are not wanted.
6170 // But we need them because their names are reserved.
6171 // Field says whether accessor will be emited or not
6172 public readonly bool IsDummy;
6174 protected readonly string prefix;
6176 ReturnParameter return_attributes;
6178 public AbstractPropertyEventMethod (MemberBase member, string prefix)
6179 : base (null, SetupName (prefix, member), null, member.Location)
6181 this.prefix = prefix;
6185 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
6187 : base (null, SetupName (prefix, member),
6188 accessor.Attributes, accessor.Location)
6190 this.prefix = prefix;
6191 this.block = accessor.Block;
6194 static MemberName SetupName (string prefix, MemberBase member)
6196 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
6199 public void UpdateName (MemberBase member)
6201 SetMemberName (SetupName (prefix, member));
6204 #region IMethodData Members
6206 public ToplevelBlock Block {
6216 public CallingConventions CallingConventions {
6218 return CallingConventions.Standard;
6222 public bool IsExcluded (EmitContext ec)
6227 GenericMethod IMethodData.GenericMethod {
6233 public MemberName MethodName {
6239 public abstract ObsoleteAttribute GetObsoleteAttribute ();
6240 public abstract Type[] ParameterTypes { get; }
6241 public abstract Type ReturnType { get; }
6242 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
6246 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6248 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6249 a.Type == TypeManager.conditional_attribute_type) {
6250 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 ());
6254 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6255 if (declarative_security == null)
6256 declarative_security = new ListDictionary ();
6257 a.ExtractSecurityPermissionSet (declarative_security);
6261 if (a.Target == AttributeTargets.Method) {
6262 method_data.MethodBuilder.SetCustomAttribute (cb);
6266 if (a.Target == AttributeTargets.ReturnValue) {
6267 if (return_attributes == null)
6268 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6270 return_attributes.ApplyAttributeBuilder (a, cb);
6274 ApplyToExtraTarget (a, cb);
6277 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6279 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6282 public override bool Define()
6284 throw new NotSupportedException ();
6287 public virtual void Emit (TypeContainer container)
6289 EmitMethod (container);
6291 if (declarative_security != null) {
6292 foreach (DictionaryEntry de in declarative_security) {
6293 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6300 protected virtual void EmitMethod (TypeContainer container)
6302 method_data.Emit (container, this);
6305 public override bool IsClsComplianceRequired(DeclSpace ds)
6310 public bool IsDuplicateImplementation (MethodCore method)
6312 if (Name != method.Name)
6315 Type[] param_types = method.ParameterTypes;
6317 if (param_types.Length != ParameterTypes.Length)
6320 for (int i = 0; i < param_types.Length; i++)
6321 if (param_types [i] != ParameterTypes [i])
6324 Report.SymbolRelatedToPreviousError (method);
6325 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with " +
6326 "the same parameter types", Parent.Name, Name);
6330 public override bool IsUsed
6340 public new Location Location {
6342 return base.Location;
6347 // Represents header string for documentation comment.
6349 public override string DocCommentHeader {
6350 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6353 protected override void VerifyObsoleteAttribute()
6360 // Properties and Indexers both generate PropertyBuilders, we use this to share
6361 // their common bits.
6363 abstract public class PropertyBase : MethodCore {
6365 public class GetMethod: PropertyMethod
6367 static string[] attribute_targets = new string [] { "method", "return" };
6369 public GetMethod (MethodCore method):
6370 base (method, "get_")
6374 public GetMethod (MethodCore method, Accessor accessor):
6375 base (method, accessor, "get_")
6379 public override MethodBuilder Define(TypeContainer container)
6381 base.Define (container);
6383 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
6385 if (!method_data.Define (container))
6388 return method_data.MethodBuilder;
6391 public override string GetSignatureForError (TypeContainer tc)
6393 return String.Concat (base.GetSignatureForError (tc), ".get");
6396 public override Type ReturnType {
6398 return method.MemberType;
6402 public override string[] ValidAttributeTargets {
6404 return attribute_targets;
6409 public class SetMethod: PropertyMethod {
6411 static string[] attribute_targets = new string [] { "method", "param", "return" };
6412 ImplicitParameter param_attr;
6414 public SetMethod (MethodCore method):
6415 base (method, "set_")
6419 public SetMethod (MethodCore method, Accessor accessor):
6420 base (method, accessor, "set_")
6424 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6426 if (a.Target == AttributeTargets.Parameter) {
6427 if (param_attr == null)
6428 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6430 param_attr.ApplyAttributeBuilder (a, cb);
6434 base.ApplyAttributeBuilder (a, cb);
6437 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
6439 Parameter [] parms = new Parameter [1];
6440 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
6441 Parameters parameters = new Parameters (parms, null, method.Location);
6443 bool old_unsafe = ec.InUnsafe;
6444 ec.InUnsafe = InUnsafe;
6445 Type [] types = parameters.GetParameterInfo (ec);
6446 ec.InUnsafe = old_unsafe;
6448 return new InternalParameters (types, parameters);
6451 public override MethodBuilder Define (TypeContainer container)
6453 if (container.EmitContext == null)
6454 throw new InternalErrorException ("SetMethod.Define called too early");
6456 base.Define (container);
6458 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6460 if (!method_data.Define (container))
6463 return method_data.MethodBuilder;
6466 public override string GetSignatureForError (TypeContainer tc)
6468 return String.Concat (base.GetSignatureForError (tc), ".set");
6471 public override Type[] ParameterTypes {
6473 return new Type[] { method.MemberType };
6477 public override Type ReturnType {
6479 return TypeManager.void_type;
6483 public override string[] ValidAttributeTargets {
6485 return attribute_targets;
6490 static string[] attribute_targets = new string [] { "property" };
6492 public abstract class PropertyMethod: AbstractPropertyEventMethod {
6493 protected readonly MethodCore method;
6494 protected MethodAttributes flags;
6496 public PropertyMethod (MethodCore method, string prefix)
6497 : base (method, prefix)
6499 this.method = method;
6500 Parent = method.Parent;
6503 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6504 : base (method, accessor, prefix)
6506 this.method = method;
6507 Parent = method.Parent;
6508 this.ModFlags = accessor.ModFlags;
6510 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6511 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
6515 public override AttributeTargets AttributeTargets {
6517 return AttributeTargets.Method;
6521 public override bool IsClsComplianceRequired(DeclSpace ds)
6523 return method.IsClsComplianceRequired (ds);
6526 public InternalParameters ParameterInfo
6529 return method_data.ParameterInfo;
6533 public virtual MethodBuilder Define (TypeContainer container)
6536 // Check for custom access modifier
6538 if (ModFlags == 0) {
6539 ModFlags = method.ModFlags;
6540 flags = method.flags;
6542 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6543 Report.Error (442, Location, "{0}': abstract properties cannot have private accessors", GetSignatureForError (container));
6546 CheckModifiers (container, ModFlags);
6547 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6548 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6549 flags = Modifiers.MethodAttr (ModFlags);
6550 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6557 public bool HasCustomAccessModifier
6560 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6564 public override Type[] ParameterTypes {
6566 return TypeManager.NoTypes;
6570 public override EmitContext CreateEmitContext (TypeContainer tc,
6573 return new EmitContext (
6574 tc, method.ds, method.Location, ig, ReturnType,
6575 method.ModFlags, false);
6578 public override ObsoleteAttribute GetObsoleteAttribute ()
6580 return method.GetObsoleteAttribute (method.ds);
6583 public override string GetSignatureForError (TypeContainer tc)
6585 return String.Concat (tc.Name, '.', method.Name);
6588 void CheckModifiers (TypeContainer container, int modflags)
6591 int mflags = method.ModFlags & Modifiers.Accessibility;
6593 if ((mflags & Modifiers.PUBLIC) != 0) {
6594 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6596 else if ((mflags & Modifiers.PROTECTED) != 0) {
6597 if ((mflags & Modifiers.INTERNAL) != 0)
6598 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6600 flags |= Modifiers.PRIVATE;
6602 else if ((mflags & Modifiers.INTERNAL) != 0)
6603 flags |= Modifiers.PRIVATE;
6605 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6606 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6607 GetSignatureForError (container));
6610 public override bool MarkForDuplicationCheck ()
6612 caching_flags |= Flags.TestMethodDuplication;
6617 public PropertyMethod Get, Set;
6618 public PropertyBuilder PropertyBuilder;
6619 public MethodBuilder GetBuilder, SetBuilder;
6621 protected EmitContext ec;
6623 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6624 int allowed_mod, bool is_iface, MemberName name,
6625 Parameters parameters, Attributes attrs,
6627 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6628 attrs, parameters, loc)
6632 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6634 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6635 a.Error_InvalidSecurityParent ();
6639 PropertyBuilder.SetCustomAttribute (cb);
6642 public override AttributeTargets AttributeTargets {
6644 return AttributeTargets.Property;
6648 public override bool Define ()
6653 if (!IsTypePermitted ())
6659 protected override bool DoDefine ()
6661 if (!base.DoDefine ())
6665 // Accessors modifiers check
6667 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6668 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6669 GetSignatureForError ());
6673 if ((Get.IsDummy || Set.IsDummy)
6674 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6675 Report.Error (276, Location,
6676 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6677 GetSignatureForError ());
6681 if (MemberType.IsAbstract && MemberType.IsSealed) {
6682 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6686 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6690 public override string GetSignatureForError()
6692 if (PropertyBuilder == null)
6693 return GetSignatureForError (Parent);
6695 return TypeManager.CSharpSignature (PropertyBuilder, false);
6698 protected override bool CheckForDuplications ()
6700 ArrayList ar = Parent.Indexers;
6702 int arLen = ar.Count;
6704 for (int i = 0; i < arLen; i++) {
6705 Indexer m = (Indexer) ar [i];
6706 if (IsDuplicateImplementation (m))
6711 ar = Parent.Properties;
6713 int arLen = ar.Count;
6715 for (int i = 0; i < arLen; i++) {
6716 Property m = (Property) ar [i];
6717 if (IsDuplicateImplementation (m))
6725 // TODO: rename to Resolve......
6726 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6728 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6729 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6731 if (base_property == null)
6734 base_ret_type = base_property.PropertyType;
6735 MethodInfo get_accessor = base_property.GetGetMethod (true);
6736 MethodInfo set_accessor = base_property.GetSetMethod (true);
6737 MethodAttributes get_accessor_access, set_accessor_access;
6739 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6740 if (Get != null && !Get.IsDummy && get_accessor == null) {
6741 Report.SymbolRelatedToPreviousError (base_property);
6742 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6745 if (Set != null && !Set.IsDummy && set_accessor == null) {
6746 Report.SymbolRelatedToPreviousError (base_property);
6747 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6752 // Check base class accessors access
6754 get_accessor_access = set_accessor_access = 0;
6755 if ((ModFlags & Modifiers.NEW) == 0) {
6756 if (get_accessor != null) {
6757 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6758 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6760 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6761 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6762 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6765 if (set_accessor != null) {
6766 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6767 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6769 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6770 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6771 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6776 // Get the less restrictive access
6778 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6781 public override void Emit ()
6784 // The PropertyBuilder can be null for explicit implementations, in that
6785 // case, we do not actually emit the ".property", so there is nowhere to
6786 // put the attribute
6788 if (PropertyBuilder != null && OptAttributes != null)
6789 OptAttributes.Emit (ec, this);
6801 /// Tests whether accessors are not in collision with some method (CS0111)
6803 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6805 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6808 public override bool IsUsed
6814 return Get.IsUsed | Set.IsUsed;
6818 protected override void SetMemberName (MemberName new_name)
6820 base.SetMemberName (new_name);
6822 Get.UpdateName (this);
6823 Set.UpdateName (this);
6826 public override string[] ValidAttributeTargets {
6828 return attribute_targets;
6833 // Represents header string for documentation comment.
6835 public override string DocCommentHeader {
6836 get { return "P:"; }
6840 public class Property : PropertyBase, IIteratorContainer {
6841 const int AllowedModifiers =
6844 Modifiers.PROTECTED |
6845 Modifiers.INTERNAL |
6849 Modifiers.OVERRIDE |
6850 Modifiers.ABSTRACT |
6853 Modifiers.METHOD_YIELDS |
6856 const int AllowedInterfaceModifiers =
6859 public Property (TypeContainer parent, Expression type, int mod_flags,
6860 bool is_iface, MemberName name, Attributes attrs,
6861 Accessor get_block, Accessor set_block, Location loc)
6862 : base (parent, type, mod_flags,
6863 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6864 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6867 if (get_block == null)
6868 Get = new GetMethod (this);
6870 Get = new GetMethod (this, get_block);
6872 if (set_block == null)
6873 Set = new SetMethod (this);
6875 Set = new SetMethod (this, set_block);
6878 public override bool Define ()
6880 if (!DoDefineBase ())
6883 if (!base.Define ())
6889 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6893 GetBuilder = Get.Define (Parent);
6894 if (GetBuilder == null)
6898 // Setup iterator if we are one
6900 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6901 Iterator iterator = new Iterator (
6902 Parent, "get", MemberType,
6904 ModFlags, Get.Block, Location);
6906 if (!iterator.DefineIterator ())
6908 Get.Block = iterator.Block;
6913 SetBuilder = Set.Define (Parent);
6914 if (SetBuilder == null)
6917 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6920 // FIXME - PropertyAttributes.HasDefault ?
6922 PropertyAttributes prop_attr = PropertyAttributes.None;
6924 prop_attr |= PropertyAttributes.RTSpecialName |
6925 PropertyAttributes.SpecialName;
6927 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6928 Name, prop_attr, MemberType, null);
6931 PropertyBuilder.SetGetMethod (GetBuilder);
6934 PropertyBuilder.SetSetMethod (SetBuilder);
6936 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6940 public void SetYields ()
6942 ModFlags |= Modifiers.METHOD_YIELDS;
6947 /// Gigantic workaround for lameness in SRE follows :
6948 /// This class derives from EventInfo and attempts to basically
6949 /// wrap around the EventBuilder so that FindMembers can quickly
6950 /// return this in it search for members
6952 public class MyEventBuilder : EventInfo {
6955 // We use this to "point" to our Builder which is
6956 // not really a MemberInfo
6958 EventBuilder MyBuilder;
6961 // We "catch" and wrap these methods
6963 MethodInfo raise, remove, add;
6965 EventAttributes attributes;
6966 Type declaring_type, reflected_type, event_type;
6971 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6973 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6975 // And now store the values in our own fields.
6977 declaring_type = type_builder;
6979 reflected_type = type_builder;
6981 attributes = event_attr;
6984 this.event_type = event_type;
6988 // Methods that you have to override. Note that you only need
6989 // to "implement" the variants that take the argument (those are
6990 // the "abstract" methods, the others (GetAddMethod()) are
6993 public override MethodInfo GetAddMethod (bool nonPublic)
6998 public override MethodInfo GetRemoveMethod (bool nonPublic)
7003 public override MethodInfo GetRaiseMethod (bool nonPublic)
7009 // These methods make "MyEventInfo" look like a Builder
7011 public void SetRaiseMethod (MethodBuilder raiseMethod)
7013 raise = raiseMethod;
7014 MyBuilder.SetRaiseMethod (raiseMethod);
7017 public void SetRemoveOnMethod (MethodBuilder removeMethod)
7019 remove = removeMethod;
7020 MyBuilder.SetRemoveOnMethod (removeMethod);
7023 public void SetAddOnMethod (MethodBuilder addMethod)
7026 MyBuilder.SetAddOnMethod (addMethod);
7029 public void SetCustomAttribute (CustomAttributeBuilder cb)
7031 MyBuilder.SetCustomAttribute (cb);
7034 public override object [] GetCustomAttributes (bool inherit)
7036 // FIXME : There's nothing which can be seemingly done here because
7037 // we have no way of getting at the custom attribute objects of the
7042 public override object [] GetCustomAttributes (Type t, bool inherit)
7044 // FIXME : Same here !
7048 public override bool IsDefined (Type t, bool b)
7053 public override EventAttributes Attributes {
7059 public override string Name {
7065 public override Type DeclaringType {
7067 return declaring_type;
7071 public override Type ReflectedType {
7073 return reflected_type;
7077 public Type EventType {
7083 public void SetUsed ()
7085 if (my_event != null) {
7086 my_event.status = FieldBase.Status.ASSIGNED;
7087 my_event.SetMemberIsUsed ();
7093 /// For case when event is declared like property (with add and remove accessors).
7095 public class EventProperty: Event {
7097 static string[] attribute_targets = new string [] { "event", "property" };
7099 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
7100 bool is_iface, MemberName name, Object init,
7101 Attributes attrs, Accessor add, Accessor remove,
7103 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
7105 Add = new AddDelegateMethod (this, add);
7106 Remove = new RemoveDelegateMethod (this, remove);
7108 // For this event syntax we don't report error CS0067
7109 // because it is hard to do it.
7113 public override string[] ValidAttributeTargets {
7115 return attribute_targets;
7121 /// Event is declared like field.
7123 public class EventField: Event {
7125 static string[] attribute_targets = new string [] { "event", "field", "method" };
7126 static string[] attribute_targets_interface = new string[] { "event", "method" };
7128 public EventField (TypeContainer parent, Expression type, int mod_flags,
7129 bool is_iface, MemberName name, Object init,
7130 Attributes attrs, Location loc)
7131 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
7133 Add = new AddDelegateMethod (this);
7134 Remove = new RemoveDelegateMethod (this);
7137 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7139 if (a.Target == AttributeTargets.Field) {
7140 FieldBuilder.SetCustomAttribute (cb);
7144 if (a.Target == AttributeTargets.Method) {
7145 Add.ApplyAttributeBuilder (a, cb);
7146 Remove.ApplyAttributeBuilder (a, cb);
7150 base.ApplyAttributeBuilder (a, cb);
7153 public override string[] ValidAttributeTargets {
7155 return IsInterface ? attribute_targets_interface : attribute_targets;
7160 public abstract class Event : FieldBase {
7162 protected sealed class AddDelegateMethod: DelegateMethod
7165 public AddDelegateMethod (Event method):
7166 base (method, "add_")
7170 public AddDelegateMethod (Event method, Accessor accessor):
7171 base (method, accessor, "add_")
7175 protected override MethodInfo DelegateMethodInfo {
7177 return TypeManager.delegate_combine_delegate_delegate;
7183 protected sealed class RemoveDelegateMethod: DelegateMethod
7185 public RemoveDelegateMethod (Event method):
7186 base (method, "remove_")
7190 public RemoveDelegateMethod (Event method, Accessor accessor):
7191 base (method, accessor, "remove_")
7195 protected override MethodInfo DelegateMethodInfo {
7197 return TypeManager.delegate_remove_delegate_delegate;
7203 public abstract class DelegateMethod: AbstractPropertyEventMethod
7205 protected readonly Event method;
7206 ImplicitParameter param_attr;
7208 static string[] attribute_targets = new string [] { "method", "param", "return" };
7210 public DelegateMethod (Event method, string prefix)
7211 : base (method, prefix)
7213 this.method = method;
7216 public DelegateMethod (Event method, Accessor accessor, string prefix)
7217 : base (method, accessor, prefix)
7219 this.method = method;
7222 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7224 if (a.Target == AttributeTargets.Parameter) {
7225 if (param_attr == null)
7226 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7228 param_attr.ApplyAttributeBuilder (a, cb);
7232 base.ApplyAttributeBuilder (a, cb);
7235 public override AttributeTargets AttributeTargets {
7237 return AttributeTargets.Method;
7241 public override bool IsClsComplianceRequired(DeclSpace ds)
7243 return method.IsClsComplianceRequired (ds);
7246 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
7248 method_data = new MethodData (method, ip, method.ModFlags,
7249 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7251 if (!method_data.Define (container))
7254 MethodBuilder mb = method_data.MethodBuilder;
7255 mb.DefineParameter (1, ParameterAttributes.None, "value");
7260 protected override void EmitMethod (TypeContainer tc)
7262 if (block != null) {
7263 base.EmitMethod (tc);
7267 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7270 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
7271 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
7273 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
7274 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7275 ig.Emit (OpCodes.Ldsfld, field_info);
7276 ig.Emit (OpCodes.Ldarg_0);
7277 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7278 ig.Emit (OpCodes.Castclass, method.MemberType);
7279 ig.Emit (OpCodes.Stsfld, field_info);
7281 ig.Emit (OpCodes.Ldarg_0);
7282 ig.Emit (OpCodes.Ldarg_0);
7283 ig.Emit (OpCodes.Ldfld, field_info);
7284 ig.Emit (OpCodes.Ldarg_1);
7285 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7286 ig.Emit (OpCodes.Castclass, method.MemberType);
7287 ig.Emit (OpCodes.Stfld, field_info);
7289 ig.Emit (OpCodes.Ret);
7292 protected abstract MethodInfo DelegateMethodInfo { get; }
7294 public override Type[] ParameterTypes {
7296 return new Type[] { method.MemberType };
7300 public override Type ReturnType {
7302 return TypeManager.void_type;
7306 public override EmitContext CreateEmitContext (TypeContainer tc,
7309 return new EmitContext (
7310 tc, method.Parent, Location, ig, ReturnType,
7311 method.ModFlags, false);
7314 public override string GetSignatureForError (TypeContainer tc)
7316 return String.Concat (tc.Name, '.', method.Name);
7319 public override ObsoleteAttribute GetObsoleteAttribute ()
7321 return method.GetObsoleteAttribute (method.Parent);
7324 public override string[] ValidAttributeTargets {
7326 return attribute_targets;
7332 const int AllowedModifiers =
7335 Modifiers.PROTECTED |
7336 Modifiers.INTERNAL |
7341 Modifiers.OVERRIDE |
7345 const int AllowedInterfaceModifiers =
7348 public DelegateMethod Add, Remove;
7349 public MyEventBuilder EventBuilder;
7350 public MethodBuilder AddBuilder, RemoveBuilder;
7352 public Event (TypeContainer parent, Expression type, int mod_flags,
7353 bool is_iface, MemberName name, Object init, Attributes attrs,
7355 : base (parent, type, mod_flags,
7356 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7357 name, init, attrs, loc)
7359 IsInterface = is_iface;
7362 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7364 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7365 a.Error_InvalidSecurityParent ();
7369 EventBuilder.SetCustomAttribute (cb);
7372 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7374 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7377 public override AttributeTargets AttributeTargets {
7379 return AttributeTargets.Event;
7383 public override bool Define ()
7385 EventAttributes e_attr;
7386 e_attr = EventAttributes.None;
7388 if (!DoDefineBase ())
7394 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
7395 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
7396 "': abstract event can not have an initializer");
7400 if (!TypeManager.IsDelegateType (MemberType)) {
7401 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
7402 "' : event must be of a delegate type");
7406 EmitContext ec = Parent.EmitContext;
7408 throw new InternalErrorException ("Event.Define called too early?");
7409 bool old_unsafe = ec.InUnsafe;
7410 ec.InUnsafe = InUnsafe;
7412 Parameter [] parms = new Parameter [1];
7413 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
7414 Parameters parameters = new Parameters (parms, null, Location);
7415 Type [] types = parameters.GetParameterInfo (ec);
7416 InternalParameters ip = new InternalParameters (types, parameters);
7418 ec.InUnsafe = old_unsafe;
7424 // Now define the accessors
7427 AddBuilder = Add.Define (Parent, ip);
7428 if (AddBuilder == null)
7431 RemoveBuilder = Remove.Define (Parent, ip);
7432 if (RemoveBuilder == null)
7435 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7437 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7438 FieldBuilder = Parent.TypeBuilder.DefineField (
7440 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7441 TypeManager.RegisterPrivateFieldOfEvent (
7442 (EventInfo) EventBuilder, FieldBuilder);
7443 TypeManager.RegisterFieldBase (FieldBuilder, this);
7446 EventBuilder.SetAddOnMethod (AddBuilder);
7447 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7449 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7453 protected override bool CheckBase ()
7455 if (!base.CheckBase ())
7458 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7459 if (!(conflict_symbol is EventInfo)) {
7460 Report.SymbolRelatedToPreviousError (conflict_symbol);
7461 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
7469 public override void Emit ()
7471 if (OptAttributes != null) {
7472 EmitContext ec = new EmitContext (
7473 Parent, Location, null, MemberType, ModFlags);
7474 OptAttributes.Emit (ec, this);
7478 Remove.Emit (Parent);
7483 public override string GetSignatureForError ()
7485 if (EventBuilder == null)
7486 return base.GetSignatureForError (Parent);
7488 return TypeManager.GetFullNameSignature (EventBuilder);
7492 // Represents header string for documentation comment.
7494 public override string DocCommentHeader {
7495 get { return "E:"; }
7500 public class Indexer : PropertyBase {
7502 class GetIndexerMethod: GetMethod
7504 public GetIndexerMethod (MethodCore method):
7509 public GetIndexerMethod (MethodCore method, Accessor accessor):
7510 base (method, accessor)
7514 // TODO: one GetSignatureForError is enough (reuse Parent member)
7515 public override string GetSignatureForError (TypeContainer tc)
7517 string core = base.GetSignatureForError (tc);
7518 return core.Replace (TypeContainer.DefaultIndexerName,
7519 String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
7522 public override Type[] ParameterTypes {
7524 return method.ParameterTypes;
7529 class SetIndexerMethod: SetMethod
7531 readonly Parameters parameters;
7533 public SetIndexerMethod (MethodCore method):
7538 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7539 base (method, accessor)
7541 this.parameters = parameters;
7544 public override Type[] ParameterTypes {
7546 int top = method.ParameterTypes.Length;
7547 Type [] set_pars = new Type [top + 1];
7548 method.ParameterTypes.CopyTo (set_pars, 0);
7549 set_pars [top] = method.MemberType;
7554 protected override InternalParameters GetParameterInfo (EmitContext ec)
7556 Parameter [] fixed_parms = parameters.FixedParameters;
7558 if (fixed_parms == null){
7559 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7560 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7561 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7563 // Here is the problem: the `value' parameter has
7564 // to come *after* the array parameter in the declaration
7566 // X (object [] x, Type value)
7569 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7570 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7574 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7576 fixed_parms.CopyTo (tmp, 0);
7577 tmp [fixed_parms.Length] = new Parameter (
7578 method.Type, "value", Parameter.Modifier.NONE, null);
7580 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7581 Type [] types = set_formal_params.GetParameterInfo (ec);
7583 return new InternalParameters (types, set_formal_params);
7587 const int AllowedModifiers =
7590 Modifiers.PROTECTED |
7591 Modifiers.INTERNAL |
7595 Modifiers.OVERRIDE |
7600 const int AllowedInterfaceModifiers =
7604 // Are we implementing an interface ?
7606 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7607 bool is_iface, Parameters parameters, Attributes attrs,
7608 Accessor get_block, Accessor set_block, Location loc)
7609 : base (parent, type, mod,
7610 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7611 is_iface, name, parameters, attrs, loc)
7613 if (get_block == null)
7614 Get = new GetIndexerMethod (this);
7616 Get = new GetIndexerMethod (this, get_block);
7618 if (set_block == null)
7619 Set = new SetIndexerMethod (this);
7621 Set = new SetIndexerMethod (this, parameters, set_block);
7624 public override bool Define ()
7626 PropertyAttributes prop_attr =
7627 PropertyAttributes.RTSpecialName |
7628 PropertyAttributes.SpecialName;
7630 if (!DoDefineBase ())
7633 if (!base.Define ())
7636 if (MemberType == TypeManager.void_type) {
7637 Report.Error (620, Location, "Indexers cannot have void type");
7641 if (OptAttributes != null) {
7642 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7643 if (indexer_attr != null) {
7644 // Remove the attribute from the list because it is not emitted
7645 OptAttributes.Attrs.Remove (indexer_attr);
7647 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7649 if (IsExplicitImpl) {
7650 Report.Error (415, indexer_attr.Location,
7651 "The 'IndexerName' attribute is valid only on an " +
7652 "indexer that is not an explicit interface member declaration");
7656 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7657 Report.Error (609, indexer_attr.Location,
7658 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7662 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7663 Report.Error (633, indexer_attr.Location,
7664 "The argument to the 'IndexerName' attribute must be a valid identifier");
7670 if (InterfaceType != null) {
7671 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7672 if (base_IndexerName != Name)
7673 ShortName = base_IndexerName;
7676 if (!Parent.AddToMemberContainer (this) ||
7677 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7683 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7685 GetBuilder = Get.Define (Parent);
7686 if (GetBuilder == null)
7691 SetBuilder = Set.Define (Parent);
7692 if (SetBuilder == null)
7697 // Now name the parameters
7699 Parameter [] p = Parameters.FixedParameters;
7701 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7702 Report.Error (631, Location, "ref and out are not valid in this context");
7708 for (i = 0; i < p.Length; ++i) {
7710 GetBuilder.DefineParameter (
7711 i + 1, p [i].Attributes, p [i].Name);
7714 SetBuilder.DefineParameter (
7715 i + 1, p [i].Attributes, p [i].Name);
7719 SetBuilder.DefineParameter (
7720 i + 1, ParameterAttributes.None, "value");
7722 if (i != ParameterTypes.Length) {
7723 Parameter array_param = Parameters.ArrayParameter;
7725 SetBuilder.DefineParameter (
7726 i + 1, array_param.Attributes, array_param.Name);
7730 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7731 Name, prop_attr, MemberType, ParameterTypes);
7734 PropertyBuilder.SetGetMethod (GetBuilder);
7737 PropertyBuilder.SetSetMethod (SetBuilder);
7739 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7744 public override string GetSignatureForError ()
7746 if (PropertyBuilder == null)
7747 return GetSignatureForError (Parent);
7749 return TypeManager.CSharpSignature (PropertyBuilder, true);
7752 public override string GetSignatureForError(TypeContainer tc)
7754 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7757 public override bool MarkForDuplicationCheck ()
7759 caching_flags |= Flags.TestMethodDuplication;
7765 public class Operator : MethodCore, IIteratorContainer {
7767 const int AllowedModifiers =
7773 public enum OpType : byte {
7783 // Unary and Binary operators
7806 // Implicit and Explicit
7811 public readonly OpType OperatorType;
7812 public MethodBuilder OperatorMethodBuilder;
7814 public Method OperatorMethod;
7816 static string[] attribute_targets = new string [] { "method", "return" };
7818 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7819 int mod_flags, Parameters parameters,
7820 ToplevelBlock block, Attributes attrs, Location loc)
7821 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7822 new MemberName ("op_" + type), attrs, parameters, loc)
7824 OperatorType = type;
7828 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7830 OperatorMethod.ApplyAttributeBuilder (a, cb);
7833 public override AttributeTargets AttributeTargets {
7835 return AttributeTargets.Method;
7839 protected override bool CheckGenericOverride (MethodInfo method, string name)
7844 protected override bool CheckForDuplications()
7846 ArrayList ar = Parent.Operators;
7848 int arLen = ar.Count;
7850 for (int i = 0; i < arLen; i++) {
7851 Operator o = (Operator) ar [i];
7852 if (IsDuplicateImplementation (o))
7857 ar = Parent.Methods;
7859 int arLen = ar.Count;
7861 for (int i = 0; i < arLen; i++) {
7862 Method m = (Method) ar [i];
7863 if (IsDuplicateImplementation (m))
7871 public override bool Define ()
7873 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7874 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7875 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7882 if (MemberType == TypeManager.void_type) {
7883 Report.Error (590, Location, "User-defined operators cannot return void");
7887 OperatorMethod = new Method (
7888 Parent, null, Type, ModFlags, false, MemberName,
7889 Parameters, OptAttributes, Location);
7891 OperatorMethod.Block = Block;
7892 OperatorMethod.IsOperator = true;
7893 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7894 OperatorMethod.Define ();
7896 if (OperatorMethod.MethodBuilder == null)
7899 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7901 parameter_types = OperatorMethod.ParameterTypes;
7902 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7903 Type return_type = OperatorMethod.ReturnType;
7904 Type first_arg_type = parameter_types [0];
7909 // Rules for conversion operators
7911 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7912 if (first_arg_type == return_type && first_arg_type == declaring_type){
7915 "User-defined conversion cannot take an object of the " +
7916 "enclosing type and convert to an object of the enclosing" +
7921 if (first_arg_type != declaring_type && return_type != declaring_type){
7924 "User-defined conversion must convert to or from the " +
7929 if (first_arg_type == TypeManager.object_type ||
7930 return_type == TypeManager.object_type){
7933 "User-defined conversion cannot convert to or from " +
7938 if (first_arg_type.IsInterface || return_type.IsInterface){
7941 "User-defined conversion cannot convert to or from an " +
7946 if (first_arg_type.IsSubclassOf (return_type)
7947 || return_type.IsSubclassOf (first_arg_type)){
7948 if (declaring_type.IsSubclassOf (return_type)) {
7949 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7952 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7955 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7956 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7957 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");
7960 } else if (Parameters.FixedParameters.Length == 1) {
7961 // Checks for Unary operators
7963 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7964 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7965 Report.Error (448, Location,
7966 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7969 if (first_arg_type != declaring_type){
7971 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7976 if (first_arg_type != declaring_type){
7979 "The parameter of a unary operator must be the " +
7984 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7985 if (return_type != TypeManager.bool_type){
7988 "The return type of operator True or False " +
7995 if (OperatorType == OpType.BitwiseAnd &&
7996 (first_arg_type != return_type || first_arg_type != parameter_types [1])) {
7997 Report.Error (217, Location, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
7998 "must have the same return type as the type of its 2 parameters", GetSignatureForError ());
8002 // Checks for Binary operators
8004 if (first_arg_type != declaring_type &&
8005 parameter_types [1] != declaring_type){
8008 "One of the parameters of a binary operator must " +
8009 "be the containing type");
8017 public override void Emit ()
8020 // abstract or extern methods have no bodies
8022 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
8025 OperatorMethod.Emit ();
8029 // Operator cannot be override
8030 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
8035 public static string GetName (OpType ot)
8038 case OpType.LogicalNot:
8040 case OpType.OnesComplement:
8042 case OpType.Increment:
8044 case OpType.Decrement:
8050 case OpType.Addition:
8052 case OpType.Subtraction:
8054 case OpType.UnaryPlus:
8056 case OpType.UnaryNegation:
8058 case OpType.Multiply:
8060 case OpType.Division:
8062 case OpType.Modulus:
8064 case OpType.BitwiseAnd:
8066 case OpType.BitwiseOr:
8068 case OpType.ExclusiveOr:
8070 case OpType.LeftShift:
8072 case OpType.RightShift:
8074 case OpType.Equality:
8076 case OpType.Inequality:
8078 case OpType.GreaterThan:
8080 case OpType.LessThan:
8082 case OpType.GreaterThanOrEqual:
8084 case OpType.LessThanOrEqual:
8086 case OpType.Implicit:
8088 case OpType.Explicit:
8094 public override string GetSignatureForError (TypeContainer tc)
8096 StringBuilder sb = new StringBuilder ();
8097 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
8098 Parameters.FixedParameters [0].GetSignatureForError ());
8100 if (Parameters.FixedParameters.Length > 1) {
8102 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
8105 return sb.ToString ();
8108 public override string GetSignatureForError ()
8113 public override bool MarkForDuplicationCheck ()
8115 caching_flags |= Flags.TestMethodDuplication;
8119 public override string ToString ()
8121 if (OperatorMethod == null)
8124 Type return_type = OperatorMethod.ReturnType;
8125 Type [] param_types = OperatorMethod.ParameterTypes;
8127 if (Parameters.FixedParameters.Length == 1)
8128 return String.Format (
8129 "{0} operator {1}({2})",
8130 TypeManager.CSharpName (return_type),
8131 GetName (OperatorType),
8134 return String.Format (
8135 "{0} operator {1}({2}, {3})",
8136 TypeManager.CSharpName (return_type),
8137 GetName (OperatorType),
8138 param_types [0], param_types [1]);
8141 public override string[] ValidAttributeTargets {
8143 return attribute_targets;
8147 public void SetYields ()
8149 ModFlags |= Modifiers.METHOD_YIELDS;
8154 // This is used to compare method signatures
8156 struct MethodSignature {
8158 public Type RetType;
8159 public Type [] Parameters;
8162 /// This delegate is used to extract methods which have the
8163 /// same signature as the argument
8165 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8167 public MethodSignature (string name, Type ret_type, Type [] parameters)
8172 if (parameters == null)
8173 Parameters = TypeManager.NoTypes;
8175 Parameters = parameters;
8178 public override string ToString ()
8181 if (Parameters.Length != 0){
8182 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8183 for (int i = 0; i < Parameters.Length; i++){
8184 sb.Append (Parameters [i]);
8185 if (i+1 < Parameters.Length)
8188 pars = sb.ToString ();
8191 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8194 public override int GetHashCode ()
8196 return Name.GetHashCode ();
8199 public override bool Equals (Object o)
8201 MethodSignature other = (MethodSignature) o;
8203 if (other.Name != Name)
8206 if (other.RetType != RetType)
8209 if (Parameters == null){
8210 if (other.Parameters == null)
8215 if (other.Parameters == null)
8218 int c = Parameters.Length;
8219 if (other.Parameters.Length != c)
8222 for (int i = 0; i < c; i++)
8223 if (other.Parameters [i] != Parameters [i])
8229 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8231 MethodSignature sig = (MethodSignature) filter_criteria;
8233 if (m.Name != sig.Name)
8237 MethodInfo mi = m as MethodInfo;
8238 PropertyInfo pi = m as PropertyInfo;
8241 ReturnType = mi.ReturnType;
8242 else if (pi != null)
8243 ReturnType = pi.PropertyType;
8248 // we use sig.RetType == null to mean `do not check the
8249 // method return value.
8251 if (sig.RetType != null)
8252 if (ReturnType != sig.RetType)
8257 args = TypeManager.GetArgumentTypes (mi);
8259 args = TypeManager.GetArgumentTypes (pi);
8260 Type [] sigp = sig.Parameters;
8262 if (args.Length != sigp.Length)
8265 for (int i = args.Length; i > 0; ){
8267 if (args [i] != sigp [i])