2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
36 using System.Collections;
37 using System.Collections.Specialized;
38 using System.Reflection;
39 using System.Reflection.Emit;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42 using System.Security;
43 using System.Security.Permissions;
46 using Mono.CompilerServices.SymbolWriter;
48 namespace Mono.CSharp {
58 /// This is the base class for structs and classes.
60 public abstract class TypeContainer : DeclSpace, IMemberContainer {
62 protected class CircularDepException: Exception
64 public TypeContainer Container;
65 public CircularDepException (TypeContainer tc)
71 public class MemberCoreArrayList: ArrayList
74 /// Defines the MemberCore objects that are in this array
76 public virtual void DefineContainerMembers ()
78 foreach (MemberCore mc in this) {
83 public virtual void Emit ()
85 foreach (MemberCore mc in this)
90 public class MethodArrayList: MemberCoreArrayList
98 CachedMethods cached_method;
99 TypeContainer container;
101 public MethodArrayList (TypeContainer container)
103 this.container = container;
107 /// Method container contains Equals method
109 public bool HasEquals {
111 cached_method |= CachedMethods.Equals;
115 return (cached_method & CachedMethods.Equals) != 0;
120 /// Method container contains GetHashCode method
122 public bool HasGetHashCode {
124 cached_method |= CachedMethods.GetHashCode;
128 return (cached_method & CachedMethods.GetHashCode) != 0;
132 public override void DefineContainerMembers ()
134 base.DefineContainerMembers ();
136 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
137 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
143 public sealed class IndexerArrayList: MemberCoreArrayList
146 /// The indexer name for this container
148 public string IndexerName = DefaultIndexerName;
150 bool seen_normal_indexers = false;
152 TypeContainer container;
154 public IndexerArrayList (TypeContainer container)
156 this.container = container;
160 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
161 /// class is consistent. Either it is `Item' or it is the name defined by all the
162 /// indexers with the `IndexerName' attribute.
164 /// Turns out that the IndexerNameAttribute is applied to each indexer,
165 /// but it is never emitted, instead a DefaultMember attribute is attached
168 public override void DefineContainerMembers()
170 base.DefineContainerMembers ();
172 string class_indexer_name = null;
175 // If there's both an explicit and an implicit interface implementation, the
176 // explicit one actually implements the interface while the other one is just
177 // a normal indexer. See bug #37714.
180 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
181 foreach (Indexer i in this) {
182 if (i.InterfaceType != null) {
183 if (seen_normal_indexers)
184 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
188 seen_normal_indexers = true;
190 if (class_indexer_name == null) {
191 class_indexer_name = i.ShortName;
195 if (i.ShortName != class_indexer_name)
196 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
199 if (class_indexer_name != null)
200 IndexerName = class_indexer_name;
203 public override void Emit ()
207 if (!seen_normal_indexers)
210 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
211 container.TypeBuilder.SetCustomAttribute (cb);
215 public class OperatorArrayList: MemberCoreArrayList
217 TypeContainer container;
219 public OperatorArrayList (TypeContainer container)
221 this.container = container;
225 // Operator pair checking
230 public Type ret_type;
231 public Type type1, type2;
233 public Operator.OpType ot;
235 public OperatorEntry (int f, Operator o)
239 ret_type = o.OperatorMethod.ReturnType;
240 Type [] pt = o.OperatorMethod.ParameterTypes;
247 public override int GetHashCode ()
249 return ret_type.GetHashCode ();
252 public override bool Equals (object o)
254 OperatorEntry other = (OperatorEntry) o;
256 if (other.ret_type != ret_type)
258 if (other.type1 != type1)
260 if (other.type2 != type2)
267 // Checks that some operators come in pairs:
273 // They are matched based on the return type and the argument types
275 void CheckPairedOperators ()
277 Hashtable pairs = new Hashtable (null, null);
278 Operator true_op = null;
279 Operator false_op = null;
280 bool has_equality_or_inequality = false;
282 // Register all the operators we care about.
283 foreach (Operator op in this){
286 // Skip erroneous code.
287 if (op.OperatorMethod == null)
290 switch (op.OperatorType){
291 case Operator.OpType.Equality:
293 has_equality_or_inequality = true;
295 case Operator.OpType.Inequality:
297 has_equality_or_inequality = true;
300 case Operator.OpType.True:
303 case Operator.OpType.False:
307 case Operator.OpType.GreaterThan:
309 case Operator.OpType.LessThan:
312 case Operator.OpType.GreaterThanOrEqual:
314 case Operator.OpType.LessThanOrEqual:
320 OperatorEntry oe = new OperatorEntry (reg, op);
322 object o = pairs [oe];
326 oe = (OperatorEntry) o;
331 if (true_op != null){
332 if (false_op == null)
333 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
334 } else if (false_op != null)
335 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
338 // Look for the mistakes.
340 foreach (DictionaryEntry de in pairs){
341 OperatorEntry oe = (OperatorEntry) de.Key;
348 case Operator.OpType.Equality:
351 case Operator.OpType.Inequality:
354 case Operator.OpType.GreaterThan:
357 case Operator.OpType.LessThan:
360 case Operator.OpType.GreaterThanOrEqual:
363 case Operator.OpType.LessThanOrEqual:
367 Report.Error (216, oe.op.Location,
368 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
371 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
372 if (container.Methods == null || !container.Methods.HasEquals)
373 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
375 if (container.Methods == null || !container.Methods.HasGetHashCode)
376 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
380 public override void DefineContainerMembers ()
382 base.DefineContainerMembers ();
383 CheckPairedOperators ();
388 // Whether this is a struct, class or interface
389 public readonly Kind Kind;
391 // Holds a list of classes and structures
394 // Holds the list of properties
395 MemberCoreArrayList properties;
397 // Holds the list of enumerations
398 MemberCoreArrayList enums;
400 // Holds the list of delegates
401 MemberCoreArrayList delegates;
403 // Holds the list of constructors
404 protected MemberCoreArrayList instance_constructors;
406 // Holds the list of fields
407 MemberCoreArrayList fields;
409 // Holds a list of fields that have initializers
410 protected ArrayList initialized_fields;
412 // Holds a list of static fields that have initializers
413 protected ArrayList initialized_static_fields;
415 // Holds the list of constants
416 MemberCoreArrayList constants;
419 MemberCoreArrayList interfaces;
421 // Holds the methods.
422 MethodArrayList methods;
425 protected MemberCoreArrayList events;
427 // Holds the indexers
428 IndexerArrayList indexers;
430 // Holds the operators
431 MemberCoreArrayList operators;
433 // Holds the iterators
436 // Holds the parts of a partial class;
440 // Pointers to the default constructor and the default static constructor
442 protected Constructor default_constructor;
443 protected Constructor default_static_constructor;
446 // Whether we have at least one non-static field
448 bool have_nonstatic_fields = false;
451 // This one is computed after we can distinguish interfaces
452 // from classes from the arraylist `type_bases'
454 string base_class_name;
456 TypeExpr[] iface_exprs;
458 ArrayList type_bases;
460 bool members_defined;
461 bool members_defined_ok;
463 // The interfaces we implement.
464 protected Type[] ifaces;
465 protected Type ptype;
467 // The base member cache and our member cache
468 MemberCache base_cache;
469 MemberCache member_cache;
471 public const string DefaultIndexerName = "Item";
474 GenericTypeParameterBuilder[] gen_params;
476 // This is used to catch recursive definitions in declarations.
477 protected bool InTransit;
479 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
480 Attributes attrs, Kind kind, Location l)
481 : base (ns, parent, name, attrs, l)
483 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
484 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
488 types = new ArrayList ();
490 base_class_name = null;
493 public bool AddToMemberContainer (MemberCore symbol)
495 return AddToContainer (symbol, symbol.Name);
498 bool AddToTypeContainer (DeclSpace ds)
500 // Parent == null ==> this == RootContext.Tree.Types
501 return AddToContainer (ds, (Parent == null) ? ds.Name : ds.Basename);
504 public void AddConstant (Const constant)
506 if (!AddToMemberContainer (constant))
509 if (constants == null)
510 constants = new MemberCoreArrayList ();
512 constants.Add (constant);
515 public void AddEnum (Mono.CSharp.Enum e)
517 if (!AddToTypeContainer (e))
521 enums = new MemberCoreArrayList ();
526 public void AddClassOrStruct (TypeContainer c)
528 if (!AddToTypeContainer (c))
534 public void AddDelegate (Delegate d)
536 if (!AddToTypeContainer (d))
539 if (delegates == null)
540 delegates = new MemberCoreArrayList ();
545 public void AddMethod (Method method)
547 if (!AddToMemberContainer (method))
551 methods = new MethodArrayList (this);
553 if (method.MemberName.Left != null)
554 methods.Insert (0, method);
556 methods.Add (method);
559 public void AddConstructor (Constructor c)
561 if (c.Name != MemberName.Name) {
562 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
565 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
568 if (default_static_constructor != null) {
569 Report.SymbolRelatedToPreviousError (default_static_constructor);
570 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
571 "called '{1}' with the same parameter types", Name, c.Name);
575 default_static_constructor = c;
578 if (default_constructor != null) {
579 Report.SymbolRelatedToPreviousError (default_constructor);
580 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
581 "called '{1}' with the same parameter types", Name, c.Name);
584 default_constructor = c;
587 if (instance_constructors == null)
588 instance_constructors = new MemberCoreArrayList ();
590 instance_constructors.Add (c);
594 public void AddInterface (TypeContainer iface)
596 if (!AddToTypeContainer (iface))
599 if (interfaces == null) {
600 interfaces = new MemberCoreArrayList ();
603 interfaces.Add (iface);
606 public void AddField (FieldMember field)
608 if (!AddToMemberContainer (field))
612 fields = new MemberCoreArrayList ();
616 if (field.HasInitializer)
617 RegisterFieldForInitialization (field);
619 if ((field.ModFlags & Modifiers.STATIC) == 0)
620 have_nonstatic_fields = true;
623 public void AddProperty (Property prop)
625 if (!AddToMemberContainer (prop) ||
626 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
629 if (properties == null)
630 properties = new MemberCoreArrayList ();
632 if (prop.MemberName.Left != null)
633 properties.Insert (0, prop);
635 properties.Add (prop);
638 public void AddEvent (Event e)
640 if (!AddToMemberContainer (e))
643 if (e is EventProperty) {
644 if (!AddToMemberContainer (e.Add))
647 if (!AddToMemberContainer (e.Remove))
652 events = new MemberCoreArrayList ();
658 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
660 public void AddIndexer (Indexer i)
662 if (indexers == null)
663 indexers = new IndexerArrayList (this);
665 if (i.IsExplicitImpl)
666 indexers.Insert (0, i);
671 public void AddOperator (Operator op)
673 if (!AddToMemberContainer (op))
676 if (operators == null)
677 operators = new OperatorArrayList (this);
682 public void AddIterator (Iterator i)
684 if (iterators == null)
685 iterators = new ArrayList ();
690 public void AddType (TypeContainer tc)
695 public void AddPart (ClassPart part)
698 parts = new ArrayList ();
703 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
705 if (a.Type == TypeManager.default_member_type) {
706 if (Indexers != null) {
707 Report.Error (646, a.Location,
708 "Cannot specify the DefaultMember attribute on" +
709 " a type containing an indexer");
714 base.ApplyAttributeBuilder (a, cb);
717 public override AttributeTargets AttributeTargets {
721 return AttributeTargets.Class;
723 return AttributeTargets.Struct;
725 return AttributeTargets.Interface;
727 throw new NotSupportedException ();
732 public ArrayList Types {
738 public MethodArrayList Methods {
744 public ArrayList Constants {
750 public ArrayList Interfaces {
756 public ArrayList Iterators {
764 return base_class_name;
768 public ArrayList Bases {
778 public ArrayList Fields {
784 public ArrayList InstanceConstructors {
786 return instance_constructors;
790 public ArrayList Properties {
796 public ArrayList Events {
802 public ArrayList Enums {
808 public ArrayList Indexers {
814 public ArrayList Operators {
820 public ArrayList Delegates {
826 public ArrayList Parts {
832 protected override TypeAttributes TypeAttr {
834 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
838 public string IndexerName {
840 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
844 public virtual void RegisterFieldForInitialization (FieldMember field)
846 if ((field.ModFlags & Modifiers.STATIC) != 0){
847 if (initialized_static_fields == null)
848 initialized_static_fields = new ArrayList ();
850 initialized_static_fields.Add (field);
852 if (initialized_fields == null)
853 initialized_fields = new ArrayList ();
855 initialized_fields.Add (field);
860 // Emits the instance field initializers
862 public virtual bool EmitFieldInitializers (EmitContext ec)
865 Expression instance_expr;
868 fields = initialized_static_fields;
869 instance_expr = null;
871 fields = initialized_fields;
872 instance_expr = new This (Location.Null).Resolve (ec);
878 foreach (FieldMember f in fields){
879 Expression e = f.GetInitializerExpression (ec);
883 Location l = f.Location;
884 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
885 fe.InstanceExpression = instance_expr;
887 ExpressionStatement a = new Assign (fe, e, l);
889 a = a.ResolveStatement (ec);
893 Constant c = e as Constant;
895 if (c.IsDefaultValue)
899 a.EmitStatement (ec);
906 // Defines the default constructors
908 protected void DefineDefaultConstructor (bool is_static)
912 // The default constructor is public
913 // If the class is abstract, the default constructor is protected
914 // The default static constructor is private
916 int mods = Modifiers.PUBLIC;
918 mods = Modifiers.STATIC | Modifiers.PRIVATE;
919 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
920 mods = Modifiers.PROTECTED;
922 TypeContainer constructor_parent = this;
924 constructor_parent = (TypeContainer) Parts [0];
926 c = new Constructor (constructor_parent, MemberName.Name, mods,
927 Parameters.EmptyReadOnlyParameters,
928 new ConstructorBaseInitializer (null, Location),
933 c.Block = new ToplevelBlock (null, Location);
938 /// The pending methods that need to be implemented
939 // (interfaces or abstract methods)
941 public PendingImplementation Pending;
943 public abstract PendingImplementation GetPendingImplementations ();
945 TypeExpr[] GetPartialBases (out TypeExpr base_class)
947 ArrayList ifaces = new ArrayList ();
950 Location base_loc = Location.Null;
952 foreach (ClassPart part in parts) {
953 TypeExpr new_base_class;
954 TypeExpr[] new_ifaces;
956 new_ifaces = part.GetClassBases (out new_base_class);
957 if (new_ifaces == null && base_type != null)
960 if ((base_class != null) && (new_base_class != null) &&
961 !base_class.Equals (new_base_class)) {
962 Report.Error (263, part.Location,
963 "Partial declarations of `{0}' must " +
964 "not specify different base classes",
967 if (!Location.IsNull (base_loc))
968 Report.LocationOfPreviousError (base_loc);
973 if ((base_class == null) && (new_base_class != null)) {
974 base_class = new_base_class;
975 base_loc = part.Location;
978 if (new_ifaces == null)
981 foreach (TypeExpr iface in new_ifaces) {
983 foreach (TypeExpr old_iface in ifaces) {
984 if (old_iface.Equals (iface)) {
995 TypeExpr[] retval = new TypeExpr [ifaces.Count];
996 ifaces.CopyTo (retval, 0);
1000 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1004 int count = Bases.Count;
1005 int start = 0, i, j;
1007 if (Kind == Kind.Class){
1008 TypeExpr name = ResolveBaseTypeExpr (
1009 (Expression) Bases [0], false, Location);
1015 if (!name.IsInterface) {
1016 // base_class could be a class, struct, enum, delegate.
1017 // This is validated in GetClassBases.
1023 TypeExpr [] ifaces = new TypeExpr [count-start];
1025 for (i = start, j = 0; i < count; i++, j++){
1026 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1027 if (resolved == null) {
1031 ifaces [j] = resolved;
1038 /// This function computes the Base class and also the
1039 /// list of interfaces that the class or struct @c implements.
1041 /// The return value is an array (might be null) of
1042 /// interfaces implemented (as Types).
1044 /// The @base_class argument is set to the base object or null
1045 /// if this is `System.Object'.
1047 TypeExpr [] GetClassBases (out TypeExpr base_class)
1054 ifaces = GetPartialBases (out base_class);
1055 else if (Bases == null){
1059 ifaces = GetNormalBases (out base_class);
1064 if ((base_class != null) && (Kind == Kind.Class)){
1065 if (base_class is TypeParameterExpr){
1067 689, base_class.Location,
1068 "Type parameter `{0}' can not be used as a " +
1069 "base class or interface", base_class.Name);
1074 if (IsGeneric && base_class.Type.IsSubclassOf (TypeManager.attribute_type)){
1076 698, base_class.Location,
1077 "A generic type cannot derive from `{0}' " +
1078 "because it is an attribute class",
1084 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1085 Report.Error (1521, base_class.Location, "Invalid base type");
1089 if (base_class.IsSealed){
1090 Report.SymbolRelatedToPreviousError (base_class.Type);
1091 if (base_class.Type.IsAbstract) {
1092 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1094 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1099 if (!base_class.CanInheritFrom ()){
1100 Report.Error (644, Location,
1101 "`{0}' cannot inherit from special class `{1}'",
1102 Name, base_class.Name);
1106 if (!base_class.AsAccessible (this, ModFlags)) {
1107 Report.SymbolRelatedToPreviousError (base_class.Type);
1108 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1109 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1113 if (base_class != null)
1114 base_class_name = base_class.Name;
1119 int count = ifaces != null ? ifaces.Length : 0;
1121 for (i = 0; i < count; i++) {
1122 TypeExpr iface = (TypeExpr) ifaces [i];
1124 if (!iface.IsInterface) {
1125 if (Kind != Kind.Class) {
1126 // TODO: location of symbol related ....
1127 Error_TypeInListIsNotInterface (Location, iface.FullName);
1129 else if (base_class != null)
1130 Report.Error (1721, Location,
1131 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1134 Report.Error (1722, Location,
1135 "In Class `{0}', `{1}' is not " +
1136 "an interface, a base class must be listed first", Name, iface.Name);
1141 for (int x = 0; x < i; x++) {
1142 if (iface.Equals (ifaces [x])) {
1143 Report.Error (528, Location,
1144 "`{0}' is already listed in " +
1145 "interface list", iface.Name);
1150 if ((Kind == Kind.Interface) &&
1151 !iface.AsAccessible (Parent, ModFlags)) {
1152 Report.Error (61, Location,
1153 "Inconsistent accessibility: base " +
1154 "interface `{0}' is less accessible " +
1155 "than interface `{1}'", iface.Name,
1163 bool CheckGenericInterfaces (Type[] ifaces)
1165 ArrayList already_checked = new ArrayList ();
1167 for (int i = 0; i < ifaces.Length; i++) {
1168 Type iface = ifaces [i];
1169 foreach (Type t in already_checked) {
1173 Type[] infered = new Type [CountTypeParameters];
1174 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1179 "`{0}' cannot implement both `{1}' and `{2}' " +
1180 "because they may unify for some type " +
1181 "parameter substitutions",
1182 TypeManager.GetFullName (TypeBuilder),
1187 already_checked.Add (iface);
1195 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1197 Report.Error (527, loc, "'{0}': type in interface list is not an interface", type);
1201 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1203 public override TypeBuilder DefineType ()
1208 if (TypeBuilder != null)
1211 TypeAttributes type_attributes = TypeAttr;
1217 if (TypeManager.NamespaceClash (Name, Location)) {
1222 ModuleBuilder builder = CodeGen.Module.Builder;
1223 TypeBuilder = builder.DefineType (
1224 Name, type_attributes, null, null);
1226 TypeBuilder builder = Parent.TypeBuilder;
1227 if (builder == null) {
1232 TypeBuilder = builder.DefineNestedType (
1233 Basename, type_attributes, ptype, null);
1235 } catch (ArgumentException) {
1236 Report.RuntimeMissingSupport (Location, "static classes");
1241 TypeManager.AddUserType (Name, TypeBuilder, this);
1243 if (Parts != null) {
1245 foreach (ClassPart part in Parts) {
1246 part.TypeBuilder = TypeBuilder;
1248 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1249 part.ec.ContainerType = TypeBuilder;
1252 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1253 ec.ContainerType = TypeBuilder;
1257 string[] param_names = new string [TypeParameters.Length];
1258 for (int i = 0; i < TypeParameters.Length; i++)
1259 param_names [i] = TypeParameters [i].Name;
1261 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1263 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1264 for (int i = offset; i < gen_params.Length; i++)
1265 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1268 iface_exprs = GetClassBases (out base_type);
1269 if (iface_exprs == null && base_type != null) {
1274 if (base_type == null) {
1275 if (Kind == Kind.Class){
1276 if (RootContext.StdLib)
1277 base_type = TypeManager.system_object_expr;
1278 else if (Name != "System.Object")
1279 base_type = TypeManager.system_object_expr;
1280 } else if (Kind == Kind.Struct){
1282 // If we are compiling our runtime,
1283 // and we are defining ValueType, then our
1284 // base is `System.Object'.
1286 if (!RootContext.StdLib && Name == "System.ValueType")
1287 base_type = TypeManager.system_object_expr;
1288 else if (Kind == Kind.Struct)
1289 base_type = TypeManager.system_valuetype_expr;
1293 if (base_type != null) {
1294 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1295 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1296 ptype = base_type.ResolveType (TypeResolveEmitContext);
1297 if (ptype == null) {
1302 ptype = base_type.Type;
1306 TypeBuilder.SetParent (ptype);
1308 // add interfaces that were not added at type creation
1309 if (iface_exprs != null) {
1310 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1311 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1312 TypeResolveEmitContext.ContainerType = TypeBuilder;
1313 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1314 if (ifaces == null) {
1319 foreach (Type itype in ifaces)
1320 TypeBuilder.AddInterfaceImplementation (itype);
1322 if (!CheckGenericInterfaces (ifaces)) {
1327 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1330 if (!(this is Iterator))
1331 RootContext.RegisterOrder (this);
1332 else if (!ResolveType ())
1337 if (!DefineNestedTypes ()) {
1344 public bool ResolveType ()
1349 TypeExpr current_type = null;
1350 if (Parts != null) {
1351 foreach (ClassPart part in Parts) {
1352 if (!part.DefineTypeParameters ()) {
1358 foreach (TypeParameter type_param in CurrentTypeParameters) {
1359 if (!type_param.Resolve (this)) {
1365 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1366 for (int i = offset; i < gen_params.Length; i++)
1367 CurrentTypeParameters [i - offset].DefineConstraints ();
1369 foreach (TypeParameter type_param in TypeParameters) {
1370 if (!type_param.DefineType (ec)) {
1376 current_type = new ConstructedType (
1377 TypeBuilder, TypeParameters, Location);
1380 foreach (TypeParameter type_param in TypeParameters)
1381 if (!type_param.CheckDependencies (ec)) {
1386 if (current_type != null) {
1387 current_type = current_type.ResolveAsTypeTerminal (ec);
1388 if (current_type == null) {
1393 CurrentType = current_type.Type;
1399 protected virtual bool DefineNestedTypes ()
1401 if (Interfaces != null) {
1402 foreach (TypeContainer iface in Interfaces)
1403 if (iface.DefineType () == null)
1407 if (Types != null) {
1408 foreach (TypeContainer tc in Types)
1409 if (tc.DefineType () == null)
1413 if (Delegates != null) {
1414 foreach (Delegate d in Delegates)
1415 if (d.DefineType () == null)
1419 if (Enums != null) {
1420 foreach (Enum en in Enums)
1421 if (en.DefineType () == null)
1428 static void Error_KeywordNotAllowed (Location loc)
1430 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1434 /// Populates our TypeBuilder with fields and methods
1436 public override bool DefineMembers (TypeContainer container)
1438 if (members_defined)
1439 return members_defined_ok;
1441 members_defined_ok = DoDefineMembers ();
1442 members_defined = true;
1444 return members_defined_ok;
1447 protected virtual bool DoDefineMembers ()
1449 if (iface_exprs != null) {
1450 foreach (TypeExpr iface in iface_exprs) {
1451 ConstructedType ct = iface as ConstructedType;
1452 if ((ct != null) && !ct.CheckConstraints (ec))
1457 if (base_type != null) {
1458 ConstructedType ct = base_type as ConstructedType;
1459 if ((ct != null) && !ct.CheckConstraints (ec))
1464 if ((ModFlags & Modifiers.NEW) != 0)
1465 Error_KeywordNotAllowed (Location);
1467 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1468 if (conflict_symbol == null) {
1469 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1470 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1472 if ((ModFlags & Modifiers.NEW) == 0) {
1473 Report.SymbolRelatedToPreviousError (conflict_symbol);
1474 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1479 DefineContainerMembers (constants);
1480 DefineContainerMembers (fields);
1482 if ((Kind == Kind.Class) && !(this is ClassPart)){
1483 if ((instance_constructors == null) &&
1484 !(this is StaticClass)) {
1485 if (default_constructor == null)
1486 DefineDefaultConstructor (false);
1489 if (initialized_static_fields != null &&
1490 default_static_constructor == null)
1491 DefineDefaultConstructor (true);
1494 if (Kind == Kind.Struct){
1496 // Structs can not have initialized instance
1499 if (initialized_static_fields != null &&
1500 default_static_constructor == null)
1501 DefineDefaultConstructor (true);
1503 if (initialized_fields != null)
1504 ReportStructInitializedInstanceError ();
1507 Pending = GetPendingImplementations ();
1509 if (parts != null) {
1510 foreach (ClassPart part in parts) {
1511 if (!part.DefineMembers (this))
1517 // Constructors are not in the defined_names array
1519 DefineContainerMembers (instance_constructors);
1521 if (default_static_constructor != null)
1522 default_static_constructor.Define ();
1524 DefineContainerMembers (properties);
1525 DefineContainerMembers (events);
1526 DefineContainerMembers (indexers);
1527 DefineContainerMembers (methods);
1528 DefineContainerMembers (operators);
1529 DefineContainerMembers (enums);
1530 DefineContainerMembers (delegates);
1532 if (CurrentType != null) {
1533 GenericType = CurrentType;
1535 ec.ContainerType = GenericType;
1540 if (!(this is ClassPart))
1541 member_cache = new MemberCache (this);
1544 if (parts != null) {
1545 foreach (ClassPart part in parts)
1546 part.member_cache = member_cache;
1549 if (iterators != null) {
1550 foreach (Iterator iterator in iterators) {
1551 if (iterator.DefineType () == null)
1555 foreach (Iterator iterator in iterators) {
1556 if (!iterator.DefineMembers (this))
1564 void ReportStructInitializedInstanceError ()
1566 string n = TypeBuilder.FullName;
1568 foreach (Field f in initialized_fields){
1571 "`" + n + "." + f.Name + "': can not have " +
1572 "instance field initializers in structs");
1576 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1579 mcal.DefineContainerMembers ();
1582 public override bool Define ()
1584 if (parts != null) {
1585 foreach (ClassPart part in parts) {
1586 if (!part.Define ())
1594 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1596 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1600 /// This function is based by a delegate to the FindMembers routine
1602 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1608 /// This filter is used by FindMembers, and we just keep
1609 /// a global for the filter to `AlwaysAccept'
1611 static MemberFilter accepting_filter;
1614 static TypeContainer ()
1616 accepting_filter = new MemberFilter (AlwaysAccept);
1619 public MethodInfo[] GetMethods ()
1621 ArrayList members = new ArrayList ();
1623 DefineMembers (null);
1625 if (methods != null) {
1626 int len = methods.Count;
1627 for (int i = 0; i < len; i++) {
1628 Method m = (Method) methods [i];
1630 members.Add (m.MethodBuilder);
1634 if (operators != null) {
1635 int len = operators.Count;
1636 for (int i = 0; i < len; i++) {
1637 Operator o = (Operator) operators [i];
1639 members.Add (o.OperatorMethodBuilder);
1643 if (properties != null) {
1644 int len = properties.Count;
1645 for (int i = 0; i < len; i++) {
1646 Property p = (Property) properties [i];
1648 if (p.GetBuilder != null)
1649 members.Add (p.GetBuilder);
1650 if (p.SetBuilder != null)
1651 members.Add (p.SetBuilder);
1655 if (indexers != null) {
1656 int len = indexers.Count;
1657 for (int i = 0; i < len; i++) {
1658 Indexer ix = (Indexer) indexers [i];
1660 if (ix.GetBuilder != null)
1661 members.Add (ix.GetBuilder);
1662 if (ix.SetBuilder != null)
1663 members.Add (ix.SetBuilder);
1667 if (events != null) {
1668 int len = events.Count;
1669 for (int i = 0; i < len; i++) {
1670 Event e = (Event) events [i];
1672 if (e.AddBuilder != null)
1673 members.Add (e.AddBuilder);
1674 if (e.RemoveBuilder != null)
1675 members.Add (e.RemoveBuilder);
1679 MethodInfo[] retMethods = new MethodInfo [members.Count];
1680 members.CopyTo (retMethods, 0);
1684 // Indicated whether container has StructLayout attribute set Explicit
1685 public virtual bool HasExplicitLayout {
1691 public override Type FindNestedType (string name)
1693 ArrayList [] lists = { types, enums, delegates, interfaces };
1695 for (int j = 0; j < lists.Length; ++j) {
1696 ArrayList list = lists [j];
1700 int len = list.Count;
1701 for (int i = 0; i < len; ++i) {
1702 DeclSpace ds = (DeclSpace) list [i];
1703 if (ds.Basename == name) {
1705 return ds.TypeBuilder;
1713 private void FindMembers_NestedTypes (int modflags,
1714 BindingFlags bf, MemberFilter filter, object criteria,
1715 ref ArrayList members)
1717 ArrayList [] lists = { types, enums, delegates, interfaces };
1719 for (int j = 0; j < lists.Length; ++j) {
1720 ArrayList list = lists [j];
1724 int len = list.Count;
1725 for (int i = 0; i < len; i++) {
1726 DeclSpace ds = (DeclSpace) list [i];
1728 if ((ds.ModFlags & modflags) == 0)
1731 TypeBuilder tb = ds.TypeBuilder;
1733 if (!(criteria is string) || ds.Basename.Equals (criteria))
1734 tb = ds.DefineType ();
1737 if (tb != null && (filter (tb, criteria) == true)) {
1738 if (members == null)
1739 members = new ArrayList ();
1748 /// This method returns the members of this type just like Type.FindMembers would
1749 /// Only, we need to use this for types which are _being_ defined because MS'
1750 /// implementation can't take care of that.
1753 // FIXME: return an empty static array instead of null, that cleans up
1754 // some code and is consistent with some coding conventions I just found
1758 // Notice that in various cases we check if our field is non-null,
1759 // something that would normally mean that there was a bug elsewhere.
1761 // The problem happens while we are defining p-invoke methods, as those
1762 // will trigger a FindMembers, but this happens before things are defined
1764 // Since the whole process is a no-op, it is fine to check for null here.
1766 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1767 MemberFilter filter, object criteria)
1769 ArrayList members = null;
1772 if ((bf & BindingFlags.Public) != 0)
1773 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1775 if ((bf & BindingFlags.NonPublic) != 0)
1776 modflags |= Modifiers.PRIVATE;
1778 int static_mask = 0, static_flags = 0;
1779 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1780 case BindingFlags.Static:
1781 static_mask = static_flags = Modifiers.STATIC;
1784 case BindingFlags.Instance:
1785 static_mask = Modifiers.STATIC;
1790 static_mask = static_flags = 0;
1794 Timer.StartTimer (TimerType.TcFindMembers);
1797 filter = accepting_filter;
1799 if ((mt & MemberTypes.Field) != 0) {
1800 if (fields != null) {
1801 int len = fields.Count;
1802 for (int i = 0; i < len; i++) {
1803 FieldMember f = (FieldMember) fields [i];
1805 if ((f.ModFlags & modflags) == 0)
1807 if ((f.ModFlags & static_mask) != static_flags)
1810 FieldBuilder fb = f.FieldBuilder;
1811 if (fb != null && filter (fb, criteria) == true) {
1812 if (members == null)
1813 members = new ArrayList ();
1820 if (constants != null) {
1821 int len = constants.Count;
1822 for (int i = 0; i < len; i++) {
1823 Const con = (Const) constants [i];
1825 if ((con.ModFlags & modflags) == 0)
1827 if ((con.ModFlags & static_mask) != static_flags)
1830 FieldBuilder fb = con.FieldBuilder;
1833 fb = con.FieldBuilder;
1835 if (fb != null && filter (fb, criteria) == true) {
1836 if (members == null)
1837 members = new ArrayList ();
1845 if ((mt & MemberTypes.Method) != 0) {
1846 if (methods != null) {
1847 int len = methods.Count;
1848 for (int i = 0; i < len; i++) {
1849 Method m = (Method) methods [i];
1851 if ((m.ModFlags & modflags) == 0)
1853 if ((m.ModFlags & static_mask) != static_flags)
1856 MethodBuilder mb = m.MethodBuilder;
1858 if (mb != null && filter (mb, criteria) == true) {
1859 if (members == null)
1860 members = new ArrayList ();
1867 if (operators != null) {
1868 int len = operators.Count;
1869 for (int i = 0; i < len; i++) {
1870 Operator o = (Operator) operators [i];
1872 if ((o.ModFlags & modflags) == 0)
1874 if ((o.ModFlags & static_mask) != static_flags)
1877 MethodBuilder ob = o.OperatorMethodBuilder;
1878 if (ob != null && filter (ob, criteria) == true) {
1879 if (members == null)
1880 members = new ArrayList ();
1887 if (properties != null) {
1888 int len = properties.Count;
1889 for (int i = 0; i < len; i++) {
1890 Property p = (Property) properties [i];
1892 if ((p.ModFlags & modflags) == 0)
1894 if ((p.ModFlags & static_mask) != static_flags)
1900 if (b != null && filter (b, criteria) == true) {
1901 if (members == null)
1902 members = new ArrayList ();
1908 if (b != null && filter (b, criteria) == true) {
1909 if (members == null)
1910 members = new ArrayList ();
1917 if (indexers != null) {
1918 int len = indexers.Count;
1919 for (int i = 0; i < len; i++) {
1920 Indexer ix = (Indexer) indexers [i];
1922 if ((ix.ModFlags & modflags) == 0)
1924 if ((ix.ModFlags & static_mask) != static_flags)
1930 if (b != null && filter (b, criteria) == true) {
1931 if (members == null)
1932 members = new ArrayList ();
1938 if (b != null && filter (b, criteria) == true) {
1939 if (members == null)
1940 members = new ArrayList ();
1948 if ((mt & MemberTypes.Event) != 0) {
1949 if (events != null) {
1950 int len = events.Count;
1951 for (int i = 0; i < len; i++) {
1952 Event e = (Event) events [i];
1954 if ((e.ModFlags & modflags) == 0)
1956 if ((e.ModFlags & static_mask) != static_flags)
1959 MemberInfo eb = e.EventBuilder;
1960 if (eb != null && filter (eb, criteria) == true) {
1961 if (members == null)
1962 members = new ArrayList ();
1964 members.Add (e.EventBuilder);
1970 if ((mt & MemberTypes.Property) != 0){
1971 if (properties != null) {
1972 int len = properties.Count;
1973 for (int i = 0; i < len; i++) {
1974 Property p = (Property) properties [i];
1976 if ((p.ModFlags & modflags) == 0)
1978 if ((p.ModFlags & static_mask) != static_flags)
1981 MemberInfo pb = p.PropertyBuilder;
1982 if (pb != null && filter (pb, criteria) == true) {
1983 if (members == null)
1984 members = new ArrayList ();
1986 members.Add (p.PropertyBuilder);
1991 if (indexers != null) {
1992 int len = indexers.Count;
1993 for (int i = 0; i < len; i++) {
1994 Indexer ix = (Indexer) indexers [i];
1996 if ((ix.ModFlags & modflags) == 0)
1998 if ((ix.ModFlags & static_mask) != static_flags)
2001 MemberInfo ib = ix.PropertyBuilder;
2002 if (ib != null && filter (ib, criteria) == true) {
2003 if (members == null)
2004 members = new ArrayList ();
2006 members.Add (ix.PropertyBuilder);
2012 if ((mt & MemberTypes.NestedType) != 0)
2013 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2015 if ((mt & MemberTypes.Constructor) != 0){
2016 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2017 int len = instance_constructors.Count;
2018 for (int i = 0; i < len; i++) {
2019 Constructor c = (Constructor) instance_constructors [i];
2021 ConstructorBuilder cb = c.ConstructorBuilder;
2022 if (cb != null && filter (cb, criteria) == true) {
2023 if (members == null)
2024 members = new ArrayList ();
2031 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2032 ConstructorBuilder cb =
2033 default_static_constructor.ConstructorBuilder;
2035 if (cb != null && filter (cb, criteria) == true) {
2036 if (members == null)
2037 members = new ArrayList ();
2045 // Lookup members in base if requested.
2047 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2048 if (TypeBuilder.BaseType != null) {
2049 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2050 if (list.Count > 0) {
2051 if (members == null)
2052 members = new ArrayList ();
2054 members.AddRange (list);
2060 Timer.StopTimer (TimerType.TcFindMembers);
2062 if (members == null)
2063 return MemberList.Empty;
2065 return new MemberList (members);
2068 public override MemberCache MemberCache {
2070 return member_cache;
2074 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2075 MemberFilter filter, object criteria)
2077 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2080 return ds.FindMembers (mt, bf, filter, criteria);
2082 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2086 // FindMethods will look for methods not only in the type `t', but in
2087 // any interfaces implemented by the type.
2089 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2090 MemberFilter filter, object criteria)
2096 /// Emits the values for the constants
2098 public void EmitConstants ()
2100 if (constants != null)
2101 foreach (Const con in constants)
2106 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2111 foreach (MemberCore mc in al) {
2112 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2116 Report.Warning (169, mc.Location, "The private {0} '{1}' is never used", member_type, mc.GetSignatureForError ());
2121 public virtual void VerifyMembers ()
2124 // Check for internal or private fields that were never assigned
2126 if (RootContext.WarningLevel >= 3) {
2127 CheckMemberUsage (properties, "property");
2128 CheckMemberUsage (methods, "method");
2129 CheckMemberUsage (constants, "constant");
2131 if (fields != null){
2132 foreach (FieldMember f in fields) {
2133 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2137 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2142 // Only report 649 on level 4
2144 if (RootContext.WarningLevel < 4)
2147 if ((f.status & Field.Status.ASSIGNED) != 0)
2150 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2157 /// Emits the code, this step is performed after all
2158 /// the types, enumerations, constructors
2160 public void EmitType ()
2162 if (OptAttributes != null)
2163 OptAttributes.Emit (ec, this);
2166 // Structs with no fields need to have at least one byte.
2167 // The right thing would be to set the PackingSize in a DefineType
2168 // but there are no functions that allow interfaces *and* the size to
2172 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
2173 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2174 FieldAttributes.Private);
2176 if (HasExplicitLayout){
2177 object [] ctor_args = new object [1];
2180 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2181 TypeManager.field_offset_attribute_ctor, ctor_args);
2182 fb.SetCustomAttribute (cba);
2188 if (instance_constructors != null) {
2189 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired (this)) {
2190 bool has_compliant_args = false;
2192 foreach (Constructor c in instance_constructors) {
2195 if (has_compliant_args)
2198 has_compliant_args = c.HasCompliantArgs;
2200 if (!has_compliant_args)
2201 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2203 foreach (Constructor c in instance_constructors)
2210 if (default_static_constructor != null)
2211 default_static_constructor.Emit ();
2213 if (methods != null)
2214 foreach (Method m in methods)
2217 if (operators != null)
2218 foreach (Operator o in operators)
2221 if (properties != null)
2222 foreach (Property p in properties)
2225 if (indexers != null){
2230 foreach (FieldMember f in fields)
2233 if (events != null){
2234 foreach (Event e in Events)
2238 if (delegates != null) {
2239 foreach (Delegate d in Delegates) {
2244 if (enums != null) {
2245 foreach (Enum e in enums) {
2250 if (parts != null) {
2251 foreach (ClassPart part in parts)
2255 if ((Pending != null) && !(this is ClassPart))
2256 if (Pending.VerifyPendingMethods ())
2259 if (iterators != null)
2260 foreach (Iterator iterator in iterators)
2261 iterator.EmitType ();
2263 // if (types != null)
2264 // foreach (TypeContainer tc in types)
2268 public override void CloseType ()
2270 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2274 caching_flags |= Flags.CloseTypeCreated;
2275 TypeBuilder.CreateType ();
2276 } catch (TypeLoadException){
2278 // This is fine, the code still created the type
2280 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2281 // Console.WriteLine (e.Message);
2283 Console.WriteLine ("In type: " + Name);
2288 foreach (Enum en in Enums)
2292 foreach (TypeContainer tc in Types)
2293 if (tc.Kind == Kind.Struct)
2296 foreach (TypeContainer tc in Types)
2297 if (tc.Kind != Kind.Struct)
2301 if (Delegates != null)
2302 foreach (Delegate d in Delegates)
2305 if (Iterators != null)
2306 foreach (Iterator i in Iterators)
2314 initialized_fields = null;
2315 initialized_static_fields = null;
2324 default_constructor = null;
2325 default_static_constructor = null;
2327 OptAttributes = null;
2330 member_cache = null;
2333 // TODO: make it obsolete and use GetSignatureForError
2334 public string MakeName (string n)
2336 return "`" + Name + "." + n + "'";
2340 // Performs the validation on a Method's modifiers (properties have
2341 // the same properties).
2343 public bool MethodModifiersValid (MemberCore mc)
2345 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2346 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2347 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2349 int flags = mc.ModFlags;
2352 // At most one of static, virtual or override
2354 if ((flags & Modifiers.STATIC) != 0){
2355 if ((flags & vao) != 0){
2356 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2357 GetSignatureForError ());
2362 if (Kind == Kind.Struct){
2363 if ((flags & va) != 0){
2364 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2369 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2370 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2375 // If the declaration includes the abstract modifier, then the
2376 // declaration does not include static, virtual or extern
2378 if ((flags & Modifiers.ABSTRACT) != 0){
2379 if ((flags & Modifiers.EXTERN) != 0){
2381 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2385 if ((flags & Modifiers.SEALED) != 0) {
2386 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2390 if ((flags & Modifiers.VIRTUAL) != 0){
2391 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2395 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2396 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2401 if ((flags & Modifiers.PRIVATE) != 0){
2402 if ((flags & vao) != 0){
2403 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2408 if ((flags & Modifiers.SEALED) != 0){
2409 if ((flags & Modifiers.OVERRIDE) == 0){
2410 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2418 public bool UserDefinedStaticConstructor {
2420 return default_static_constructor != null;
2424 public Constructor DefaultStaticConstructor {
2425 get { return default_static_constructor; }
2428 protected override bool VerifyClsCompliance (DeclSpace ds)
2430 if (!base.VerifyClsCompliance (ds))
2435 Type base_type = TypeBuilder.BaseType;
2436 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2437 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2440 if (!Parent.IsClsComplianceRequired (ds)) {
2441 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2442 GetSignatureForError (), Parent.GetSignatureForError ());
2449 /// Checks whether container name is CLS Compliant
2451 void VerifyClsName ()
2453 Hashtable base_members = base_cache == null ?
2455 base_cache.GetPublicMembers ();
2456 Hashtable this_members = new Hashtable ();
2458 foreach (DictionaryEntry entry in defined_names) {
2459 MemberCore mc = (MemberCore)entry.Value;
2460 if (!mc.IsClsComplianceRequired (this))
2463 string name = (string)entry.Key;
2464 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2466 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2467 object found = base_members [lcase];
2468 if (found == null) {
2469 found = this_members [lcase];
2470 if (found == null) {
2471 this_members.Add (lcase, mc);
2476 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2479 if (found is MemberInfo) {
2480 if (basename == ((MemberInfo)found).Name)
2482 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2484 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2486 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2492 /// Performs checks for an explicit interface implementation. First it
2493 /// checks whether the `interface_type' is a base inteface implementation.
2494 /// Then it checks whether `name' exists in the interface type.
2496 public virtual bool VerifyImplements (Type interface_type, string full,
2497 string name, Location loc)
2501 if (ifaces != null){
2502 foreach (Type t in ifaces){
2503 if (t == interface_type){
2511 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2512 full, interface_type.FullName);
2519 protected override void VerifyObsoleteAttribute()
2521 CheckUsageOfObsoleteAttribute (TypeBuilder.BaseType);
2526 foreach (Type iface in ifaces) {
2527 CheckUsageOfObsoleteAttribute (iface);
2535 string IMemberContainer.Name {
2541 Type IMemberContainer.Type {
2547 MemberCache IMemberContainer.MemberCache {
2549 return member_cache;
2553 bool IMemberContainer.IsInterface {
2555 return Kind == Kind.Interface;
2559 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2561 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2563 if (GenericType != null)
2564 return TypeManager.FindMembers (GenericType, mt, new_bf,
2567 return FindMembers (mt, new_bf, null, null);
2571 // Generates xml doc comments (if any), and if required,
2572 // handle warning report.
2574 internal override void GenerateDocComment (DeclSpace ds)
2576 DocUtil.GenerateTypeDocComment (this, ds);
2579 public override string DocCommentHeader {
2580 get { return "T:"; }
2583 public virtual MemberCache BaseCache {
2585 if (base_cache != null)
2587 if (TypeBuilder.BaseType != null)
2588 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2589 if (TypeBuilder.IsInterface)
2590 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2597 public class PartialContainer : TypeContainer {
2599 public readonly Namespace Namespace;
2600 public readonly int OriginalModFlags;
2601 public readonly int AllowedModifiers;
2602 public readonly TypeAttributes DefaultTypeAttributes;
2604 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2605 MemberName member_name, int mod_flags, Kind kind,
2608 PartialContainer pc;
2609 DeclSpace ds = RootContext.Tree.GetDecl (member_name);
2611 pc = ds as PartialContainer;
2615 260, ds.Location, "Missing partial modifier " +
2616 "on declaration of type `{0}'; another " +
2617 "partial implementation of this type exists",
2618 member_name.GetTypeName());
2620 Report.LocationOfPreviousError (loc);
2624 if (pc.Kind != kind) {
2626 261, loc, "Partial declarations of `{0}' " +
2627 "must be all classes, all structs or " +
2628 "all interfaces", member_name.GetTypeName ());
2632 if (pc.OriginalModFlags != mod_flags) {
2634 262, loc, "Partial declarations of `{0}' " +
2635 "have conflicting accessibility modifiers",
2636 member_name.GetTypeName ());
2641 if (pc.CountTypeParameters != member_name.CountTypeArguments) {
2643 264, loc, "Partial declarations of `{0}' " +
2644 "must have the same type parameter names in " +
2645 "the same order", member_name.GetTypeName ());
2649 string[] pc_names = pc.MemberName.TypeArguments.GetDeclarations ();
2650 string[] names = member_name.TypeArguments.GetDeclarations ();
2652 for (int i = 0; i < pc.CountTypeParameters; i++) {
2653 if (pc_names [i] == names [i])
2657 264, loc, "Partial declarations of `{0}' " +
2658 "must have the same type parameter names in " +
2659 "the same order", member_name.GetTypeName ());
2667 if (parent is ClassPart)
2668 parent = ((ClassPart) parent).PartialContainer;
2670 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2671 RootContext.Tree.RecordDecl (member_name, pc);
2673 if (kind == Kind.Interface)
2674 parent.AddInterface (pc);
2675 else if (kind == Kind.Class || kind == Kind.Struct)
2676 parent.AddClassOrStruct (pc);
2678 throw new InvalidOperationException ();
2680 // This is needed to define our type parameters; we define the constraints later.
2681 pc.SetParameterInfo (null);
2685 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2686 MemberName name, int mod, Attributes attrs,
2687 Kind kind, Location loc)
2689 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2691 // An error occured; create a dummy container, but don't
2693 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2696 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2701 protected PartialContainer (Namespace ns, TypeContainer parent,
2702 MemberName name, int mod, Kind kind, Location l)
2703 : base (null, parent, name, null, kind, l)
2705 this.Namespace = ns;
2709 AllowedModifiers = Class.AllowedModifiers;
2710 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2714 AllowedModifiers = Struct.AllowedModifiers;
2715 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2718 case Kind.Interface:
2719 AllowedModifiers = Interface.AllowedModifiers;
2720 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2724 throw new InvalidOperationException ();
2728 if (parent.Parent == null)
2729 accmods = Modifiers.INTERNAL;
2731 accmods = Modifiers.PRIVATE;
2733 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2734 this.OriginalModFlags = mod;
2737 public override PendingImplementation GetPendingImplementations ()
2739 return PendingImplementation.GetPendingImplementations (this);
2742 protected override TypeAttributes TypeAttr {
2744 return base.TypeAttr | DefaultTypeAttributes;
2749 public class ClassPart : TypeContainer, IMemberContainer {
2750 public readonly PartialContainer PartialContainer;
2751 public readonly bool IsPartial;
2753 Constraints[] constraints;
2755 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2756 int mod, Attributes attrs, Kind kind, Location l)
2757 : base (ns, parent, pc.MemberName, attrs, kind, l)
2759 this.PartialContainer = pc;
2760 this.IsPartial = true;
2763 if (parent == null || parent == RootContext.Tree.Types)
2764 accmods = Modifiers.INTERNAL;
2766 accmods = Modifiers.PRIVATE;
2768 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2771 constraints = new Constraints [pc.CountCurrentTypeParameters];
2774 public override PendingImplementation GetPendingImplementations ()
2776 return PartialContainer.Pending;
2779 public override bool VerifyImplements (Type interface_type, string full,
2780 string name, Location loc)
2782 return PartialContainer.VerifyImplements (
2783 interface_type, full, name, loc);
2786 public override void SetParameterInfo (ArrayList constraints_list)
2788 if (constraints_list == null)
2791 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2792 for (int i = 0; i < constraints.Length; i++) {
2793 foreach (Constraints constraint in constraints_list) {
2794 if (constraint.TypeParameter == current_params [i].Name) {
2795 constraints [i] = constraint;
2802 public bool DefineTypeParameters ()
2804 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2806 for (int i = 0; i < current_params.Length; i++) {
2807 Constraints new_constraints = constraints [i];
2808 if (new_constraints == null)
2811 if (!current_params [i].UpdateConstraints (ec, new_constraints)) {
2812 Report.Error (265, Location, "Partial declarations of `{0}' have " +
2813 "inconsistent constraints for type parameter `{1}'.",
2814 MemberName.GetTypeName (), current_params [i].Name);
2819 for (int i = 0; i < current_params.Length; i++) {
2820 if (!current_params [i].Resolve (this))
2824 for (int i = 0; i < current_params.Length; i++)
2825 current_params [i].DefineConstraints ();
2827 foreach (TypeParameter type_param in PartialContainer.TypeParameters) {
2828 if (!type_param.DefineType (ec))
2835 public override void RegisterFieldForInitialization (FieldMember field)
2837 PartialContainer.RegisterFieldForInitialization (field);
2840 public override bool EmitFieldInitializers (EmitContext ec)
2842 return PartialContainer.EmitFieldInitializers (ec);
2845 public override Type FindNestedType (string name)
2847 return PartialContainer.FindNestedType (name);
2850 public override MemberCache BaseCache {
2852 return PartialContainer.BaseCache;
2857 public abstract class ClassOrStruct : TypeContainer {
2858 bool has_explicit_layout = false;
2859 ListDictionary declarative_security;
2861 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2862 MemberName name, Attributes attrs, Kind kind,
2864 : base (ns, parent, name, attrs, kind, l)
2868 public override PendingImplementation GetPendingImplementations ()
2870 return PendingImplementation.GetPendingImplementations (this);
2873 public override bool HasExplicitLayout {
2875 return has_explicit_layout;
2879 public override void VerifyMembers ()
2881 base.VerifyMembers ();
2883 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2884 foreach (Event e in events){
2886 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2891 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2893 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2894 if (declarative_security == null)
2895 declarative_security = new ListDictionary ();
2897 a.ExtractSecurityPermissionSet (declarative_security);
2901 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2902 has_explicit_layout = true;
2904 base.ApplyAttributeBuilder (a, cb);
2907 public override void Emit()
2911 if (declarative_security != null) {
2912 foreach (DictionaryEntry de in declarative_security) {
2913 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2920 /// Class handles static classes declaration
2922 public sealed class StaticClass: Class {
2923 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2924 Attributes attrs, Location l)
2925 : base (ns, parent, name, mod, attrs, l)
2927 if (RootContext.Version == LanguageVersion.ISO_1) {
2928 Report.FeatureIsNotStandardized (l, "static classes");
2932 protected override int AllowedModifiersProp {
2934 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2935 Modifiers.STATIC | Modifiers.UNSAFE;
2939 protected override void DefineContainerMembers (MemberCoreArrayList list)
2944 foreach (MemberCore m in list) {
2945 if (m is Operator) {
2946 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2950 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2951 Report.Warning (628, 4, m.Location, "'{0}': new protected member declared in static class", m.GetSignatureForError (this));
2954 Report.Error (720, m.Location, "'{0}': cannot declare indexers in a static class", m.GetSignatureForError (this));
2958 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2961 if (m is Constructor) {
2962 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2966 if (m is Destructor) {
2967 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2970 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2973 base.DefineContainerMembers (list);
2976 public override TypeBuilder DefineType()
2978 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2979 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2983 TypeBuilder tb = base.DefineType ();
2987 if ((ptype != null) && (ptype != TypeManager.object_type)) {
2990 "Static class '{0}' cannot derive from type '{1}'. " +
2991 "Static classes must derive from object",
2992 GetSignatureForError (), ptype);
2996 if (ifaces != null) {
2997 foreach (Type t in ifaces)
2998 Report.SymbolRelatedToPreviousError (t);
3001 "'{0}': static classes cannot implement interfaces",
3002 GetSignatureForError ());
3007 protected override TypeAttributes TypeAttr {
3009 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
3014 public class Class : ClassOrStruct {
3015 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
3016 public const int AllowedModifiers =
3019 Modifiers.PROTECTED |
3020 Modifiers.INTERNAL |
3022 Modifiers.ABSTRACT |
3026 bool WasTransitError;
3028 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3029 Attributes attrs, Location l)
3030 : base (ns, parent, name, attrs, Kind.Class, l)
3032 this.ModFlags = mod;
3035 virtual protected int AllowedModifiersProp {
3037 return AllowedModifiers;
3041 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
3043 if (a.Type == TypeManager.attribute_usage_type) {
3044 if (ptype != TypeManager.attribute_type &&
3045 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
3046 TypeBuilder.FullName != "System.Attribute") {
3047 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
3051 if (a.Type == TypeManager.conditional_attribute_type &&
3052 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
3053 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
3057 if (AttributeTester.IsAttributeExcluded (a.Type))
3060 base.ApplyAttributeBuilder (a, cb);
3063 public const TypeAttributes DefaultTypeAttributes =
3064 TypeAttributes.AutoLayout | TypeAttributes.Class;
3066 public override TypeBuilder DefineType()
3069 if (WasTransitError)
3071 throw new CircularDepException (this);
3074 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
3075 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
3079 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
3080 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
3083 return base.DefineType ();
3085 catch (CircularDepException e) {
3086 Report.SymbolRelatedToPreviousError (e.Container);
3087 Report.Error (146, Location, "Circular base class dependency involving '{0}' and '{1}'",
3088 GetSignatureForError (), e.Container.GetSignatureForError ());
3089 WasTransitError = true;
3094 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3095 /// Valid only for attribute classes.
3096 public bool IsExcluded ()
3098 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3099 return (caching_flags & Flags.Excluded) != 0;
3101 caching_flags &= ~Flags.Excluded_Undetected;
3103 if (OptAttributes == null)
3106 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3111 foreach (Attribute a in attrs) {
3112 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3113 if (RootContext.AllDefines.Contains (condition))
3117 caching_flags |= Flags.Excluded;
3122 // FIXME: How do we deal with the user specifying a different
3125 protected override TypeAttributes TypeAttr {
3127 return base.TypeAttr | DefaultTypeAttributes;
3132 public class Struct : ClassOrStruct {
3134 // Modifiers allowed in a struct declaration
3136 public const int AllowedModifiers =
3139 Modifiers.PROTECTED |
3140 Modifiers.INTERNAL |
3144 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
3145 int mod, Attributes attrs, Location l)
3146 : base (ns, parent, name, attrs, Kind.Struct, l)
3150 if (parent.Parent == null)
3151 accmods = Modifiers.INTERNAL;
3153 accmods = Modifiers.PRIVATE;
3155 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3157 this.ModFlags |= Modifiers.SEALED;
3160 public const TypeAttributes DefaultTypeAttributes =
3161 TypeAttributes.SequentialLayout |
3162 TypeAttributes.Sealed |
3163 TypeAttributes.BeforeFieldInit;
3166 // FIXME: Allow the user to specify a different set of attributes
3167 // in some cases (Sealed for example is mandatory for a class,
3168 // but what SequentialLayout can be changed
3170 protected override TypeAttributes TypeAttr {
3172 return base.TypeAttr | DefaultTypeAttributes;
3176 public override TypeBuilder DefineType()
3180 throw new CircularDepException (this);
3184 return base.DefineType ();
3186 catch (CircularDepException e) {
3188 Report.SymbolRelatedToPreviousError (this);
3189 Error_TypeInListIsNotInterface (e.Container.Location, GetSignatureForError ());
3198 public class Interface : TypeContainer, IMemberContainer {
3200 bool WasTransitError;
3203 /// Modifiers allowed in a class declaration
3205 public const int AllowedModifiers =
3208 Modifiers.PROTECTED |
3209 Modifiers.INTERNAL |
3213 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name,
3214 int mod, Attributes attrs, Location l)
3215 : base (ns, parent, name, attrs, Kind.Interface, l)
3219 if (parent.Parent == null)
3220 accmods = Modifiers.INTERNAL;
3222 accmods = Modifiers.PRIVATE;
3224 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3227 public override PendingImplementation GetPendingImplementations ()
3232 public const TypeAttributes DefaultTypeAttributes =
3233 TypeAttributes.AutoLayout |
3234 TypeAttributes.Abstract |
3235 TypeAttributes.Interface;
3237 protected override TypeAttributes TypeAttr {
3239 return base.TypeAttr | DefaultTypeAttributes;
3243 public override TypeBuilder DefineType()
3246 if (WasTransitError)
3248 throw new CircularDepException (this);
3252 return base.DefineType ();
3254 catch (CircularDepException e) {
3255 Report.SymbolRelatedToPreviousError (e.Container);
3256 Report.Error (529, Location, "Inherited interface '{0}' causes a cycle in the interface hierarchy of '{1}'",
3257 e.Container.GetSignatureForError (), GetSignatureForError ());
3258 WasTransitError = true;
3263 protected override bool VerifyClsCompliance (DeclSpace ds)
3265 if (!base.VerifyClsCompliance (ds))
3268 if (ifaces != null) {
3269 foreach (Type t in ifaces) {
3270 if (AttributeTester.IsClsCompliant (t))
3273 Report.SymbolRelatedToPreviousError (t);
3274 Report.Warning (3027, 1, Location, "'{0}' is not CLS-compliant because base interface '{1}' is not CLS-compliant",
3275 GetSignatureForError (), TypeManager.CSharpName (t));
3283 public abstract class MethodCore : MemberBase {
3284 public readonly Parameters Parameters;
3285 public readonly GenericMethod GenericMethod;
3286 protected ToplevelBlock block;
3289 // Parameters, cached for semantic analysis.
3291 protected InternalParameters parameter_info;
3292 protected Type [] parameter_types;
3294 // Whether this is an operator method.
3295 public bool IsOperator;
3298 // The method we're overriding if this is an override method.
3300 protected MethodInfo base_method = null;
3302 static string[] attribute_targets = new string [] { "method", "return" };
3304 public MethodCore (TypeContainer parent, GenericMethod generic,
3305 Expression type, int mod, int allowed_mod, bool is_iface,
3306 MemberName name, Attributes attrs, Parameters parameters,
3308 : base (parent, generic != null ? generic : (DeclSpace) parent,
3309 type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs, loc)
3311 Parameters = parameters;
3312 IsInterface = is_iface;
3313 this.GenericMethod = generic;
3317 // Returns the System.Type array for the parameters of this method
3319 public Type [] ParameterTypes {
3321 return parameter_types;
3325 public InternalParameters ParameterInfo
3328 return parameter_info;
3332 public ToplevelBlock Block {
3342 protected override bool CheckBase ()
3344 if (!base.CheckBase ())
3347 // Check whether arguments were correct.
3348 if (!DoDefineParameters ())
3351 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3357 // Is null for System.Object while compiling corlib and base interfaces
3358 if (Parent.BaseCache == null) {
3359 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3360 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3365 Type base_ret_type = null;
3366 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3368 // method is override
3369 if (base_method != null) {
3371 if (!CheckMethodAgainstBase ())
3374 if ((ModFlags & Modifiers.NEW) == 0) {
3375 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_ret_type))) {
3376 Report.SymbolRelatedToPreviousError (base_method);
3377 if (this is PropertyBase) {
3378 Report.Error (1715, Location, "'{0}': type must be '{1}' to match overridden member '{2}'",
3379 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3382 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3383 "change return type when overriding inherited member");
3388 if (base_method.IsAbstract && !IsInterface) {
3389 Report.SymbolRelatedToPreviousError (base_method);
3390 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3395 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3396 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3400 if (RootContext.WarningLevel > 2) {
3401 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3402 Parent.Methods.HasEquals = true;
3403 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3404 Parent.Methods.HasGetHashCode = true;
3407 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3408 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3410 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3411 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3412 Report.SymbolRelatedToPreviousError (base_method);
3413 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3420 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3421 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3422 if (conflict_symbol != null) {
3423 Report.SymbolRelatedToPreviousError (conflict_symbol);
3424 if (this is PropertyBase)
3425 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3427 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3429 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3433 if (conflict_symbol == null) {
3434 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3435 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3440 if ((ModFlags & Modifiers.NEW) == 0) {
3441 if (this is Method && conflict_symbol is MethodBase)
3444 Report.SymbolRelatedToPreviousError (conflict_symbol);
3445 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3453 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3454 // that have been defined.
3456 // `name' is the user visible name for reporting errors (this is used to
3457 // provide the right name regarding method names and properties)
3459 bool CheckMethodAgainstBase ()
3463 // TODO: replace with GetSignatureForError
3464 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3466 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3467 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3469 506, Location, Parent.MakeName (Name) +
3470 ": cannot override inherited member `" +
3471 name + "' because it is not " +
3472 "virtual, abstract or override");
3476 // Now we check that the overriden method is not final
3478 if (base_method.IsFinal) {
3479 Report.SymbolRelatedToPreviousError (base_method);
3480 Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
3481 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3485 // Check that the permissions are not being changed
3487 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3488 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3490 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3491 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3496 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3497 ModFlags |= Modifiers.NEW;
3498 Report.SymbolRelatedToPreviousError (base_method);
3499 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3500 if (RootContext.WarningLevel >= 2)
3501 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));
3503 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3509 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3511 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3513 // when overriding protected internal, the method can be declared
3514 // protected internal only within the same assembly
3517 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3518 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3520 // assemblies differ - report an error
3524 } else if (thisp != base_classp) {
3526 // same assembly, but other attributes differ - report an error
3531 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3533 // if it's not "protected internal", it must be "protected"
3537 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3539 // protected within the same assembly - an error
3542 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3543 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3545 // protected ok, but other attributes differ - report an error
3551 return (thisp == base_classp);
3555 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3558 // FIXME: report the old/new permissions?
3561 507, Location, parent.MakeName (Name) +
3562 ": can't change the access modifiers when overriding inherited " +
3563 "member `" + name + "'");
3566 protected static string Error722 {
3568 return "'{0}': static types cannot be used as return types";
3573 /// For custom member duplication search in a container
3575 protected abstract bool CheckForDuplications ();
3578 /// Gets base method and its return type
3580 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3582 protected virtual bool DoDefineParameters ()
3584 EmitContext ec = ds.EmitContext;
3586 throw new InternalErrorException ("DoDefineParameters invoked too early");
3588 bool old_unsafe = ec.InUnsafe;
3589 ec.InUnsafe = InUnsafe;
3590 // Check if arguments were correct
3591 parameter_types = Parameters.GetParameterInfo (ec);
3592 ec.InUnsafe = old_unsafe;
3594 if ((parameter_types == null) ||
3595 !CheckParameters (ds, parameter_types))
3598 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3599 parameter_info = new InternalParameters (parameter_types, Parameters, tparam);
3601 Parameter array_param = Parameters.ArrayParameter;
3602 if ((array_param != null) &&
3603 (!array_param.ParameterType.IsArray ||
3604 (array_param.ParameterType.GetArrayRank () != 1))) {
3605 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3612 void error_425 (Type old, Type t, string name)
3614 Report.Error (425, Location,
3615 "The constraints of type parameter `{0}' " +
3616 "of method `{1}' must match the constraints for " +
3617 "type parameter `{2}' of method `{3}'",
3618 TypeManager.CSharpName (old), Name,
3619 TypeManager.CSharpName (t), name);
3622 protected override bool CheckGenericOverride (MethodInfo method, string name)
3624 ParameterData pd = TypeManager.GetParameterData (method);
3626 for (int i = 0; i < ParameterTypes.Length; i++) {
3627 GenericConstraints ogc = pd.GenericConstraints (i);
3628 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3630 if ((gc == null) && (ogc == null))
3633 Type ot = pd.ParameterType (i);
3634 Type t = ParameterTypes [i];
3636 if (!((gc != null) && (ogc != null))) {
3637 error_425 (ot, t, name);
3641 if ((gc.Attributes != ogc.Attributes) ||
3642 (gc.HasClassConstraint != ogc.HasClassConstraint)) {
3643 error_425 (ot, t, name);
3647 if (ogc.HasClassConstraint &&
3648 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3649 error_425 (ot, t, name);
3653 Type[] oct = ogc.InterfaceConstraints;
3654 Type[] ct = gc.InterfaceConstraints;
3656 if (oct.Length != ct.Length) {
3657 error_425 (ot, t, name);
3661 for (int j = 0; j < oct.Length; j++)
3662 if (!oct [j].Equals (ct [j])) {
3663 error_425 (ot, t, name);
3671 public override string[] ValidAttributeTargets {
3673 return attribute_targets;
3677 protected override bool VerifyClsCompliance (DeclSpace ds)
3679 if (!base.VerifyClsCompliance (ds)) {
3680 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsComplianceRequired (ds)) {
3681 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3686 if (Parameters.HasArglist) {
3687 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3690 if (!AttributeTester.IsClsCompliant (MemberType)) {
3691 if (this is PropertyBase)
3692 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3693 GetSignatureForError ());
3695 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3696 GetSignatureForError ());
3699 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3704 bool MayUnify (MethodCore first, MethodCore second)
3706 int a_type_params = 0;
3707 if (first.GenericMethod != null)
3708 a_type_params = first.GenericMethod.CountTypeParameters;
3710 int b_type_params = 0;
3711 if (second.GenericMethod != null)
3712 b_type_params = second.GenericMethod.CountTypeParameters;
3714 if (a_type_params != b_type_params)
3717 Type[] class_infered, method_infered;
3718 if (Parent.CountTypeParameters > 0)
3719 class_infered = new Type [Parent.CountTypeParameters];
3721 class_infered = null;
3723 if (a_type_params > 0)
3724 method_infered = new Type [a_type_params];
3726 method_infered = null;
3728 return TypeManager.MayBecomeEqualGenericInstances (
3729 first.ParameterTypes, second.ParameterTypes, class_infered, method_infered);
3732 protected bool IsDuplicateImplementation (MethodCore method)
3734 if ((method == this) ||
3735 (method.MemberName.GetTypeName () != MemberName.GetTypeName ()))
3738 Type[] param_types = method.ParameterTypes;
3739 if (param_types == null)
3742 if (param_types.Length != ParameterTypes.Length)
3746 bool may_unify = MayUnify (this, method);
3748 for (int i = 0; i < param_types.Length; i++) {
3749 if (param_types [i] != ParameterTypes [i])
3753 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3754 equal = may_unify = false;
3756 // TODO: make operator compatible with MethodCore to avoid this
3757 if (this is Operator && method is Operator) {
3758 if (MemberType != method.MemberType)
3759 equal = may_unify = false;
3764 // Try to report 663: method only differs on out/ref
3766 ParameterData info = ParameterInfo;
3767 ParameterData other_info = method.ParameterInfo;
3768 for (int i = 0; i < info.Count; i++){
3769 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3770 Report.Error (663, Location,
3771 "Overload method only differs " +
3772 "in parameter modifier");
3777 Report.SymbolRelatedToPreviousError (method);
3778 if (this is Operator && method is Operator)
3779 Report.Error (557, Location,
3780 "Duplicate user-defined conversion in type '{0}'",
3783 Report.Error (111, Location,
3784 "Type '{0}' already defines a member called '{1}' " +
3785 "with the same parameter types", Parent.Name, Name);
3787 } else if (may_unify) {
3788 Report.Error (408, Location,
3789 "`{0}' cannot define overload members that " +
3790 "may unify for some type parameter substitutions",
3797 public override bool IsUsed
3808 // Returns a string that represents the signature for this
3809 // member which should be used in XML documentation.
3811 public override string GetDocCommentName (DeclSpace ds)
3813 return DocUtil.GetMethodDocCommentName (this, ds);
3817 // Raised (and passed an XmlElement that contains the comment)
3818 // when GenerateDocComment is writing documentation expectedly.
3820 // FIXME: with a few effort, it could be done with XmlReader,
3821 // that means removal of DOM use.
3823 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3825 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3829 // Represents header string for documentation comment.
3831 public override string DocCommentHeader {
3832 get { return "M:"; }
3835 protected override void VerifyObsoleteAttribute()
3837 base.VerifyObsoleteAttribute ();
3839 if (parameter_types == null)
3842 foreach (Type type in parameter_types) {
3843 CheckUsageOfObsoleteAttribute (type);
3848 public class SourceMethod : ISourceMethod
3850 TypeContainer container;
3853 protected SourceMethod (TypeContainer container, MethodBase builder,
3854 ISourceFile file, Location start, Location end)
3856 this.container = container;
3857 this.builder = builder;
3859 CodeGen.SymbolWriter.OpenMethod (
3860 file, this, start.Row, 0, end.Row, 0);
3863 public string Name {
3864 get { return builder.Name; }
3867 public int NamespaceID {
3868 get { return container.NamespaceEntry.SymbolFileID; }
3873 if (builder is MethodBuilder)
3874 return ((MethodBuilder) builder).GetToken ().Token;
3875 else if (builder is ConstructorBuilder)
3876 return ((ConstructorBuilder) builder).GetToken ().Token;
3878 throw new NotSupportedException ();
3882 public void CloseMethod ()
3884 if (CodeGen.SymbolWriter != null)
3885 CodeGen.SymbolWriter.CloseMethod ();
3888 public static SourceMethod Create (TypeContainer parent,
3889 MethodBase builder, Block block)
3891 if (CodeGen.SymbolWriter == null)
3896 Location start_loc = block.StartLocation;
3897 if (Location.IsNull (start_loc))
3900 Location end_loc = block.EndLocation;
3901 if (Location.IsNull (end_loc))
3904 ISourceFile file = start_loc.SourceFile;
3908 return new SourceMethod (
3909 parent, builder, file, start_loc, end_loc);
3913 public class Method : MethodCore, IIteratorContainer, IMethodData {
3914 public MethodBuilder MethodBuilder;
3915 public MethodData MethodData;
3916 ReturnParameter return_attributes;
3917 ListDictionary declarative_security;
3920 /// Modifiers allowed in a class declaration
3922 const int AllowedModifiers =
3925 Modifiers.PROTECTED |
3926 Modifiers.INTERNAL |
3931 Modifiers.OVERRIDE |
3932 Modifiers.ABSTRACT |
3934 Modifiers.METHOD_YIELDS |
3937 const int AllowedInterfaceModifiers =
3938 Modifiers.NEW | Modifiers.UNSAFE;
3941 // return_type can be "null" for VOID values.
3943 public Method (TypeContainer parent, GenericMethod generic,
3944 Expression return_type, int mod, bool is_iface,
3945 MemberName name, Parameters parameters, Attributes attrs,
3947 : base (parent, generic, return_type, mod,
3948 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3949 is_iface, name, attrs, parameters, l)
3953 public override AttributeTargets AttributeTargets {
3955 return AttributeTargets.Method;
3959 public override string GetSignatureForError()
3961 if (MethodBuilder == null) {
3962 return GetSignatureForError (Parent);
3964 return TypeManager.CSharpSignature (MethodBuilder);
3968 /// Use this method when MethodBuilder is null
3970 public override string GetSignatureForError (TypeContainer tc)
3972 // TODO: get params from somewhere
3973 if (parameter_info == null)
3974 return base.GetSignatureForError (tc);
3976 // TODO: move to parameters
3977 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3978 if (parameter_info.Parameters.FixedParameters != null) {
3979 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3980 Parameter p = parameter_info.Parameters.FixedParameters [i];
3981 args.Append (p.GetSignatureForError ());
3983 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3988 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3991 void DuplicateEntryPoint (MethodInfo b, Location location)
3995 "Program `" + CodeGen.FileName +
3996 "' has more than one entry point defined: `" +
3997 TypeManager.CSharpSignature(b) + "'");
4000 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
4002 if (b.ReturnType != TypeManager.void_type &&
4003 b.ReturnType != TypeManager.int32_type)
4006 if (pinfo.Count == 0)
4009 if (pinfo.Count > 1)
4012 Type t = pinfo.ParameterType(0);
4014 (t.GetArrayRank() == 1) &&
4015 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
4016 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
4022 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4024 if (a.Target == AttributeTargets.ReturnValue) {
4025 if (return_attributes == null)
4026 return_attributes = new ReturnParameter (MethodBuilder, Location);
4028 return_attributes.ApplyAttributeBuilder (a, cb);
4032 if (a.Type == TypeManager.methodimpl_attr_type &&
4033 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4034 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4037 if (a.Type == TypeManager.dllimport_type) {
4038 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4039 if ((ModFlags & extern_static) != extern_static) {
4040 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
4046 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4047 if (declarative_security == null)
4048 declarative_security = new ListDictionary ();
4049 a.ExtractSecurityPermissionSet (declarative_security);
4053 if (a.Type == TypeManager.conditional_attribute_type) {
4054 if (IsOperator || IsExplicitImpl) {
4055 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4059 if (ReturnType != TypeManager.void_type) {
4060 Report.Error (578, Location, "Conditional not valid on '{0}' because its return type is not void", GetSignatureForError ());
4064 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4065 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
4070 Report.Error (582, Location, "Conditional not valid on interface members");
4074 if (MethodData.IsImplementing) {
4075 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
4079 for (int i = 0; i < parameter_info.Count; ++i) {
4080 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
4081 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
4087 MethodBuilder.SetCustomAttribute (cb);
4090 protected override bool CheckForDuplications ()
4092 ArrayList ar = Parent.Methods;
4094 int arLen = ar.Count;
4096 for (int i = 0; i < arLen; i++) {
4097 Method m = (Method) ar [i];
4098 if (IsDuplicateImplementation (m))
4103 ar = Parent.Properties;
4105 for (int i = 0; i < ar.Count; ++i) {
4106 PropertyBase pb = (PropertyBase) ar [i];
4107 if (pb.AreAccessorsDuplicateImplementation (this))
4112 ar = Parent.Indexers;
4114 for (int i = 0; i < ar.Count; ++i) {
4115 PropertyBase pb = (PropertyBase) ar [i];
4116 if (pb.AreAccessorsDuplicateImplementation (this))
4123 for (int i = 0; i < ar.Count; ++i) {
4124 Event ev = (Event) ar [i];
4125 if (ev.AreAccessorsDuplicateImplementation (this))
4136 public override bool Define ()
4138 if (!DoDefineBase ())
4141 MethodBuilder mb = null;
4142 if (GenericMethod != null) {
4143 string method_name = MemberName.Name;
4146 method_name = TypeManager.GetFullName (InterfaceType) + "." + method_name;
4148 mb = Parent.TypeBuilder.DefineGenericMethod (method_name, flags);
4149 if (!GenericMethod.Define (mb))
4156 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4157 Error1599 (Location, ReturnType);
4165 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
4167 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
4168 this, mb, GenericMethod, base_method);
4170 if (!MethodData.Define (Parent))
4173 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4174 Name == "Finalize" && !(this is Destructor)) {
4175 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4179 // Setup iterator if we are one
4181 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4182 Iterator iterator = new Iterator (
4183 Parent, Name, MemberType,
4184 ParameterInfo, ModFlags, block, Location);
4186 if (!iterator.DefineIterator ())
4189 block = iterator.Block;
4192 MethodBuilder = MethodData.MethodBuilder;
4195 // This is used to track the Entry Point,
4197 if (Name == "Main" &&
4198 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
4199 (RootContext.MainClass == null ||
4200 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4201 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
4202 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4203 md.SetMemberIsUsed ();
4205 if (RootContext.EntryPoint == null) {
4206 if (Parent.IsGeneric){
4207 Report.Error (-201, Location,
4208 "Entry point can not be defined in a generic class");
4211 RootContext.EntryPoint = MethodBuilder;
4212 RootContext.EntryPointLocation = Location;
4214 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4215 DuplicateEntryPoint (MethodBuilder, Location);
4218 if (RootContext.WarningLevel >= 4)
4219 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder) );
4223 if (MemberType.IsAbstract && MemberType.IsSealed) {
4224 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4234 public override void Emit ()
4236 MethodData.Emit (Parent, this);
4239 if (declarative_security != null) {
4240 foreach (DictionaryEntry de in declarative_security) {
4241 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4249 public static void Error1599 (Location loc, Type t)
4251 Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
4254 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4256 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
4257 container.TypeBuilder, Name, ParameterTypes, false);
4262 base_ret_type = mi.ReturnType;
4266 public override bool MarkForDuplicationCheck ()
4268 caching_flags |= Flags.TestMethodDuplication;
4272 protected override bool VerifyClsCompliance(DeclSpace ds)
4274 if (!base.VerifyClsCompliance (ds))
4277 if (parameter_types.Length > 0) {
4278 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
4280 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4287 void IIteratorContainer.SetYields ()
4289 ModFlags |= Modifiers.METHOD_YIELDS;
4292 #region IMethodData Members
4294 public CallingConventions CallingConventions {
4296 CallingConventions cc = Parameters.GetCallingConvention ();
4297 if (Parameters.HasArglist)
4298 block.HasVarargs = true;
4301 if ((ModFlags & Modifiers.STATIC) == 0)
4302 cc |= CallingConventions.HasThis;
4304 // FIXME: How is `ExplicitThis' used in C#?
4310 public Type ReturnType {
4316 public MemberName MethodName {
4322 public new Location Location {
4324 return base.Location;
4328 protected override bool CheckBase() {
4329 if (!base.CheckBase ())
4332 // TODO: Destructor should derive from MethodCore
4333 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4334 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4335 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4342 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4344 return new EmitContext (
4345 tc, ds, Location, ig, ReturnType, ModFlags, false);
4348 public ObsoleteAttribute GetObsoleteAttribute ()
4350 return GetObsoleteAttribute (ds);
4354 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4356 public bool IsExcluded (EmitContext ec)
4358 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4359 return (caching_flags & Flags.Excluded) != 0;
4361 caching_flags &= ~Flags.Excluded_Undetected;
4363 if (base_method == null) {
4364 if (OptAttributes == null)
4367 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4372 foreach (Attribute a in attrs) {
4373 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4374 if (RootContext.AllDefines.Contains (condition))
4378 caching_flags |= Flags.Excluded;
4382 IMethodData md = TypeManager.GetMethod (base_method);
4384 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4385 caching_flags |= Flags.Excluded;
4391 if (md.IsExcluded (ec)) {
4392 caching_flags |= Flags.Excluded;
4398 GenericMethod IMethodData.GenericMethod {
4400 return GenericMethod;
4407 public abstract class ConstructorInitializer {
4408 ArrayList argument_list;
4409 protected ConstructorInfo base_constructor;
4412 public ConstructorInitializer (ArrayList argument_list, Location loc)
4414 this.argument_list = argument_list;
4418 public ArrayList Arguments {
4420 return argument_list;
4424 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4426 Expression base_constructor_group;
4430 ec.CurrentBlock = block;
4432 if (argument_list != null){
4433 foreach (Argument a in argument_list){
4434 if (!a.Resolve (ec, loc))
4438 ec.CurrentBlock = null;
4440 if (this is ConstructorBaseInitializer) {
4441 if (ec.ContainerType.BaseType == null)
4444 t = ec.ContainerType.BaseType;
4445 if (ec.ContainerType.IsValueType) {
4446 Report.Error (522, loc,
4447 "structs cannot call base class constructors");
4451 t = ec.ContainerType;
4453 base_constructor_group = Expression.MemberLookup (
4454 ec, t, ".ctor", MemberTypes.Constructor,
4455 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4458 if (base_constructor_group == null){
4460 base_constructor_group = Expression.MemberLookup (
4461 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4462 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4466 int errors = Report.Errors;
4467 if (base_constructor_group != null)
4468 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4469 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4472 if (base_constructor == null) {
4473 if (errors == Report.Errors)
4474 Report.Error (1501, loc, "Can not find a constructor for this argument list");
4479 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
4480 TypeManager.CSharpSignature (base_constructor));
4481 base_constructor = null;
4485 if (base_constructor == caller_builder){
4486 Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
4493 public void Emit (EmitContext ec)
4495 if (base_constructor != null){
4496 ec.Mark (loc, false);
4498 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4500 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4505 public class ConstructorBaseInitializer : ConstructorInitializer {
4506 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4507 base (argument_list, l)
4512 public class ConstructorThisInitializer : ConstructorInitializer {
4513 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4514 base (argument_list, l)
4519 public class Constructor : MethodCore, IMethodData {
4520 public ConstructorBuilder ConstructorBuilder;
4521 public ConstructorInitializer Initializer;
4522 ListDictionary declarative_security;
4525 // Modifiers allowed for a constructor.
4527 public const int AllowedModifiers =
4529 Modifiers.PROTECTED |
4530 Modifiers.INTERNAL |
4536 bool has_compliant_args = false;
4538 // The spec claims that static is not permitted, but
4539 // my very own code has static constructors.
4541 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4542 ConstructorInitializer init, Location l)
4543 : base (ds, null, null, mod, AllowedModifiers, false,
4544 new MemberName (name), null, args, l)
4549 public override string GetSignatureForError()
4551 if (ConstructorBuilder == null)
4552 return GetSignatureForError (Parent);
4554 return TypeManager.CSharpSignature (ConstructorBuilder);
4557 public bool HasCompliantArgs {
4559 return has_compliant_args;
4563 public override AttributeTargets AttributeTargets {
4565 return AttributeTargets.Constructor;
4571 // Returns true if this is a default constructor
4573 public bool IsDefault ()
4575 if ((ModFlags & Modifiers.STATIC) != 0)
4576 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4577 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4580 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4581 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4582 (Initializer is ConstructorBaseInitializer) &&
4583 (Initializer.Arguments == null);
4586 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4588 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4589 if (declarative_security == null) {
4590 declarative_security = new ListDictionary ();
4592 a.ExtractSecurityPermissionSet (declarative_security);
4596 ConstructorBuilder.SetCustomAttribute (cb);
4599 protected override bool CheckForDuplications ()
4601 ArrayList ar = Parent.InstanceConstructors;
4603 int arLen = ar.Count;
4605 for (int i = 0; i < arLen; i++) {
4606 Constructor m = (Constructor) ar [i];
4607 if (IsDuplicateImplementation (m))
4614 protected override bool CheckBase ()
4616 // Check whether arguments were correct.
4617 if (!DoDefineParameters ())
4620 // TODO: skip the rest for generated ctor
4621 if ((ModFlags & Modifiers.STATIC) != 0)
4624 if (!CheckForDuplications ())
4627 if (Parent.Kind == Kind.Struct) {
4628 if (ParameterTypes.Length == 0) {
4629 Report.Error (568, Location,
4630 "Structs can not contain explicit parameterless " +
4635 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4636 Report.Error (666, Location, "Protected member in struct declaration");
4641 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4642 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4649 // Creates the ConstructorBuilder
4651 public override bool Define ()
4653 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4654 MethodAttributes.SpecialName);
4656 if ((ModFlags & Modifiers.STATIC) != 0){
4657 ca |= MethodAttributes.Static | MethodAttributes.Private;
4659 ca |= MethodAttributes.HideBySig;
4661 if ((ModFlags & Modifiers.PUBLIC) != 0)
4662 ca |= MethodAttributes.Public;
4663 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4664 if ((ModFlags & Modifiers.INTERNAL) != 0)
4665 ca |= MethodAttributes.FamORAssem;
4667 ca |= MethodAttributes.Family;
4668 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4669 ca |= MethodAttributes.Assembly;
4670 else if (IsDefault ())
4671 ca |= MethodAttributes.Public;
4673 ca |= MethodAttributes.Private;
4676 // Check if arguments were correct.
4680 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4681 ca, CallingConventions,
4684 if ((ModFlags & Modifiers.UNSAFE) != 0)
4685 ConstructorBuilder.InitLocals = false;
4687 TypeManager.AddMethod (ConstructorBuilder, this);
4690 // HACK because System.Reflection.Emit is lame
4692 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4700 public override void Emit ()
4702 EmitContext ec = CreateEmitContext (null, null);
4705 // extern methods have no bodies
4707 if ((ModFlags & Modifiers.EXTERN) != 0) {
4708 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4710 179, Location, "External constructor `" +
4711 TypeManager.CSharpSignature (ConstructorBuilder) +
4712 "' can not have a body");
4715 } else if (block == null) {
4717 501, Location, "Constructor `" +
4718 TypeManager.CSharpSignature (ConstructorBuilder) +
4719 "' must declare a body since it is not marked extern");
4723 // If this is a non-static `struct' constructor and doesn't have any
4724 // initializer, it must initialize all of the struct's fields.
4725 if ((Parent.Kind == Kind.Struct) &&
4726 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4727 Block.AddThisVariable (Parent, Location);
4730 block.ResolveMeta (ec, ParameterInfo);
4732 if ((ModFlags & Modifiers.STATIC) == 0){
4733 if (Parent.Kind == Kind.Class && Initializer == null)
4734 Initializer = new ConstructorBaseInitializer (
4739 // Spec mandates that Initializers will not have
4743 if ((Initializer != null) &&
4744 !Initializer.Resolve (ConstructorBuilder, block, ec))
4746 ec.IsStatic = false;
4749 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4751 SourceMethod source = SourceMethod.Create (
4752 Parent, ConstructorBuilder, block);
4755 // Classes can have base initializers and instance field initializers.
4757 if (Parent.Kind == Kind.Class){
4758 if ((ModFlags & Modifiers.STATIC) == 0){
4761 // If we use a "this (...)" constructor initializer, then
4762 // do not emit field initializers, they are initialized in the other constructor
4764 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4765 Parent.EmitFieldInitializers (ec);
4768 if (Initializer != null) {
4769 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4770 ec.TestObsoleteMethodUsage = false;
4772 Initializer.Emit (ec);
4775 if ((ModFlags & Modifiers.STATIC) != 0)
4776 Parent.EmitFieldInitializers (ec);
4778 if (OptAttributes != null)
4779 OptAttributes.Emit (ec, this);
4781 ec.EmitTopBlock (block, ParameterInfo, Location);
4784 source.CloseMethod ();
4788 if (declarative_security != null) {
4789 foreach (DictionaryEntry de in declarative_security) {
4790 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4797 // Is never override
4798 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4803 protected override bool VerifyClsCompliance (DeclSpace ds)
4805 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4809 if (parameter_types.Length > 0) {
4810 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4812 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4814 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4815 foreach (Type param in parameter_types) {
4816 if (param.IsArray) {
4822 has_compliant_args = true;
4826 #region IMethodData Members
4828 public System.Reflection.CallingConventions CallingConventions {
4830 CallingConventions cc = Parameters.GetCallingConvention ();
4832 if (Parent.Kind == Kind.Class)
4833 if ((ModFlags & Modifiers.STATIC) == 0)
4834 cc |= CallingConventions.HasThis;
4836 // FIXME: How is `ExplicitThis' used in C#?
4842 public new Location Location {
4844 return base.Location;
4848 public MemberName MethodName {
4854 public Type ReturnType {
4860 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4862 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4863 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4866 public ObsoleteAttribute GetObsoleteAttribute ()
4868 return GetObsoleteAttribute (Parent);
4871 public bool IsExcluded(EmitContext ec)
4876 GenericMethod IMethodData.GenericMethod {
4886 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4888 public interface IMethodData
4890 CallingConventions CallingConventions { get; }
4891 Location Location { get; }
4892 MemberName MethodName { get; }
4893 Type[] ParameterTypes { get; }
4894 Type ReturnType { get; }
4895 GenericMethod GenericMethod { get; }
4897 Attributes OptAttributes { get; }
4898 ToplevelBlock Block { get; }
4900 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4901 ObsoleteAttribute GetObsoleteAttribute ();
4902 string GetSignatureForError (TypeContainer tc);
4903 bool IsExcluded (EmitContext ec);
4904 bool IsClsComplianceRequired (DeclSpace ds);
4905 void SetMemberIsUsed ();
4909 // Encapsulates most of the Method's state
4911 public class MethodData {
4913 readonly IMethodData method;
4916 // The return type of this method
4918 public readonly GenericMethod GenericMethod;
4919 public readonly InternalParameters ParameterInfo;
4922 // Are we implementing an interface ?
4924 public bool IsImplementing = false;
4929 protected MemberBase member;
4930 protected int modifiers;
4931 protected MethodAttributes flags;
4932 protected Type declaring_type;
4933 protected MethodInfo parent_method;
4935 MethodBuilder builder = null;
4936 public MethodBuilder MethodBuilder {
4942 public Type DeclaringType {
4944 return declaring_type;
4948 public MethodData (MemberBase member, InternalParameters parameters,
4949 int modifiers, MethodAttributes flags, IMethodData method)
4951 this.member = member;
4952 this.ParameterInfo = parameters;
4953 this.modifiers = modifiers;
4956 this.method = method;
4959 public MethodData (MemberBase member, InternalParameters parameters,
4960 int modifiers, MethodAttributes flags,
4961 IMethodData method, MethodBuilder builder,
4962 GenericMethod generic, MethodInfo parent_method)
4963 : this (member, parameters, modifiers, flags, method)
4965 this.builder = builder;
4966 this.GenericMethod = generic;
4967 this.parent_method = parent_method;
4970 public bool Define (TypeContainer container)
4972 MethodInfo implementing = null;
4974 string name = method.MethodName.Basename;
4975 string method_name = method.MethodName.FullName;
4977 Type[] ParameterTypes = method.ParameterTypes;
4979 if (container.Pending != null){
4980 if (member is Indexer) // TODO: test it, but it should work without this IF
4981 implementing = container.Pending.IsInterfaceIndexer (
4982 member.InterfaceType, method.ReturnType, ParameterInfo);
4984 implementing = container.Pending.IsInterfaceMethod (
4985 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4987 if (member.InterfaceType != null){
4988 if (implementing == null){
4989 if (member is PropertyBase) {
4990 Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
4991 method.GetSignatureForError (container), member.Name);
4994 Report.Error (539, method.Location, "'{0}' in explicit interface " +
4995 "declaration is not a member of interface",
5000 if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
5001 Report.SymbolRelatedToPreviousError (implementing);
5002 Report.Error (683, method.Location, "'{0}' explicit method implementation cannot implement '{1}' because it is an accessor",
5003 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5007 method_name = TypeManager.GetFullName (member.InterfaceType) + "." + method_name;
5009 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
5010 Report.SymbolRelatedToPreviousError (implementing);
5011 Report.Error (686, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
5012 method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5019 // For implicit implementations, make sure we are public, for
5020 // explicit implementations, make sure we are private.
5022 if (implementing != null){
5024 // Setting null inside this block will trigger a more
5025 // verbose error reporting for missing interface implementations
5027 // The "candidate" function has been flagged already
5028 // but it wont get cleared
5030 if (member.IsExplicitImpl){
5031 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
5032 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
5033 implementing = null;
5035 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
5036 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
5038 // If this is an interface method implementation,
5039 // check for public accessibility
5041 implementing = null;
5042 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5043 // We may never be private.
5044 implementing = null;
5045 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5047 // We may be protected if we're overriding something.
5049 implementing = null;
5054 // Static is not allowed
5056 if ((modifiers & Modifiers.STATIC) != 0){
5057 implementing = null;
5058 Modifiers.Error_InvalidModifier (method.Location, "static");
5063 // If implementing is still valid, set flags
5065 if (implementing != null){
5067 // When implementing interface methods, set NewSlot
5068 // unless, we are overwriting a method.
5070 if (implementing.DeclaringType.IsInterface){
5071 if ((modifiers & Modifiers.OVERRIDE) == 0)
5072 flags |= MethodAttributes.NewSlot;
5075 MethodAttributes.Virtual |
5076 MethodAttributes.HideBySig;
5078 // Set Final unless we're virtual, abstract or already overriding a method.
5079 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5080 flags |= MethodAttributes.Final;
5082 IsImplementing = true;
5085 EmitContext ec = method.CreateEmitContext (container, null);
5087 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
5089 if (builder == null)
5092 if (container.CurrentType != null)
5093 declaring_type = container.CurrentType;
5095 declaring_type = container.TypeBuilder;
5097 if ((modifiers & Modifiers.UNSAFE) != 0)
5098 builder.InitLocals = false;
5100 if (IsImplementing){
5102 // clear the pending implemntation flag
5104 if (member is Indexer) {
5105 container.Pending.ImplementIndexer (
5106 member.InterfaceType, builder, method.ReturnType,
5107 ParameterInfo, member.IsExplicitImpl);
5109 container.Pending.ImplementMethod (
5110 member.InterfaceType, name, method.ReturnType,
5111 ParameterInfo, member.IsExplicitImpl);
5113 if (member.IsExplicitImpl)
5114 container.TypeBuilder.DefineMethodOverride (
5115 builder, implementing);
5118 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
5119 TypeManager.AddMethod (builder, method);
5121 if (GenericMethod != null) {
5122 bool is_override = member.IsExplicitImpl |
5123 ((modifiers & Modifiers.OVERRIDE) != 0);
5125 if (implementing != null)
5126 parent_method = implementing;
5128 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5136 /// Create the MethodBuilder for the method
5138 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
5140 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
5142 if ((modifiers & extern_static) == extern_static) {
5144 if (method.OptAttributes != null) {
5145 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
5146 if (dllimport_attribute != null) {
5147 flags |= MethodAttributes.PinvokeImpl;
5148 builder = dllimport_attribute.DefinePInvokeMethod (
5149 ec, container.TypeBuilder, method_name, flags,
5150 method.ReturnType, ParameterTypes);
5156 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5157 // We are more strict than Microsoft and report CS0626 like error
5158 if (method.OptAttributes == null ||
5159 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
5160 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));
5165 if (builder == null)
5166 builder = container.TypeBuilder.DefineMethod (
5167 method_name, flags, method.CallingConventions,
5168 method.ReturnType, ParameterTypes);
5170 builder.SetGenericMethodSignature (
5171 flags, method.CallingConventions,
5172 method.ReturnType, ParameterTypes);
5178 public void Emit (TypeContainer container, Attributable kind)
5181 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5182 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
5184 ec = method.CreateEmitContext (container, null);
5186 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
5187 ec.TestObsoleteMethodUsage = false;
5189 Location loc = method.Location;
5190 Attributes OptAttributes = method.OptAttributes;
5192 if (OptAttributes != null)
5193 OptAttributes.Emit (ec, kind);
5195 if (member is MethodCore)
5196 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
5198 ToplevelBlock block = method.Block;
5201 // abstract or extern methods have no bodies
5203 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
5208 // abstract or extern methods have no bodies.
5210 if ((modifiers & Modifiers.ABSTRACT) != 0)
5212 500, method.Location, "Abstract method `" +
5213 TypeManager.CSharpSignature (builder) +
5214 "' can not have a body");
5216 if ((modifiers & Modifiers.EXTERN) != 0)
5218 179, method.Location, "External method `" +
5219 TypeManager.CSharpSignature (builder) +
5220 "' can not have a body");
5226 // Methods must have a body unless they're extern or abstract
5228 if (block == null) {
5230 501, method.Location, "Method `" +
5231 TypeManager.CSharpSignature (builder) +
5232 "' must declare a body since it is not marked " +
5233 "abstract or extern");
5237 SourceMethod source = SourceMethod.Create (
5238 container, MethodBuilder, method.Block);
5241 // Handle destructors specially
5243 // FIXME: This code generates buggy code
5245 if (member is Destructor)
5246 EmitDestructor (ec, block);
5248 ec.EmitTopBlock (block, ParameterInfo, loc);
5251 source.CloseMethod ();
5254 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5256 ILGenerator ig = ec.ig;
5258 Label finish = ig.DefineLabel ();
5260 block.SetDestructor ();
5262 ig.BeginExceptionBlock ();
5263 ec.ReturnLabel = finish;
5264 ec.HasReturnLabel = true;
5265 ec.EmitTopBlock (block, null, method.Location);
5267 // ig.MarkLabel (finish);
5268 ig.BeginFinallyBlock ();
5270 if (ec.ContainerType.BaseType != null) {
5271 Expression member_lookup = Expression.MemberLookup (
5272 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5273 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5275 if (member_lookup != null){
5276 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5278 ig.Emit (OpCodes.Ldarg_0);
5279 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5283 ig.EndExceptionBlock ();
5284 //ig.MarkLabel (ec.ReturnLabel);
5285 ig.Emit (OpCodes.Ret);
5289 // Should derive from MethodCore
5290 public class Destructor : Method {
5292 public Destructor (TypeContainer ds, Expression return_type, int mod, string name,
5293 Parameters parameters, Attributes attrs, Location l)
5294 : base (ds, null, return_type, mod, false, new MemberName (name),
5295 parameters, attrs, l)
5298 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5300 if (a.Type == TypeManager.conditional_attribute_type) {
5301 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
5305 base.ApplyAttributeBuilder (a, cb);
5309 abstract public class MemberBase : MemberCore {
5310 public Expression Type;
5312 public MethodAttributes flags;
5313 public readonly DeclSpace ds;
5315 protected readonly int explicit_mod_flags;
5318 // The "short" name of this property / indexer / event. This is the
5319 // name without the explicit interface.
5321 public string ShortName {
5322 get { return MemberName.Name; }
5324 SetMemberName (new MemberName (MemberName.Left, value));
5329 // The type of this property / indexer / event
5331 protected Type member_type;
5332 public Type MemberType {
5334 if (member_type == null && Type != null) {
5335 EmitContext ec = ds.EmitContext;
5336 bool old_unsafe = ec.InUnsafe;
5337 ec.InUnsafe = InUnsafe;
5338 Type = Type.ResolveAsTypeTerminal (ec);
5339 ec.InUnsafe = old_unsafe;
5341 member_type = Type == null ? null : Type.Type;
5348 // Whether this is an interface member.
5350 public bool IsInterface;
5353 // If true, this is an explicit interface implementation
5355 public bool IsExplicitImpl;
5358 // The interface type we are explicitly implementing
5360 public Type InterfaceType = null;
5363 // The constructor is only exposed to our children
5365 protected MemberBase (TypeContainer parent, DeclSpace ds, Expression type, int mod,
5366 int allowed_mod, int def_mod, MemberName name,
5367 Attributes attrs, Location loc)
5368 : base (parent, name, attrs, loc)
5371 explicit_mod_flags = mod;
5373 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
5374 IsExplicitImpl = (MemberName.Left != null);
5377 protected virtual bool CheckBase ()
5379 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5380 Report.Error (666, Location, "Protected member in struct declaration");
5384 if ((RootContext.WarningLevel >= 4) &&
5385 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5386 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5387 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5388 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
5394 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5396 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5400 foreach (Type partype in parameters){
5401 if (partype == TypeManager.void_type) {
5403 1547, Location, "Keyword 'void' cannot " +
5404 "be used in this context");
5408 if (partype.IsPointer){
5411 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5415 if (ds.AsAccessible (partype, ModFlags))
5418 if (this is Indexer)
5419 Report.Error (55, Location,
5420 "Inconsistent accessibility: parameter type `" +
5421 TypeManager.CSharpName (partype) + "' is less " +
5422 "accessible than indexer `" + Name + "'");
5423 else if ((this is Method) && ((Method) this).IsOperator)
5424 Report.Error (57, Location,
5425 "Inconsistent accessibility: parameter type `" +
5426 TypeManager.CSharpName (partype) + "' is less " +
5427 "accessible than operator `" + Name + "'");
5429 Report.Error (51, Location,
5430 "Inconsistent accessibility: parameter type `" +
5431 TypeManager.CSharpName (partype) + "' is less " +
5432 "accessible than method `" + Name + "'");
5439 protected virtual bool DoDefineBase ()
5441 EmitContext ec = Parent.EmitContext;
5443 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5446 throw new InternalErrorException ();
5449 ModFlags = Modifiers.PUBLIC |
5450 Modifiers.ABSTRACT |
5451 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5453 flags = MethodAttributes.Public |
5454 MethodAttributes.Abstract |
5455 MethodAttributes.HideBySig |
5456 MethodAttributes.NewSlot |
5457 MethodAttributes.Virtual;
5459 if (!Parent.MethodModifiersValid (this))
5462 flags = Modifiers.MethodAttr (ModFlags);
5465 if (IsExplicitImpl) {
5466 Expression expr = MemberName.Left.GetTypeExpression (Location);
5467 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5468 if (iface_texpr == null)
5471 InterfaceType = iface_texpr.Type;
5473 if (!InterfaceType.IsInterface) {
5474 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5478 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5481 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5487 protected virtual bool DoDefine ()
5489 EmitContext ec = ds.EmitContext;
5491 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5493 ec.InUnsafe = InUnsafe;
5495 if (MemberType == null)
5498 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5499 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5500 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5505 // verify accessibility
5506 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5507 Report.SymbolRelatedToPreviousError (MemberType);
5508 if (this is Property)
5509 Report.Error (53, Location,
5510 "Inconsistent accessibility: property type `" +
5511 TypeManager.CSharpName (MemberType) + "' is less " +
5512 "accessible than property `" + GetSignatureForError () + "'");
5513 else if (this is Indexer)
5514 Report.Error (54, Location,
5515 "Inconsistent accessibility: indexer return type `" +
5516 TypeManager.CSharpName (MemberType) + "' is less " +
5517 "accessible than indexer `" + Name + "'");
5518 else if (this is MethodCore) {
5519 if (this is Operator)
5520 Report.Error (56, Location,
5521 "Inconsistent accessibility: return type `" +
5522 TypeManager.CSharpName (MemberType) + "' is less " +
5523 "accessible than operator `" + Name + "'");
5525 Report.Error (50, Location,
5526 "Inconsistent accessibility: return type `" +
5527 TypeManager.CSharpName (MemberType) + "' is less " +
5528 "accessible than method `" + Name + "'");
5530 Report.Error (52, Location,
5531 "Inconsistent accessibility: field type `" +
5532 TypeManager.CSharpName (MemberType) + "' is less " +
5533 "accessible than field `" + Name + "'");
5538 if (MemberType.IsPointer && !UnsafeOK (Parent))
5544 public override string GetSignatureForError (TypeContainer tc)
5546 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5549 protected bool IsTypePermitted ()
5551 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5552 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5558 protected override bool VerifyClsCompliance(DeclSpace ds)
5560 if (base.VerifyClsCompliance (ds)) {
5564 if (IsInterface && HasClsCompliantAttribute && ds.IsClsComplianceRequired (ds)) {
5565 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5570 protected override void VerifyObsoleteAttribute()
5572 CheckUsageOfObsoleteAttribute (MemberType);
5577 // Fields and Events both generate FieldBuilders, we use this to share
5578 // their common bits. This is also used to flag usage of the field
5580 abstract public class FieldBase : MemberBase {
5581 public FieldBuilder FieldBuilder;
5582 public Status status;
5585 public enum Status : byte {
5587 HAS_OFFSET = 4 // Used by FieldMember.
5590 static string[] attribute_targets = new string [] { "field" };
5593 /// Symbol with same name in base class/struct
5595 public MemberInfo conflict_symbol;
5598 // The constructor is only exposed to our children
5600 protected FieldBase (TypeContainer parent, Expression type, int mod,
5601 int allowed_mod, MemberName name, object init,
5602 Attributes attrs, Location loc)
5603 : base (parent, parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5609 public override AttributeTargets AttributeTargets {
5611 return AttributeTargets.Field;
5615 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5617 if (a.Type == TypeManager.marshal_as_attr_type) {
5618 UnmanagedMarshal marshal = a.GetMarshal (this);
5619 if (marshal != null) {
5620 FieldBuilder.SetMarshal (marshal);
5625 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5626 a.Error_InvalidSecurityParent ();
5630 FieldBuilder.SetCustomAttribute (cb);
5634 // Whether this field has an initializer.
5636 public bool HasInitializer {
5638 return init != null;
5642 protected readonly Object init;
5644 Expression init_expr;
5645 bool init_expr_initialized = false;
5647 protected override bool CheckGenericOverride (MethodInfo method, string name)
5653 // Resolves and returns the field initializer.
5655 public Expression GetInitializerExpression (EmitContext ec)
5657 if (init_expr_initialized)
5661 if (init is Expression)
5662 e = (Expression) init;
5664 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5666 EmitContext parent_ec = Parent.EmitContext;
5668 bool old_is_static = parent_ec.IsStatic;
5669 parent_ec.IsStatic = ec.IsStatic;
5670 parent_ec.IsFieldInitializer = true;
5671 e = e.DoResolve (parent_ec);
5672 parent_ec.IsFieldInitializer = false;
5673 parent_ec.IsStatic = old_is_static;
5676 init_expr_initialized = true;
5681 protected override bool CheckBase ()
5683 if (!base.CheckBase ())
5690 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5691 if (conflict_symbol == null) {
5692 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5693 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5698 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5699 Report.SymbolRelatedToPreviousError (conflict_symbol);
5700 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5706 protected override bool DoDefine ()
5708 if (!base.DoDefine ())
5711 if (MemberType == TypeManager.void_type) {
5712 Report.Error (1547, Location,
5713 "Keyword 'void' cannot be used in this context");
5719 public override string GetSignatureForError ()
5721 if (FieldBuilder == null) {
5722 return base.GetSignatureForError (Parent);
5724 return TypeManager.GetFullNameSignature (FieldBuilder);
5727 protected virtual bool IsFieldClsCompliant {
5729 if (FieldBuilder == null)
5732 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5736 public override string[] ValidAttributeTargets {
5738 return attribute_targets;
5742 protected override bool VerifyClsCompliance (DeclSpace ds)
5744 if (!base.VerifyClsCompliance (ds))
5747 if (!IsFieldClsCompliant) {
5748 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5754 public void SetAssigned ()
5756 status |= Status.ASSIGNED;
5760 public abstract class FieldMember: FieldBase
5762 protected FieldMember (TypeContainer parent, Expression type, int mod,
5763 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5764 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5766 if ((mod & Modifiers.ABSTRACT) != 0)
5767 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5770 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5772 if (a.Type == TypeManager.field_offset_attribute_type)
5774 status |= Status.HAS_OFFSET;
5776 if (!Parent.HasExplicitLayout) {
5777 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5781 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5782 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5787 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5788 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5792 base.ApplyAttributeBuilder (a, cb);
5796 public override bool Define()
5798 EmitContext ec = Parent.EmitContext;
5800 throw new InternalErrorException ("FieldMember.Define called too early");
5802 if (MemberType == null)
5805 if (MemberType == TypeManager.void_type) {
5806 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5813 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5814 Report.Error (52, Location,
5815 "Inconsistent accessibility: field type `" +
5816 TypeManager.CSharpName (MemberType) + "' is less " +
5817 "accessible than field `" + Name + "'");
5821 if (!IsTypePermitted ())
5824 if (MemberType.IsPointer && !UnsafeOK (Parent))
5830 public override void Emit ()
5832 if (OptAttributes != null) {
5833 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5834 OptAttributes.Emit (ec, this);
5837 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5838 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5845 // Represents header string for documentation comment.
5847 public override string DocCommentHeader {
5848 get { return "F:"; }
5852 interface IFixedBuffer
5854 FieldInfo Element { get; }
5855 Type ElementType { get; }
5858 public class FixedFieldExternal: IFixedBuffer
5860 FieldInfo element_field;
5862 public FixedFieldExternal (FieldInfo fi)
5864 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5867 #region IFixedField Members
5869 public FieldInfo Element {
5871 return element_field;
5875 public Type ElementType {
5877 return element_field.FieldType;
5885 /// Fixed buffer implementation
5887 public class FixedField: FieldMember, IFixedBuffer
5889 public const string FixedElementName = "FixedElementField";
5890 static int GlobalCounter = 0;
5891 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5892 static FieldInfo[] fi;
5894 TypeBuilder fixed_buffer_type;
5895 FieldBuilder element;
5896 Expression size_expr;
5899 const int AllowedModifiers =
5902 Modifiers.PROTECTED |
5903 Modifiers.INTERNAL |
5906 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5907 Expression size_expr, Attributes attrs, Location loc):
5908 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5910 if (RootContext.Version == LanguageVersion.ISO_1)
5911 Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
5913 this.size_expr = size_expr;
5916 public override bool Define()
5918 if (Parent.Kind != Kind.Struct) {
5919 Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
5923 if (!base.Define ())
5926 if (!TypeManager.IsPrimitiveType (MemberType)) {
5927 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");
5931 Expression e = size_expr.Resolve (Parent.EmitContext);
5935 Constant c = e as Constant;
5937 Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
5941 IntConstant buffer_size_const = c.ToInt (Location);
5942 if (buffer_size_const == null)
5945 buffer_size = buffer_size_const.Value;
5947 if (buffer_size <= 0) {
5948 Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
5952 int type_size = Expression.GetTypeSize (MemberType);
5954 if (buffer_size > int.MaxValue / type_size) {
5955 Report.Error (1664, Location, "Fixed sized buffer of length '{0}' and type '{1}' exceeded 2^31 limit",
5956 buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5960 buffer_size *= type_size;
5963 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5965 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5966 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5967 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5968 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5970 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5971 TypeManager.RegisterFieldBase (FieldBuilder, this);
5976 public override void Emit()
5979 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5981 object[] fi_val = new object[1];
5982 fi_val [0] = buffer_size;
5984 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5985 ctor_args, fi, fi_val);
5986 fixed_buffer_type.SetCustomAttribute (cab);
5988 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5989 FieldBuilder.SetCustomAttribute (cab);
5993 protected override bool IsFieldClsCompliant {
5999 #region IFixedField Members
6001 public FieldInfo Element {
6007 public Type ElementType {
6017 // The Field class is used to represents class/struct fields during parsing.
6019 public class Field : FieldMember {
6021 // Modifiers allowed in a class declaration
6023 const int AllowedModifiers =
6026 Modifiers.PROTECTED |
6027 Modifiers.INTERNAL |
6030 Modifiers.VOLATILE |
6034 public Field (TypeContainer parent, Expression type, int mod, string name,
6035 Object expr_or_array_init, Attributes attrs, Location loc)
6036 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
6037 expr_or_array_init, attrs, loc)
6041 public override bool Define ()
6043 if (!base.Define ())
6046 if (RootContext.WarningLevel > 1){
6047 Type ptype = Parent.TypeBuilder.BaseType;
6049 // ptype is only null for System.Object while compiling corlib.
6051 TypeContainer.FindMembers (
6052 ptype, MemberTypes.Method,
6053 BindingFlags.Public |
6054 BindingFlags.Static | BindingFlags.Instance,
6055 System.Type.FilterName, Name);
6059 if ((ModFlags & Modifiers.VOLATILE) != 0){
6060 if (!MemberType.IsClass){
6061 Type vt = MemberType;
6063 if (TypeManager.IsEnumType (vt))
6064 vt = TypeManager.EnumToUnderlying (MemberType);
6066 if (!((vt == TypeManager.bool_type) ||
6067 (vt == TypeManager.sbyte_type) ||
6068 (vt == TypeManager.byte_type) ||
6069 (vt == TypeManager.short_type) ||
6070 (vt == TypeManager.ushort_type) ||
6071 (vt == TypeManager.int32_type) ||
6072 (vt == TypeManager.uint32_type) ||
6073 (vt == TypeManager.char_type) ||
6074 (vt == TypeManager.float_type) ||
6075 (!vt.IsValueType))){
6077 677, Location, Parent.MakeName (Name) +
6078 " A volatile field can not be of type `" +
6079 TypeManager.CSharpName (vt) + "'");
6084 if ((ModFlags & Modifiers.READONLY) != 0){
6087 "A field can not be both volatile and readonly");
6092 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6094 if (Parent.Kind == Kind.Struct &&
6095 ((fa & FieldAttributes.Static) == 0) &&
6096 MemberType == Parent.TypeBuilder &&
6097 !TypeManager.IsBuiltinType (MemberType)){
6098 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6099 "' causes a cycle in the structure layout");
6104 FieldBuilder = Parent.TypeBuilder.DefineField (
6105 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6107 TypeManager.RegisterFieldBase (FieldBuilder, this);
6109 catch (ArgumentException) {
6110 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6117 protected override bool VerifyClsCompliance (DeclSpace ds)
6119 if (!base.VerifyClsCompliance (ds))
6122 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6123 Report.Warning (3026, 1, Location, "CLS-compliant field '{0}' cannot be volatile", GetSignatureForError ());
6131 // `set' and `get' accessors are represented with an Accessor.
6133 public class Accessor {
6135 // Null if the accessor is empty, or a Block if not
6137 public const int AllowedModifiers =
6139 Modifiers.PROTECTED |
6140 Modifiers.INTERNAL |
6143 public ToplevelBlock Block;
6144 public Attributes Attributes;
6145 public Location Location;
6146 public int ModFlags;
6148 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6153 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6158 // Ooouh Martin, templates are missing here.
6159 // When it will be possible move here a lot of child code and template method type.
6160 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
6161 protected MethodData method_data;
6162 protected ToplevelBlock block;
6163 protected ListDictionary declarative_security;
6165 // The accessor are created event if they are not wanted.
6166 // But we need them because their names are reserved.
6167 // Field says whether accessor will be emited or not
6168 public readonly bool IsDummy;
6170 protected readonly string prefix;
6172 ReturnParameter return_attributes;
6174 public AbstractPropertyEventMethod (MemberBase member, string prefix)
6175 : base (null, SetupName (prefix, member), null, member.Location)
6177 this.prefix = prefix;
6181 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
6183 : base (null, SetupName (prefix, member),
6184 accessor.Attributes, accessor.Location)
6186 this.prefix = prefix;
6187 this.block = accessor.Block;
6190 static MemberName SetupName (string prefix, MemberBase member)
6192 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
6195 public void UpdateName (MemberBase member)
6197 SetMemberName (SetupName (prefix, member));
6200 #region IMethodData Members
6202 public ToplevelBlock Block {
6212 public CallingConventions CallingConventions {
6214 return CallingConventions.Standard;
6218 public bool IsExcluded (EmitContext ec)
6223 GenericMethod IMethodData.GenericMethod {
6229 public MemberName MethodName {
6235 public abstract ObsoleteAttribute GetObsoleteAttribute ();
6236 public abstract Type[] ParameterTypes { get; }
6237 public abstract Type ReturnType { get; }
6238 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
6242 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6244 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6245 a.Type == TypeManager.conditional_attribute_type) {
6246 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 ());
6250 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6251 if (declarative_security == null)
6252 declarative_security = new ListDictionary ();
6253 a.ExtractSecurityPermissionSet (declarative_security);
6257 if (a.Target == AttributeTargets.Method) {
6258 method_data.MethodBuilder.SetCustomAttribute (cb);
6262 if (a.Target == AttributeTargets.ReturnValue) {
6263 if (return_attributes == null)
6264 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6266 return_attributes.ApplyAttributeBuilder (a, cb);
6270 ApplyToExtraTarget (a, cb);
6273 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6275 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6278 public override bool Define()
6280 throw new NotSupportedException ();
6283 public virtual void Emit (TypeContainer container)
6285 EmitMethod (container);
6287 if (declarative_security != null) {
6288 foreach (DictionaryEntry de in declarative_security) {
6289 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6296 protected virtual void EmitMethod (TypeContainer container)
6298 method_data.Emit (container, this);
6301 public override bool IsClsComplianceRequired(DeclSpace ds)
6306 public bool IsDuplicateImplementation (MethodCore method)
6308 if (Name != method.Name)
6311 Type[] param_types = method.ParameterTypes;
6313 if (param_types.Length != ParameterTypes.Length)
6316 for (int i = 0; i < param_types.Length; i++)
6317 if (param_types [i] != ParameterTypes [i])
6320 Report.SymbolRelatedToPreviousError (method);
6321 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with " +
6322 "the same parameter types", Parent.Name, Name);
6326 public override bool IsUsed
6336 public new Location Location {
6338 return base.Location;
6343 // Represents header string for documentation comment.
6345 public override string DocCommentHeader {
6346 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6349 protected override void VerifyObsoleteAttribute()
6356 // Properties and Indexers both generate PropertyBuilders, we use this to share
6357 // their common bits.
6359 abstract public class PropertyBase : MethodCore {
6361 public class GetMethod: PropertyMethod
6363 static string[] attribute_targets = new string [] { "method", "return" };
6365 public GetMethod (MethodCore method):
6366 base (method, "get_")
6370 public GetMethod (MethodCore method, Accessor accessor):
6371 base (method, accessor, "get_")
6375 public override MethodBuilder Define(TypeContainer container)
6377 base.Define (container);
6379 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
6381 if (!method_data.Define (container))
6384 return method_data.MethodBuilder;
6387 public override string GetSignatureForError (TypeContainer tc)
6389 return String.Concat (base.GetSignatureForError (tc), ".get");
6392 public override Type ReturnType {
6394 return method.MemberType;
6398 public override string[] ValidAttributeTargets {
6400 return attribute_targets;
6405 public class SetMethod: PropertyMethod {
6407 static string[] attribute_targets = new string [] { "method", "param", "return" };
6408 ImplicitParameter param_attr;
6410 public SetMethod (MethodCore method):
6411 base (method, "set_")
6415 public SetMethod (MethodCore method, Accessor accessor):
6416 base (method, accessor, "set_")
6420 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6422 if (a.Target == AttributeTargets.Parameter) {
6423 if (param_attr == null)
6424 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6426 param_attr.ApplyAttributeBuilder (a, cb);
6430 base.ApplyAttributeBuilder (a, cb);
6433 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
6435 Parameter [] parms = new Parameter [1];
6436 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
6437 Parameters parameters = new Parameters (parms, null, method.Location);
6439 bool old_unsafe = ec.InUnsafe;
6440 ec.InUnsafe = InUnsafe;
6441 Type [] types = parameters.GetParameterInfo (ec);
6442 ec.InUnsafe = old_unsafe;
6444 return new InternalParameters (types, parameters);
6447 public override MethodBuilder Define (TypeContainer container)
6449 if (container.EmitContext == null)
6450 throw new InternalErrorException ("SetMethod.Define called too early");
6452 base.Define (container);
6454 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6456 if (!method_data.Define (container))
6459 return method_data.MethodBuilder;
6462 public override string GetSignatureForError (TypeContainer tc)
6464 return String.Concat (base.GetSignatureForError (tc), ".set");
6467 public override Type[] ParameterTypes {
6469 return new Type[] { method.MemberType };
6473 public override Type ReturnType {
6475 return TypeManager.void_type;
6479 public override string[] ValidAttributeTargets {
6481 return attribute_targets;
6486 static string[] attribute_targets = new string [] { "property" };
6488 public abstract class PropertyMethod: AbstractPropertyEventMethod {
6489 protected readonly MethodCore method;
6490 protected MethodAttributes flags;
6492 public PropertyMethod (MethodCore method, string prefix)
6493 : base (method, prefix)
6495 this.method = method;
6496 Parent = method.Parent;
6499 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6500 : base (method, accessor, prefix)
6502 this.method = method;
6503 Parent = method.Parent;
6504 this.ModFlags = accessor.ModFlags;
6506 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6507 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
6511 public override AttributeTargets AttributeTargets {
6513 return AttributeTargets.Method;
6517 public override bool IsClsComplianceRequired(DeclSpace ds)
6519 return method.IsClsComplianceRequired (ds);
6522 public InternalParameters ParameterInfo
6525 return method_data.ParameterInfo;
6529 public virtual MethodBuilder Define (TypeContainer container)
6532 // Check for custom access modifier
6534 if (ModFlags == 0) {
6535 ModFlags = method.ModFlags;
6536 flags = method.flags;
6538 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6539 Report.Error (442, Location, "{0}': abstract properties cannot have private accessors", GetSignatureForError (container));
6542 CheckModifiers (container, ModFlags);
6543 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6544 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6545 flags = Modifiers.MethodAttr (ModFlags);
6546 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6553 public bool HasCustomAccessModifier
6556 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6560 public override Type[] ParameterTypes {
6562 return TypeManager.NoTypes;
6566 public override EmitContext CreateEmitContext (TypeContainer tc,
6569 return new EmitContext (
6570 tc, method.ds, method.Location, ig, ReturnType,
6571 method.ModFlags, false);
6574 public override ObsoleteAttribute GetObsoleteAttribute ()
6576 return method.GetObsoleteAttribute (method.ds);
6579 public override string GetSignatureForError (TypeContainer tc)
6581 return String.Concat (tc.Name, '.', method.Name);
6584 void CheckModifiers (TypeContainer container, int modflags)
6587 int mflags = method.ModFlags & Modifiers.Accessibility;
6589 if ((mflags & Modifiers.PUBLIC) != 0) {
6590 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6592 else if ((mflags & Modifiers.PROTECTED) != 0) {
6593 if ((mflags & Modifiers.INTERNAL) != 0)
6594 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6596 flags |= Modifiers.PRIVATE;
6598 else if ((mflags & Modifiers.INTERNAL) != 0)
6599 flags |= Modifiers.PRIVATE;
6601 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6602 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6603 GetSignatureForError (container));
6606 public override bool MarkForDuplicationCheck ()
6608 caching_flags |= Flags.TestMethodDuplication;
6613 public PropertyMethod Get, Set;
6614 public PropertyBuilder PropertyBuilder;
6615 public MethodBuilder GetBuilder, SetBuilder;
6617 protected EmitContext ec;
6619 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6620 int allowed_mod, bool is_iface, MemberName name,
6621 Parameters parameters, Attributes attrs,
6623 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6624 attrs, parameters, loc)
6628 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6630 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6631 a.Error_InvalidSecurityParent ();
6635 PropertyBuilder.SetCustomAttribute (cb);
6638 public override AttributeTargets AttributeTargets {
6640 return AttributeTargets.Property;
6644 public override bool Define ()
6649 if (!IsTypePermitted ())
6655 protected override bool DoDefine ()
6657 if (!base.DoDefine ())
6661 // Accessors modifiers check
6663 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6664 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6665 GetSignatureForError ());
6669 if ((Get.IsDummy || Set.IsDummy)
6670 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6671 Report.Error (276, Location,
6672 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6673 GetSignatureForError ());
6677 if (MemberType.IsAbstract && MemberType.IsSealed) {
6678 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6682 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6686 public override string GetSignatureForError()
6688 if (PropertyBuilder == null)
6689 return GetSignatureForError (Parent);
6691 return TypeManager.CSharpSignature (PropertyBuilder, false);
6694 protected override bool CheckForDuplications ()
6696 ArrayList ar = Parent.Indexers;
6698 int arLen = ar.Count;
6700 for (int i = 0; i < arLen; i++) {
6701 Indexer m = (Indexer) ar [i];
6702 if (IsDuplicateImplementation (m))
6707 ar = Parent.Properties;
6709 int arLen = ar.Count;
6711 for (int i = 0; i < arLen; i++) {
6712 Property m = (Property) ar [i];
6713 if (IsDuplicateImplementation (m))
6721 // TODO: rename to Resolve......
6722 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6724 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6725 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6727 if (base_property == null)
6730 base_ret_type = base_property.PropertyType;
6731 MethodInfo get_accessor = base_property.GetGetMethod (true);
6732 MethodInfo set_accessor = base_property.GetSetMethod (true);
6733 MethodAttributes get_accessor_access, set_accessor_access;
6735 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6736 if (Get != null && !Get.IsDummy && get_accessor == null) {
6737 Report.SymbolRelatedToPreviousError (base_property);
6738 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6741 if (Set != null && !Set.IsDummy && set_accessor == null) {
6742 Report.SymbolRelatedToPreviousError (base_property);
6743 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6748 // Check base class accessors access
6750 get_accessor_access = set_accessor_access = 0;
6751 if ((ModFlags & Modifiers.NEW) == 0) {
6752 if (get_accessor != null) {
6753 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6754 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6756 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6757 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6758 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6761 if (set_accessor != null) {
6762 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6763 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6765 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6766 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6767 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6772 // Get the less restrictive access
6774 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6777 public override void Emit ()
6780 // The PropertyBuilder can be null for explicit implementations, in that
6781 // case, we do not actually emit the ".property", so there is nowhere to
6782 // put the attribute
6784 if (PropertyBuilder != null && OptAttributes != null)
6785 OptAttributes.Emit (ec, this);
6797 /// Tests whether accessors are not in collision with some method (CS0111)
6799 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6801 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6804 public override bool IsUsed
6810 return Get.IsUsed | Set.IsUsed;
6814 protected override void SetMemberName (MemberName new_name)
6816 base.SetMemberName (new_name);
6818 Get.UpdateName (this);
6819 Set.UpdateName (this);
6822 public override string[] ValidAttributeTargets {
6824 return attribute_targets;
6829 // Represents header string for documentation comment.
6831 public override string DocCommentHeader {
6832 get { return "P:"; }
6836 public class Property : PropertyBase, IIteratorContainer {
6837 const int AllowedModifiers =
6840 Modifiers.PROTECTED |
6841 Modifiers.INTERNAL |
6845 Modifiers.OVERRIDE |
6846 Modifiers.ABSTRACT |
6849 Modifiers.METHOD_YIELDS |
6852 const int AllowedInterfaceModifiers =
6855 public Property (TypeContainer parent, Expression type, int mod_flags,
6856 bool is_iface, MemberName name, Attributes attrs,
6857 Accessor get_block, Accessor set_block, Location loc)
6858 : base (parent, type, mod_flags,
6859 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6860 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6863 if (get_block == null)
6864 Get = new GetMethod (this);
6866 Get = new GetMethod (this, get_block);
6868 if (set_block == null)
6869 Set = new SetMethod (this);
6871 Set = new SetMethod (this, set_block);
6874 public override bool Define ()
6876 if (!DoDefineBase ())
6879 if (!base.Define ())
6885 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6889 GetBuilder = Get.Define (Parent);
6890 if (GetBuilder == null)
6894 // Setup iterator if we are one
6896 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6897 Iterator iterator = new Iterator (
6898 Parent, "get", MemberType,
6900 ModFlags, Get.Block, Location);
6902 if (!iterator.DefineIterator ())
6904 Get.Block = iterator.Block;
6909 SetBuilder = Set.Define (Parent);
6910 if (SetBuilder == null)
6913 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6916 // FIXME - PropertyAttributes.HasDefault ?
6918 PropertyAttributes prop_attr = PropertyAttributes.None;
6920 prop_attr |= PropertyAttributes.RTSpecialName |
6921 PropertyAttributes.SpecialName;
6923 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6924 Name, prop_attr, MemberType, null);
6927 PropertyBuilder.SetGetMethod (GetBuilder);
6930 PropertyBuilder.SetSetMethod (SetBuilder);
6932 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6936 public void SetYields ()
6938 ModFlags |= Modifiers.METHOD_YIELDS;
6943 /// Gigantic workaround for lameness in SRE follows :
6944 /// This class derives from EventInfo and attempts to basically
6945 /// wrap around the EventBuilder so that FindMembers can quickly
6946 /// return this in it search for members
6948 public class MyEventBuilder : EventInfo {
6951 // We use this to "point" to our Builder which is
6952 // not really a MemberInfo
6954 EventBuilder MyBuilder;
6957 // We "catch" and wrap these methods
6959 MethodInfo raise, remove, add;
6961 EventAttributes attributes;
6962 Type declaring_type, reflected_type, event_type;
6967 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6969 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6971 // And now store the values in our own fields.
6973 declaring_type = type_builder;
6975 reflected_type = type_builder;
6977 attributes = event_attr;
6980 this.event_type = event_type;
6984 // Methods that you have to override. Note that you only need
6985 // to "implement" the variants that take the argument (those are
6986 // the "abstract" methods, the others (GetAddMethod()) are
6989 public override MethodInfo GetAddMethod (bool nonPublic)
6994 public override MethodInfo GetRemoveMethod (bool nonPublic)
6999 public override MethodInfo GetRaiseMethod (bool nonPublic)
7005 // These methods make "MyEventInfo" look like a Builder
7007 public void SetRaiseMethod (MethodBuilder raiseMethod)
7009 raise = raiseMethod;
7010 MyBuilder.SetRaiseMethod (raiseMethod);
7013 public void SetRemoveOnMethod (MethodBuilder removeMethod)
7015 remove = removeMethod;
7016 MyBuilder.SetRemoveOnMethod (removeMethod);
7019 public void SetAddOnMethod (MethodBuilder addMethod)
7022 MyBuilder.SetAddOnMethod (addMethod);
7025 public void SetCustomAttribute (CustomAttributeBuilder cb)
7027 MyBuilder.SetCustomAttribute (cb);
7030 public override object [] GetCustomAttributes (bool inherit)
7032 // FIXME : There's nothing which can be seemingly done here because
7033 // we have no way of getting at the custom attribute objects of the
7038 public override object [] GetCustomAttributes (Type t, bool inherit)
7040 // FIXME : Same here !
7044 public override bool IsDefined (Type t, bool b)
7049 public override EventAttributes Attributes {
7055 public override string Name {
7061 public override Type DeclaringType {
7063 return declaring_type;
7067 public override Type ReflectedType {
7069 return reflected_type;
7073 public Type EventType {
7079 public void SetUsed ()
7081 if (my_event != null) {
7082 my_event.status = FieldBase.Status.ASSIGNED;
7083 my_event.SetMemberIsUsed ();
7089 /// For case when event is declared like property (with add and remove accessors).
7091 public class EventProperty: Event {
7093 static string[] attribute_targets = new string [] { "event", "property" };
7095 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
7096 bool is_iface, MemberName name, Object init,
7097 Attributes attrs, Accessor add, Accessor remove,
7099 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
7101 Add = new AddDelegateMethod (this, add);
7102 Remove = new RemoveDelegateMethod (this, remove);
7104 // For this event syntax we don't report error CS0067
7105 // because it is hard to do it.
7109 public override string[] ValidAttributeTargets {
7111 return attribute_targets;
7117 /// Event is declared like field.
7119 public class EventField: Event {
7121 static string[] attribute_targets = new string [] { "event", "field", "method" };
7122 static string[] attribute_targets_interface = new string[] { "event", "method" };
7124 public EventField (TypeContainer parent, Expression type, int mod_flags,
7125 bool is_iface, MemberName name, Object init,
7126 Attributes attrs, Location loc)
7127 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
7129 Add = new AddDelegateMethod (this);
7130 Remove = new RemoveDelegateMethod (this);
7133 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7135 if (a.Target == AttributeTargets.Field) {
7136 FieldBuilder.SetCustomAttribute (cb);
7140 if (a.Target == AttributeTargets.Method) {
7141 Add.ApplyAttributeBuilder (a, cb);
7142 Remove.ApplyAttributeBuilder (a, cb);
7146 base.ApplyAttributeBuilder (a, cb);
7149 public override string[] ValidAttributeTargets {
7151 return IsInterface ? attribute_targets_interface : attribute_targets;
7156 public abstract class Event : FieldBase {
7158 protected sealed class AddDelegateMethod: DelegateMethod
7161 public AddDelegateMethod (Event method):
7162 base (method, "add_")
7166 public AddDelegateMethod (Event method, Accessor accessor):
7167 base (method, accessor, "add_")
7171 protected override MethodInfo DelegateMethodInfo {
7173 return TypeManager.delegate_combine_delegate_delegate;
7179 protected sealed class RemoveDelegateMethod: DelegateMethod
7181 public RemoveDelegateMethod (Event method):
7182 base (method, "remove_")
7186 public RemoveDelegateMethod (Event method, Accessor accessor):
7187 base (method, accessor, "remove_")
7191 protected override MethodInfo DelegateMethodInfo {
7193 return TypeManager.delegate_remove_delegate_delegate;
7199 public abstract class DelegateMethod: AbstractPropertyEventMethod
7201 protected readonly Event method;
7202 ImplicitParameter param_attr;
7204 static string[] attribute_targets = new string [] { "method", "param", "return" };
7206 public DelegateMethod (Event method, string prefix)
7207 : base (method, prefix)
7209 this.method = method;
7212 public DelegateMethod (Event method, Accessor accessor, string prefix)
7213 : base (method, accessor, prefix)
7215 this.method = method;
7218 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7220 if (a.Target == AttributeTargets.Parameter) {
7221 if (param_attr == null)
7222 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7224 param_attr.ApplyAttributeBuilder (a, cb);
7228 base.ApplyAttributeBuilder (a, cb);
7231 public override AttributeTargets AttributeTargets {
7233 return AttributeTargets.Method;
7237 public override bool IsClsComplianceRequired(DeclSpace ds)
7239 return method.IsClsComplianceRequired (ds);
7242 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
7244 method_data = new MethodData (method, ip, method.ModFlags,
7245 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7247 if (!method_data.Define (container))
7250 MethodBuilder mb = method_data.MethodBuilder;
7251 mb.DefineParameter (1, ParameterAttributes.None, "value");
7256 protected override void EmitMethod (TypeContainer tc)
7258 if (block != null) {
7259 base.EmitMethod (tc);
7263 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7266 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
7267 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
7269 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
7270 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7271 ig.Emit (OpCodes.Ldsfld, field_info);
7272 ig.Emit (OpCodes.Ldarg_0);
7273 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7274 ig.Emit (OpCodes.Castclass, method.MemberType);
7275 ig.Emit (OpCodes.Stsfld, field_info);
7277 ig.Emit (OpCodes.Ldarg_0);
7278 ig.Emit (OpCodes.Ldarg_0);
7279 ig.Emit (OpCodes.Ldfld, field_info);
7280 ig.Emit (OpCodes.Ldarg_1);
7281 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7282 ig.Emit (OpCodes.Castclass, method.MemberType);
7283 ig.Emit (OpCodes.Stfld, field_info);
7285 ig.Emit (OpCodes.Ret);
7288 protected abstract MethodInfo DelegateMethodInfo { get; }
7290 public override Type[] ParameterTypes {
7292 return new Type[] { method.MemberType };
7296 public override Type ReturnType {
7298 return TypeManager.void_type;
7302 public override EmitContext CreateEmitContext (TypeContainer tc,
7305 return new EmitContext (
7306 tc, method.Parent, Location, ig, ReturnType,
7307 method.ModFlags, false);
7310 public override string GetSignatureForError (TypeContainer tc)
7312 return String.Concat (tc.Name, '.', method.Name);
7315 public override ObsoleteAttribute GetObsoleteAttribute ()
7317 return method.GetObsoleteAttribute (method.Parent);
7320 public override string[] ValidAttributeTargets {
7322 return attribute_targets;
7328 const int AllowedModifiers =
7331 Modifiers.PROTECTED |
7332 Modifiers.INTERNAL |
7337 Modifiers.OVERRIDE |
7341 const int AllowedInterfaceModifiers =
7344 public DelegateMethod Add, Remove;
7345 public MyEventBuilder EventBuilder;
7346 public MethodBuilder AddBuilder, RemoveBuilder;
7348 public Event (TypeContainer parent, Expression type, int mod_flags,
7349 bool is_iface, MemberName name, Object init, Attributes attrs,
7351 : base (parent, type, mod_flags,
7352 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7353 name, init, attrs, loc)
7355 IsInterface = is_iface;
7358 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7360 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7361 a.Error_InvalidSecurityParent ();
7365 EventBuilder.SetCustomAttribute (cb);
7368 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7370 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7373 public override AttributeTargets AttributeTargets {
7375 return AttributeTargets.Event;
7379 public override bool Define ()
7381 EventAttributes e_attr;
7382 e_attr = EventAttributes.None;
7384 if (!DoDefineBase ())
7390 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
7391 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
7392 "': abstract event can not have an initializer");
7396 if (!TypeManager.IsDelegateType (MemberType)) {
7397 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
7398 "' : event must be of a delegate type");
7402 EmitContext ec = Parent.EmitContext;
7404 throw new InternalErrorException ("Event.Define called too early?");
7405 bool old_unsafe = ec.InUnsafe;
7406 ec.InUnsafe = InUnsafe;
7408 Parameter [] parms = new Parameter [1];
7409 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
7410 Parameters parameters = new Parameters (parms, null, Location);
7411 Type [] types = parameters.GetParameterInfo (ec);
7412 InternalParameters ip = new InternalParameters (types, parameters);
7414 ec.InUnsafe = old_unsafe;
7420 // Now define the accessors
7423 AddBuilder = Add.Define (Parent, ip);
7424 if (AddBuilder == null)
7427 RemoveBuilder = Remove.Define (Parent, ip);
7428 if (RemoveBuilder == null)
7431 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7433 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7434 FieldBuilder = Parent.TypeBuilder.DefineField (
7436 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7437 TypeManager.RegisterPrivateFieldOfEvent (
7438 (EventInfo) EventBuilder, FieldBuilder);
7439 TypeManager.RegisterFieldBase (FieldBuilder, this);
7442 EventBuilder.SetAddOnMethod (AddBuilder);
7443 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7445 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7449 protected override bool CheckBase ()
7451 if (!base.CheckBase ())
7454 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7455 if (!(conflict_symbol is EventInfo)) {
7456 Report.SymbolRelatedToPreviousError (conflict_symbol);
7457 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
7465 public override void Emit ()
7467 if (OptAttributes != null) {
7468 EmitContext ec = new EmitContext (
7469 Parent, Location, null, MemberType, ModFlags);
7470 OptAttributes.Emit (ec, this);
7474 Remove.Emit (Parent);
7479 public override string GetSignatureForError ()
7481 if (EventBuilder == null)
7482 return base.GetSignatureForError (Parent);
7484 return TypeManager.GetFullNameSignature (EventBuilder);
7488 // Represents header string for documentation comment.
7490 public override string DocCommentHeader {
7491 get { return "E:"; }
7496 public class Indexer : PropertyBase {
7498 class GetIndexerMethod: GetMethod
7500 public GetIndexerMethod (MethodCore method):
7505 public GetIndexerMethod (MethodCore method, Accessor accessor):
7506 base (method, accessor)
7510 // TODO: one GetSignatureForError is enough (reuse Parent member)
7511 public override string GetSignatureForError (TypeContainer tc)
7513 string core = base.GetSignatureForError (tc);
7514 return core.Replace (TypeContainer.DefaultIndexerName,
7515 String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
7518 public override Type[] ParameterTypes {
7520 return method.ParameterTypes;
7525 class SetIndexerMethod: SetMethod
7527 readonly Parameters parameters;
7529 public SetIndexerMethod (MethodCore method):
7534 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7535 base (method, accessor)
7537 this.parameters = parameters;
7540 public override Type[] ParameterTypes {
7542 int top = method.ParameterTypes.Length;
7543 Type [] set_pars = new Type [top + 1];
7544 method.ParameterTypes.CopyTo (set_pars, 0);
7545 set_pars [top] = method.MemberType;
7550 protected override InternalParameters GetParameterInfo (EmitContext ec)
7552 Parameter [] fixed_parms = parameters.FixedParameters;
7554 if (fixed_parms == null){
7555 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7556 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7557 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7559 // Here is the problem: the `value' parameter has
7560 // to come *after* the array parameter in the declaration
7562 // X (object [] x, Type value)
7565 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7566 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7570 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7572 fixed_parms.CopyTo (tmp, 0);
7573 tmp [fixed_parms.Length] = new Parameter (
7574 method.Type, "value", Parameter.Modifier.NONE, null);
7576 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7577 Type [] types = set_formal_params.GetParameterInfo (ec);
7579 return new InternalParameters (types, set_formal_params);
7583 const int AllowedModifiers =
7586 Modifiers.PROTECTED |
7587 Modifiers.INTERNAL |
7591 Modifiers.OVERRIDE |
7596 const int AllowedInterfaceModifiers =
7600 // Are we implementing an interface ?
7602 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7603 bool is_iface, Parameters parameters, Attributes attrs,
7604 Accessor get_block, Accessor set_block, Location loc)
7605 : base (parent, type, mod,
7606 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7607 is_iface, name, parameters, attrs, loc)
7609 if (get_block == null)
7610 Get = new GetIndexerMethod (this);
7612 Get = new GetIndexerMethod (this, get_block);
7614 if (set_block == null)
7615 Set = new SetIndexerMethod (this);
7617 Set = new SetIndexerMethod (this, parameters, set_block);
7620 public override bool Define ()
7622 PropertyAttributes prop_attr =
7623 PropertyAttributes.RTSpecialName |
7624 PropertyAttributes.SpecialName;
7626 if (!DoDefineBase ())
7629 if (!base.Define ())
7632 if (MemberType == TypeManager.void_type) {
7633 Report.Error (620, Location, "Indexers cannot have void type");
7637 if (OptAttributes != null) {
7638 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7639 if (indexer_attr != null) {
7640 // Remove the attribute from the list because it is not emitted
7641 OptAttributes.Attrs.Remove (indexer_attr);
7643 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7645 if (IsExplicitImpl) {
7646 Report.Error (415, indexer_attr.Location,
7647 "The 'IndexerName' attribute is valid only on an " +
7648 "indexer that is not an explicit interface member declaration");
7652 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7653 Report.Error (609, indexer_attr.Location,
7654 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7658 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7659 Report.Error (633, indexer_attr.Location,
7660 "The argument to the 'IndexerName' attribute must be a valid identifier");
7666 if (InterfaceType != null) {
7667 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7668 if (base_IndexerName != Name)
7669 ShortName = base_IndexerName;
7672 if (!Parent.AddToMemberContainer (this) ||
7673 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7679 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7681 GetBuilder = Get.Define (Parent);
7682 if (GetBuilder == null)
7687 SetBuilder = Set.Define (Parent);
7688 if (SetBuilder == null)
7693 // Now name the parameters
7695 Parameter [] p = Parameters.FixedParameters;
7697 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7698 Report.Error (631, Location, "ref and out are not valid in this context");
7704 for (i = 0; i < p.Length; ++i) {
7706 GetBuilder.DefineParameter (
7707 i + 1, p [i].Attributes, p [i].Name);
7710 SetBuilder.DefineParameter (
7711 i + 1, p [i].Attributes, p [i].Name);
7715 SetBuilder.DefineParameter (
7716 i + 1, ParameterAttributes.None, "value");
7718 if (i != ParameterTypes.Length) {
7719 Parameter array_param = Parameters.ArrayParameter;
7721 SetBuilder.DefineParameter (
7722 i + 1, array_param.Attributes, array_param.Name);
7726 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7727 Name, prop_attr, MemberType, ParameterTypes);
7730 PropertyBuilder.SetGetMethod (GetBuilder);
7733 PropertyBuilder.SetSetMethod (SetBuilder);
7735 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7740 public override string GetSignatureForError ()
7742 if (PropertyBuilder == null)
7743 return GetSignatureForError (Parent);
7745 return TypeManager.CSharpSignature (PropertyBuilder, true);
7748 public override string GetSignatureForError(TypeContainer tc)
7750 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7753 public override bool MarkForDuplicationCheck ()
7755 caching_flags |= Flags.TestMethodDuplication;
7761 public class Operator : MethodCore, IIteratorContainer {
7763 const int AllowedModifiers =
7769 public enum OpType : byte {
7779 // Unary and Binary operators
7802 // Implicit and Explicit
7807 public readonly OpType OperatorType;
7808 public MethodBuilder OperatorMethodBuilder;
7810 public Method OperatorMethod;
7812 static string[] attribute_targets = new string [] { "method", "return" };
7814 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7815 int mod_flags, Parameters parameters,
7816 ToplevelBlock block, Attributes attrs, Location loc)
7817 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7818 new MemberName ("op_" + type), attrs, parameters, loc)
7820 OperatorType = type;
7824 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7826 OperatorMethod.ApplyAttributeBuilder (a, cb);
7829 public override AttributeTargets AttributeTargets {
7831 return AttributeTargets.Method;
7835 protected override bool CheckGenericOverride (MethodInfo method, string name)
7840 protected override bool CheckForDuplications()
7842 ArrayList ar = Parent.Operators;
7844 int arLen = ar.Count;
7846 for (int i = 0; i < arLen; i++) {
7847 Operator o = (Operator) ar [i];
7848 if (IsDuplicateImplementation (o))
7853 ar = Parent.Methods;
7855 int arLen = ar.Count;
7857 for (int i = 0; i < arLen; i++) {
7858 Method m = (Method) ar [i];
7859 if (IsDuplicateImplementation (m))
7867 public override bool Define ()
7869 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7870 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7871 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7878 if (MemberType == TypeManager.void_type) {
7879 Report.Error (590, Location, "User-defined operators cannot return void");
7883 OperatorMethod = new Method (
7884 Parent, null, Type, ModFlags, false, MemberName,
7885 Parameters, OptAttributes, Location);
7887 OperatorMethod.Block = Block;
7888 OperatorMethod.IsOperator = true;
7889 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7890 OperatorMethod.Define ();
7892 if (OperatorMethod.MethodBuilder == null)
7895 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7897 parameter_types = OperatorMethod.ParameterTypes;
7898 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7899 Type return_type = OperatorMethod.ReturnType;
7900 Type first_arg_type = parameter_types [0];
7905 // Rules for conversion operators
7907 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7908 if (first_arg_type == return_type && first_arg_type == declaring_type){
7911 "User-defined conversion cannot take an object of the " +
7912 "enclosing type and convert to an object of the enclosing" +
7917 if (first_arg_type != declaring_type && return_type != declaring_type){
7920 "User-defined conversion must convert to or from the " +
7925 if (first_arg_type == TypeManager.object_type ||
7926 return_type == TypeManager.object_type){
7929 "User-defined conversion cannot convert to or from " +
7934 if (first_arg_type.IsInterface || return_type.IsInterface){
7937 "User-defined conversion cannot convert to or from an " +
7942 if (first_arg_type.IsSubclassOf (return_type)
7943 || return_type.IsSubclassOf (first_arg_type)){
7944 if (declaring_type.IsSubclassOf (return_type)) {
7945 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7948 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7951 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7952 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7953 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");
7956 } else if (Parameters.FixedParameters.Length == 1) {
7957 // Checks for Unary operators
7959 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7960 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7961 Report.Error (448, Location,
7962 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7965 if (first_arg_type != declaring_type){
7967 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7972 if (first_arg_type != declaring_type){
7975 "The parameter of a unary operator must be the " +
7980 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7981 if (return_type != TypeManager.bool_type){
7984 "The return type of operator True or False " +
7991 if (OperatorType == OpType.BitwiseAnd &&
7992 (first_arg_type != return_type || first_arg_type != parameter_types [1])) {
7993 Report.Error (217, Location, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
7994 "must have the same return type as the type of its 2 parameters", GetSignatureForError ());
7998 // Checks for Binary operators
8000 if (first_arg_type != declaring_type &&
8001 parameter_types [1] != declaring_type){
8004 "One of the parameters of a binary operator must " +
8005 "be the containing type");
8013 public override void Emit ()
8016 // abstract or extern methods have no bodies
8018 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
8021 OperatorMethod.Emit ();
8025 // Operator cannot be override
8026 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
8031 public static string GetName (OpType ot)
8034 case OpType.LogicalNot:
8036 case OpType.OnesComplement:
8038 case OpType.Increment:
8040 case OpType.Decrement:
8046 case OpType.Addition:
8048 case OpType.Subtraction:
8050 case OpType.UnaryPlus:
8052 case OpType.UnaryNegation:
8054 case OpType.Multiply:
8056 case OpType.Division:
8058 case OpType.Modulus:
8060 case OpType.BitwiseAnd:
8062 case OpType.BitwiseOr:
8064 case OpType.ExclusiveOr:
8066 case OpType.LeftShift:
8068 case OpType.RightShift:
8070 case OpType.Equality:
8072 case OpType.Inequality:
8074 case OpType.GreaterThan:
8076 case OpType.LessThan:
8078 case OpType.GreaterThanOrEqual:
8080 case OpType.LessThanOrEqual:
8082 case OpType.Implicit:
8084 case OpType.Explicit:
8090 public override string GetSignatureForError (TypeContainer tc)
8092 StringBuilder sb = new StringBuilder ();
8093 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
8094 Parameters.FixedParameters [0].GetSignatureForError ());
8096 if (Parameters.FixedParameters.Length > 1) {
8098 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
8101 return sb.ToString ();
8104 public override string GetSignatureForError ()
8109 public override bool MarkForDuplicationCheck ()
8111 caching_flags |= Flags.TestMethodDuplication;
8115 public override string ToString ()
8117 if (OperatorMethod == null)
8120 Type return_type = OperatorMethod.ReturnType;
8121 Type [] param_types = OperatorMethod.ParameterTypes;
8123 if (Parameters.FixedParameters.Length == 1)
8124 return String.Format (
8125 "{0} operator {1}({2})",
8126 TypeManager.CSharpName (return_type),
8127 GetName (OperatorType),
8130 return String.Format (
8131 "{0} operator {1}({2}, {3})",
8132 TypeManager.CSharpName (return_type),
8133 GetName (OperatorType),
8134 param_types [0], param_types [1]);
8137 public override string[] ValidAttributeTargets {
8139 return attribute_targets;
8143 public void SetYields ()
8145 ModFlags |= Modifiers.METHOD_YIELDS;
8150 // This is used to compare method signatures
8152 struct MethodSignature {
8154 public Type RetType;
8155 public Type [] Parameters;
8158 /// This delegate is used to extract methods which have the
8159 /// same signature as the argument
8161 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8163 public MethodSignature (string name, Type ret_type, Type [] parameters)
8168 if (parameters == null)
8169 Parameters = TypeManager.NoTypes;
8171 Parameters = parameters;
8174 public override string ToString ()
8177 if (Parameters.Length != 0){
8178 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8179 for (int i = 0; i < Parameters.Length; i++){
8180 sb.Append (Parameters [i]);
8181 if (i+1 < Parameters.Length)
8184 pars = sb.ToString ();
8187 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8190 public override int GetHashCode ()
8192 return Name.GetHashCode ();
8195 public override bool Equals (Object o)
8197 MethodSignature other = (MethodSignature) o;
8199 if (other.Name != Name)
8202 if (other.RetType != RetType)
8205 if (Parameters == null){
8206 if (other.Parameters == null)
8211 if (other.Parameters == null)
8214 int c = Parameters.Length;
8215 if (other.Parameters.Length != c)
8218 for (int i = 0; i < c; i++)
8219 if (other.Parameters [i] != Parameters [i])
8225 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8227 MethodSignature sig = (MethodSignature) filter_criteria;
8229 if (m.Name != sig.Name)
8233 MethodInfo mi = m as MethodInfo;
8234 PropertyInfo pi = m as PropertyInfo;
8237 ReturnType = mi.ReturnType;
8238 else if (pi != null)
8239 ReturnType = pi.PropertyType;
8244 // we use sig.RetType == null to mean `do not check the
8245 // method return value.
8247 if (sig.RetType != null)
8248 if (ReturnType != sig.RetType)
8253 args = TypeManager.GetArgumentTypes (mi);
8255 args = TypeManager.GetArgumentTypes (pi);
8256 Type [] sigp = sig.Parameters;
8258 if (args.Length != sigp.Length)
8261 for (int i = args.Length; i > 0; ){
8263 if (args [i] != sigp [i])