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.SymbolRelatedToPreviousError (parent.Type);
1073 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1074 TypeManager.CSharpName (parent.Type), GetSignatureForError ());
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 Report.Error (1722, Location,
1102 "In Class `{0}', `{1}' is not " +
1103 "an interface, a base class must be listed first", Name, iface.Name);
1108 for (int x = 0; x < i; x++) {
1109 if (iface.Equals (ifaces [x])) {
1110 Report.Error (528, Location,
1111 "`{0}' is already listed in " +
1112 "interface list", iface.Name);
1118 if ((Kind == Kind.Interface) &&
1119 !iface.AsAccessible (Parent, ModFlags))
1120 Report.Error (61, Location,
1121 "Inconsistent accessibility: base " +
1122 "interface `{0}' is less accessible " +
1123 "than interface `{1}'", iface.Name,
1130 bool CheckGenericInterfaces (Type[] ifaces)
1132 ArrayList already_checked = new ArrayList ();
1134 for (int i = 0; i < ifaces.Length; i++) {
1135 Type iface = ifaces [i];
1136 foreach (Type t in already_checked) {
1140 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t))
1145 "`{0}' cannot implement both `{1}' and `{2}' " +
1146 "because they may unify for some type " +
1147 "parameter substitutions",
1148 TypeManager.GetFullName (TypeBuilder),
1153 already_checked.Add (iface);
1162 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1164 public override TypeBuilder DefineType ()
1171 if (TypeBuilder != null)
1174 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1176 TypeAttributes type_attributes = TypeAttr;
1180 if (TypeManager.NamespaceClash (Name, Location)) {
1185 ModuleBuilder builder = CodeGen.Module.Builder;
1186 TypeBuilder = builder.DefineType (
1187 Name, type_attributes, null, null);
1189 TypeBuilder builder;
1190 if (Parent.TypeBuilder != null)
1191 builder = Parent.TypeBuilder;
1193 builder = Parent.DefineType ();
1195 if (builder == null) {
1200 TypeBuilder = builder.DefineNestedType (
1201 MemberName.Basename, type_attributes,
1205 catch (ArgumentException) {
1206 Report.RuntimeMissingSupport (Location, "static classes");
1210 TypeManager.AddUserType (Name, TypeBuilder, this);
1212 TypeExpr current_type = null;
1215 string[] param_names = new string [TypeParameters.Length];
1216 for (int i = 0; i < TypeParameters.Length; i++)
1217 param_names [i] = TypeParameters [i].Name;
1219 GenericTypeParameterBuilder[] gen_params;
1220 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1222 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1223 for (int i = offset; i < gen_params.Length; i++)
1224 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1226 foreach (TypeParameter type_param in CurrentTypeParameters) {
1227 if (!type_param.Resolve (this)) {
1233 for (int i = offset; i < gen_params.Length; i++)
1234 CurrentTypeParameters [i - offset].DefineConstraints ();
1236 current_type = new ConstructedType (Name, TypeParameters, Location);
1240 foreach (TypeParameter type_param in TypeParameters)
1241 if (!type_param.DefineType (ec)) {
1247 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1248 throw new Exception ();
1250 TypeExpr[] iface_exprs = GetClassBases (out parent_type, out error);
1254 if (parent_type == null) {
1255 if (Kind == Kind.Class){
1256 if (RootContext.StdLib)
1257 parent_type = TypeManager.system_object_expr;
1258 else if (Name != "System.Object")
1259 parent_type = TypeManager.system_object_expr;
1260 } else if (Kind == Kind.Struct){
1262 // If we are compiling our runtime,
1263 // and we are defining ValueType, then our
1264 // parent is `System.Object'.
1266 if (!RootContext.StdLib && Name == "System.ValueType")
1267 parent_type = TypeManager.system_object_expr;
1268 else if (Kind == Kind.Struct)
1269 parent_type = TypeManager.system_valuetype_expr;
1273 if (parent_type != null) {
1274 parent_type = parent_type.ResolveAsTypeTerminal (ec);
1275 if (parent_type == null) {
1280 ptype = parent_type.Type;
1283 if (!CheckRecursiveDefinition ()) {
1289 TypeBuilder.SetParent (ptype);
1292 // Structs with no fields need to have at least one byte.
1293 // The right thing would be to set the PackingSize in a DefineType
1294 // but there are no functions that allow interfaces *and* the size to
1298 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1299 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1300 FieldAttributes.Private);
1303 // add interfaces that were not added at type creation
1304 if (iface_exprs != null) {
1305 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1306 if (ifaces == null) {
1311 foreach (Type itype in ifaces)
1312 TypeBuilder.AddInterfaceImplementation (itype);
1314 if (!CheckGenericInterfaces (ifaces)) {
1319 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1323 foreach (TypeParameter type_param in TypeParameters)
1324 if (!type_param.CheckDependencies (ec)) {
1330 if (current_type != null) {
1331 current_type = current_type.ResolveAsTypeTerminal (ec);
1332 if (current_type == null) {
1337 CurrentType = current_type.Type;
1341 // Finish the setup for the EmitContext
1343 ec.ContainerType = TypeBuilder;
1345 if ((parent_type != null) && parent_type.IsAttribute) {
1346 RootContext.RegisterAttribute (this);
1347 } else if (!(this is Iterator))
1348 RootContext.RegisterOrder (this);
1350 if (!DefineNestedTypes ()) {
1358 protected virtual bool DefineNestedTypes ()
1360 if (Interfaces != null) {
1361 foreach (TypeContainer iface in Interfaces)
1362 if (iface.DefineType () == null)
1366 if (Types != null) {
1367 foreach (TypeContainer tc in Types)
1368 if (tc.DefineType () == null)
1372 if (Delegates != null) {
1373 foreach (Delegate d in Delegates)
1374 if (d.DefineType () == null)
1378 if (Enums != null) {
1379 foreach (Enum en in Enums)
1380 if (en.DefineType () == null)
1384 if (Parts != null) {
1385 foreach (ClassPart part in Parts) {
1386 part.TypeBuilder = TypeBuilder;
1387 part.parent_type = parent_type;
1388 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1395 protected bool CheckRecursiveDefinition ()
1398 Report.Error (146, Location,
1399 "Class definition is circular: `{0}'",
1400 GetSignatureForError ());
1407 Type parent = ptype;
1408 if (parent != null) {
1409 if (parent.IsGenericInstance)
1410 parent = parent.GetGenericTypeDefinition ();
1412 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1413 if ((ptc != null) && !ptc.CheckRecursiveDefinition ())
1421 static void Error_KeywordNotAllowed (Location loc)
1423 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1427 /// Populates our TypeBuilder with fields and methods
1429 public override bool DefineMembers (TypeContainer container)
1431 if (members_defined)
1432 return members_defined_ok;
1434 members_defined_ok = DoDefineMembers ();
1435 members_defined = true;
1437 return members_defined_ok;
1440 protected virtual bool DoDefineMembers ()
1443 // We need to be able to use the member cache while we are checking/defining
1445 if (TypeBuilder.BaseType != null)
1446 parent_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
1448 if (TypeBuilder.IsInterface)
1449 parent_cache = TypeManager.LookupParentInterfacesCache (TypeBuilder);
1452 if ((ModFlags & Modifiers.NEW) != 0)
1453 Error_KeywordNotAllowed (Location);
1455 // HACK: missing implemenation
1456 // This is not fully functional. Better way how to handle this is to have recursive definition of containers
1457 // instead of flat as we have now.
1458 // Now we are not able to check inner attribute class because its parent had not been defined.
1460 // TODO: remove this if
1461 if (Parent.MemberCache != null) {
1462 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1463 if (conflict_symbol == null) {
1464 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1465 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1467 if ((ModFlags & Modifiers.NEW) == 0) {
1468 Report.SymbolRelatedToPreviousError (conflict_symbol);
1469 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1475 DefineContainerMembers (constants);
1476 DefineContainerMembers (fields);
1478 if ((Kind == Kind.Class) && !(this is ClassPart) && !(this is StaticClass)){
1479 if ((instance_constructors == null) &&
1480 !(this is StaticClass)) {
1481 if (default_constructor == null)
1482 DefineDefaultConstructor (false);
1485 if (initialized_static_fields != null &&
1486 default_static_constructor == null)
1487 DefineDefaultConstructor (true);
1490 if (Kind == Kind.Struct){
1492 // Structs can not have initialized instance
1495 if (initialized_static_fields != null &&
1496 default_static_constructor == null)
1497 DefineDefaultConstructor (true);
1499 if (initialized_fields != null)
1500 ReportStructInitializedInstanceError ();
1503 Pending = GetPendingImplementations ();
1505 if (parts != null) {
1506 foreach (ClassPart part in parts) {
1507 if (!part.DefineMembers (this))
1513 // Constructors are not in the defined_names array
1515 DefineContainerMembers (instance_constructors);
1517 if (default_static_constructor != null)
1518 default_static_constructor.Define ();
1520 DefineContainerMembers (properties);
1521 DefineContainerMembers (events);
1522 DefineContainerMembers (indexers);
1523 DefineContainerMembers (methods);
1524 DefineContainerMembers (operators);
1525 DefineContainerMembers (enums);
1526 DefineContainerMembers (delegates);
1528 if (CurrentType != null) {
1529 GenericType = CurrentType;
1531 ec.ContainerType = GenericType;
1536 if (!(this is ClassPart))
1537 member_cache = new MemberCache (this);
1540 if (parts != null) {
1541 foreach (ClassPart part in parts)
1542 part.member_cache = member_cache;
1545 if (iterators != null) {
1546 foreach (Iterator iterator in iterators) {
1547 if (iterator.DefineType () == null)
1551 foreach (Iterator iterator in iterators) {
1552 if (!iterator.DefineMembers (this))
1560 void ReportStructInitializedInstanceError ()
1562 string n = TypeBuilder.FullName;
1564 foreach (Field f in initialized_fields){
1567 "`" + n + "." + f.Name + "': can not have " +
1568 "instance field initializers in structs");
1572 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1575 mcal.DefineContainerMembers ();
1578 public override bool Define ()
1580 if (parts != null) {
1581 foreach (ClassPart part in parts) {
1582 if (!part.Define ())
1590 public MemberInfo FindMemberWithSameName (string name, bool ignore_methods)
1592 return ParentCache.FindMemberWithSameName (name, ignore_methods, null);
1596 /// This function is based by a delegate to the FindMembers routine
1598 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1604 /// This filter is used by FindMembers, and we just keep
1605 /// a global for the filter to `AlwaysAccept'
1607 static MemberFilter accepting_filter;
1610 static TypeContainer ()
1612 accepting_filter = new MemberFilter (AlwaysAccept);
1615 public MethodInfo[] GetMethods ()
1617 ArrayList members = new ArrayList ();
1619 DefineMembers (null);
1621 if (methods != null) {
1622 int len = methods.Count;
1623 for (int i = 0; i < len; i++) {
1624 Method m = (Method) methods [i];
1626 members.Add (m.MethodBuilder);
1630 if (operators != null) {
1631 int len = operators.Count;
1632 for (int i = 0; i < len; i++) {
1633 Operator o = (Operator) operators [i];
1635 members.Add (o.OperatorMethodBuilder);
1639 if (properties != null) {
1640 int len = properties.Count;
1641 for (int i = 0; i < len; i++) {
1642 Property p = (Property) properties [i];
1644 if (p.GetBuilder != null)
1645 members.Add (p.GetBuilder);
1646 if (p.SetBuilder != null)
1647 members.Add (p.SetBuilder);
1651 if (indexers != null) {
1652 int len = indexers.Count;
1653 for (int i = 0; i < len; i++) {
1654 Indexer ix = (Indexer) indexers [i];
1656 if (ix.GetBuilder != null)
1657 members.Add (ix.GetBuilder);
1658 if (ix.SetBuilder != null)
1659 members.Add (ix.SetBuilder);
1663 if (events != null) {
1664 int len = events.Count;
1665 for (int i = 0; i < len; i++) {
1666 Event e = (Event) events [i];
1668 if (e.AddBuilder != null)
1669 members.Add (e.AddBuilder);
1670 if (e.RemoveBuilder != null)
1671 members.Add (e.RemoveBuilder);
1675 MethodInfo[] retMethods = new MethodInfo [members.Count];
1676 members.CopyTo (retMethods, 0);
1680 // Indicated whether container has StructLayout attribute set Explicit
1681 public virtual bool HasExplicitLayout {
1688 /// This method returns the members of this type just like Type.FindMembers would
1689 /// Only, we need to use this for types which are _being_ defined because MS'
1690 /// implementation can't take care of that.
1693 // FIXME: return an empty static array instead of null, that cleans up
1694 // some code and is consistent with some coding conventions I just found
1698 // Notice that in various cases we check if our field is non-null,
1699 // something that would normally mean that there was a bug elsewhere.
1701 // The problem happens while we are defining p-invoke methods, as those
1702 // will trigger a FindMembers, but this happens before things are defined
1704 // Since the whole process is a no-op, it is fine to check for null here.
1706 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1707 MemberFilter filter, object criteria)
1709 ArrayList members = null;
1712 if ((bf & BindingFlags.Public) != 0)
1713 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1715 if ((bf & BindingFlags.NonPublic) != 0)
1716 modflags |= Modifiers.PRIVATE;
1718 int static_mask = 0, static_flags = 0;
1719 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1720 case BindingFlags.Static:
1721 static_mask = static_flags = Modifiers.STATIC;
1724 case BindingFlags.Instance:
1725 static_mask = Modifiers.STATIC;
1730 static_mask = static_flags = 0;
1734 Timer.StartTimer (TimerType.TcFindMembers);
1737 filter = accepting_filter;
1739 if ((mt & MemberTypes.Field) != 0) {
1740 if (fields != null) {
1741 int len = fields.Count;
1742 for (int i = 0; i < len; i++) {
1743 Field f = (Field) fields [i];
1745 if ((f.ModFlags & modflags) == 0)
1747 if ((f.ModFlags & static_mask) != static_flags)
1750 FieldBuilder fb = f.FieldBuilder;
1751 if (fb != null && filter (fb, criteria) == true) {
1752 if (members == null)
1753 members = new ArrayList ();
1760 if (constants != null) {
1761 int len = constants.Count;
1762 for (int i = 0; i < len; i++) {
1763 Const con = (Const) constants [i];
1765 if ((con.ModFlags & modflags) == 0)
1767 if ((con.ModFlags & static_mask) != static_flags)
1770 FieldBuilder fb = con.FieldBuilder;
1771 if (fb != null && filter (fb, criteria) == true) {
1772 if (members == null)
1773 members = new ArrayList ();
1781 if ((mt & MemberTypes.Method) != 0) {
1782 if (methods != null) {
1783 int len = methods.Count;
1784 for (int i = 0; i < len; i++) {
1785 Method m = (Method) methods [i];
1787 if ((m.ModFlags & modflags) == 0)
1789 if ((m.ModFlags & static_mask) != static_flags)
1792 MethodBuilder mb = m.MethodBuilder;
1794 if (mb != null && filter (mb, criteria) == true) {
1795 if (members == null)
1796 members = new ArrayList ();
1803 if (operators != null) {
1804 int len = operators.Count;
1805 for (int i = 0; i < len; i++) {
1806 Operator o = (Operator) operators [i];
1808 if ((o.ModFlags & modflags) == 0)
1810 if ((o.ModFlags & static_mask) != static_flags)
1813 MethodBuilder ob = o.OperatorMethodBuilder;
1814 if (ob != null && filter (ob, criteria) == true) {
1815 if (members == null)
1816 members = new ArrayList ();
1823 if (properties != null) {
1824 int len = properties.Count;
1825 for (int i = 0; i < len; i++) {
1826 Property p = (Property) properties [i];
1828 if ((p.ModFlags & modflags) == 0)
1830 if ((p.ModFlags & static_mask) != static_flags)
1836 if (b != null && filter (b, criteria) == true) {
1837 if (members == null)
1838 members = new ArrayList ();
1844 if (b != null && filter (b, criteria) == true) {
1845 if (members == null)
1846 members = new ArrayList ();
1853 if (indexers != null) {
1854 int len = indexers.Count;
1855 for (int i = 0; i < len; i++) {
1856 Indexer ix = (Indexer) indexers [i];
1858 if ((ix.ModFlags & modflags) == 0)
1860 if ((ix.ModFlags & static_mask) != static_flags)
1866 if (b != null && filter (b, criteria) == true) {
1867 if (members == null)
1868 members = new ArrayList ();
1874 if (b != null && filter (b, criteria) == true) {
1875 if (members == null)
1876 members = new ArrayList ();
1884 if ((mt & MemberTypes.Event) != 0) {
1885 if (events != null) {
1886 int len = events.Count;
1887 for (int i = 0; i < len; i++) {
1888 Event e = (Event) events [i];
1890 if ((e.ModFlags & modflags) == 0)
1892 if ((e.ModFlags & static_mask) != static_flags)
1895 MemberInfo eb = e.EventBuilder;
1896 if (eb != null && filter (eb, criteria) == true) {
1897 if (members == null)
1898 members = new ArrayList ();
1900 members.Add (e.EventBuilder);
1906 if ((mt & MemberTypes.Property) != 0){
1907 if (properties != null) {
1908 int len = properties.Count;
1909 for (int i = 0; i < len; i++) {
1910 Property p = (Property) properties [i];
1912 if ((p.ModFlags & modflags) == 0)
1914 if ((p.ModFlags & static_mask) != static_flags)
1917 MemberInfo pb = p.PropertyBuilder;
1918 if (pb != null && filter (pb, criteria) == true) {
1919 if (members == null)
1920 members = new ArrayList ();
1922 members.Add (p.PropertyBuilder);
1927 if (indexers != null) {
1928 int len = indexers.Count;
1929 for (int i = 0; i < len; i++) {
1930 Indexer ix = (Indexer) indexers [i];
1932 if ((ix.ModFlags & modflags) == 0)
1934 if ((ix.ModFlags & static_mask) != static_flags)
1937 MemberInfo ib = ix.PropertyBuilder;
1938 if (ib != null && filter (ib, criteria) == true) {
1939 if (members == null)
1940 members = new ArrayList ();
1942 members.Add (ix.PropertyBuilder);
1948 if ((mt & MemberTypes.NestedType) != 0) {
1949 if (types != null) {
1950 int len = types.Count;
1951 for (int i = 0; i < len; i++) {
1952 TypeContainer t = (TypeContainer) types [i];
1954 if ((t.ModFlags & modflags) == 0)
1957 TypeBuilder tb = t.TypeBuilder;
1958 if (tb != null && (filter (tb, criteria) == true)) {
1959 if (members == null)
1960 members = new ArrayList ();
1967 if (enums != null) {
1968 int len = enums.Count;
1969 for (int i = 0; i < len; i++) {
1970 Enum en = (Enum) enums [i];
1972 if ((en.ModFlags & modflags) == 0)
1975 TypeBuilder tb = en.TypeBuilder;
1976 if (tb != null && (filter (tb, criteria) == true)) {
1977 if (members == null)
1978 members = new ArrayList ();
1985 if (delegates != null) {
1986 int len = delegates.Count;
1987 for (int i = 0; i < len; i++) {
1988 Delegate d = (Delegate) delegates [i];
1990 if ((d.ModFlags & modflags) == 0)
1993 TypeBuilder tb = d.TypeBuilder;
1994 if (tb != null && (filter (tb, criteria) == true)) {
1995 if (members == null)
1996 members = new ArrayList ();
2003 if (interfaces != null) {
2004 int len = interfaces.Count;
2005 for (int i = 0; i < len; i++) {
2006 TypeContainer iface = (TypeContainer) interfaces [i];
2008 if ((iface.ModFlags & modflags) == 0)
2011 TypeBuilder tb = iface.TypeBuilder;
2012 if (tb != null && (filter (tb, criteria) == true)) {
2013 if (members == null)
2014 members = new ArrayList ();
2022 if ((mt & MemberTypes.Constructor) != 0){
2023 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2024 int len = instance_constructors.Count;
2025 for (int i = 0; i < len; i++) {
2026 Constructor c = (Constructor) instance_constructors [i];
2028 ConstructorBuilder cb = c.ConstructorBuilder;
2029 if (cb != null && filter (cb, criteria) == true) {
2030 if (members == null)
2031 members = new ArrayList ();
2038 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2039 ConstructorBuilder cb =
2040 default_static_constructor.ConstructorBuilder;
2042 if (cb != null && filter (cb, criteria) == true) {
2043 if (members == null)
2044 members = new ArrayList ();
2052 // Lookup members in parent if requested.
2054 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2055 if (TypeBuilder.BaseType != null) {
2056 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2057 if (list.Count > 0) {
2058 if (members == null)
2059 members = new ArrayList ();
2061 members.AddRange (list);
2067 Timer.StopTimer (TimerType.TcFindMembers);
2069 if (members == null)
2070 return MemberList.Empty;
2072 return new MemberList (members);
2075 public override MemberCache MemberCache {
2077 return member_cache;
2081 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2082 MemberFilter filter, object criteria)
2084 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2087 return ds.FindMembers (mt, bf, filter, criteria);
2089 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2093 // FindMethods will look for methods not only in the type `t', but in
2094 // any interfaces implemented by the type.
2096 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2097 MemberFilter filter, object criteria)
2103 /// Emits the values for the constants
2105 public void EmitConstants ()
2107 if (constants != null)
2108 foreach (Const con in constants)
2113 protected virtual void VerifyMembers (EmitContext ec)
2116 // Check for internal or private fields that were never assigned
2118 if (RootContext.WarningLevel >= 3) {
2119 if (fields != null){
2120 foreach (Field f in fields) {
2121 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2124 if ((f.status & Field.Status.USED) == 0){
2125 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2130 // Only report 649 on level 4
2132 if (RootContext.WarningLevel < 4)
2135 if ((f.status & Field.Status.ASSIGNED) != 0)
2138 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2145 /// Emits the code, this step is performed after all
2146 /// the types, enumerations, constructors
2148 public void EmitType ()
2150 if (OptAttributes != null)
2151 OptAttributes.Emit (ec, this);
2155 if (instance_constructors != null) {
2156 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2157 bool has_compliant_args = false;
2159 foreach (Constructor c in instance_constructors) {
2162 if (has_compliant_args)
2165 has_compliant_args = c.HasCompliantArgs;
2167 if (!has_compliant_args)
2168 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2170 foreach (Constructor c in instance_constructors)
2177 if (default_static_constructor != null)
2178 default_static_constructor.Emit ();
2180 if (methods != null)
2181 foreach (Method m in methods)
2184 if (operators != null)
2185 foreach (Operator o in operators)
2188 if (properties != null)
2189 foreach (Property p in properties)
2192 if (indexers != null){
2197 foreach (Field f in fields)
2200 if (events != null){
2201 foreach (Event e in Events)
2205 if (delegates != null) {
2206 foreach (Delegate d in Delegates) {
2211 if (enums != null) {
2212 foreach (Enum e in enums) {
2217 if (parts != null) {
2218 foreach (ClassPart part in parts)
2222 if ((Pending != null) && !(this is ClassPart))
2223 if (Pending.VerifyPendingMethods ())
2228 if (iterators != null)
2229 foreach (Iterator iterator in iterators)
2230 iterator.EmitType ();
2232 // if (types != null)
2233 // foreach (TypeContainer tc in types)
2237 public override void CloseType ()
2239 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2243 caching_flags |= Flags.CloseTypeCreated;
2244 TypeBuilder.CreateType ();
2245 } catch (TypeLoadException){
2247 // This is fine, the code still created the type
2249 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2250 // Console.WriteLine (e.Message);
2252 Console.WriteLine ("In type: " + Name);
2257 foreach (Enum en in Enums)
2261 foreach (TypeContainer tc in Types)
2262 if (tc.Kind == Kind.Struct)
2265 foreach (TypeContainer tc in Types)
2266 if (tc.Kind != Kind.Struct)
2270 if (Delegates != null)
2271 foreach (Delegate d in Delegates)
2274 if (Iterators != null)
2275 foreach (Iterator i in Iterators)
2283 initialized_fields = null;
2284 initialized_static_fields = null;
2293 default_constructor = null;
2294 default_static_constructor = null;
2296 OptAttributes = null;
2298 parent_cache = null;
2299 member_cache = null;
2302 // TODO: make it obsolete and use GetSignatureForError
2303 public string MakeName (string n)
2305 return "`" + Name + "." + n + "'";
2309 // Performs the validation on a Method's modifiers (properties have
2310 // the same properties).
2312 public bool MethodModifiersValid (int flags, string n, Location loc)
2314 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2315 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2316 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2320 // At most one of static, virtual or override
2322 if ((flags & Modifiers.STATIC) != 0){
2323 if ((flags & vao) != 0){
2325 112, loc, "static method " + MakeName (n) + "can not be marked " +
2326 "as virtual, abstract or override");
2331 if (Kind == Kind.Struct){
2332 if ((flags & va) != 0){
2333 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
2338 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2340 113, loc, MakeName (n) +
2341 " marked as override cannot be marked as new or virtual");
2346 // If the declaration includes the abstract modifier, then the
2347 // declaration does not include static, virtual or extern
2349 if ((flags & Modifiers.ABSTRACT) != 0){
2350 if ((flags & Modifiers.EXTERN) != 0){
2352 180, loc, MakeName (n) + " can not be both abstract and extern");
2356 if ((flags & Modifiers.VIRTUAL) != 0){
2358 503, loc, MakeName (n) + " can not be both abstract and virtual");
2362 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2364 513, loc, MakeName (n) +
2365 " is abstract but its container class is not");
2371 if ((flags & Modifiers.PRIVATE) != 0){
2372 if ((flags & vao) != 0){
2374 621, loc, MakeName (n) +
2375 " virtual or abstract members can not be private");
2380 if ((flags & Modifiers.SEALED) != 0){
2381 if ((flags & Modifiers.OVERRIDE) == 0){
2383 238, loc, MakeName (n) +
2384 " cannot be sealed because it is not an override");
2392 public bool UserDefinedStaticConstructor {
2394 return default_static_constructor != null;
2398 protected override bool VerifyClsCompliance (DeclSpace ds)
2400 if (!base.VerifyClsCompliance (ds))
2405 Type base_type = TypeBuilder.BaseType;
2406 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2407 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2414 /// Checks whether container name is CLS Compliant
2416 void VerifyClsName ()
2418 Hashtable parent_members = parent_cache == null ?
2420 parent_cache.GetPublicMembers ();
2421 Hashtable this_members = new Hashtable ();
2423 foreach (DictionaryEntry entry in defined_names) {
2424 MemberCore mc = (MemberCore)entry.Value;
2425 if (!mc.IsClsCompliaceRequired (this))
2428 string name = (string)entry.Key;
2429 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2431 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2432 object found = parent_members [lcase];
2433 if (found == null) {
2434 found = this_members [lcase];
2435 if (found == null) {
2436 this_members.Add (lcase, mc);
2441 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2444 if (found is MemberInfo) {
2445 if (basename == ((MemberInfo)found).Name)
2447 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2449 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2451 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2457 /// Performs checks for an explicit interface implementation. First it
2458 /// checks whether the `interface_type' is a base inteface implementation.
2459 /// Then it checks whether `name' exists in the interface type.
2461 public virtual bool VerifyImplements (Type interface_type, string full,
2462 string name, Location loc)
2466 if (ifaces != null){
2467 foreach (Type t in ifaces){
2468 if (t == interface_type){
2476 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
2483 protected override void VerifyObsoleteAttribute()
2485 CheckUsageOfObsoleteAttribute (TypeBuilder.BaseType);
2490 foreach (Type iface in ifaces) {
2491 CheckUsageOfObsoleteAttribute (iface);
2499 string IMemberContainer.Name {
2505 Type IMemberContainer.Type {
2511 MemberCache IMemberContainer.MemberCache {
2513 return member_cache;
2517 bool IMemberContainer.IsInterface {
2519 return Kind == Kind.Interface;
2523 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2525 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2527 if (GenericType != null)
2528 return TypeManager.FindMembers (GenericType, mt, new_bf,
2531 return FindMembers (mt, new_bf, null, null);
2534 public virtual MemberCache ParentCache {
2536 return parent_cache;
2542 public class PartialContainer : TypeContainer {
2544 public readonly Namespace Namespace;
2545 public readonly int OriginalModFlags;
2546 public readonly int AllowedModifiers;
2547 public readonly TypeAttributes DefaultTypeAttributes;
2549 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2550 MemberName member_name, int mod_flags, Kind kind,
2553 PartialContainer pc;
2554 string full_name = member_name.GetName (true);
2555 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2557 pc = ds as PartialContainer;
2561 260, ds.Location, "Missing partial modifier " +
2562 "on declaration of type `{0}'; another " +
2563 "partial implementation of this type exists",
2564 member_name.GetPartialName());
2566 Report.LocationOfPreviousError (loc);
2570 if (pc.Kind != kind) {
2572 261, loc, "Partial declarations of `{0}' " +
2573 "must be all classes, all structs or " +
2574 "all interfaces", member_name.GetPartialName ());
2578 if (pc.OriginalModFlags != mod_flags) {
2580 262, loc, "Partial declarations of `{0}' " +
2581 "have conflicting accessibility modifiers",
2582 member_name.GetPartialName ());
2589 pc = new PartialContainer (ns, parent, member_name, mod_flags, kind, loc);
2590 RootContext.Tree.RecordDecl (full_name, pc);
2591 parent.AddType (pc);
2596 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2597 MemberName name, int mod, Attributes attrs,
2598 Kind kind, Location loc)
2600 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2602 // An error occured; create a dummy container, but don't
2604 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2607 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2612 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2613 MemberName name, int mod, Kind kind, Location l)
2614 : base (ns, parent, name, null, kind, l)
2616 this.Namespace = ns.NS;
2620 AllowedModifiers = Class.AllowedModifiers;
2621 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2625 AllowedModifiers = Struct.AllowedModifiers;
2626 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2629 case Kind.Interface:
2630 AllowedModifiers = Interface.AllowedModifiers;
2631 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2635 throw new InvalidOperationException ();
2639 if (parent.Parent == null)
2640 accmods = Modifiers.INTERNAL;
2642 accmods = Modifiers.PRIVATE;
2644 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2645 this.OriginalModFlags = mod;
2648 public override void Register ()
2650 if (Kind == Kind.Interface)
2651 Parent.AddInterface (this);
2652 else if (Kind == Kind.Class || Kind == Kind.Struct)
2653 Parent.AddClassOrStruct (this);
2655 throw new InvalidOperationException ();
2658 public override PendingImplementation GetPendingImplementations ()
2660 return PendingImplementation.GetPendingImplementations (this);
2663 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2666 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2671 public override TypeAttributes TypeAttr {
2673 return base.TypeAttr | DefaultTypeAttributes;
2678 public class ClassPart : TypeContainer, IMemberContainer {
2679 public readonly PartialContainer PartialContainer;
2680 public readonly bool IsPartial;
2682 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2683 int mod, Attributes attrs, Kind kind, Location l)
2684 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2686 this.PartialContainer = parent;
2687 this.IsPartial = true;
2690 if (parent.Parent == null)
2691 accmods = Modifiers.INTERNAL;
2693 accmods = Modifiers.PRIVATE;
2695 this.ModFlags = Modifiers.Check (
2696 parent.AllowedModifiers, mod, accmods, l);
2699 public override void Register ()
2703 public override PendingImplementation GetPendingImplementations ()
2705 return PartialContainer.Pending;
2708 public override bool VerifyImplements (Type interface_type, string full,
2709 string name, Location loc)
2711 return PartialContainer.VerifyImplements (
2712 interface_type, full, name, loc);
2715 public override MemberCache ParentCache {
2717 return PartialContainer.ParentCache;
2722 public abstract class ClassOrStruct : TypeContainer {
2723 bool hasExplicitLayout = false;
2724 ListDictionary declarative_security;
2726 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2727 MemberName name, Attributes attrs, Kind kind,
2729 : base (ns, parent, name, attrs, kind, l)
2733 public override PendingImplementation GetPendingImplementations ()
2735 return PendingImplementation.GetPendingImplementations (this);
2738 public override bool HasExplicitLayout {
2740 return hasExplicitLayout;
2744 protected override void VerifyMembers (EmitContext ec)
2746 base.VerifyMembers (ec);
2748 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2749 foreach (Event e in events){
2751 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2756 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2758 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2759 if (declarative_security == null)
2760 declarative_security = new ListDictionary ();
2762 a.ExtractSecurityPermissionSet (declarative_security);
2766 if (a.Type == TypeManager.struct_layout_attribute_type
2767 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2768 hasExplicitLayout = true;
2770 base.ApplyAttributeBuilder (a, cb);
2773 public override void Emit()
2777 if (declarative_security != null) {
2778 foreach (DictionaryEntry de in declarative_security) {
2779 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2784 public override void Register ()
2786 Parent.AddClassOrStruct (this);
2791 /// Class handles static classes declaration
2793 public sealed class StaticClass: Class {
2794 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2795 Attributes attrs, Location l)
2796 : base (ns, parent, name, mod & ~Modifiers.STATIC, attrs, l)
2798 if (RootContext.Version == LanguageVersion.ISO_1) {
2799 Report.FeatureIsNotStandardized (l, "static classes");
2800 Environment.Exit (1);
2804 protected override void DefineContainerMembers (MemberCoreArrayList list)
2809 foreach (MemberCore m in list) {
2810 if (m is Operator) {
2811 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2815 if ((m.ModFlags & Modifiers.STATIC) != 0)
2818 if (m is Constructor) {
2819 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2823 if (m is Destructor) {
2824 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2827 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2830 base.DefineContainerMembers (list);
2833 public override TypeBuilder DefineType()
2835 TypeBuilder tb = base.DefineType ();
2839 if ((ptype != null) && (ptype != TypeManager.object_type)) {
2842 "Static class '{0}' cannot derive from type '{1}'. " +
2843 "Static classes must derive from object",
2844 GetSignatureForError (), ptype);
2848 if (ifaces != null) {
2849 foreach (Type t in ifaces)
2850 Report.SymbolRelatedToPreviousError (t);
2853 "'{0}': static classes cannot implement interfaces",
2854 GetSignatureForError ());
2859 public override TypeAttributes TypeAttr {
2861 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2866 public class Class : ClassOrStruct {
2868 // Modifiers allowed in a class declaration
2870 public const int AllowedModifiers =
2873 Modifiers.PROTECTED |
2874 Modifiers.INTERNAL |
2876 Modifiers.ABSTRACT |
2880 // Information in the case we are an attribute type
2881 AttributeUsageAttribute attribute_usage;
2883 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2884 Attributes attrs, Location l)
2885 : base (ns, parent, name, attrs, Kind.Class, l)
2889 if (parent.Parent == null)
2890 accmods = Modifiers.INTERNAL;
2892 accmods = Modifiers.PRIVATE;
2894 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2895 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.SEALED)) == (Modifiers.ABSTRACT | Modifiers.SEALED)) {
2896 Report.Error (502, Location, "'{0}' cannot be both abstract and sealed", GetSignatureForError ());
2899 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2902 public override AttributeTargets AttributeTargets {
2904 return AttributeTargets.Class;
2908 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2910 if (a.UsageAttribute != null) {
2911 if (ptype != TypeManager.attribute_type &&
2912 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2913 TypeBuilder.FullName != "System.Attribute") {
2914 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2916 attribute_usage = a.UsageAttribute;
2919 base.ApplyAttributeBuilder (a, cb);
2922 public AttributeUsageAttribute AttributeUsage {
2924 return attribute_usage;
2928 public const TypeAttributes DefaultTypeAttributes =
2929 TypeAttributes.AutoLayout | TypeAttributes.Class;
2932 // FIXME: How do we deal with the user specifying a different
2935 public override TypeAttributes TypeAttr {
2937 return base.TypeAttr | DefaultTypeAttributes;
2942 public class Struct : ClassOrStruct {
2944 // Modifiers allowed in a struct declaration
2946 public const int AllowedModifiers =
2949 Modifiers.PROTECTED |
2950 Modifiers.INTERNAL |
2954 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2955 int mod, Attributes attrs, Location l)
2956 : base (ns, parent, name, attrs, Kind.Struct, l)
2960 if (parent.Parent == null)
2961 accmods = Modifiers.INTERNAL;
2963 accmods = Modifiers.PRIVATE;
2965 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2967 this.ModFlags |= Modifiers.SEALED;
2970 public override AttributeTargets AttributeTargets {
2972 return AttributeTargets.Struct;
2976 public const TypeAttributes DefaultTypeAttributes =
2977 TypeAttributes.SequentialLayout |
2978 TypeAttributes.Sealed |
2979 TypeAttributes.BeforeFieldInit;
2982 // FIXME: Allow the user to specify a different set of attributes
2983 // in some cases (Sealed for example is mandatory for a class,
2984 // but what SequentialLayout can be changed
2986 public override TypeAttributes TypeAttr {
2988 return base.TypeAttr | DefaultTypeAttributes;
2996 public class Interface : TypeContainer, IMemberContainer {
2998 /// Modifiers allowed in a class declaration
3000 public const int AllowedModifiers =
3003 Modifiers.PROTECTED |
3004 Modifiers.INTERNAL |
3008 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name,
3009 int mod, Attributes attrs, Location l)
3010 : base (ns, parent, name, attrs, Kind.Interface, l)
3014 if (parent.Parent == null)
3015 accmods = Modifiers.INTERNAL;
3017 accmods = Modifiers.PRIVATE;
3019 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3022 public override void Register ()
3024 Parent.AddInterface (this);
3027 public override PendingImplementation GetPendingImplementations ()
3032 public override AttributeTargets AttributeTargets {
3034 return AttributeTargets.Interface;
3038 public const TypeAttributes DefaultTypeAttributes =
3039 TypeAttributes.AutoLayout |
3040 TypeAttributes.Abstract |
3041 TypeAttributes.Interface;
3043 public override TypeAttributes TypeAttr {
3045 return base.TypeAttr | DefaultTypeAttributes;
3050 public abstract class MethodCore : MemberBase {
3051 public readonly Parameters Parameters;
3052 public readonly GenericMethod GenericMethod;
3053 public readonly DeclSpace ds;
3054 protected ToplevelBlock block;
3057 // Parameters, cached for semantic analysis.
3059 protected InternalParameters parameter_info;
3060 protected Type [] parameter_types;
3062 // Whether this is an operator method.
3063 public bool IsOperator;
3066 // The method we're overriding if this is an override method.
3068 protected MethodInfo parent_method = null;
3070 static string[] attribute_targets = new string [] { "method", "return" };
3072 public MethodCore (TypeContainer parent, GenericMethod generic,
3073 Expression type, int mod, int allowed_mod, bool is_iface,
3074 MemberName name, Attributes attrs, Parameters parameters,
3076 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3079 Parameters = parameters;
3080 IsInterface = is_iface;
3081 this.GenericMethod = generic;
3083 if (generic != null)
3090 // Returns the System.Type array for the parameters of this method
3092 public Type [] ParameterTypes {
3094 return parameter_types;
3098 public InternalParameters ParameterInfo
3101 return parameter_info;
3105 public ToplevelBlock Block {
3115 protected override bool CheckBase ()
3117 if (!base.CheckBase ())
3120 // Check whether arguments were correct.
3121 if (!DoDefineParameters ())
3124 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3130 // Is null for System.Object while compiling corlib and base interfaces
3131 if (Parent.ParentCache == null) {
3132 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3133 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3138 Type parent_ret_type = null;
3139 parent_method = FindOutParentMethod (Parent, ref parent_ret_type);
3141 // method is override
3142 if (parent_method != null) {
3144 if (!CheckMethodAgainstBase ())
3147 if ((ModFlags & Modifiers.NEW) == 0) {
3148 if (!MemberType.Equals (TypeManager.TypeToCoreType (parent_ret_type))) {
3149 Report.SymbolRelatedToPreviousError (parent_method);
3150 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3151 "change return type when overriding inherited member");
3155 if (parent_method.IsAbstract && !IsInterface) {
3156 Report.SymbolRelatedToPreviousError (parent_method);
3157 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3162 if (parent_method.IsSpecialName && !(this is PropertyBase)) {
3163 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (parent_method));
3167 if (RootContext.WarningLevel > 2) {
3168 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3169 Parent.Methods.HasEquals = true;
3170 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3171 Parent.Methods.HasGetHashCode = true;
3174 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (parent_method);
3176 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3177 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3178 Report.SymbolRelatedToPreviousError (parent_method);
3179 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3185 MemberInfo conflict_symbol = Parent.FindMemberWithSameName (Name, !(this is Property));
3186 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3187 if (conflict_symbol != null) {
3188 Report.SymbolRelatedToPreviousError (conflict_symbol);
3189 if (this is PropertyBase)
3190 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3192 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3194 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3198 if (conflict_symbol == null) {
3199 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3200 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3205 if ((ModFlags & Modifiers.NEW) == 0) {
3206 if (this is Method && conflict_symbol is MethodBase)
3209 Report.SymbolRelatedToPreviousError (conflict_symbol);
3210 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3218 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3219 // that have been defined.
3221 // `name' is the user visible name for reporting errors (this is used to
3222 // provide the right name regarding method names and properties)
3224 bool CheckMethodAgainstBase ()
3228 // TODO: replace with GetSignatureForError
3229 string name = parent_method.DeclaringType.Name + "." + parent_method.Name;
3231 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3232 if (!(parent_method.IsAbstract || parent_method.IsVirtual)){
3234 506, Location, Parent.MakeName (Name) +
3235 ": cannot override inherited member `" +
3236 name + "' because it is not " +
3237 "virtual, abstract or override");
3241 // Now we check that the overriden method is not final
3243 if (parent_method.IsFinal) {
3244 // This happens when implementing interface methods.
3245 if (parent_method.IsHideBySig && parent_method.IsVirtual) {
3247 506, Location, Parent.MakeName (Name) +
3248 ": cannot override inherited member `" +
3249 name + "' because it is not " +
3250 "virtual, abstract or override");
3252 Report.Error (239, Location, Parent.MakeName (Name) + " : cannot " +
3253 "override inherited member `" + name +
3254 "' because it is sealed.");
3258 // Check that the permissions are not being changed
3260 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3261 MethodAttributes parentp = parent_method.Attributes & MethodAttributes.MemberAccessMask;
3263 if (!CheckAccessModifiers (thisp, parentp, parent_method)) {
3264 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3269 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3270 ModFlags |= Modifiers.NEW;
3271 Report.SymbolRelatedToPreviousError (parent_method);
3272 if (!IsInterface && (parent_method.IsVirtual || parent_method.IsAbstract)) {
3273 if (RootContext.WarningLevel >= 2)
3274 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));
3276 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3282 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes parentp, MethodInfo base_method)
3284 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3286 // when overriding protected internal, the method can be declared
3287 // protected internal only within the same assembly
3290 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3291 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3293 // assemblies differ - report an error
3297 } else if (thisp != parentp) {
3299 // same assembly, but other attributes differ - report an error
3304 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3306 // if it's not "protected internal", it must be "protected"
3310 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3312 // protected within the same assembly - an error
3315 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3316 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3318 // protected ok, but other attributes differ - report an error
3324 return (thisp == parentp);
3328 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method, string name)
3331 // FIXME: report the old/new permissions?
3334 507, Location, parent.MakeName (Name) +
3335 ": can't change the access modifiers when overriding inherited " +
3336 "member `" + name + "'");
3339 protected static string Error722 {
3341 return "'{0}': static types cannot be used as return types";
3346 /// For custom member duplication search in a container
3348 protected abstract bool CheckForDuplications ();
3351 /// Gets parent method and its return type
3353 protected abstract MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type);
3355 protected virtual bool DoDefineParameters ()
3357 EmitContext ec = ds.EmitContext;
3359 throw new InternalErrorException ("DoDefineParameters invoked too early");
3361 bool old_unsafe = ec.InUnsafe;
3362 ec.InUnsafe = InUnsafe;
3363 // Check if arguments were correct
3364 parameter_types = Parameters.GetParameterInfo (ec);
3365 ec.InUnsafe = old_unsafe;
3367 if ((parameter_types == null) ||
3368 !CheckParameters (ds, parameter_types))
3371 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3372 parameter_info = new InternalParameters (parameter_types, Parameters, tparam);
3374 Parameter array_param = Parameters.ArrayParameter;
3375 if ((array_param != null) &&
3376 (!array_param.ParameterType.IsArray ||
3377 (array_param.ParameterType.GetArrayRank () != 1))) {
3378 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3385 void error_425 (Type old, Type t, string name)
3387 Report.Error (425, Location,
3388 "The constraints of type parameter `{0}' " +
3389 "of method `{1}' must match the constraints for " +
3390 "type parameter `{2}' of method `{3}'",
3391 TypeManager.CSharpName (old), Name,
3392 TypeManager.CSharpName (t), name);
3395 protected override bool CheckGenericOverride (MethodInfo method, string name)
3397 ParameterData pd = Invocation.GetParameterData (method);
3399 for (int i = 0; i < ParameterTypes.Length; i++) {
3400 GenericConstraints ogc = pd.GenericConstraints (i);
3401 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3403 if ((gc == null) && (ogc == null))
3406 Type ot = pd.ParameterType (i);
3407 Type t = ParameterTypes [i];
3409 if (!((gc != null) && (ogc != null))) {
3410 error_425 (ot, t, name);
3414 if ((gc.Attributes != ogc.Attributes) ||
3415 (gc.HasClassConstraint != ogc.HasClassConstraint)) {
3416 error_425 (ot, t, name);
3420 if (ogc.HasClassConstraint &&
3421 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3422 error_425 (ot, t, name);
3426 Type[] oct = ogc.InterfaceConstraints;
3427 Type[] ct = gc.InterfaceConstraints;
3429 if (oct.Length != ct.Length) {
3430 error_425 (ot, t, name);
3434 for (int j = 0; j < oct.Length; j++)
3435 if (!oct [j].Equals (ct [j])) {
3436 error_425 (ot, t, name);
3444 public override string[] ValidAttributeTargets {
3446 return attribute_targets;
3450 protected override bool VerifyClsCompliance (DeclSpace ds)
3452 if (!base.VerifyClsCompliance (ds)) {
3453 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3454 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3459 if (Parameters.HasArglist) {
3460 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3463 if (!AttributeTester.IsClsCompliant (MemberType)) {
3464 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant", GetSignatureForError ());
3467 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3472 protected bool IsDuplicateImplementation (MethodCore method)
3474 if ((method == this) ||
3475 (method.MemberName.GetTypeName () != MemberName.GetTypeName ()))
3478 Type[] param_types = method.ParameterTypes;
3479 if (param_types == null)
3482 if (param_types.Length != ParameterTypes.Length)
3485 int type_params = 0;
3486 if (GenericMethod != null)
3487 type_params = GenericMethod.CountTypeParameters;
3489 int m_type_params = 0;
3490 if (method.GenericMethod != null)
3491 m_type_params = method.GenericMethod.CountTypeParameters;
3493 if (type_params != m_type_params)
3499 Type[] infered_types;
3500 if (type_params > 0)
3501 infered_types = new Type [type_params];
3503 infered_types = null;
3505 may_unify = Invocation.InferTypeArguments (
3506 param_types, ParameterTypes, ref infered_types);
3509 if (type_params > 0)
3510 infered_types = new Type [type_params];
3512 infered_types = null;
3514 may_unify = Invocation.InferTypeArguments (
3515 ParameterTypes, param_types, ref infered_types);
3518 for (int i = 0; i < param_types.Length; i++) {
3519 if (param_types [i] != ParameterTypes [i])
3523 // TODO: make operator compatible with MethodCore to avoid this
3524 if (this is Operator && method is Operator) {
3525 if (MemberType != method.MemberType)
3531 // Try to report 663: method only differs on out/ref
3533 ParameterData info = ParameterInfo;
3534 ParameterData other_info = method.ParameterInfo;
3535 for (int i = 0; i < info.Count; i++){
3536 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3537 Report.Error (663, Location,
3538 "Overload method only differs " +
3539 "in parameter modifier");
3544 Report.SymbolRelatedToPreviousError (method);
3545 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with the same parameter types", Parent.Name, Name);
3547 } else if (may_unify) {
3548 Report.Error (408, Location,
3549 "`{0}' cannot define overload members that " +
3550 "may unify for some type parameter substitutions",
3558 protected override void VerifyObsoleteAttribute()
3560 base.VerifyObsoleteAttribute ();
3562 if (parameter_types == null)
3565 foreach (Type type in parameter_types) {
3566 CheckUsageOfObsoleteAttribute (type);
3571 public class SourceMethod : ISourceMethod
3573 TypeContainer container;
3576 protected SourceMethod (TypeContainer container, MethodBase builder,
3577 ISourceFile file, Location start, Location end)
3579 this.container = container;
3580 this.builder = builder;
3582 CodeGen.SymbolWriter.OpenMethod (
3583 file, this, start.Row, 0, end.Row, 0);
3586 public string Name {
3587 get { return builder.Name; }
3590 public int NamespaceID {
3591 get { return container.NamespaceEntry.SymbolFileID; }
3596 if (builder is MethodBuilder)
3597 return ((MethodBuilder) builder).GetToken ().Token;
3598 else if (builder is ConstructorBuilder)
3599 return ((ConstructorBuilder) builder).GetToken ().Token;
3601 throw new NotSupportedException ();
3605 public void CloseMethod ()
3607 if (CodeGen.SymbolWriter != null)
3608 CodeGen.SymbolWriter.CloseMethod ();
3611 public static SourceMethod Create (TypeContainer parent,
3612 MethodBase builder, Block block)
3614 if (CodeGen.SymbolWriter == null)
3619 Location start_loc = block.StartLocation;
3620 if (Location.IsNull (start_loc))
3623 Location end_loc = block.EndLocation;
3624 if (Location.IsNull (end_loc))
3627 ISourceFile file = start_loc.SourceFile;
3631 return new SourceMethod (
3632 parent, builder, file, start_loc, end_loc);
3636 public class Method : MethodCore, IIteratorContainer, IMethodData {
3637 public MethodBuilder MethodBuilder;
3638 public MethodData MethodData;
3639 ReturnParameter return_attributes;
3640 ListDictionary declarative_security;
3643 /// Modifiers allowed in a class declaration
3645 const int AllowedModifiers =
3648 Modifiers.PROTECTED |
3649 Modifiers.INTERNAL |
3654 Modifiers.OVERRIDE |
3655 Modifiers.ABSTRACT |
3657 Modifiers.METHOD_YIELDS |
3660 const int AllowedInterfaceModifiers =
3661 Modifiers.NEW | Modifiers.UNSAFE;
3664 // return_type can be "null" for VOID values.
3666 public Method (TypeContainer parent, GenericMethod generic,
3667 Expression return_type, int mod, bool is_iface,
3668 MemberName name, Parameters parameters, Attributes attrs,
3670 : base (parent, generic, return_type, mod,
3671 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3672 is_iface, name, attrs, parameters, l)
3676 public override AttributeTargets AttributeTargets {
3678 return AttributeTargets.Method;
3682 public override string GetSignatureForError()
3684 if (MethodBuilder == null) {
3685 return GetSignatureForError (Parent);
3687 return TypeManager.CSharpSignature (MethodBuilder);
3691 /// Use this method when MethodBuilder is null
3693 public override string GetSignatureForError (TypeContainer tc)
3695 // TODO: get params from somewhere
3696 if (parameter_info == null)
3697 return base.GetSignatureForError (tc);
3699 // TODO: move to parameters
3700 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3701 if (parameter_info.Parameters.FixedParameters != null) {
3702 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3703 Parameter p = parameter_info.Parameters.FixedParameters [i];
3704 args.Append (p.GetSignatureForError ());
3706 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3711 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3714 void DuplicateEntryPoint (MethodInfo b, Location location)
3718 "Program `" + CodeGen.FileName +
3719 "' has more than one entry point defined: `" +
3720 TypeManager.CSharpSignature(b) + "'");
3723 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3725 if (b.ReturnType != TypeManager.void_type &&
3726 b.ReturnType != TypeManager.int32_type)
3729 if (pinfo.Count == 0)
3732 if (pinfo.Count > 1)
3735 Type t = pinfo.ParameterType(0);
3737 (t.GetArrayRank() == 1) &&
3738 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3739 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3745 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3747 if (a.Target == AttributeTargets.ReturnValue) {
3748 if (return_attributes == null)
3749 return_attributes = new ReturnParameter (MethodBuilder, Location);
3751 return_attributes.ApplyAttributeBuilder (a, cb);
3755 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
3756 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3759 if (a.Type == TypeManager.dllimport_type) {
3760 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3761 if ((ModFlags & extern_static) != extern_static) {
3762 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3768 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3769 if (declarative_security == null)
3770 declarative_security = new ListDictionary ();
3771 a.ExtractSecurityPermissionSet (declarative_security);
3775 if (a.Type == TypeManager.conditional_attribute_type) {
3776 if (IsOperator || IsExplicitImpl) {
3777 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3781 if (ReturnType != TypeManager.void_type) {
3782 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3786 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3787 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3792 Report.Error (582, Location, "Conditional not valid on interface members");
3796 if (MethodData.IsImplementing) {
3797 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3801 for (int i = 0; i < parameter_info.Count; ++i) {
3802 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3803 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3809 MethodBuilder.SetCustomAttribute (cb);
3812 protected override bool CheckForDuplications ()
3814 ArrayList ar = Parent.Methods;
3816 int arLen = ar.Count;
3818 for (int i = 0; i < arLen; i++) {
3819 Method m = (Method) ar [i];
3820 if (IsDuplicateImplementation (m))
3825 ar = Parent.Properties;
3827 for (int i = 0; i < ar.Count; ++i) {
3828 PropertyBase pb = (PropertyBase) ar [i];
3829 if (pb.AreAccessorsDuplicateImplementation (this))
3834 ar = Parent.Indexers;
3836 for (int i = 0; i < ar.Count; ++i) {
3837 PropertyBase pb = (PropertyBase) ar [i];
3838 if (pb.AreAccessorsDuplicateImplementation (this))
3845 for (int i = 0; i < ar.Count; ++i) {
3846 Event ev = (Event) ar [i];
3847 if (ev.AreAccessorsDuplicateImplementation (this))
3858 public override bool Define ()
3860 if (!DoDefineBase ())
3863 MethodBuilder mb = null;
3864 if (GenericMethod != null) {
3865 string mname = MemberName.GetMethodName ();
3866 mb = Parent.TypeBuilder.DefineGenericMethod (mname, flags);
3867 if (!GenericMethod.Define (mb, ReturnType))
3878 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3880 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
3881 this, mb, GenericMethod, parent_method);
3883 if (!MethodData.Define (Parent))
3887 // Setup iterator if we are one
3889 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3890 Iterator iterator = new Iterator (
3891 Parent, Name, MemberType, ParameterTypes,
3892 ParameterInfo, ModFlags, block, Location);
3894 if (!iterator.DefineIterator ())
3897 block = iterator.Block;
3900 MethodBuilder = MethodData.MethodBuilder;
3903 // This is used to track the Entry Point,
3905 if (Name == "Main" &&
3906 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3907 (RootContext.MainClass == null ||
3908 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3909 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3910 if (RootContext.EntryPoint == null) {
3911 if (Parent.IsGeneric){
3912 Report.Error (-201, Location,
3913 "Entry point can not be defined in a generic class");
3916 RootContext.EntryPoint = MethodBuilder;
3917 RootContext.EntryPointLocation = Location;
3919 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3920 DuplicateEntryPoint (MethodBuilder, Location);
3923 if (RootContext.WarningLevel >= 4)
3924 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder) );
3928 if (MemberType.IsAbstract && MemberType.IsSealed) {
3929 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3939 public override void Emit ()
3941 MethodData.Emit (Parent, this);
3944 if (declarative_security != null) {
3945 foreach (DictionaryEntry de in declarative_security) {
3946 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3954 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
3956 MethodInfo mi = (MethodInfo) container.ParentCache.FindMemberToOverride (
3957 container.TypeBuilder, Name, ParameterTypes, false);
3962 parent_ret_type = mi.ReturnType;
3966 protected override bool VerifyClsCompliance(DeclSpace ds)
3968 if (!base.VerifyClsCompliance (ds))
3971 if (parameter_types.Length > 0) {
3972 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3974 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3981 void IIteratorContainer.SetYields ()
3983 ModFlags |= Modifiers.METHOD_YIELDS;
3986 #region IMethodData Members
3988 public CallingConventions CallingConventions {
3990 CallingConventions cc = Parameters.GetCallingConvention ();
3991 if (Parameters.HasArglist)
3992 block.HasVarargs = true;
3995 if ((ModFlags & Modifiers.STATIC) == 0)
3996 cc |= CallingConventions.HasThis;
3998 // FIXME: How is `ExplicitThis' used in C#?
4004 public Type ReturnType {
4010 public MemberName MethodName {
4016 public new Location Location {
4018 return base.Location;
4022 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4024 return new EmitContext (
4025 tc, ds, Location, ig, ReturnType, ModFlags, false);
4028 public ObsoleteAttribute GetObsoleteAttribute ()
4030 return GetObsoleteAttribute (ds);
4034 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4036 public bool IsExcluded (EmitContext ec)
4038 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4039 return (caching_flags & Flags.Excluded) != 0;
4041 caching_flags &= ~Flags.Excluded_Undetected;
4043 if (parent_method == null) {
4044 if (OptAttributes == null)
4047 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4052 foreach (Attribute a in attrs) {
4053 string condition = a.GetConditionalAttributeValue (ds);
4054 if (RootContext.AllDefines.Contains (condition))
4058 caching_flags |= Flags.Excluded;
4062 IMethodData md = TypeManager.GetMethod (parent_method);
4064 if (AttributeTester.IsConditionalMethodExcluded (parent_method)) {
4065 caching_flags |= Flags.Excluded;
4071 if (md.IsExcluded (ec)) {
4072 caching_flags |= Flags.Excluded;
4078 GenericMethod IMethodData.GenericMethod {
4080 return GenericMethod;
4087 public abstract class ConstructorInitializer {
4088 ArrayList argument_list;
4089 protected ConstructorInfo parent_constructor;
4090 Parameters parameters;
4093 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4096 this.argument_list = argument_list;
4097 this.parameters = parameters;
4101 public ArrayList Arguments {
4103 return argument_list;
4107 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4109 Expression parent_constructor_group;
4112 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
4114 if (argument_list != null){
4115 foreach (Argument a in argument_list){
4116 if (!a.Resolve (ec, loc))
4120 ec.CurrentBlock = null;
4122 if (this is ConstructorBaseInitializer) {
4123 if (ec.ContainerType.BaseType == null)
4126 t = ec.ContainerType.BaseType;
4127 if (ec.ContainerType.IsValueType) {
4128 Report.Error (522, loc,
4129 "structs cannot call base class constructors");
4133 t = ec.ContainerType;
4135 parent_constructor_group = Expression.MemberLookup (
4136 ec, t, ".ctor", MemberTypes.Constructor,
4137 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4140 if (parent_constructor_group == null){
4141 parent_constructor_group = Expression.MemberLookup (
4142 ec, t, ".ctor", MemberTypes.Constructor,
4143 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4146 if (parent_constructor_group != null)
4148 112, loc, "`{0}.{1}' is inaccessible due to " +
4149 "its protection level", t.FullName, t.Name);
4152 1501, loc, "Can not find a constructor for " +
4153 "this argument list");
4157 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4158 ec, (MethodGroupExpr) parent_constructor_group, argument_list,
4161 if (parent_constructor == null){
4162 Report.Error (1501, loc,
4163 "Can not find a constructor for this argument list");
4167 if (parent_constructor == caller_builder){
4168 Report.Error (516, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
4175 public void Emit (EmitContext ec)
4177 if (parent_constructor != null){
4178 ec.Mark (loc, false);
4180 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
4182 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
4187 /// Method search for base ctor. (We do not cache it).
4189 Constructor GetOverloadedConstructor (TypeContainer tc)
4191 if (tc.InstanceConstructors == null)
4194 foreach (Constructor c in tc.InstanceConstructors) {
4195 if (Arguments == null) {
4196 if (c.ParameterTypes.Length == 0)
4204 int count = c.ParameterInfo.Count;
4206 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4207 for (int i = 0; i < count-1; i++)
4208 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4213 if (c.ParameterTypes.Length != Arguments.Count)
4216 for (int i = 0; i < Arguments.Count; ++i)
4217 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4232 //TODO: implement caching when it will be necessary
4233 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4235 Constructor ctor = GetOverloadedConstructor (tc);
4239 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4243 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4247 public class ConstructorBaseInitializer : ConstructorInitializer {
4248 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4249 base (argument_list, pars, l)
4253 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4254 if (parent_constructor == null)
4257 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4258 if (type_ds == null) {
4259 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (parent_constructor);
4262 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (parent_constructor), loc);
4267 base.CheckObsoleteAttribute (type_ds, loc);
4272 public class ConstructorThisInitializer : ConstructorInitializer {
4273 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4274 base (argument_list, pars, l)
4279 public class Constructor : MethodCore, IMethodData {
4280 public ConstructorBuilder ConstructorBuilder;
4281 public ConstructorInitializer Initializer;
4282 ListDictionary declarative_security;
4285 // Modifiers allowed for a constructor.
4287 public const int AllowedModifiers =
4289 Modifiers.PROTECTED |
4290 Modifiers.INTERNAL |
4296 bool has_compliant_args = false;
4298 // The spec claims that static is not permitted, but
4299 // my very own code has static constructors.
4301 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4302 ConstructorInitializer init, Location l)
4303 : base (ds, null, null, mod, AllowedModifiers, false,
4304 new MemberName (name), null, args, l)
4309 public override string GetSignatureForError()
4311 if (ConstructorBuilder == null)
4312 return GetSignatureForError (Parent);
4314 return TypeManager.CSharpSignature (ConstructorBuilder);
4317 public bool HasCompliantArgs {
4319 return has_compliant_args;
4323 public override AttributeTargets AttributeTargets {
4325 return AttributeTargets.Constructor;
4331 // Returns true if this is a default constructor
4333 public bool IsDefault ()
4335 if ((ModFlags & Modifiers.STATIC) != 0)
4336 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4337 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4340 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4341 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4342 (Initializer is ConstructorBaseInitializer) &&
4343 (Initializer.Arguments == null);
4346 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4348 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4349 if (declarative_security == null) {
4350 declarative_security = new ListDictionary ();
4352 a.ExtractSecurityPermissionSet (declarative_security);
4356 ConstructorBuilder.SetCustomAttribute (cb);
4359 protected override bool CheckForDuplications ()
4361 ArrayList ar = Parent.InstanceConstructors;
4363 int arLen = ar.Count;
4365 for (int i = 0; i < arLen; i++) {
4366 Constructor m = (Constructor) ar [i];
4367 if (IsDuplicateImplementation (m))
4374 protected override bool CheckBase ()
4376 // Check whether arguments were correct.
4377 if (!DoDefineParameters ())
4380 // TODO: skip the rest for generated ctor
4381 if ((ModFlags & Modifiers.STATIC) != 0)
4384 if (!CheckForDuplications ())
4387 if (Parent.Kind == Kind.Struct) {
4388 if (ParameterTypes.Length == 0) {
4389 Report.Error (568, Location,
4390 "Structs can not contain explicit parameterless " +
4395 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4396 Report.Error (666, Location, "Protected member in struct declaration");
4401 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4402 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4409 // Creates the ConstructorBuilder
4411 public override bool Define ()
4413 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4414 MethodAttributes.SpecialName);
4416 if ((ModFlags & Modifiers.STATIC) != 0){
4417 ca |= MethodAttributes.Static | MethodAttributes.Private;
4419 ca |= MethodAttributes.HideBySig;
4421 if ((ModFlags & Modifiers.PUBLIC) != 0)
4422 ca |= MethodAttributes.Public;
4423 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4424 if ((ModFlags & Modifiers.INTERNAL) != 0)
4425 ca |= MethodAttributes.FamORAssem;
4427 ca |= MethodAttributes.Family;
4428 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4429 ca |= MethodAttributes.Assembly;
4430 else if (IsDefault ())
4431 ca |= MethodAttributes.Public;
4433 ca |= MethodAttributes.Private;
4436 // Check if arguments were correct.
4440 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4441 ca, CallingConventions,
4444 if ((ModFlags & Modifiers.UNSAFE) != 0)
4445 ConstructorBuilder.InitLocals = false;
4447 TypeManager.AddMethod (ConstructorBuilder, this);
4450 // HACK because System.Reflection.Emit is lame
4452 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4460 public override void Emit ()
4462 EmitContext ec = CreateEmitContext (null, null);
4465 // extern methods have no bodies
4467 if ((ModFlags & Modifiers.EXTERN) != 0) {
4468 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4470 179, Location, "External constructor `" +
4471 TypeManager.CSharpSignature (ConstructorBuilder) +
4472 "' can not have a body");
4475 } else if (block == null) {
4477 501, Location, "Constructor `" +
4478 TypeManager.CSharpSignature (ConstructorBuilder) +
4479 "' must declare a body since it is not marked extern");
4483 if ((ModFlags & Modifiers.STATIC) == 0){
4484 if (Parent.Kind == Kind.Class && Initializer == null)
4485 Initializer = new ConstructorBaseInitializer (
4486 null, Parameters.EmptyReadOnlyParameters, Location);
4490 // Spec mandates that Initializers will not have
4494 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4496 ec.IsStatic = false;
4499 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4501 SourceMethod source = SourceMethod.Create (
4502 Parent, ConstructorBuilder, block);
4505 // Classes can have base initializers and instance field initializers.
4507 if (Parent.Kind == Kind.Class){
4508 if ((ModFlags & Modifiers.STATIC) == 0){
4511 // If we use a "this (...)" constructor initializer, then
4512 // do not emit field initializers, they are initialized in the other constructor
4514 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4515 Parent.EmitFieldInitializers (ec);
4518 if (Initializer != null) {
4519 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4520 Initializer.CheckObsoleteAttribute (Parent, Location);
4522 ec.TestObsoleteMethodUsage = false;
4523 Initializer.Emit (ec);
4526 if ((ModFlags & Modifiers.STATIC) != 0)
4527 Parent.EmitFieldInitializers (ec);
4529 if (OptAttributes != null)
4530 OptAttributes.Emit (ec, this);
4532 // If this is a non-static `struct' constructor and doesn't have any
4533 // initializer, it must initialize all of the struct's fields.
4534 if ((Parent.Kind == Kind.Struct) &&
4535 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4536 Block.AddThisVariable (Parent, Location);
4538 ec.EmitTopBlock (block, ParameterInfo, Location);
4541 source.CloseMethod ();
4545 if (declarative_security != null) {
4546 foreach (DictionaryEntry de in declarative_security) {
4547 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4554 // Is never override
4555 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
4560 protected override bool VerifyClsCompliance (DeclSpace ds)
4562 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4566 if (parameter_types.Length > 0) {
4567 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4569 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4571 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4572 foreach (Type param in parameter_types) {
4573 if (param.IsArray) {
4579 has_compliant_args = true;
4583 #region IMethodData Members
4585 public System.Reflection.CallingConventions CallingConventions {
4587 CallingConventions cc = Parameters.GetCallingConvention ();
4589 if (Parent.Kind == Kind.Class)
4590 if ((ModFlags & Modifiers.STATIC) == 0)
4591 cc |= CallingConventions.HasThis;
4593 // FIXME: How is `ExplicitThis' used in C#?
4599 public new Location Location {
4601 return base.Location;
4605 public MemberName MethodName {
4611 public Type ReturnType {
4617 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4619 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4620 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4623 public ObsoleteAttribute GetObsoleteAttribute ()
4628 public bool IsExcluded(EmitContext ec)
4633 GenericMethod IMethodData.GenericMethod {
4643 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4645 public interface IMethodData
4647 CallingConventions CallingConventions { get; }
4648 Location Location { get; }
4649 MemberName MethodName { get; }
4650 Type[] ParameterTypes { get; }
4651 Type ReturnType { get; }
4652 GenericMethod GenericMethod { get; }
4654 Attributes OptAttributes { get; }
4655 ToplevelBlock Block { get; }
4657 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4658 ObsoleteAttribute GetObsoleteAttribute ();
4659 string GetSignatureForError (TypeContainer tc);
4660 bool IsExcluded (EmitContext ec);
4661 bool IsClsCompliaceRequired (DeclSpace ds);
4665 // Encapsulates most of the Method's state
4667 public class MethodData {
4669 readonly IMethodData method;
4672 // The return type of this method
4674 public readonly GenericMethod GenericMethod;
4675 public readonly InternalParameters ParameterInfo;
4678 // Are we implementing an interface ?
4680 public bool IsImplementing = false;
4685 protected MemberBase member;
4686 protected int modifiers;
4687 protected MethodAttributes flags;
4688 protected Type declaring_type;
4689 protected MethodInfo parent_method;
4693 MethodBuilder builder = null;
4694 public MethodBuilder MethodBuilder {
4700 public Type DeclaringType {
4702 return declaring_type;
4706 public MethodData (MemberBase member, InternalParameters parameters,
4707 int modifiers, MethodAttributes flags, IMethodData method)
4709 this.member = member;
4710 this.ParameterInfo = parameters;
4711 this.modifiers = modifiers;
4714 this.method = method;
4717 public MethodData (MemberBase member, InternalParameters parameters,
4718 int modifiers, MethodAttributes flags,
4719 IMethodData method, MethodBuilder builder,
4720 GenericMethod generic, MethodInfo parent_method)
4721 : this (member, parameters, modifiers, flags, method)
4723 this.builder = builder;
4724 this.GenericMethod = generic;
4725 this.parent_method = parent_method;
4728 static string RemoveArity (string name)
4731 StringBuilder sb = new StringBuilder ();
4732 while (start < name.Length) {
4733 int pos = name.IndexOf ('`', start);
4735 sb.Append (name.Substring (start));
4739 sb.Append (name.Substring (start, pos-start));
4742 while ((pos < name.Length) && Char.IsNumber (name [pos]))
4748 return sb.ToString ();
4751 public bool Define (TypeContainer container)
4753 MethodInfo implementing = null;
4756 if (member.IsExplicitImpl)
4757 prefix = member.InterfaceType.FullName + ".";
4761 string name = method.MethodName.Basename;
4762 string method_name = prefix + name;
4764 Type[] ParameterTypes = method.ParameterTypes;
4766 if (container.Pending != null){
4767 if (member is Indexer)
4768 implementing = container.Pending.IsInterfaceIndexer (
4769 member.InterfaceType, method.ReturnType, ParameterTypes);
4771 implementing = container.Pending.IsInterfaceMethod (
4772 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4774 if (member.InterfaceType != null){
4775 if (implementing == null){
4776 Report.Error (539, method.Location,
4777 "'{0}' in explicit interface declaration is not an interface", method_name);
4784 // For implicit implementations, make sure we are public, for
4785 // explicit implementations, make sure we are private.
4787 if (implementing != null){
4789 // Setting null inside this block will trigger a more
4790 // verbose error reporting for missing interface implementations
4792 // The "candidate" function has been flagged already
4793 // but it wont get cleared
4795 if (member.IsExplicitImpl){
4796 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4797 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4798 implementing = null;
4800 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4801 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4803 // If this is an interface method implementation,
4804 // check for public accessibility
4806 implementing = null;
4807 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4808 // We may never be private.
4809 implementing = null;
4810 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4812 // We may be protected if we're overriding something.
4814 implementing = null;
4819 // Static is not allowed
4821 if ((modifiers & Modifiers.STATIC) != 0){
4822 implementing = null;
4823 Modifiers.Error_InvalidModifier (method.Location, "static");
4828 // If implementing is still valid, set flags
4830 if (implementing != null){
4832 // When implementing interface methods, set NewSlot
4833 // unless, we are overwriting a method.
4835 if (implementing.DeclaringType.IsInterface){
4836 if ((modifiers & Modifiers.OVERRIDE) == 0)
4837 flags |= MethodAttributes.NewSlot;
4840 MethodAttributes.Virtual |
4841 MethodAttributes.HideBySig;
4843 // Set Final unless we're virtual, abstract or already overriding a method.
4844 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4845 flags |= MethodAttributes.Final;
4847 IsImplementing = true;
4850 EmitContext ec = method.CreateEmitContext (container, null);
4852 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4854 if (builder == null)
4857 if (container.CurrentType != null)
4858 declaring_type = container.CurrentType;
4860 declaring_type = container.TypeBuilder;
4862 if ((modifiers & Modifiers.UNSAFE) != 0)
4863 builder.InitLocals = false;
4865 if (IsImplementing){
4867 // clear the pending implemntation flag
4869 if (member is Indexer) {
4870 container.Pending.ImplementIndexer (
4871 member.InterfaceType, builder, method.ReturnType,
4872 ParameterTypes, member.IsExplicitImpl);
4874 container.Pending.ImplementMethod (
4875 member.InterfaceType, name, method.ReturnType,
4876 ParameterTypes, member.IsExplicitImpl);
4878 if (member.IsExplicitImpl)
4879 container.TypeBuilder.DefineMethodOverride (
4880 builder, implementing);
4884 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4885 TypeManager.AddMethod (builder, method);
4887 if (GenericMethod != null) {
4888 bool is_override = member.IsExplicitImpl |
4889 ((modifiers & Modifiers.OVERRIDE) != 0);
4891 if (implementing != null)
4892 parent_method = implementing;
4894 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
4902 /// Create the MethodBuilder for the method
4904 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4906 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4908 if ((modifiers & extern_static) == extern_static) {
4910 if (method.OptAttributes != null) {
4911 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4912 if (dllimport_attribute != null) {
4913 flags |= MethodAttributes.PinvokeImpl;
4914 builder = dllimport_attribute.DefinePInvokeMethod (
4915 ec, container.TypeBuilder, method_name, flags,
4916 method.ReturnType, ParameterTypes);
4922 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4923 // We are more strict than Microsoft and report CS0626 like error
4924 if (method.OptAttributes == null ||
4925 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4926 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));
4931 if (builder == null)
4932 builder = container.TypeBuilder.DefineMethod (
4933 method_name, flags, method.CallingConventions,
4934 method.ReturnType, ParameterTypes);
4936 builder.SetGenericMethodSignature (
4937 flags, method.CallingConventions,
4938 method.ReturnType, ParameterTypes);
4944 public void Emit (TypeContainer container, Attributable kind)
4947 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4948 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4950 ec = method.CreateEmitContext (container, null);
4952 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container.Parent) != null)
4953 ec.TestObsoleteMethodUsage = false;
4955 Location loc = method.Location;
4956 Attributes OptAttributes = method.OptAttributes;
4958 if (OptAttributes != null)
4959 OptAttributes.Emit (ec, kind);
4961 if (member is MethodCore)
4962 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4964 SymbolWriter sw = CodeGen.SymbolWriter;
4965 ToplevelBlock block = method.Block;
4968 // abstract or extern methods have no bodies
4970 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4975 // abstract or extern methods have no bodies.
4977 if ((modifiers & Modifiers.ABSTRACT) != 0)
4979 500, method.Location, "Abstract method `" +
4980 TypeManager.CSharpSignature (builder) +
4981 "' can not have a body");
4983 if ((modifiers & Modifiers.EXTERN) != 0)
4985 179, method.Location, "External method `" +
4986 TypeManager.CSharpSignature (builder) +
4987 "' can not have a body");
4993 // Methods must have a body unless they're extern or abstract
4995 if (block == null) {
4997 501, method.Location, "Method `" +
4998 TypeManager.CSharpSignature (builder) +
4999 "' must declare a body since it is not marked " +
5000 "abstract or extern");
5004 SourceMethod source = SourceMethod.Create (
5005 container, MethodBuilder, method.Block);
5008 // Handle destructors specially
5010 // FIXME: This code generates buggy code
5012 if (member is Destructor)
5013 EmitDestructor (ec, block);
5015 ec.EmitTopBlock (block, ParameterInfo, loc);
5018 source.CloseMethod ();
5021 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5023 ILGenerator ig = ec.ig;
5025 Label finish = ig.DefineLabel ();
5027 block.SetDestructor ();
5029 ig.BeginExceptionBlock ();
5030 ec.ReturnLabel = finish;
5031 ec.HasReturnLabel = true;
5032 ec.EmitTopBlock (block, null, method.Location);
5034 // ig.MarkLabel (finish);
5035 ig.BeginFinallyBlock ();
5037 if (ec.ContainerType.BaseType != null) {
5038 Expression member_lookup = Expression.MemberLookup (
5039 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5040 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5042 if (member_lookup != null){
5043 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
5045 ig.Emit (OpCodes.Ldarg_0);
5046 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
5050 ig.EndExceptionBlock ();
5051 //ig.MarkLabel (ec.ReturnLabel);
5052 ig.Emit (OpCodes.Ret);
5056 public class Destructor : Method {
5058 public Destructor (TypeContainer ds, Expression return_type, int mod, string name,
5059 Parameters parameters, Attributes attrs, Location l)
5060 : base (ds, null, return_type, mod, false, new MemberName (name),
5061 parameters, attrs, l)
5064 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5066 if (a.Type == TypeManager.conditional_attribute_type) {
5067 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
5071 base.ApplyAttributeBuilder (a, cb);
5075 abstract public class MemberBase : MemberCore {
5076 public Expression Type;
5078 public MethodAttributes flags;
5080 protected readonly int explicit_mod_flags;
5083 // The "short" name of this property / indexer / event. This is the
5084 // name without the explicit interface.
5086 public string ShortName;
5089 // The type of this property / indexer / event
5091 public Type MemberType;
5094 // If true, this is an explicit interface implementation
5096 public bool IsExplicitImpl = false;
5099 // The name of the interface we are explicitly implementing
5101 public MemberName ExplicitInterfaceName = null;
5104 // Whether this is an interface member.
5106 public bool IsInterface;
5109 // If true, the interface type we are explicitly implementing
5111 public Type InterfaceType = null;
5114 // The constructor is only exposed to our children
5116 protected MemberBase (TypeContainer parent, Expression type, int mod,
5117 int allowed_mod, int def_mod, MemberName name,
5118 Attributes attrs, Location loc)
5119 : base (parent, name, attrs, loc)
5121 explicit_mod_flags = mod;
5123 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
5125 // Check for explicit interface implementation
5126 if (MemberName.Left != null) {
5127 ExplicitInterfaceName = MemberName.Left;
5128 ShortName = MemberName.Name;
5129 IsExplicitImpl = true;
5134 protected virtual bool CheckBase ()
5136 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5137 Report.Error (666, Location, "Protected member in struct declaration");
5141 if ((RootContext.WarningLevel >= 4) &&
5142 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5143 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5144 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5145 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
5151 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5153 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5157 foreach (Type partype in parameters){
5158 if (partype == TypeManager.void_type) {
5160 1547, Location, "Keyword 'void' cannot " +
5161 "be used in this context");
5165 if (partype.IsPointer){
5168 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5172 if (ds.AsAccessible (partype, ModFlags))
5175 if (this is Indexer)
5176 Report.Error (55, Location,
5177 "Inconsistent accessibility: parameter type `" +
5178 TypeManager.CSharpName (partype) + "' is less " +
5179 "accessible than indexer `" + Name + "'");
5180 else if ((this is Method) && ((Method) this).IsOperator)
5181 Report.Error (57, Location,
5182 "Inconsistent accessibility: parameter type `" +
5183 TypeManager.CSharpName (partype) + "' is less " +
5184 "accessible than operator `" + Name + "'");
5186 Report.Error (51, Location,
5187 "Inconsistent accessibility: parameter type `" +
5188 TypeManager.CSharpName (partype) + "' is less " +
5189 "accessible than method `" + Name + "'");
5196 protected virtual bool DoDefineBase ()
5198 EmitContext ec = Parent.EmitContext;
5200 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5203 throw new InternalErrorException ();
5206 ModFlags = Modifiers.PUBLIC |
5207 Modifiers.ABSTRACT |
5208 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5210 flags = MethodAttributes.Public |
5211 MethodAttributes.Abstract |
5212 MethodAttributes.HideBySig |
5213 MethodAttributes.NewSlot |
5214 MethodAttributes.Virtual;
5216 if (!Parent.MethodModifiersValid (ModFlags, Name, Location))
5219 flags = Modifiers.MethodAttr (ModFlags);
5225 protected virtual bool DoDefine (DeclSpace decl)
5227 EmitContext ec = decl.EmitContext;
5229 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5231 ec.InUnsafe = InUnsafe;
5233 // Lookup Type, verify validity
5234 bool old_unsafe = ec.InUnsafe;
5235 ec.InUnsafe = InUnsafe;
5236 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
5237 ec.InUnsafe = old_unsafe;
5242 MemberType = texpr.Type;
5244 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5245 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5246 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5251 // verify accessibility
5252 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5253 if (this is Property)
5254 Report.Error (53, Location,
5255 "Inconsistent accessibility: property type `" +
5256 TypeManager.CSharpName (MemberType) + "' is less " +
5257 "accessible than property `" + Name + "'");
5258 else if (this is Indexer)
5259 Report.Error (54, Location,
5260 "Inconsistent accessibility: indexer return type `" +
5261 TypeManager.CSharpName (MemberType) + "' is less " +
5262 "accessible than indexer `" + Name + "'");
5263 else if (this is MethodCore) {
5264 if (this is Operator)
5265 Report.Error (56, Location,
5266 "Inconsistent accessibility: return type `" +
5267 TypeManager.CSharpName (MemberType) + "' is less " +
5268 "accessible than operator `" + Name + "'");
5270 Report.Error (50, Location,
5271 "Inconsistent accessibility: return type `" +
5272 TypeManager.CSharpName (MemberType) + "' is less " +
5273 "accessible than method `" + Name + "'");
5275 Report.Error (52, Location,
5276 "Inconsistent accessibility: field type `" +
5277 TypeManager.CSharpName (MemberType) + "' is less " +
5278 "accessible than field `" + Name + "'");
5283 if (MemberType.IsPointer && !UnsafeOK (Parent))
5286 if (IsExplicitImpl) {
5287 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
5288 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5289 if (iface_texpr == null)
5292 InterfaceType = iface_texpr.Type;
5294 if (!InterfaceType.IsInterface) {
5295 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5299 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5302 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5309 /// The name of the member can be changed during definition (see IndexerName attribute)
5311 protected virtual void UpdateMemberName ()
5313 MemberName.Name = ShortName;
5316 public override string GetSignatureForError (TypeContainer tc)
5318 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5321 protected bool IsTypePermitted ()
5323 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5324 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5330 protected override bool VerifyClsCompliance(DeclSpace ds)
5332 if (base.VerifyClsCompliance (ds)) {
5336 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5337 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5342 protected override void VerifyObsoleteAttribute()
5344 CheckUsageOfObsoleteAttribute (MemberType);
5349 // Fields and Events both generate FieldBuilders, we use this to share
5350 // their common bits. This is also used to flag usage of the field
5352 abstract public class FieldBase : MemberBase {
5353 public FieldBuilder FieldBuilder;
5354 public Status status;
5357 public enum Status : byte {
5360 HAS_OFFSET = 4 // Used by FieldMember.
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
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 status |= Status.HAS_OFFSET;
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 && ((status & Status.HAS_OFFSET) == 0) && (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()
5864 throw new NotSupportedException ();
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);
6625 // For this event syntax we don't report error CS0067
6626 // because it is hard to do it.
6630 public override string[] ValidAttributeTargets {
6632 return attribute_targets;
6638 /// Event is declared like field.
6640 public class EventField: Event {
6642 static string[] attribute_targets = new string [] { "event", "field", "method" };
6643 static string[] attribute_targets_interface = new string[] { "event", "method" };
6645 public EventField (TypeContainer parent, Expression type, int mod_flags,
6646 bool is_iface, MemberName name, Object init,
6647 Attributes attrs, Location loc)
6648 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6650 Add = new AddDelegateMethod (this);
6651 Remove = new RemoveDelegateMethod (this);
6654 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6656 if (a.Target == AttributeTargets.Field) {
6657 FieldBuilder.SetCustomAttribute (cb);
6661 if (a.Target == AttributeTargets.Method) {
6662 Add.ApplyAttributeBuilder (a, cb);
6663 Remove.ApplyAttributeBuilder (a, cb);
6667 base.ApplyAttributeBuilder (a, cb);
6670 public override string[] ValidAttributeTargets {
6672 return IsInterface ? attribute_targets_interface : attribute_targets;
6677 public abstract class Event : FieldBase {
6679 protected sealed class AddDelegateMethod: DelegateMethod
6682 public AddDelegateMethod (Event method):
6683 base (method, "add_")
6687 public AddDelegateMethod (Event method, Accessor accessor):
6688 base (method, accessor, "add_")
6692 protected override MethodInfo DelegateMethodInfo {
6694 return TypeManager.delegate_combine_delegate_delegate;
6700 protected sealed class RemoveDelegateMethod: DelegateMethod
6702 public RemoveDelegateMethod (Event method):
6703 base (method, "remove_")
6707 public RemoveDelegateMethod (Event method, Accessor accessor):
6708 base (method, accessor, "remove_")
6712 protected override MethodInfo DelegateMethodInfo {
6714 return TypeManager.delegate_remove_delegate_delegate;
6720 public abstract class DelegateMethod: AbstractPropertyEventMethod
6722 protected readonly Event method;
6723 ImplicitParameter param_attr;
6725 static string[] attribute_targets = new string [] { "method", "param", "return" };
6727 public DelegateMethod (Event method, string prefix)
6728 : base (method, prefix)
6730 this.method = method;
6733 public DelegateMethod (Event method, Accessor accessor, string prefix)
6734 : base (method, accessor, prefix)
6736 this.method = method;
6739 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6741 if (a.Target == AttributeTargets.Parameter) {
6742 if (param_attr == null)
6743 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6745 param_attr.ApplyAttributeBuilder (a, cb);
6749 base.ApplyAttributeBuilder (a, cb);
6752 public override AttributeTargets AttributeTargets {
6754 return AttributeTargets.Method;
6758 public override bool IsClsCompliaceRequired(DeclSpace ds)
6760 return method.IsClsCompliaceRequired (ds);
6763 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6765 method_data = new MethodData (method, ip, method.ModFlags,
6766 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6768 if (!method_data.Define (container))
6771 MethodBuilder mb = method_data.MethodBuilder;
6772 mb.DefineParameter (1, ParameterAttributes.None, "value");
6777 public override void Emit (TypeContainer tc)
6779 if (block != null) {
6784 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6785 EmitContext ec = CreateEmitContext (tc, ig);
6786 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6788 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6789 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6790 ig.Emit (OpCodes.Ldsfld, field_info);
6791 ig.Emit (OpCodes.Ldarg_0);
6792 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6793 ig.Emit (OpCodes.Castclass, method.MemberType);
6794 ig.Emit (OpCodes.Stsfld, field_info);
6796 ig.Emit (OpCodes.Ldarg_0);
6797 ig.Emit (OpCodes.Ldarg_0);
6798 ig.Emit (OpCodes.Ldfld, field_info);
6799 ig.Emit (OpCodes.Ldarg_1);
6800 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6801 ig.Emit (OpCodes.Castclass, method.MemberType);
6802 ig.Emit (OpCodes.Stfld, field_info);
6804 ig.Emit (OpCodes.Ret);
6807 protected abstract MethodInfo DelegateMethodInfo { get; }
6809 public override Type[] ParameterTypes {
6811 return new Type[] { method.MemberType };
6815 public override Type ReturnType {
6817 return TypeManager.void_type;
6821 public override EmitContext CreateEmitContext (TypeContainer tc,
6824 return new EmitContext (
6825 tc, method.Parent, Location, ig, ReturnType,
6826 method.ModFlags, false);
6829 public override string GetSignatureForError (TypeContainer tc)
6831 return String.Concat (tc.Name, '.', method.Name);
6834 public override ObsoleteAttribute GetObsoleteAttribute ()
6836 return method.GetObsoleteAttribute (method.Parent);
6839 public override string[] ValidAttributeTargets {
6841 return attribute_targets;
6847 const int AllowedModifiers =
6850 Modifiers.PROTECTED |
6851 Modifiers.INTERNAL |
6856 Modifiers.OVERRIDE |
6860 const int AllowedInterfaceModifiers =
6863 public DelegateMethod Add, Remove;
6864 public MyEventBuilder EventBuilder;
6865 public MethodBuilder AddBuilder, RemoveBuilder;
6867 MethodData AddData, RemoveData;
6869 public Event (TypeContainer parent, Expression type, int mod_flags,
6870 bool is_iface, MemberName name, Object init, Attributes attrs,
6872 : base (parent, type, mod_flags,
6873 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6874 name, init, attrs, loc)
6876 IsInterface = is_iface;
6879 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6881 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6882 a.Error_InvalidSecurityParent ();
6886 EventBuilder.SetCustomAttribute (cb);
6889 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6891 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6894 public override AttributeTargets AttributeTargets {
6896 return AttributeTargets.Event;
6900 public override bool Define ()
6902 EventAttributes e_attr;
6903 e_attr = EventAttributes.None;
6905 if (!DoDefineBase ())
6908 if (!DoDefine (Parent))
6911 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6912 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6913 "': abstract event can not have an initializer");
6917 if (!TypeManager.IsDelegateType (MemberType)) {
6918 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6919 "' : event must be of a delegate type");
6923 EmitContext ec = Parent.EmitContext;
6925 throw new InternalErrorException ("Event.Define called too early?");
6926 bool old_unsafe = ec.InUnsafe;
6927 ec.InUnsafe = InUnsafe;
6929 Parameter [] parms = new Parameter [1];
6930 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6931 Parameters parameters = new Parameters (parms, null, Location);
6932 Type [] types = parameters.GetParameterInfo (ec);
6933 InternalParameters ip = new InternalParameters (types, parameters);
6935 ec.InUnsafe = old_unsafe;
6941 // Now define the accessors
6944 AddBuilder = Add.Define (Parent, ip);
6945 if (AddBuilder == null)
6948 RemoveBuilder = Remove.Define (Parent, ip);
6949 if (RemoveBuilder == null)
6952 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6954 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6955 FieldBuilder = Parent.TypeBuilder.DefineField (
6957 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6958 TypeManager.RegisterPrivateFieldOfEvent (
6959 (EventInfo) EventBuilder, FieldBuilder);
6960 TypeManager.RegisterFieldBase (FieldBuilder, this);
6963 EventBuilder.SetAddOnMethod (AddBuilder);
6964 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6966 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6970 protected override bool CheckBase ()
6972 if (!base.CheckBase ())
6975 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6976 if (!(conflict_symbol is EventInfo)) {
6977 Report.SymbolRelatedToPreviousError (conflict_symbol);
6978 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6986 public override void Emit ()
6988 if (OptAttributes != null) {
6989 EmitContext ec = new EmitContext (
6990 Parent, Location, null, MemberType, ModFlags);
6991 OptAttributes.Emit (ec, this);
6996 Remove.Emit (Parent);
7002 public override string GetSignatureForError ()
7004 if (EventBuilder == null)
7005 return base.GetSignatureForError (Parent);
7007 return TypeManager.GetFullNameSignature (EventBuilder);
7012 public class Indexer : PropertyBase {
7014 class GetIndexerMethod: GetMethod
7016 public GetIndexerMethod (MethodCore method):
7021 public GetIndexerMethod (MethodCore method, Accessor accessor):
7022 base (method, accessor)
7026 public override Type[] ParameterTypes {
7028 return method.ParameterTypes;
7033 class SetIndexerMethod: SetMethod
7035 readonly Parameters parameters;
7037 public SetIndexerMethod (MethodCore method):
7042 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7043 base (method, accessor)
7045 this.parameters = parameters;
7048 public override Type[] ParameterTypes {
7050 int top = method.ParameterTypes.Length;
7051 Type [] set_pars = new Type [top + 1];
7052 method.ParameterTypes.CopyTo (set_pars, 0);
7053 set_pars [top] = method.MemberType;
7058 protected override InternalParameters GetParameterInfo (EmitContext ec)
7060 Parameter [] fixed_parms = parameters.FixedParameters;
7062 if (fixed_parms == null){
7063 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7064 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7065 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7067 // Here is the problem: the `value' parameter has
7068 // to come *after* the array parameter in the declaration
7070 // X (object [] x, Type value)
7073 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7074 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7078 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7080 fixed_parms.CopyTo (tmp, 0);
7081 tmp [fixed_parms.Length] = new Parameter (
7082 method.Type, "value", Parameter.Modifier.NONE, null);
7084 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7085 Type [] types = set_formal_params.GetParameterInfo (ec);
7087 return new InternalParameters (types, set_formal_params);
7091 const int AllowedModifiers =
7094 Modifiers.PROTECTED |
7095 Modifiers.INTERNAL |
7099 Modifiers.OVERRIDE |
7104 const int AllowedInterfaceModifiers =
7108 // Are we implementing an interface ?
7110 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7111 bool is_iface, Parameters parameters, Attributes attrs,
7112 Accessor get_block, Accessor set_block, Location loc)
7113 : base (parent, type, mod,
7114 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7115 is_iface, name, parameters, attrs, loc)
7117 if (get_block == null)
7118 Get = new GetIndexerMethod (this);
7120 Get = new GetIndexerMethod (this, get_block);
7122 if (set_block == null)
7123 Set = new SetIndexerMethod (this);
7125 Set = new SetIndexerMethod (this, parameters, set_block);
7128 public override bool Define ()
7130 PropertyAttributes prop_attr =
7131 PropertyAttributes.RTSpecialName |
7132 PropertyAttributes.SpecialName;
7134 if (!DoDefineBase ())
7137 if (!base.Define ())
7140 if (OptAttributes != null) {
7141 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7142 if (indexer_attr != null) {
7143 // Remove the attribute from the list because it is not emitted
7144 OptAttributes.Attrs.Remove (indexer_attr);
7146 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7148 if (IsExplicitImpl) {
7149 Report.Error (415, indexer_attr.Location,
7150 "The 'IndexerName' attribute is valid only on an" +
7151 "indexer that is not an explicit interface member declaration");
7155 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7156 Report.Error (609, indexer_attr.Location,
7157 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7161 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7162 Report.Error (633, indexer_attr.Location,
7163 "The argument to the 'IndexerName' attribute must be a valid identifier");
7167 UpdateMemberName ();
7171 if (InterfaceType != null) {
7172 string parent_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7173 if (parent_IndexerName != Name)
7174 ShortName = parent_IndexerName;
7175 UpdateMemberName ();
7178 if (!Parent.AddToMemberContainer (this, true) ||
7179 !Parent.AddToMemberContainer (Get, true) || !Parent.AddToMemberContainer (Set, true))
7185 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7187 GetBuilder = Get.Define (Parent);
7188 if (GetBuilder == null)
7193 SetBuilder = Set.Define (Parent);
7194 if (SetBuilder == null)
7199 // Now name the parameters
7201 Parameter [] p = Parameters.FixedParameters;
7203 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7204 Report.Error (631, Location, "ref and out are not valid in this context");
7210 for (i = 0; i < p.Length; ++i) {
7212 GetBuilder.DefineParameter (
7213 i + 1, p [i].Attributes, p [i].Name);
7216 SetBuilder.DefineParameter (
7217 i + 1, p [i].Attributes, p [i].Name);
7221 SetBuilder.DefineParameter (
7222 i + 1, ParameterAttributes.None, "value");
7224 if (i != ParameterTypes.Length) {
7225 Parameter array_param = Parameters.ArrayParameter;
7227 SetBuilder.DefineParameter (
7228 i + 1, array_param.Attributes, array_param.Name);
7232 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7233 Name, prop_attr, MemberType, ParameterTypes);
7236 PropertyBuilder.SetGetMethod (GetBuilder);
7239 PropertyBuilder.SetSetMethod (SetBuilder);
7241 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7246 public override string GetSignatureForError ()
7248 if (PropertyBuilder == null)
7249 return GetSignatureForError (Parent);
7251 return TypeManager.CSharpSignature (PropertyBuilder, true);
7254 public override string GetSignatureForError(TypeContainer tc)
7256 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7260 public class Operator : MethodCore, IIteratorContainer {
7262 const int AllowedModifiers =
7268 public enum OpType : byte {
7278 // Unary and Binary operators
7301 // Implicit and Explicit
7306 public readonly OpType OperatorType;
7307 public MethodBuilder OperatorMethodBuilder;
7309 public Method OperatorMethod;
7311 static string[] attribute_targets = new string [] { "method", "return" };
7313 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7314 int mod_flags, Parameters parameters,
7315 ToplevelBlock block, Attributes attrs, Location loc)
7316 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7317 new MemberName ("op_" + type), attrs, parameters, loc)
7319 OperatorType = type;
7323 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7325 OperatorMethod.ApplyAttributeBuilder (a, cb);
7328 public override AttributeTargets AttributeTargets {
7330 return AttributeTargets.Method;
7334 protected override bool CheckGenericOverride (MethodInfo method, string name)
7339 protected override bool CheckForDuplications()
7341 ArrayList ar = Parent.Operators;
7343 int arLen = ar.Count;
7345 for (int i = 0; i < arLen; i++) {
7346 Operator o = (Operator) ar [i];
7347 if (IsDuplicateImplementation (o))
7352 ar = Parent.Methods;
7354 int arLen = ar.Count;
7356 for (int i = 0; i < arLen; i++) {
7357 Method m = (Method) ar [i];
7358 if (IsDuplicateImplementation (m))
7366 public override bool Define ()
7368 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7369 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7370 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7377 OperatorMethod = new Method (
7378 Parent, null, Type, ModFlags, false, MemberName,
7379 Parameters, OptAttributes, Location);
7381 OperatorMethod.Block = Block;
7382 OperatorMethod.IsOperator = true;
7383 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7384 OperatorMethod.Define ();
7386 if (OperatorMethod.MethodBuilder == null)
7389 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7391 parameter_types = OperatorMethod.ParameterTypes;
7392 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7393 Type return_type = OperatorMethod.ReturnType;
7394 Type first_arg_type = parameter_types [0];
7399 // Rules for conversion operators
7401 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7402 if (first_arg_type == return_type && first_arg_type == declaring_type){
7405 "User-defined conversion cannot take an object of the " +
7406 "enclosing type and convert to an object of the enclosing" +
7411 if (first_arg_type != declaring_type && return_type != declaring_type){
7414 "User-defined conversion must convert to or from the " +
7419 if (first_arg_type == TypeManager.object_type ||
7420 return_type == TypeManager.object_type){
7423 "User-defined conversion cannot convert to or from " +
7428 if (first_arg_type.IsInterface || return_type.IsInterface){
7431 "User-defined conversion cannot convert to or from an " +
7436 if (first_arg_type.IsSubclassOf (return_type)
7437 || return_type.IsSubclassOf (first_arg_type)){
7438 if (declaring_type.IsSubclassOf (return_type)) {
7439 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7442 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7445 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7446 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7447 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");
7450 } else if (Parameters.FixedParameters.Length == 1) {
7451 // Checks for Unary operators
7453 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7454 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7455 Report.Error (448, Location,
7456 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7459 if (first_arg_type != declaring_type){
7461 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7466 if (first_arg_type != declaring_type){
7469 "The parameter of a unary operator must be the " +
7474 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7475 if (return_type != TypeManager.bool_type){
7478 "The return type of operator True or False " +
7485 // Checks for Binary operators
7487 if (first_arg_type != declaring_type &&
7488 parameter_types [1] != declaring_type){
7491 "One of the parameters of a binary operator must " +
7492 "be the containing type");
7500 public override void Emit ()
7503 // abstract or extern methods have no bodies
7505 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7508 OperatorMethod.Emit ();
7512 // Operator cannot be override
7513 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
7518 public static string GetName (OpType ot)
7521 case OpType.LogicalNot:
7523 case OpType.OnesComplement:
7525 case OpType.Increment:
7527 case OpType.Decrement:
7533 case OpType.Addition:
7535 case OpType.Subtraction:
7537 case OpType.UnaryPlus:
7539 case OpType.UnaryNegation:
7541 case OpType.Multiply:
7543 case OpType.Division:
7545 case OpType.Modulus:
7547 case OpType.BitwiseAnd:
7549 case OpType.BitwiseOr:
7551 case OpType.ExclusiveOr:
7553 case OpType.LeftShift:
7555 case OpType.RightShift:
7557 case OpType.Equality:
7559 case OpType.Inequality:
7561 case OpType.GreaterThan:
7563 case OpType.LessThan:
7565 case OpType.GreaterThanOrEqual:
7567 case OpType.LessThanOrEqual:
7569 case OpType.Implicit:
7571 case OpType.Explicit:
7577 public override string GetSignatureForError (TypeContainer tc)
7579 StringBuilder sb = new StringBuilder ();
7580 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7581 Parameters.FixedParameters [0].GetSignatureForError ());
7583 if (Parameters.FixedParameters.Length > 1) {
7585 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7588 return sb.ToString ();
7591 public override string GetSignatureForError ()
7596 public override string ToString ()
7598 if (OperatorMethod == null)
7601 Type return_type = OperatorMethod.ReturnType;
7602 Type [] param_types = OperatorMethod.ParameterTypes;
7604 if (Parameters.FixedParameters.Length == 1)
7605 return String.Format (
7606 "{0} operator {1}({2})",
7607 TypeManager.CSharpName (return_type),
7608 GetName (OperatorType),
7611 return String.Format (
7612 "{0} operator {1}({2}, {3})",
7613 TypeManager.CSharpName (return_type),
7614 GetName (OperatorType),
7615 param_types [0], param_types [1]);
7618 public override string[] ValidAttributeTargets {
7620 return attribute_targets;
7624 public void SetYields ()
7626 ModFlags |= Modifiers.METHOD_YIELDS;
7631 // This is used to compare method signatures
7633 struct MethodSignature {
7635 public Type RetType;
7636 public Type [] Parameters;
7639 /// This delegate is used to extract methods which have the
7640 /// same signature as the argument
7642 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7644 public MethodSignature (string name, Type ret_type, Type [] parameters)
7649 if (parameters == null)
7650 Parameters = TypeManager.NoTypes;
7652 Parameters = parameters;
7655 public override string ToString ()
7658 if (Parameters.Length != 0){
7659 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7660 for (int i = 0; i < Parameters.Length; i++){
7661 sb.Append (Parameters [i]);
7662 if (i+1 < Parameters.Length)
7665 pars = sb.ToString ();
7668 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7671 public override int GetHashCode ()
7673 return Name.GetHashCode ();
7676 public override bool Equals (Object o)
7678 MethodSignature other = (MethodSignature) o;
7680 if (other.Name != Name)
7683 if (other.RetType != RetType)
7686 if (Parameters == null){
7687 if (other.Parameters == null)
7692 if (other.Parameters == null)
7695 int c = Parameters.Length;
7696 if (other.Parameters.Length != c)
7699 for (int i = 0; i < c; i++)
7700 if (other.Parameters [i] != Parameters [i])
7706 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7708 MethodSignature sig = (MethodSignature) filter_criteria;
7710 if (m.Name != sig.Name)
7714 MethodInfo mi = m as MethodInfo;
7715 PropertyInfo pi = m as PropertyInfo;
7718 ReturnType = mi.ReturnType;
7719 else if (pi != null)
7720 ReturnType = pi.PropertyType;
7725 // we use sig.RetType == null to mean `do not check the
7726 // method return value.
7728 if (sig.RetType != null)
7729 if (ReturnType != sig.RetType)
7734 args = TypeManager.GetArgumentTypes (mi);
7736 args = TypeManager.GetArgumentTypes (pi);
7737 Type [] sigp = sig.Parameters;
7739 if (args.Length != sigp.Length)
7742 for (int i = args.Length; i > 0; ){
7744 if (args [i] != sigp [i])