2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@gnome.org)
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)
13 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
15 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
16 // have fixed a remaining problem: not every AddXXXX was adding a
17 // fully qualified name.
19 // Now everyone registers a fully qualified name in the DeclSpace as
20 // being defined instead of the partial name.
22 // Downsides: we are slower than we need to be due to the excess
23 // copies and the names being registered this way.
25 // The reason for this is that we currently depend (on the corlib
26 // bootstrap for instance) that types are fully qualified, because
27 // we dump all the types in the namespace, and we should really have
28 // types inserted into the proper namespace, so we can only store the
29 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
44 using Mono.CompilerServices.SymbolWriter;
46 namespace Mono.CSharp {
56 /// This is the base class for structs and classes.
58 public abstract class TypeContainer : DeclSpace, IMemberContainer {
60 public class MemberCoreArrayList: ArrayList
63 /// Defines the MemberCore objects that are in this array
65 public virtual void DefineContainerMembers ()
67 foreach (MemberCore mc in this) {
72 public virtual void Emit ()
74 foreach (MemberCore mc in this)
79 public class MethodArrayList: MemberCoreArrayList
87 CachedMethods cached_method;
88 TypeContainer container;
90 public MethodArrayList (TypeContainer container)
92 this.container = container;
96 /// Method container contains Equals method
98 public bool HasEquals {
100 cached_method |= CachedMethods.Equals;
104 return (cached_method & CachedMethods.Equals) != 0;
109 /// Method container contains GetHashCode method
111 public bool HasGetHashCode {
113 cached_method |= CachedMethods.GetHashCode;
117 return (cached_method & CachedMethods.GetHashCode) != 0;
121 public override void DefineContainerMembers ()
123 base.DefineContainerMembers ();
125 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
126 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
132 public sealed class IndexerArrayList: MemberCoreArrayList
135 /// The indexer name for this container
137 public string IndexerName = DefaultIndexerName;
139 bool seen_normal_indexers = false;
141 TypeContainer container;
143 public IndexerArrayList (TypeContainer container)
145 this.container = container;
149 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
150 /// class is consistent. Either it is `Item' or it is the name defined by all the
151 /// indexers with the `IndexerName' attribute.
153 /// Turns out that the IndexerNameAttribute is applied to each indexer,
154 /// but it is never emitted, instead a DefaultMember attribute is attached
157 public override void DefineContainerMembers()
159 base.DefineContainerMembers ();
161 string class_indexer_name = null;
164 // If there's both an explicit and an implicit interface implementation, the
165 // explicit one actually implements the interface while the other one is just
166 // a normal indexer. See bug #37714.
169 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
170 foreach (Indexer i in this) {
171 if (i.InterfaceType != null) {
172 if (seen_normal_indexers)
173 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
177 seen_normal_indexers = true;
179 if (class_indexer_name == null) {
180 class_indexer_name = i.ShortName;
184 if (i.ShortName != class_indexer_name)
185 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");
188 if (class_indexer_name != null)
189 IndexerName = class_indexer_name;
192 public override void Emit ()
196 if (!seen_normal_indexers)
199 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
200 container.TypeBuilder.SetCustomAttribute (cb);
204 public class OperatorArrayList: MemberCoreArrayList
206 TypeContainer container;
208 public OperatorArrayList (TypeContainer container)
210 this.container = container;
214 // Operator pair checking
219 public Type ret_type;
220 public Type type1, type2;
222 public Operator.OpType ot;
224 public OperatorEntry (int f, Operator o)
228 ret_type = o.OperatorMethod.ReturnType;
229 Type [] pt = o.OperatorMethod.ParameterTypes;
236 public override int GetHashCode ()
238 return ret_type.GetHashCode ();
241 public override bool Equals (object o)
243 OperatorEntry other = (OperatorEntry) o;
245 if (other.ret_type != ret_type)
247 if (other.type1 != type1)
249 if (other.type2 != type2)
256 // Checks that some operators come in pairs:
262 // They are matched based on the return type and the argument types
264 void CheckPairedOperators ()
266 Hashtable pairs = new Hashtable (null, null);
267 Operator true_op = null;
268 Operator false_op = null;
269 bool has_equality_or_inequality = false;
271 // Register all the operators we care about.
272 foreach (Operator op in this){
275 switch (op.OperatorType){
276 case Operator.OpType.Equality:
278 has_equality_or_inequality = true;
280 case Operator.OpType.Inequality:
282 has_equality_or_inequality = true;
285 case Operator.OpType.True:
288 case Operator.OpType.False:
292 case Operator.OpType.GreaterThan:
294 case Operator.OpType.LessThan:
297 case Operator.OpType.GreaterThanOrEqual:
299 case Operator.OpType.LessThanOrEqual:
305 OperatorEntry oe = new OperatorEntry (reg, op);
307 object o = pairs [oe];
311 oe = (OperatorEntry) o;
316 if (true_op != null){
317 if (false_op == null)
318 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
319 } else if (false_op != null)
320 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
323 // Look for the mistakes.
325 foreach (DictionaryEntry de in pairs){
326 OperatorEntry oe = (OperatorEntry) de.Key;
333 case Operator.OpType.Equality:
336 case Operator.OpType.Inequality:
339 case Operator.OpType.GreaterThan:
342 case Operator.OpType.LessThan:
345 case Operator.OpType.GreaterThanOrEqual:
348 case Operator.OpType.LessThanOrEqual:
352 Report.Error (216, oe.op.Location,
353 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
356 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
357 if (container.Methods == null || !container.Methods.HasEquals)
358 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
360 if (container.Methods == null || !container.Methods.HasGetHashCode)
361 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
365 public override void DefineContainerMembers ()
367 base.DefineContainerMembers ();
368 CheckPairedOperators ();
373 // Whether this is a struct, class or interface
374 public readonly Kind Kind;
376 // Holds a list of classes and structures
379 // Holds the list of properties
380 MemberCoreArrayList properties;
382 // Holds the list of enumerations
383 MemberCoreArrayList enums;
385 // Holds the list of delegates
386 MemberCoreArrayList delegates;
388 // Holds the list of constructors
389 protected MemberCoreArrayList instance_constructors;
391 // Holds the list of fields
392 MemberCoreArrayList fields;
394 // Holds a list of fields that have initializers
395 protected ArrayList initialized_fields;
397 // Holds a list of static fields that have initializers
398 protected ArrayList initialized_static_fields;
400 // Holds the list of constants
401 MemberCoreArrayList constants;
404 MemberCoreArrayList interfaces;
406 // Holds the methods.
407 MethodArrayList methods;
410 protected MemberCoreArrayList events;
412 // Holds the indexers
413 IndexerArrayList indexers;
415 // Holds the operators
416 MemberCoreArrayList operators;
418 // Holds the iterators
421 // Holds the parts of a partial class;
425 // Pointers to the default constructor and the default static constructor
427 protected Constructor default_constructor;
428 protected Constructor default_static_constructor;
431 // Whether we have at least one non-static field
433 bool have_nonstatic_fields = false;
436 // This one is computed after we can distinguish interfaces
437 // from classes from the arraylist `type_bases'
439 string base_class_name;
440 TypeExpr parent_type;
442 ArrayList type_bases;
444 bool members_defined;
445 bool members_defined_ok;
447 // The interfaces we implement.
448 protected Type[] ifaces;
449 protected Type ptype;
451 // The parent member cache and our member cache
452 MemberCache parent_cache;
453 MemberCache member_cache;
455 public const string DefaultIndexerName = "Item";
459 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
460 Attributes attrs, Kind kind, Location l)
461 : base (ns, parent, name, attrs, l)
465 types = new ArrayList ();
467 base_class_name = null;
470 public bool AddToMemberContainer (MemberCore symbol, bool is_method)
472 return AddToContainer (symbol, is_method, String.Concat (Name, '.', symbol.Name), symbol.Name);
475 bool AddToTypeContainer (DeclSpace ds)
477 return AddToContainer (ds, false, ds.Name, ds.Basename);
480 public void AddConstant (Const constant)
482 if (!AddToMemberContainer (constant, false))
485 if (constants == null)
486 constants = new MemberCoreArrayList ();
488 constants.Add (constant);
491 public void AddEnum (Mono.CSharp.Enum e)
493 if (!AddToTypeContainer (e))
497 enums = new MemberCoreArrayList ();
502 public void AddClassOrStruct (TypeContainer c)
504 if (!AddToTypeContainer (c))
510 public void AddDelegate (Delegate d)
512 if (!AddToTypeContainer (d))
515 if (delegates == null)
516 delegates = new MemberCoreArrayList ();
521 public void AddMethod (Method method)
523 if (!AddToMemberContainer (method, true))
527 methods = new MethodArrayList (this);
529 if (method.Name.IndexOf ('.') != -1)
530 methods.Insert (0, method);
532 methods.Add (method);
535 public void AddConstructor (Constructor c)
537 if (c.Name != Basename) {
538 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
541 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
544 if (default_static_constructor != null) {
545 Report.SymbolRelatedToPreviousError (default_static_constructor);
546 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
547 "called '{1}' with the same parameter types", Name, c.Name);
551 default_static_constructor = c;
554 if (default_constructor != null) {
555 Report.SymbolRelatedToPreviousError (default_constructor);
556 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
557 "called '{1}' with the same parameter types", Name, c.Name);
560 default_constructor = c;
563 if (instance_constructors == null)
564 instance_constructors = new MemberCoreArrayList ();
566 instance_constructors.Add (c);
570 public void AddInterface (TypeContainer iface)
572 if (!AddToTypeContainer (iface))
575 if (interfaces == null) {
576 interfaces = new MemberCoreArrayList ();
579 interfaces.Add (iface);
582 public void AddField (Field field)
584 if (!AddToMemberContainer (field, false))
588 fields = new MemberCoreArrayList ();
592 if (field.HasInitializer){
593 if ((field.ModFlags & Modifiers.STATIC) != 0){
594 if (initialized_static_fields == null)
595 initialized_static_fields = new ArrayList ();
597 initialized_static_fields.Add (field);
600 if (initialized_fields == null)
601 initialized_fields = new ArrayList ();
603 initialized_fields.Add (field);
607 if ((field.ModFlags & Modifiers.STATIC) == 0)
608 have_nonstatic_fields = true;
611 public void AddProperty (Property prop)
613 if (!AddToMemberContainer (prop, false) ||
614 !AddToMemberContainer (prop.Get, true) || !AddToMemberContainer (prop.Set, true))
617 if (properties == null)
618 properties = new MemberCoreArrayList ();
620 if (prop.Name.IndexOf ('.') != -1)
621 properties.Insert (0, prop);
623 properties.Add (prop);
626 public void AddEvent (Event e)
628 if (!AddToMemberContainer (e, false))
631 if (e is EventProperty) {
632 if (!AddToMemberContainer (e.Add, true))
635 if (!AddToMemberContainer (e.Remove, true))
640 events = new MemberCoreArrayList ();
646 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
648 public void AddIndexer (Indexer i)
650 if (indexers == null)
651 indexers = new IndexerArrayList (this);
653 if (i.IsExplicitImpl)
654 indexers.Insert (0, i);
659 public void AddOperator (Operator op)
661 if (!AddToMemberContainer (op, true))
664 if (operators == null)
665 operators = new OperatorArrayList (this);
670 public void AddIterator (Iterator i)
672 if (iterators == null)
673 iterators = new ArrayList ();
678 public void AddType (TypeContainer tc)
683 public void AddPart (ClassPart part)
686 parts = new ArrayList ();
691 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
693 if (a.Type == TypeManager.default_member_type) {
694 if (Indexers != null) {
695 Report.Error (646, a.Location,
696 "Cannot specify the DefaultMember attribute on" +
697 " a type containing an indexer");
702 base.ApplyAttributeBuilder (a, cb);
705 public override AttributeTargets AttributeTargets {
707 throw new NotSupportedException ();
711 public ArrayList Types {
717 public MethodArrayList Methods {
723 public ArrayList Constants {
729 public ArrayList Interfaces {
735 public ArrayList Iterators {
743 return base_class_name;
747 public ArrayList Bases {
757 public ArrayList Fields {
763 public ArrayList InstanceConstructors {
765 return instance_constructors;
769 public ArrayList Properties {
775 public ArrayList Events {
781 public ArrayList Enums {
787 public ArrayList Indexers {
793 public ArrayList Operators {
799 public ArrayList Delegates {
805 public ArrayList Parts {
811 public virtual TypeAttributes TypeAttr {
813 return Modifiers.TypeAttr (ModFlags, this);
817 public string IndexerName {
819 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
824 // Emits the instance field initializers
826 public bool EmitFieldInitializers (EmitContext ec)
829 Expression instance_expr;
832 fields = initialized_static_fields;
833 instance_expr = null;
835 fields = initialized_fields;
836 instance_expr = new This (Location.Null).Resolve (ec);
842 foreach (Field f in fields){
843 Expression e = f.GetInitializerExpression (ec);
847 Location l = f.Location;
848 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
849 fe.InstanceExpression = instance_expr;
850 fe.IsFieldInitializer = true;
852 ExpressionStatement a = new Assign (fe, e, l);
854 a = a.ResolveStatement (ec);
858 a.EmitStatement (ec);
865 // Defines the default constructors
867 protected void DefineDefaultConstructor (bool is_static)
871 // The default constructor is public
872 // If the class is abstract, the default constructor is protected
873 // The default static constructor is private
875 int mods = Modifiers.PUBLIC;
877 mods = Modifiers.STATIC | Modifiers.PRIVATE;
878 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
879 mods = Modifiers.PROTECTED;
881 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
882 new ConstructorBaseInitializer (
883 null, Parameters.EmptyReadOnlyParameters,
889 c.Block = new ToplevelBlock (null, Location);
894 /// The pending methods that need to be implemented
895 // (interfaces or abstract methods)
897 public PendingImplementation Pending;
899 public abstract void Register ();
901 public abstract PendingImplementation GetPendingImplementations ();
903 TypeExpr[] GetPartialBases (out TypeExpr parent, out bool error)
905 ArrayList ifaces = new ArrayList ();
908 Location parent_loc = Location.Null;
910 foreach (ClassPart part in parts) {
912 TypeExpr[] new_ifaces;
914 new_ifaces = part.GetClassBases (out new_parent, out error);
918 if ((parent != null) && (new_parent != null) &&
919 !parent.Equals (new_parent)) {
920 Report.Error (263, part.Location,
921 "Partial declarations of `{0}' must " +
922 "not specify different base classes",
925 if (!Location.IsNull (parent_loc))
926 Report.LocationOfPreviousError (parent_loc);
932 if ((parent == null) && (new_parent != null)) {
934 parent_loc = part.Location;
937 if (new_ifaces == null)
940 foreach (TypeExpr iface in new_ifaces) {
942 foreach (TypeExpr old_iface in ifaces) {
943 if (old_iface.Equals (iface)) {
956 TypeExpr[] retval = new TypeExpr [ifaces.Count];
957 ifaces.CopyTo (retval, 0);
961 TypeExpr[] GetNormalBases (out TypeExpr parent, out bool error)
965 int count = Bases.Count;
968 if (Kind == Kind.Class){
969 TypeExpr name = ResolveTypeExpr ((Expression) Bases [0], Location);
986 TypeExpr [] ifaces = new TypeExpr [count-start];
988 for (i = start, j = 0; i < count; i++, j++){
989 Expression name = (Expression) Bases [i];
990 TypeExpr resolved = ResolveTypeExpr (name, Location);
991 if (resolved == null) {
996 ifaces [j] = resolved;
1004 /// This function computes the Base class and also the
1005 /// list of interfaces that the class or struct @c implements.
1007 /// The return value is an array (might be null) of
1008 /// interfaces implemented (as Types).
1010 /// The @parent argument is set to the parent object or null
1011 /// if this is `System.Object'.
1013 TypeExpr [] GetClassBases (out TypeExpr parent, out bool error)
1022 ifaces = GetPartialBases (out parent, out error);
1023 else if (Bases == null){
1027 ifaces = GetNormalBases (out parent, out error);
1032 if ((parent != null) && (Kind == Kind.Class)){
1033 if (parent is TypeParameterExpr){
1035 689, parent.Location,
1036 "Type parameter `{0}' can not be used as a " +
1037 "base class or interface", parent.Name);
1042 if (IsGeneric && parent.IsAttribute){
1044 698, parent.Location,
1045 "A generic type cannot derive from `{0}' " +
1046 "because it is an attribute class",
1052 if (parent.IsSealed){
1054 Report.SymbolRelatedToPreviousError (parent.Type);
1055 if (parent.Type.IsAbstract) {
1056 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1058 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1063 if (!parent.CanInheritFrom ()){
1064 Report.Error (644, Location,
1065 "`{0}' cannot inherit from special class `{1}'",
1066 Name, parent_type.Name);
1071 if (!parent.AsAccessible (this, ModFlags))
1072 Report.Error (60, Location,
1073 "Inconsistent accessibility: base class `" +
1074 parent.Name + "' is less accessible than class `" +
1079 base_class_name = parent.Name;
1084 int count = ifaces != null ? ifaces.Length : 0;
1086 for (i = 0; i < count; i++) {
1087 TypeExpr iface = (TypeExpr) ifaces [i];
1089 if ((Kind != Kind.Class) && !iface.IsInterface){
1090 string what = Kind == Kind.Struct ?
1091 "Struct" : "Interface";
1093 Report.Error (527, Location,
1094 "In {0} `{1}', type `{2}' is not "+
1095 "an interface", what, Name, iface.Name);
1100 if (iface.IsClass) {
1101 if (parent != null){
1102 Report.Error (527, Location,
1103 "In Class `{0}', `{1}' is not " +
1104 "an interface", Name, iface.Name);
1110 for (int x = 0; x < i; x++) {
1111 if (iface.Equals (ifaces [x])) {
1112 Report.Error (528, Location,
1113 "`{0}' is already listed in " +
1114 "interface list", iface.Name);
1120 if ((Kind == Kind.Interface) &&
1121 !iface.AsAccessible (Parent, ModFlags))
1122 Report.Error (61, Location,
1123 "Inconsistent accessibility: base " +
1124 "interface `{0}' is less accessible " +
1125 "than interface `{1}'", iface.Name,
1132 bool CheckGenericInterfaces (Type[] ifaces)
1134 ArrayList already_checked = new ArrayList ();
1136 for (int i = 0; i < ifaces.Length; i++) {
1137 Type iface = ifaces [i];
1138 foreach (Type t in already_checked) {
1142 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t))
1147 "`{0}' cannot implement both `{1}' and `{2}' " +
1148 "because they may unify for some type " +
1149 "parameter substitutions",
1150 TypeManager.GetFullName (TypeBuilder),
1155 already_checked.Add (iface);
1164 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1166 public override TypeBuilder DefineType ()
1173 if (TypeBuilder != null)
1176 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1178 TypeAttributes type_attributes = TypeAttr;
1182 if (TypeManager.NamespaceClash (Name, Location)) {
1187 ModuleBuilder builder = CodeGen.Module.Builder;
1188 TypeBuilder = builder.DefineType (
1189 Name, type_attributes, null, null);
1191 TypeBuilder builder;
1192 if (Parent.TypeBuilder != null)
1193 builder = Parent.TypeBuilder;
1195 builder = Parent.DefineType ();
1197 if (builder == null) {
1202 TypeBuilder = builder.DefineNestedType (
1203 MemberName.Basename, type_attributes,
1207 catch (ArgumentException) {
1208 Report.RuntimeMissingSupport (Location, "static classes");
1212 TypeManager.AddUserType (Name, TypeBuilder, this);
1214 TypeExpr current_type = null;
1217 string[] param_names = new string [TypeParameters.Length];
1218 for (int i = 0; i < TypeParameters.Length; i++)
1219 param_names [i] = TypeParameters [i].Name;
1221 GenericTypeParameterBuilder[] gen_params;
1222 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1224 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1225 for (int i = offset; i < gen_params.Length; i++)
1226 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1228 foreach (TypeParameter type_param in CurrentTypeParameters) {
1229 if (!type_param.Resolve (this)) {
1235 for (int i = offset; i < gen_params.Length; i++)
1236 CurrentTypeParameters [i - offset].DefineConstraints ();
1238 current_type = new ConstructedType (Name, TypeParameters, Location);
1242 foreach (TypeParameter type_param in TypeParameters)
1243 if (!type_param.DefineType (ec)) {
1249 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1250 throw new Exception ();
1252 TypeExpr[] iface_exprs = GetClassBases (out parent_type, out error);
1256 if (parent_type == null) {
1257 if (Kind == Kind.Class){
1258 if (RootContext.StdLib)
1259 parent_type = TypeManager.system_object_expr;
1260 else if (Name != "System.Object")
1261 parent_type = TypeManager.system_object_expr;
1262 } else if (Kind == Kind.Struct){
1264 // If we are compiling our runtime,
1265 // and we are defining ValueType, then our
1266 // parent is `System.Object'.
1268 if (!RootContext.StdLib && Name == "System.ValueType")
1269 parent_type = TypeManager.system_object_expr;
1270 else if (Kind == Kind.Struct)
1271 parent_type = TypeManager.system_valuetype_expr;
1275 if (parent_type != null) {
1276 parent_type = parent_type.ResolveAsTypeTerminal (ec);
1277 if (parent_type == null) {
1282 ptype = parent_type.Type;
1285 if (!CheckRecursiveDefinition ()) {
1291 TypeBuilder.SetParent (ptype);
1294 // Structs with no fields need to have at least one byte.
1295 // The right thing would be to set the PackingSize in a DefineType
1296 // but there are no functions that allow interfaces *and* the size to
1300 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1301 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1302 FieldAttributes.Private);
1305 // add interfaces that were not added at type creation
1306 if (iface_exprs != null) {
1307 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1308 if (ifaces == null) {
1313 foreach (Type itype in ifaces)
1314 TypeBuilder.AddInterfaceImplementation (itype);
1316 if (!CheckGenericInterfaces (ifaces)) {
1321 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1325 foreach (TypeParameter type_param in TypeParameters)
1326 if (!type_param.CheckDependencies (ec)) {
1332 if (current_type != null) {
1333 current_type = current_type.ResolveAsTypeTerminal (ec);
1334 if (current_type == null) {
1339 CurrentType = current_type.Type;
1343 // Finish the setup for the EmitContext
1345 ec.ContainerType = TypeBuilder;
1347 if ((parent_type != null) && parent_type.IsAttribute) {
1348 RootContext.RegisterAttribute (this);
1349 } else if (!(this is Iterator))
1350 RootContext.RegisterOrder (this);
1352 if (!DefineNestedTypes ()) {
1360 protected virtual bool DefineNestedTypes ()
1362 if (Interfaces != null) {
1363 foreach (TypeContainer iface in Interfaces)
1364 if (iface.DefineType () == null)
1368 if (Types != null) {
1369 foreach (TypeContainer tc in Types)
1370 if (tc.DefineType () == null)
1374 if (Delegates != null) {
1375 foreach (Delegate d in Delegates)
1376 if (d.DefineType () == null)
1380 if (Enums != null) {
1381 foreach (Enum en in Enums)
1382 if (en.DefineType () == null)
1386 if (Parts != null) {
1387 foreach (ClassPart part in Parts) {
1388 part.TypeBuilder = TypeBuilder;
1389 part.parent_type = parent_type;
1390 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1397 protected bool CheckRecursiveDefinition ()
1400 Report.Error (146, Location,
1401 "Class definition is circular: `{0}'",
1402 GetSignatureForError ());
1409 Type parent = ptype;
1410 if (parent != null) {
1411 if (parent.IsGenericInstance)
1412 parent = parent.GetGenericTypeDefinition ();
1414 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1415 if ((ptc != null) && !ptc.CheckRecursiveDefinition ())
1423 static void Error_KeywordNotAllowed (Location loc)
1425 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1429 /// Populates our TypeBuilder with fields and methods
1431 public override bool DefineMembers (TypeContainer container)
1433 if (members_defined)
1434 return members_defined_ok;
1436 members_defined_ok = DoDefineMembers ();
1437 members_defined = true;
1439 return members_defined_ok;
1442 protected virtual bool DoDefineMembers ()
1445 // We need to be able to use the member cache while we are checking/defining
1447 if (TypeBuilder.BaseType != null)
1448 parent_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
1450 if (TypeBuilder.IsInterface)
1451 parent_cache = TypeManager.LookupParentInterfacesCache (TypeBuilder);
1454 if ((ModFlags & Modifiers.NEW) != 0)
1455 Error_KeywordNotAllowed (Location);
1457 // HACK: missing implemenation
1458 // This is not fully functional. Better way how to handle this is to have recursive definition of containers
1459 // instead of flat as we have now.
1460 // Now we are not able to check inner attribute class because its parent had not been defined.
1462 // TODO: remove this if
1463 if (Parent.MemberCache != null) {
1464 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1465 if (conflict_symbol == null) {
1466 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1467 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1469 if ((ModFlags & Modifiers.NEW) == 0) {
1470 Report.SymbolRelatedToPreviousError (conflict_symbol);
1471 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1477 DefineContainerMembers (constants);
1478 DefineContainerMembers (fields);
1480 if ((Kind == Kind.Class) && !(this is ClassPart) && !(this is StaticClass)){
1481 if ((instance_constructors == null) &&
1482 !(this is StaticClass)) {
1483 if (default_constructor == null)
1484 DefineDefaultConstructor (false);
1487 if (initialized_static_fields != null &&
1488 default_static_constructor == null)
1489 DefineDefaultConstructor (true);
1492 if (Kind == Kind.Struct){
1494 // Structs can not have initialized instance
1497 if (initialized_static_fields != null &&
1498 default_static_constructor == null)
1499 DefineDefaultConstructor (true);
1501 if (initialized_fields != null)
1502 ReportStructInitializedInstanceError ();
1505 Pending = GetPendingImplementations ();
1507 if (parts != null) {
1508 foreach (ClassPart part in parts) {
1509 if (!part.DefineMembers (this))
1515 // Constructors are not in the defined_names array
1517 DefineContainerMembers (instance_constructors);
1519 if (default_static_constructor != null)
1520 default_static_constructor.Define ();
1522 DefineContainerMembers (properties);
1523 DefineContainerMembers (events);
1524 DefineContainerMembers (indexers);
1525 DefineContainerMembers (methods);
1526 DefineContainerMembers (operators);
1527 DefineContainerMembers (enums);
1528 DefineContainerMembers (delegates);
1530 if (CurrentType != null) {
1531 GenericType = CurrentType;
1533 ec.ContainerType = GenericType;
1538 if (!(this is ClassPart))
1539 member_cache = new MemberCache (this);
1542 if (parts != null) {
1543 foreach (ClassPart part in parts)
1544 part.member_cache = member_cache;
1547 if (iterators != null) {
1548 foreach (Iterator iterator in iterators) {
1549 if (iterator.DefineType () == null)
1553 foreach (Iterator iterator in iterators) {
1554 if (!iterator.DefineMembers (this))
1562 void ReportStructInitializedInstanceError ()
1564 string n = TypeBuilder.FullName;
1566 foreach (Field f in initialized_fields){
1569 "`" + n + "." + f.Name + "': can not have " +
1570 "instance field initializers in structs");
1574 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1577 mcal.DefineContainerMembers ();
1580 public override bool Define ()
1582 if (parts != null) {
1583 foreach (ClassPart part in parts) {
1584 if (!part.Define ())
1592 public MemberInfo FindMemberWithSameName (string name, bool ignore_methods)
1594 return ParentCache.FindMemberWithSameName (name, ignore_methods, null);
1598 /// This function is based by a delegate to the FindMembers routine
1600 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1606 /// This filter is used by FindMembers, and we just keep
1607 /// a global for the filter to `AlwaysAccept'
1609 static MemberFilter accepting_filter;
1612 static TypeContainer ()
1614 accepting_filter = new MemberFilter (AlwaysAccept);
1617 public MethodInfo[] GetMethods ()
1619 ArrayList members = new ArrayList ();
1621 DefineMembers (null);
1623 if (methods != null) {
1624 int len = methods.Count;
1625 for (int i = 0; i < len; i++) {
1626 Method m = (Method) methods [i];
1628 members.Add (m.MethodBuilder);
1632 if (operators != null) {
1633 int len = operators.Count;
1634 for (int i = 0; i < len; i++) {
1635 Operator o = (Operator) operators [i];
1637 members.Add (o.OperatorMethodBuilder);
1641 if (properties != null) {
1642 int len = properties.Count;
1643 for (int i = 0; i < len; i++) {
1644 Property p = (Property) properties [i];
1646 if (p.GetBuilder != null)
1647 members.Add (p.GetBuilder);
1648 if (p.SetBuilder != null)
1649 members.Add (p.SetBuilder);
1653 if (indexers != null) {
1654 int len = indexers.Count;
1655 for (int i = 0; i < len; i++) {
1656 Indexer ix = (Indexer) indexers [i];
1658 if (ix.GetBuilder != null)
1659 members.Add (ix.GetBuilder);
1660 if (ix.SetBuilder != null)
1661 members.Add (ix.SetBuilder);
1665 if (events != null) {
1666 int len = events.Count;
1667 for (int i = 0; i < len; i++) {
1668 Event e = (Event) events [i];
1670 if (e.AddBuilder != null)
1671 members.Add (e.AddBuilder);
1672 if (e.RemoveBuilder != null)
1673 members.Add (e.RemoveBuilder);
1677 MethodInfo[] retMethods = new MethodInfo [members.Count];
1678 members.CopyTo (retMethods, 0);
1682 // Indicated whether container has StructLayout attribute set Explicit
1683 public virtual bool HasExplicitLayout {
1690 /// This method returns the members of this type just like Type.FindMembers would
1691 /// Only, we need to use this for types which are _being_ defined because MS'
1692 /// implementation can't take care of that.
1695 // FIXME: return an empty static array instead of null, that cleans up
1696 // some code and is consistent with some coding conventions I just found
1700 // Notice that in various cases we check if our field is non-null,
1701 // something that would normally mean that there was a bug elsewhere.
1703 // The problem happens while we are defining p-invoke methods, as those
1704 // will trigger a FindMembers, but this happens before things are defined
1706 // Since the whole process is a no-op, it is fine to check for null here.
1708 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1709 MemberFilter filter, object criteria)
1711 ArrayList members = null;
1714 if ((bf & BindingFlags.Public) != 0)
1715 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1717 if ((bf & BindingFlags.NonPublic) != 0)
1718 modflags |= Modifiers.PRIVATE;
1720 int static_mask = 0, static_flags = 0;
1721 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1722 case BindingFlags.Static:
1723 static_mask = static_flags = Modifiers.STATIC;
1726 case BindingFlags.Instance:
1727 static_mask = Modifiers.STATIC;
1732 static_mask = static_flags = 0;
1736 Timer.StartTimer (TimerType.TcFindMembers);
1739 filter = accepting_filter;
1741 if ((mt & MemberTypes.Field) != 0) {
1742 if (fields != null) {
1743 int len = fields.Count;
1744 for (int i = 0; i < len; i++) {
1745 Field f = (Field) fields [i];
1747 if ((f.ModFlags & modflags) == 0)
1749 if ((f.ModFlags & static_mask) != static_flags)
1752 FieldBuilder fb = f.FieldBuilder;
1753 if (fb != null && filter (fb, criteria) == true) {
1754 if (members == null)
1755 members = new ArrayList ();
1762 if (constants != null) {
1763 int len = constants.Count;
1764 for (int i = 0; i < len; i++) {
1765 Const con = (Const) constants [i];
1767 if ((con.ModFlags & modflags) == 0)
1769 if ((con.ModFlags & static_mask) != static_flags)
1772 FieldBuilder fb = con.FieldBuilder;
1773 if (fb != null && filter (fb, criteria) == true) {
1774 if (members == null)
1775 members = new ArrayList ();
1783 if ((mt & MemberTypes.Method) != 0) {
1784 if (methods != null) {
1785 int len = methods.Count;
1786 for (int i = 0; i < len; i++) {
1787 Method m = (Method) methods [i];
1789 if ((m.ModFlags & modflags) == 0)
1791 if ((m.ModFlags & static_mask) != static_flags)
1794 MethodBuilder mb = m.MethodBuilder;
1796 if (mb != null && filter (mb, criteria) == true) {
1797 if (members == null)
1798 members = new ArrayList ();
1805 if (operators != null) {
1806 int len = operators.Count;
1807 for (int i = 0; i < len; i++) {
1808 Operator o = (Operator) operators [i];
1810 if ((o.ModFlags & modflags) == 0)
1812 if ((o.ModFlags & static_mask) != static_flags)
1815 MethodBuilder ob = o.OperatorMethodBuilder;
1816 if (ob != null && filter (ob, criteria) == true) {
1817 if (members == null)
1818 members = new ArrayList ();
1825 if (properties != null) {
1826 int len = properties.Count;
1827 for (int i = 0; i < len; i++) {
1828 Property p = (Property) properties [i];
1830 if ((p.ModFlags & modflags) == 0)
1832 if ((p.ModFlags & static_mask) != static_flags)
1838 if (b != null && filter (b, criteria) == true) {
1839 if (members == null)
1840 members = new ArrayList ();
1846 if (b != null && filter (b, criteria) == true) {
1847 if (members == null)
1848 members = new ArrayList ();
1855 if (indexers != null) {
1856 int len = indexers.Count;
1857 for (int i = 0; i < len; i++) {
1858 Indexer ix = (Indexer) indexers [i];
1860 if ((ix.ModFlags & modflags) == 0)
1862 if ((ix.ModFlags & static_mask) != static_flags)
1868 if (b != null && filter (b, criteria) == true) {
1869 if (members == null)
1870 members = new ArrayList ();
1876 if (b != null && filter (b, criteria) == true) {
1877 if (members == null)
1878 members = new ArrayList ();
1886 if ((mt & MemberTypes.Event) != 0) {
1887 if (events != null) {
1888 int len = events.Count;
1889 for (int i = 0; i < len; i++) {
1890 Event e = (Event) events [i];
1892 if ((e.ModFlags & modflags) == 0)
1894 if ((e.ModFlags & static_mask) != static_flags)
1897 MemberInfo eb = e.EventBuilder;
1898 if (eb != null && filter (eb, criteria) == true) {
1899 if (members == null)
1900 members = new ArrayList ();
1902 members.Add (e.EventBuilder);
1908 if ((mt & MemberTypes.Property) != 0){
1909 if (properties != null) {
1910 int len = properties.Count;
1911 for (int i = 0; i < len; i++) {
1912 Property p = (Property) properties [i];
1914 if ((p.ModFlags & modflags) == 0)
1916 if ((p.ModFlags & static_mask) != static_flags)
1919 MemberInfo pb = p.PropertyBuilder;
1920 if (pb != null && filter (pb, criteria) == true) {
1921 if (members == null)
1922 members = new ArrayList ();
1924 members.Add (p.PropertyBuilder);
1929 if (indexers != null) {
1930 int len = indexers.Count;
1931 for (int i = 0; i < len; i++) {
1932 Indexer ix = (Indexer) indexers [i];
1934 if ((ix.ModFlags & modflags) == 0)
1936 if ((ix.ModFlags & static_mask) != static_flags)
1939 MemberInfo ib = ix.PropertyBuilder;
1940 if (ib != null && filter (ib, criteria) == true) {
1941 if (members == null)
1942 members = new ArrayList ();
1944 members.Add (ix.PropertyBuilder);
1950 if ((mt & MemberTypes.NestedType) != 0) {
1951 if (types != null) {
1952 int len = types.Count;
1953 for (int i = 0; i < len; i++) {
1954 TypeContainer t = (TypeContainer) types [i];
1956 if ((t.ModFlags & modflags) == 0)
1959 TypeBuilder tb = t.TypeBuilder;
1960 if (tb != null && (filter (tb, criteria) == true)) {
1961 if (members == null)
1962 members = new ArrayList ();
1969 if (enums != null) {
1970 int len = enums.Count;
1971 for (int i = 0; i < len; i++) {
1972 Enum en = (Enum) enums [i];
1974 if ((en.ModFlags & modflags) == 0)
1977 TypeBuilder tb = en.TypeBuilder;
1978 if (tb != null && (filter (tb, criteria) == true)) {
1979 if (members == null)
1980 members = new ArrayList ();
1987 if (delegates != null) {
1988 int len = delegates.Count;
1989 for (int i = 0; i < len; i++) {
1990 Delegate d = (Delegate) delegates [i];
1992 if ((d.ModFlags & modflags) == 0)
1995 TypeBuilder tb = d.TypeBuilder;
1996 if (tb != null && (filter (tb, criteria) == true)) {
1997 if (members == null)
1998 members = new ArrayList ();
2005 if (interfaces != null) {
2006 int len = interfaces.Count;
2007 for (int i = 0; i < len; i++) {
2008 TypeContainer iface = (TypeContainer) interfaces [i];
2010 if ((iface.ModFlags & modflags) == 0)
2013 TypeBuilder tb = iface.TypeBuilder;
2014 if (tb != null && (filter (tb, criteria) == true)) {
2015 if (members == null)
2016 members = new ArrayList ();
2024 if ((mt & MemberTypes.Constructor) != 0){
2025 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2026 int len = instance_constructors.Count;
2027 for (int i = 0; i < len; i++) {
2028 Constructor c = (Constructor) instance_constructors [i];
2030 ConstructorBuilder cb = c.ConstructorBuilder;
2031 if (cb != null && filter (cb, criteria) == true) {
2032 if (members == null)
2033 members = new ArrayList ();
2040 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2041 ConstructorBuilder cb =
2042 default_static_constructor.ConstructorBuilder;
2044 if (cb != null && filter (cb, criteria) == true) {
2045 if (members == null)
2046 members = new ArrayList ();
2054 // Lookup members in parent if requested.
2056 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2057 if (TypeBuilder.BaseType != null) {
2058 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2059 if (list.Count > 0) {
2060 if (members == null)
2061 members = new ArrayList ();
2063 members.AddRange (list);
2069 Timer.StopTimer (TimerType.TcFindMembers);
2071 if (members == null)
2072 return MemberList.Empty;
2074 return new MemberList (members);
2077 public override MemberCache MemberCache {
2079 return member_cache;
2083 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2084 MemberFilter filter, object criteria)
2086 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2089 return ds.FindMembers (mt, bf, filter, criteria);
2091 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2095 // FindMethods will look for methods not only in the type `t', but in
2096 // any interfaces implemented by the type.
2098 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2099 MemberFilter filter, object criteria)
2105 /// Emits the values for the constants
2107 public void EmitConstants ()
2109 if (constants != null)
2110 foreach (Const con in constants)
2115 protected virtual void VerifyMembers (EmitContext ec)
2118 // Check for internal or private fields that were never assigned
2120 if (RootContext.WarningLevel >= 3) {
2121 if (fields != null){
2122 foreach (Field f in fields) {
2123 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2126 if ((f.status & Field.Status.USED) == 0){
2127 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2132 // Only report 649 on level 4
2134 if (RootContext.WarningLevel < 4)
2137 if ((f.status & Field.Status.ASSIGNED) != 0)
2140 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2147 /// Emits the code, this step is performed after all
2148 /// the types, enumerations, constructors
2150 public void EmitType ()
2152 if (OptAttributes != null)
2153 OptAttributes.Emit (ec, this);
2157 if (instance_constructors != null) {
2158 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2159 bool has_compliant_args = false;
2161 foreach (Constructor c in instance_constructors) {
2164 if (has_compliant_args)
2167 has_compliant_args = c.HasCompliantArgs;
2169 if (!has_compliant_args)
2170 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2172 foreach (Constructor c in instance_constructors)
2179 if (default_static_constructor != null)
2180 default_static_constructor.Emit ();
2182 if (methods != null)
2183 foreach (Method m in methods)
2186 if (operators != null)
2187 foreach (Operator o in operators)
2190 if (properties != null)
2191 foreach (Property p in properties)
2194 if (indexers != null){
2199 foreach (Field f in fields)
2202 if (events != null){
2203 foreach (Event e in Events)
2207 if (delegates != null) {
2208 foreach (Delegate d in Delegates) {
2213 if (enums != null) {
2214 foreach (Enum e in enums) {
2219 if (parts != null) {
2220 foreach (ClassPart part in parts)
2224 if ((Pending != null) && !(this is ClassPart))
2225 if (Pending.VerifyPendingMethods ())
2230 if (iterators != null)
2231 foreach (Iterator iterator in iterators)
2232 iterator.EmitType ();
2234 // if (types != null)
2235 // foreach (TypeContainer tc in types)
2239 public override void CloseType ()
2241 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2245 caching_flags |= Flags.CloseTypeCreated;
2246 TypeBuilder.CreateType ();
2247 } catch (TypeLoadException){
2249 // This is fine, the code still created the type
2251 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2252 // Console.WriteLine (e.Message);
2254 Console.WriteLine ("In type: " + Name);
2259 foreach (Enum en in Enums)
2263 foreach (TypeContainer tc in Types)
2264 if (tc.Kind == Kind.Struct)
2267 foreach (TypeContainer tc in Types)
2268 if (tc.Kind != Kind.Struct)
2272 if (Delegates != null)
2273 foreach (Delegate d in Delegates)
2276 if (Iterators != null)
2277 foreach (Iterator i in Iterators)
2285 initialized_fields = null;
2286 initialized_static_fields = null;
2295 default_constructor = null;
2296 default_static_constructor = null;
2298 OptAttributes = null;
2300 parent_cache = null;
2301 member_cache = null;
2304 // TODO: make it obsolete and use GetSignatureForError
2305 public string MakeName (string n)
2307 return "`" + Name + "." + n + "'";
2311 // Performs the validation on a Method's modifiers (properties have
2312 // the same properties).
2314 public bool MethodModifiersValid (int flags, string n, Location loc)
2316 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2317 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2318 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2322 // At most one of static, virtual or override
2324 if ((flags & Modifiers.STATIC) != 0){
2325 if ((flags & vao) != 0){
2327 112, loc, "static method " + MakeName (n) + "can not be marked " +
2328 "as virtual, abstract or override");
2333 if (Kind == Kind.Struct){
2334 if ((flags & va) != 0){
2335 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
2340 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2342 113, loc, MakeName (n) +
2343 " marked as override cannot be marked as new or virtual");
2348 // If the declaration includes the abstract modifier, then the
2349 // declaration does not include static, virtual or extern
2351 if ((flags & Modifiers.ABSTRACT) != 0){
2352 if ((flags & Modifiers.EXTERN) != 0){
2354 180, loc, MakeName (n) + " can not be both abstract and extern");
2358 if ((flags & Modifiers.VIRTUAL) != 0){
2360 503, loc, MakeName (n) + " can not be both abstract and virtual");
2364 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2366 513, loc, MakeName (n) +
2367 " is abstract but its container class is not");
2373 if ((flags & Modifiers.PRIVATE) != 0){
2374 if ((flags & vao) != 0){
2376 621, loc, MakeName (n) +
2377 " virtual or abstract members can not be private");
2382 if ((flags & Modifiers.SEALED) != 0){
2383 if ((flags & Modifiers.OVERRIDE) == 0){
2385 238, loc, MakeName (n) +
2386 " cannot be sealed because it is not an override");
2394 public bool UserDefinedStaticConstructor {
2396 return default_static_constructor != null;
2400 protected override bool VerifyClsCompliance (DeclSpace ds)
2402 if (!base.VerifyClsCompliance (ds))
2407 Type base_type = TypeBuilder.BaseType;
2408 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2409 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2416 /// Checks whether container name is CLS Compliant
2418 void VerifyClsName ()
2420 Hashtable parent_members = parent_cache == null ?
2422 parent_cache.GetPublicMembers ();
2423 Hashtable this_members = new Hashtable ();
2425 foreach (DictionaryEntry entry in defined_names) {
2426 MemberCore mc = (MemberCore)entry.Value;
2427 if (!mc.IsClsCompliaceRequired (this))
2430 string name = (string)entry.Key;
2431 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2433 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2434 object found = parent_members [lcase];
2435 if (found == null) {
2436 found = this_members [lcase];
2437 if (found == null) {
2438 this_members.Add (lcase, mc);
2443 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2446 if (found is MemberInfo) {
2447 if (basename == ((MemberInfo)found).Name)
2449 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2451 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2453 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2459 /// Performs checks for an explicit interface implementation. First it
2460 /// checks whether the `interface_type' is a base inteface implementation.
2461 /// Then it checks whether `name' exists in the interface type.
2463 public virtual bool VerifyImplements (Type interface_type, string full,
2464 string name, Location loc)
2468 if (ifaces != null){
2469 foreach (Type t in ifaces){
2470 if (t == interface_type){
2478 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
2485 protected override void VerifyObsoleteAttribute()
2487 CheckUsageOfObsoleteAttribute (TypeBuilder.BaseType);
2492 foreach (Type iface in ifaces) {
2493 CheckUsageOfObsoleteAttribute (iface);
2501 string IMemberContainer.Name {
2507 Type IMemberContainer.Type {
2513 MemberCache IMemberContainer.MemberCache {
2515 return member_cache;
2519 bool IMemberContainer.IsInterface {
2521 return Kind == Kind.Interface;
2525 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2527 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2529 if (GenericType != null)
2530 return TypeManager.FindMembers (GenericType, mt, new_bf,
2533 return FindMembers (mt, new_bf, null, null);
2536 public virtual MemberCache ParentCache {
2538 return parent_cache;
2544 public class PartialContainer : TypeContainer {
2546 public readonly Namespace Namespace;
2547 public readonly int OriginalModFlags;
2548 public readonly int AllowedModifiers;
2549 public readonly TypeAttributes DefaultTypeAttributes;
2551 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2552 MemberName name, int mod_flags, Kind kind,
2555 PartialContainer pc;
2556 string full_name = name.GetName (true);
2557 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2559 pc = ds as PartialContainer;
2563 260, ds.Location, "Missing partial modifier " +
2564 "on declaration of type `{0}'; another " +
2565 "partial implementation of this type exists",
2568 Report.LocationOfPreviousError (loc);
2572 if (pc.Kind != kind) {
2574 261, loc, "Partial declarations of `{0}' " +
2575 "must be all classes, all structs or " +
2576 "all interfaces", name);
2580 if (pc.OriginalModFlags != mod_flags) {
2582 262, loc, "Partial declarations of `{0}' " +
2583 "have conflicting accessibility modifiers",
2591 pc = new PartialContainer (ns, parent, name, mod_flags, kind, loc);
2592 RootContext.Tree.RecordDecl (full_name, pc);
2593 parent.AddType (pc);
2598 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2599 MemberName name, int mod, Attributes attrs,
2600 Kind kind, Location loc)
2602 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2604 // An error occured; create a dummy container, but don't
2606 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2609 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2614 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2615 MemberName name, int mod, Kind kind, Location l)
2616 : base (ns, parent, name, null, kind, l)
2618 this.Namespace = ns.NS;
2622 AllowedModifiers = Class.AllowedModifiers;
2623 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2627 AllowedModifiers = Struct.AllowedModifiers;
2628 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2631 case Kind.Interface:
2632 AllowedModifiers = Interface.AllowedModifiers;
2633 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2637 throw new InvalidOperationException ();
2641 if (parent.Parent == null)
2642 accmods = Modifiers.INTERNAL;
2644 accmods = Modifiers.PRIVATE;
2646 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2647 this.OriginalModFlags = mod;
2650 public override void Register ()
2652 if (Kind == Kind.Interface)
2653 Parent.AddInterface (this);
2654 else if (Kind == Kind.Class || Kind == Kind.Struct)
2655 Parent.AddClassOrStruct (this);
2657 throw new InvalidOperationException ();
2660 public override PendingImplementation GetPendingImplementations ()
2662 return PendingImplementation.GetPendingImplementations (this);
2665 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2668 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2673 public override TypeAttributes TypeAttr {
2675 return base.TypeAttr | DefaultTypeAttributes;
2680 public class ClassPart : TypeContainer, IMemberContainer {
2681 public readonly PartialContainer PartialContainer;
2682 public readonly bool IsPartial;
2684 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2685 int mod, Attributes attrs, Kind kind, Location l)
2686 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2688 this.PartialContainer = parent;
2689 this.IsPartial = true;
2692 if (parent.Parent == null)
2693 accmods = Modifiers.INTERNAL;
2695 accmods = Modifiers.PRIVATE;
2697 this.ModFlags = Modifiers.Check (
2698 parent.AllowedModifiers, mod, accmods, l);
2701 public override void Register ()
2705 public override PendingImplementation GetPendingImplementations ()
2707 return PartialContainer.Pending;
2710 public override bool VerifyImplements (Type interface_type, string full,
2711 string name, Location loc)
2713 return PartialContainer.VerifyImplements (
2714 interface_type, full, name, loc);
2717 public override MemberCache ParentCache {
2719 return PartialContainer.ParentCache;
2724 public abstract class ClassOrStruct : TypeContainer {
2725 bool hasExplicitLayout = false;
2726 ListDictionary declarative_security;
2728 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2729 MemberName name, Attributes attrs, Kind kind,
2731 : base (ns, parent, name, attrs, kind, l)
2735 public override PendingImplementation GetPendingImplementations ()
2737 return PendingImplementation.GetPendingImplementations (this);
2740 public override bool HasExplicitLayout {
2742 return hasExplicitLayout;
2746 protected override void VerifyMembers (EmitContext ec)
2748 base.VerifyMembers (ec);
2750 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2751 foreach (Event e in events){
2753 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2758 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2760 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2761 if (declarative_security == null)
2762 declarative_security = new ListDictionary ();
2764 a.ExtractSecurityPermissionSet (declarative_security);
2768 if (a.Type == TypeManager.struct_layout_attribute_type
2769 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2770 hasExplicitLayout = true;
2772 base.ApplyAttributeBuilder (a, cb);
2775 public override void Emit()
2779 if (declarative_security != null) {
2780 foreach (DictionaryEntry de in declarative_security) {
2781 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2786 public override void Register ()
2788 Parent.AddClassOrStruct (this);
2793 /// Class handles static classes declaration
2795 public sealed class StaticClass: Class {
2796 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2797 Attributes attrs, Location l)
2798 : base (ns, parent, name, mod & ~Modifiers.STATIC, attrs, l)
2800 if (RootContext.Version == LanguageVersion.ISO_1) {
2801 Report.FeatureIsNotStandardized (l, "static classes");
2802 Environment.Exit (1);
2806 protected override void DefineContainerMembers (MemberCoreArrayList list)
2811 foreach (MemberCore m in list) {
2812 if (m is Operator) {
2813 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2817 if ((m.ModFlags & Modifiers.STATIC) != 0)
2820 if (m is Constructor) {
2821 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2825 if (m is Destructor) {
2826 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2829 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2832 base.DefineContainerMembers (list);
2835 public override TypeBuilder DefineType()
2837 TypeBuilder tb = base.DefineType ();
2841 if ((ptype != null) && (ptype != TypeManager.object_type)) {
2844 "Static class '{0}' cannot derive from type '{1}'. " +
2845 "Static classes must derive from object",
2846 GetSignatureForError (), ptype);
2850 if (ifaces != null) {
2851 foreach (Type t in ifaces)
2852 Report.SymbolRelatedToPreviousError (t);
2855 "'{0}': static classes cannot implement interfaces",
2856 GetSignatureForError ());
2861 public override TypeAttributes TypeAttr {
2863 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2868 public class Class : ClassOrStruct {
2870 // Modifiers allowed in a class declaration
2872 public const int AllowedModifiers =
2875 Modifiers.PROTECTED |
2876 Modifiers.INTERNAL |
2878 Modifiers.ABSTRACT |
2882 // Information in the case we are an attribute type
2883 AttributeUsageAttribute attribute_usage;
2885 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2886 Attributes attrs, Location l)
2887 : base (ns, parent, name, attrs, Kind.Class, l)
2891 if (parent.Parent == null)
2892 accmods = Modifiers.INTERNAL;
2894 accmods = Modifiers.PRIVATE;
2896 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2897 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.SEALED)) == (Modifiers.ABSTRACT | Modifiers.SEALED)) {
2898 Report.Error (502, Location, "'{0}' cannot be both abstract and sealed", GetSignatureForError ());
2901 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2904 public override AttributeTargets AttributeTargets {
2906 return AttributeTargets.Class;
2910 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2912 if (a.UsageAttribute != null) {
2913 if (ptype != TypeManager.attribute_type &&
2914 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2915 TypeBuilder.FullName != "System.Attribute") {
2916 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2918 attribute_usage = a.UsageAttribute;
2921 base.ApplyAttributeBuilder (a, cb);
2924 public AttributeUsageAttribute AttributeUsage {
2926 return attribute_usage;
2930 public const TypeAttributes DefaultTypeAttributes =
2931 TypeAttributes.AutoLayout | TypeAttributes.Class;
2934 // FIXME: How do we deal with the user specifying a different
2937 public override TypeAttributes TypeAttr {
2939 return base.TypeAttr | DefaultTypeAttributes;
2944 public class Struct : ClassOrStruct {
2946 // Modifiers allowed in a struct declaration
2948 public const int AllowedModifiers =
2951 Modifiers.PROTECTED |
2952 Modifiers.INTERNAL |
2956 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2957 int mod, Attributes attrs, Location l)
2958 : base (ns, parent, name, attrs, Kind.Struct, l)
2962 if (parent.Parent == null)
2963 accmods = Modifiers.INTERNAL;
2965 accmods = Modifiers.PRIVATE;
2967 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2969 this.ModFlags |= Modifiers.SEALED;
2972 public override AttributeTargets AttributeTargets {
2974 return AttributeTargets.Struct;
2978 public const TypeAttributes DefaultTypeAttributes =
2979 TypeAttributes.SequentialLayout |
2980 TypeAttributes.Sealed |
2981 TypeAttributes.BeforeFieldInit;
2984 // FIXME: Allow the user to specify a different set of attributes
2985 // in some cases (Sealed for example is mandatory for a class,
2986 // but what SequentialLayout can be changed
2988 public override TypeAttributes TypeAttr {
2990 return base.TypeAttr | DefaultTypeAttributes;
2998 public class Interface : TypeContainer, IMemberContainer {
3000 /// Modifiers allowed in a class declaration
3002 public const int AllowedModifiers =
3005 Modifiers.PROTECTED |
3006 Modifiers.INTERNAL |
3010 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name,
3011 int mod, Attributes attrs, Location l)
3012 : base (ns, parent, name, attrs, Kind.Interface, l)
3016 if (parent.Parent == null)
3017 accmods = Modifiers.INTERNAL;
3019 accmods = Modifiers.PRIVATE;
3021 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3024 public override void Register ()
3026 Parent.AddInterface (this);
3029 public override PendingImplementation GetPendingImplementations ()
3034 public override AttributeTargets AttributeTargets {
3036 return AttributeTargets.Interface;
3040 public const TypeAttributes DefaultTypeAttributes =
3041 TypeAttributes.AutoLayout |
3042 TypeAttributes.Abstract |
3043 TypeAttributes.Interface;
3045 public override TypeAttributes TypeAttr {
3047 return base.TypeAttr | DefaultTypeAttributes;
3052 public abstract class MethodCore : MemberBase {
3053 public readonly Parameters Parameters;
3054 public readonly GenericMethod GenericMethod;
3055 public readonly DeclSpace ds;
3056 protected ToplevelBlock block;
3059 // Parameters, cached for semantic analysis.
3061 protected InternalParameters parameter_info;
3062 protected Type [] parameter_types;
3064 // Whether this is an operator method.
3065 public bool IsOperator;
3068 // The method we're overriding if this is an override method.
3070 protected MethodInfo parent_method = null;
3072 static string[] attribute_targets = new string [] { "method", "return" };
3074 public MethodCore (TypeContainer parent, GenericMethod generic,
3075 Expression type, int mod, int allowed_mod, bool is_iface,
3076 MemberName name, Attributes attrs, Parameters parameters,
3078 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3081 Parameters = parameters;
3082 IsInterface = is_iface;
3083 this.GenericMethod = generic;
3085 if (generic != null)
3092 // Returns the System.Type array for the parameters of this method
3094 public Type [] ParameterTypes {
3096 return parameter_types;
3100 public InternalParameters ParameterInfo
3103 return parameter_info;
3107 public ToplevelBlock Block {
3117 protected override bool CheckBase ()
3119 if (!base.CheckBase ())
3122 // Check whether arguments were correct.
3123 if (!DoDefineParameters ())
3126 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3132 // Is null for System.Object while compiling corlib and base interfaces
3133 if (Parent.ParentCache == null) {
3134 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3135 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3140 Type parent_ret_type = null;
3141 parent_method = FindOutParentMethod (Parent, ref parent_ret_type);
3143 // method is override
3144 if (parent_method != null) {
3146 if (!CheckMethodAgainstBase ())
3149 if ((ModFlags & Modifiers.NEW) == 0) {
3150 if (!MemberType.Equals (TypeManager.TypeToCoreType (parent_ret_type))) {
3151 Report.SymbolRelatedToPreviousError (parent_method);
3152 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3153 "change return type when overriding inherited member");
3157 if (parent_method.IsAbstract && !IsInterface) {
3158 Report.SymbolRelatedToPreviousError (parent_method);
3159 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3164 if (parent_method.IsSpecialName && !(this is PropertyBase)) {
3165 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (parent_method));
3169 if (RootContext.WarningLevel > 2) {
3170 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3171 Parent.Methods.HasEquals = true;
3172 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3173 Parent.Methods.HasGetHashCode = true;
3176 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (parent_method);
3178 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3179 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3180 Report.SymbolRelatedToPreviousError (parent_method);
3181 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3187 MemberInfo conflict_symbol = Parent.FindMemberWithSameName (Name, !(this is Property));
3188 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3189 if (conflict_symbol != null) {
3190 Report.SymbolRelatedToPreviousError (conflict_symbol);
3191 if (this is PropertyBase)
3192 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3194 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3196 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3200 if (conflict_symbol == null) {
3201 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3202 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3207 if ((ModFlags & Modifiers.NEW) == 0) {
3208 if (this is Method && conflict_symbol is MethodBase)
3211 Report.SymbolRelatedToPreviousError (conflict_symbol);
3212 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3220 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3221 // that have been defined.
3223 // `name' is the user visible name for reporting errors (this is used to
3224 // provide the right name regarding method names and properties)
3226 bool CheckMethodAgainstBase ()
3230 // TODO: replace with GetSignatureForError
3231 string name = parent_method.DeclaringType.Name + "." + parent_method.Name;
3233 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3234 if (!(parent_method.IsAbstract || parent_method.IsVirtual)){
3236 506, Location, Parent.MakeName (Name) +
3237 ": cannot override inherited member `" +
3238 name + "' because it is not " +
3239 "virtual, abstract or override");
3243 // Now we check that the overriden method is not final
3245 if (parent_method.IsFinal) {
3246 // This happens when implementing interface methods.
3247 if (parent_method.IsHideBySig && parent_method.IsVirtual) {
3249 506, Location, Parent.MakeName (Name) +
3250 ": cannot override inherited member `" +
3251 name + "' because it is not " +
3252 "virtual, abstract or override");
3254 Report.Error (239, Location, Parent.MakeName (Name) + " : cannot " +
3255 "override inherited member `" + name +
3256 "' because it is sealed.");
3260 // Check that the permissions are not being changed
3262 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3263 MethodAttributes parentp = parent_method.Attributes & MethodAttributes.MemberAccessMask;
3265 if (!CheckAccessModifiers (thisp, parentp, parent_method)) {
3266 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3271 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3272 ModFlags |= Modifiers.NEW;
3273 Report.SymbolRelatedToPreviousError (parent_method);
3274 if (!IsInterface && (parent_method.IsVirtual || parent_method.IsAbstract)) {
3275 if (RootContext.WarningLevel >= 2)
3276 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 (parent_method));
3278 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3284 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes parentp, MethodInfo base_method)
3286 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3288 // when overriding protected internal, the method can be declared
3289 // protected internal only within the same assembly
3292 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3293 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3295 // assemblies differ - report an error
3299 } else if (thisp != parentp) {
3301 // same assembly, but other attributes differ - report an error
3306 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3308 // if it's not "protected internal", it must be "protected"
3312 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3314 // protected within the same assembly - an error
3317 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3318 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3320 // protected ok, but other attributes differ - report an error
3326 return (thisp == parentp);
3330 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method, string name)
3333 // FIXME: report the old/new permissions?
3336 507, Location, parent.MakeName (Name) +
3337 ": can't change the access modifiers when overriding inherited " +
3338 "member `" + name + "'");
3341 protected static string Error722 {
3343 return "'{0}': static types cannot be used as return types";
3348 /// For custom member duplication search in a container
3350 protected abstract bool CheckForDuplications ();
3353 /// Gets parent method and its return type
3355 protected abstract MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type);
3357 protected virtual bool DoDefineParameters ()
3359 EmitContext ec = ds.EmitContext;
3361 throw new InternalErrorException ("DoDefineParameters invoked too early");
3363 bool old_unsafe = ec.InUnsafe;
3364 ec.InUnsafe = InUnsafe;
3365 // Check if arguments were correct
3366 parameter_types = Parameters.GetParameterInfo (ec);
3367 ec.InUnsafe = old_unsafe;
3369 if ((parameter_types == null) ||
3370 !CheckParameters (ds, parameter_types))
3373 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3374 parameter_info = new InternalParameters (parameter_types, Parameters, tparam);
3376 Parameter array_param = Parameters.ArrayParameter;
3377 if ((array_param != null) &&
3378 (!array_param.ParameterType.IsArray ||
3379 (array_param.ParameterType.GetArrayRank () != 1))) {
3380 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3387 void error_425 (Type old, Type t, string name)
3389 Report.Error (425, Location,
3390 "The constraints of type parameter `{0}' " +
3391 "of method `{1}' must match the constraints for " +
3392 "type parameter `{2}' of method `{3}'",
3393 TypeManager.CSharpName (old), Name,
3394 TypeManager.CSharpName (t), name);
3397 protected override bool CheckGenericOverride (MethodInfo method, string name)
3399 ParameterData pd = Invocation.GetParameterData (method);
3401 for (int i = 0; i < ParameterTypes.Length; i++) {
3402 GenericConstraints ogc = pd.GenericConstraints (i);
3403 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3405 if ((gc == null) && (ogc == null))
3408 Type ot = pd.ParameterType (i);
3409 Type t = ParameterTypes [i];
3411 if (!((gc != null) && (ogc != null))) {
3412 error_425 (ot, t, name);
3416 if ((gc.Attributes != ogc.Attributes) ||
3417 (gc.HasClassConstraint != ogc.HasClassConstraint)) {
3418 error_425 (ot, t, name);
3422 if (ogc.HasClassConstraint &&
3423 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3424 error_425 (ot, t, name);
3428 Type[] oct = ogc.InterfaceConstraints;
3429 Type[] ct = gc.InterfaceConstraints;
3431 if (oct.Length != ct.Length) {
3432 error_425 (ot, t, name);
3436 for (int j = 0; j < oct.Length; j++)
3437 if (!oct [j].Equals (ct [j])) {
3438 error_425 (ot, t, name);
3446 public override string[] ValidAttributeTargets {
3448 return attribute_targets;
3452 protected override bool VerifyClsCompliance (DeclSpace ds)
3454 if (!base.VerifyClsCompliance (ds)) {
3455 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3456 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3461 if (Parameters.HasArglist) {
3462 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3465 if (!AttributeTester.IsClsCompliant (MemberType)) {
3466 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant", GetSignatureForError ());
3469 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3474 protected bool IsDuplicateImplementation (MethodCore method)
3476 if ((method == this) ||
3477 (method.MemberName.GetTypeName () != MemberName.GetTypeName ()))
3480 Type[] param_types = method.ParameterTypes;
3481 if (param_types == null)
3484 if (param_types.Length != ParameterTypes.Length)
3487 int type_params = 0;
3488 if (GenericMethod != null)
3489 type_params = GenericMethod.CountTypeParameters;
3491 int m_type_params = 0;
3492 if (method.GenericMethod != null)
3493 m_type_params = method.GenericMethod.CountTypeParameters;
3495 if (type_params != m_type_params)
3501 Type[] infered_types;
3502 if (type_params > 0)
3503 infered_types = new Type [type_params];
3505 infered_types = null;
3507 may_unify = Invocation.InferTypeArguments (
3508 param_types, ParameterTypes, ref infered_types);
3511 if (type_params > 0)
3512 infered_types = new Type [type_params];
3514 infered_types = null;
3516 may_unify = Invocation.InferTypeArguments (
3517 ParameterTypes, param_types, ref infered_types);
3520 for (int i = 0; i < param_types.Length; i++) {
3521 if (param_types [i] != ParameterTypes [i])
3525 // TODO: make operator compatible with MethodCore to avoid this
3526 if (this is Operator && method is Operator) {
3527 if (MemberType != method.MemberType)
3533 // Try to report 663: method only differs on out/ref
3535 ParameterData info = ParameterInfo;
3536 ParameterData other_info = method.ParameterInfo;
3537 for (int i = 0; i < info.Count; i++){
3538 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3539 Report.Error (663, Location,
3540 "Overload method only differs " +
3541 "in parameter modifier");
3546 Report.SymbolRelatedToPreviousError (method);
3547 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with the same parameter types", Parent.Name, Name);
3549 } else if (may_unify) {
3550 Report.Error (408, Location,
3551 "`{0}' cannot define overload members that " +
3552 "may unify for some type parameter substitutions",
3560 protected override void VerifyObsoleteAttribute()
3562 base.VerifyObsoleteAttribute ();
3564 if (parameter_types == null)
3567 foreach (Type type in parameter_types) {
3568 CheckUsageOfObsoleteAttribute (type);
3573 public class SourceMethod : ISourceMethod
3575 TypeContainer container;
3578 protected SourceMethod (TypeContainer container, MethodBase builder,
3579 ISourceFile file, Location start, Location end)
3581 this.container = container;
3582 this.builder = builder;
3584 CodeGen.SymbolWriter.OpenMethod (
3585 file, this, start.Row, 0, end.Row, 0);
3588 public string Name {
3589 get { return builder.Name; }
3592 public int NamespaceID {
3593 get { return container.NamespaceEntry.SymbolFileID; }
3598 if (builder is MethodBuilder)
3599 return ((MethodBuilder) builder).GetToken ().Token;
3600 else if (builder is ConstructorBuilder)
3601 return ((ConstructorBuilder) builder).GetToken ().Token;
3603 throw new NotSupportedException ();
3607 public void CloseMethod ()
3609 if (CodeGen.SymbolWriter != null)
3610 CodeGen.SymbolWriter.CloseMethod ();
3613 public static SourceMethod Create (TypeContainer parent,
3614 MethodBase builder, Block block)
3616 if (CodeGen.SymbolWriter == null)
3621 Location start_loc = block.StartLocation;
3622 if (Location.IsNull (start_loc))
3625 Location end_loc = block.EndLocation;
3626 if (Location.IsNull (end_loc))
3629 ISourceFile file = start_loc.SourceFile;
3633 return new SourceMethod (
3634 parent, builder, file, start_loc, end_loc);
3638 public class Method : MethodCore, IIteratorContainer, IMethodData {
3639 public MethodBuilder MethodBuilder;
3640 public MethodData MethodData;
3641 ReturnParameter return_attributes;
3642 ListDictionary declarative_security;
3645 /// Modifiers allowed in a class declaration
3647 const int AllowedModifiers =
3650 Modifiers.PROTECTED |
3651 Modifiers.INTERNAL |
3656 Modifiers.OVERRIDE |
3657 Modifiers.ABSTRACT |
3659 Modifiers.METHOD_YIELDS |
3662 const int AllowedInterfaceModifiers =
3663 Modifiers.NEW | Modifiers.UNSAFE;
3666 // return_type can be "null" for VOID values.
3668 public Method (TypeContainer parent, GenericMethod generic,
3669 Expression return_type, int mod, bool is_iface,
3670 MemberName name, Parameters parameters, Attributes attrs,
3672 : base (parent, generic, return_type, mod,
3673 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3674 is_iface, name, attrs, parameters, l)
3678 public override AttributeTargets AttributeTargets {
3680 return AttributeTargets.Method;
3684 public override string GetSignatureForError()
3686 if (MethodBuilder == null) {
3687 return GetSignatureForError (Parent);
3689 return TypeManager.CSharpSignature (MethodBuilder);
3693 /// Use this method when MethodBuilder is null
3695 public override string GetSignatureForError (TypeContainer tc)
3697 // TODO: get params from somewhere
3698 if (parameter_info == null)
3699 return base.GetSignatureForError (tc);
3701 // TODO: move to parameters
3702 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3703 if (parameter_info.Parameters.FixedParameters != null) {
3704 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3705 Parameter p = parameter_info.Parameters.FixedParameters [i];
3706 args.Append (p.GetSignatureForError ());
3708 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3713 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3716 void DuplicateEntryPoint (MethodInfo b, Location location)
3720 "Program `" + CodeGen.FileName +
3721 "' has more than one entry point defined: `" +
3722 TypeManager.CSharpSignature(b) + "'");
3725 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3727 if (b.ReturnType != TypeManager.void_type &&
3728 b.ReturnType != TypeManager.int32_type)
3731 if (pinfo.Count == 0)
3734 if (pinfo.Count > 1)
3737 Type t = pinfo.ParameterType(0);
3739 (t.GetArrayRank() == 1) &&
3740 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3741 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3747 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3749 if (a.Target == AttributeTargets.ReturnValue) {
3750 if (return_attributes == null)
3751 return_attributes = new ReturnParameter (MethodBuilder, Location);
3753 return_attributes.ApplyAttributeBuilder (a, cb);
3757 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
3758 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3761 if (a.Type == TypeManager.dllimport_type) {
3762 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3763 if ((ModFlags & extern_static) != extern_static) {
3764 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3770 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3771 if (declarative_security == null)
3772 declarative_security = new ListDictionary ();
3773 a.ExtractSecurityPermissionSet (declarative_security);
3777 if (a.Type == TypeManager.conditional_attribute_type) {
3778 if (IsOperator || IsExplicitImpl) {
3779 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3783 if (ReturnType != TypeManager.void_type) {
3784 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3788 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3789 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3794 Report.Error (582, Location, "Conditional not valid on interface members");
3798 if (MethodData.IsImplementing) {
3799 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3803 for (int i = 0; i < parameter_info.Count; ++i) {
3804 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3805 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3811 MethodBuilder.SetCustomAttribute (cb);
3814 protected override bool CheckForDuplications ()
3816 ArrayList ar = Parent.Methods;
3818 int arLen = ar.Count;
3820 for (int i = 0; i < arLen; i++) {
3821 Method m = (Method) ar [i];
3822 if (IsDuplicateImplementation (m))
3827 ar = Parent.Properties;
3829 for (int i = 0; i < ar.Count; ++i) {
3830 PropertyBase pb = (PropertyBase) ar [i];
3831 if (pb.AreAccessorsDuplicateImplementation (this))
3836 ar = Parent.Indexers;
3838 for (int i = 0; i < ar.Count; ++i) {
3839 PropertyBase pb = (PropertyBase) ar [i];
3840 if (pb.AreAccessorsDuplicateImplementation (this))
3847 for (int i = 0; i < ar.Count; ++i) {
3848 Event ev = (Event) ar [i];
3849 if (ev.AreAccessorsDuplicateImplementation (this))
3860 public override bool Define ()
3862 if (!DoDefineBase ())
3865 MethodBuilder mb = null;
3866 if (GenericMethod != null) {
3867 string mname = MemberName.GetMethodName ();
3868 mb = Parent.TypeBuilder.DefineGenericMethod (mname, flags);
3869 if (!GenericMethod.Define (mb, ReturnType))
3880 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3882 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
3883 this, mb, GenericMethod, parent_method);
3885 if (!MethodData.Define (Parent))
3889 // Setup iterator if we are one
3891 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3892 Iterator iterator = new Iterator (
3893 Parent, Name, MemberType, ParameterTypes,
3894 ParameterInfo, ModFlags, block, Location);
3896 if (!iterator.DefineIterator ())
3899 block = iterator.Block;
3902 MethodBuilder = MethodData.MethodBuilder;
3905 // This is used to track the Entry Point,
3907 if (Name == "Main" &&
3908 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3909 (RootContext.MainClass == null ||
3910 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3911 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3912 if (RootContext.EntryPoint == null) {
3913 if (Parent.IsGeneric){
3914 Report.Error (-201, Location,
3915 "Entry point can not be defined in a generic class");
3918 RootContext.EntryPoint = MethodBuilder;
3919 RootContext.EntryPointLocation = Location;
3921 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3922 DuplicateEntryPoint (MethodBuilder, Location);
3925 if (RootContext.WarningLevel >= 4)
3926 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder) );
3930 if (MemberType.IsAbstract && MemberType.IsSealed) {
3931 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3941 public override void Emit ()
3943 MethodData.Emit (Parent, this);
3946 if (declarative_security != null) {
3947 foreach (DictionaryEntry de in declarative_security) {
3948 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3956 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
3958 MethodInfo mi = (MethodInfo) container.ParentCache.FindMemberToOverride (
3959 container.TypeBuilder, Name, ParameterTypes, false);
3964 parent_ret_type = mi.ReturnType;
3968 protected override bool VerifyClsCompliance(DeclSpace ds)
3970 if (!base.VerifyClsCompliance (ds))
3973 if (parameter_types.Length > 0) {
3974 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3976 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3983 void IIteratorContainer.SetYields ()
3985 ModFlags |= Modifiers.METHOD_YIELDS;
3988 #region IMethodData Members
3990 public CallingConventions CallingConventions {
3992 CallingConventions cc = Parameters.GetCallingConvention ();
3993 if (Parameters.HasArglist)
3994 block.HasVarargs = true;
3997 if ((ModFlags & Modifiers.STATIC) == 0)
3998 cc |= CallingConventions.HasThis;
4000 // FIXME: How is `ExplicitThis' used in C#?
4006 public Type ReturnType {
4012 public MemberName MethodName {
4018 public new Location Location {
4020 return base.Location;
4024 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4026 return new EmitContext (
4027 tc, ds, Location, ig, ReturnType, ModFlags, false);
4030 public ObsoleteAttribute GetObsoleteAttribute ()
4032 return GetObsoleteAttribute (ds);
4036 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4038 public bool IsExcluded (EmitContext ec)
4040 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4041 return (caching_flags & Flags.Excluded) != 0;
4043 caching_flags &= ~Flags.Excluded_Undetected;
4045 if (parent_method == null) {
4046 if (OptAttributes == null)
4049 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4054 foreach (Attribute a in attrs) {
4055 string condition = a.GetConditionalAttributeValue (ds);
4056 if (RootContext.AllDefines.Contains (condition))
4060 caching_flags |= Flags.Excluded;
4064 IMethodData md = TypeManager.GetMethod (parent_method);
4066 if (AttributeTester.IsConditionalMethodExcluded (parent_method)) {
4067 caching_flags |= Flags.Excluded;
4073 if (md.IsExcluded (ec)) {
4074 caching_flags |= Flags.Excluded;
4080 GenericMethod IMethodData.GenericMethod {
4082 return GenericMethod;
4089 public abstract class ConstructorInitializer {
4090 ArrayList argument_list;
4091 protected ConstructorInfo parent_constructor;
4092 Parameters parameters;
4095 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4098 this.argument_list = argument_list;
4099 this.parameters = parameters;
4103 public ArrayList Arguments {
4105 return argument_list;
4109 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4111 Expression parent_constructor_group;
4114 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
4116 if (argument_list != null){
4117 foreach (Argument a in argument_list){
4118 if (!a.Resolve (ec, loc))
4122 ec.CurrentBlock = null;
4124 if (this is ConstructorBaseInitializer) {
4125 if (ec.ContainerType.BaseType == null)
4128 t = ec.ContainerType.BaseType;
4129 if (ec.ContainerType.IsValueType) {
4130 Report.Error (522, loc,
4131 "structs cannot call base class constructors");
4135 t = ec.ContainerType;
4137 parent_constructor_group = Expression.MemberLookup (
4138 ec, t, ".ctor", MemberTypes.Constructor,
4139 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4142 if (parent_constructor_group == null){
4143 parent_constructor_group = Expression.MemberLookup (
4144 ec, t, ".ctor", MemberTypes.Constructor,
4145 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4148 if (parent_constructor_group != null)
4150 112, loc, "`{0}.{1}' is inaccessible due to " +
4151 "its protection level", t.FullName, t.Name);
4154 1501, loc, "Can not find a constructor for " +
4155 "this argument list");
4159 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4160 ec, (MethodGroupExpr) parent_constructor_group, argument_list,
4163 if (parent_constructor == null){
4164 Report.Error (1501, loc,
4165 "Can not find a constructor for this argument list");
4169 if (parent_constructor == caller_builder){
4170 Report.Error (516, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
4177 public void Emit (EmitContext ec)
4179 if (parent_constructor != null){
4180 ec.Mark (loc, false);
4182 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
4184 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
4189 /// Method search for base ctor. (We do not cache it).
4191 Constructor GetOverloadedConstructor (TypeContainer tc)
4193 if (tc.InstanceConstructors == null)
4196 foreach (Constructor c in tc.InstanceConstructors) {
4197 if (Arguments == null) {
4198 if (c.ParameterTypes.Length == 0)
4206 int count = c.ParameterInfo.Count;
4208 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4209 for (int i = 0; i < count-1; i++)
4210 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4215 if (c.ParameterTypes.Length != Arguments.Count)
4218 for (int i = 0; i < Arguments.Count; ++i)
4219 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4234 //TODO: implement caching when it will be necessary
4235 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4237 Constructor ctor = GetOverloadedConstructor (tc);
4241 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4245 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4249 public class ConstructorBaseInitializer : ConstructorInitializer {
4250 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4251 base (argument_list, pars, l)
4255 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4256 if (parent_constructor == null)
4259 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4260 if (type_ds == null) {
4261 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (parent_constructor);
4264 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (parent_constructor), loc);
4269 base.CheckObsoleteAttribute (type_ds, loc);
4274 public class ConstructorThisInitializer : ConstructorInitializer {
4275 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4276 base (argument_list, pars, l)
4281 public class Constructor : MethodCore, IMethodData {
4282 public ConstructorBuilder ConstructorBuilder;
4283 public ConstructorInitializer Initializer;
4284 ListDictionary declarative_security;
4287 // Modifiers allowed for a constructor.
4289 public const int AllowedModifiers =
4291 Modifiers.PROTECTED |
4292 Modifiers.INTERNAL |
4298 bool has_compliant_args = false;
4300 // The spec claims that static is not permitted, but
4301 // my very own code has static constructors.
4303 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4304 ConstructorInitializer init, Location l)
4305 : base (ds, null, null, mod, AllowedModifiers, false,
4306 new MemberName (name), null, args, l)
4311 public override string GetSignatureForError()
4313 if (ConstructorBuilder == null)
4314 return GetSignatureForError (Parent);
4316 return TypeManager.CSharpSignature (ConstructorBuilder);
4319 public bool HasCompliantArgs {
4321 return has_compliant_args;
4325 public override AttributeTargets AttributeTargets {
4327 return AttributeTargets.Constructor;
4333 // Returns true if this is a default constructor
4335 public bool IsDefault ()
4337 if ((ModFlags & Modifiers.STATIC) != 0)
4338 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4339 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4342 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4343 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4344 (Initializer is ConstructorBaseInitializer) &&
4345 (Initializer.Arguments == null);
4348 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4350 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4351 if (declarative_security == null) {
4352 declarative_security = new ListDictionary ();
4354 a.ExtractSecurityPermissionSet (declarative_security);
4358 ConstructorBuilder.SetCustomAttribute (cb);
4361 protected override bool CheckForDuplications ()
4363 ArrayList ar = Parent.InstanceConstructors;
4365 int arLen = ar.Count;
4367 for (int i = 0; i < arLen; i++) {
4368 Constructor m = (Constructor) ar [i];
4369 if (IsDuplicateImplementation (m))
4376 protected override bool CheckBase ()
4378 // Check whether arguments were correct.
4379 if (!DoDefineParameters ())
4382 // TODO: skip the rest for generated ctor
4383 if ((ModFlags & Modifiers.STATIC) != 0)
4386 if (!CheckForDuplications ())
4389 if (Parent.Kind == Kind.Struct) {
4390 if (ParameterTypes.Length == 0) {
4391 Report.Error (568, Location,
4392 "Structs can not contain explicit parameterless " +
4397 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4398 Report.Error (666, Location, "Protected member in struct declaration");
4403 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4404 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4411 // Creates the ConstructorBuilder
4413 public override bool Define ()
4415 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4416 MethodAttributes.SpecialName);
4418 if ((ModFlags & Modifiers.STATIC) != 0){
4419 ca |= MethodAttributes.Static | MethodAttributes.Private;
4421 ca |= MethodAttributes.HideBySig;
4423 if ((ModFlags & Modifiers.PUBLIC) != 0)
4424 ca |= MethodAttributes.Public;
4425 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4426 if ((ModFlags & Modifiers.INTERNAL) != 0)
4427 ca |= MethodAttributes.FamORAssem;
4429 ca |= MethodAttributes.Family;
4430 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4431 ca |= MethodAttributes.Assembly;
4432 else if (IsDefault ())
4433 ca |= MethodAttributes.Public;
4435 ca |= MethodAttributes.Private;
4438 // Check if arguments were correct.
4442 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4443 ca, CallingConventions,
4446 if ((ModFlags & Modifiers.UNSAFE) != 0)
4447 ConstructorBuilder.InitLocals = false;
4449 TypeManager.AddMethod (ConstructorBuilder, this);
4452 // HACK because System.Reflection.Emit is lame
4454 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4462 public override void Emit ()
4464 EmitContext ec = CreateEmitContext (null, null);
4467 // extern methods have no bodies
4469 if ((ModFlags & Modifiers.EXTERN) != 0) {
4470 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4472 179, Location, "External constructor `" +
4473 TypeManager.CSharpSignature (ConstructorBuilder) +
4474 "' can not have a body");
4477 } else if (block == null) {
4479 501, Location, "Constructor `" +
4480 TypeManager.CSharpSignature (ConstructorBuilder) +
4481 "' must declare a body since it is not marked extern");
4485 if ((ModFlags & Modifiers.STATIC) == 0){
4486 if (Parent.Kind == Kind.Class && Initializer == null)
4487 Initializer = new ConstructorBaseInitializer (
4488 null, Parameters.EmptyReadOnlyParameters, Location);
4492 // Spec mandates that Initializers will not have
4496 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4498 ec.IsStatic = false;
4501 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4503 SourceMethod source = SourceMethod.Create (
4504 Parent, ConstructorBuilder, block);
4507 // Classes can have base initializers and instance field initializers.
4509 if (Parent.Kind == Kind.Class){
4510 if ((ModFlags & Modifiers.STATIC) == 0){
4513 // If we use a "this (...)" constructor initializer, then
4514 // do not emit field initializers, they are initialized in the other constructor
4516 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4517 Parent.EmitFieldInitializers (ec);
4520 if (Initializer != null) {
4521 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4522 Initializer.CheckObsoleteAttribute (Parent, Location);
4524 ec.TestObsoleteMethodUsage = false;
4525 Initializer.Emit (ec);
4528 if ((ModFlags & Modifiers.STATIC) != 0)
4529 Parent.EmitFieldInitializers (ec);
4531 if (OptAttributes != null)
4532 OptAttributes.Emit (ec, this);
4534 // If this is a non-static `struct' constructor and doesn't have any
4535 // initializer, it must initialize all of the struct's fields.
4536 if ((Parent.Kind == Kind.Struct) &&
4537 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4538 Block.AddThisVariable (Parent, Location);
4540 ec.EmitTopBlock (block, ParameterInfo, Location);
4543 source.CloseMethod ();
4547 if (declarative_security != null) {
4548 foreach (DictionaryEntry de in declarative_security) {
4549 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4556 // Is never override
4557 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
4562 protected override bool VerifyClsCompliance (DeclSpace ds)
4564 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4568 if (parameter_types.Length > 0) {
4569 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4571 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4573 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4574 foreach (Type param in parameter_types) {
4575 if (param.IsArray) {
4581 has_compliant_args = true;
4585 #region IMethodData Members
4587 public System.Reflection.CallingConventions CallingConventions {
4589 CallingConventions cc = Parameters.GetCallingConvention ();
4591 if (Parent.Kind == Kind.Class)
4592 if ((ModFlags & Modifiers.STATIC) == 0)
4593 cc |= CallingConventions.HasThis;
4595 // FIXME: How is `ExplicitThis' used in C#?
4601 public new Location Location {
4603 return base.Location;
4607 public MemberName MethodName {
4613 public Type ReturnType {
4619 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4621 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4622 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4625 public ObsoleteAttribute GetObsoleteAttribute ()
4630 public bool IsExcluded(EmitContext ec)
4635 GenericMethod IMethodData.GenericMethod {
4645 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4647 public interface IMethodData
4649 CallingConventions CallingConventions { get; }
4650 Location Location { get; }
4651 MemberName MethodName { get; }
4652 Type[] ParameterTypes { get; }
4653 Type ReturnType { get; }
4654 GenericMethod GenericMethod { get; }
4656 Attributes OptAttributes { get; }
4657 ToplevelBlock Block { get; }
4659 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4660 ObsoleteAttribute GetObsoleteAttribute ();
4661 string GetSignatureForError (TypeContainer tc);
4662 bool IsExcluded (EmitContext ec);
4663 bool IsClsCompliaceRequired (DeclSpace ds);
4667 // Encapsulates most of the Method's state
4669 public class MethodData {
4671 readonly IMethodData method;
4674 // The return type of this method
4676 public readonly GenericMethod GenericMethod;
4677 public readonly InternalParameters ParameterInfo;
4680 // Are we implementing an interface ?
4682 public bool IsImplementing = false;
4687 protected MemberBase member;
4688 protected int modifiers;
4689 protected MethodAttributes flags;
4690 protected Type declaring_type;
4691 protected MethodInfo parent_method;
4695 MethodBuilder builder = null;
4696 public MethodBuilder MethodBuilder {
4702 public Type DeclaringType {
4704 return declaring_type;
4708 public MethodData (MemberBase member, InternalParameters parameters,
4709 int modifiers, MethodAttributes flags, IMethodData method)
4711 this.member = member;
4712 this.ParameterInfo = parameters;
4713 this.modifiers = modifiers;
4716 this.method = method;
4719 public MethodData (MemberBase member, InternalParameters parameters,
4720 int modifiers, MethodAttributes flags,
4721 IMethodData method, MethodBuilder builder,
4722 GenericMethod generic, MethodInfo parent_method)
4723 : this (member, parameters, modifiers, flags, method)
4725 this.builder = builder;
4726 this.GenericMethod = generic;
4727 this.parent_method = parent_method;
4730 static string RemoveArity (string name)
4733 StringBuilder sb = new StringBuilder ();
4734 while (start < name.Length) {
4735 int pos = name.IndexOf ('`', start);
4737 sb.Append (name.Substring (start));
4741 sb.Append (name.Substring (start, pos-start));
4744 while ((pos < name.Length) && Char.IsNumber (name [pos]))
4750 return sb.ToString ();
4753 public bool Define (TypeContainer container)
4755 MethodInfo implementing = null;
4758 if (member.IsExplicitImpl)
4759 prefix = member.InterfaceType.FullName + ".";
4763 string name = method.MethodName.Basename;
4764 string method_name = prefix + name;
4766 Type[] ParameterTypes = method.ParameterTypes;
4768 if (container.Pending != null){
4769 if (member is Indexer)
4770 implementing = container.Pending.IsInterfaceIndexer (
4771 member.InterfaceType, method.ReturnType, ParameterTypes);
4773 implementing = container.Pending.IsInterfaceMethod (
4774 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4776 if (member.InterfaceType != null){
4777 if (implementing == null){
4778 Report.Error (539, method.Location,
4779 "'{0}' in explicit interface declaration is not an interface", method_name);
4786 // For implicit implementations, make sure we are public, for
4787 // explicit implementations, make sure we are private.
4789 if (implementing != null){
4791 // Setting null inside this block will trigger a more
4792 // verbose error reporting for missing interface implementations
4794 // The "candidate" function has been flagged already
4795 // but it wont get cleared
4797 if (member.IsExplicitImpl){
4798 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4799 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4800 implementing = null;
4802 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4803 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4805 // If this is an interface method implementation,
4806 // check for public accessibility
4808 implementing = null;
4809 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4810 // We may never be private.
4811 implementing = null;
4812 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4814 // We may be protected if we're overriding something.
4816 implementing = null;
4821 // Static is not allowed
4823 if ((modifiers & Modifiers.STATIC) != 0){
4824 implementing = null;
4825 Modifiers.Error_InvalidModifier (method.Location, "static");
4830 // If implementing is still valid, set flags
4832 if (implementing != null){
4834 // When implementing interface methods, set NewSlot
4835 // unless, we are overwriting a method.
4837 if (implementing.DeclaringType.IsInterface){
4838 if ((modifiers & Modifiers.OVERRIDE) == 0)
4839 flags |= MethodAttributes.NewSlot;
4842 MethodAttributes.Virtual |
4843 MethodAttributes.HideBySig;
4845 // Set Final unless we're virtual, abstract or already overriding a method.
4846 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4847 flags |= MethodAttributes.Final;
4849 IsImplementing = true;
4852 EmitContext ec = method.CreateEmitContext (container, null);
4854 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4856 if (builder == null)
4859 if (container.CurrentType != null)
4860 declaring_type = container.CurrentType;
4862 declaring_type = container.TypeBuilder;
4864 if ((modifiers & Modifiers.UNSAFE) != 0)
4865 builder.InitLocals = false;
4867 if (IsImplementing){
4869 // clear the pending implemntation flag
4871 if (member is Indexer) {
4872 container.Pending.ImplementIndexer (
4873 member.InterfaceType, builder, method.ReturnType,
4874 ParameterTypes, member.IsExplicitImpl);
4876 container.Pending.ImplementMethod (
4877 member.InterfaceType, name, method.ReturnType,
4878 ParameterTypes, member.IsExplicitImpl);
4880 if (member.IsExplicitImpl)
4881 container.TypeBuilder.DefineMethodOverride (
4882 builder, implementing);
4886 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4887 TypeManager.AddMethod (builder, method);
4889 if (GenericMethod != null) {
4890 bool is_override = member.IsExplicitImpl |
4891 ((modifiers & Modifiers.OVERRIDE) != 0);
4893 if (implementing != null)
4894 parent_method = implementing;
4896 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
4904 /// Create the MethodBuilder for the method
4906 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4908 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4910 if ((modifiers & extern_static) == extern_static) {
4912 if (method.OptAttributes != null) {
4913 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4914 if (dllimport_attribute != null) {
4915 flags |= MethodAttributes.PinvokeImpl;
4916 builder = dllimport_attribute.DefinePInvokeMethod (
4917 ec, container.TypeBuilder, method_name, flags,
4918 method.ReturnType, ParameterTypes);
4924 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4925 // We are more strict than Microsoft and report CS0626 like error
4926 if (method.OptAttributes == null ||
4927 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4928 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));
4933 if (builder == null)
4934 builder = container.TypeBuilder.DefineMethod (
4935 method_name, flags, method.CallingConventions,
4936 method.ReturnType, ParameterTypes);
4938 builder.SetGenericMethodSignature (
4939 flags, method.CallingConventions,
4940 method.ReturnType, ParameterTypes);
4946 public void Emit (TypeContainer container, Attributable kind)
4949 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4950 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4952 ec = method.CreateEmitContext (container, null);
4954 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container.Parent) != null)
4955 ec.TestObsoleteMethodUsage = false;
4957 Location loc = method.Location;
4958 Attributes OptAttributes = method.OptAttributes;
4960 if (OptAttributes != null)
4961 OptAttributes.Emit (ec, kind);
4963 if (member is MethodCore)
4964 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4966 SymbolWriter sw = CodeGen.SymbolWriter;
4967 ToplevelBlock block = method.Block;
4970 // abstract or extern methods have no bodies
4972 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4977 // abstract or extern methods have no bodies.
4979 if ((modifiers & Modifiers.ABSTRACT) != 0)
4981 500, method.Location, "Abstract method `" +
4982 TypeManager.CSharpSignature (builder) +
4983 "' can not have a body");
4985 if ((modifiers & Modifiers.EXTERN) != 0)
4987 179, method.Location, "External method `" +
4988 TypeManager.CSharpSignature (builder) +
4989 "' can not have a body");
4995 // Methods must have a body unless they're extern or abstract
4997 if (block == null) {
4999 501, method.Location, "Method `" +
5000 TypeManager.CSharpSignature (builder) +
5001 "' must declare a body since it is not marked " +
5002 "abstract or extern");
5006 SourceMethod source = SourceMethod.Create (
5007 container, MethodBuilder, method.Block);
5010 // Handle destructors specially
5012 // FIXME: This code generates buggy code
5014 if (member is Destructor)
5015 EmitDestructor (ec, block);
5017 ec.EmitTopBlock (block, ParameterInfo, loc);
5020 source.CloseMethod ();
5023 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5025 ILGenerator ig = ec.ig;
5027 Label finish = ig.DefineLabel ();
5029 block.SetDestructor ();
5031 ig.BeginExceptionBlock ();
5032 ec.ReturnLabel = finish;
5033 ec.HasReturnLabel = true;
5034 ec.EmitTopBlock (block, null, method.Location);
5036 // ig.MarkLabel (finish);
5037 ig.BeginFinallyBlock ();
5039 if (ec.ContainerType.BaseType != null) {
5040 Expression member_lookup = Expression.MemberLookup (
5041 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5042 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5044 if (member_lookup != null){
5045 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
5047 ig.Emit (OpCodes.Ldarg_0);
5048 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
5052 ig.EndExceptionBlock ();
5053 //ig.MarkLabel (ec.ReturnLabel);
5054 ig.Emit (OpCodes.Ret);
5058 public class Destructor : Method {
5060 public Destructor (TypeContainer ds, Expression return_type, int mod, string name,
5061 Parameters parameters, Attributes attrs, Location l)
5062 : base (ds, null, return_type, mod, false, new MemberName (name),
5063 parameters, attrs, l)
5066 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5068 if (a.Type == TypeManager.conditional_attribute_type) {
5069 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
5073 base.ApplyAttributeBuilder (a, cb);
5077 abstract public class MemberBase : MemberCore {
5078 public Expression Type;
5080 public MethodAttributes flags;
5082 protected readonly int explicit_mod_flags;
5085 // The "short" name of this property / indexer / event. This is the
5086 // name without the explicit interface.
5088 public string ShortName;
5091 // The type of this property / indexer / event
5093 public Type MemberType;
5096 // If true, this is an explicit interface implementation
5098 public bool IsExplicitImpl = false;
5101 // The name of the interface we are explicitly implementing
5103 public MemberName ExplicitInterfaceName = null;
5106 // Whether this is an interface member.
5108 public bool IsInterface;
5111 // If true, the interface type we are explicitly implementing
5113 public Type InterfaceType = null;
5116 // The constructor is only exposed to our children
5118 protected MemberBase (TypeContainer parent, Expression type, int mod,
5119 int allowed_mod, int def_mod, MemberName name,
5120 Attributes attrs, Location loc)
5121 : base (parent, name, attrs, loc)
5123 explicit_mod_flags = mod;
5125 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
5127 // Check for explicit interface implementation
5128 if (MemberName.Left != null) {
5129 ExplicitInterfaceName = MemberName.Left;
5130 ShortName = MemberName.Name;
5131 IsExplicitImpl = true;
5136 protected virtual bool CheckBase ()
5138 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5139 Report.Error (666, Location, "Protected member in struct declaration");
5143 if ((RootContext.WarningLevel >= 4) &&
5144 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5145 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5146 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5147 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
5153 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5155 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5159 foreach (Type partype in parameters){
5160 if (partype == TypeManager.void_type) {
5162 1547, Location, "Keyword 'void' cannot " +
5163 "be used in this context");
5167 if (partype.IsPointer){
5170 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5174 if (ds.AsAccessible (partype, ModFlags))
5177 if (this is Indexer)
5178 Report.Error (55, Location,
5179 "Inconsistent accessibility: parameter type `" +
5180 TypeManager.CSharpName (partype) + "' is less " +
5181 "accessible than indexer `" + Name + "'");
5182 else if ((this is Method) && ((Method) this).IsOperator)
5183 Report.Error (57, Location,
5184 "Inconsistent accessibility: parameter type `" +
5185 TypeManager.CSharpName (partype) + "' is less " +
5186 "accessible than operator `" + Name + "'");
5188 Report.Error (51, Location,
5189 "Inconsistent accessibility: parameter type `" +
5190 TypeManager.CSharpName (partype) + "' is less " +
5191 "accessible than method `" + Name + "'");
5198 protected virtual bool DoDefineBase ()
5200 EmitContext ec = Parent.EmitContext;
5202 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5205 throw new InternalErrorException ();
5208 ModFlags = Modifiers.PUBLIC |
5209 Modifiers.ABSTRACT |
5210 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5212 flags = MethodAttributes.Public |
5213 MethodAttributes.Abstract |
5214 MethodAttributes.HideBySig |
5215 MethodAttributes.NewSlot |
5216 MethodAttributes.Virtual;
5218 if (!Parent.MethodModifiersValid (ModFlags, Name, Location))
5221 flags = Modifiers.MethodAttr (ModFlags);
5227 protected virtual bool DoDefine (DeclSpace decl)
5229 EmitContext ec = decl.EmitContext;
5231 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5233 ec.InUnsafe = InUnsafe;
5235 // Lookup Type, verify validity
5236 bool old_unsafe = ec.InUnsafe;
5237 ec.InUnsafe = InUnsafe;
5238 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
5239 ec.InUnsafe = old_unsafe;
5244 MemberType = texpr.Type;
5246 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5247 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5248 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5253 // verify accessibility
5254 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5255 if (this is Property)
5256 Report.Error (53, Location,
5257 "Inconsistent accessibility: property type `" +
5258 TypeManager.CSharpName (MemberType) + "' is less " +
5259 "accessible than property `" + Name + "'");
5260 else if (this is Indexer)
5261 Report.Error (54, Location,
5262 "Inconsistent accessibility: indexer return type `" +
5263 TypeManager.CSharpName (MemberType) + "' is less " +
5264 "accessible than indexer `" + Name + "'");
5265 else if (this is Method) {
5266 if (((Method) this).IsOperator)
5267 Report.Error (56, Location,
5268 "Inconsistent accessibility: return type `" +
5269 TypeManager.CSharpName (MemberType) + "' is less " +
5270 "accessible than operator `" + Name + "'");
5272 Report.Error (50, Location,
5273 "Inconsistent accessibility: return type `" +
5274 TypeManager.CSharpName (MemberType) + "' is less " +
5275 "accessible than method `" + Name + "'");
5277 Report.Error (52, Location,
5278 "Inconsistent accessibility: field type `" +
5279 TypeManager.CSharpName (MemberType) + "' is less " +
5280 "accessible than field `" + Name + "'");
5284 if (MemberType.IsPointer && !UnsafeOK (Parent))
5287 if (IsExplicitImpl) {
5288 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
5289 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5290 if (iface_texpr == null)
5293 InterfaceType = iface_texpr.Type;
5295 if (InterfaceType.IsClass) {
5296 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", ExplicitInterfaceName);
5300 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5303 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5310 /// The name of the member can be changed during definition (see IndexerName attribute)
5312 protected virtual void UpdateMemberName ()
5314 MemberName.Name = ShortName;
5317 public override string GetSignatureForError (TypeContainer tc)
5319 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5322 protected bool IsTypePermitted ()
5324 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5325 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5331 protected override bool VerifyClsCompliance(DeclSpace ds)
5333 if (base.VerifyClsCompliance (ds)) {
5337 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5338 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5343 protected override void VerifyObsoleteAttribute()
5345 CheckUsageOfObsoleteAttribute (MemberType);
5350 // Fields and Events both generate FieldBuilders, we use this to share
5351 // their common bits. This is also used to flag usage of the field
5353 abstract public class FieldBase : MemberBase {
5354 public FieldBuilder FieldBuilder;
5355 public Status status;
5358 public enum Status : byte {
5363 static string[] attribute_targets = new string [] { "field" };
5366 /// Symbol with same name in parent class/struct
5368 public MemberInfo conflict_symbol;
5371 // The constructor is only exposed to our children
5373 protected FieldBase (TypeContainer parent, Expression type, int mod,
5374 int allowed_mod, MemberName name, object init,
5375 Attributes attrs, Location loc)
5376 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5382 public override AttributeTargets AttributeTargets {
5384 return AttributeTargets.Field;
5388 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5390 if (a.Type == TypeManager.marshal_as_attr_type) {
5391 UnmanagedMarshal marshal = a.GetMarshal (this);
5392 if (marshal != null) {
5393 FieldBuilder.SetMarshal (marshal);
5398 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5399 a.Error_InvalidSecurityParent ();
5403 FieldBuilder.SetCustomAttribute (cb);
5407 // Whether this field has an initializer.
5409 public bool HasInitializer {
5411 return init != null;
5415 protected readonly Object init;
5417 Expression init_expr;
5418 bool init_expr_initialized = false;
5420 protected override bool CheckGenericOverride (MethodInfo method, string name)
5426 // Resolves and returns the field initializer.
5428 public Expression GetInitializerExpression (EmitContext ec)
5430 if (init_expr_initialized)
5434 if (init is Expression)
5435 e = (Expression) init;
5437 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5439 ec.IsFieldInitializer = true;
5440 e = e.DoResolve (ec);
5441 ec.IsFieldInitializer = false;
5444 init_expr_initialized = true;
5449 protected override bool CheckBase ()
5451 if (!base.CheckBase ())
5458 conflict_symbol = Parent.FindMemberWithSameName (Name, false);
5459 if (conflict_symbol == null) {
5460 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5461 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5466 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5467 Report.SymbolRelatedToPreviousError (conflict_symbol);
5468 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5474 protected override bool DoDefine (DeclSpace ds)
5476 if (!base.DoDefine (ds))
5479 if (MemberType == TypeManager.void_type) {
5480 Report.Error (1547, Location,
5481 "Keyword 'void' cannot be used in this context");
5487 public override string GetSignatureForError ()
5489 if (FieldBuilder == null) {
5490 return base.GetSignatureForError (Parent);
5492 return TypeManager.GetFullNameSignature (FieldBuilder);
5495 public override string[] ValidAttributeTargets {
5497 return attribute_targets;
5501 protected override bool VerifyClsCompliance (DeclSpace ds)
5503 if (!base.VerifyClsCompliance (ds))
5506 if (FieldBuilder == null) {
5510 if (!AttributeTester.IsClsCompliant (FieldBuilder.FieldType)) {
5511 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5517 public void SetAssigned ()
5519 status |= Status.ASSIGNED;
5523 public abstract class FieldMember: FieldBase
5525 bool has_field_offset = false;
5527 protected FieldMember (TypeContainer parent, Expression type, int mod,
5528 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5529 : base (parent, type, mod, allowed_mod, name, init, attrs, loc)
5533 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5535 if (a.Type == TypeManager.field_offset_attribute_type)
5537 has_field_offset = true;
5539 if (!Parent.HasExplicitLayout) {
5540 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5544 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5545 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5549 base.ApplyAttributeBuilder (a, cb);
5553 public override bool Define()
5555 EmitContext ec = Parent.EmitContext;
5557 throw new InternalErrorException ("FieldMember.Define called too early");
5559 bool old_unsafe = ec.InUnsafe;
5560 ec.InUnsafe = InUnsafe;
5561 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
5562 ec.InUnsafe = old_unsafe;
5566 MemberType = texpr.Type;
5571 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5572 Report.Error (52, Location,
5573 "Inconsistent accessibility: field type `" +
5574 TypeManager.CSharpName (MemberType) + "' is less " +
5575 "accessible than field `" + Name + "'");
5579 if (!IsTypePermitted ())
5582 if (MemberType.IsPointer && !UnsafeOK (Parent))
5588 public override void Emit ()
5590 if (Parent.HasExplicitLayout && !has_field_offset && (ModFlags & Modifiers.STATIC) == 0) {
5591 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5599 // The Field class is used to represents class/struct fields during parsing.
5601 public class Field : FieldMember {
5603 // Modifiers allowed in a class declaration
5605 const int AllowedModifiers =
5608 Modifiers.PROTECTED |
5609 Modifiers.INTERNAL |
5612 Modifiers.VOLATILE |
5616 public Field (TypeContainer parent, Expression type, int mod, string name,
5617 Object expr_or_array_init, Attributes attrs, Location loc)
5618 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5619 expr_or_array_init, attrs, loc)
5623 public override bool Define ()
5625 if (!base.Define ())
5628 if (RootContext.WarningLevel > 1){
5629 Type ptype = Parent.TypeBuilder.BaseType;
5631 // ptype is only null for System.Object while compiling corlib.
5633 TypeContainer.FindMembers (
5634 ptype, MemberTypes.Method,
5635 BindingFlags.Public |
5636 BindingFlags.Static | BindingFlags.Instance,
5637 System.Type.FilterName, Name);
5641 if ((ModFlags & Modifiers.VOLATILE) != 0){
5642 if (!MemberType.IsClass){
5643 Type vt = MemberType;
5645 if (TypeManager.IsEnumType (vt))
5646 vt = TypeManager.EnumToUnderlying (MemberType);
5648 if (!((vt == TypeManager.bool_type) ||
5649 (vt == TypeManager.sbyte_type) ||
5650 (vt == TypeManager.byte_type) ||
5651 (vt == TypeManager.short_type) ||
5652 (vt == TypeManager.ushort_type) ||
5653 (vt == TypeManager.int32_type) ||
5654 (vt == TypeManager.uint32_type) ||
5655 (vt == TypeManager.char_type) ||
5656 (vt == TypeManager.float_type) ||
5657 (!vt.IsValueType))){
5659 677, Location, Parent.MakeName (Name) +
5660 " A volatile field can not be of type `" +
5661 TypeManager.CSharpName (vt) + "'");
5666 if ((ModFlags & Modifiers.READONLY) != 0){
5669 "A field can not be both volatile and readonly");
5674 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5676 if (Parent.Kind == Kind.Struct &&
5677 ((fa & FieldAttributes.Static) == 0) &&
5678 MemberType == Parent.TypeBuilder &&
5679 !TypeManager.IsBuiltinType (MemberType)){
5680 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5681 "' causes a cycle in the structure layout");
5686 FieldBuilder = Parent.TypeBuilder.DefineField (
5687 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5689 TypeManager.RegisterFieldBase (FieldBuilder, this);
5691 catch (ArgumentException) {
5692 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5699 public override void Emit ()
5701 if (OptAttributes != null) {
5702 EmitContext ec = new EmitContext (
5703 Parent, Location, null, FieldBuilder.FieldType,
5705 OptAttributes.Emit (ec, this);
5713 // `set' and `get' accessors are represented with an Accessor.
5715 public class Accessor {
5717 // Null if the accessor is empty, or a Block if not
5719 public const int AllowedModifiers =
5721 Modifiers.PROTECTED |
5722 Modifiers.INTERNAL |
5725 public ToplevelBlock Block;
5726 public Attributes Attributes;
5727 public Location Location;
5728 public int ModFlags;
5730 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5735 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5740 // Ooouh Martin, templates are missing here.
5741 // When it will be possible move here a lot of child code and template method type.
5742 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5743 protected MethodData method_data;
5744 protected ToplevelBlock block;
5745 protected ListDictionary declarative_security;
5747 // The accessor are created event if they are not wanted.
5748 // But we need them because their names are reserved.
5749 // Field says whether accessor will be emited or not
5750 public readonly bool IsDummy;
5752 protected readonly string prefix;
5754 ReturnParameter return_attributes;
5756 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5757 : base (null, SetupName (prefix, member), null, member.Location)
5759 this.prefix = prefix;
5763 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5765 : base (null, SetupName (prefix, member),
5766 accessor.Attributes, accessor.Location)
5768 this.prefix = prefix;
5769 this.block = accessor.Block;
5772 static MemberName SetupName (string prefix, MemberBase member)
5774 MemberName name = member.MemberName.Clone ();
5775 name.Name = prefix + member.ShortName;
5779 public void UpdateName (MemberBase member)
5781 MemberName.Name = prefix + member.ShortName;
5784 #region IMethodData Members
5786 public ToplevelBlock Block {
5796 public CallingConventions CallingConventions {
5798 return CallingConventions.Standard;
5802 public bool IsExcluded (EmitContext ec)
5807 GenericMethod IMethodData.GenericMethod {
5813 public MemberName MethodName {
5819 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5820 public abstract Type[] ParameterTypes { get; }
5821 public abstract Type ReturnType { get; }
5822 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5826 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5828 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5829 a.Type == TypeManager.conditional_attribute_type) {
5830 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 ());
5834 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5835 if (declarative_security == null)
5836 declarative_security = new ListDictionary ();
5837 a.ExtractSecurityPermissionSet (declarative_security);
5841 if (a.Target == AttributeTargets.Method) {
5842 method_data.MethodBuilder.SetCustomAttribute (cb);
5846 if (a.Target == AttributeTargets.ReturnValue) {
5847 if (return_attributes == null)
5848 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5850 return_attributes.ApplyAttributeBuilder (a, cb);
5854 ApplyToExtraTarget (a, cb);
5857 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5859 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5862 public override bool Define()
5867 public virtual void Emit (TypeContainer container)
5869 method_data.Emit (container, this);
5871 if (declarative_security != null) {
5872 foreach (DictionaryEntry de in declarative_security) {
5873 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5880 public override bool IsClsCompliaceRequired(DeclSpace ds)
5885 public bool IsDuplicateImplementation (MethodCore method)
5887 if (Name != method.Name)
5890 Type[] param_types = method.ParameterTypes;
5892 if (param_types.Length != ParameterTypes.Length)
5895 for (int i = 0; i < param_types.Length; i++)
5896 if (param_types [i] != ParameterTypes [i])
5899 Report.SymbolRelatedToPreviousError (method);
5900 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with " +
5901 "the same parameter types", Parent.Name, Name);
5905 public new Location Location {
5907 return base.Location;
5911 protected override void VerifyObsoleteAttribute()
5918 // Properties and Indexers both generate PropertyBuilders, we use this to share
5919 // their common bits.
5921 abstract public class PropertyBase : MethodCore {
5923 public class GetMethod: PropertyMethod
5925 static string[] attribute_targets = new string [] { "method", "return" };
5927 public GetMethod (MethodCore method):
5928 base (method, "get_")
5932 public GetMethod (MethodCore method, Accessor accessor):
5933 base (method, accessor, "get_")
5937 public override MethodBuilder Define(TypeContainer container)
5939 base.Define (container);
5941 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5943 if (!method_data.Define (container))
5946 return method_data.MethodBuilder;
5949 public override string GetSignatureForError (TypeContainer tc)
5951 return String.Concat (base.GetSignatureForError (tc), ".get");
5954 public override Type ReturnType {
5956 return method.MemberType;
5960 public override string[] ValidAttributeTargets {
5962 return attribute_targets;
5967 public class SetMethod: PropertyMethod {
5969 static string[] attribute_targets = new string [] { "method", "param", "return" };
5970 ImplicitParameter param_attr;
5972 public SetMethod (MethodCore method):
5973 base (method, "set_")
5977 public SetMethod (MethodCore method, Accessor accessor):
5978 base (method, accessor, "set_")
5982 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5984 if (a.Target == AttributeTargets.Parameter) {
5985 if (param_attr == null)
5986 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5988 param_attr.ApplyAttributeBuilder (a, cb);
5992 base.ApplyAttributeBuilder (a, cb);
5995 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5997 Parameter [] parms = new Parameter [1];
5998 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
5999 Parameters parameters = new Parameters (parms, null, method.Location);
6000 Type [] types = parameters.GetParameterInfo (ec);
6001 return new InternalParameters (types, parameters);
6004 public override MethodBuilder Define(TypeContainer container)
6006 if (container.EmitContext == null)
6007 throw new InternalErrorException ("SetMethod.Define called too early");
6009 base.Define (container);
6011 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6013 if (!method_data.Define (container))
6016 return method_data.MethodBuilder;
6019 public override string GetSignatureForError (TypeContainer tc)
6021 return String.Concat (base.GetSignatureForError (tc), ".set");
6024 public override Type[] ParameterTypes {
6026 return new Type[] { method.MemberType };
6030 public override Type ReturnType {
6032 return TypeManager.void_type;
6036 public override string[] ValidAttributeTargets {
6038 return attribute_targets;
6043 static string[] attribute_targets = new string [] { "property" };
6045 public abstract class PropertyMethod: AbstractPropertyEventMethod {
6046 protected readonly MethodCore method;
6047 protected MethodAttributes flags;
6049 public PropertyMethod (MethodCore method, string prefix)
6050 : base (method, prefix)
6052 this.method = method;
6055 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6056 : base (method, accessor, prefix)
6058 this.method = method;
6059 this.ModFlags = accessor.ModFlags;
6061 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6062 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
6063 Environment.Exit (1);
6067 public override AttributeTargets AttributeTargets {
6069 return AttributeTargets.Method;
6073 public override bool IsClsCompliaceRequired(DeclSpace ds)
6075 return method.IsClsCompliaceRequired (ds);
6078 public InternalParameters ParameterInfo
6081 return method_data.ParameterInfo;
6085 public virtual MethodBuilder Define (TypeContainer container)
6088 // Check for custom access modifier
6090 if (ModFlags == 0) {
6091 ModFlags = method.ModFlags;
6092 flags = method.flags;
6094 CheckModifiers (container, ModFlags);
6095 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6096 flags = Modifiers.MethodAttr (ModFlags);
6097 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6104 public override Type[] ParameterTypes {
6106 return TypeManager.NoTypes;
6110 public override EmitContext CreateEmitContext (TypeContainer tc,
6113 return new EmitContext (
6114 tc, method.ds, method.Location, ig, ReturnType,
6115 method.ModFlags, false);
6118 public override ObsoleteAttribute GetObsoleteAttribute ()
6120 return method.GetObsoleteAttribute (method.ds);
6123 public override string GetSignatureForError (TypeContainer tc)
6125 return String.Concat (tc.Name, '.', method.Name);
6128 void CheckModifiers (TypeContainer container, int modflags)
6131 int mflags = method.ModFlags & Modifiers.Accessibility;
6133 if ((mflags & Modifiers.PUBLIC) != 0) {
6134 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6136 else if ((mflags & Modifiers.PROTECTED) != 0) {
6137 if ((mflags & Modifiers.INTERNAL) != 0)
6138 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6140 flags |= Modifiers.PRIVATE;
6142 else if ((mflags & Modifiers.INTERNAL) != 0)
6143 flags |= Modifiers.PRIVATE;
6145 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6146 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6147 GetSignatureForError (container));
6151 public PropertyMethod Get, Set;
6152 public PropertyBuilder PropertyBuilder;
6153 public MethodBuilder GetBuilder, SetBuilder;
6155 protected EmitContext ec;
6157 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6158 int allowed_mod, bool is_iface, MemberName name,
6159 Parameters parameters, Attributes attrs,
6161 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6162 attrs, parameters, loc)
6166 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6168 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6169 a.Error_InvalidSecurityParent ();
6173 PropertyBuilder.SetCustomAttribute (cb);
6176 public override AttributeTargets AttributeTargets {
6178 return AttributeTargets.Property;
6182 public override bool Define ()
6184 if (!DoDefine (Parent))
6187 if (!IsTypePermitted ())
6193 protected override bool DoDefine (DeclSpace ds)
6195 if (!base.DoDefine (ds))
6199 // Accessors modifiers check
6201 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6202 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6203 GetSignatureForError ());
6207 if ((Get.IsDummy || Set.IsDummy)
6208 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6209 Report.Error (276, Location,
6210 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6211 GetSignatureForError ());
6215 if (MemberType.IsAbstract && MemberType.IsSealed) {
6216 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6220 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6224 public override string GetSignatureForError()
6226 if (PropertyBuilder == null)
6227 return GetSignatureForError (Parent);
6229 return TypeManager.CSharpSignature (PropertyBuilder, false);
6233 protected override bool CheckForDuplications ()
6235 ArrayList ar = Parent.Indexers;
6237 int arLen = ar.Count;
6239 for (int i = 0; i < arLen; i++) {
6240 Indexer m = (Indexer) ar [i];
6241 if (IsDuplicateImplementation (m))
6246 ar = Parent.Properties;
6248 int arLen = ar.Count;
6250 for (int i = 0; i < arLen; i++) {
6251 Property m = (Property) ar [i];
6252 if (IsDuplicateImplementation (m))
6260 // TODO: rename to Resolve......
6261 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
6263 PropertyInfo parent_property = container.ParentCache.FindMemberToOverride (
6264 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6266 if (parent_property == null)
6269 parent_ret_type = parent_property.PropertyType;
6270 MethodInfo get_accessor = parent_property.GetGetMethod (true);
6271 MethodInfo set_accessor = parent_property.GetSetMethod (true);
6272 MethodAttributes get_accessor_access, set_accessor_access;
6274 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6275 if (Get != null && !Get.IsDummy && get_accessor == null) {
6276 Report.SymbolRelatedToPreviousError (parent_property);
6277 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
6280 if (Set != null && !Set.IsDummy && set_accessor == null) {
6281 Report.SymbolRelatedToPreviousError (parent_property);
6282 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
6287 // Check parent accessors access
6289 get_accessor_access = set_accessor_access = 0;
6290 if ((ModFlags & Modifiers.NEW) == 0) {
6291 if (get_accessor != null) {
6292 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6293 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6295 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6296 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6297 GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
6300 if (set_accessor != null) {
6301 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6302 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6304 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6305 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6306 GetSignatureForError (container), TypeManager.GetFullNameSignature (parent_property));
6311 // Get the less restrictive access
6313 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6316 public override void Emit ()
6319 // The PropertyBuilder can be null for explicit implementations, in that
6320 // case, we do not actually emit the ".property", so there is nowhere to
6321 // put the attribute
6323 if (PropertyBuilder != null && OptAttributes != null)
6324 OptAttributes.Emit (ec, this);
6336 /// Tests whether accessors are not in collision with some method (CS0111)
6338 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6340 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6343 protected override void UpdateMemberName ()
6345 base.UpdateMemberName ();
6347 Get.UpdateName (this);
6348 Set.UpdateName (this);
6352 public override string[] ValidAttributeTargets {
6354 return attribute_targets;
6359 public class Property : PropertyBase, IIteratorContainer {
6360 const int AllowedModifiers =
6363 Modifiers.PROTECTED |
6364 Modifiers.INTERNAL |
6368 Modifiers.OVERRIDE |
6369 Modifiers.ABSTRACT |
6372 Modifiers.METHOD_YIELDS |
6375 const int AllowedInterfaceModifiers =
6378 public Property (TypeContainer parent, Expression type, int mod_flags,
6379 bool is_iface, MemberName name, Attributes attrs,
6380 Accessor get_block, Accessor set_block, Location loc)
6381 : base (parent, type, mod_flags,
6382 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6383 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6386 if (get_block == null)
6387 Get = new GetMethod (this);
6389 Get = new GetMethod (this, get_block);
6391 if (set_block == null)
6392 Set = new SetMethod (this);
6394 Set = new SetMethod (this, set_block);
6397 public override bool Define ()
6399 if (!DoDefineBase ())
6402 if (!base.Define ())
6408 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6412 GetBuilder = Get.Define (Parent);
6413 if (GetBuilder == null)
6417 // Setup iterator if we are one
6419 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6420 Iterator iterator = new Iterator (
6421 Parent, "get", MemberType,
6422 TypeManager.NoTypes, Get.ParameterInfo,
6423 ModFlags, Get.Block, Location);
6425 if (!iterator.DefineIterator ())
6427 Get.Block = iterator.Block;
6432 SetBuilder = Set.Define (Parent);
6433 if (SetBuilder == null)
6436 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6439 // FIXME - PropertyAttributes.HasDefault ?
6441 PropertyAttributes prop_attr = PropertyAttributes.None;
6443 prop_attr |= PropertyAttributes.RTSpecialName |
6444 PropertyAttributes.SpecialName;
6446 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6447 Name, prop_attr, MemberType, null);
6450 PropertyBuilder.SetGetMethod (GetBuilder);
6453 PropertyBuilder.SetSetMethod (SetBuilder);
6455 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6459 public void SetYields ()
6461 ModFlags |= Modifiers.METHOD_YIELDS;
6466 /// Gigantic workaround for lameness in SRE follows :
6467 /// This class derives from EventInfo and attempts to basically
6468 /// wrap around the EventBuilder so that FindMembers can quickly
6469 /// return this in it search for members
6471 public class MyEventBuilder : EventInfo {
6474 // We use this to "point" to our Builder which is
6475 // not really a MemberInfo
6477 EventBuilder MyBuilder;
6480 // We "catch" and wrap these methods
6482 MethodInfo raise, remove, add;
6484 EventAttributes attributes;
6485 Type declaring_type, reflected_type, event_type;
6490 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6492 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6494 // And now store the values in our own fields.
6496 declaring_type = type_builder;
6498 reflected_type = type_builder;
6500 attributes = event_attr;
6503 this.event_type = event_type;
6507 // Methods that you have to override. Note that you only need
6508 // to "implement" the variants that take the argument (those are
6509 // the "abstract" methods, the others (GetAddMethod()) are
6512 public override MethodInfo GetAddMethod (bool nonPublic)
6517 public override MethodInfo GetRemoveMethod (bool nonPublic)
6522 public override MethodInfo GetRaiseMethod (bool nonPublic)
6528 // These methods make "MyEventInfo" look like a Builder
6530 public void SetRaiseMethod (MethodBuilder raiseMethod)
6532 raise = raiseMethod;
6533 MyBuilder.SetRaiseMethod (raiseMethod);
6536 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6538 remove = removeMethod;
6539 MyBuilder.SetRemoveOnMethod (removeMethod);
6542 public void SetAddOnMethod (MethodBuilder addMethod)
6545 MyBuilder.SetAddOnMethod (addMethod);
6548 public void SetCustomAttribute (CustomAttributeBuilder cb)
6550 MyBuilder.SetCustomAttribute (cb);
6553 public override object [] GetCustomAttributes (bool inherit)
6555 // FIXME : There's nothing which can be seemingly done here because
6556 // we have no way of getting at the custom attribute objects of the
6561 public override object [] GetCustomAttributes (Type t, bool inherit)
6563 // FIXME : Same here !
6567 public override bool IsDefined (Type t, bool b)
6572 public override EventAttributes Attributes {
6578 public override string Name {
6584 public override Type DeclaringType {
6586 return declaring_type;
6590 public override Type ReflectedType {
6592 return reflected_type;
6596 public Type EventType {
6602 public void SetUsed ()
6604 if (my_event != null)
6605 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6610 /// For case when event is declared like property (with add and remove accessors).
6612 public class EventProperty: Event {
6614 static string[] attribute_targets = new string [] { "event", "property" };
6616 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6617 bool is_iface, MemberName name, Object init,
6618 Attributes attrs, Accessor add, Accessor remove,
6620 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6622 Add = new AddDelegateMethod (this, add);
6623 Remove = new RemoveDelegateMethod (this, remove);
6626 public override string[] ValidAttributeTargets {
6628 return attribute_targets;
6634 /// Event is declared like field.
6636 public class EventField: Event {
6638 static string[] attribute_targets = new string [] { "event", "field", "method" };
6640 public EventField (TypeContainer parent, Expression type, int mod_flags,
6641 bool is_iface, MemberName name, Object init,
6642 Attributes attrs, Location loc)
6643 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6645 Add = new AddDelegateMethod (this);
6646 Remove = new RemoveDelegateMethod (this);
6649 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6651 if (a.Target == AttributeTargets.Field) {
6652 FieldBuilder.SetCustomAttribute (cb);
6656 if (a.Target == AttributeTargets.Method) {
6657 AddBuilder.SetCustomAttribute (cb);
6658 RemoveBuilder.SetCustomAttribute (cb);
6662 base.ApplyAttributeBuilder (a, cb);
6665 public override string[] ValidAttributeTargets {
6667 return attribute_targets;
6672 public abstract class Event : FieldBase {
6674 protected sealed class AddDelegateMethod: DelegateMethod
6677 public AddDelegateMethod (Event method):
6678 base (method, "add_")
6682 public AddDelegateMethod (Event method, Accessor accessor):
6683 base (method, accessor, "add_")
6687 protected override MethodInfo DelegateMethodInfo {
6689 return TypeManager.delegate_combine_delegate_delegate;
6695 protected sealed class RemoveDelegateMethod: DelegateMethod
6697 public RemoveDelegateMethod (Event method):
6698 base (method, "remove_")
6702 public RemoveDelegateMethod (Event method, Accessor accessor):
6703 base (method, accessor, "remove_")
6707 protected override MethodInfo DelegateMethodInfo {
6709 return TypeManager.delegate_remove_delegate_delegate;
6715 public abstract class DelegateMethod: AbstractPropertyEventMethod
6717 protected readonly Event method;
6718 ImplicitParameter param_attr;
6720 static string[] attribute_targets = new string [] { "method", "param", "return" };
6722 public DelegateMethod (Event method, string prefix)
6723 : base (method, prefix)
6725 this.method = method;
6728 public DelegateMethod (Event method, Accessor accessor, string prefix)
6729 : base (method, accessor, prefix)
6731 this.method = method;
6734 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6736 if (a.Target == AttributeTargets.Parameter) {
6737 if (param_attr == null)
6738 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6740 param_attr.ApplyAttributeBuilder (a, cb);
6744 base.ApplyAttributeBuilder (a, cb);
6747 public override AttributeTargets AttributeTargets {
6749 return AttributeTargets.Method;
6753 public override bool IsClsCompliaceRequired(DeclSpace ds)
6755 return method.IsClsCompliaceRequired (ds);
6758 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6760 method_data = new MethodData (method, ip, method.ModFlags,
6761 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6763 if (!method_data.Define (container))
6766 MethodBuilder mb = method_data.MethodBuilder;
6767 mb.DefineParameter (1, ParameterAttributes.None, "value");
6772 public override void Emit (TypeContainer tc)
6774 if (block != null) {
6779 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6780 EmitContext ec = CreateEmitContext (tc, ig);
6781 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6783 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6784 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6785 ig.Emit (OpCodes.Ldsfld, field_info);
6786 ig.Emit (OpCodes.Ldarg_0);
6787 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6788 ig.Emit (OpCodes.Castclass, method.MemberType);
6789 ig.Emit (OpCodes.Stsfld, field_info);
6791 ig.Emit (OpCodes.Ldarg_0);
6792 ig.Emit (OpCodes.Ldarg_0);
6793 ig.Emit (OpCodes.Ldfld, field_info);
6794 ig.Emit (OpCodes.Ldarg_1);
6795 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6796 ig.Emit (OpCodes.Castclass, method.MemberType);
6797 ig.Emit (OpCodes.Stfld, field_info);
6799 ig.Emit (OpCodes.Ret);
6802 protected abstract MethodInfo DelegateMethodInfo { get; }
6804 public override Type[] ParameterTypes {
6806 return new Type[] { method.MemberType };
6810 public override Type ReturnType {
6812 return TypeManager.void_type;
6816 public override EmitContext CreateEmitContext (TypeContainer tc,
6819 return new EmitContext (
6820 tc, method.Parent, Location, ig, ReturnType,
6821 method.ModFlags, false);
6824 public override string GetSignatureForError (TypeContainer tc)
6826 return String.Concat (tc.Name, '.', method.Name);
6829 public override ObsoleteAttribute GetObsoleteAttribute ()
6831 return method.GetObsoleteAttribute (method.Parent);
6834 public override string[] ValidAttributeTargets {
6836 return attribute_targets;
6842 const int AllowedModifiers =
6845 Modifiers.PROTECTED |
6846 Modifiers.INTERNAL |
6851 Modifiers.OVERRIDE |
6855 const int AllowedInterfaceModifiers =
6858 public DelegateMethod Add, Remove;
6859 public MyEventBuilder EventBuilder;
6860 public MethodBuilder AddBuilder, RemoveBuilder;
6862 MethodData AddData, RemoveData;
6864 public Event (TypeContainer parent, Expression type, int mod_flags,
6865 bool is_iface, MemberName name, Object init, Attributes attrs,
6867 : base (parent, type, mod_flags,
6868 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6869 name, init, attrs, loc)
6871 IsInterface = is_iface;
6874 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6876 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6877 a.Error_InvalidSecurityParent ();
6881 EventBuilder.SetCustomAttribute (cb);
6884 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6886 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6889 public override AttributeTargets AttributeTargets {
6891 return AttributeTargets.Event;
6895 public override bool Define ()
6897 EventAttributes e_attr;
6898 e_attr = EventAttributes.None;
6900 if (!DoDefineBase ())
6903 if (!DoDefine (Parent))
6906 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6907 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6908 "': abstract event can not have an initializer");
6912 if (!TypeManager.IsDelegateType (MemberType)) {
6913 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6914 "' : event must be of a delegate type");
6918 EmitContext ec = Parent.EmitContext;
6920 throw new InternalErrorException ("Event.Define called too early?");
6921 bool old_unsafe = ec.InUnsafe;
6922 ec.InUnsafe = InUnsafe;
6924 Parameter [] parms = new Parameter [1];
6925 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6926 Parameters parameters = new Parameters (parms, null, Location);
6927 Type [] types = parameters.GetParameterInfo (ec);
6928 InternalParameters ip = new InternalParameters (types, parameters);
6930 ec.InUnsafe = old_unsafe;
6936 // Now define the accessors
6939 AddBuilder = Add.Define (Parent, ip);
6940 if (AddBuilder == null)
6943 RemoveBuilder = Remove.Define (Parent, ip);
6944 if (RemoveBuilder == null)
6947 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6949 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6950 FieldBuilder = Parent.TypeBuilder.DefineField (
6952 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6953 TypeManager.RegisterPrivateFieldOfEvent (
6954 (EventInfo) EventBuilder, FieldBuilder);
6955 TypeManager.RegisterFieldBase (FieldBuilder, this);
6958 EventBuilder.SetAddOnMethod (AddBuilder);
6959 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6961 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6965 protected override bool CheckBase ()
6967 if (!base.CheckBase ())
6970 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6971 if (!(conflict_symbol is EventInfo)) {
6972 Report.SymbolRelatedToPreviousError (conflict_symbol);
6973 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6981 public override void Emit ()
6983 if (OptAttributes != null) {
6984 EmitContext ec = new EmitContext (
6985 Parent, Location, null, MemberType, ModFlags);
6986 OptAttributes.Emit (ec, this);
6991 Remove.Emit (Parent);
6997 public override string GetSignatureForError ()
6999 if (EventBuilder == null)
7000 return base.GetSignatureForError (Parent);
7002 return TypeManager.GetFullNameSignature (EventBuilder);
7007 public class Indexer : PropertyBase {
7009 class GetIndexerMethod: GetMethod
7011 public GetIndexerMethod (MethodCore method):
7016 public GetIndexerMethod (MethodCore method, Accessor accessor):
7017 base (method, accessor)
7021 public override Type[] ParameterTypes {
7023 return method.ParameterTypes;
7028 class SetIndexerMethod: SetMethod
7030 readonly Parameters parameters;
7032 public SetIndexerMethod (MethodCore method):
7037 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7038 base (method, accessor)
7040 this.parameters = parameters;
7043 public override Type[] ParameterTypes {
7045 int top = method.ParameterTypes.Length;
7046 Type [] set_pars = new Type [top + 1];
7047 method.ParameterTypes.CopyTo (set_pars, 0);
7048 set_pars [top] = method.MemberType;
7053 protected override InternalParameters GetParameterInfo (EmitContext ec)
7055 Parameter [] fixed_parms = parameters.FixedParameters;
7057 if (fixed_parms == null){
7058 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7059 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7060 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7062 // Here is the problem: the `value' parameter has
7063 // to come *after* the array parameter in the declaration
7065 // X (object [] x, Type value)
7068 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7069 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7073 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7075 fixed_parms.CopyTo (tmp, 0);
7076 tmp [fixed_parms.Length] = new Parameter (
7077 method.Type, "value", Parameter.Modifier.NONE, null);
7079 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7080 Type [] types = set_formal_params.GetParameterInfo (ec);
7082 return new InternalParameters (types, set_formal_params);
7086 const int AllowedModifiers =
7089 Modifiers.PROTECTED |
7090 Modifiers.INTERNAL |
7094 Modifiers.OVERRIDE |
7099 const int AllowedInterfaceModifiers =
7103 // Are we implementing an interface ?
7105 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7106 bool is_iface, Parameters parameters, Attributes attrs,
7107 Accessor get_block, Accessor set_block, Location loc)
7108 : base (parent, type, mod,
7109 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7110 is_iface, name, parameters, attrs, loc)
7112 if (get_block == null)
7113 Get = new GetIndexerMethod (this);
7115 Get = new GetIndexerMethod (this, get_block);
7117 if (set_block == null)
7118 Set = new SetIndexerMethod (this);
7120 Set = new SetIndexerMethod (this, parameters, set_block);
7123 public override bool Define ()
7125 PropertyAttributes prop_attr =
7126 PropertyAttributes.RTSpecialName |
7127 PropertyAttributes.SpecialName;
7129 if (!DoDefineBase ())
7132 if (!base.Define ())
7135 if (OptAttributes != null) {
7136 Attribute indexer_attr = OptAttributes.GetIndexerNameAttribute (ec);
7137 if (indexer_attr != null) {
7138 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7140 if (IsExplicitImpl) {
7141 Report.Error (415, indexer_attr.Location,
7142 "The 'IndexerName' attribute is valid only on an" +
7143 "indexer that is not an explicit interface member declaration");
7147 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7148 Report.Error (609, indexer_attr.Location,
7149 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7153 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7154 Report.Error (633, indexer_attr.Location,
7155 "The argument to the 'IndexerName' attribute must be a valid identifier");
7159 UpdateMemberName ();
7163 if (InterfaceType != null) {
7164 string parent_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7165 if (parent_IndexerName != Name)
7166 ShortName = parent_IndexerName;
7167 UpdateMemberName ();
7170 if (!Parent.AddToMemberContainer (this, true) ||
7171 !Parent.AddToMemberContainer (Get, true) || !Parent.AddToMemberContainer (Set, true))
7177 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7179 GetBuilder = Get.Define (Parent);
7180 if (GetBuilder == null)
7185 SetBuilder = Set.Define (Parent);
7186 if (SetBuilder == null)
7191 // Now name the parameters
7193 Parameter [] p = Parameters.FixedParameters;
7195 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7196 Report.Error (631, Location, "ref and out are not valid in this context");
7202 for (i = 0; i < p.Length; ++i) {
7204 GetBuilder.DefineParameter (
7205 i + 1, p [i].Attributes, p [i].Name);
7208 SetBuilder.DefineParameter (
7209 i + 1, p [i].Attributes, p [i].Name);
7213 SetBuilder.DefineParameter (
7214 i + 1, ParameterAttributes.None, "value");
7216 if (i != ParameterTypes.Length) {
7217 Parameter array_param = Parameters.ArrayParameter;
7219 SetBuilder.DefineParameter (
7220 i + 1, array_param.Attributes, array_param.Name);
7224 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7225 Name, prop_attr, MemberType, ParameterTypes);
7228 PropertyBuilder.SetGetMethod (GetBuilder);
7231 PropertyBuilder.SetSetMethod (SetBuilder);
7233 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7238 public override string GetSignatureForError ()
7240 if (PropertyBuilder == null)
7241 return GetSignatureForError (Parent);
7243 return TypeManager.CSharpSignature (PropertyBuilder, true);
7246 public override string GetSignatureForError(TypeContainer tc)
7248 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7252 public class Operator : MethodCore, IIteratorContainer {
7254 const int AllowedModifiers =
7260 public enum OpType : byte {
7270 // Unary and Binary operators
7293 // Implicit and Explicit
7298 public readonly OpType OperatorType;
7299 public MethodBuilder OperatorMethodBuilder;
7301 public Method OperatorMethod;
7303 static string[] attribute_targets = new string [] { "method", "return" };
7305 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7306 int mod_flags, Parameters parameters,
7307 ToplevelBlock block, Attributes attrs, Location loc)
7308 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7309 new MemberName ("op_" + type), attrs, parameters, loc)
7311 OperatorType = type;
7315 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7317 OperatorMethod.ApplyAttributeBuilder (a, cb);
7320 public override AttributeTargets AttributeTargets {
7322 return AttributeTargets.Method;
7326 protected override bool CheckGenericOverride (MethodInfo method, string name)
7331 protected override bool CheckForDuplications()
7333 ArrayList ar = Parent.Operators;
7335 int arLen = ar.Count;
7337 for (int i = 0; i < arLen; i++) {
7338 Operator o = (Operator) ar [i];
7339 if (IsDuplicateImplementation (o))
7344 ar = Parent.Methods;
7346 int arLen = ar.Count;
7348 for (int i = 0; i < arLen; i++) {
7349 Method m = (Method) ar [i];
7350 if (IsDuplicateImplementation (m))
7358 public override bool Define ()
7360 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7361 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7362 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7369 OperatorMethod = new Method (
7370 Parent, null, Type, ModFlags, false, MemberName,
7371 Parameters, OptAttributes, Location);
7373 OperatorMethod.Block = Block;
7374 OperatorMethod.IsOperator = true;
7375 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7376 OperatorMethod.Define ();
7378 if (OperatorMethod.MethodBuilder == null)
7381 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7383 parameter_types = OperatorMethod.ParameterTypes;
7384 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7385 Type return_type = OperatorMethod.ReturnType;
7386 Type first_arg_type = parameter_types [0];
7391 // Rules for conversion operators
7393 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7394 if (first_arg_type == return_type && first_arg_type == declaring_type){
7397 "User-defined conversion cannot take an object of the " +
7398 "enclosing type and convert to an object of the enclosing" +
7403 if (first_arg_type != declaring_type && return_type != declaring_type){
7406 "User-defined conversion must convert to or from the " +
7411 if (first_arg_type == TypeManager.object_type ||
7412 return_type == TypeManager.object_type){
7415 "User-defined conversion cannot convert to or from " +
7420 if (first_arg_type.IsInterface || return_type.IsInterface){
7423 "User-defined conversion cannot convert to or from an " +
7428 if (first_arg_type.IsSubclassOf (return_type)
7429 || return_type.IsSubclassOf (first_arg_type)){
7430 if (declaring_type.IsSubclassOf (return_type)) {
7431 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7434 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7437 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7438 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7439 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");
7442 } else if (Parameters.FixedParameters.Length == 1) {
7443 // Checks for Unary operators
7445 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7446 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7447 Report.Error (448, Location,
7448 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7451 if (first_arg_type != declaring_type){
7453 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7458 if (first_arg_type != declaring_type){
7461 "The parameter of a unary operator must be the " +
7466 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7467 if (return_type != TypeManager.bool_type){
7470 "The return type of operator True or False " +
7477 // Checks for Binary operators
7479 if (first_arg_type != declaring_type &&
7480 parameter_types [1] != declaring_type){
7483 "One of the parameters of a binary operator must " +
7484 "be the containing type");
7492 public override void Emit ()
7495 // abstract or extern methods have no bodies
7497 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7500 OperatorMethod.Emit ();
7504 // Operator cannot be override
7505 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
7510 public static string GetName (OpType ot)
7513 case OpType.LogicalNot:
7515 case OpType.OnesComplement:
7517 case OpType.Increment:
7519 case OpType.Decrement:
7525 case OpType.Addition:
7527 case OpType.Subtraction:
7529 case OpType.UnaryPlus:
7531 case OpType.UnaryNegation:
7533 case OpType.Multiply:
7535 case OpType.Division:
7537 case OpType.Modulus:
7539 case OpType.BitwiseAnd:
7541 case OpType.BitwiseOr:
7543 case OpType.ExclusiveOr:
7545 case OpType.LeftShift:
7547 case OpType.RightShift:
7549 case OpType.Equality:
7551 case OpType.Inequality:
7553 case OpType.GreaterThan:
7555 case OpType.LessThan:
7557 case OpType.GreaterThanOrEqual:
7559 case OpType.LessThanOrEqual:
7561 case OpType.Implicit:
7563 case OpType.Explicit:
7569 public override string GetSignatureForError (TypeContainer tc)
7571 StringBuilder sb = new StringBuilder ();
7572 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7573 Parameters.FixedParameters [0].GetSignatureForError ());
7575 if (Parameters.FixedParameters.Length > 1) {
7577 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7580 return sb.ToString ();
7583 public override string GetSignatureForError ()
7588 public override string ToString ()
7590 if (OperatorMethod == null)
7593 Type return_type = OperatorMethod.ReturnType;
7594 Type [] param_types = OperatorMethod.ParameterTypes;
7596 if (Parameters.FixedParameters.Length == 1)
7597 return String.Format (
7598 "{0} operator {1}({2})",
7599 TypeManager.CSharpName (return_type),
7600 GetName (OperatorType),
7603 return String.Format (
7604 "{0} operator {1}({2}, {3})",
7605 TypeManager.CSharpName (return_type),
7606 GetName (OperatorType),
7607 param_types [0], param_types [1]);
7610 public override string[] ValidAttributeTargets {
7612 return attribute_targets;
7616 public void SetYields ()
7618 ModFlags |= Modifiers.METHOD_YIELDS;
7623 // This is used to compare method signatures
7625 struct MethodSignature {
7627 public Type RetType;
7628 public Type [] Parameters;
7631 /// This delegate is used to extract methods which have the
7632 /// same signature as the argument
7634 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7636 public MethodSignature (string name, Type ret_type, Type [] parameters)
7641 if (parameters == null)
7642 Parameters = TypeManager.NoTypes;
7644 Parameters = parameters;
7647 public override string ToString ()
7650 if (Parameters.Length != 0){
7651 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7652 for (int i = 0; i < Parameters.Length; i++){
7653 sb.Append (Parameters [i]);
7654 if (i+1 < Parameters.Length)
7657 pars = sb.ToString ();
7660 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7663 public override int GetHashCode ()
7665 return Name.GetHashCode ();
7668 public override bool Equals (Object o)
7670 MethodSignature other = (MethodSignature) o;
7672 if (other.Name != Name)
7675 if (other.RetType != RetType)
7678 if (Parameters == null){
7679 if (other.Parameters == null)
7684 if (other.Parameters == null)
7687 int c = Parameters.Length;
7688 if (other.Parameters.Length != c)
7691 for (int i = 0; i < c; i++)
7692 if (other.Parameters [i] != Parameters [i])
7698 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7700 MethodSignature sig = (MethodSignature) filter_criteria;
7702 if (m.Name != sig.Name)
7706 MethodInfo mi = m as MethodInfo;
7707 PropertyInfo pi = m as PropertyInfo;
7710 ReturnType = mi.ReturnType;
7711 else if (pi != null)
7712 ReturnType = pi.PropertyType;
7717 // we use sig.RetType == null to mean `do not check the
7718 // method return value.
7720 if (sig.RetType != null)
7721 if (ReturnType != sig.RetType)
7726 args = TypeManager.GetArgumentTypes (mi);
7728 args = TypeManager.GetArgumentTypes (pi);
7729 Type [] sigp = sig.Parameters;
7731 if (args.Length != sigp.Length)
7734 for (int i = args.Length; i > 0; ){
7736 if (args [i] != sigp [i])