2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
36 using System.Collections;
37 using System.Collections.Specialized;
38 using System.Reflection;
39 using System.Reflection.Emit;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42 using System.Security;
43 using System.Security.Permissions;
46 using Mono.CompilerServices.SymbolWriter;
48 namespace Mono.CSharp {
58 /// This is the base class for structs and classes.
60 public abstract class TypeContainer : DeclSpace, IMemberContainer {
62 public class MemberCoreArrayList: ArrayList
65 /// Defines the MemberCore objects that are in this array
67 public virtual void DefineContainerMembers ()
69 foreach (MemberCore mc in this) {
74 public virtual void Emit ()
76 foreach (MemberCore mc in this)
81 public class MethodArrayList: MemberCoreArrayList
89 CachedMethods cached_method;
90 TypeContainer container;
92 public MethodArrayList (TypeContainer container)
94 this.container = container;
98 /// Method container contains Equals method
100 public bool HasEquals {
102 cached_method |= CachedMethods.Equals;
106 return (cached_method & CachedMethods.Equals) != 0;
111 /// Method container contains GetHashCode method
113 public bool HasGetHashCode {
115 cached_method |= CachedMethods.GetHashCode;
119 return (cached_method & CachedMethods.GetHashCode) != 0;
123 public override void DefineContainerMembers ()
125 base.DefineContainerMembers ();
127 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
128 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
134 public sealed class IndexerArrayList: MemberCoreArrayList
137 /// The indexer name for this container
139 public string IndexerName = DefaultIndexerName;
141 bool seen_normal_indexers = false;
143 TypeContainer container;
145 public IndexerArrayList (TypeContainer container)
147 this.container = container;
151 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
152 /// class is consistent. Either it is `Item' or it is the name defined by all the
153 /// indexers with the `IndexerName' attribute.
155 /// Turns out that the IndexerNameAttribute is applied to each indexer,
156 /// but it is never emitted, instead a DefaultMember attribute is attached
159 public override void DefineContainerMembers()
161 base.DefineContainerMembers ();
163 string class_indexer_name = null;
166 // If there's both an explicit and an implicit interface implementation, the
167 // explicit one actually implements the interface while the other one is just
168 // a normal indexer. See bug #37714.
171 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
172 foreach (Indexer i in this) {
173 if (i.InterfaceType != null) {
174 if (seen_normal_indexers)
175 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
179 seen_normal_indexers = true;
181 if (class_indexer_name == null) {
182 class_indexer_name = i.ShortName;
186 if (i.ShortName != class_indexer_name)
187 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
190 if (class_indexer_name != null)
191 IndexerName = class_indexer_name;
194 public override void Emit ()
198 if (!seen_normal_indexers)
201 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
202 container.TypeBuilder.SetCustomAttribute (cb);
206 public class OperatorArrayList: MemberCoreArrayList
208 TypeContainer container;
210 public OperatorArrayList (TypeContainer container)
212 this.container = container;
216 // Operator pair checking
221 public Type ret_type;
222 public Type type1, type2;
224 public Operator.OpType ot;
226 public OperatorEntry (int f, Operator o)
230 ret_type = o.OperatorMethod.ReturnType;
231 Type [] pt = o.OperatorMethod.ParameterTypes;
238 public override int GetHashCode ()
240 return ret_type.GetHashCode ();
243 public override bool Equals (object o)
245 OperatorEntry other = (OperatorEntry) o;
247 if (other.ret_type != ret_type)
249 if (other.type1 != type1)
251 if (other.type2 != type2)
258 // Checks that some operators come in pairs:
264 // They are matched based on the return type and the argument types
266 void CheckPairedOperators ()
268 Hashtable pairs = new Hashtable (null, null);
269 Operator true_op = null;
270 Operator false_op = null;
271 bool has_equality_or_inequality = false;
273 // Register all the operators we care about.
274 foreach (Operator op in this){
277 switch (op.OperatorType){
278 case Operator.OpType.Equality:
280 has_equality_or_inequality = true;
282 case Operator.OpType.Inequality:
284 has_equality_or_inequality = true;
287 case Operator.OpType.True:
290 case Operator.OpType.False:
294 case Operator.OpType.GreaterThan:
296 case Operator.OpType.LessThan:
299 case Operator.OpType.GreaterThanOrEqual:
301 case Operator.OpType.LessThanOrEqual:
307 OperatorEntry oe = new OperatorEntry (reg, op);
309 object o = pairs [oe];
313 oe = (OperatorEntry) o;
318 if (true_op != null){
319 if (false_op == null)
320 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
321 } else if (false_op != null)
322 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
325 // Look for the mistakes.
327 foreach (DictionaryEntry de in pairs){
328 OperatorEntry oe = (OperatorEntry) de.Key;
335 case Operator.OpType.Equality:
338 case Operator.OpType.Inequality:
341 case Operator.OpType.GreaterThan:
344 case Operator.OpType.LessThan:
347 case Operator.OpType.GreaterThanOrEqual:
350 case Operator.OpType.LessThanOrEqual:
354 Report.Error (216, oe.op.Location,
355 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
358 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
359 if (container.Methods == null || !container.Methods.HasEquals)
360 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
362 if (container.Methods == null || !container.Methods.HasGetHashCode)
363 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
367 public override void DefineContainerMembers ()
369 base.DefineContainerMembers ();
370 CheckPairedOperators ();
375 // Whether this is a struct, class or interface
376 public readonly Kind Kind;
378 // Holds a list of classes and structures
381 // Holds the list of properties
382 MemberCoreArrayList properties;
384 // Holds the list of enumerations
385 MemberCoreArrayList enums;
387 // Holds the list of delegates
388 MemberCoreArrayList delegates;
390 // Holds the list of constructors
391 protected MemberCoreArrayList instance_constructors;
393 // Holds the list of fields
394 MemberCoreArrayList fields;
396 // Holds a list of fields that have initializers
397 protected ArrayList initialized_fields;
399 // Holds a list of static fields that have initializers
400 protected ArrayList initialized_static_fields;
402 // Holds the list of constants
403 MemberCoreArrayList constants;
406 MemberCoreArrayList interfaces;
408 // Holds the methods.
409 MethodArrayList methods;
412 protected MemberCoreArrayList events;
414 // Holds the indexers
415 IndexerArrayList indexers;
417 // Holds the operators
418 MemberCoreArrayList operators;
420 // Holds the iterators
423 // Holds the parts of a partial class;
427 // Pointers to the default constructor and the default static constructor
429 protected Constructor default_constructor;
430 protected Constructor default_static_constructor;
433 // Whether we have at least one non-static field
435 bool have_nonstatic_fields = false;
438 // This one is computed after we can distinguish interfaces
439 // from classes from the arraylist `type_bases'
441 string base_class_name;
444 ArrayList type_bases;
446 bool members_defined;
447 bool members_defined_ok;
449 // The interfaces we implement.
450 protected Type[] ifaces;
451 protected Type ptype;
453 // The base member cache and our member cache
454 MemberCache base_cache;
455 MemberCache member_cache;
457 public const string DefaultIndexerName = "Item";
461 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
462 Attributes attrs, Kind kind, Location l)
463 : base (ns, parent, name, attrs, l)
467 types = new ArrayList ();
469 base_class_name = null;
472 public bool AddToMemberContainer (MemberCore symbol)
474 return AddToContainer (symbol, String.Concat (Name, '.', symbol.Name), symbol.Name);
477 bool AddToTypeContainer (DeclSpace ds)
479 return AddToContainer (ds, ds.Name, ds.Basename);
482 public void AddConstant (Const constant)
484 if (!AddToMemberContainer (constant))
487 if (constants == null)
488 constants = new MemberCoreArrayList ();
490 constants.Add (constant);
493 public void AddEnum (Mono.CSharp.Enum e)
495 if (!AddToTypeContainer (e))
499 enums = new MemberCoreArrayList ();
504 public void AddClassOrStruct (TypeContainer c)
506 if (!AddToTypeContainer (c))
512 public void AddDelegate (Delegate d)
514 if (!AddToTypeContainer (d))
517 if (delegates == null)
518 delegates = new MemberCoreArrayList ();
523 public void AddMethod (Method method)
525 if (!AddToMemberContainer (method))
529 methods = new MethodArrayList (this);
531 if (method.Name.IndexOf ('.') != -1)
532 methods.Insert (0, method);
534 methods.Add (method);
537 public void AddConstructor (Constructor c)
539 if (c.Name != Basename) {
540 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
543 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
546 if (default_static_constructor != null) {
547 Report.SymbolRelatedToPreviousError (default_static_constructor);
548 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
549 "called '{1}' with the same parameter types", Name, c.Name);
553 default_static_constructor = c;
556 if (default_constructor != null) {
557 Report.SymbolRelatedToPreviousError (default_constructor);
558 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
559 "called '{1}' with the same parameter types", Name, c.Name);
562 default_constructor = c;
565 if (instance_constructors == null)
566 instance_constructors = new MemberCoreArrayList ();
568 instance_constructors.Add (c);
572 public void AddInterface (TypeContainer iface)
574 if (!AddToTypeContainer (iface))
577 if (interfaces == null) {
578 interfaces = new MemberCoreArrayList ();
581 interfaces.Add (iface);
584 public void AddField (Field field)
586 if (!AddToMemberContainer (field))
590 fields = new MemberCoreArrayList ();
594 if (field.HasInitializer){
595 if ((field.ModFlags & Modifiers.STATIC) != 0){
596 if (initialized_static_fields == null)
597 initialized_static_fields = new ArrayList ();
599 initialized_static_fields.Add (field);
602 if (initialized_fields == null)
603 initialized_fields = new ArrayList ();
605 initialized_fields.Add (field);
609 if ((field.ModFlags & Modifiers.STATIC) == 0)
610 have_nonstatic_fields = true;
613 public void AddProperty (Property prop)
615 if (!AddToMemberContainer (prop) ||
616 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
619 if (properties == null)
620 properties = new MemberCoreArrayList ();
622 if (prop.Name.IndexOf ('.') != -1)
623 properties.Insert (0, prop);
625 properties.Add (prop);
628 public void AddEvent (Event e)
630 if (!AddToMemberContainer (e))
633 if (e is EventProperty) {
634 if (!AddToMemberContainer (e.Add))
637 if (!AddToMemberContainer (e.Remove))
642 events = new MemberCoreArrayList ();
648 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
650 public void AddIndexer (Indexer i)
652 if (indexers == null)
653 indexers = new IndexerArrayList (this);
655 if (i.IsExplicitImpl)
656 indexers.Insert (0, i);
661 public void AddOperator (Operator op)
663 if (!AddToMemberContainer (op))
666 if (operators == null)
667 operators = new OperatorArrayList (this);
672 public void AddIterator (Iterator i)
674 if (iterators == null)
675 iterators = new ArrayList ();
680 public void AddType (TypeContainer tc)
685 public void AddPart (ClassPart part)
688 parts = new ArrayList ();
693 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
695 if (a.Type == TypeManager.default_member_type) {
696 if (Indexers != null) {
697 Report.Error (646, a.Location,
698 "Cannot specify the DefaultMember attribute on" +
699 " a type containing an indexer");
704 base.ApplyAttributeBuilder (a, cb);
707 public override AttributeTargets AttributeTargets {
711 return AttributeTargets.Class;
713 return AttributeTargets.Struct;
715 return AttributeTargets.Interface;
717 throw new NotSupportedException ();
722 public ArrayList Types {
728 public MethodArrayList Methods {
734 public ArrayList Constants {
740 public ArrayList Interfaces {
746 public ArrayList Iterators {
754 return base_class_name;
758 public ArrayList Bases {
768 public ArrayList Fields {
774 public ArrayList InstanceConstructors {
776 return instance_constructors;
780 public ArrayList Properties {
786 public ArrayList Events {
792 public ArrayList Enums {
798 public ArrayList Indexers {
804 public ArrayList Operators {
810 public ArrayList Delegates {
816 public ArrayList Parts {
822 public virtual TypeAttributes TypeAttr {
824 return Modifiers.TypeAttr (ModFlags, this);
828 public string IndexerName {
830 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
835 // Emits the instance field initializers
837 public bool EmitFieldInitializers (EmitContext ec)
840 Expression instance_expr;
843 fields = initialized_static_fields;
844 instance_expr = null;
846 fields = initialized_fields;
847 instance_expr = new This (Location.Null).Resolve (ec);
853 foreach (Field f in fields){
854 Expression e = f.GetInitializerExpression (ec);
858 Location l = f.Location;
859 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
860 fe.InstanceExpression = instance_expr;
861 fe.IsFieldInitializer = true;
863 ExpressionStatement a = new Assign (fe, e, l);
865 a = a.ResolveStatement (ec);
869 a.EmitStatement (ec);
876 // Defines the default constructors
878 protected void DefineDefaultConstructor (bool is_static)
882 // The default constructor is public
883 // If the class is abstract, the default constructor is protected
884 // The default static constructor is private
886 int mods = Modifiers.PUBLIC;
888 mods = Modifiers.STATIC | Modifiers.PRIVATE;
889 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
890 mods = Modifiers.PROTECTED;
892 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
893 new ConstructorBaseInitializer (
894 null, Parameters.EmptyReadOnlyParameters,
900 c.Block = new ToplevelBlock (null, Location);
905 /// The pending methods that need to be implemented
906 // (interfaces or abstract methods)
908 public PendingImplementation Pending;
910 public abstract void Register ();
912 public abstract PendingImplementation GetPendingImplementations ();
914 TypeExpr[] GetPartialBases (out TypeExpr base_class, out bool error)
916 ArrayList ifaces = new ArrayList ();
919 Location base_loc = Location.Null;
921 foreach (ClassPart part in parts) {
922 TypeExpr new_base_class;
923 TypeExpr[] new_ifaces;
925 new_ifaces = part.GetClassBases (out new_base_class, out error);
929 if ((base_class != null) && (new_base_class != null) &&
930 !base_class.Equals (new_base_class)) {
931 Report.Error (263, part.Location,
932 "Partial declarations of `{0}' must " +
933 "not specify different base classes",
936 if (!Location.IsNull (base_loc))
937 Report.LocationOfPreviousError (base_loc);
943 if ((base_class == null) && (new_base_class != null)) {
944 base_class = new_base_class;
945 base_loc = part.Location;
948 if (new_ifaces == null)
951 foreach (TypeExpr iface in new_ifaces) {
953 foreach (TypeExpr old_iface in ifaces) {
954 if (old_iface.Equals (iface)) {
967 TypeExpr[] retval = new TypeExpr [ifaces.Count];
968 ifaces.CopyTo (retval, 0);
972 TypeExpr[] GetNormalBases (out TypeExpr base_class, out bool error)
976 int count = Bases.Count;
979 if (Kind == Kind.Class){
980 TypeExpr name = ResolveBaseTypeExpr (
981 (Expression) Bases [0], false, Location);
988 if (!name.IsInterface) {
989 // base_class could be a class, struct, enum, delegate.
990 // This is validated in GetClassBases.
996 TypeExpr [] ifaces = new TypeExpr [count-start];
998 for (i = start, j = 0; i < count; i++, j++){
999 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1000 if (resolved == null) {
1005 ifaces [j] = resolved;
1013 /// This function computes the Base class and also the
1014 /// list of interfaces that the class or struct @c implements.
1016 /// The return value is an array (might be null) of
1017 /// interfaces implemented (as Types).
1019 /// The @base_class argument is set to the base object or null
1020 /// if this is `System.Object'.
1022 TypeExpr [] GetClassBases (out TypeExpr base_class, out bool error)
1031 ifaces = GetPartialBases (out base_class, out error);
1032 else if (Bases == null){
1036 ifaces = GetNormalBases (out base_class, out error);
1041 if ((base_class != null) && (Kind == Kind.Class)){
1042 if (base_class is TypeParameterExpr){
1044 689, base_class.Location,
1045 "Type parameter `{0}' can not be used as a " +
1046 "base class or interface", base_class.Name);
1051 if (IsGeneric && base_class.IsAttribute){
1053 698, base_class.Location,
1054 "A generic type cannot derive from `{0}' " +
1055 "because it is an attribute class",
1061 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1062 Report.Error (1521, base_class.Location, "Invalid base type");
1067 if (base_class.IsSealed){
1069 Report.SymbolRelatedToPreviousError (base_class.Type);
1070 if (base_class.Type.IsAbstract) {
1071 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1073 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1078 if (!base_class.CanInheritFrom ()){
1079 Report.Error (644, Location,
1080 "`{0}' cannot inherit from special class `{1}'",
1081 Name, base_class.Name);
1086 if (!base_class.AsAccessible (this, ModFlags)) {
1087 Report.SymbolRelatedToPreviousError (base_class.Type);
1088 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1089 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1093 if (base_class != null)
1094 base_class_name = base_class.Name;
1099 int count = ifaces != null ? ifaces.Length : 0;
1101 for (i = 0; i < count; i++) {
1102 TypeExpr iface = (TypeExpr) ifaces [i];
1104 if (!iface.IsInterface) {
1106 if (Kind != Kind.Class) {
1107 string what = Kind == Kind.Struct ? "Struct" : "Interface";
1109 Report.Error (527, Location,
1110 "In {0} `{1}', type `{2}' is not "+
1111 "an interface", what, Name, iface.Name);
1113 else if (base_class != null)
1114 Report.Error (1721, Location,
1115 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1118 Report.Error (1722, Location,
1119 "In Class `{0}', `{1}' is not " +
1120 "an interface, a base class must be listed first", Name, iface.Name);
1125 for (int x = 0; x < i; x++) {
1126 if (iface.Equals (ifaces [x])) {
1127 Report.Error (528, Location,
1128 "`{0}' is already listed in " +
1129 "interface list", iface.Name);
1134 if ((Kind == Kind.Interface) &&
1135 !iface.AsAccessible (Parent, ModFlags)) {
1136 Report.Error (61, Location,
1137 "Inconsistent accessibility: base " +
1138 "interface `{0}' is less accessible " +
1139 "than interface `{1}'", iface.Name,
1151 bool CheckGenericInterfaces (Type[] ifaces)
1153 ArrayList already_checked = new ArrayList ();
1155 for (int i = 0; i < ifaces.Length; i++) {
1156 Type iface = ifaces [i];
1157 foreach (Type t in already_checked) {
1161 Type[] infered = new Type [CountTypeParameters];
1162 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1167 "`{0}' cannot implement both `{1}' and `{2}' " +
1168 "because they may unify for some type " +
1169 "parameter substitutions",
1170 TypeManager.GetFullName (TypeBuilder),
1175 already_checked.Add (iface);
1184 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1186 public override TypeBuilder DefineType ()
1191 if (TypeBuilder != null)
1194 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1196 TypeAttributes type_attributes = TypeAttr;
1200 if (TypeManager.NamespaceClash (Name, Location)) {
1205 ModuleBuilder builder = CodeGen.Module.Builder;
1206 TypeBuilder = builder.DefineType (
1207 Name, type_attributes, null, null);
1209 TypeBuilder builder;
1210 if (Parent.TypeBuilder != null)
1211 builder = Parent.TypeBuilder;
1213 builder = Parent.DefineType ();
1215 if (builder == null) {
1220 TypeBuilder = builder.DefineNestedType (
1221 MemberName.Basename, type_attributes,
1225 catch (ArgumentException) {
1226 Report.RuntimeMissingSupport (Location, "static classes");
1230 TypeManager.AddUserType (Name, TypeBuilder, this);
1232 TypeExpr current_type = null;
1235 string[] param_names = new string [TypeParameters.Length];
1236 for (int i = 0; i < TypeParameters.Length; i++)
1237 param_names [i] = TypeParameters [i].Name;
1239 GenericTypeParameterBuilder[] gen_params;
1240 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1242 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1243 for (int i = offset; i < gen_params.Length; i++)
1244 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1246 foreach (TypeParameter type_param in CurrentTypeParameters) {
1247 if (!type_param.Resolve (this)) {
1253 for (int i = offset; i < gen_params.Length; i++)
1254 CurrentTypeParameters [i - offset].DefineConstraints ();
1256 current_type = new ConstructedType (Name, TypeParameters, Location);
1260 foreach (TypeParameter type_param in TypeParameters)
1261 if (!type_param.DefineType (ec)) {
1267 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1268 throw new Exception ();
1270 TypeExpr[] iface_exprs = GetClassBases (out base_type, out error);
1274 if (base_type == null) {
1275 if (Kind == Kind.Class){
1276 if (RootContext.StdLib)
1277 base_type = TypeManager.system_object_expr;
1278 else if (Name != "System.Object")
1279 base_type = TypeManager.system_object_expr;
1280 } else if (Kind == Kind.Struct){
1282 // If we are compiling our runtime,
1283 // and we are defining ValueType, then our
1284 // base is `System.Object'.
1286 if (!RootContext.StdLib && Name == "System.ValueType")
1287 base_type = TypeManager.system_object_expr;
1288 else if (Kind == Kind.Struct)
1289 base_type = TypeManager.system_valuetype_expr;
1293 if (base_type != null) {
1294 base_type = base_type.ResolveAsTypeTerminal (ec);
1295 if (base_type == null) {
1300 ptype = base_type.Type;
1303 if (!CheckRecursiveDefinition ()) {
1309 TypeBuilder.SetParent (ptype);
1312 // Structs with no fields need to have at least one byte.
1313 // The right thing would be to set the PackingSize in a DefineType
1314 // but there are no functions that allow interfaces *and* the size to
1318 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1319 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1320 FieldAttributes.Private);
1323 // add interfaces that were not added at type creation
1324 if (iface_exprs != null) {
1325 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1326 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1327 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1328 if (ifaces == null) {
1333 foreach (Type itype in ifaces)
1334 TypeBuilder.AddInterfaceImplementation (itype);
1336 if (!CheckGenericInterfaces (ifaces)) {
1341 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1345 foreach (TypeParameter type_param in TypeParameters)
1346 if (!type_param.CheckDependencies (ec)) {
1352 if (current_type != null) {
1353 current_type = current_type.ResolveAsTypeTerminal (ec);
1354 if (current_type == null) {
1359 CurrentType = current_type.Type;
1363 // Finish the setup for the EmitContext
1365 ec.ContainerType = TypeBuilder;
1367 if ((base_type != null) && base_type.IsAttribute) {
1368 RootContext.RegisterAttribute (this);
1369 } else if (!(this is Iterator))
1370 RootContext.RegisterOrder (this);
1372 if (!DefineNestedTypes ()) {
1380 protected virtual bool DefineNestedTypes ()
1382 if (Interfaces != null) {
1383 foreach (TypeContainer iface in Interfaces)
1384 if (iface.DefineType () == null)
1388 if (Types != null) {
1389 foreach (TypeContainer tc in Types)
1390 if (tc.DefineType () == null)
1394 if (Delegates != null) {
1395 foreach (Delegate d in Delegates)
1396 if (d.DefineType () == null)
1400 if (Enums != null) {
1401 foreach (Enum en in Enums)
1402 if (en.DefineType () == null)
1406 if (Parts != null) {
1407 foreach (ClassPart part in Parts) {
1408 part.TypeBuilder = TypeBuilder;
1409 part.base_type = base_type;
1410 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1417 protected bool CheckRecursiveDefinition ()
1420 Report.Error (146, Location,
1421 "Class definition is circular: `{0}'",
1422 GetSignatureForError ());
1429 Type parent = ptype;
1430 if (parent != null) {
1431 if (parent.IsGenericInstance)
1432 parent = parent.GetGenericTypeDefinition ();
1434 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1435 if ((ptc != null) && !ptc.CheckRecursiveDefinition ())
1443 static void Error_KeywordNotAllowed (Location loc)
1445 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1449 /// Populates our TypeBuilder with fields and methods
1451 public override bool DefineMembers (TypeContainer container)
1453 if (members_defined)
1454 return members_defined_ok;
1456 members_defined_ok = DoDefineMembers ();
1457 members_defined = true;
1459 return members_defined_ok;
1462 protected virtual bool DoDefineMembers ()
1465 // We need to be able to use the member cache while we are checking/defining
1467 if (TypeBuilder.BaseType != null)
1468 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
1470 if (TypeBuilder.IsInterface)
1471 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
1474 if ((ModFlags & Modifiers.NEW) != 0)
1475 Error_KeywordNotAllowed (Location);
1477 // HACK: missing implemenation
1478 // This is not fully functional. Better way how to handle this is to have recursive definition of containers
1479 // instead of flat as we have now.
1480 // Now we are not able to check inner attribute class because its parent had not been defined.
1482 // TODO: remove this if
1483 if (Parent.MemberCache != null) {
1484 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1485 if (conflict_symbol == null) {
1486 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1487 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1489 if ((ModFlags & Modifiers.NEW) == 0) {
1490 Report.SymbolRelatedToPreviousError (conflict_symbol);
1491 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1497 DefineContainerMembers (constants);
1498 DefineContainerMembers (fields);
1500 if ((Kind == Kind.Class) && !(this is ClassPart) && !(this is StaticClass)){
1501 if ((instance_constructors == null) &&
1502 !(this is StaticClass)) {
1503 if (default_constructor == null)
1504 DefineDefaultConstructor (false);
1507 if (initialized_static_fields != null &&
1508 default_static_constructor == null)
1509 DefineDefaultConstructor (true);
1512 if (Kind == Kind.Struct){
1514 // Structs can not have initialized instance
1517 if (initialized_static_fields != null &&
1518 default_static_constructor == null)
1519 DefineDefaultConstructor (true);
1521 if (initialized_fields != null)
1522 ReportStructInitializedInstanceError ();
1525 Pending = GetPendingImplementations ();
1527 if (parts != null) {
1528 foreach (ClassPart part in parts) {
1529 if (!part.DefineMembers (this))
1535 // Constructors are not in the defined_names array
1537 DefineContainerMembers (instance_constructors);
1539 if (default_static_constructor != null)
1540 default_static_constructor.Define ();
1542 DefineContainerMembers (properties);
1543 DefineContainerMembers (events);
1544 DefineContainerMembers (indexers);
1545 DefineContainerMembers (methods);
1546 DefineContainerMembers (operators);
1547 DefineContainerMembers (enums);
1548 DefineContainerMembers (delegates);
1550 if (CurrentType != null) {
1551 GenericType = CurrentType;
1553 ec.ContainerType = GenericType;
1558 if (!(this is ClassPart))
1559 member_cache = new MemberCache (this);
1562 if (parts != null) {
1563 foreach (ClassPart part in parts)
1564 part.member_cache = member_cache;
1567 if (iterators != null) {
1568 foreach (Iterator iterator in iterators) {
1569 if (iterator.DefineType () == null)
1573 foreach (Iterator iterator in iterators) {
1574 if (!iterator.DefineMembers (this))
1582 void ReportStructInitializedInstanceError ()
1584 string n = TypeBuilder.FullName;
1586 foreach (Field f in initialized_fields){
1589 "`" + n + "." + f.Name + "': can not have " +
1590 "instance field initializers in structs");
1594 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1597 mcal.DefineContainerMembers ();
1600 public override bool Define ()
1602 if (parts != null) {
1603 foreach (ClassPart part in parts) {
1604 if (!part.Define ())
1612 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1614 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1618 /// This function is based by a delegate to the FindMembers routine
1620 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1626 /// This filter is used by FindMembers, and we just keep
1627 /// a global for the filter to `AlwaysAccept'
1629 static MemberFilter accepting_filter;
1632 static TypeContainer ()
1634 accepting_filter = new MemberFilter (AlwaysAccept);
1637 public MethodInfo[] GetMethods ()
1639 ArrayList members = new ArrayList ();
1641 DefineMembers (null);
1643 if (methods != null) {
1644 int len = methods.Count;
1645 for (int i = 0; i < len; i++) {
1646 Method m = (Method) methods [i];
1648 members.Add (m.MethodBuilder);
1652 if (operators != null) {
1653 int len = operators.Count;
1654 for (int i = 0; i < len; i++) {
1655 Operator o = (Operator) operators [i];
1657 members.Add (o.OperatorMethodBuilder);
1661 if (properties != null) {
1662 int len = properties.Count;
1663 for (int i = 0; i < len; i++) {
1664 Property p = (Property) properties [i];
1666 if (p.GetBuilder != null)
1667 members.Add (p.GetBuilder);
1668 if (p.SetBuilder != null)
1669 members.Add (p.SetBuilder);
1673 if (indexers != null) {
1674 int len = indexers.Count;
1675 for (int i = 0; i < len; i++) {
1676 Indexer ix = (Indexer) indexers [i];
1678 if (ix.GetBuilder != null)
1679 members.Add (ix.GetBuilder);
1680 if (ix.SetBuilder != null)
1681 members.Add (ix.SetBuilder);
1685 if (events != null) {
1686 int len = events.Count;
1687 for (int i = 0; i < len; i++) {
1688 Event e = (Event) events [i];
1690 if (e.AddBuilder != null)
1691 members.Add (e.AddBuilder);
1692 if (e.RemoveBuilder != null)
1693 members.Add (e.RemoveBuilder);
1697 MethodInfo[] retMethods = new MethodInfo [members.Count];
1698 members.CopyTo (retMethods, 0);
1702 // Indicated whether container has StructLayout attribute set Explicit
1703 public virtual bool HasExplicitLayout {
1710 /// This method returns the members of this type just like Type.FindMembers would
1711 /// Only, we need to use this for types which are _being_ defined because MS'
1712 /// implementation can't take care of that.
1715 // FIXME: return an empty static array instead of null, that cleans up
1716 // some code and is consistent with some coding conventions I just found
1720 // Notice that in various cases we check if our field is non-null,
1721 // something that would normally mean that there was a bug elsewhere.
1723 // The problem happens while we are defining p-invoke methods, as those
1724 // will trigger a FindMembers, but this happens before things are defined
1726 // Since the whole process is a no-op, it is fine to check for null here.
1728 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1729 MemberFilter filter, object criteria)
1731 ArrayList members = null;
1734 if ((bf & BindingFlags.Public) != 0)
1735 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1737 if ((bf & BindingFlags.NonPublic) != 0)
1738 modflags |= Modifiers.PRIVATE;
1740 int static_mask = 0, static_flags = 0;
1741 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1742 case BindingFlags.Static:
1743 static_mask = static_flags = Modifiers.STATIC;
1746 case BindingFlags.Instance:
1747 static_mask = Modifiers.STATIC;
1752 static_mask = static_flags = 0;
1756 Timer.StartTimer (TimerType.TcFindMembers);
1759 filter = accepting_filter;
1761 if ((mt & MemberTypes.Field) != 0) {
1762 if (fields != null) {
1763 int len = fields.Count;
1764 for (int i = 0; i < len; i++) {
1765 Field f = (Field) fields [i];
1767 if ((f.ModFlags & modflags) == 0)
1769 if ((f.ModFlags & static_mask) != static_flags)
1772 FieldBuilder fb = f.FieldBuilder;
1773 if (fb != null && filter (fb, criteria) == true) {
1774 if (members == null)
1775 members = new ArrayList ();
1782 if (constants != null) {
1783 int len = constants.Count;
1784 for (int i = 0; i < len; i++) {
1785 Const con = (Const) constants [i];
1787 if ((con.ModFlags & modflags) == 0)
1789 if ((con.ModFlags & static_mask) != static_flags)
1792 FieldBuilder fb = con.FieldBuilder;
1793 if (fb != null && filter (fb, criteria) == true) {
1794 if (members == null)
1795 members = new ArrayList ();
1803 if ((mt & MemberTypes.Method) != 0) {
1804 if (methods != null) {
1805 int len = methods.Count;
1806 for (int i = 0; i < len; i++) {
1807 Method m = (Method) methods [i];
1809 if ((m.ModFlags & modflags) == 0)
1811 if ((m.ModFlags & static_mask) != static_flags)
1814 MethodBuilder mb = m.MethodBuilder;
1816 if (mb != null && filter (mb, criteria) == true) {
1817 if (members == null)
1818 members = new ArrayList ();
1825 if (operators != null) {
1826 int len = operators.Count;
1827 for (int i = 0; i < len; i++) {
1828 Operator o = (Operator) operators [i];
1830 if ((o.ModFlags & modflags) == 0)
1832 if ((o.ModFlags & static_mask) != static_flags)
1835 MethodBuilder ob = o.OperatorMethodBuilder;
1836 if (ob != null && filter (ob, criteria) == true) {
1837 if (members == null)
1838 members = new ArrayList ();
1845 if (properties != null) {
1846 int len = properties.Count;
1847 for (int i = 0; i < len; i++) {
1848 Property p = (Property) properties [i];
1850 if ((p.ModFlags & modflags) == 0)
1852 if ((p.ModFlags & static_mask) != static_flags)
1858 if (b != null && filter (b, criteria) == true) {
1859 if (members == null)
1860 members = new ArrayList ();
1866 if (b != null && filter (b, criteria) == true) {
1867 if (members == null)
1868 members = new ArrayList ();
1875 if (indexers != null) {
1876 int len = indexers.Count;
1877 for (int i = 0; i < len; i++) {
1878 Indexer ix = (Indexer) indexers [i];
1880 if ((ix.ModFlags & modflags) == 0)
1882 if ((ix.ModFlags & static_mask) != static_flags)
1888 if (b != null && filter (b, criteria) == true) {
1889 if (members == null)
1890 members = new ArrayList ();
1896 if (b != null && filter (b, criteria) == true) {
1897 if (members == null)
1898 members = new ArrayList ();
1906 if ((mt & MemberTypes.Event) != 0) {
1907 if (events != null) {
1908 int len = events.Count;
1909 for (int i = 0; i < len; i++) {
1910 Event e = (Event) events [i];
1912 if ((e.ModFlags & modflags) == 0)
1914 if ((e.ModFlags & static_mask) != static_flags)
1917 MemberInfo eb = e.EventBuilder;
1918 if (eb != null && filter (eb, criteria) == true) {
1919 if (members == null)
1920 members = new ArrayList ();
1922 members.Add (e.EventBuilder);
1928 if ((mt & MemberTypes.Property) != 0){
1929 if (properties != null) {
1930 int len = properties.Count;
1931 for (int i = 0; i < len; i++) {
1932 Property p = (Property) properties [i];
1934 if ((p.ModFlags & modflags) == 0)
1936 if ((p.ModFlags & static_mask) != static_flags)
1939 MemberInfo pb = p.PropertyBuilder;
1940 if (pb != null && filter (pb, criteria) == true) {
1941 if (members == null)
1942 members = new ArrayList ();
1944 members.Add (p.PropertyBuilder);
1949 if (indexers != null) {
1950 int len = indexers.Count;
1951 for (int i = 0; i < len; i++) {
1952 Indexer ix = (Indexer) indexers [i];
1954 if ((ix.ModFlags & modflags) == 0)
1956 if ((ix.ModFlags & static_mask) != static_flags)
1959 MemberInfo ib = ix.PropertyBuilder;
1960 if (ib != null && filter (ib, criteria) == true) {
1961 if (members == null)
1962 members = new ArrayList ();
1964 members.Add (ix.PropertyBuilder);
1970 if ((mt & MemberTypes.NestedType) != 0) {
1971 if (types != null) {
1972 int len = types.Count;
1973 for (int i = 0; i < len; i++) {
1974 TypeContainer t = (TypeContainer) types [i];
1976 if ((t.ModFlags & modflags) == 0)
1979 TypeBuilder tb = t.TypeBuilder;
1980 if (tb != null && (filter (tb, criteria) == true)) {
1981 if (members == null)
1982 members = new ArrayList ();
1989 if (enums != null) {
1990 int len = enums.Count;
1991 for (int i = 0; i < len; i++) {
1992 Enum en = (Enum) enums [i];
1994 if ((en.ModFlags & modflags) == 0)
1997 TypeBuilder tb = en.TypeBuilder;
1998 if (tb != null && (filter (tb, criteria) == true)) {
1999 if (members == null)
2000 members = new ArrayList ();
2007 if (delegates != null) {
2008 int len = delegates.Count;
2009 for (int i = 0; i < len; i++) {
2010 Delegate d = (Delegate) delegates [i];
2012 if ((d.ModFlags & modflags) == 0)
2015 TypeBuilder tb = d.TypeBuilder;
2016 if (tb != null && (filter (tb, criteria) == true)) {
2017 if (members == null)
2018 members = new ArrayList ();
2025 if (interfaces != null) {
2026 int len = interfaces.Count;
2027 for (int i = 0; i < len; i++) {
2028 TypeContainer iface = (TypeContainer) interfaces [i];
2030 if ((iface.ModFlags & modflags) == 0)
2033 TypeBuilder tb = iface.TypeBuilder;
2034 if (tb != null && (filter (tb, criteria) == true)) {
2035 if (members == null)
2036 members = new ArrayList ();
2044 if ((mt & MemberTypes.Constructor) != 0){
2045 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2046 int len = instance_constructors.Count;
2047 for (int i = 0; i < len; i++) {
2048 Constructor c = (Constructor) instance_constructors [i];
2050 ConstructorBuilder cb = c.ConstructorBuilder;
2051 if (cb != null && filter (cb, criteria) == true) {
2052 if (members == null)
2053 members = new ArrayList ();
2060 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2061 ConstructorBuilder cb =
2062 default_static_constructor.ConstructorBuilder;
2064 if (cb != null && filter (cb, criteria) == true) {
2065 if (members == null)
2066 members = new ArrayList ();
2074 // Lookup members in base if requested.
2076 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2077 if (TypeBuilder.BaseType != null) {
2078 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2079 if (list.Count > 0) {
2080 if (members == null)
2081 members = new ArrayList ();
2083 members.AddRange (list);
2089 Timer.StopTimer (TimerType.TcFindMembers);
2091 if (members == null)
2092 return MemberList.Empty;
2094 return new MemberList (members);
2097 public override MemberCache MemberCache {
2099 return member_cache;
2103 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2104 MemberFilter filter, object criteria)
2106 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2109 return ds.FindMembers (mt, bf, filter, criteria);
2111 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2115 // FindMethods will look for methods not only in the type `t', but in
2116 // any interfaces implemented by the type.
2118 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2119 MemberFilter filter, object criteria)
2125 /// Emits the values for the constants
2127 public void EmitConstants ()
2129 if (constants != null)
2130 foreach (Const con in constants)
2135 protected virtual void VerifyMembers (EmitContext ec)
2138 // Check for internal or private fields that were never assigned
2140 if (RootContext.WarningLevel >= 4) {
2141 if (fields != null){
2142 foreach (Field f in fields) {
2143 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2146 if ((f.status & Field.Status.USED) == 0){
2147 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2152 // Only report 649 on level 4
2154 if (RootContext.WarningLevel < 4)
2157 if ((f.status & Field.Status.ASSIGNED) != 0)
2160 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2167 /// Emits the code, this step is performed after all
2168 /// the types, enumerations, constructors
2170 public void EmitType ()
2172 if (OptAttributes != null)
2173 OptAttributes.Emit (ec, this);
2177 if (instance_constructors != null) {
2178 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2179 bool has_compliant_args = false;
2181 foreach (Constructor c in instance_constructors) {
2184 if (has_compliant_args)
2187 has_compliant_args = c.HasCompliantArgs;
2189 if (!has_compliant_args)
2190 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2192 foreach (Constructor c in instance_constructors)
2199 if (default_static_constructor != null)
2200 default_static_constructor.Emit ();
2202 if (methods != null)
2203 foreach (Method m in methods)
2206 if (operators != null)
2207 foreach (Operator o in operators)
2210 if (properties != null)
2211 foreach (Property p in properties)
2214 if (indexers != null){
2219 foreach (Field f in fields)
2222 if (events != null){
2223 foreach (Event e in Events)
2227 if (delegates != null) {
2228 foreach (Delegate d in Delegates) {
2233 if (enums != null) {
2234 foreach (Enum e in enums) {
2239 if (parts != null) {
2240 foreach (ClassPart part in parts)
2244 if ((Pending != null) && !(this is ClassPart))
2245 if (Pending.VerifyPendingMethods ())
2250 if (iterators != null)
2251 foreach (Iterator iterator in iterators)
2252 iterator.EmitType ();
2254 // if (types != null)
2255 // foreach (TypeContainer tc in types)
2259 public override void CloseType ()
2261 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2265 caching_flags |= Flags.CloseTypeCreated;
2266 TypeBuilder.CreateType ();
2267 } catch (TypeLoadException){
2269 // This is fine, the code still created the type
2271 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2272 // Console.WriteLine (e.Message);
2274 Console.WriteLine ("In type: " + Name);
2279 foreach (Enum en in Enums)
2283 foreach (TypeContainer tc in Types)
2284 if (tc.Kind == Kind.Struct)
2287 foreach (TypeContainer tc in Types)
2288 if (tc.Kind != Kind.Struct)
2292 if (Delegates != null)
2293 foreach (Delegate d in Delegates)
2296 if (Iterators != null)
2297 foreach (Iterator i in Iterators)
2305 initialized_fields = null;
2306 initialized_static_fields = null;
2315 default_constructor = null;
2316 default_static_constructor = null;
2318 OptAttributes = null;
2321 member_cache = null;
2324 // TODO: make it obsolete and use GetSignatureForError
2325 public string MakeName (string n)
2327 return "`" + Name + "." + n + "'";
2331 // Performs the validation on a Method's modifiers (properties have
2332 // the same properties).
2334 public bool MethodModifiersValid (MemberCore mc)
2336 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2337 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2338 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2340 int flags = mc.ModFlags;
2343 // At most one of static, virtual or override
2345 if ((flags & Modifiers.STATIC) != 0){
2346 if ((flags & vao) != 0){
2347 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2348 GetSignatureForError ());
2353 if (Kind == Kind.Struct){
2354 if ((flags & va) != 0){
2355 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2360 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2361 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2366 // If the declaration includes the abstract modifier, then the
2367 // declaration does not include static, virtual or extern
2369 if ((flags & Modifiers.ABSTRACT) != 0){
2370 if ((flags & Modifiers.EXTERN) != 0){
2372 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2376 if ((flags & Modifiers.SEALED) != 0) {
2377 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2381 if ((flags & Modifiers.VIRTUAL) != 0){
2382 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2386 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2387 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2392 if ((flags & Modifiers.PRIVATE) != 0){
2393 if ((flags & vao) != 0){
2394 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2399 if ((flags & Modifiers.SEALED) != 0){
2400 if ((flags & Modifiers.OVERRIDE) == 0){
2401 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2409 public bool UserDefinedStaticConstructor {
2411 return default_static_constructor != null;
2415 public Constructor DefaultStaticConstructor {
2416 get { return default_static_constructor; }
2419 protected override bool VerifyClsCompliance (DeclSpace ds)
2421 if (!base.VerifyClsCompliance (ds))
2427 Report.Error (3024, Location, "'{0}': type parameters are not CLS-compliant",
2428 GetSignatureForError ());
2432 Type base_type = TypeBuilder.BaseType;
2433 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2434 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2437 if (!Parent.IsClsCompliaceRequired (ds)) {
2438 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2439 GetSignatureForError (), Parent.GetSignatureForError ());
2446 /// Checks whether container name is CLS Compliant
2448 void VerifyClsName ()
2450 Hashtable base_members = base_cache == null ?
2452 base_cache.GetPublicMembers ();
2453 Hashtable this_members = new Hashtable ();
2455 foreach (DictionaryEntry entry in defined_names) {
2456 MemberCore mc = (MemberCore)entry.Value;
2457 if (!mc.IsClsCompliaceRequired (this))
2460 string name = (string)entry.Key;
2461 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2463 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2464 object found = base_members [lcase];
2465 if (found == null) {
2466 found = this_members [lcase];
2467 if (found == null) {
2468 this_members.Add (lcase, mc);
2473 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2476 if (found is MemberInfo) {
2477 if (basename == ((MemberInfo)found).Name)
2479 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2481 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2483 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2489 /// Performs checks for an explicit interface implementation. First it
2490 /// checks whether the `interface_type' is a base inteface implementation.
2491 /// Then it checks whether `name' exists in the interface type.
2493 public virtual bool VerifyImplements (Type interface_type, string full,
2494 string name, Location loc)
2498 if (ifaces != null){
2499 foreach (Type t in ifaces){
2500 if (t == interface_type){
2508 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2509 full, interface_type.FullName);
2516 protected override void VerifyObsoleteAttribute()
2518 CheckUsageOfObsoleteAttribute (TypeBuilder.BaseType);
2523 foreach (Type iface in ifaces) {
2524 CheckUsageOfObsoleteAttribute (iface);
2532 string IMemberContainer.Name {
2538 Type IMemberContainer.Type {
2544 MemberCache IMemberContainer.MemberCache {
2546 return member_cache;
2550 bool IMemberContainer.IsInterface {
2552 return Kind == Kind.Interface;
2556 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2558 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2560 if (GenericType != null)
2561 return TypeManager.FindMembers (GenericType, mt, new_bf,
2564 return FindMembers (mt, new_bf, null, null);
2568 // Generates xml doc comments (if any), and if required,
2569 // handle warning report.
2571 internal override void GenerateDocComment (DeclSpace ds)
2573 DocUtil.GenerateTypeDocComment (this, ds);
2576 public override string DocCommentHeader {
2577 get { return "T:"; }
2580 public virtual MemberCache BaseCache {
2588 public class PartialContainer : TypeContainer {
2590 public readonly Namespace Namespace;
2591 public readonly int OriginalModFlags;
2592 public readonly int AllowedModifiers;
2593 public readonly TypeAttributes DefaultTypeAttributes;
2595 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2596 MemberName member_name, int mod_flags, Kind kind,
2599 PartialContainer pc;
2600 string full_name = member_name.GetName (true);
2601 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2603 pc = ds as PartialContainer;
2607 260, ds.Location, "Missing partial modifier " +
2608 "on declaration of type `{0}'; another " +
2609 "partial implementation of this type exists",
2610 member_name.GetTypeName());
2612 Report.LocationOfPreviousError (loc);
2616 if (pc.Kind != kind) {
2618 261, loc, "Partial declarations of `{0}' " +
2619 "must be all classes, all structs or " +
2620 "all interfaces", member_name.GetTypeName ());
2624 if (pc.OriginalModFlags != mod_flags) {
2626 262, loc, "Partial declarations of `{0}' " +
2627 "have conflicting accessibility modifiers",
2628 member_name.GetTypeName ());
2635 pc = new PartialContainer (ns, parent, member_name, mod_flags, kind, loc);
2636 RootContext.Tree.RecordDecl (full_name, pc);
2637 parent.AddType (pc);
2642 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2643 MemberName name, int mod, Attributes attrs,
2644 Kind kind, Location loc)
2646 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2648 // An error occured; create a dummy container, but don't
2650 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2653 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2658 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2659 MemberName name, int mod, Kind kind, Location l)
2660 : base (ns, parent, name, null, kind, l)
2662 this.Namespace = ns.NS;
2666 AllowedModifiers = Class.AllowedModifiers;
2667 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2671 AllowedModifiers = Struct.AllowedModifiers;
2672 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2675 case Kind.Interface:
2676 AllowedModifiers = Interface.AllowedModifiers;
2677 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2681 throw new InvalidOperationException ();
2685 if (parent.Parent == null)
2686 accmods = Modifiers.INTERNAL;
2688 accmods = Modifiers.PRIVATE;
2690 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2691 this.OriginalModFlags = mod;
2694 public override void Register ()
2696 if (Kind == Kind.Interface)
2697 Parent.AddInterface (this);
2698 else if (Kind == Kind.Class || Kind == Kind.Struct)
2699 Parent.AddClassOrStruct (this);
2701 throw new InvalidOperationException ();
2704 public override PendingImplementation GetPendingImplementations ()
2706 return PendingImplementation.GetPendingImplementations (this);
2709 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2712 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2717 public override TypeAttributes TypeAttr {
2719 return base.TypeAttr | DefaultTypeAttributes;
2724 public class ClassPart : TypeContainer, IMemberContainer {
2725 public readonly PartialContainer PartialContainer;
2726 public readonly bool IsPartial;
2728 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2729 int mod, Attributes attrs, Kind kind, Location l)
2730 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2732 this.PartialContainer = parent;
2733 this.IsPartial = true;
2736 if (parent.Parent == null)
2737 accmods = Modifiers.INTERNAL;
2739 accmods = Modifiers.PRIVATE;
2741 this.ModFlags = Modifiers.Check (
2742 parent.AllowedModifiers, mod, accmods, l);
2745 public override void Register ()
2749 public override PendingImplementation GetPendingImplementations ()
2751 return PartialContainer.Pending;
2754 public override bool VerifyImplements (Type interface_type, string full,
2755 string name, Location loc)
2757 return PartialContainer.VerifyImplements (
2758 interface_type, full, name, loc);
2761 public override MemberCache BaseCache {
2763 return PartialContainer.BaseCache;
2768 public abstract class ClassOrStruct : TypeContainer {
2769 bool hasExplicitLayout = false;
2770 ListDictionary declarative_security;
2772 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2773 MemberName name, Attributes attrs, Kind kind,
2775 : base (ns, parent, name, attrs, kind, l)
2779 public override PendingImplementation GetPendingImplementations ()
2781 return PendingImplementation.GetPendingImplementations (this);
2784 public override bool HasExplicitLayout {
2786 return hasExplicitLayout;
2790 protected override void VerifyMembers (EmitContext ec)
2792 base.VerifyMembers (ec);
2794 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2795 foreach (Event e in events){
2797 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2802 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2804 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2805 if (declarative_security == null)
2806 declarative_security = new ListDictionary ();
2808 a.ExtractSecurityPermissionSet (declarative_security);
2812 if (a.Type == TypeManager.struct_layout_attribute_type
2813 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2814 hasExplicitLayout = true;
2816 base.ApplyAttributeBuilder (a, cb);
2819 public override void Emit()
2823 if (declarative_security != null) {
2824 foreach (DictionaryEntry de in declarative_security) {
2825 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2830 public override void Register ()
2832 Parent.AddClassOrStruct (this);
2837 /// Class handles static classes declaration
2839 public sealed class StaticClass: Class {
2840 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2841 Attributes attrs, Location l)
2842 : base (ns, parent, name, mod, attrs, l)
2844 if (RootContext.Version == LanguageVersion.ISO_1) {
2845 Report.FeatureIsNotStandardized (l, "static classes");
2846 Environment.Exit (1);
2850 protected override int AllowedModifiersProp {
2852 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2853 Modifiers.STATIC | Modifiers.UNSAFE;
2857 protected override void DefineContainerMembers (MemberCoreArrayList list)
2862 foreach (MemberCore m in list) {
2863 if (m is Operator) {
2864 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2868 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2871 if (m is Constructor) {
2872 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2876 if (m is Destructor) {
2877 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2880 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2883 base.DefineContainerMembers (list);
2886 public override TypeBuilder DefineType()
2888 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2889 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2893 TypeBuilder tb = base.DefineType ();
2897 if ((ptype != null) && (ptype != TypeManager.object_type)) {
2900 "Static class '{0}' cannot derive from type '{1}'. " +
2901 "Static classes must derive from object",
2902 GetSignatureForError (), ptype);
2906 if (ifaces != null) {
2907 foreach (Type t in ifaces)
2908 Report.SymbolRelatedToPreviousError (t);
2911 "'{0}': static classes cannot implement interfaces",
2912 GetSignatureForError ());
2917 public override TypeAttributes TypeAttr {
2919 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2924 public class Class : ClassOrStruct {
2925 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2926 public const int AllowedModifiers =
2929 Modifiers.PROTECTED |
2930 Modifiers.INTERNAL |
2932 Modifiers.ABSTRACT |
2936 // Information in the case we are an attribute type
2937 AttributeUsageAttribute attribute_usage;
2939 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2940 Attributes attrs, Location l)
2941 : base (ns, parent, name, attrs, Kind.Class, l)
2943 this.ModFlags = mod;
2944 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2947 virtual protected int AllowedModifiersProp {
2949 return AllowedModifiers;
2953 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2955 if (a.UsageAttribute != null) {
2956 if (ptype != TypeManager.attribute_type &&
2957 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2958 TypeBuilder.FullName != "System.Attribute") {
2959 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2961 attribute_usage = a.UsageAttribute;
2964 base.ApplyAttributeBuilder (a, cb);
2967 public AttributeUsageAttribute AttributeUsage {
2969 return attribute_usage;
2973 public const TypeAttributes DefaultTypeAttributes =
2974 TypeAttributes.AutoLayout | TypeAttributes.Class;
2976 public override TypeBuilder DefineType()
2978 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2979 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2983 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2984 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2986 return base.DefineType ();
2990 // FIXME: How do we deal with the user specifying a different
2993 public override TypeAttributes TypeAttr {
2995 return base.TypeAttr | DefaultTypeAttributes;
3000 public class Struct : ClassOrStruct {
3002 // Modifiers allowed in a struct declaration
3004 public const int AllowedModifiers =
3007 Modifiers.PROTECTED |
3008 Modifiers.INTERNAL |
3012 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
3013 int mod, Attributes attrs, Location l)
3014 : base (ns, parent, name, attrs, Kind.Struct, l)
3018 if (parent.Parent == null)
3019 accmods = Modifiers.INTERNAL;
3021 accmods = Modifiers.PRIVATE;
3023 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3025 this.ModFlags |= Modifiers.SEALED;
3028 public const TypeAttributes DefaultTypeAttributes =
3029 TypeAttributes.SequentialLayout |
3030 TypeAttributes.Sealed |
3031 TypeAttributes.BeforeFieldInit;
3034 // FIXME: Allow the user to specify a different set of attributes
3035 // in some cases (Sealed for example is mandatory for a class,
3036 // but what SequentialLayout can be changed
3038 public override TypeAttributes TypeAttr {
3040 return base.TypeAttr | DefaultTypeAttributes;
3048 public class Interface : TypeContainer, IMemberContainer {
3050 /// Modifiers allowed in a class declaration
3052 public const int AllowedModifiers =
3055 Modifiers.PROTECTED |
3056 Modifiers.INTERNAL |
3060 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name,
3061 int mod, Attributes attrs, Location l)
3062 : base (ns, parent, name, attrs, Kind.Interface, l)
3066 if (parent.Parent == null)
3067 accmods = Modifiers.INTERNAL;
3069 accmods = Modifiers.PRIVATE;
3071 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3074 public override void Register ()
3076 Parent.AddInterface (this);
3079 public override PendingImplementation GetPendingImplementations ()
3084 public const TypeAttributes DefaultTypeAttributes =
3085 TypeAttributes.AutoLayout |
3086 TypeAttributes.Abstract |
3087 TypeAttributes.Interface;
3089 public override TypeAttributes TypeAttr {
3091 return base.TypeAttr | DefaultTypeAttributes;
3096 public abstract class MethodCore : MemberBase {
3097 public readonly Parameters Parameters;
3098 public readonly GenericMethod GenericMethod;
3099 public readonly DeclSpace ds;
3100 protected ToplevelBlock block;
3103 // Parameters, cached for semantic analysis.
3105 protected InternalParameters parameter_info;
3106 protected Type [] parameter_types;
3108 // Whether this is an operator method.
3109 public bool IsOperator;
3112 // The method we're overriding if this is an override method.
3114 protected MethodInfo base_method = null;
3116 static string[] attribute_targets = new string [] { "method", "return" };
3118 public MethodCore (TypeContainer parent, GenericMethod generic,
3119 Expression type, int mod, int allowed_mod, bool is_iface,
3120 MemberName name, Attributes attrs, Parameters parameters,
3122 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3125 Parameters = parameters;
3126 IsInterface = is_iface;
3127 this.GenericMethod = generic;
3129 if (generic != null)
3136 // Returns the System.Type array for the parameters of this method
3138 public Type [] ParameterTypes {
3140 return parameter_types;
3144 public InternalParameters ParameterInfo
3147 return parameter_info;
3151 public ToplevelBlock Block {
3161 protected override bool CheckBase ()
3163 if (!base.CheckBase ())
3166 // Check whether arguments were correct.
3167 if (!DoDefineParameters ())
3170 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3176 // Is null for System.Object while compiling corlib and base interfaces
3177 if (Parent.BaseCache == null) {
3178 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3179 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3184 Type base_ret_type = null;
3185 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3187 // method is override
3188 if (base_method != null) {
3190 if (!CheckMethodAgainstBase ())
3193 if ((ModFlags & Modifiers.NEW) == 0) {
3194 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3195 Report.SymbolRelatedToPreviousError (base_method);
3196 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3197 "change return type when overriding inherited member");
3201 if (base_method.IsAbstract && !IsInterface) {
3202 Report.SymbolRelatedToPreviousError (base_method);
3203 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3208 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3209 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3213 if (RootContext.WarningLevel > 2) {
3214 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3215 Parent.Methods.HasEquals = true;
3216 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3217 Parent.Methods.HasGetHashCode = true;
3220 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3221 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3223 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3224 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3225 Report.SymbolRelatedToPreviousError (base_method);
3226 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3233 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3234 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3235 if (conflict_symbol != null) {
3236 Report.SymbolRelatedToPreviousError (conflict_symbol);
3237 if (this is PropertyBase)
3238 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3240 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3242 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3246 if (conflict_symbol == null) {
3247 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3248 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3253 if ((ModFlags & Modifiers.NEW) == 0) {
3254 if (this is Method && conflict_symbol is MethodBase)
3257 Report.SymbolRelatedToPreviousError (conflict_symbol);
3258 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3266 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3267 // that have been defined.
3269 // `name' is the user visible name for reporting errors (this is used to
3270 // provide the right name regarding method names and properties)
3272 bool CheckMethodAgainstBase ()
3276 // TODO: replace with GetSignatureForError
3277 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3279 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3280 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3282 506, Location, Parent.MakeName (Name) +
3283 ": cannot override inherited member `" +
3284 name + "' because it is not " +
3285 "virtual, abstract or override");
3289 // Now we check that the overriden method is not final
3291 if (base_method.IsFinal) {
3292 // This happens when implementing interface methods.
3293 if (base_method.IsHideBySig && base_method.IsVirtual) {
3295 506, Location, Parent.MakeName (Name) +
3296 ": cannot override inherited member `" +
3297 name + "' because it is not " +
3298 "virtual, abstract or override");
3300 Report.Error (239, Location, Parent.MakeName (Name) + " : cannot " +
3301 "override inherited member `" + name +
3302 "' because it is sealed.");
3306 // Check that the permissions are not being changed
3308 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3309 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3311 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3312 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3317 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3318 ModFlags |= Modifiers.NEW;
3319 Report.SymbolRelatedToPreviousError (base_method);
3320 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3321 if (RootContext.WarningLevel >= 2)
3322 Report.Warning (114, Location, "'{0}' hides inherited member '{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword", GetSignatureForError (Parent), TypeManager.CSharpSignature (base_method));
3324 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3330 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3332 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3334 // when overriding protected internal, the method can be declared
3335 // protected internal only within the same assembly
3338 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3339 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3341 // assemblies differ - report an error
3345 } else if (thisp != base_classp) {
3347 // same assembly, but other attributes differ - report an error
3352 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3354 // if it's not "protected internal", it must be "protected"
3358 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3360 // protected within the same assembly - an error
3363 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3364 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3366 // protected ok, but other attributes differ - report an error
3372 return (thisp == base_classp);
3376 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3379 // FIXME: report the old/new permissions?
3382 507, Location, parent.MakeName (Name) +
3383 ": can't change the access modifiers when overriding inherited " +
3384 "member `" + name + "'");
3387 protected static string Error722 {
3389 return "'{0}': static types cannot be used as return types";
3394 /// For custom member duplication search in a container
3396 protected abstract bool CheckForDuplications ();
3399 /// Gets base method and its return type
3401 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3403 protected virtual bool DoDefineParameters ()
3405 EmitContext ec = ds.EmitContext;
3407 throw new InternalErrorException ("DoDefineParameters invoked too early");
3409 bool old_unsafe = ec.InUnsafe;
3410 ec.InUnsafe = InUnsafe;
3411 // Check if arguments were correct
3412 parameter_types = Parameters.GetParameterInfo (ec);
3413 ec.InUnsafe = old_unsafe;
3415 if ((parameter_types == null) ||
3416 !CheckParameters (ds, parameter_types))
3419 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3420 parameter_info = new InternalParameters (parameter_types, Parameters, tparam);
3422 Parameter array_param = Parameters.ArrayParameter;
3423 if ((array_param != null) &&
3424 (!array_param.ParameterType.IsArray ||
3425 (array_param.ParameterType.GetArrayRank () != 1))) {
3426 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3433 void error_425 (Type old, Type t, string name)
3435 Report.Error (425, Location,
3436 "The constraints of type parameter `{0}' " +
3437 "of method `{1}' must match the constraints for " +
3438 "type parameter `{2}' of method `{3}'",
3439 TypeManager.CSharpName (old), Name,
3440 TypeManager.CSharpName (t), name);
3443 protected override bool CheckGenericOverride (MethodInfo method, string name)
3445 ParameterData pd = Invocation.GetParameterData (method);
3447 for (int i = 0; i < ParameterTypes.Length; i++) {
3448 GenericConstraints ogc = pd.GenericConstraints (i);
3449 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3451 if ((gc == null) && (ogc == null))
3454 Type ot = pd.ParameterType (i);
3455 Type t = ParameterTypes [i];
3457 if (!((gc != null) && (ogc != null))) {
3458 error_425 (ot, t, name);
3462 if ((gc.Attributes != ogc.Attributes) ||
3463 (gc.HasClassConstraint != ogc.HasClassConstraint)) {
3464 error_425 (ot, t, name);
3468 if (ogc.HasClassConstraint &&
3469 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3470 error_425 (ot, t, name);
3474 Type[] oct = ogc.InterfaceConstraints;
3475 Type[] ct = gc.InterfaceConstraints;
3477 if (oct.Length != ct.Length) {
3478 error_425 (ot, t, name);
3482 for (int j = 0; j < oct.Length; j++)
3483 if (!oct [j].Equals (ct [j])) {
3484 error_425 (ot, t, name);
3492 public override string[] ValidAttributeTargets {
3494 return attribute_targets;
3498 protected override bool VerifyClsCompliance (DeclSpace ds)
3500 if (!base.VerifyClsCompliance (ds)) {
3501 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3502 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3507 if (Parameters.HasArglist) {
3508 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3511 if (!AttributeTester.IsClsCompliant (MemberType)) {
3512 if (this is PropertyBase)
3513 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3514 GetSignatureForError ());
3516 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3517 GetSignatureForError ());
3520 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3525 bool MayUnify (MethodCore first, MethodCore second)
3527 int a_type_params = 0;
3528 if (first.GenericMethod != null)
3529 a_type_params = first.GenericMethod.CountTypeParameters;
3531 int b_type_params = 0;
3532 if (second.GenericMethod != null)
3533 b_type_params = second.GenericMethod.CountTypeParameters;
3535 if (a_type_params != b_type_params)
3538 Type[] class_infered, method_infered;
3539 if (Parent.CountTypeParameters > 0)
3540 class_infered = new Type [Parent.CountTypeParameters];
3542 class_infered = null;
3544 if (a_type_params > 0)
3545 method_infered = new Type [a_type_params];
3547 method_infered = null;
3549 return TypeManager.MayBecomeEqualGenericInstances (
3550 first.ParameterTypes, second.ParameterTypes, class_infered, method_infered);
3553 protected bool IsDuplicateImplementation (MethodCore method)
3555 if ((method == this) ||
3556 (method.MemberName.GetTypeName () != MemberName.GetTypeName ()))
3559 Type[] param_types = method.ParameterTypes;
3560 if (param_types == null)
3563 if (param_types.Length != ParameterTypes.Length)
3567 bool may_unify = MayUnify (this, method);
3569 for (int i = 0; i < param_types.Length; i++) {
3570 if (param_types [i] != ParameterTypes [i])
3574 // TODO: make operator compatible with MethodCore to avoid this
3575 if (this is Operator && method is Operator) {
3576 if (MemberType != method.MemberType)
3577 equal = may_unify = false;
3582 // Try to report 663: method only differs on out/ref
3584 ParameterData info = ParameterInfo;
3585 ParameterData other_info = method.ParameterInfo;
3586 for (int i = 0; i < info.Count; i++){
3587 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3588 Report.Error (663, Location,
3589 "Overload method only differs " +
3590 "in parameter modifier");
3595 Report.SymbolRelatedToPreviousError (method);
3596 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with the same parameter types", Parent.Name, Name);
3598 } else if (may_unify) {
3599 Report.Error (408, Location,
3600 "`{0}' cannot define overload members that " +
3601 "may unify for some type parameter substitutions",
3610 // Returns a string that represents the signature for this
3611 // member which should be used in XML documentation.
3613 public override string GetDocCommentName (DeclSpace ds)
3615 return DocUtil.GetMethodDocCommentName (this, ds);
3619 // Raised (and passed an XmlElement that contains the comment)
3620 // when GenerateDocComment is writing documentation expectedly.
3622 // FIXME: with a few effort, it could be done with XmlReader,
3623 // that means removal of DOM use.
3625 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3627 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3631 // Represents header string for documentation comment.
3633 public override string DocCommentHeader {
3634 get { return "M:"; }
3637 protected override void VerifyObsoleteAttribute()
3639 base.VerifyObsoleteAttribute ();
3641 if (parameter_types == null)
3644 foreach (Type type in parameter_types) {
3645 CheckUsageOfObsoleteAttribute (type);
3650 public class SourceMethod : ISourceMethod
3652 TypeContainer container;
3655 protected SourceMethod (TypeContainer container, MethodBase builder,
3656 ISourceFile file, Location start, Location end)
3658 this.container = container;
3659 this.builder = builder;
3661 CodeGen.SymbolWriter.OpenMethod (
3662 file, this, start.Row, 0, end.Row, 0);
3665 public string Name {
3666 get { return builder.Name; }
3669 public int NamespaceID {
3670 get { return container.NamespaceEntry.SymbolFileID; }
3675 if (builder is MethodBuilder)
3676 return ((MethodBuilder) builder).GetToken ().Token;
3677 else if (builder is ConstructorBuilder)
3678 return ((ConstructorBuilder) builder).GetToken ().Token;
3680 throw new NotSupportedException ();
3684 public void CloseMethod ()
3686 if (CodeGen.SymbolWriter != null)
3687 CodeGen.SymbolWriter.CloseMethod ();
3690 public static SourceMethod Create (TypeContainer parent,
3691 MethodBase builder, Block block)
3693 if (CodeGen.SymbolWriter == null)
3698 Location start_loc = block.StartLocation;
3699 if (Location.IsNull (start_loc))
3702 Location end_loc = block.EndLocation;
3703 if (Location.IsNull (end_loc))
3706 ISourceFile file = start_loc.SourceFile;
3710 return new SourceMethod (
3711 parent, builder, file, start_loc, end_loc);
3715 public class Method : MethodCore, IIteratorContainer, IMethodData {
3716 public MethodBuilder MethodBuilder;
3717 public MethodData MethodData;
3718 ReturnParameter return_attributes;
3719 ListDictionary declarative_security;
3722 /// Modifiers allowed in a class declaration
3724 const int AllowedModifiers =
3727 Modifiers.PROTECTED |
3728 Modifiers.INTERNAL |
3733 Modifiers.OVERRIDE |
3734 Modifiers.ABSTRACT |
3736 Modifiers.METHOD_YIELDS |
3739 const int AllowedInterfaceModifiers =
3740 Modifiers.NEW | Modifiers.UNSAFE;
3743 // return_type can be "null" for VOID values.
3745 public Method (TypeContainer parent, GenericMethod generic,
3746 Expression return_type, int mod, bool is_iface,
3747 MemberName name, Parameters parameters, Attributes attrs,
3749 : base (parent, generic, return_type, mod,
3750 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3751 is_iface, name, attrs, parameters, l)
3755 public override AttributeTargets AttributeTargets {
3757 return AttributeTargets.Method;
3761 public override string GetSignatureForError()
3763 if (MethodBuilder == null) {
3764 return GetSignatureForError (Parent);
3766 return TypeManager.CSharpSignature (MethodBuilder);
3770 /// Use this method when MethodBuilder is null
3772 public override string GetSignatureForError (TypeContainer tc)
3774 // TODO: get params from somewhere
3775 if (parameter_info == null)
3776 return base.GetSignatureForError (tc);
3778 // TODO: move to parameters
3779 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3780 if (parameter_info.Parameters.FixedParameters != null) {
3781 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3782 Parameter p = parameter_info.Parameters.FixedParameters [i];
3783 args.Append (p.GetSignatureForError ());
3785 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3790 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3793 void DuplicateEntryPoint (MethodInfo b, Location location)
3797 "Program `" + CodeGen.FileName +
3798 "' has more than one entry point defined: `" +
3799 TypeManager.CSharpSignature(b) + "'");
3802 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3804 if (b.ReturnType != TypeManager.void_type &&
3805 b.ReturnType != TypeManager.int32_type)
3808 if (pinfo.Count == 0)
3811 if (pinfo.Count > 1)
3814 Type t = pinfo.ParameterType(0);
3816 (t.GetArrayRank() == 1) &&
3817 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3818 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3824 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3826 if (a.Target == AttributeTargets.ReturnValue) {
3827 if (return_attributes == null)
3828 return_attributes = new ReturnParameter (MethodBuilder, Location);
3830 return_attributes.ApplyAttributeBuilder (a, cb);
3834 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
3835 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3838 if (a.Type == TypeManager.dllimport_type) {
3839 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3840 if ((ModFlags & extern_static) != extern_static) {
3841 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3847 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3848 if (declarative_security == null)
3849 declarative_security = new ListDictionary ();
3850 a.ExtractSecurityPermissionSet (declarative_security);
3854 if (a.Type == TypeManager.conditional_attribute_type) {
3855 if (IsOperator || IsExplicitImpl) {
3856 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3860 if (ReturnType != TypeManager.void_type) {
3861 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3865 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3866 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3871 Report.Error (582, Location, "Conditional not valid on interface members");
3875 if (MethodData.IsImplementing) {
3876 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3880 for (int i = 0; i < parameter_info.Count; ++i) {
3881 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3882 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3888 MethodBuilder.SetCustomAttribute (cb);
3891 protected override bool CheckForDuplications ()
3893 ArrayList ar = Parent.Methods;
3895 int arLen = ar.Count;
3897 for (int i = 0; i < arLen; i++) {
3898 Method m = (Method) ar [i];
3899 if (IsDuplicateImplementation (m))
3904 ar = Parent.Properties;
3906 for (int i = 0; i < ar.Count; ++i) {
3907 PropertyBase pb = (PropertyBase) ar [i];
3908 if (pb.AreAccessorsDuplicateImplementation (this))
3913 ar = Parent.Indexers;
3915 for (int i = 0; i < ar.Count; ++i) {
3916 PropertyBase pb = (PropertyBase) ar [i];
3917 if (pb.AreAccessorsDuplicateImplementation (this))
3924 for (int i = 0; i < ar.Count; ++i) {
3925 Event ev = (Event) ar [i];
3926 if (ev.AreAccessorsDuplicateImplementation (this))
3937 public override bool Define ()
3939 if (!DoDefineBase ())
3942 MethodBuilder mb = null;
3943 if (GenericMethod != null) {
3944 string mname = MemberName.GetMethodName ();
3945 mb = Parent.TypeBuilder.DefineGenericMethod (mname, flags);
3946 if (!GenericMethod.Define (mb, ReturnType))
3957 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3959 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
3960 this, mb, GenericMethod, base_method);
3962 if (!MethodData.Define (Parent))
3966 // Setup iterator if we are one
3968 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3969 Iterator iterator = new Iterator (
3970 Parent, Name, MemberType, ParameterTypes,
3971 ParameterInfo, ModFlags, block, Location);
3973 if (!iterator.DefineIterator ())
3976 block = iterator.Block;
3979 MethodBuilder = MethodData.MethodBuilder;
3982 // This is used to track the Entry Point,
3984 if (Name == "Main" &&
3985 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3986 (RootContext.MainClass == null ||
3987 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3988 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3989 if (RootContext.EntryPoint == null) {
3990 if (Parent.IsGeneric){
3991 Report.Error (-201, Location,
3992 "Entry point can not be defined in a generic class");
3995 RootContext.EntryPoint = MethodBuilder;
3996 RootContext.EntryPointLocation = Location;
3998 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3999 DuplicateEntryPoint (MethodBuilder, Location);
4002 if (RootContext.WarningLevel >= 4)
4003 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder) );
4007 if (MemberType.IsAbstract && MemberType.IsSealed) {
4008 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4018 public override void Emit ()
4020 MethodData.Emit (Parent, this);
4023 if (declarative_security != null) {
4024 foreach (DictionaryEntry de in declarative_security) {
4025 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4033 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4035 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
4036 container.TypeBuilder, Name, ParameterTypes, false);
4041 base_ret_type = mi.ReturnType;
4045 public override bool MarkForDuplicationCheck ()
4047 caching_flags |= Flags.TestMethodDuplication;
4051 protected override bool VerifyClsCompliance(DeclSpace ds)
4053 if (!base.VerifyClsCompliance (ds))
4056 if (parameter_types.Length > 0) {
4057 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
4059 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4066 void IIteratorContainer.SetYields ()
4068 ModFlags |= Modifiers.METHOD_YIELDS;
4071 #region IMethodData Members
4073 public CallingConventions CallingConventions {
4075 CallingConventions cc = Parameters.GetCallingConvention ();
4076 if (Parameters.HasArglist)
4077 block.HasVarargs = true;
4080 if ((ModFlags & Modifiers.STATIC) == 0)
4081 cc |= CallingConventions.HasThis;
4083 // FIXME: How is `ExplicitThis' used in C#?
4089 public Type ReturnType {
4095 public MemberName MethodName {
4101 public new Location Location {
4103 return base.Location;
4107 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4109 return new EmitContext (
4110 tc, ds, Location, ig, ReturnType, ModFlags, false);
4113 public ObsoleteAttribute GetObsoleteAttribute ()
4115 return GetObsoleteAttribute (ds);
4119 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4121 public bool IsExcluded (EmitContext ec)
4123 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4124 return (caching_flags & Flags.Excluded) != 0;
4126 caching_flags &= ~Flags.Excluded_Undetected;
4128 if (base_method == null) {
4129 if (OptAttributes == null)
4132 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4137 foreach (Attribute a in attrs) {
4138 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4139 if (RootContext.AllDefines.Contains (condition))
4143 caching_flags |= Flags.Excluded;
4147 IMethodData md = TypeManager.GetMethod (base_method);
4149 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4150 caching_flags |= Flags.Excluded;
4156 if (md.IsExcluded (ec)) {
4157 caching_flags |= Flags.Excluded;
4163 GenericMethod IMethodData.GenericMethod {
4165 return GenericMethod;
4172 public abstract class ConstructorInitializer {
4173 ArrayList argument_list;
4174 protected ConstructorInfo base_constructor;
4175 Parameters parameters;
4178 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4181 this.argument_list = argument_list;
4182 this.parameters = parameters;
4186 public ArrayList Arguments {
4188 return argument_list;
4192 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4194 Expression base_constructor_group;
4197 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
4199 if (argument_list != null){
4200 foreach (Argument a in argument_list){
4201 if (!a.Resolve (ec, loc))
4205 ec.CurrentBlock = null;
4207 if (this is ConstructorBaseInitializer) {
4208 if (ec.ContainerType.BaseType == null)
4211 t = ec.ContainerType.BaseType;
4212 if (ec.ContainerType.IsValueType) {
4213 Report.Error (522, loc,
4214 "structs cannot call base class constructors");
4218 t = ec.ContainerType;
4220 base_constructor_group = Expression.MemberLookup (
4221 ec, t, ".ctor", MemberTypes.Constructor,
4222 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4225 if (base_constructor_group == null){
4226 base_constructor_group = Expression.MemberLookup (
4227 ec, t, ".ctor", MemberTypes.Constructor,
4228 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4231 if (base_constructor_group != null)
4233 112, loc, "`{0}.{1}' is inaccessible due to " +
4234 "its protection level", t.FullName, t.Name);
4237 1501, loc, "Can not find a constructor for " +
4238 "this argument list");
4242 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4243 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4246 if (base_constructor == null){
4247 Report.Error (1501, loc,
4248 "Can not find a constructor for this argument list");
4252 if (base_constructor == caller_builder){
4253 Report.Error (516, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
4260 public void Emit (EmitContext ec)
4262 if (base_constructor != null){
4263 ec.Mark (loc, false);
4265 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4267 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4272 /// Method search for base ctor. (We do not cache it).
4274 Constructor GetOverloadedConstructor (TypeContainer tc)
4276 if (tc.InstanceConstructors == null)
4279 foreach (Constructor c in tc.InstanceConstructors) {
4280 if (Arguments == null) {
4281 if (c.ParameterTypes.Length == 0)
4289 int count = c.ParameterInfo.Count;
4291 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4292 for (int i = 0; i < count-1; i++)
4293 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4298 if (c.ParameterTypes.Length != Arguments.Count)
4301 for (int i = 0; i < Arguments.Count; ++i)
4302 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4317 //TODO: implement caching when it will be necessary
4318 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4320 Constructor ctor = GetOverloadedConstructor (tc);
4324 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4328 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4332 public class ConstructorBaseInitializer : ConstructorInitializer {
4333 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4334 base (argument_list, pars, l)
4338 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4339 if (base_constructor == null)
4342 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4343 if (type_ds == null) {
4344 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (base_constructor);
4347 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (base_constructor), loc);
4352 base.CheckObsoleteAttribute (type_ds, loc);
4357 public class ConstructorThisInitializer : ConstructorInitializer {
4358 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4359 base (argument_list, pars, l)
4364 public class Constructor : MethodCore, IMethodData {
4365 public ConstructorBuilder ConstructorBuilder;
4366 public ConstructorInitializer Initializer;
4367 ListDictionary declarative_security;
4370 // Modifiers allowed for a constructor.
4372 public const int AllowedModifiers =
4374 Modifiers.PROTECTED |
4375 Modifiers.INTERNAL |
4381 bool has_compliant_args = false;
4383 // The spec claims that static is not permitted, but
4384 // my very own code has static constructors.
4386 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4387 ConstructorInitializer init, Location l)
4388 : base (ds, null, null, mod, AllowedModifiers, false,
4389 new MemberName (name), null, args, l)
4394 public override string GetSignatureForError()
4396 if (ConstructorBuilder == null)
4397 return GetSignatureForError (Parent);
4399 return TypeManager.CSharpSignature (ConstructorBuilder);
4402 public bool HasCompliantArgs {
4404 return has_compliant_args;
4408 public override AttributeTargets AttributeTargets {
4410 return AttributeTargets.Constructor;
4416 // Returns true if this is a default constructor
4418 public bool IsDefault ()
4420 if ((ModFlags & Modifiers.STATIC) != 0)
4421 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4422 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4425 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4426 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4427 (Initializer is ConstructorBaseInitializer) &&
4428 (Initializer.Arguments == null);
4431 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4433 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4434 if (declarative_security == null) {
4435 declarative_security = new ListDictionary ();
4437 a.ExtractSecurityPermissionSet (declarative_security);
4441 ConstructorBuilder.SetCustomAttribute (cb);
4444 protected override bool CheckForDuplications ()
4446 ArrayList ar = Parent.InstanceConstructors;
4448 int arLen = ar.Count;
4450 for (int i = 0; i < arLen; i++) {
4451 Constructor m = (Constructor) ar [i];
4452 if (IsDuplicateImplementation (m))
4459 protected override bool CheckBase ()
4461 // Check whether arguments were correct.
4462 if (!DoDefineParameters ())
4465 // TODO: skip the rest for generated ctor
4466 if ((ModFlags & Modifiers.STATIC) != 0)
4469 if (!CheckForDuplications ())
4472 if (Parent.Kind == Kind.Struct) {
4473 if (ParameterTypes.Length == 0) {
4474 Report.Error (568, Location,
4475 "Structs can not contain explicit parameterless " +
4480 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4481 Report.Error (666, Location, "Protected member in struct declaration");
4486 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4487 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4494 // Creates the ConstructorBuilder
4496 public override bool Define ()
4498 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4499 MethodAttributes.SpecialName);
4501 if ((ModFlags & Modifiers.STATIC) != 0){
4502 ca |= MethodAttributes.Static | MethodAttributes.Private;
4504 ca |= MethodAttributes.HideBySig;
4506 if ((ModFlags & Modifiers.PUBLIC) != 0)
4507 ca |= MethodAttributes.Public;
4508 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4509 if ((ModFlags & Modifiers.INTERNAL) != 0)
4510 ca |= MethodAttributes.FamORAssem;
4512 ca |= MethodAttributes.Family;
4513 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4514 ca |= MethodAttributes.Assembly;
4515 else if (IsDefault ())
4516 ca |= MethodAttributes.Public;
4518 ca |= MethodAttributes.Private;
4521 // Check if arguments were correct.
4525 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4526 ca, CallingConventions,
4529 if ((ModFlags & Modifiers.UNSAFE) != 0)
4530 ConstructorBuilder.InitLocals = false;
4532 TypeManager.AddMethod (ConstructorBuilder, this);
4535 // HACK because System.Reflection.Emit is lame
4537 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4545 public override void Emit ()
4547 EmitContext ec = CreateEmitContext (null, null);
4550 // extern methods have no bodies
4552 if ((ModFlags & Modifiers.EXTERN) != 0) {
4553 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4555 179, Location, "External constructor `" +
4556 TypeManager.CSharpSignature (ConstructorBuilder) +
4557 "' can not have a body");
4560 } else if (block == null) {
4562 501, Location, "Constructor `" +
4563 TypeManager.CSharpSignature (ConstructorBuilder) +
4564 "' must declare a body since it is not marked extern");
4568 if ((ModFlags & Modifiers.STATIC) == 0){
4569 if (Parent.Kind == Kind.Class && Initializer == null)
4570 Initializer = new ConstructorBaseInitializer (
4571 null, Parameters.EmptyReadOnlyParameters, Location);
4575 // Spec mandates that Initializers will not have
4579 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4581 ec.IsStatic = false;
4584 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4586 SourceMethod source = SourceMethod.Create (
4587 Parent, ConstructorBuilder, block);
4590 // Classes can have base initializers and instance field initializers.
4592 if (Parent.Kind == Kind.Class){
4593 if ((ModFlags & Modifiers.STATIC) == 0){
4596 // If we use a "this (...)" constructor initializer, then
4597 // do not emit field initializers, they are initialized in the other constructor
4599 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4600 Parent.EmitFieldInitializers (ec);
4603 if (Initializer != null) {
4604 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4605 Initializer.CheckObsoleteAttribute (Parent, Location);
4607 ec.TestObsoleteMethodUsage = false;
4608 Initializer.Emit (ec);
4611 if ((ModFlags & Modifiers.STATIC) != 0)
4612 Parent.EmitFieldInitializers (ec);
4614 if (OptAttributes != null)
4615 OptAttributes.Emit (ec, this);
4617 // If this is a non-static `struct' constructor and doesn't have any
4618 // initializer, it must initialize all of the struct's fields.
4619 if ((Parent.Kind == Kind.Struct) &&
4620 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4621 Block.AddThisVariable (Parent, Location);
4623 ec.EmitTopBlock (block, ParameterInfo, Location);
4626 source.CloseMethod ();
4630 if (declarative_security != null) {
4631 foreach (DictionaryEntry de in declarative_security) {
4632 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4639 // Is never override
4640 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4645 protected override bool VerifyClsCompliance (DeclSpace ds)
4647 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4651 if (parameter_types.Length > 0) {
4652 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4654 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4656 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4657 foreach (Type param in parameter_types) {
4658 if (param.IsArray) {
4664 has_compliant_args = true;
4668 #region IMethodData Members
4670 public System.Reflection.CallingConventions CallingConventions {
4672 CallingConventions cc = Parameters.GetCallingConvention ();
4674 if (Parent.Kind == Kind.Class)
4675 if ((ModFlags & Modifiers.STATIC) == 0)
4676 cc |= CallingConventions.HasThis;
4678 // FIXME: How is `ExplicitThis' used in C#?
4684 public new Location Location {
4686 return base.Location;
4690 public MemberName MethodName {
4696 public Type ReturnType {
4702 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4704 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4705 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4708 public ObsoleteAttribute GetObsoleteAttribute ()
4713 public bool IsExcluded(EmitContext ec)
4718 GenericMethod IMethodData.GenericMethod {
4728 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4730 public interface IMethodData
4732 CallingConventions CallingConventions { get; }
4733 Location Location { get; }
4734 MemberName MethodName { get; }
4735 Type[] ParameterTypes { get; }
4736 Type ReturnType { get; }
4737 GenericMethod GenericMethod { get; }
4739 Attributes OptAttributes { get; }
4740 ToplevelBlock Block { get; }
4742 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4743 ObsoleteAttribute GetObsoleteAttribute ();
4744 string GetSignatureForError (TypeContainer tc);
4745 bool IsExcluded (EmitContext ec);
4746 bool IsClsCompliaceRequired (DeclSpace ds);
4750 // Encapsulates most of the Method's state
4752 public class MethodData {
4754 readonly IMethodData method;
4757 // The return type of this method
4759 public readonly GenericMethod GenericMethod;
4760 public readonly InternalParameters ParameterInfo;
4763 // Are we implementing an interface ?
4765 public bool IsImplementing = false;
4770 protected MemberBase member;
4771 protected int modifiers;
4772 protected MethodAttributes flags;
4773 protected Type declaring_type;
4774 protected MethodInfo parent_method;
4778 MethodBuilder builder = null;
4779 public MethodBuilder MethodBuilder {
4785 public Type DeclaringType {
4787 return declaring_type;
4791 public MethodData (MemberBase member, InternalParameters parameters,
4792 int modifiers, MethodAttributes flags, IMethodData method)
4794 this.member = member;
4795 this.ParameterInfo = parameters;
4796 this.modifiers = modifiers;
4799 this.method = method;
4802 public MethodData (MemberBase member, InternalParameters parameters,
4803 int modifiers, MethodAttributes flags,
4804 IMethodData method, MethodBuilder builder,
4805 GenericMethod generic, MethodInfo parent_method)
4806 : this (member, parameters, modifiers, flags, method)
4808 this.builder = builder;
4809 this.GenericMethod = generic;
4810 this.parent_method = parent_method;
4813 static string RemoveArity (string name)
4816 StringBuilder sb = new StringBuilder ();
4817 while (start < name.Length) {
4818 int pos = name.IndexOf ('`', start);
4820 sb.Append (name.Substring (start));
4824 sb.Append (name.Substring (start, pos-start));
4827 while ((pos < name.Length) && Char.IsNumber (name [pos]))
4833 return sb.ToString ();
4836 public bool Define (TypeContainer container)
4838 MethodInfo implementing = null;
4841 if (member.IsExplicitImpl)
4842 prefix = member.InterfaceType.FullName + ".";
4846 string name = method.MethodName.Basename;
4847 string method_name = prefix + name;
4849 Type[] ParameterTypes = method.ParameterTypes;
4851 if (container.Pending != null){
4852 if (member is Indexer)
4853 implementing = container.Pending.IsInterfaceIndexer (
4854 member.InterfaceType, method.ReturnType, ParameterTypes);
4856 implementing = container.Pending.IsInterfaceMethod (
4857 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4859 if (member.InterfaceType != null){
4860 if (implementing == null){
4861 Report.Error (539, method.Location,
4862 "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
4869 // For implicit implementations, make sure we are public, for
4870 // explicit implementations, make sure we are private.
4872 if (implementing != null){
4874 // Setting null inside this block will trigger a more
4875 // verbose error reporting for missing interface implementations
4877 // The "candidate" function has been flagged already
4878 // but it wont get cleared
4880 if (member.IsExplicitImpl){
4881 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4882 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4883 implementing = null;
4885 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4886 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4888 // If this is an interface method implementation,
4889 // check for public accessibility
4891 implementing = null;
4892 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4893 // We may never be private.
4894 implementing = null;
4895 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4897 // We may be protected if we're overriding something.
4899 implementing = null;
4904 // Static is not allowed
4906 if ((modifiers & Modifiers.STATIC) != 0){
4907 implementing = null;
4908 Modifiers.Error_InvalidModifier (method.Location, "static");
4913 // If implementing is still valid, set flags
4915 if (implementing != null){
4917 // When implementing interface methods, set NewSlot
4918 // unless, we are overwriting a method.
4920 if (implementing.DeclaringType.IsInterface){
4921 if ((modifiers & Modifiers.OVERRIDE) == 0)
4922 flags |= MethodAttributes.NewSlot;
4925 MethodAttributes.Virtual |
4926 MethodAttributes.HideBySig;
4928 // Set Final unless we're virtual, abstract or already overriding a method.
4929 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4930 flags |= MethodAttributes.Final;
4932 IsImplementing = true;
4935 EmitContext ec = method.CreateEmitContext (container, null);
4937 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4939 if (builder == null)
4942 if (container.CurrentType != null)
4943 declaring_type = container.CurrentType;
4945 declaring_type = container.TypeBuilder;
4947 if ((modifiers & Modifiers.UNSAFE) != 0)
4948 builder.InitLocals = false;
4950 if (IsImplementing){
4952 // clear the pending implemntation flag
4954 if (member is Indexer) {
4955 container.Pending.ImplementIndexer (
4956 member.InterfaceType, builder, method.ReturnType,
4957 ParameterTypes, member.IsExplicitImpl);
4959 container.Pending.ImplementMethod (
4960 member.InterfaceType, name, method.ReturnType,
4961 ParameterTypes, member.IsExplicitImpl);
4963 if (member.IsExplicitImpl)
4964 container.TypeBuilder.DefineMethodOverride (
4965 builder, implementing);
4969 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4970 TypeManager.AddMethod (builder, method);
4972 if (GenericMethod != null) {
4973 bool is_override = member.IsExplicitImpl |
4974 ((modifiers & Modifiers.OVERRIDE) != 0);
4976 if (implementing != null)
4977 parent_method = implementing;
4979 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
4987 /// Create the MethodBuilder for the method
4989 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4991 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4993 if ((modifiers & extern_static) == extern_static) {
4995 if (method.OptAttributes != null) {
4996 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4997 if (dllimport_attribute != null) {
4998 flags |= MethodAttributes.PinvokeImpl;
4999 builder = dllimport_attribute.DefinePInvokeMethod (
5000 ec, container.TypeBuilder, method_name, flags,
5001 method.ReturnType, ParameterTypes);
5007 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5008 // We are more strict than Microsoft and report CS0626 like error
5009 if (method.OptAttributes == null ||
5010 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
5011 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));
5016 if (builder == null)
5017 builder = container.TypeBuilder.DefineMethod (
5018 method_name, flags, method.CallingConventions,
5019 method.ReturnType, ParameterTypes);
5021 builder.SetGenericMethodSignature (
5022 flags, method.CallingConventions,
5023 method.ReturnType, ParameterTypes);
5029 public void Emit (TypeContainer container, Attributable kind)
5032 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5033 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
5035 ec = method.CreateEmitContext (container, null);
5037 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container.Parent) != null)
5038 ec.TestObsoleteMethodUsage = false;
5040 Location loc = method.Location;
5041 Attributes OptAttributes = method.OptAttributes;
5043 if (OptAttributes != null)
5044 OptAttributes.Emit (ec, kind);
5046 if (member is MethodCore)
5047 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
5049 ToplevelBlock block = method.Block;
5052 // abstract or extern methods have no bodies
5054 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
5059 // abstract or extern methods have no bodies.
5061 if ((modifiers & Modifiers.ABSTRACT) != 0)
5063 500, method.Location, "Abstract method `" +
5064 TypeManager.CSharpSignature (builder) +
5065 "' can not have a body");
5067 if ((modifiers & Modifiers.EXTERN) != 0)
5069 179, method.Location, "External method `" +
5070 TypeManager.CSharpSignature (builder) +
5071 "' can not have a body");
5077 // Methods must have a body unless they're extern or abstract
5079 if (block == null) {
5081 501, method.Location, "Method `" +
5082 TypeManager.CSharpSignature (builder) +
5083 "' must declare a body since it is not marked " +
5084 "abstract or extern");
5088 SourceMethod source = SourceMethod.Create (
5089 container, MethodBuilder, method.Block);
5092 // Handle destructors specially
5094 // FIXME: This code generates buggy code
5096 if (member is Destructor)
5097 EmitDestructor (ec, block);
5099 ec.EmitTopBlock (block, ParameterInfo, loc);
5102 source.CloseMethod ();
5105 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5107 ILGenerator ig = ec.ig;
5109 Label finish = ig.DefineLabel ();
5111 block.SetDestructor ();
5113 ig.BeginExceptionBlock ();
5114 ec.ReturnLabel = finish;
5115 ec.HasReturnLabel = true;
5116 ec.EmitTopBlock (block, null, method.Location);
5118 // ig.MarkLabel (finish);
5119 ig.BeginFinallyBlock ();
5121 if (ec.ContainerType.BaseType != null) {
5122 Expression member_lookup = Expression.MemberLookup (
5123 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5124 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5126 if (member_lookup != null){
5127 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5129 ig.Emit (OpCodes.Ldarg_0);
5130 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5134 ig.EndExceptionBlock ();
5135 //ig.MarkLabel (ec.ReturnLabel);
5136 ig.Emit (OpCodes.Ret);
5140 public class Destructor : Method {
5142 public Destructor (TypeContainer ds, Expression return_type, int mod, string name,
5143 Parameters parameters, Attributes attrs, Location l)
5144 : base (ds, null, return_type, mod, false, new MemberName (name),
5145 parameters, attrs, l)
5148 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5150 if (a.Type == TypeManager.conditional_attribute_type) {
5151 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
5155 base.ApplyAttributeBuilder (a, cb);
5159 abstract public class MemberBase : MemberCore {
5160 public Expression Type;
5162 public MethodAttributes flags;
5164 protected readonly int explicit_mod_flags;
5167 // The "short" name of this property / indexer / event. This is the
5168 // name without the explicit interface.
5170 public string ShortName;
5173 // The type of this property / indexer / event
5175 public Type MemberType;
5178 // If true, this is an explicit interface implementation
5180 public bool IsExplicitImpl = false;
5183 // The name of the interface we are explicitly implementing
5185 public MemberName ExplicitInterfaceName = null;
5188 // Whether this is an interface member.
5190 public bool IsInterface;
5193 // If true, the interface type we are explicitly implementing
5195 public Type InterfaceType = null;
5198 // The constructor is only exposed to our children
5200 protected MemberBase (TypeContainer parent, Expression type, int mod,
5201 int allowed_mod, int def_mod, MemberName name,
5202 Attributes attrs, Location loc)
5203 : base (parent, name, attrs, loc)
5205 explicit_mod_flags = mod;
5207 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
5209 // Check for explicit interface implementation
5210 if (MemberName.Left != null) {
5211 ExplicitInterfaceName = MemberName.Left;
5212 ShortName = MemberName.Name;
5213 IsExplicitImpl = true;
5218 protected virtual bool CheckBase ()
5220 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5221 Report.Error (666, Location, "Protected member in struct declaration");
5225 if ((RootContext.WarningLevel >= 4) &&
5226 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5227 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5228 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5229 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
5235 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5237 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5241 foreach (Type partype in parameters){
5242 if (partype == TypeManager.void_type) {
5244 1547, Location, "Keyword 'void' cannot " +
5245 "be used in this context");
5249 if (partype.IsPointer){
5252 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5256 if (ds.AsAccessible (partype, ModFlags))
5259 if (this is Indexer)
5260 Report.Error (55, Location,
5261 "Inconsistent accessibility: parameter type `" +
5262 TypeManager.CSharpName (partype) + "' is less " +
5263 "accessible than indexer `" + Name + "'");
5264 else if ((this is Method) && ((Method) this).IsOperator)
5265 Report.Error (57, Location,
5266 "Inconsistent accessibility: parameter type `" +
5267 TypeManager.CSharpName (partype) + "' is less " +
5268 "accessible than operator `" + Name + "'");
5270 Report.Error (51, Location,
5271 "Inconsistent accessibility: parameter type `" +
5272 TypeManager.CSharpName (partype) + "' is less " +
5273 "accessible than method `" + Name + "'");
5280 protected virtual bool DoDefineBase ()
5282 EmitContext ec = Parent.EmitContext;
5284 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5287 throw new InternalErrorException ();
5290 ModFlags = Modifiers.PUBLIC |
5291 Modifiers.ABSTRACT |
5292 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5294 flags = MethodAttributes.Public |
5295 MethodAttributes.Abstract |
5296 MethodAttributes.HideBySig |
5297 MethodAttributes.NewSlot |
5298 MethodAttributes.Virtual;
5300 if (!Parent.MethodModifiersValid (this))
5303 flags = Modifiers.MethodAttr (ModFlags);
5309 protected virtual bool DoDefine (DeclSpace decl)
5311 EmitContext ec = decl.EmitContext;
5313 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5315 ec.InUnsafe = InUnsafe;
5317 // Lookup Type, verify validity
5318 bool old_unsafe = ec.InUnsafe;
5319 ec.InUnsafe = InUnsafe;
5320 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
5321 ec.InUnsafe = old_unsafe;
5326 MemberType = texpr.Type;
5328 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5329 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5330 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5335 // verify accessibility
5336 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5337 Report.SymbolRelatedToPreviousError (MemberType);
5338 if (this is Property)
5339 Report.Error (53, Location,
5340 "Inconsistent accessibility: property type `" +
5341 TypeManager.CSharpName (MemberType) + "' is less " +
5342 "accessible than property `" + GetSignatureForError () + "'");
5343 else if (this is Indexer)
5344 Report.Error (54, Location,
5345 "Inconsistent accessibility: indexer return type `" +
5346 TypeManager.CSharpName (MemberType) + "' is less " +
5347 "accessible than indexer `" + Name + "'");
5348 else if (this is MethodCore) {
5349 if (this is Operator)
5350 Report.Error (56, Location,
5351 "Inconsistent accessibility: return type `" +
5352 TypeManager.CSharpName (MemberType) + "' is less " +
5353 "accessible than operator `" + Name + "'");
5355 Report.Error (50, Location,
5356 "Inconsistent accessibility: return type `" +
5357 TypeManager.CSharpName (MemberType) + "' is less " +
5358 "accessible than method `" + Name + "'");
5360 Report.Error (52, Location,
5361 "Inconsistent accessibility: field type `" +
5362 TypeManager.CSharpName (MemberType) + "' is less " +
5363 "accessible than field `" + Name + "'");
5368 if (MemberType.IsPointer && !UnsafeOK (Parent))
5371 if (IsExplicitImpl) {
5372 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
5373 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5374 if (iface_texpr == null)
5377 InterfaceType = iface_texpr.Type;
5379 if (!InterfaceType.IsInterface) {
5380 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5384 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5387 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5394 /// The name of the member can be changed during definition (see IndexerName attribute)
5396 protected virtual void UpdateMemberName ()
5398 MemberName.Name = ShortName;
5401 public override string GetSignatureForError (TypeContainer tc)
5403 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5406 protected bool IsTypePermitted ()
5408 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5409 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5415 protected override bool VerifyClsCompliance(DeclSpace ds)
5417 if (base.VerifyClsCompliance (ds)) {
5421 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5422 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5427 protected override void VerifyObsoleteAttribute()
5429 CheckUsageOfObsoleteAttribute (MemberType);
5434 // Fields and Events both generate FieldBuilders, we use this to share
5435 // their common bits. This is also used to flag usage of the field
5437 abstract public class FieldBase : MemberBase {
5438 public FieldBuilder FieldBuilder;
5439 public Status status;
5442 public enum Status : byte {
5445 HAS_OFFSET = 4 // Used by FieldMember.
5448 static string[] attribute_targets = new string [] { "field" };
5451 /// Symbol with same name in base class/struct
5453 public MemberInfo conflict_symbol;
5456 // The constructor is only exposed to our children
5458 protected FieldBase (TypeContainer parent, Expression type, int mod,
5459 int allowed_mod, MemberName name, object init,
5460 Attributes attrs, Location loc)
5461 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5467 public override AttributeTargets AttributeTargets {
5469 return AttributeTargets.Field;
5473 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5475 if (a.Type == TypeManager.marshal_as_attr_type) {
5476 UnmanagedMarshal marshal = a.GetMarshal (this);
5477 if (marshal != null) {
5478 FieldBuilder.SetMarshal (marshal);
5483 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5484 a.Error_InvalidSecurityParent ();
5488 FieldBuilder.SetCustomAttribute (cb);
5492 // Whether this field has an initializer.
5494 public bool HasInitializer {
5496 return init != null;
5500 protected readonly Object init;
5502 Expression init_expr;
5503 bool init_expr_initialized = false;
5505 protected override bool CheckGenericOverride (MethodInfo method, string name)
5511 // Resolves and returns the field initializer.
5513 public Expression GetInitializerExpression (EmitContext ec)
5515 if (init_expr_initialized)
5519 if (init is Expression)
5520 e = (Expression) init;
5522 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5524 ec.IsFieldInitializer = true;
5525 e = e.DoResolve (ec);
5526 ec.IsFieldInitializer = false;
5529 init_expr_initialized = true;
5534 protected override bool CheckBase ()
5536 if (!base.CheckBase ())
5543 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5544 if (conflict_symbol == null) {
5545 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5546 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5551 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5552 Report.SymbolRelatedToPreviousError (conflict_symbol);
5553 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5559 protected override bool DoDefine (DeclSpace ds)
5561 if (!base.DoDefine (ds))
5564 if (MemberType == TypeManager.void_type) {
5565 Report.Error (1547, Location,
5566 "Keyword 'void' cannot be used in this context");
5572 public override string GetSignatureForError ()
5574 if (FieldBuilder == null) {
5575 return base.GetSignatureForError (Parent);
5577 return TypeManager.GetFullNameSignature (FieldBuilder);
5580 public override string[] ValidAttributeTargets {
5582 return attribute_targets;
5586 protected override bool VerifyClsCompliance (DeclSpace ds)
5588 if (!base.VerifyClsCompliance (ds))
5591 if (FieldBuilder == null) {
5595 if (!AttributeTester.IsClsCompliant (FieldBuilder.FieldType)) {
5596 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5602 public void SetAssigned ()
5604 status |= Status.ASSIGNED;
5608 public abstract class FieldMember: FieldBase
5612 protected FieldMember (TypeContainer parent, Expression type, int mod,
5613 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5614 : base (parent, type, mod, allowed_mod, name, init, attrs, loc)
5618 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5620 if (a.Type == TypeManager.field_offset_attribute_type)
5622 status |= Status.HAS_OFFSET;
5624 if (!Parent.HasExplicitLayout) {
5625 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5629 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5630 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5634 base.ApplyAttributeBuilder (a, cb);
5638 public override bool Define()
5640 EmitContext ec = Parent.EmitContext;
5642 throw new InternalErrorException ("FieldMember.Define called too early");
5644 bool old_unsafe = ec.InUnsafe;
5645 ec.InUnsafe = InUnsafe;
5646 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
5647 ec.InUnsafe = old_unsafe;
5651 MemberType = texpr.Type;
5653 if (MemberType == TypeManager.void_type) {
5654 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5658 ec.InUnsafe = old_unsafe;
5663 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5664 Report.Error (52, Location,
5665 "Inconsistent accessibility: field type `" +
5666 TypeManager.CSharpName (MemberType) + "' is less " +
5667 "accessible than field `" + Name + "'");
5671 if (!IsTypePermitted ())
5674 if (MemberType.IsPointer && !UnsafeOK (Parent))
5680 public override void Emit ()
5682 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5683 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5690 // Represents header string for documentation comment.
5692 public override string DocCommentHeader {
5693 get { return "F:"; }
5698 // The Field class is used to represents class/struct fields during parsing.
5700 public class Field : FieldMember {
5702 // Modifiers allowed in a class declaration
5704 const int AllowedModifiers =
5707 Modifiers.PROTECTED |
5708 Modifiers.INTERNAL |
5711 Modifiers.VOLATILE |
5715 public Field (TypeContainer parent, Expression type, int mod, string name,
5716 Object expr_or_array_init, Attributes attrs, Location loc)
5717 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5718 expr_or_array_init, attrs, loc)
5722 public override bool Define ()
5724 if (!base.Define ())
5727 if (RootContext.WarningLevel > 1){
5728 Type ptype = Parent.TypeBuilder.BaseType;
5730 // ptype is only null for System.Object while compiling corlib.
5732 TypeContainer.FindMembers (
5733 ptype, MemberTypes.Method,
5734 BindingFlags.Public |
5735 BindingFlags.Static | BindingFlags.Instance,
5736 System.Type.FilterName, Name);
5740 if ((ModFlags & Modifiers.VOLATILE) != 0){
5741 if (!MemberType.IsClass){
5742 Type vt = MemberType;
5744 if (TypeManager.IsEnumType (vt))
5745 vt = TypeManager.EnumToUnderlying (MemberType);
5747 if (!((vt == TypeManager.bool_type) ||
5748 (vt == TypeManager.sbyte_type) ||
5749 (vt == TypeManager.byte_type) ||
5750 (vt == TypeManager.short_type) ||
5751 (vt == TypeManager.ushort_type) ||
5752 (vt == TypeManager.int32_type) ||
5753 (vt == TypeManager.uint32_type) ||
5754 (vt == TypeManager.char_type) ||
5755 (vt == TypeManager.float_type) ||
5756 (!vt.IsValueType))){
5758 677, Location, Parent.MakeName (Name) +
5759 " A volatile field can not be of type `" +
5760 TypeManager.CSharpName (vt) + "'");
5765 if ((ModFlags & Modifiers.READONLY) != 0){
5768 "A field can not be both volatile and readonly");
5773 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5775 if (Parent.Kind == Kind.Struct &&
5776 ((fa & FieldAttributes.Static) == 0) &&
5777 MemberType == Parent.TypeBuilder &&
5778 !TypeManager.IsBuiltinType (MemberType)){
5779 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5780 "' causes a cycle in the structure layout");
5785 FieldBuilder = Parent.TypeBuilder.DefineField (
5786 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5788 TypeManager.RegisterFieldBase (FieldBuilder, this);
5790 catch (ArgumentException) {
5791 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5798 public override void Emit ()
5800 if (OptAttributes != null) {
5801 EmitContext ec = new EmitContext (
5802 Parent, Location, null, FieldBuilder.FieldType,
5804 OptAttributes.Emit (ec, this);
5812 // `set' and `get' accessors are represented with an Accessor.
5814 public class Accessor {
5816 // Null if the accessor is empty, or a Block if not
5818 public const int AllowedModifiers =
5820 Modifiers.PROTECTED |
5821 Modifiers.INTERNAL |
5824 public ToplevelBlock Block;
5825 public Attributes Attributes;
5826 public Location Location;
5827 public int ModFlags;
5829 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5834 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5839 // Ooouh Martin, templates are missing here.
5840 // When it will be possible move here a lot of child code and template method type.
5841 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5842 protected MethodData method_data;
5843 protected ToplevelBlock block;
5844 protected ListDictionary declarative_security;
5846 // The accessor are created event if they are not wanted.
5847 // But we need them because their names are reserved.
5848 // Field says whether accessor will be emited or not
5849 public readonly bool IsDummy;
5851 protected readonly string prefix;
5853 ReturnParameter return_attributes;
5855 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5856 : base (null, SetupName (prefix, member), null, member.Location)
5858 this.prefix = prefix;
5862 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5864 : base (null, SetupName (prefix, member),
5865 accessor.Attributes, accessor.Location)
5867 this.prefix = prefix;
5868 this.block = accessor.Block;
5871 static MemberName SetupName (string prefix, MemberBase member)
5873 MemberName name = member.MemberName.Clone ();
5874 name.Name = prefix + member.ShortName;
5878 public void UpdateName (MemberBase member)
5880 MemberName.Name = prefix + member.ShortName;
5883 #region IMethodData Members
5885 public ToplevelBlock Block {
5895 public CallingConventions CallingConventions {
5897 return CallingConventions.Standard;
5901 public bool IsExcluded (EmitContext ec)
5906 GenericMethod IMethodData.GenericMethod {
5912 public MemberName MethodName {
5918 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5919 public abstract Type[] ParameterTypes { get; }
5920 public abstract Type ReturnType { get; }
5921 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5925 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5927 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5928 a.Type == TypeManager.conditional_attribute_type) {
5929 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 ());
5933 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5934 if (declarative_security == null)
5935 declarative_security = new ListDictionary ();
5936 a.ExtractSecurityPermissionSet (declarative_security);
5940 if (a.Target == AttributeTargets.Method) {
5941 method_data.MethodBuilder.SetCustomAttribute (cb);
5945 if (a.Target == AttributeTargets.ReturnValue) {
5946 if (return_attributes == null)
5947 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5949 return_attributes.ApplyAttributeBuilder (a, cb);
5953 ApplyToExtraTarget (a, cb);
5956 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5958 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5961 public override bool Define()
5963 throw new NotSupportedException ();
5966 public virtual void Emit (TypeContainer container)
5968 method_data.Emit (container, this);
5970 if (declarative_security != null) {
5971 foreach (DictionaryEntry de in declarative_security) {
5972 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5979 public override bool IsClsCompliaceRequired(DeclSpace ds)
5984 public bool IsDuplicateImplementation (MethodCore method)
5986 if (Name != method.Name)
5989 Type[] param_types = method.ParameterTypes;
5991 if (param_types.Length != ParameterTypes.Length)
5994 for (int i = 0; i < param_types.Length; i++)
5995 if (param_types [i] != ParameterTypes [i])
5998 Report.SymbolRelatedToPreviousError (method);
5999 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with " +
6000 "the same parameter types", Parent.Name, Name);
6004 public new Location Location {
6006 return base.Location;
6011 // Represents header string for documentation comment.
6013 public override string DocCommentHeader {
6014 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6017 protected override void VerifyObsoleteAttribute()
6024 // Properties and Indexers both generate PropertyBuilders, we use this to share
6025 // their common bits.
6027 abstract public class PropertyBase : MethodCore {
6029 public class GetMethod: PropertyMethod
6031 static string[] attribute_targets = new string [] { "method", "return" };
6033 public GetMethod (MethodCore method):
6034 base (method, "get_")
6038 public GetMethod (MethodCore method, Accessor accessor):
6039 base (method, accessor, "get_")
6043 public override MethodBuilder Define(TypeContainer container)
6045 base.Define (container);
6047 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
6049 if (!method_data.Define (container))
6052 return method_data.MethodBuilder;
6055 public override string GetSignatureForError (TypeContainer tc)
6057 return String.Concat (base.GetSignatureForError (tc), ".get");
6060 public override Type ReturnType {
6062 return method.MemberType;
6066 public override string[] ValidAttributeTargets {
6068 return attribute_targets;
6073 public class SetMethod: PropertyMethod {
6075 static string[] attribute_targets = new string [] { "method", "param", "return" };
6076 ImplicitParameter param_attr;
6078 public SetMethod (MethodCore method):
6079 base (method, "set_")
6083 public SetMethod (MethodCore method, Accessor accessor):
6084 base (method, accessor, "set_")
6088 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6090 if (a.Target == AttributeTargets.Parameter) {
6091 if (param_attr == null)
6092 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6094 param_attr.ApplyAttributeBuilder (a, cb);
6098 base.ApplyAttributeBuilder (a, cb);
6101 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
6103 Parameter [] parms = new Parameter [1];
6104 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
6105 Parameters parameters = new Parameters (parms, null, method.Location);
6107 bool old_unsafe = ec.InUnsafe;
6108 ec.InUnsafe = InUnsafe;
6109 Type [] types = parameters.GetParameterInfo (ec);
6110 ec.InUnsafe = old_unsafe;
6112 return new InternalParameters (types, parameters);
6115 public override MethodBuilder Define (TypeContainer container)
6117 if (container.EmitContext == null)
6118 throw new InternalErrorException ("SetMethod.Define called too early");
6120 base.Define (container);
6122 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6124 if (!method_data.Define (container))
6127 return method_data.MethodBuilder;
6130 public override string GetSignatureForError (TypeContainer tc)
6132 return String.Concat (base.GetSignatureForError (tc), ".set");
6135 public override Type[] ParameterTypes {
6137 return new Type[] { method.MemberType };
6141 public override Type ReturnType {
6143 return TypeManager.void_type;
6147 public override string[] ValidAttributeTargets {
6149 return attribute_targets;
6154 static string[] attribute_targets = new string [] { "property" };
6156 public abstract class PropertyMethod: AbstractPropertyEventMethod {
6157 protected readonly MethodCore method;
6158 protected MethodAttributes flags;
6160 public PropertyMethod (MethodCore method, string prefix)
6161 : base (method, prefix)
6163 this.method = method;
6164 Parent = method.Parent;
6167 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6168 : base (method, accessor, prefix)
6170 this.method = method;
6171 Parent = method.Parent;
6172 this.ModFlags = accessor.ModFlags;
6174 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6175 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
6176 Environment.Exit (1);
6180 public override AttributeTargets AttributeTargets {
6182 return AttributeTargets.Method;
6186 public override bool IsClsCompliaceRequired(DeclSpace ds)
6188 return method.IsClsCompliaceRequired (ds);
6191 public InternalParameters ParameterInfo
6194 return method_data.ParameterInfo;
6198 public virtual MethodBuilder Define (TypeContainer container)
6201 // Check for custom access modifier
6203 if (ModFlags == 0) {
6204 ModFlags = method.ModFlags;
6205 flags = method.flags;
6207 CheckModifiers (container, ModFlags);
6208 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6209 flags = Modifiers.MethodAttr (ModFlags);
6210 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6217 public override Type[] ParameterTypes {
6219 return TypeManager.NoTypes;
6223 public override EmitContext CreateEmitContext (TypeContainer tc,
6226 return new EmitContext (
6227 tc, method.ds, method.Location, ig, ReturnType,
6228 method.ModFlags, false);
6231 public override ObsoleteAttribute GetObsoleteAttribute ()
6233 return method.GetObsoleteAttribute (method.ds);
6236 public override string GetSignatureForError (TypeContainer tc)
6238 return String.Concat (tc.Name, '.', method.Name);
6241 void CheckModifiers (TypeContainer container, int modflags)
6244 int mflags = method.ModFlags & Modifiers.Accessibility;
6246 if ((mflags & Modifiers.PUBLIC) != 0) {
6247 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6249 else if ((mflags & Modifiers.PROTECTED) != 0) {
6250 if ((mflags & Modifiers.INTERNAL) != 0)
6251 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6253 flags |= Modifiers.PRIVATE;
6255 else if ((mflags & Modifiers.INTERNAL) != 0)
6256 flags |= Modifiers.PRIVATE;
6258 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6259 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6260 GetSignatureForError (container));
6263 public override bool MarkForDuplicationCheck ()
6265 caching_flags |= Flags.TestMethodDuplication;
6270 public PropertyMethod Get, Set;
6271 public PropertyBuilder PropertyBuilder;
6272 public MethodBuilder GetBuilder, SetBuilder;
6274 protected EmitContext ec;
6276 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6277 int allowed_mod, bool is_iface, MemberName name,
6278 Parameters parameters, Attributes attrs,
6280 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6281 attrs, parameters, loc)
6285 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6287 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6288 a.Error_InvalidSecurityParent ();
6292 PropertyBuilder.SetCustomAttribute (cb);
6295 public override AttributeTargets AttributeTargets {
6297 return AttributeTargets.Property;
6301 public override bool Define ()
6303 if (!DoDefine (Parent))
6306 if (!IsTypePermitted ())
6312 protected override bool DoDefine (DeclSpace ds)
6314 if (!base.DoDefine (ds))
6318 // Accessors modifiers check
6320 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6321 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6322 GetSignatureForError ());
6326 if ((Get.IsDummy || Set.IsDummy)
6327 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6328 Report.Error (276, Location,
6329 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6330 GetSignatureForError ());
6334 if (MemberType.IsAbstract && MemberType.IsSealed) {
6335 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6339 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6343 public override string GetSignatureForError()
6345 if (PropertyBuilder == null)
6346 return GetSignatureForError (Parent);
6348 return TypeManager.CSharpSignature (PropertyBuilder, false);
6351 protected override bool CheckForDuplications ()
6353 ArrayList ar = Parent.Indexers;
6355 int arLen = ar.Count;
6357 for (int i = 0; i < arLen; i++) {
6358 Indexer m = (Indexer) ar [i];
6359 if (IsDuplicateImplementation (m))
6364 ar = Parent.Properties;
6366 int arLen = ar.Count;
6368 for (int i = 0; i < arLen; i++) {
6369 Property m = (Property) ar [i];
6370 if (IsDuplicateImplementation (m))
6378 // TODO: rename to Resolve......
6379 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6381 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6382 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6384 if (base_property == null)
6387 base_ret_type = base_property.PropertyType;
6388 MethodInfo get_accessor = base_property.GetGetMethod (true);
6389 MethodInfo set_accessor = base_property.GetSetMethod (true);
6390 MethodAttributes get_accessor_access, set_accessor_access;
6392 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6393 if (Get != null && !Get.IsDummy && get_accessor == null) {
6394 Report.SymbolRelatedToPreviousError (base_property);
6395 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6398 if (Set != null && !Set.IsDummy && set_accessor == null) {
6399 Report.SymbolRelatedToPreviousError (base_property);
6400 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6405 // Check base class accessors access
6407 get_accessor_access = set_accessor_access = 0;
6408 if ((ModFlags & Modifiers.NEW) == 0) {
6409 if (get_accessor != null) {
6410 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6411 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6413 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6414 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6415 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6418 if (set_accessor != null) {
6419 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6420 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6422 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6423 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6424 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6429 // Get the less restrictive access
6431 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6434 public override void Emit ()
6437 // The PropertyBuilder can be null for explicit implementations, in that
6438 // case, we do not actually emit the ".property", so there is nowhere to
6439 // put the attribute
6441 if (PropertyBuilder != null && OptAttributes != null)
6442 OptAttributes.Emit (ec, this);
6454 /// Tests whether accessors are not in collision with some method (CS0111)
6456 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6458 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6461 protected override void UpdateMemberName ()
6463 base.UpdateMemberName ();
6465 Get.UpdateName (this);
6466 Set.UpdateName (this);
6469 protected override bool VerifyClsCompliance (DeclSpace ds)
6471 if (!base.VerifyClsCompliance (ds))
6474 if ((Get.ModFlags != ModFlags && !Get.IsDummy) || (Set.ModFlags != ModFlags && !Set.IsDummy)) {
6475 Report.Error (3025, Get.ModFlags != ModFlags ? Get.Location : Set.Location,
6476 "CLS-compliant accessors must have the same accessibility as their property");
6481 public override string[] ValidAttributeTargets {
6483 return attribute_targets;
6488 // Represents header string for documentation comment.
6490 public override string DocCommentHeader {
6491 get { return "P:"; }
6495 public class Property : PropertyBase, IIteratorContainer {
6496 const int AllowedModifiers =
6499 Modifiers.PROTECTED |
6500 Modifiers.INTERNAL |
6504 Modifiers.OVERRIDE |
6505 Modifiers.ABSTRACT |
6508 Modifiers.METHOD_YIELDS |
6511 const int AllowedInterfaceModifiers =
6514 public Property (TypeContainer parent, Expression type, int mod_flags,
6515 bool is_iface, MemberName name, Attributes attrs,
6516 Accessor get_block, Accessor set_block, Location loc)
6517 : base (parent, type, mod_flags,
6518 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6519 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6522 if (get_block == null)
6523 Get = new GetMethod (this);
6525 Get = new GetMethod (this, get_block);
6527 if (set_block == null)
6528 Set = new SetMethod (this);
6530 Set = new SetMethod (this, set_block);
6533 public override bool Define ()
6535 if (!DoDefineBase ())
6538 if (!base.Define ())
6544 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6548 GetBuilder = Get.Define (Parent);
6549 if (GetBuilder == null)
6553 // Setup iterator if we are one
6555 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6556 Iterator iterator = new Iterator (
6557 Parent, "get", MemberType,
6558 TypeManager.NoTypes, Get.ParameterInfo,
6559 ModFlags, Get.Block, Location);
6561 if (!iterator.DefineIterator ())
6563 Get.Block = iterator.Block;
6568 SetBuilder = Set.Define (Parent);
6569 if (SetBuilder == null)
6572 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6575 // FIXME - PropertyAttributes.HasDefault ?
6577 PropertyAttributes prop_attr = PropertyAttributes.None;
6579 prop_attr |= PropertyAttributes.RTSpecialName |
6580 PropertyAttributes.SpecialName;
6582 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6583 Name, prop_attr, MemberType, null);
6586 PropertyBuilder.SetGetMethod (GetBuilder);
6589 PropertyBuilder.SetSetMethod (SetBuilder);
6591 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6595 public void SetYields ()
6597 ModFlags |= Modifiers.METHOD_YIELDS;
6602 /// Gigantic workaround for lameness in SRE follows :
6603 /// This class derives from EventInfo and attempts to basically
6604 /// wrap around the EventBuilder so that FindMembers can quickly
6605 /// return this in it search for members
6607 public class MyEventBuilder : EventInfo {
6610 // We use this to "point" to our Builder which is
6611 // not really a MemberInfo
6613 EventBuilder MyBuilder;
6616 // We "catch" and wrap these methods
6618 MethodInfo raise, remove, add;
6620 EventAttributes attributes;
6621 Type declaring_type, reflected_type, event_type;
6626 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6628 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6630 // And now store the values in our own fields.
6632 declaring_type = type_builder;
6634 reflected_type = type_builder;
6636 attributes = event_attr;
6639 this.event_type = event_type;
6643 // Methods that you have to override. Note that you only need
6644 // to "implement" the variants that take the argument (those are
6645 // the "abstract" methods, the others (GetAddMethod()) are
6648 public override MethodInfo GetAddMethod (bool nonPublic)
6653 public override MethodInfo GetRemoveMethod (bool nonPublic)
6658 public override MethodInfo GetRaiseMethod (bool nonPublic)
6664 // These methods make "MyEventInfo" look like a Builder
6666 public void SetRaiseMethod (MethodBuilder raiseMethod)
6668 raise = raiseMethod;
6669 MyBuilder.SetRaiseMethod (raiseMethod);
6672 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6674 remove = removeMethod;
6675 MyBuilder.SetRemoveOnMethod (removeMethod);
6678 public void SetAddOnMethod (MethodBuilder addMethod)
6681 MyBuilder.SetAddOnMethod (addMethod);
6684 public void SetCustomAttribute (CustomAttributeBuilder cb)
6686 MyBuilder.SetCustomAttribute (cb);
6689 public override object [] GetCustomAttributes (bool inherit)
6691 // FIXME : There's nothing which can be seemingly done here because
6692 // we have no way of getting at the custom attribute objects of the
6697 public override object [] GetCustomAttributes (Type t, bool inherit)
6699 // FIXME : Same here !
6703 public override bool IsDefined (Type t, bool b)
6708 public override EventAttributes Attributes {
6714 public override string Name {
6720 public override Type DeclaringType {
6722 return declaring_type;
6726 public override Type ReflectedType {
6728 return reflected_type;
6732 public Type EventType {
6738 public void SetUsed ()
6740 if (my_event != null)
6741 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6746 /// For case when event is declared like property (with add and remove accessors).
6748 public class EventProperty: Event {
6750 static string[] attribute_targets = new string [] { "event", "property" };
6752 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6753 bool is_iface, MemberName name, Object init,
6754 Attributes attrs, Accessor add, Accessor remove,
6756 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6758 Add = new AddDelegateMethod (this, add);
6759 Remove = new RemoveDelegateMethod (this, remove);
6761 // For this event syntax we don't report error CS0067
6762 // because it is hard to do it.
6766 public override string[] ValidAttributeTargets {
6768 return attribute_targets;
6774 /// Event is declared like field.
6776 public class EventField: Event {
6778 static string[] attribute_targets = new string [] { "event", "field", "method" };
6779 static string[] attribute_targets_interface = new string[] { "event", "method" };
6781 public EventField (TypeContainer parent, Expression type, int mod_flags,
6782 bool is_iface, MemberName name, Object init,
6783 Attributes attrs, Location loc)
6784 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6786 Add = new AddDelegateMethod (this);
6787 Remove = new RemoveDelegateMethod (this);
6790 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6792 if (a.Target == AttributeTargets.Field) {
6793 FieldBuilder.SetCustomAttribute (cb);
6797 if (a.Target == AttributeTargets.Method) {
6798 Add.ApplyAttributeBuilder (a, cb);
6799 Remove.ApplyAttributeBuilder (a, cb);
6803 base.ApplyAttributeBuilder (a, cb);
6806 public override string[] ValidAttributeTargets {
6808 return IsInterface ? attribute_targets_interface : attribute_targets;
6813 public abstract class Event : FieldBase {
6815 protected sealed class AddDelegateMethod: DelegateMethod
6818 public AddDelegateMethod (Event method):
6819 base (method, "add_")
6823 public AddDelegateMethod (Event method, Accessor accessor):
6824 base (method, accessor, "add_")
6828 protected override MethodInfo DelegateMethodInfo {
6830 return TypeManager.delegate_combine_delegate_delegate;
6836 protected sealed class RemoveDelegateMethod: DelegateMethod
6838 public RemoveDelegateMethod (Event method):
6839 base (method, "remove_")
6843 public RemoveDelegateMethod (Event method, Accessor accessor):
6844 base (method, accessor, "remove_")
6848 protected override MethodInfo DelegateMethodInfo {
6850 return TypeManager.delegate_remove_delegate_delegate;
6856 public abstract class DelegateMethod: AbstractPropertyEventMethod
6858 protected readonly Event method;
6859 ImplicitParameter param_attr;
6861 static string[] attribute_targets = new string [] { "method", "param", "return" };
6863 public DelegateMethod (Event method, string prefix)
6864 : base (method, prefix)
6866 this.method = method;
6869 public DelegateMethod (Event method, Accessor accessor, string prefix)
6870 : base (method, accessor, prefix)
6872 this.method = method;
6875 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6877 if (a.Target == AttributeTargets.Parameter) {
6878 if (param_attr == null)
6879 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6881 param_attr.ApplyAttributeBuilder (a, cb);
6885 base.ApplyAttributeBuilder (a, cb);
6888 public override AttributeTargets AttributeTargets {
6890 return AttributeTargets.Method;
6894 public override bool IsClsCompliaceRequired(DeclSpace ds)
6896 return method.IsClsCompliaceRequired (ds);
6899 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6901 method_data = new MethodData (method, ip, method.ModFlags,
6902 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6904 if (!method_data.Define (container))
6907 MethodBuilder mb = method_data.MethodBuilder;
6908 mb.DefineParameter (1, ParameterAttributes.None, "value");
6913 public override void Emit (TypeContainer tc)
6915 if (block != null) {
6920 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6921 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6923 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6924 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6925 ig.Emit (OpCodes.Ldsfld, field_info);
6926 ig.Emit (OpCodes.Ldarg_0);
6927 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6928 ig.Emit (OpCodes.Castclass, method.MemberType);
6929 ig.Emit (OpCodes.Stsfld, field_info);
6931 ig.Emit (OpCodes.Ldarg_0);
6932 ig.Emit (OpCodes.Ldarg_0);
6933 ig.Emit (OpCodes.Ldfld, field_info);
6934 ig.Emit (OpCodes.Ldarg_1);
6935 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6936 ig.Emit (OpCodes.Castclass, method.MemberType);
6937 ig.Emit (OpCodes.Stfld, field_info);
6939 ig.Emit (OpCodes.Ret);
6942 protected abstract MethodInfo DelegateMethodInfo { get; }
6944 public override Type[] ParameterTypes {
6946 return new Type[] { method.MemberType };
6950 public override Type ReturnType {
6952 return TypeManager.void_type;
6956 public override EmitContext CreateEmitContext (TypeContainer tc,
6959 return new EmitContext (
6960 tc, method.Parent, Location, ig, ReturnType,
6961 method.ModFlags, false);
6964 public override string GetSignatureForError (TypeContainer tc)
6966 return String.Concat (tc.Name, '.', method.Name);
6969 public override ObsoleteAttribute GetObsoleteAttribute ()
6971 return method.GetObsoleteAttribute (method.Parent);
6974 public override string[] ValidAttributeTargets {
6976 return attribute_targets;
6982 const int AllowedModifiers =
6985 Modifiers.PROTECTED |
6986 Modifiers.INTERNAL |
6991 Modifiers.OVERRIDE |
6995 const int AllowedInterfaceModifiers =
6998 public DelegateMethod Add, Remove;
6999 public MyEventBuilder EventBuilder;
7000 public MethodBuilder AddBuilder, RemoveBuilder;
7002 MethodData AddData, RemoveData;
7004 public Event (TypeContainer parent, Expression type, int mod_flags,
7005 bool is_iface, MemberName name, Object init, Attributes attrs,
7007 : base (parent, type, mod_flags,
7008 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7009 name, init, attrs, loc)
7011 IsInterface = is_iface;
7014 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7016 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7017 a.Error_InvalidSecurityParent ();
7021 EventBuilder.SetCustomAttribute (cb);
7024 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7026 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7029 public override AttributeTargets AttributeTargets {
7031 return AttributeTargets.Event;
7035 public override bool Define ()
7037 EventAttributes e_attr;
7038 e_attr = EventAttributes.None;
7040 if (!DoDefineBase ())
7043 if (!DoDefine (Parent))
7046 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
7047 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
7048 "': abstract event can not have an initializer");
7052 if (!TypeManager.IsDelegateType (MemberType)) {
7053 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
7054 "' : event must be of a delegate type");
7058 EmitContext ec = Parent.EmitContext;
7060 throw new InternalErrorException ("Event.Define called too early?");
7061 bool old_unsafe = ec.InUnsafe;
7062 ec.InUnsafe = InUnsafe;
7064 Parameter [] parms = new Parameter [1];
7065 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
7066 Parameters parameters = new Parameters (parms, null, Location);
7067 Type [] types = parameters.GetParameterInfo (ec);
7068 InternalParameters ip = new InternalParameters (types, parameters);
7070 ec.InUnsafe = old_unsafe;
7076 // Now define the accessors
7079 AddBuilder = Add.Define (Parent, ip);
7080 if (AddBuilder == null)
7083 RemoveBuilder = Remove.Define (Parent, ip);
7084 if (RemoveBuilder == null)
7087 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7089 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7090 FieldBuilder = Parent.TypeBuilder.DefineField (
7092 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7093 TypeManager.RegisterPrivateFieldOfEvent (
7094 (EventInfo) EventBuilder, FieldBuilder);
7095 TypeManager.RegisterFieldBase (FieldBuilder, this);
7098 EventBuilder.SetAddOnMethod (AddBuilder);
7099 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7101 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7105 protected override bool CheckBase ()
7107 if (!base.CheckBase ())
7110 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7111 if (!(conflict_symbol is EventInfo)) {
7112 Report.SymbolRelatedToPreviousError (conflict_symbol);
7113 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
7121 public override void Emit ()
7123 if (OptAttributes != null) {
7124 EmitContext ec = new EmitContext (
7125 Parent, Location, null, MemberType, ModFlags);
7126 OptAttributes.Emit (ec, this);
7131 Remove.Emit (Parent);
7137 public override string GetSignatureForError ()
7139 if (EventBuilder == null)
7140 return base.GetSignatureForError (Parent);
7142 return TypeManager.GetFullNameSignature (EventBuilder);
7146 // Represents header string for documentation comment.
7148 public override string DocCommentHeader {
7149 get { return "E:"; }
7154 public class Indexer : PropertyBase {
7156 class GetIndexerMethod: GetMethod
7158 public GetIndexerMethod (MethodCore method):
7163 public GetIndexerMethod (MethodCore method, Accessor accessor):
7164 base (method, accessor)
7168 public override Type[] ParameterTypes {
7170 return method.ParameterTypes;
7175 class SetIndexerMethod: SetMethod
7177 readonly Parameters parameters;
7179 public SetIndexerMethod (MethodCore method):
7184 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7185 base (method, accessor)
7187 this.parameters = parameters;
7190 public override Type[] ParameterTypes {
7192 int top = method.ParameterTypes.Length;
7193 Type [] set_pars = new Type [top + 1];
7194 method.ParameterTypes.CopyTo (set_pars, 0);
7195 set_pars [top] = method.MemberType;
7200 protected override InternalParameters GetParameterInfo (EmitContext ec)
7202 Parameter [] fixed_parms = parameters.FixedParameters;
7204 if (fixed_parms == null){
7205 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7206 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7207 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7209 // Here is the problem: the `value' parameter has
7210 // to come *after* the array parameter in the declaration
7212 // X (object [] x, Type value)
7215 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7216 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7220 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7222 fixed_parms.CopyTo (tmp, 0);
7223 tmp [fixed_parms.Length] = new Parameter (
7224 method.Type, "value", Parameter.Modifier.NONE, null);
7226 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7227 Type [] types = set_formal_params.GetParameterInfo (ec);
7229 return new InternalParameters (types, set_formal_params);
7233 const int AllowedModifiers =
7236 Modifiers.PROTECTED |
7237 Modifiers.INTERNAL |
7241 Modifiers.OVERRIDE |
7246 const int AllowedInterfaceModifiers =
7250 // Are we implementing an interface ?
7252 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7253 bool is_iface, Parameters parameters, Attributes attrs,
7254 Accessor get_block, Accessor set_block, Location loc)
7255 : base (parent, type, mod,
7256 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7257 is_iface, name, parameters, attrs, loc)
7259 if (get_block == null)
7260 Get = new GetIndexerMethod (this);
7262 Get = new GetIndexerMethod (this, get_block);
7264 if (set_block == null)
7265 Set = new SetIndexerMethod (this);
7267 Set = new SetIndexerMethod (this, parameters, set_block);
7270 public override bool Define ()
7272 PropertyAttributes prop_attr =
7273 PropertyAttributes.RTSpecialName |
7274 PropertyAttributes.SpecialName;
7276 if (!DoDefineBase ())
7279 if (!base.Define ())
7282 if (MemberType == TypeManager.void_type) {
7283 Report.Error (620, Location, "Indexers cannot have void type");
7287 if (OptAttributes != null) {
7288 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7289 if (indexer_attr != null) {
7290 // Remove the attribute from the list because it is not emitted
7291 OptAttributes.Attrs.Remove (indexer_attr);
7293 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7295 if (IsExplicitImpl) {
7296 Report.Error (415, indexer_attr.Location,
7297 "The 'IndexerName' attribute is valid only on an" +
7298 "indexer that is not an explicit interface member declaration");
7302 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7303 Report.Error (609, indexer_attr.Location,
7304 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7308 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7309 Report.Error (633, indexer_attr.Location,
7310 "The argument to the 'IndexerName' attribute must be a valid identifier");
7314 UpdateMemberName ();
7318 if (InterfaceType != null) {
7319 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7320 if (base_IndexerName != Name)
7321 ShortName = base_IndexerName;
7322 UpdateMemberName ();
7325 if (!Parent.AddToMemberContainer (this) ||
7326 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7332 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7334 GetBuilder = Get.Define (Parent);
7335 if (GetBuilder == null)
7340 SetBuilder = Set.Define (Parent);
7341 if (SetBuilder == null)
7346 // Now name the parameters
7348 Parameter [] p = Parameters.FixedParameters;
7350 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7351 Report.Error (631, Location, "ref and out are not valid in this context");
7357 for (i = 0; i < p.Length; ++i) {
7359 GetBuilder.DefineParameter (
7360 i + 1, p [i].Attributes, p [i].Name);
7363 SetBuilder.DefineParameter (
7364 i + 1, p [i].Attributes, p [i].Name);
7368 SetBuilder.DefineParameter (
7369 i + 1, ParameterAttributes.None, "value");
7371 if (i != ParameterTypes.Length) {
7372 Parameter array_param = Parameters.ArrayParameter;
7374 SetBuilder.DefineParameter (
7375 i + 1, array_param.Attributes, array_param.Name);
7379 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7380 Name, prop_attr, MemberType, ParameterTypes);
7383 PropertyBuilder.SetGetMethod (GetBuilder);
7386 PropertyBuilder.SetSetMethod (SetBuilder);
7388 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7393 public override string GetSignatureForError ()
7395 if (PropertyBuilder == null)
7396 return GetSignatureForError (Parent);
7398 return TypeManager.CSharpSignature (PropertyBuilder, true);
7401 public override string GetSignatureForError(TypeContainer tc)
7403 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7406 public override bool MarkForDuplicationCheck ()
7408 caching_flags |= Flags.TestMethodDuplication;
7414 public class Operator : MethodCore, IIteratorContainer {
7416 const int AllowedModifiers =
7422 public enum OpType : byte {
7432 // Unary and Binary operators
7455 // Implicit and Explicit
7460 public readonly OpType OperatorType;
7461 public MethodBuilder OperatorMethodBuilder;
7463 public Method OperatorMethod;
7465 static string[] attribute_targets = new string [] { "method", "return" };
7467 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7468 int mod_flags, Parameters parameters,
7469 ToplevelBlock block, Attributes attrs, Location loc)
7470 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7471 new MemberName ("op_" + type), attrs, parameters, loc)
7473 OperatorType = type;
7477 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7479 OperatorMethod.ApplyAttributeBuilder (a, cb);
7482 public override AttributeTargets AttributeTargets {
7484 return AttributeTargets.Method;
7488 protected override bool CheckGenericOverride (MethodInfo method, string name)
7493 protected override bool CheckForDuplications()
7495 ArrayList ar = Parent.Operators;
7497 int arLen = ar.Count;
7499 for (int i = 0; i < arLen; i++) {
7500 Operator o = (Operator) ar [i];
7501 if (IsDuplicateImplementation (o))
7506 ar = Parent.Methods;
7508 int arLen = ar.Count;
7510 for (int i = 0; i < arLen; i++) {
7511 Method m = (Method) ar [i];
7512 if (IsDuplicateImplementation (m))
7520 public override bool Define ()
7522 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7523 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7524 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7531 if (MemberType == TypeManager.void_type) {
7532 Report.Error (590, Location, "User-defined operators cannot return void");
7536 OperatorMethod = new Method (
7537 Parent, null, Type, ModFlags, false, MemberName,
7538 Parameters, OptAttributes, Location);
7540 OperatorMethod.Block = Block;
7541 OperatorMethod.IsOperator = true;
7542 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7543 OperatorMethod.Define ();
7545 if (OperatorMethod.MethodBuilder == null)
7548 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7550 parameter_types = OperatorMethod.ParameterTypes;
7551 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7552 Type return_type = OperatorMethod.ReturnType;
7553 Type first_arg_type = parameter_types [0];
7558 // Rules for conversion operators
7560 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7561 if (first_arg_type == return_type && first_arg_type == declaring_type){
7564 "User-defined conversion cannot take an object of the " +
7565 "enclosing type and convert to an object of the enclosing" +
7570 if (first_arg_type != declaring_type && return_type != declaring_type){
7573 "User-defined conversion must convert to or from the " +
7578 if (first_arg_type == TypeManager.object_type ||
7579 return_type == TypeManager.object_type){
7582 "User-defined conversion cannot convert to or from " +
7587 if (first_arg_type.IsInterface || return_type.IsInterface){
7590 "User-defined conversion cannot convert to or from an " +
7595 if (first_arg_type.IsSubclassOf (return_type)
7596 || return_type.IsSubclassOf (first_arg_type)){
7597 if (declaring_type.IsSubclassOf (return_type)) {
7598 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7601 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7604 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7605 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7606 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");
7609 } else if (Parameters.FixedParameters.Length == 1) {
7610 // Checks for Unary operators
7612 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7613 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7614 Report.Error (448, Location,
7615 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7618 if (first_arg_type != declaring_type){
7620 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7625 if (first_arg_type != declaring_type){
7628 "The parameter of a unary operator must be the " +
7633 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7634 if (return_type != TypeManager.bool_type){
7637 "The return type of operator True or False " +
7644 // Checks for Binary operators
7646 if (first_arg_type != declaring_type &&
7647 parameter_types [1] != declaring_type){
7650 "One of the parameters of a binary operator must " +
7651 "be the containing type");
7659 public override void Emit ()
7662 // abstract or extern methods have no bodies
7664 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7667 OperatorMethod.Emit ();
7671 // Operator cannot be override
7672 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7677 public static string GetName (OpType ot)
7680 case OpType.LogicalNot:
7682 case OpType.OnesComplement:
7684 case OpType.Increment:
7686 case OpType.Decrement:
7692 case OpType.Addition:
7694 case OpType.Subtraction:
7696 case OpType.UnaryPlus:
7698 case OpType.UnaryNegation:
7700 case OpType.Multiply:
7702 case OpType.Division:
7704 case OpType.Modulus:
7706 case OpType.BitwiseAnd:
7708 case OpType.BitwiseOr:
7710 case OpType.ExclusiveOr:
7712 case OpType.LeftShift:
7714 case OpType.RightShift:
7716 case OpType.Equality:
7718 case OpType.Inequality:
7720 case OpType.GreaterThan:
7722 case OpType.LessThan:
7724 case OpType.GreaterThanOrEqual:
7726 case OpType.LessThanOrEqual:
7728 case OpType.Implicit:
7730 case OpType.Explicit:
7736 public override string GetSignatureForError (TypeContainer tc)
7738 StringBuilder sb = new StringBuilder ();
7739 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7740 Parameters.FixedParameters [0].GetSignatureForError ());
7742 if (Parameters.FixedParameters.Length > 1) {
7744 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7747 return sb.ToString ();
7750 public override string GetSignatureForError ()
7755 public override bool MarkForDuplicationCheck ()
7757 caching_flags |= Flags.TestMethodDuplication;
7761 public override string ToString ()
7763 if (OperatorMethod == null)
7766 Type return_type = OperatorMethod.ReturnType;
7767 Type [] param_types = OperatorMethod.ParameterTypes;
7769 if (Parameters.FixedParameters.Length == 1)
7770 return String.Format (
7771 "{0} operator {1}({2})",
7772 TypeManager.CSharpName (return_type),
7773 GetName (OperatorType),
7776 return String.Format (
7777 "{0} operator {1}({2}, {3})",
7778 TypeManager.CSharpName (return_type),
7779 GetName (OperatorType),
7780 param_types [0], param_types [1]);
7783 public override string[] ValidAttributeTargets {
7785 return attribute_targets;
7789 public void SetYields ()
7791 ModFlags |= Modifiers.METHOD_YIELDS;
7796 // This is used to compare method signatures
7798 struct MethodSignature {
7800 public Type RetType;
7801 public Type [] Parameters;
7804 /// This delegate is used to extract methods which have the
7805 /// same signature as the argument
7807 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7809 public MethodSignature (string name, Type ret_type, Type [] parameters)
7814 if (parameters == null)
7815 Parameters = TypeManager.NoTypes;
7817 Parameters = parameters;
7820 public override string ToString ()
7823 if (Parameters.Length != 0){
7824 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7825 for (int i = 0; i < Parameters.Length; i++){
7826 sb.Append (Parameters [i]);
7827 if (i+1 < Parameters.Length)
7830 pars = sb.ToString ();
7833 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7836 public override int GetHashCode ()
7838 return Name.GetHashCode ();
7841 public override bool Equals (Object o)
7843 MethodSignature other = (MethodSignature) o;
7845 if (other.Name != Name)
7848 if (other.RetType != RetType)
7851 if (Parameters == null){
7852 if (other.Parameters == null)
7857 if (other.Parameters == null)
7860 int c = Parameters.Length;
7861 if (other.Parameters.Length != c)
7864 for (int i = 0; i < c; i++)
7865 if (other.Parameters [i] != Parameters [i])
7871 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7873 MethodSignature sig = (MethodSignature) filter_criteria;
7875 if (m.Name != sig.Name)
7879 MethodInfo mi = m as MethodInfo;
7880 PropertyInfo pi = m as PropertyInfo;
7883 ReturnType = mi.ReturnType;
7884 else if (pi != null)
7885 ReturnType = pi.PropertyType;
7890 // we use sig.RetType == null to mean `do not check the
7891 // method return value.
7893 if (sig.RetType != null)
7894 if (ReturnType != sig.RetType)
7899 args = TypeManager.GetArgumentTypes (mi);
7901 args = TypeManager.GetArgumentTypes (pi);
7902 Type [] sigp = sig.Parameters;
7904 if (args.Length != sigp.Length)
7907 for (int i = args.Length; i > 0; ){
7909 if (args [i] != sigp [i])