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.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 namespace Mono.CSharp {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
79 public virtual void Emit ()
81 foreach (MemberCore mc in this)
86 public class MethodArrayList: MemberCoreArrayList
94 CachedMethods cached_method;
95 TypeContainer container;
97 public MethodArrayList (TypeContainer container)
99 this.container = container;
103 /// Method container contains Equals method
105 public bool HasEquals {
107 cached_method |= CachedMethods.Equals;
111 return (cached_method & CachedMethods.Equals) != 0;
116 /// Method container contains GetHashCode method
118 public bool HasGetHashCode {
120 cached_method |= CachedMethods.GetHashCode;
124 return (cached_method & CachedMethods.GetHashCode) != 0;
128 public override void DefineContainerMembers ()
130 base.DefineContainerMembers ();
132 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
133 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
139 public sealed class IndexerArrayList: MemberCoreArrayList
142 /// The indexer name for this container
144 public string IndexerName = DefaultIndexerName;
146 bool seen_normal_indexers = false;
148 TypeContainer container;
150 public IndexerArrayList (TypeContainer container)
152 this.container = container;
156 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
157 /// class is consistent. Either it is `Item' or it is the name defined by all the
158 /// indexers with the `IndexerName' attribute.
160 /// Turns out that the IndexerNameAttribute is applied to each indexer,
161 /// but it is never emitted, instead a DefaultMember attribute is attached
164 public override void DefineContainerMembers()
166 base.DefineContainerMembers ();
168 string class_indexer_name = null;
171 // If there's both an explicit and an implicit interface implementation, the
172 // explicit one actually implements the interface while the other one is just
173 // a normal indexer. See bug #37714.
176 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
177 foreach (Indexer i in this) {
178 if (i.InterfaceType != null) {
179 if (seen_normal_indexers)
180 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
184 seen_normal_indexers = true;
186 if (class_indexer_name == null) {
187 class_indexer_name = i.ShortName;
191 if (i.ShortName != class_indexer_name)
192 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");
195 if (class_indexer_name != null)
196 IndexerName = class_indexer_name;
199 public override void Emit ()
203 if (!seen_normal_indexers)
206 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
207 container.TypeBuilder.SetCustomAttribute (cb);
211 public class OperatorArrayList: MemberCoreArrayList
213 TypeContainer container;
215 public OperatorArrayList (TypeContainer container)
217 this.container = container;
221 // Operator pair checking
226 public Type ret_type;
227 public Type type1, type2;
229 public Operator.OpType ot;
231 public OperatorEntry (int f, Operator o)
235 ret_type = o.OperatorMethod.ReturnType;
236 Type [] pt = o.OperatorMethod.ParameterTypes;
243 public override int GetHashCode ()
245 return ret_type.GetHashCode ();
248 public override bool Equals (object o)
250 OperatorEntry other = (OperatorEntry) o;
252 if (other.ret_type != ret_type)
254 if (other.type1 != type1)
256 if (other.type2 != type2)
263 // Checks that some operators come in pairs:
269 // They are matched based on the return type and the argument types
271 void CheckPairedOperators ()
273 Hashtable pairs = new Hashtable (null, null);
274 Operator true_op = null;
275 Operator false_op = null;
276 bool has_equality_or_inequality = false;
278 // Register all the operators we care about.
279 foreach (Operator op in this){
282 // Skip erroneous code.
283 if (op.OperatorMethod == null)
286 switch (op.OperatorType){
287 case Operator.OpType.Equality:
289 has_equality_or_inequality = true;
291 case Operator.OpType.Inequality:
293 has_equality_or_inequality = true;
296 case Operator.OpType.True:
299 case Operator.OpType.False:
303 case Operator.OpType.GreaterThan:
305 case Operator.OpType.LessThan:
308 case Operator.OpType.GreaterThanOrEqual:
310 case Operator.OpType.LessThanOrEqual:
316 OperatorEntry oe = new OperatorEntry (reg, op);
318 object o = pairs [oe];
322 oe = (OperatorEntry) o;
327 if (true_op != null){
328 if (false_op == null)
329 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
330 } else if (false_op != null)
331 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
334 // Look for the mistakes.
336 foreach (DictionaryEntry de in pairs){
337 OperatorEntry oe = (OperatorEntry) de.Key;
344 case Operator.OpType.Equality:
347 case Operator.OpType.Inequality:
350 case Operator.OpType.GreaterThan:
353 case Operator.OpType.LessThan:
356 case Operator.OpType.GreaterThanOrEqual:
359 case Operator.OpType.LessThanOrEqual:
363 Report.Error (216, oe.op.Location,
364 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
367 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
368 if (container.Methods == null || !container.Methods.HasEquals)
369 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
371 if (container.Methods == null || !container.Methods.HasGetHashCode)
372 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
376 public override void DefineContainerMembers ()
378 base.DefineContainerMembers ();
379 CheckPairedOperators ();
384 // Whether this is a struct, class or interface
385 public readonly Kind Kind;
387 // Holds a list of classes and structures
390 // Holds the list of properties
391 MemberCoreArrayList properties;
393 // Holds the list of enumerations
394 MemberCoreArrayList enums;
396 // Holds the list of delegates
397 MemberCoreArrayList delegates;
399 // Holds the list of constructors
400 protected MemberCoreArrayList instance_constructors;
402 // Holds the list of fields
403 MemberCoreArrayList fields;
405 // Holds a list of fields that have initializers
406 protected ArrayList initialized_fields;
408 // Holds a list of static fields that have initializers
409 protected ArrayList initialized_static_fields;
411 // Holds the list of constants
412 MemberCoreArrayList constants;
415 MemberCoreArrayList interfaces;
417 // Holds the methods.
418 MethodArrayList methods;
421 protected MemberCoreArrayList events;
423 // Holds the indexers
424 IndexerArrayList indexers;
426 // Holds the operators
427 MemberCoreArrayList operators;
429 // Holds the iterators
432 // Holds the parts of a partial class;
436 // Pointers to the default constructor and the default static constructor
438 protected Constructor default_constructor;
439 protected Constructor default_static_constructor;
442 // Whether we have at least one non-static field
444 bool have_nonstatic_fields = false;
447 // This one is computed after we can distinguish interfaces
448 // from classes from the arraylist `type_bases'
450 string base_class_name;
453 ArrayList type_bases;
455 bool members_defined;
456 bool members_defined_ok;
458 // The interfaces we implement.
459 protected Type [] ifaces;
460 protected Type ptype;
462 // The base member cache and our member cache
463 MemberCache base_cache;
464 MemberCache member_cache;
466 public const string DefaultIndexerName = "Item";
468 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
469 Attributes attrs, Kind kind, Location l)
470 : base (ns, parent, name, attrs, l)
472 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
473 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
477 types = new ArrayList ();
479 base_class_name = null;
482 public bool AddToMemberContainer (MemberCore symbol)
484 return AddToContainer (symbol, symbol.Name);
487 bool AddToTypeContainer (DeclSpace ds)
489 // Parent == null ==> this == RootContext.Tree.Types
490 return AddToContainer (ds, (Parent == null) ? ds.Name : ds.Basename);
493 public void AddConstant (Const constant)
495 if (!AddToMemberContainer (constant))
498 if (constants == null)
499 constants = new MemberCoreArrayList ();
501 constants.Add (constant);
504 public void AddEnum (Mono.CSharp.Enum e)
506 if (!AddToTypeContainer (e))
510 enums = new MemberCoreArrayList ();
515 public void AddClassOrStruct (TypeContainer c)
517 if (!AddToTypeContainer (c))
523 public void AddDelegate (Delegate d)
525 if (!AddToTypeContainer (d))
528 if (delegates == null)
529 delegates = new MemberCoreArrayList ();
534 public void AddMethod (Method method)
536 if (!AddToMemberContainer (method))
540 methods = new MethodArrayList (this);
542 if (method.MemberName.Left != null)
543 methods.Insert (0, method);
545 methods.Add (method);
548 public void AddConstructor (Constructor c)
550 if (c.Name != Basename) {
551 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
554 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
557 if (default_static_constructor != null) {
558 Report.SymbolRelatedToPreviousError (default_static_constructor);
559 Report.Error (111, c.Location, Error111, Name, c.Name);
563 default_static_constructor = c;
566 if (default_constructor != null) {
567 Report.SymbolRelatedToPreviousError (default_constructor);
568 Report.Error (111, c.Location, Error111, c.Location, Name, c.Name);
571 default_constructor = c;
574 if (instance_constructors == null)
575 instance_constructors = new MemberCoreArrayList ();
577 instance_constructors.Add (c);
581 internal static string Error111 {
583 return "Type '{0}' already defines a member called '{1}' with the same parameter types";
587 public void AddInterface (TypeContainer iface)
589 if (!AddToTypeContainer (iface))
592 if (interfaces == null) {
593 interfaces = new MemberCoreArrayList ();
596 interfaces.Add (iface);
599 public void AddField (FieldMember field)
601 if (!AddToMemberContainer (field))
605 fields = new MemberCoreArrayList ();
609 if (field.HasInitializer){
610 if ((field.ModFlags & Modifiers.STATIC) != 0){
611 if (initialized_static_fields == null)
612 initialized_static_fields = new ArrayList ();
614 initialized_static_fields.Add (field);
616 if (initialized_fields == null)
617 initialized_fields = new ArrayList ();
619 initialized_fields.Add (field);
623 if ((field.ModFlags & Modifiers.STATIC) == 0)
624 have_nonstatic_fields = true;
627 public void AddProperty (Property prop)
629 if (!AddToMemberContainer (prop) ||
630 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
633 if (properties == null)
634 properties = new MemberCoreArrayList ();
636 if (prop.MemberName.Left != null)
637 properties.Insert (0, prop);
639 properties.Add (prop);
642 public void AddEvent (Event e)
644 if (!AddToMemberContainer (e))
647 if (e is EventProperty) {
648 if (!AddToMemberContainer (e.Add))
651 if (!AddToMemberContainer (e.Remove))
656 events = new MemberCoreArrayList ();
663 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
665 public void AddIndexer (Indexer i)
667 if (indexers == null)
668 indexers = new IndexerArrayList (this);
670 if (i.IsExplicitImpl)
671 indexers.Insert (0, i);
676 public void AddOperator (Operator op)
678 if (!AddToMemberContainer (op))
681 if (operators == null)
682 operators = new OperatorArrayList (this);
687 public void AddIterator (Iterator i)
689 if (iterators == null)
690 iterators = new ArrayList ();
695 public void AddType (TypeContainer tc)
700 public void AddPart (ClassPart part)
703 parts = new ArrayList ();
708 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
710 if (a.Type == TypeManager.default_member_type) {
711 if (Indexers != null) {
712 Report.Error (646, a.Location,
713 "Cannot specify the DefaultMember attribute on" +
714 " a type containing an indexer");
719 base.ApplyAttributeBuilder (a, cb);
722 public override AttributeTargets AttributeTargets {
726 return AttributeTargets.Class;
728 return AttributeTargets.Struct;
730 return AttributeTargets.Interface;
732 throw new NotSupportedException ();
737 public ArrayList Types {
743 public MethodArrayList Methods {
749 public ArrayList Constants {
755 public ArrayList Interfaces {
761 public ArrayList Iterators {
769 return base_class_name;
773 public ArrayList Bases {
783 public ArrayList Fields {
789 public ArrayList InstanceConstructors {
791 return instance_constructors;
795 public ArrayList Properties {
801 public ArrayList Events {
807 public ArrayList Enums {
813 public ArrayList Indexers {
819 public ArrayList Operators {
825 public ArrayList Delegates {
831 public ArrayList Parts {
837 public virtual TypeAttributes TypeAttr {
839 return Modifiers.TypeAttr (ModFlags, this);
843 public string IndexerName {
845 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
850 // Emits the instance field initializers
852 public virtual bool EmitFieldInitializers (EmitContext ec)
855 Expression instance_expr;
858 fields = initialized_static_fields;
859 instance_expr = null;
861 fields = initialized_fields;
862 instance_expr = new This (Location.Null).Resolve (ec);
868 foreach (Field f in fields){
869 Expression e = f.GetInitializerExpression (ec);
873 Location l = f.Location;
874 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
875 fe.InstanceExpression = instance_expr;
876 ExpressionStatement a = new Assign (fe, e, l);
878 a = a.ResolveStatement (ec);
882 if (RootContext.Optimize) {
883 Constant c = e as Constant;
885 if (c.IsDefaultValue)
890 a.EmitStatement (ec);
897 // Defines the default constructors
899 protected void DefineDefaultConstructor (bool is_static)
903 // The default constructor is public
904 // If the class is abstract, the default constructor is protected
905 // The default static constructor is private
907 int mods = Modifiers.PUBLIC;
909 mods = Modifiers.STATIC | Modifiers.PRIVATE;
910 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
911 mods = Modifiers.PROTECTED;
913 TypeContainer constructor_parent = this;
915 constructor_parent = (TypeContainer) Parts [0];
917 c = new Constructor (constructor_parent, Basename, mods,
918 Parameters.EmptyReadOnlyParameters,
919 new ConstructorBaseInitializer (
920 null, Parameters.EmptyReadOnlyParameters,
926 c.Block = new ToplevelBlock (null, Location);
931 /// The pending methods that need to be implemented
932 // (interfaces or abstract methods)
934 public PendingImplementation Pending;
936 public abstract PendingImplementation GetPendingImplementations ();
938 TypeExpr[] GetPartialBases (out TypeExpr base_class, out bool error)
940 ArrayList ifaces = new ArrayList ();
943 Location base_loc = Location.Null;
945 foreach (ClassPart part in parts) {
946 TypeExpr new_base_class;
947 TypeExpr[] new_ifaces;
949 new_ifaces = part.GetClassBases (out new_base_class, out error);
953 if ((base_class != null) && (new_base_class != null) &&
954 !base_class.Equals (new_base_class)) {
955 Report.Error (263, part.Location,
956 "Partial declarations of `{0}' must " +
957 "not specify different base classes",
960 if (!Location.IsNull (base_loc))
961 Report.LocationOfPreviousError (base_loc);
967 if ((base_class == null) && (new_base_class != null)) {
968 base_class = new_base_class;
969 base_loc = part.Location;
972 if (new_ifaces == null)
975 foreach (TypeExpr iface in new_ifaces) {
977 foreach (TypeExpr old_iface in ifaces) {
978 if (old_iface.Equals (iface)) {
991 TypeExpr[] retval = new TypeExpr [ifaces.Count];
992 ifaces.CopyTo (retval, 0);
996 TypeExpr[] GetNormalBases (out TypeExpr base_class, out bool error)
1000 int count = Bases.Count;
1001 int start = 0, i, j;
1003 if (Kind == Kind.Class){
1004 TypeExpr name = ResolveBaseTypeExpr (
1005 (Expression) Bases [0], false, Location);
1012 if (!name.IsInterface) {
1013 // base_class could be a class, struct, enum, delegate.
1014 // This is validated in GetClassBases.
1020 TypeExpr [] ifaces = new TypeExpr [count-start];
1022 for (i = start, j = 0; i < count; i++, j++){
1023 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1024 if (resolved == null) {
1029 ifaces [j] = resolved;
1037 /// This function computes the Base class and also the
1038 /// list of interfaces that the class or struct @c implements.
1040 /// The return value is an array (might be null) of
1041 /// interfaces implemented (as Types).
1043 /// The @base_class argument is set to the base object or null
1044 /// if this is `System.Object'.
1046 TypeExpr [] GetClassBases (out TypeExpr base_class, out bool error)
1055 ifaces = GetPartialBases (out base_class, out error);
1056 else if (Bases == null){
1060 ifaces = GetNormalBases (out base_class, out error);
1065 if ((base_class != null) && (Kind == Kind.Class)){
1067 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1068 Report.Error (1521, base_class.Location, "Invalid base type");
1073 if (base_class.IsSealed){
1075 Report.SymbolRelatedToPreviousError (base_class.Type);
1076 if (base_class.Type.IsAbstract) {
1077 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1079 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1084 if (!base_class.CanInheritFrom ()){
1085 Report.Error (644, Location,
1086 "`{0}' cannot inherit from special class `{1}'",
1087 Name, base_class.Name);
1092 if (!base_class.AsAccessible (this, ModFlags)) {
1093 Report.SymbolRelatedToPreviousError (base_class.Type);
1094 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1095 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1099 if (base_class != null)
1100 base_class_name = base_class.Name;
1105 int count = ifaces != null ? ifaces.Length : 0;
1107 for (i = 0; i < count; i++) {
1108 TypeExpr iface = (TypeExpr) ifaces [i];
1110 if (!iface.IsInterface) {
1112 if (Kind != Kind.Class) {
1113 string what = Kind == Kind.Struct ? "Struct" : "Interface";
1115 Report.Error (527, Location,
1116 "In {0} `{1}', type `{2}' is not "+
1117 "an interface", what, Name, iface.Name);
1119 else if (base_class != null)
1120 Report.Error (1721, Location,
1121 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1124 Report.Error (1722, Location,
1125 "In Class `{0}', `{1}' is not " +
1126 "an interface, a base class must be listed first", Name, iface.Name);
1131 for (int x = 0; x < i; x++) {
1132 if (iface.Equals (ifaces [x])) {
1133 Report.Error (528, Location,
1134 "`{0}' is already listed in " +
1135 "interface list", iface.Name);
1140 if ((Kind == Kind.Interface) &&
1141 !iface.AsAccessible (Parent, ModFlags)) {
1142 Report.Error (61, Location,
1143 "Inconsistent accessibility: base " +
1144 "interface `{0}' is less accessible " +
1145 "than interface `{1}'", iface.Name,
1160 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1162 public override TypeBuilder DefineType ()
1164 if (TypeBuilder != null)
1171 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
1178 TypeExpr[] iface_exprs = GetClassBases (out base_type, out error);
1182 if (base_type == null) {
1183 if (Kind == Kind.Class){
1184 if (RootContext.StdLib)
1185 base_type = TypeManager.system_object_expr;
1186 else if (Name != "System.Object")
1187 base_type = TypeManager.system_object_expr;
1188 } else if (Kind == Kind.Struct) {
1190 // If we are compiling our runtime,
1191 // and we are defining ValueType, then our
1192 // base is `System.Object'.
1194 if (!RootContext.StdLib && Name == "System.ValueType")
1195 base_type = TypeManager.system_object_expr;
1197 base_type = TypeManager.system_valuetype_expr;
1201 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1202 throw new Exception ();
1204 TypeAttributes type_attributes = TypeAttr;
1206 if (base_type != null) {
1207 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1208 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1209 ptype = base_type.ResolveType (TypeResolveEmitContext);
1210 if (ptype == null) {
1218 if (TypeManager.NamespaceClash (Name, Location)) {
1223 ModuleBuilder builder = CodeGen.Module.Builder;
1224 TypeBuilder = builder.DefineType (
1225 Name, type_attributes, ptype, null);
1228 TypeBuilder builder = Parent.TypeBuilder;
1229 if (builder == null)
1232 TypeBuilder = builder.DefineNestedType (
1233 Basename, type_attributes, ptype, null);
1236 catch (ArgumentException) {
1237 Report.RuntimeMissingSupport (Location, "static classes");
1241 if (Parts != null) {
1243 foreach (ClassPart part in Parts) {
1244 part.TypeBuilder = TypeBuilder;
1246 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1247 part.ec.ContainerType = TypeBuilder;
1251 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1252 ec.ContainerType = TypeBuilder;
1256 // Structs with no fields need to have at least one byte.
1257 // The right thing would be to set the PackingSize in a DefineType
1258 // but there are no functions that allow interfaces *and* the size to
1262 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1263 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1264 FieldAttributes.Private);
1267 // add interfaces that were not added at type creation
1268 if (iface_exprs != null) {
1269 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1270 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1271 TypeResolveEmitContext.ContainerType = TypeBuilder;
1272 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1273 if (ifaces == null) {
1278 foreach (Type itype in ifaces)
1279 TypeBuilder.AddInterfaceImplementation (itype);
1281 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1284 TypeManager.AddUserType (Name, TypeBuilder, this);
1286 if (!(this is Iterator))
1287 RootContext.RegisterOrder (this);
1289 if (!DefineNestedTypes ()) {
1298 protected virtual bool DefineNestedTypes ()
1300 if (Interfaces != null) {
1301 foreach (TypeContainer iface in Interfaces)
1302 if (iface.DefineType () == null)
1306 if (Types != null) {
1307 foreach (TypeContainer tc in Types)
1308 if (tc.DefineType () == null)
1312 if (Delegates != null) {
1313 foreach (Delegate d in Delegates)
1314 if (d.DefineType () == null)
1318 if (Enums != null) {
1319 foreach (Enum en in Enums)
1320 if (en.DefineType () == null)
1327 static void Error_KeywordNotAllowed (Location loc)
1329 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1333 /// Populates our TypeBuilder with fields and methods
1335 public override bool DefineMembers (TypeContainer container)
1337 if (members_defined)
1338 return members_defined_ok;
1340 members_defined_ok = DoDefineMembers ();
1341 members_defined = true;
1343 return members_defined_ok;
1346 bool DoDefineMembers ()
1349 if ((ModFlags & Modifiers.NEW) != 0)
1350 Error_KeywordNotAllowed (Location);
1352 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1353 if (conflict_symbol == null) {
1354 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1355 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1357 if ((ModFlags & Modifiers.NEW) == 0) {
1358 Report.SymbolRelatedToPreviousError (conflict_symbol);
1359 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1364 DefineContainerMembers (constants);
1365 DefineContainerMembers (fields);
1367 if ((Kind == Kind.Class) && !(this is ClassPart)){
1368 if ((instance_constructors == null) &&
1369 !(this is StaticClass)) {
1370 if (default_constructor == null)
1371 DefineDefaultConstructor (false);
1374 if (initialized_static_fields != null &&
1375 default_static_constructor == null)
1376 DefineDefaultConstructor (true);
1379 if (Kind == Kind.Struct){
1381 // Structs can not have initialized instance
1384 if (initialized_static_fields != null &&
1385 default_static_constructor == null)
1386 DefineDefaultConstructor (true);
1388 if (initialized_fields != null)
1389 ReportStructInitializedInstanceError ();
1392 Pending = GetPendingImplementations ();
1394 if (parts != null) {
1395 foreach (ClassPart part in parts) {
1396 if (!part.DefineMembers (this))
1402 // Constructors are not in the defined_names array
1404 DefineContainerMembers (instance_constructors);
1406 if (default_static_constructor != null)
1407 default_static_constructor.Define ();
1409 DefineContainerMembers (properties);
1410 DefineContainerMembers (events);
1411 DefineContainerMembers (indexers);
1412 DefineContainerMembers (methods);
1413 DefineContainerMembers (operators);
1414 DefineContainerMembers (enums);
1415 DefineContainerMembers (delegates);
1418 if (!(this is ClassPart))
1419 member_cache = new MemberCache (this);
1422 if (parts != null) {
1423 foreach (ClassPart part in parts)
1424 part.member_cache = member_cache;
1427 if (iterators != null) {
1428 foreach (Iterator iterator in iterators) {
1429 if (iterator.DefineType () == null)
1433 foreach (Iterator iterator in iterators) {
1434 if (!iterator.DefineMembers (this))
1442 void ReportStructInitializedInstanceError ()
1444 string n = TypeBuilder.FullName;
1446 foreach (Field f in initialized_fields){
1449 "`" + n + "." + f.Name + "': can not have " +
1450 "instance field initializers in structs");
1454 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1457 mcal.DefineContainerMembers ();
1460 public override bool Define ()
1462 if (parts != null) {
1463 foreach (ClassPart part in parts) {
1464 if (!part.Define ())
1472 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1474 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1478 /// This function is based by a delegate to the FindMembers routine
1480 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1486 /// This filter is used by FindMembers, and we just keep
1487 /// a global for the filter to `AlwaysAccept'
1489 static MemberFilter accepting_filter;
1492 static TypeContainer ()
1494 accepting_filter = new MemberFilter (AlwaysAccept);
1497 public MethodInfo[] GetMethods ()
1499 ArrayList members = new ArrayList ();
1501 DefineMembers (null);
1503 if (methods != null) {
1504 int len = methods.Count;
1505 for (int i = 0; i < len; i++) {
1506 Method m = (Method) methods [i];
1508 members.Add (m.MethodBuilder);
1512 if (operators != null) {
1513 int len = operators.Count;
1514 for (int i = 0; i < len; i++) {
1515 Operator o = (Operator) operators [i];
1517 members.Add (o.OperatorMethodBuilder);
1521 if (properties != null) {
1522 int len = properties.Count;
1523 for (int i = 0; i < len; i++) {
1524 Property p = (Property) properties [i];
1526 if (p.GetBuilder != null)
1527 members.Add (p.GetBuilder);
1528 if (p.SetBuilder != null)
1529 members.Add (p.SetBuilder);
1533 if (indexers != null) {
1534 int len = indexers.Count;
1535 for (int i = 0; i < len; i++) {
1536 Indexer ix = (Indexer) indexers [i];
1538 if (ix.GetBuilder != null)
1539 members.Add (ix.GetBuilder);
1540 if (ix.SetBuilder != null)
1541 members.Add (ix.SetBuilder);
1545 if (events != null) {
1546 int len = events.Count;
1547 for (int i = 0; i < len; i++) {
1548 Event e = (Event) events [i];
1550 if (e.AddBuilder != null)
1551 members.Add (e.AddBuilder);
1552 if (e.RemoveBuilder != null)
1553 members.Add (e.RemoveBuilder);
1557 MethodInfo[] retMethods = new MethodInfo [members.Count];
1558 members.CopyTo (retMethods, 0);
1562 // Indicated whether container has StructLayout attribute set Explicit
1563 public virtual bool HasExplicitLayout {
1569 public override Type FindNestedType (string name)
1571 ArrayList [] lists = { types, enums, delegates, interfaces };
1573 for (int j = 0; j < lists.Length; ++j) {
1574 ArrayList list = lists [j];
1578 int len = list.Count;
1579 for (int i = 0; i < len; ++i) {
1580 DeclSpace ds = (DeclSpace) list [i];
1581 if (ds.Basename == name) {
1583 return ds.TypeBuilder;
1591 private void FindMembers_NestedTypes (int modflags,
1592 BindingFlags bf, MemberFilter filter, object criteria,
1593 ref ArrayList members)
1595 ArrayList [] lists = { types, enums, delegates, interfaces };
1597 for (int j = 0; j < lists.Length; ++j) {
1598 ArrayList list = lists [j];
1602 int len = list.Count;
1603 for (int i = 0; i < len; i++) {
1604 DeclSpace ds = (DeclSpace) list [i];
1606 if ((ds.ModFlags & modflags) == 0)
1609 TypeBuilder tb = ds.TypeBuilder;
1611 if (!(criteria is string) || ds.Basename.Equals (criteria))
1612 tb = ds.DefineType ();
1615 if (tb != null && (filter (tb, criteria) == true)) {
1616 if (members == null)
1617 members = new ArrayList ();
1626 /// This method returns the members of this type just like Type.FindMembers would
1627 /// Only, we need to use this for types which are _being_ defined because MS'
1628 /// implementation can't take care of that.
1631 // FIXME: return an empty static array instead of null, that cleans up
1632 // some code and is consistent with some coding conventions I just found
1636 // Notice that in various cases we check if our field is non-null,
1637 // something that would normally mean that there was a bug elsewhere.
1639 // The problem happens while we are defining p-invoke methods, as those
1640 // will trigger a FindMembers, but this happens before things are defined
1642 // Since the whole process is a no-op, it is fine to check for null here.
1644 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1645 MemberFilter filter, object criteria)
1647 ArrayList members = null;
1650 if ((bf & BindingFlags.Public) != 0)
1651 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1653 if ((bf & BindingFlags.NonPublic) != 0)
1654 modflags |= Modifiers.PRIVATE;
1656 int static_mask = 0, static_flags = 0;
1657 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1658 case BindingFlags.Static:
1659 static_mask = static_flags = Modifiers.STATIC;
1662 case BindingFlags.Instance:
1663 static_mask = Modifiers.STATIC;
1668 static_mask = static_flags = 0;
1672 Timer.StartTimer (TimerType.TcFindMembers);
1675 filter = accepting_filter;
1677 if ((mt & MemberTypes.Field) != 0) {
1678 if (fields != null) {
1679 int len = fields.Count;
1680 for (int i = 0; i < len; i++) {
1681 FieldMember f = (FieldMember) fields [i];
1683 if ((f.ModFlags & modflags) == 0)
1685 if ((f.ModFlags & static_mask) != static_flags)
1688 FieldBuilder fb = f.FieldBuilder;
1689 if (fb != null && filter (fb, criteria) == true) {
1690 if (members == null)
1691 members = new ArrayList ();
1698 if (constants != null) {
1699 int len = constants.Count;
1700 for (int i = 0; i < len; i++) {
1701 Const con = (Const) constants [i];
1703 if ((con.ModFlags & modflags) == 0)
1705 if ((con.ModFlags & static_mask) != static_flags)
1708 FieldBuilder fb = con.FieldBuilder;
1711 fb = con.FieldBuilder;
1713 if (fb != null && filter (fb, criteria) == true) {
1714 if (members == null)
1715 members = new ArrayList ();
1723 if ((mt & MemberTypes.Method) != 0) {
1724 if (methods != null) {
1725 int len = methods.Count;
1726 for (int i = 0; i < len; i++) {
1727 Method m = (Method) methods [i];
1729 if ((m.ModFlags & modflags) == 0)
1731 if ((m.ModFlags & static_mask) != static_flags)
1734 MethodBuilder mb = m.MethodBuilder;
1736 if (mb != null && filter (mb, criteria) == true) {
1737 if (members == null)
1738 members = new ArrayList ();
1745 if (operators != null) {
1746 int len = operators.Count;
1747 for (int i = 0; i < len; i++) {
1748 Operator o = (Operator) operators [i];
1750 if ((o.ModFlags & modflags) == 0)
1752 if ((o.ModFlags & static_mask) != static_flags)
1755 MethodBuilder ob = o.OperatorMethodBuilder;
1756 if (ob != null && filter (ob, criteria) == true) {
1757 if (members == null)
1758 members = new ArrayList ();
1765 if (properties != null) {
1766 int len = properties.Count;
1767 for (int i = 0; i < len; i++) {
1768 Property p = (Property) properties [i];
1770 if ((p.ModFlags & modflags) == 0)
1772 if ((p.ModFlags & static_mask) != static_flags)
1778 if (b != null && filter (b, criteria) == true) {
1779 if (members == null)
1780 members = new ArrayList ();
1786 if (b != null && filter (b, criteria) == true) {
1787 if (members == null)
1788 members = new ArrayList ();
1795 if (indexers != null) {
1796 int len = indexers.Count;
1797 for (int i = 0; i < len; i++) {
1798 Indexer ix = (Indexer) indexers [i];
1800 if ((ix.ModFlags & modflags) == 0)
1802 if ((ix.ModFlags & static_mask) != static_flags)
1808 if (b != null && filter (b, criteria) == true) {
1809 if (members == null)
1810 members = new ArrayList ();
1816 if (b != null && filter (b, criteria) == true) {
1817 if (members == null)
1818 members = new ArrayList ();
1826 if ((mt & MemberTypes.Event) != 0) {
1827 if (events != null) {
1828 int len = events.Count;
1829 for (int i = 0; i < len; i++) {
1830 Event e = (Event) events [i];
1832 if ((e.ModFlags & modflags) == 0)
1834 if ((e.ModFlags & static_mask) != static_flags)
1837 MemberInfo eb = e.EventBuilder;
1838 if (eb != null && filter (eb, criteria) == true) {
1839 if (members == null)
1840 members = new ArrayList ();
1842 members.Add (e.EventBuilder);
1848 if ((mt & MemberTypes.Property) != 0){
1849 if (properties != null) {
1850 int len = properties.Count;
1851 for (int i = 0; i < len; i++) {
1852 Property p = (Property) properties [i];
1854 if ((p.ModFlags & modflags) == 0)
1856 if ((p.ModFlags & static_mask) != static_flags)
1859 MemberInfo pb = p.PropertyBuilder;
1860 if (pb != null && filter (pb, criteria) == true) {
1861 if (members == null)
1862 members = new ArrayList ();
1864 members.Add (p.PropertyBuilder);
1869 if (indexers != null) {
1870 int len = indexers.Count;
1871 for (int i = 0; i < len; i++) {
1872 Indexer ix = (Indexer) indexers [i];
1874 if ((ix.ModFlags & modflags) == 0)
1876 if ((ix.ModFlags & static_mask) != static_flags)
1879 MemberInfo ib = ix.PropertyBuilder;
1880 if (ib != null && filter (ib, criteria) == true) {
1881 if (members == null)
1882 members = new ArrayList ();
1884 members.Add (ix.PropertyBuilder);
1890 if ((mt & MemberTypes.NestedType) != 0)
1891 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1893 if ((mt & MemberTypes.Constructor) != 0){
1894 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1895 int len = instance_constructors.Count;
1896 for (int i = 0; i < len; i++) {
1897 Constructor c = (Constructor) instance_constructors [i];
1899 ConstructorBuilder cb = c.ConstructorBuilder;
1900 if (cb != null && filter (cb, criteria) == true) {
1901 if (members == null)
1902 members = new ArrayList ();
1909 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1910 ConstructorBuilder cb =
1911 default_static_constructor.ConstructorBuilder;
1913 if (cb != null && filter (cb, criteria) == true) {
1914 if (members == null)
1915 members = new ArrayList ();
1923 // Lookup members in base if requested.
1925 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1926 if (TypeBuilder.BaseType != null) {
1927 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1928 if (list.Count > 0) {
1929 if (members == null)
1930 members = new ArrayList ();
1932 members.AddRange (list);
1935 if (ifaces != null) {
1936 foreach (Type base_type in ifaces) {
1937 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1939 if (list.Count > 0) {
1940 if (members == null)
1941 members = new ArrayList ();
1942 members.AddRange (list);
1948 Timer.StopTimer (TimerType.TcFindMembers);
1950 if (members == null)
1951 return MemberList.Empty;
1953 return new MemberList (members);
1956 public override MemberCache MemberCache {
1958 return member_cache;
1962 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1963 MemberFilter filter, object criteria)
1965 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1968 return ds.FindMembers (mt, bf, filter, criteria);
1970 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1975 // FindMethods will look for methods not only in the type `t', but in
1976 // any interfaces implemented by the type.
1978 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1979 MemberFilter filter, object criteria)
1985 /// Emits the values for the constants
1987 public void EmitConstants ()
1989 if (constants != null)
1990 foreach (Const con in constants)
1995 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2000 foreach (MemberCore mc in al) {
2001 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2005 Report.Warning (169, mc.Location, "The private {0} '{1}' is never used", member_type, mc.GetSignatureForError ());
2010 public virtual void VerifyMembers ()
2013 // Check for internal or private fields that were never assigned
2015 if (RootContext.WarningLevel >= 3) {
2016 CheckMemberUsage (properties, "property");
2017 CheckMemberUsage (methods, "method");
2018 CheckMemberUsage (constants, "constant");
2020 if (fields != null){
2021 foreach (FieldMember f in fields) {
2022 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2026 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2031 // Only report 649 on level 4
2033 if (RootContext.WarningLevel < 4)
2036 if ((f.status & Field.Status.ASSIGNED) != 0)
2039 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2046 /// Emits the code, this step is performed after all
2047 /// the types, enumerations, constructors
2049 public void EmitType ()
2051 if (OptAttributes != null)
2052 OptAttributes.Emit (ec, this);
2056 if (instance_constructors != null) {
2057 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2058 bool has_compliant_args = false;
2060 foreach (Constructor c in instance_constructors) {
2063 if (has_compliant_args)
2066 has_compliant_args = c.HasCompliantArgs;
2068 if (!has_compliant_args)
2069 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2071 foreach (Constructor c in instance_constructors)
2078 if (default_static_constructor != null)
2079 default_static_constructor.Emit ();
2081 if (methods != null)
2082 foreach (Method m in methods)
2085 if (operators != null)
2086 foreach (Operator o in operators)
2089 if (properties != null)
2090 foreach (Property p in properties)
2093 if (indexers != null){
2098 foreach (FieldMember f in fields)
2101 if (events != null){
2102 foreach (Event e in Events)
2106 if (delegates != null) {
2107 foreach (Delegate d in Delegates) {
2112 if (enums != null) {
2113 foreach (Enum e in enums) {
2118 if (parts != null) {
2119 foreach (ClassPart part in parts)
2123 if ((Pending != null) && !(this is ClassPart))
2124 if (Pending.VerifyPendingMethods ())
2127 if (iterators != null)
2128 foreach (Iterator iterator in iterators)
2129 iterator.EmitType ();
2131 // if (types != null)
2132 // foreach (TypeContainer tc in types)
2136 public override void CloseType ()
2138 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2142 caching_flags |= Flags.CloseTypeCreated;
2143 TypeBuilder.CreateType ();
2144 } catch (TypeLoadException){
2146 // This is fine, the code still created the type
2148 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2149 // Console.WriteLine (e.Message);
2151 Console.WriteLine ("In type: " + Name);
2156 foreach (Enum en in Enums)
2160 foreach (TypeContainer tc in Types)
2161 if (tc.Kind == Kind.Struct)
2164 foreach (TypeContainer tc in Types)
2165 if (tc.Kind != Kind.Struct)
2169 if (Delegates != null)
2170 foreach (Delegate d in Delegates)
2173 if (Iterators != null)
2174 foreach (Iterator i in Iterators)
2182 initialized_fields = null;
2183 initialized_static_fields = null;
2192 default_constructor = null;
2193 default_static_constructor = null;
2195 OptAttributes = null;
2198 member_cache = null;
2201 // TODO: make it obsolete and use GetSignatureForError
2202 public string MakeName (string n)
2204 return "`" + Name + "." + n + "'";
2208 // Performs the validation on a Method's modifiers (properties have
2209 // the same properties).
2211 public bool MethodModifiersValid (MemberCore mc)
2213 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2214 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2215 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2217 int flags = mc.ModFlags;
2220 // At most one of static, virtual or override
2222 if ((flags & Modifiers.STATIC) != 0){
2223 if ((flags & vao) != 0){
2224 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2225 GetSignatureForError ());
2230 if (Kind == Kind.Struct){
2231 if ((flags & va) != 0){
2232 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2237 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2238 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2243 // If the declaration includes the abstract modifier, then the
2244 // declaration does not include static, virtual or extern
2246 if ((flags & Modifiers.ABSTRACT) != 0){
2247 if ((flags & Modifiers.EXTERN) != 0){
2249 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2253 if ((flags & Modifiers.SEALED) != 0) {
2254 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2258 if ((flags & Modifiers.VIRTUAL) != 0){
2259 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2263 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2264 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2269 if ((flags & Modifiers.PRIVATE) != 0){
2270 if ((flags & vao) != 0){
2271 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2276 if ((flags & Modifiers.SEALED) != 0){
2277 if ((flags & Modifiers.OVERRIDE) == 0){
2278 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2286 public bool UserDefinedStaticConstructor {
2288 return default_static_constructor != null;
2292 public Constructor DefaultStaticConstructor {
2293 get { return default_static_constructor; }
2296 protected override bool VerifyClsCompliance (DeclSpace ds)
2298 if (!base.VerifyClsCompliance (ds))
2303 Type base_type = TypeBuilder.BaseType;
2304 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2305 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2308 if (!Parent.IsClsCompliaceRequired (ds)) {
2309 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2310 GetSignatureForError (), Parent.GetSignatureForError ());
2317 /// Checks whether container name is CLS Compliant
2319 void VerifyClsName ()
2321 Hashtable base_members = base_cache == null ?
2323 base_cache.GetPublicMembers ();
2324 Hashtable this_members = new Hashtable ();
2326 foreach (DictionaryEntry entry in defined_names) {
2327 MemberCore mc = (MemberCore)entry.Value;
2328 if (!mc.IsClsCompliaceRequired (this))
2331 string name = (string)entry.Key;
2332 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2334 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2335 object found = base_members [lcase];
2336 if (found == null) {
2337 found = this_members [lcase];
2338 if (found == null) {
2339 this_members.Add (lcase, mc);
2344 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2347 if (found is MemberInfo) {
2348 if (basename == ((MemberInfo)found).Name)
2350 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2352 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2354 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2360 /// Performs checks for an explicit interface implementation. First it
2361 /// checks whether the `interface_type' is a base inteface implementation.
2362 /// Then it checks whether `name' exists in the interface type.
2364 public virtual bool VerifyImplements (Type interface_type, string full,
2365 string name, Location loc)
2369 if (ifaces != null){
2370 foreach (Type t in ifaces){
2371 if (t == interface_type){
2379 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2380 full, interface_type.FullName);
2387 protected override void VerifyObsoleteAttribute()
2389 CheckUsageOfObsoleteAttribute (ptype);
2394 foreach (Type iface in ifaces) {
2395 CheckUsageOfObsoleteAttribute (iface);
2404 string IMemberContainer.Name {
2410 Type IMemberContainer.Type {
2416 MemberCache IMemberContainer.MemberCache {
2418 return member_cache;
2422 bool IMemberContainer.IsInterface {
2424 return Kind == Kind.Interface;
2428 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2430 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2434 // Generates xml doc comments (if any), and if required,
2435 // handle warning report.
2437 internal override void GenerateDocComment (DeclSpace ds)
2439 DocUtil.GenerateTypeDocComment (this, ds);
2442 public override string DocCommentHeader {
2443 get { return "T:"; }
2446 public virtual MemberCache BaseCache {
2448 if (base_cache != null)
2450 if (TypeBuilder.BaseType != null)
2451 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2452 if (TypeBuilder.IsInterface)
2453 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2459 public class PartialContainer : TypeContainer {
2461 public readonly Namespace Namespace;
2462 public readonly int OriginalModFlags;
2463 public readonly int AllowedModifiers;
2464 public readonly TypeAttributes DefaultTypeAttributes;
2466 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2467 MemberName member_name, int mod_flags, Kind kind,
2470 PartialContainer pc;
2471 DeclSpace ds = RootContext.Tree.GetDecl (member_name);
2473 pc = ds as PartialContainer;
2477 260, ds.Location, "Missing partial modifier " +
2478 "on declaration of type `{0}'; another " +
2479 "partial implementation of this type exists",
2480 member_name.GetPartialName());
2482 Report.LocationOfPreviousError (loc);
2486 if (pc.Kind != kind) {
2488 261, loc, "Partial declarations of `{0}' " +
2489 "must be all classes, all structs or " +
2490 "all interfaces", member_name.GetPartialName ());
2494 if (pc.OriginalModFlags != mod_flags) {
2496 262, loc, "Partial declarations of `{0}' " +
2497 "have conflicting accessibility modifiers",
2498 member_name.GetPartialName ());
2505 if (parent is ClassPart)
2506 parent = ((ClassPart) parent).PartialContainer;
2508 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2509 RootContext.Tree.RecordDecl (member_name, pc);
2511 if (kind == Kind.Interface)
2512 parent.AddInterface (pc);
2513 else if (kind == Kind.Class || kind == Kind.Struct)
2514 parent.AddClassOrStruct (pc);
2516 throw new InvalidOperationException ();
2521 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2522 MemberName name, int mod, Attributes attrs,
2523 Kind kind, Location loc)
2525 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2527 // An error occured; create a dummy container, but don't
2529 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2532 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2537 protected PartialContainer (Namespace ns, TypeContainer parent,
2538 MemberName name, int mod, Kind kind, Location l)
2539 : base (null, parent, name, null, kind, l)
2541 this.Namespace = ns;
2545 AllowedModifiers = Class.AllowedModifiers;
2546 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2550 AllowedModifiers = Struct.AllowedModifiers;
2551 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2554 case Kind.Interface:
2555 AllowedModifiers = Interface.AllowedModifiers;
2556 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2560 throw new InvalidOperationException ();
2564 if (parent.Parent == null)
2565 accmods = Modifiers.INTERNAL;
2567 accmods = Modifiers.PRIVATE;
2569 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2570 this.OriginalModFlags = mod;
2573 public override PendingImplementation GetPendingImplementations ()
2575 return PendingImplementation.GetPendingImplementations (this);
2578 public override TypeAttributes TypeAttr {
2580 return base.TypeAttr | DefaultTypeAttributes;
2585 public class ClassPart : TypeContainer, IMemberContainer {
2586 public readonly PartialContainer PartialContainer;
2587 public readonly bool IsPartial;
2589 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2590 int mod, Attributes attrs, Kind kind, Location l)
2591 : base (ns, parent, pc.MemberName, attrs, kind, l)
2593 this.PartialContainer = pc;
2594 this.IsPartial = true;
2597 if (parent == null || parent == RootContext.Tree.Types)
2598 accmods = Modifiers.INTERNAL;
2600 accmods = Modifiers.PRIVATE;
2602 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2605 public override PendingImplementation GetPendingImplementations ()
2607 return PartialContainer.Pending;
2610 public override bool VerifyImplements (Type interface_type, string full,
2611 string name, Location loc)
2613 return PartialContainer.VerifyImplements (
2614 interface_type, full, name, loc);
2617 public override bool EmitFieldInitializers (EmitContext ec)
2619 return PartialContainer.EmitFieldInitializers (ec);
2622 public override Type FindNestedType (string name)
2624 return PartialContainer.FindNestedType (name);
2627 public override MemberCache BaseCache {
2629 return PartialContainer.BaseCache;
2634 public abstract class ClassOrStruct : TypeContainer {
2635 bool hasExplicitLayout = false;
2636 ListDictionary declarative_security;
2638 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2639 MemberName name, Attributes attrs, Kind kind,
2641 : base (ns, parent, name, attrs, kind, l)
2645 public override PendingImplementation GetPendingImplementations ()
2647 return PendingImplementation.GetPendingImplementations (this);
2650 public override bool HasExplicitLayout {
2652 return hasExplicitLayout;
2656 public override void VerifyMembers ()
2658 base.VerifyMembers ();
2660 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2661 foreach (Event e in events){
2663 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2668 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2670 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2671 if (declarative_security == null)
2672 declarative_security = new ListDictionary ();
2674 a.ExtractSecurityPermissionSet (declarative_security);
2678 if (a.Type == TypeManager.struct_layout_attribute_type &&
2679 a.GetLayoutKindValue () == LayoutKind.Explicit)
2680 hasExplicitLayout = true;
2682 base.ApplyAttributeBuilder (a, cb);
2685 public override void Emit()
2689 if (declarative_security != null) {
2690 foreach (DictionaryEntry de in declarative_security) {
2691 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2698 /// Class handles static classes declaration
2700 public sealed class StaticClass: Class {
2701 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2702 Attributes attrs, Location l)
2703 : base (ns, parent, name, mod, attrs, l)
2705 if (RootContext.Version == LanguageVersion.ISO_1) {
2706 Report.FeatureIsNotStandardized (l, "static classes");
2710 protected override int AllowedModifiersProp {
2712 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2713 Modifiers.STATIC | Modifiers.UNSAFE;
2717 protected override void DefineContainerMembers (MemberCoreArrayList list)
2722 foreach (MemberCore m in list) {
2723 if (m is Operator) {
2724 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2728 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2729 Report.Warning (628, 4, m.Location, "'{0}': new protected member declared in static class", m.GetSignatureForError (this));
2732 Report.Error (720, m.Location, "'{0}': cannot declare indexers in a static class", m.GetSignatureForError (this));
2736 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2739 if (m is Constructor) {
2740 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2744 if (m is Destructor) {
2745 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2749 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2752 base.DefineContainerMembers (list);
2755 public override TypeBuilder DefineType()
2757 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2758 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2762 TypeBuilder tb = base.DefineType ();
2766 if (ptype != TypeManager.object_type) {
2767 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2771 if (ifaces != null) {
2772 foreach (Type t in ifaces)
2773 Report.SymbolRelatedToPreviousError (t);
2774 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2779 public override TypeAttributes TypeAttr {
2781 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2786 public class Class : ClassOrStruct {
2787 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2788 public const int AllowedModifiers =
2791 Modifiers.PROTECTED |
2792 Modifiers.INTERNAL |
2794 Modifiers.ABSTRACT |
2798 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2799 Attributes attrs, Location l)
2800 : base (ns, parent, name, attrs, Kind.Class, l)
2802 this.ModFlags = mod;
2805 virtual protected int AllowedModifiersProp {
2807 return AllowedModifiers;
2811 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2813 if (a.Type == TypeManager.attribute_usage_type) {
2814 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2815 TypeBuilder.FullName != "System.Attribute") {
2816 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2820 if (a.Type == TypeManager.conditional_attribute_type &&
2821 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
2822 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2826 if (AttributeTester.IsAttributeExcluded (a.Type))
2829 base.ApplyAttributeBuilder (a, cb);
2832 public const TypeAttributes DefaultTypeAttributes =
2833 TypeAttributes.AutoLayout | TypeAttributes.Class;
2835 public override TypeBuilder DefineType()
2837 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2838 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2842 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2843 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2845 return base.DefineType ();
2848 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2849 /// Valid only for attribute classes.
2850 public bool IsExcluded ()
2852 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2853 return (caching_flags & Flags.Excluded) != 0;
2855 caching_flags &= ~Flags.Excluded_Undetected;
2857 if (OptAttributes == null)
2860 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
2865 foreach (Attribute a in attrs) {
2866 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
2867 if (RootContext.AllDefines.Contains (condition))
2871 caching_flags |= Flags.Excluded;
2876 // FIXME: How do we deal with the user specifying a different
2879 public override TypeAttributes TypeAttr {
2881 return base.TypeAttr | DefaultTypeAttributes;
2886 public class Struct : ClassOrStruct {
2888 // Modifiers allowed in a struct declaration
2890 public const int AllowedModifiers =
2893 Modifiers.PROTECTED |
2894 Modifiers.INTERNAL |
2898 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2899 int mod, Attributes attrs, Location l)
2900 : base (ns, parent, name, attrs, Kind.Struct, l)
2904 if (parent.Parent == null)
2905 accmods = Modifiers.INTERNAL;
2907 accmods = Modifiers.PRIVATE;
2909 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2911 this.ModFlags |= Modifiers.SEALED;
2914 public const TypeAttributes DefaultTypeAttributes =
2915 TypeAttributes.SequentialLayout |
2916 TypeAttributes.Sealed |
2917 TypeAttributes.BeforeFieldInit;
2920 // FIXME: Allow the user to specify a different set of attributes
2921 // in some cases (Sealed for example is mandatory for a class,
2922 // but what SequentialLayout can be changed
2924 public override TypeAttributes TypeAttr {
2926 return base.TypeAttr | DefaultTypeAttributes;
2934 public class Interface : TypeContainer, IMemberContainer {
2936 /// Modifiers allowed in a class declaration
2938 public const int AllowedModifiers =
2941 Modifiers.PROTECTED |
2942 Modifiers.INTERNAL |
2946 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2947 Attributes attrs, Location l)
2948 : base (ns, parent, name, attrs, Kind.Interface, l)
2952 if (parent.Parent == null)
2953 accmods = Modifiers.INTERNAL;
2955 accmods = Modifiers.PRIVATE;
2957 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2960 public override PendingImplementation GetPendingImplementations ()
2965 public const TypeAttributes DefaultTypeAttributes =
2966 TypeAttributes.AutoLayout |
2967 TypeAttributes.Abstract |
2968 TypeAttributes.Interface;
2970 public override TypeAttributes TypeAttr {
2972 return base.TypeAttr | DefaultTypeAttributes;
2977 public abstract class MethodCore : MemberBase {
2978 public readonly Parameters Parameters;
2979 protected ToplevelBlock block;
2982 // Parameters, cached for semantic analysis.
2984 protected InternalParameters parameter_info;
2985 protected Type [] parameter_types;
2987 // Whether this is an operator method.
2988 public bool IsOperator;
2991 // The method we're overriding if this is an override method.
2993 protected MethodInfo base_method = null;
2995 static string[] attribute_targets = new string [] { "method", "return" };
2997 public MethodCore (TypeContainer parent, Expression type, int mod,
2998 int allowed_mod, bool is_interface, MemberName name,
2999 Attributes attrs, Parameters parameters, Location loc)
3000 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3003 Parameters = parameters;
3004 IsInterface = is_interface;
3008 // Returns the System.Type array for the parameters of this method
3010 public Type [] ParameterTypes {
3012 return parameter_types;
3016 public InternalParameters ParameterInfo
3019 return parameter_info;
3023 public ToplevelBlock Block {
3033 protected override bool CheckBase ()
3035 if (!base.CheckBase ())
3038 // Check whether arguments were correct.
3039 if (!DoDefineParameters ())
3042 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3048 // Is null for System.Object while compiling corlib and base interfaces
3049 if (Parent.BaseCache == null) {
3050 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3051 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3056 Type base_ret_type = null;
3057 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3059 // method is override
3060 if (base_method != null) {
3062 if (!CheckMethodAgainstBase ())
3065 if ((ModFlags & Modifiers.NEW) == 0) {
3066 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3067 Report.SymbolRelatedToPreviousError (base_method);
3068 if (this is PropertyBase) {
3069 Report.Error (1715, Location, "'{0}': type must be '{1}' to match overridden member '{2}'",
3070 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3073 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3074 "change return type when overriding inherited member");
3079 if (base_method.IsAbstract && !IsInterface) {
3080 Report.SymbolRelatedToPreviousError (base_method);
3081 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3086 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3087 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3091 if (RootContext.WarningLevel > 2) {
3092 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3093 Parent.Methods.HasEquals = true;
3094 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3095 Parent.Methods.HasGetHashCode = true;
3098 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3099 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3101 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3102 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3103 Report.SymbolRelatedToPreviousError (base_method);
3104 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3111 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3112 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3113 if (conflict_symbol != null) {
3114 Report.SymbolRelatedToPreviousError (conflict_symbol);
3115 if (this is PropertyBase)
3116 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3118 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3120 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3124 if (conflict_symbol == null) {
3125 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3126 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3131 if ((ModFlags & Modifiers.NEW) == 0) {
3132 if (this is Method && conflict_symbol is MethodBase)
3135 Report.SymbolRelatedToPreviousError (conflict_symbol);
3136 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3144 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3145 // that have been defined.
3147 // `name' is the user visible name for reporting errors (this is used to
3148 // provide the right name regarding method names and properties)
3150 bool CheckMethodAgainstBase ()
3154 // TODO: replace with GetSignatureForError
3155 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3157 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3158 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3160 506, Location, Parent.MakeName (Name) +
3161 ": cannot override inherited member `" +
3162 name + "' because it is not " +
3163 "virtual, abstract or override");
3167 // Now we check that the overriden method is not final
3169 if (base_method.IsFinal) {
3170 Report.SymbolRelatedToPreviousError (base_method);
3171 Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
3172 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3176 // Check that the permissions are not being changed
3178 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3179 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3181 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3182 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3187 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3188 ModFlags |= Modifiers.NEW;
3189 Report.SymbolRelatedToPreviousError (base_method);
3190 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3191 if (RootContext.WarningLevel >= 2)
3192 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));
3194 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3200 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3202 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3204 // when overriding protected internal, the method can be declared
3205 // protected internal only within the same assembly
3208 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3209 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3211 // assemblies differ - report an error
3215 } else if (thisp != base_classp) {
3217 // same assembly, but other attributes differ - report an error
3222 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3224 // if it's not "protected internal", it must be "protected"
3228 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3230 // protected within the same assembly - an error
3233 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3234 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3236 // protected ok, but other attributes differ - report an error
3242 return (thisp == base_classp);
3246 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3249 // FIXME: report the old/new permissions?
3252 507, Location, parent.MakeName (Name) +
3253 ": can't change the access modifiers when overriding inherited " +
3254 "member `" + name + "'");
3257 protected static string Error722 {
3259 return "'{0}': static types cannot be used as return types";
3264 /// For custom member duplication search in a container
3266 protected abstract bool CheckForDuplications ();
3269 /// Gets base method and its return type
3271 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3273 protected virtual bool DoDefineParameters ()
3275 EmitContext ec = Parent.EmitContext;
3277 throw new InternalErrorException ("DoDefineParameters invoked too early");
3279 bool old_unsafe = ec.InUnsafe;
3280 ec.InUnsafe = InUnsafe;
3281 // Check if arguments were correct
3282 parameter_types = Parameters.GetParameterInfo (ec);
3283 ec.InUnsafe = old_unsafe;
3285 if ((parameter_types == null) ||
3286 !CheckParameters (Parent, parameter_types))
3289 parameter_info = new InternalParameters (parameter_types, Parameters);
3291 Parameter array_param = Parameters.ArrayParameter;
3292 if ((array_param != null) &&
3293 (!array_param.ParameterType.IsArray ||
3294 (array_param.ParameterType.GetArrayRank () != 1))) {
3295 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3302 public override string[] ValidAttributeTargets {
3304 return attribute_targets;
3308 protected override bool VerifyClsCompliance (DeclSpace ds)
3310 if (!base.VerifyClsCompliance (ds)) {
3311 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3312 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3317 if (Parameters.HasArglist) {
3318 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3321 if (!AttributeTester.IsClsCompliant (MemberType)) {
3322 if (this is PropertyBase)
3323 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3324 GetSignatureForError ());
3326 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3327 GetSignatureForError ());
3330 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3335 protected bool IsDuplicateImplementation (MethodCore method)
3337 if ((method == this) || (method.Name != Name))
3340 Type[] param_types = method.ParameterTypes;
3341 if (param_types == null)
3344 if (param_types.Length != ParameterTypes.Length)
3347 for (int i = 0; i < param_types.Length; i++)
3348 if (param_types [i] != ParameterTypes [i])
3351 // TODO: make operator compatible with MethodCore to avoid this
3352 if (this is Operator && method is Operator) {
3353 if (MemberType != method.MemberType)
3358 // Try to report 663: method only differs on out/ref
3360 ParameterData info = ParameterInfo;
3361 ParameterData other_info = method.ParameterInfo;
3362 for (int i = 0; i < info.Count; i++){
3363 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3364 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3369 Report.SymbolRelatedToPreviousError (method);
3370 if (this is Operator && method is Operator)
3371 Report.Error (557, Location, "Duplicate user-defined conversion in type '{0}'", Parent.Name);
3373 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3377 public override bool IsUsed
3388 // Returns a string that represents the signature for this
3389 // member which should be used in XML documentation.
3391 public override string GetDocCommentName (DeclSpace ds)
3393 return DocUtil.GetMethodDocCommentName (this, ds);
3397 // Raised (and passed an XmlElement that contains the comment)
3398 // when GenerateDocComment is writing documentation expectedly.
3400 // FIXME: with a few effort, it could be done with XmlReader,
3401 // that means removal of DOM use.
3403 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3405 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3409 // Represents header string for documentation comment.
3411 public override string DocCommentHeader {
3412 get { return "M:"; }
3415 protected override void VerifyObsoleteAttribute()
3417 base.VerifyObsoleteAttribute ();
3419 if (parameter_types == null)
3422 foreach (Type type in parameter_types) {
3423 CheckUsageOfObsoleteAttribute (type);
3428 public class SourceMethod : ISourceMethod
3430 TypeContainer container;
3433 protected SourceMethod (TypeContainer container, MethodBase builder,
3434 ISourceFile file, Location start, Location end)
3436 this.container = container;
3437 this.builder = builder;
3439 CodeGen.SymbolWriter.OpenMethod (
3440 file, this, start.Row, 0, end.Row, 0);
3443 public string Name {
3444 get { return builder.Name; }
3447 public int NamespaceID {
3448 get { return container.NamespaceEntry.SymbolFileID; }
3453 if (builder is MethodBuilder)
3454 return ((MethodBuilder) builder).GetToken ().Token;
3455 else if (builder is ConstructorBuilder)
3456 return ((ConstructorBuilder) builder).GetToken ().Token;
3458 throw new NotSupportedException ();
3462 public void CloseMethod ()
3464 if (CodeGen.SymbolWriter != null)
3465 CodeGen.SymbolWriter.CloseMethod ();
3468 public static SourceMethod Create (TypeContainer parent,
3469 MethodBase builder, Block block)
3471 if (CodeGen.SymbolWriter == null)
3476 Location start_loc = block.StartLocation;
3477 if (Location.IsNull (start_loc))
3480 Location end_loc = block.EndLocation;
3481 if (Location.IsNull (end_loc))
3484 ISourceFile file = start_loc.SourceFile;
3488 return new SourceMethod (
3489 parent, builder, file, start_loc, end_loc);
3493 public class Method : MethodCore, IIteratorContainer, IMethodData {
3494 public MethodBuilder MethodBuilder;
3495 public MethodData MethodData;
3496 ReturnParameter return_attributes;
3497 ListDictionary declarative_security;
3500 /// Modifiers allowed in a class declaration
3502 const int AllowedModifiers =
3505 Modifiers.PROTECTED |
3506 Modifiers.INTERNAL |
3511 Modifiers.OVERRIDE |
3512 Modifiers.ABSTRACT |
3514 Modifiers.METHOD_YIELDS |
3517 const int AllowedInterfaceModifiers =
3518 Modifiers.NEW | Modifiers.UNSAFE;
3521 // return_type can be "null" for VOID values.
3523 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3524 MemberName name, Parameters parameters, Attributes attrs,
3526 : base (ds, return_type, mod,
3527 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3528 is_iface, name, attrs, parameters, l)
3532 public override AttributeTargets AttributeTargets {
3534 return AttributeTargets.Method;
3538 public override string GetSignatureForError()
3540 if (MethodBuilder == null) {
3541 return GetSignatureForError (Parent);
3543 return TypeManager.CSharpSignature (MethodBuilder);
3547 /// Use this method when MethodBuilder is null
3549 public override string GetSignatureForError (TypeContainer tc)
3551 // TODO: get params from somewhere
3552 if (parameter_info == null)
3553 return base.GetSignatureForError (tc);
3555 // TODO: move to parameters
3556 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3557 if (parameter_info.Parameters.FixedParameters != null) {
3558 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3559 Parameter p = parameter_info.Parameters.FixedParameters [i];
3560 args.Append (p.GetSignatureForError ());
3562 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3567 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3570 void DuplicateEntryPoint (MethodInfo b, Location location)
3574 "Program `" + CodeGen.FileName +
3575 "' has more than one entry point defined: `" +
3576 TypeManager.CSharpSignature(b) + "'");
3579 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3581 if (b.ReturnType != TypeManager.void_type &&
3582 b.ReturnType != TypeManager.int32_type)
3585 if (pinfo.Count == 0)
3588 if (pinfo.Count > 1)
3591 Type t = pinfo.ParameterType(0);
3593 (t.GetArrayRank() == 1) &&
3594 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3595 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3601 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3603 if (a.Target == AttributeTargets.ReturnValue) {
3604 if (return_attributes == null)
3605 return_attributes = new ReturnParameter (MethodBuilder, Location);
3607 return_attributes.ApplyAttributeBuilder (a, cb);
3611 if (a.Type == TypeManager.methodimpl_attr_type &&
3612 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3613 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3616 if (a.Type == TypeManager.dllimport_type) {
3617 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3618 if ((ModFlags & extern_static) != extern_static) {
3619 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3625 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3626 if (declarative_security == null)
3627 declarative_security = new ListDictionary ();
3628 a.ExtractSecurityPermissionSet (declarative_security);
3632 if (a.Type == TypeManager.conditional_attribute_type) {
3633 if (IsOperator || IsExplicitImpl) {
3634 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3638 if (ReturnType != TypeManager.void_type) {
3639 Report.Error (578, Location, "Conditional not valid on '{0}' because its return type is not void", GetSignatureForError ());
3643 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3644 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3649 Report.Error (582, Location, "Conditional not valid on interface members");
3653 if (MethodData.IsImplementing) {
3654 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3658 for (int i = 0; i < parameter_info.Count; ++i) {
3659 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3660 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3666 MethodBuilder.SetCustomAttribute (cb);
3669 protected override bool CheckForDuplications ()
3671 ArrayList ar = Parent.Methods;
3673 int arLen = ar.Count;
3675 for (int i = 0; i < arLen; i++) {
3676 Method m = (Method) ar [i];
3677 if (IsDuplicateImplementation (m))
3682 ar = Parent.Properties;
3684 for (int i = 0; i < ar.Count; ++i) {
3685 PropertyBase pb = (PropertyBase) ar [i];
3686 if (pb.AreAccessorsDuplicateImplementation (this))
3691 ar = Parent.Indexers;
3693 for (int i = 0; i < ar.Count; ++i) {
3694 PropertyBase pb = (PropertyBase) ar [i];
3695 if (pb.AreAccessorsDuplicateImplementation (this))
3702 for (int i = 0; i < ar.Count; ++i) {
3703 Event ev = (Event) ar [i];
3704 if (ev.AreAccessorsDuplicateImplementation (this))
3715 public override bool Define ()
3720 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3721 Error1599 (Location, ReturnType);
3729 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3731 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3733 if (!MethodData.Define (Parent))
3737 // Setup iterator if we are one
3739 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3740 Iterator iterator = new Iterator (
3741 Parent, Name, MemberType,
3742 ParameterInfo, ModFlags, block, Location);
3744 if (!iterator.DefineIterator ())
3747 block = iterator.Block;
3750 MethodBuilder = MethodData.MethodBuilder;
3753 // This is used to track the Entry Point,
3755 if (Name == "Main" &&
3756 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3757 (RootContext.MainClass == null ||
3758 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3759 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3760 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3761 md.SetMemberIsUsed ();
3763 if (RootContext.EntryPoint == null) {
3764 RootContext.EntryPoint = MethodBuilder;
3765 RootContext.EntryPointLocation = Location;
3767 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3768 DuplicateEntryPoint (MethodBuilder, Location);
3771 if (RootContext.WarningLevel >= 4)
3772 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3776 if (MemberType.IsAbstract && MemberType.IsSealed) {
3777 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3787 public override void Emit ()
3789 MethodData.Emit (Parent, this);
3792 if (declarative_security != null) {
3793 foreach (DictionaryEntry de in declarative_security) {
3794 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3802 public static void Error1599 (Location loc, Type t)
3804 Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
3807 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3809 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3810 container.TypeBuilder, Name, ParameterTypes, false);
3815 base_ret_type = mi.ReturnType;
3819 public override bool MarkForDuplicationCheck ()
3821 caching_flags |= Flags.TestMethodDuplication;
3825 protected override bool VerifyClsCompliance(DeclSpace ds)
3827 if (!base.VerifyClsCompliance (ds))
3830 if (parameter_types.Length > 0) {
3831 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3833 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3840 void IIteratorContainer.SetYields ()
3842 ModFlags |= Modifiers.METHOD_YIELDS;
3845 #region IMethodData Members
3847 public CallingConventions CallingConventions {
3849 CallingConventions cc = Parameters.GetCallingConvention ();
3850 if (Parameters.HasArglist)
3851 block.HasVarargs = true;
3854 if ((ModFlags & Modifiers.STATIC) == 0)
3855 cc |= CallingConventions.HasThis;
3857 // FIXME: How is `ExplicitThis' used in C#?
3863 public Type ReturnType {
3869 public MemberName MethodName {
3875 public new Location Location {
3877 return base.Location;
3881 protected override bool CheckBase() {
3882 if (!base.CheckBase ())
3885 // TODO: Destructor should derive from MethodCore
3886 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3887 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3888 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3895 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3897 return new EmitContext (
3898 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3901 public ObsoleteAttribute GetObsoleteAttribute ()
3903 return GetObsoleteAttribute (Parent);
3907 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3909 public bool IsExcluded (EmitContext ec)
3911 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3912 return (caching_flags & Flags.Excluded) != 0;
3914 caching_flags &= ~Flags.Excluded_Undetected;
3916 if (base_method == null) {
3917 if (OptAttributes == null)
3920 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3925 foreach (Attribute a in attrs) {
3926 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3927 if (RootContext.AllDefines.Contains (condition))
3931 caching_flags |= Flags.Excluded;
3935 IMethodData md = TypeManager.GetMethod (base_method);
3937 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
3938 caching_flags |= Flags.Excluded;
3944 if (md.IsExcluded (ec)) {
3945 caching_flags |= Flags.Excluded;
3954 public abstract class ConstructorInitializer {
3955 ArrayList argument_list;
3956 protected ConstructorInfo base_constructor;
3957 Parameters parameters;
3960 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
3963 this.argument_list = argument_list;
3964 this.parameters = parameters;
3968 public ArrayList Arguments {
3970 return argument_list;
3974 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
3976 Expression base_constructor_group;
3980 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
3982 if (argument_list != null){
3983 foreach (Argument a in argument_list){
3984 if (!a.Resolve (ec, loc))
3988 ec.CurrentBlock = null;
3990 if (this is ConstructorBaseInitializer) {
3991 if (ec.ContainerType.BaseType == null)
3994 t = ec.ContainerType.BaseType;
3995 if (ec.ContainerType.IsValueType) {
3996 Report.Error (522, loc,
3997 "structs cannot call base class constructors");
4001 t = ec.ContainerType;
4003 base_constructor_group = Expression.MemberLookup (
4004 ec, t, ".ctor", MemberTypes.Constructor,
4005 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4008 if (base_constructor_group == null){
4010 base_constructor_group = Expression.MemberLookup (
4011 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4012 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4016 int errors = Report.Errors;
4017 if (base_constructor_group != null)
4018 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4019 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4022 if (base_constructor == null) {
4023 if (errors == Report.Errors)
4024 Report.Error (1501, loc, "Can not find a constructor for this argument list");
4029 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
4030 TypeManager.CSharpSignature (base_constructor));
4031 base_constructor = null;
4035 if (base_constructor == caller_builder){
4036 Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
4043 public void Emit (EmitContext ec)
4045 if (base_constructor != null){
4046 ec.Mark (loc, false);
4048 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4050 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4055 /// Method search for base ctor. (We do not cache it).
4057 Constructor GetOverloadedConstructor (TypeContainer tc)
4059 if (tc.InstanceConstructors == null)
4062 foreach (Constructor c in tc.InstanceConstructors) {
4063 if (Arguments == null) {
4064 if (c.ParameterTypes.Length == 0)
4072 int count = c.ParameterInfo.Count;
4074 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4075 for (int i = 0; i < count-1; i++)
4076 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4081 if (c.ParameterTypes.Length != Arguments.Count)
4084 for (int i = 0; i < Arguments.Count; ++i)
4085 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4100 //TODO: implement caching when it will be necessary
4101 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4103 Constructor ctor = GetOverloadedConstructor (tc);
4107 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4111 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4115 public class ConstructorBaseInitializer : ConstructorInitializer {
4116 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4117 base (argument_list, pars, l)
4121 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4122 if (base_constructor == null)
4125 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4126 if (type_ds == null) {
4127 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (base_constructor);
4130 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (base_constructor), loc);
4135 base.CheckObsoleteAttribute (type_ds, loc);
4140 public class ConstructorThisInitializer : ConstructorInitializer {
4141 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4142 base (argument_list, pars, l)
4147 public class Constructor : MethodCore, IMethodData {
4148 public ConstructorBuilder ConstructorBuilder;
4149 public ConstructorInitializer Initializer;
4150 ListDictionary declarative_security;
4153 // Modifiers allowed for a constructor.
4155 public const int AllowedModifiers =
4157 Modifiers.PROTECTED |
4158 Modifiers.INTERNAL |
4164 bool has_compliant_args = false;
4166 // The spec claims that static is not permitted, but
4167 // my very own code has static constructors.
4169 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4170 ConstructorInitializer init, Location l)
4171 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4177 public override string GetSignatureForError()
4179 if (ConstructorBuilder == null)
4180 return GetSignatureForError (Parent);
4182 return TypeManager.CSharpSignature (ConstructorBuilder);
4185 public bool HasCompliantArgs {
4187 return has_compliant_args;
4191 public override AttributeTargets AttributeTargets {
4193 return AttributeTargets.Constructor;
4199 // Returns true if this is a default constructor
4201 public bool IsDefault ()
4203 if ((ModFlags & Modifiers.STATIC) != 0)
4204 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4205 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4208 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4209 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4210 (Initializer is ConstructorBaseInitializer) &&
4211 (Initializer.Arguments == null);
4214 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4216 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4217 if (declarative_security == null) {
4218 declarative_security = new ListDictionary ();
4220 a.ExtractSecurityPermissionSet (declarative_security);
4224 ConstructorBuilder.SetCustomAttribute (cb);
4227 protected override bool CheckForDuplications ()
4229 ArrayList ar = Parent.InstanceConstructors;
4231 int arLen = ar.Count;
4233 for (int i = 0; i < arLen; i++) {
4234 Constructor m = (Constructor) ar [i];
4235 if (IsDuplicateImplementation (m))
4242 protected override bool CheckBase ()
4244 // Check whether arguments were correct.
4245 if (!DoDefineParameters ())
4248 // TODO: skip the rest for generated ctor
4249 if ((ModFlags & Modifiers.STATIC) != 0)
4252 if (!CheckForDuplications ())
4255 if (Parent.Kind == Kind.Struct) {
4256 if (ParameterTypes.Length == 0) {
4257 Report.Error (568, Location,
4258 "Structs can not contain explicit parameterless " +
4263 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4264 Report.Error (666, Location, "Protected member in struct declaration");
4269 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4270 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4277 // Creates the ConstructorBuilder
4279 public override bool Define ()
4281 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4282 MethodAttributes.SpecialName);
4284 if ((ModFlags & Modifiers.STATIC) != 0) {
4285 ca |= MethodAttributes.Static | MethodAttributes.Private;
4287 ca |= MethodAttributes.HideBySig;
4289 if ((ModFlags & Modifiers.PUBLIC) != 0)
4290 ca |= MethodAttributes.Public;
4291 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4292 if ((ModFlags & Modifiers.INTERNAL) != 0)
4293 ca |= MethodAttributes.FamORAssem;
4295 ca |= MethodAttributes.Family;
4296 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4297 ca |= MethodAttributes.Assembly;
4298 else if (IsDefault ())
4299 ca |= MethodAttributes.Public;
4301 ca |= MethodAttributes.Private;
4304 // Check if arguments were correct.
4308 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4309 ca, CallingConventions,
4312 if ((ModFlags & Modifiers.UNSAFE) != 0)
4313 ConstructorBuilder.InitLocals = false;
4315 TypeManager.AddMethod (ConstructorBuilder, this);
4318 // HACK because System.Reflection.Emit is lame
4320 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4328 public override void Emit ()
4330 EmitContext ec = CreateEmitContext (null, null);
4333 // extern methods have no bodies
4335 if ((ModFlags & Modifiers.EXTERN) != 0) {
4336 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4338 179, Location, "External constructor `" +
4339 TypeManager.CSharpSignature (ConstructorBuilder) +
4340 "' can not have a body");
4343 } else if (block == null) {
4345 501, Location, "Constructor `" +
4346 TypeManager.CSharpSignature (ConstructorBuilder) +
4347 "' must declare a body since it is not marked extern");
4351 if ((ModFlags & Modifiers.STATIC) == 0){
4352 if (Parent.Kind == Kind.Class && Initializer == null)
4353 Initializer = new ConstructorBaseInitializer (
4354 null, Parameters.EmptyReadOnlyParameters, Location);
4358 // Spec mandates that Initializers will not have
4362 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4364 ec.IsStatic = false;
4367 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4369 SourceMethod source = SourceMethod.Create (
4370 Parent, ConstructorBuilder, block);
4373 // Classes can have base initializers and instance field initializers.
4375 if (Parent.Kind == Kind.Class){
4376 if ((ModFlags & Modifiers.STATIC) == 0){
4379 // If we use a "this (...)" constructor initializer, then
4380 // do not emit field initializers, they are initialized in the other constructor
4382 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4383 Parent.EmitFieldInitializers (ec);
4386 if (Initializer != null) {
4387 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null)
4388 Initializer.CheckObsoleteAttribute (Parent, Location);
4390 ec.TestObsoleteMethodUsage = false;
4391 Initializer.Emit (ec);
4394 if ((ModFlags & Modifiers.STATIC) != 0)
4395 Parent.EmitFieldInitializers (ec);
4397 if (OptAttributes != null)
4398 OptAttributes.Emit (ec, this);
4400 // If this is a non-static `struct' constructor and doesn't have any
4401 // initializer, it must initialize all of the struct's fields.
4402 if ((Parent.Kind == Kind.Struct) &&
4403 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4404 Block.AddThisVariable (Parent, Location);
4406 ec.EmitTopBlock (block, ParameterInfo, Location);
4409 source.CloseMethod ();
4413 if (declarative_security != null) {
4414 foreach (DictionaryEntry de in declarative_security) {
4415 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4422 // Is never override
4423 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4428 protected override bool VerifyClsCompliance (DeclSpace ds)
4430 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4434 if (parameter_types.Length > 0) {
4435 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4437 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4439 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4440 foreach (Type param in parameter_types) {
4441 if (param.IsArray) {
4447 has_compliant_args = true;
4451 #region IMethodData Members
4453 public System.Reflection.CallingConventions CallingConventions {
4455 CallingConventions cc = Parameters.GetCallingConvention ();
4457 if (Parent.Kind == Kind.Class)
4458 if ((ModFlags & Modifiers.STATIC) == 0)
4459 cc |= CallingConventions.HasThis;
4461 // FIXME: How is `ExplicitThis' used in C#?
4467 public new Location Location {
4469 return base.Location;
4473 public MemberName MethodName {
4479 public Type ReturnType {
4485 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4487 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4488 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4491 public ObsoleteAttribute GetObsoleteAttribute ()
4496 public bool IsExcluded(EmitContext ec)
4505 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4507 public interface IMethodData
4509 CallingConventions CallingConventions { get; }
4510 Location Location { get; }
4511 MemberName MethodName { get; }
4512 Type[] ParameterTypes { get; }
4513 Type ReturnType { get; }
4515 Attributes OptAttributes { get; }
4516 ToplevelBlock Block { get; }
4518 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4519 ObsoleteAttribute GetObsoleteAttribute ();
4520 string GetSignatureForError (TypeContainer tc);
4521 bool IsExcluded (EmitContext ec);
4522 bool IsClsCompliaceRequired (DeclSpace ds);
4523 void SetMemberIsUsed ();
4527 // Encapsulates most of the Method's state
4529 public class MethodData {
4531 readonly IMethodData method;
4534 // The return type of this method
4536 public readonly InternalParameters ParameterInfo;
4539 // Are we implementing an interface ?
4541 public bool IsImplementing = false;
4546 protected MemberBase member;
4547 protected int modifiers;
4548 protected MethodAttributes flags;
4550 MethodBuilder builder = null;
4551 public MethodBuilder MethodBuilder {
4557 public MethodData (MemberBase member, InternalParameters parameters,
4558 int modifiers, MethodAttributes flags, IMethodData method)
4560 this.member = member;
4561 this.ParameterInfo = parameters;
4562 this.modifiers = modifiers;
4565 this.method = method;
4568 public bool Define (TypeContainer container)
4570 MethodInfo implementing = null;
4572 string name = method.MethodName.Name;
4573 string method_name = name;
4575 Type[] ParameterTypes = method.ParameterTypes;
4577 if (container.Pending != null){
4578 if (member is Indexer) // TODO: test it, but it should work without this IF
4579 implementing = container.Pending.IsInterfaceIndexer (
4580 member.InterfaceType, method.ReturnType, ParameterInfo);
4582 implementing = container.Pending.IsInterfaceMethod (
4583 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4585 if (member.InterfaceType != null){
4586 if (implementing == null){
4587 if (member is PropertyBase) {
4588 Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
4589 method.GetSignatureForError (container), member.Name);
4592 Report.Error (539, method.Location,
4593 "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
4597 if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
4598 Report.SymbolRelatedToPreviousError (implementing);
4599 Report.Error (683, method.Location, "'{0}' explicit method implementation cannot implement '{1}' because it is an accessor",
4600 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4603 method_name = member.InterfaceType.FullName + "." + name;
4605 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
4606 Report.SymbolRelatedToPreviousError (implementing);
4607 Report.Error (686, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
4608 method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4615 // For implicit implementations, make sure we are public, for
4616 // explicit implementations, make sure we are private.
4618 if (implementing != null){
4620 // Setting null inside this block will trigger a more
4621 // verbose error reporting for missing interface implementations
4623 // The "candidate" function has been flagged already
4624 // but it wont get cleared
4626 if (member.IsExplicitImpl){
4627 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4628 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4629 implementing = null;
4631 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4632 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4634 // If this is an interface method implementation,
4635 // check for public accessibility
4637 implementing = null;
4638 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4639 // We may never be private.
4640 implementing = null;
4641 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4643 // We may be protected if we're overriding something.
4645 implementing = null;
4650 // Static is not allowed
4652 if ((modifiers & Modifiers.STATIC) != 0){
4653 implementing = null;
4654 Modifiers.Error_InvalidModifier (method.Location, "static");
4659 // If implementing is still valid, set flags
4661 if (implementing != null){
4663 // When implementing interface methods, set NewSlot
4664 // unless, we are overwriting a method.
4666 if (implementing.DeclaringType.IsInterface){
4667 if ((modifiers & Modifiers.OVERRIDE) == 0)
4668 flags |= MethodAttributes.NewSlot;
4671 MethodAttributes.Virtual |
4672 MethodAttributes.HideBySig;
4674 // Set Final unless we're virtual, abstract or already overriding a method.
4675 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4676 flags |= MethodAttributes.Final;
4678 IsImplementing = true;
4681 EmitContext ec = method.CreateEmitContext (container, null);
4683 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4685 if (builder == null)
4688 if ((modifiers & Modifiers.UNSAFE) != 0)
4689 builder.InitLocals = false;
4691 if (IsImplementing){
4693 // clear the pending implemntation flag
4695 if (member is Indexer) {
4696 container.Pending.ImplementIndexer (
4697 member.InterfaceType, builder, method.ReturnType,
4698 ParameterInfo, member.IsExplicitImpl);
4700 container.Pending.ImplementMethod (
4701 member.InterfaceType, name, method.ReturnType,
4702 ParameterInfo, member.IsExplicitImpl);
4704 if (member.IsExplicitImpl)
4705 container.TypeBuilder.DefineMethodOverride (
4706 builder, implementing);
4710 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4711 TypeManager.AddMethod (builder, method);
4718 /// Create the MethodBuilder for the method
4720 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4722 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4724 if ((modifiers & extern_static) == extern_static) {
4726 if (method.OptAttributes != null) {
4727 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4728 if (dllimport_attribute != null) {
4729 flags |= MethodAttributes.PinvokeImpl;
4730 builder = dllimport_attribute.DefinePInvokeMethod (
4731 ec, container.TypeBuilder, method_name, flags,
4732 method.ReturnType, ParameterTypes);
4738 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4739 // We are more strict than Microsoft and report CS0626 like error
4740 if (method.OptAttributes == null ||
4741 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4742 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));
4747 builder = container.TypeBuilder.DefineMethod (
4748 method_name, flags, method.CallingConventions,
4749 method.ReturnType, ParameterTypes);
4755 public void Emit (TypeContainer container, Attributable kind)
4758 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4759 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4761 ec = method.CreateEmitContext (container, null);
4763 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
4764 ec.TestObsoleteMethodUsage = false;
4766 Location loc = method.Location;
4767 Attributes OptAttributes = method.OptAttributes;
4769 if (OptAttributes != null)
4770 OptAttributes.Emit (ec, kind);
4772 if (member is MethodCore)
4773 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4775 ToplevelBlock block = method.Block;
4778 // abstract or extern methods have no bodies
4780 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4785 // abstract or extern methods have no bodies.
4787 if ((modifiers & Modifiers.ABSTRACT) != 0)
4789 500, method.Location, "Abstract method `" +
4790 TypeManager.CSharpSignature (builder) +
4791 "' can not have a body");
4793 if ((modifiers & Modifiers.EXTERN) != 0)
4795 179, method.Location, "External method `" +
4796 TypeManager.CSharpSignature (builder) +
4797 "' can not have a body");
4803 // Methods must have a body unless they're extern or abstract
4805 if (block == null) {
4807 501, method.Location, "Method `" +
4808 TypeManager.CSharpSignature (builder) +
4809 "' must declare a body since it is not marked " +
4810 "abstract or extern");
4814 SourceMethod source = SourceMethod.Create (
4815 container, MethodBuilder, method.Block);
4818 // Handle destructors specially
4820 // FIXME: This code generates buggy code
4822 if (member is Destructor)
4823 EmitDestructor (ec, block);
4825 ec.EmitTopBlock (block, ParameterInfo, loc);
4828 source.CloseMethod ();
4831 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4833 ILGenerator ig = ec.ig;
4835 Label finish = ig.DefineLabel ();
4837 block.SetDestructor ();
4839 ig.BeginExceptionBlock ();
4840 ec.ReturnLabel = finish;
4841 ec.HasReturnLabel = true;
4842 ec.EmitTopBlock (block, null, method.Location);
4844 // ig.MarkLabel (finish);
4845 ig.BeginFinallyBlock ();
4847 if (ec.ContainerType.BaseType != null) {
4848 Expression member_lookup = Expression.MemberLookup (
4849 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4850 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4852 if (member_lookup != null){
4853 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4855 ig.Emit (OpCodes.Ldarg_0);
4856 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4860 ig.EndExceptionBlock ();
4861 //ig.MarkLabel (ec.ReturnLabel);
4862 ig.Emit (OpCodes.Ret);
4866 // Should derive from MethodCore
4867 public class Destructor : Method {
4869 public Destructor (TypeContainer ds, Expression return_type, int mod,
4870 string name, Parameters parameters, Attributes attrs,
4872 : base (ds, return_type, mod, false, new MemberName (name),
4873 parameters, attrs, l)
4876 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4878 if (a.Type == TypeManager.conditional_attribute_type) {
4879 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4883 base.ApplyAttributeBuilder (a, cb);
4887 abstract public class MemberBase : MemberCore {
4888 public Expression Type;
4890 public MethodAttributes flags;
4892 protected readonly int explicit_mod_flags;
4895 // The "short" name of this property / indexer / event. This is the
4896 // name without the explicit interface.
4898 public string ShortName {
4899 get { return MemberName.Name; }
4901 SetMemberName (new MemberName (MemberName.Left, value));
4906 // The type of this property / indexer / event
4909 public Type MemberType {
4911 if (member_type == null && Type != null) {
4912 EmitContext ec = Parent.EmitContext;
4913 bool old_unsafe = ec.InUnsafe;
4914 ec.InUnsafe = InUnsafe;
4915 Type = Type.ResolveAsTypeTerminal (ec, false);
4916 ec.InUnsafe = old_unsafe;
4918 member_type = Type == null ? null : Type.Type;
4925 // Whether this is an interface member.
4927 public bool IsInterface;
4930 // If true, this is an explicit interface implementation
4932 public bool IsExplicitImpl;
4935 // The interface type we are explicitly implementing
4937 public Type InterfaceType = null;
4940 // The constructor is only exposed to our children
4942 protected MemberBase (TypeContainer parent, Expression type, int mod,
4943 int allowed_mod, int def_mod, MemberName name,
4944 Attributes attrs, Location loc)
4945 : base (parent, name, attrs, loc)
4947 explicit_mod_flags = mod;
4949 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4950 IsExplicitImpl = (MemberName.Left != null);
4953 protected virtual bool CheckBase ()
4955 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4956 Report.Error (666, Location, "Protected member in struct declaration");
4960 if ((RootContext.WarningLevel >= 4) &&
4961 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4962 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4963 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4964 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4969 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4973 foreach (Type partype in parameters){
4974 if (partype == TypeManager.void_type) {
4976 1547, Location, "Keyword 'void' cannot " +
4977 "be used in this context");
4981 if (partype.IsPointer){
4984 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4988 if (ds.AsAccessible (partype, ModFlags))
4991 if (this is Indexer)
4992 Report.Error (55, Location,
4993 "Inconsistent accessibility: parameter type `" +
4994 TypeManager.CSharpName (partype) + "' is less " +
4995 "accessible than indexer `" + Name + "'");
4996 else if ((this is Method) && ((Method) this).IsOperator)
4997 Report.Error (57, Location,
4998 "Inconsistent accessibility: parameter type `" +
4999 TypeManager.CSharpName (partype) + "' is less " +
5000 "accessible than operator `" + Name + "'");
5002 Report.Error (51, Location,
5003 "Inconsistent accessibility: parameter type `" +
5004 TypeManager.CSharpName (partype) + "' is less " +
5005 "accessible than method `" + Name + "'");
5012 protected virtual bool DoDefine ()
5014 EmitContext ec = Parent.EmitContext;
5016 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5019 throw new InternalErrorException ();
5022 ModFlags = Modifiers.PUBLIC |
5023 Modifiers.ABSTRACT |
5024 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5026 flags = MethodAttributes.Public |
5027 MethodAttributes.Abstract |
5028 MethodAttributes.HideBySig |
5029 MethodAttributes.NewSlot |
5030 MethodAttributes.Virtual;
5032 if (!Parent.MethodModifiersValid (this))
5035 flags = Modifiers.MethodAttr (ModFlags);
5038 if (MemberType == null)
5041 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5042 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5043 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5048 // verify accessibility
5049 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5050 Report.SymbolRelatedToPreviousError (MemberType);
5051 if (this is Property)
5052 Report.Error (53, Location,
5053 "Inconsistent accessibility: property type `" +
5054 TypeManager.CSharpName (MemberType) + "' is less " +
5055 "accessible than property `" + GetSignatureForError () + "'");
5056 else if (this is Indexer)
5057 Report.Error (54, Location,
5058 "Inconsistent accessibility: indexer return type `" +
5059 TypeManager.CSharpName (MemberType) + "' is less " +
5060 "accessible than indexer `" + Name + "'");
5061 else if (this is MethodCore) {
5062 if (this is Operator)
5063 Report.Error (56, Location,
5064 "Inconsistent accessibility: return type `" +
5065 TypeManager.CSharpName (MemberType) + "' is less " +
5066 "accessible than operator `" + Name + "'");
5068 Report.Error (50, Location,
5069 "Inconsistent accessibility: return type `" +
5070 TypeManager.CSharpName (MemberType) + "' is less " +
5071 "accessible than method `" + Name + "'");
5073 Report.Error (52, Location,
5074 "Inconsistent accessibility: field type `" +
5075 TypeManager.CSharpName (MemberType) + "' is less " +
5076 "accessible than field `" + Name + "'");
5081 if (MemberType.IsPointer && !UnsafeOK (Parent))
5084 if (IsExplicitImpl) {
5085 Expression expr = MemberName.Left.GetTypeExpression (Location);
5086 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5090 InterfaceType = texpr.ResolveType (ec);
5092 if (!InterfaceType.IsInterface) {
5093 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5097 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5100 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5106 public override string GetSignatureForError (TypeContainer tc)
5108 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5111 protected bool IsTypePermitted ()
5113 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5114 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5120 protected override bool VerifyClsCompliance(DeclSpace ds)
5122 if (base.VerifyClsCompliance (ds)) {
5126 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5127 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5132 protected override void VerifyObsoleteAttribute()
5134 CheckUsageOfObsoleteAttribute (MemberType);
5139 // Fields and Events both generate FieldBuilders, we use this to share
5140 // their common bits. This is also used to flag usage of the field
5142 abstract public class FieldBase : MemberBase {
5143 public FieldBuilder FieldBuilder;
5144 public Status status;
5147 public enum Status : byte {
5149 HAS_OFFSET = 4 // Used by FieldMember.
5152 static string[] attribute_targets = new string [] { "field" };
5155 /// Symbol with same name in base class/struct
5157 public MemberInfo conflict_symbol;
5160 // The constructor is only exposed to our children
5162 protected FieldBase (TypeContainer parent, Expression type, int mod,
5163 int allowed_mod, MemberName name, object init,
5164 Attributes attrs, Location loc)
5165 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5171 public override AttributeTargets AttributeTargets {
5173 return AttributeTargets.Field;
5177 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5179 if (a.Type == TypeManager.marshal_as_attr_type) {
5180 UnmanagedMarshal marshal = a.GetMarshal (this);
5181 if (marshal != null) {
5182 FieldBuilder.SetMarshal (marshal);
5187 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5188 a.Error_InvalidSecurityParent ();
5192 FieldBuilder.SetCustomAttribute (cb);
5196 // Whether this field has an initializer.
5198 public bool HasInitializer {
5200 return init != null;
5204 protected readonly Object init;
5207 Expression init_expr;
5208 bool init_expr_initialized = false;
5211 // Resolves and returns the field initializer.
5213 public Expression GetInitializerExpression (EmitContext ec)
5215 if (init_expr_initialized)
5219 if (init is Expression)
5220 e = (Expression) init;
5222 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5224 EmitContext parent_ec = Parent.EmitContext;
5226 bool old_is_static = parent_ec.IsStatic;
5227 parent_ec.IsStatic = ec.IsStatic;
5228 parent_ec.IsFieldInitializer = true;
5229 e = e.DoResolve (parent_ec);
5230 parent_ec.IsFieldInitializer = false;
5231 parent_ec.IsStatic = old_is_static;
5234 init_expr_initialized = true;
5239 protected override bool CheckBase ()
5241 if (!base.CheckBase ())
5248 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5249 if (conflict_symbol == null) {
5250 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5251 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5256 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5257 Report.SymbolRelatedToPreviousError (conflict_symbol);
5258 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5264 public override string GetSignatureForError ()
5266 if (FieldBuilder == null) {
5267 return base.GetSignatureForError (Parent);
5269 return TypeManager.GetFullNameSignature (FieldBuilder);
5272 protected virtual bool IsFieldClsCompliant {
5274 if (FieldBuilder == null)
5277 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5281 public override string[] ValidAttributeTargets {
5283 return attribute_targets;
5287 protected override bool VerifyClsCompliance (DeclSpace ds)
5289 if (!base.VerifyClsCompliance (ds))
5292 if (!IsFieldClsCompliant) {
5293 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5299 public void SetAssigned ()
5301 status |= Status.ASSIGNED;
5305 public abstract class FieldMember: FieldBase
5307 protected FieldMember (TypeContainer parent, Expression type, int mod,
5308 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5309 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5311 if ((mod & Modifiers.ABSTRACT) != 0)
5312 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5315 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5317 if (a.Type == TypeManager.field_offset_attribute_type)
5319 status |= Status.HAS_OFFSET;
5321 if (!Parent.HasExplicitLayout) {
5322 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5326 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5327 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5333 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5334 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5339 base.ApplyAttributeBuilder (a, cb);
5343 public override bool Define()
5345 EmitContext ec = Parent.EmitContext;
5347 throw new InternalErrorException ("FieldMember.Define called too early");
5349 if (MemberType == null)
5352 if (MemberType == TypeManager.void_type) {
5353 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5360 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5361 Report.Error (52, Location,
5362 "Inconsistent accessibility: field type `" +
5363 TypeManager.CSharpName (MemberType) + "' is less " +
5364 "accessible than field `" + Name + "'");
5368 if (!IsTypePermitted ())
5371 if (MemberType.IsPointer && !UnsafeOK (Parent))
5377 public override void Emit ()
5379 if (OptAttributes != null) {
5380 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5381 OptAttributes.Emit (ec, this);
5384 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5385 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5392 // Represents header string for documentation comment.
5394 public override string DocCommentHeader {
5395 get { return "F:"; }
5399 interface IFixedBuffer
5401 FieldInfo Element { get; }
5402 Type ElementType { get; }
5405 public class FixedFieldExternal: IFixedBuffer
5407 FieldInfo element_field;
5409 public FixedFieldExternal (FieldInfo fi)
5411 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5414 #region IFixedField Members
5416 public FieldInfo Element {
5418 return element_field;
5422 public Type ElementType {
5424 return element_field.FieldType;
5432 /// Fixed buffer implementation
5434 public class FixedField: FieldMember, IFixedBuffer
5436 public const string FixedElementName = "FixedElementField";
5437 static int GlobalCounter = 0;
5438 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5439 static FieldInfo[] fi;
5441 TypeBuilder fixed_buffer_type;
5442 FieldBuilder element;
5443 Expression size_expr;
5446 const int AllowedModifiers =
5449 Modifiers.PROTECTED |
5450 Modifiers.INTERNAL |
5453 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5454 Expression size_expr, Attributes attrs, Location loc):
5455 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5457 if (RootContext.Version == LanguageVersion.ISO_1)
5458 Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
5460 this.size_expr = size_expr;
5463 public override bool Define()
5466 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5467 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5470 if (Parent.Kind != Kind.Struct) {
5471 Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
5475 if (!base.Define ())
5478 if (!TypeManager.IsPrimitiveType (MemberType)) {
5479 Report.Error (1663, Location, "Fixed sized buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double");
5483 Expression e = size_expr.Resolve (Parent.EmitContext);
5487 Constant c = e as Constant;
5489 Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
5493 IntConstant buffer_size_const = c.ToInt (Location);
5494 if (buffer_size_const == null)
5497 buffer_size = buffer_size_const.Value;
5499 if (buffer_size <= 0) {
5500 Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
5504 int type_size = Expression.GetTypeSize (MemberType);
5506 if (buffer_size > int.MaxValue / type_size) {
5507 Report.Error (1664, Location, "Fixed sized buffer of length '{0}' and type '{1}' exceeded 2^31 limit",
5508 buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5512 buffer_size *= type_size;
5515 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5517 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5518 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5519 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5520 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5522 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5523 TypeManager.RegisterFieldBase (FieldBuilder, this);
5528 public override void Emit()
5531 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5533 object[] fi_val = new object[1];
5534 fi_val [0] = buffer_size;
5536 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5537 ctor_args, fi, fi_val);
5538 fixed_buffer_type.SetCustomAttribute (cab);
5541 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5542 FieldBuilder.SetCustomAttribute (cab);
5547 protected override bool IsFieldClsCompliant {
5553 #region IFixedField Members
5555 public FieldInfo Element {
5561 public Type ElementType {
5571 // The Field class is used to represents class/struct fields during parsing.
5573 public class Field : FieldMember {
5575 // Modifiers allowed in a class declaration
5577 const int AllowedModifiers =
5580 Modifiers.PROTECTED |
5581 Modifiers.INTERNAL |
5584 Modifiers.VOLATILE |
5588 public Field (TypeContainer parent, Expression type, int mod, string name,
5589 Object expr_or_array_init, Attributes attrs, Location loc)
5590 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5591 expr_or_array_init, attrs, loc)
5595 public override bool Define ()
5597 if (!base.Define ())
5600 if (RootContext.WarningLevel > 1){
5601 Type ptype = Parent.TypeBuilder.BaseType;
5603 // ptype is only null for System.Object while compiling corlib.
5605 TypeContainer.FindMembers (
5606 ptype, MemberTypes.Method,
5607 BindingFlags.Public |
5608 BindingFlags.Static | BindingFlags.Instance,
5609 System.Type.FilterName, Name);
5613 if ((ModFlags & Modifiers.VOLATILE) != 0){
5614 if (!MemberType.IsClass){
5615 Type vt = MemberType;
5617 if (TypeManager.IsEnumType (vt))
5618 vt = TypeManager.EnumToUnderlying (MemberType);
5620 if (!((vt == TypeManager.bool_type) ||
5621 (vt == TypeManager.sbyte_type) ||
5622 (vt == TypeManager.byte_type) ||
5623 (vt == TypeManager.short_type) ||
5624 (vt == TypeManager.ushort_type) ||
5625 (vt == TypeManager.int32_type) ||
5626 (vt == TypeManager.uint32_type) ||
5627 (vt == TypeManager.char_type) ||
5628 (vt == TypeManager.float_type) ||
5629 (!vt.IsValueType))){
5631 677, Location, Parent.MakeName (Name) +
5632 " A volatile field can not be of type `" +
5633 TypeManager.CSharpName (vt) + "'");
5638 if ((ModFlags & Modifiers.READONLY) != 0){
5641 "A field can not be both volatile and readonly");
5646 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5648 if (Parent.Kind == Kind.Struct &&
5649 ((fa & FieldAttributes.Static) == 0) &&
5650 MemberType == Parent.TypeBuilder &&
5651 !TypeManager.IsBuiltinType (MemberType)){
5652 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5653 "' causes a cycle in the structure layout");
5658 FieldBuilder = Parent.TypeBuilder.DefineField (
5659 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5661 TypeManager.RegisterFieldBase (FieldBuilder, this);
5663 catch (ArgumentException) {
5664 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5673 // `set' and `get' accessors are represented with an Accessor.
5675 public class Accessor {
5677 // Null if the accessor is empty, or a Block if not
5679 public const int AllowedModifiers =
5681 Modifiers.PROTECTED |
5682 Modifiers.INTERNAL |
5685 public ToplevelBlock Block;
5686 public Attributes Attributes;
5687 public Location Location;
5688 public int ModFlags;
5690 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5695 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5700 // Ooouh Martin, templates are missing here.
5701 // When it will be possible move here a lot of child code and template method type.
5702 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5703 protected MethodData method_data;
5704 protected ToplevelBlock block;
5705 protected ListDictionary declarative_security;
5707 // The accessor are created event if they are not wanted.
5708 // But we need them because their names are reserved.
5709 // Field says whether accessor will be emited or not
5710 public readonly bool IsDummy;
5712 protected readonly string prefix;
5714 ReturnParameter return_attributes;
5716 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5717 : base (null, SetupName (prefix, member), null, member.Location)
5719 this.prefix = prefix;
5723 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5725 : base (null, SetupName (prefix, member),
5726 accessor.Attributes, accessor.Location)
5728 this.prefix = prefix;
5729 this.block = accessor.Block;
5732 static MemberName SetupName (string prefix, MemberBase member)
5734 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
5737 public void UpdateName (MemberBase member)
5739 SetMemberName (SetupName (prefix, member));
5742 #region IMethodData Members
5744 public ToplevelBlock Block {
5754 public CallingConventions CallingConventions {
5756 return CallingConventions.Standard;
5760 public bool IsExcluded (EmitContext ec)
5765 public MemberName MethodName {
5771 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5772 public abstract Type[] ParameterTypes { get; }
5773 public abstract Type ReturnType { get; }
5774 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5778 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5780 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5781 a.Type == TypeManager.conditional_attribute_type) {
5782 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 ());
5786 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5787 if (declarative_security == null)
5788 declarative_security = new ListDictionary ();
5789 a.ExtractSecurityPermissionSet (declarative_security);
5793 if (a.Target == AttributeTargets.Method) {
5794 method_data.MethodBuilder.SetCustomAttribute (cb);
5798 if (a.Target == AttributeTargets.ReturnValue) {
5799 if (return_attributes == null)
5800 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5802 return_attributes.ApplyAttributeBuilder (a, cb);
5806 ApplyToExtraTarget (a, cb);
5809 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5811 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5814 public override bool Define()
5816 throw new NotSupportedException ();
5819 public virtual void Emit (TypeContainer container)
5821 EmitMethod (container);
5823 if (declarative_security != null) {
5824 foreach (DictionaryEntry de in declarative_security) {
5825 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5832 protected virtual void EmitMethod (TypeContainer container)
5834 method_data.Emit (container, this);
5837 public override bool IsClsCompliaceRequired(DeclSpace ds)
5842 public bool IsDuplicateImplementation (MethodCore method)
5844 if (Name != method.Name)
5847 Type[] param_types = method.ParameterTypes;
5849 if (param_types.Length != ParameterTypes.Length)
5852 for (int i = 0; i < param_types.Length; i++)
5853 if (param_types [i] != ParameterTypes [i])
5856 Report.SymbolRelatedToPreviousError (method);
5857 Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
5861 public override bool IsUsed
5871 public new Location Location {
5873 return base.Location;
5878 // Represents header string for documentation comment.
5880 public override string DocCommentHeader {
5881 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5884 protected override void VerifyObsoleteAttribute()
5891 // Properties and Indexers both generate PropertyBuilders, we use this to share
5892 // their common bits.
5894 abstract public class PropertyBase : MethodCore {
5896 public class GetMethod: PropertyMethod
5898 static string[] attribute_targets = new string [] { "method", "return" };
5900 public GetMethod (MethodCore method):
5901 base (method, "get_")
5905 public GetMethod (MethodCore method, Accessor accessor):
5906 base (method, accessor, "get_")
5910 public override MethodBuilder Define(TypeContainer container)
5912 base.Define (container);
5914 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5916 if (!method_data.Define (container))
5919 return method_data.MethodBuilder;
5922 public override string GetSignatureForError (TypeContainer tc)
5924 return String.Concat (base.GetSignatureForError (tc), ".get");
5927 public override Type ReturnType {
5929 return method.MemberType;
5933 public override string[] ValidAttributeTargets {
5935 return attribute_targets;
5940 public class SetMethod: PropertyMethod {
5942 static string[] attribute_targets = new string [] { "method", "param", "return" };
5943 ImplicitParameter param_attr;
5945 public SetMethod (MethodCore method):
5946 base (method, "set_")
5950 public SetMethod (MethodCore method, Accessor accessor):
5951 base (method, accessor, "set_")
5955 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5957 if (a.Target == AttributeTargets.Parameter) {
5958 if (param_attr == null)
5959 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5961 param_attr.ApplyAttributeBuilder (a, cb);
5965 base.ApplyAttributeBuilder (a, cb);
5968 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5970 Parameter [] parms = new Parameter [1];
5971 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
5972 Parameters parameters = new Parameters (parms, null, method.Location);
5974 bool old_unsafe = ec.InUnsafe;
5975 ec.InUnsafe = InUnsafe;
5976 Type [] types = parameters.GetParameterInfo (ec);
5977 ec.InUnsafe = old_unsafe;
5979 return new InternalParameters (types, parameters);
5982 public override MethodBuilder Define (TypeContainer container)
5984 if (container.EmitContext == null)
5985 throw new InternalErrorException ("SetMethod.Define called too early");
5987 base.Define (container);
5989 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5991 if (!method_data.Define (container))
5994 return method_data.MethodBuilder;
5997 public override string GetSignatureForError (TypeContainer tc)
5999 return String.Concat (base.GetSignatureForError (tc), ".set");
6002 public override Type[] ParameterTypes {
6004 return new Type[] { method.MemberType };
6008 public override Type ReturnType {
6010 return TypeManager.void_type;
6014 public override string[] ValidAttributeTargets {
6016 return attribute_targets;
6021 static string[] attribute_targets = new string [] { "property" };
6023 public abstract class PropertyMethod: AbstractPropertyEventMethod
6025 protected readonly MethodCore method;
6026 protected MethodAttributes flags;
6028 public PropertyMethod (MethodCore method, string prefix)
6029 : base (method, prefix)
6031 this.method = method;
6032 Parent = method.Parent;
6035 public PropertyMethod (MethodCore method, Accessor accessor,
6037 : base (method, accessor, prefix)
6039 this.method = method;
6040 Parent = method.Parent;
6041 this.ModFlags = accessor.ModFlags;
6043 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6044 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
6048 public override AttributeTargets AttributeTargets {
6050 return AttributeTargets.Method;
6054 public override bool IsClsCompliaceRequired(DeclSpace ds)
6056 return method.IsClsCompliaceRequired (ds);
6059 public InternalParameters ParameterInfo
6062 return method_data.ParameterInfo;
6066 public virtual MethodBuilder Define (TypeContainer container)
6069 // Check for custom access modifier
6071 if (ModFlags == 0) {
6072 ModFlags = method.ModFlags;
6073 flags = method.flags;
6075 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6076 Report.Error (442, Location, "{0}': abstract properties cannot have private accessors", GetSignatureForError (container));
6079 CheckModifiers (container, ModFlags);
6080 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6081 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6082 flags = Modifiers.MethodAttr (ModFlags);
6083 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6090 public bool HasCustomAccessModifier
6093 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6097 public override Type[] ParameterTypes {
6099 return TypeManager.NoTypes;
6103 public override EmitContext CreateEmitContext (TypeContainer tc,
6106 return new EmitContext (
6107 tc, method.Parent, method.Location, ig, ReturnType,
6108 method.ModFlags, false);
6111 public override ObsoleteAttribute GetObsoleteAttribute ()
6113 return method.GetObsoleteAttribute (method.Parent);
6116 public override string GetSignatureForError (TypeContainer tc)
6118 return String.Concat (tc.Name, '.', method.Name);
6121 void CheckModifiers (TypeContainer container, int modflags)
6124 int mflags = method.ModFlags & Modifiers.Accessibility;
6126 if ((mflags & Modifiers.PUBLIC) != 0) {
6127 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6129 else if ((mflags & Modifiers.PROTECTED) != 0) {
6130 if ((mflags & Modifiers.INTERNAL) != 0)
6131 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6133 flags |= Modifiers.PRIVATE;
6135 else if ((mflags & Modifiers.INTERNAL) != 0)
6136 flags |= Modifiers.PRIVATE;
6138 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6139 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6140 GetSignatureForError (container));
6143 public override bool MarkForDuplicationCheck ()
6145 caching_flags |= Flags.TestMethodDuplication;
6151 public PropertyMethod Get, Set;
6152 public PropertyBuilder PropertyBuilder;
6153 public MethodBuilder GetBuilder, SetBuilder;
6155 protected EmitContext ec;
6157 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6158 int allowed_mod, bool is_iface, MemberName name,
6159 Parameters parameters, Attributes attrs,
6161 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6162 attrs, parameters, loc)
6166 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6168 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6169 a.Error_InvalidSecurityParent ();
6173 PropertyBuilder.SetCustomAttribute (cb);
6176 public override AttributeTargets AttributeTargets {
6178 return AttributeTargets.Property;
6182 public override bool Define ()
6187 if (!IsTypePermitted ())
6193 protected override bool DoDefine ()
6195 if (!base.DoDefine ())
6199 // Accessors modifiers check
6201 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6202 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6203 GetSignatureForError ());
6207 if ((Get.IsDummy || Set.IsDummy)
6208 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6209 Report.Error (276, Location,
6210 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6211 GetSignatureForError ());
6215 if (MemberType.IsAbstract && MemberType.IsSealed) {
6216 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6220 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6224 public override string GetSignatureForError()
6226 if (PropertyBuilder == null)
6227 return GetSignatureForError (Parent);
6229 return TypeManager.CSharpSignature (PropertyBuilder, false);
6232 protected override bool CheckForDuplications ()
6234 ArrayList ar = Parent.Indexers;
6236 int arLen = ar.Count;
6238 for (int i = 0; i < arLen; i++) {
6239 Indexer m = (Indexer) ar [i];
6240 if (IsDuplicateImplementation (m))
6245 ar = Parent.Properties;
6247 int arLen = ar.Count;
6249 for (int i = 0; i < arLen; i++) {
6250 Property m = (Property) ar [i];
6251 if (IsDuplicateImplementation (m))
6259 // TODO: rename to Resolve......
6260 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6262 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6263 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6265 if (base_property == null)
6268 base_ret_type = base_property.PropertyType;
6269 MethodInfo get_accessor = base_property.GetGetMethod (true);
6270 MethodInfo set_accessor = base_property.GetSetMethod (true);
6271 MethodAttributes get_accessor_access, set_accessor_access;
6273 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6274 if (Get != null && !Get.IsDummy && get_accessor == null) {
6275 Report.SymbolRelatedToPreviousError (base_property);
6276 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6279 if (Set != null && !Set.IsDummy && set_accessor == null) {
6280 Report.SymbolRelatedToPreviousError (base_property);
6281 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6286 // Check base class accessors access
6288 get_accessor_access = set_accessor_access = 0;
6289 if ((ModFlags & Modifiers.NEW) == 0) {
6290 if (get_accessor != null) {
6291 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6292 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6294 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6295 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6296 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6299 if (set_accessor != null) {
6300 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6301 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6303 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6304 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6305 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6310 // Get the less restrictive access
6312 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6315 public override void Emit ()
6318 // The PropertyBuilder can be null for explicit implementations, in that
6319 // case, we do not actually emit the ".property", so there is nowhere to
6320 // put the attribute
6322 if (PropertyBuilder != null && OptAttributes != null)
6323 OptAttributes.Emit (ec, this);
6335 /// Tests whether accessors are not in collision with some method (CS0111)
6337 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6339 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6342 public override bool IsUsed
6348 return Get.IsUsed | Set.IsUsed;
6352 protected override void SetMemberName (MemberName new_name)
6354 base.SetMemberName (new_name);
6356 Get.UpdateName (this);
6357 Set.UpdateName (this);
6360 protected override bool VerifyClsCompliance (DeclSpace ds)
6362 if (!base.VerifyClsCompliance (ds))
6365 if ((Get.ModFlags != ModFlags && !Get.IsDummy) || (Set.ModFlags != ModFlags && !Set.IsDummy)) {
6366 Report.Error (3025, Get.ModFlags != ModFlags ? Get.Location : Set.Location,
6367 "CLS-compliant accessors must have the same accessibility as their property");
6372 public override string[] ValidAttributeTargets {
6374 return attribute_targets;
6379 // Represents header string for documentation comment.
6381 public override string DocCommentHeader {
6382 get { return "P:"; }
6386 public class Property : PropertyBase, IIteratorContainer {
6387 const int AllowedModifiers =
6390 Modifiers.PROTECTED |
6391 Modifiers.INTERNAL |
6395 Modifiers.OVERRIDE |
6396 Modifiers.ABSTRACT |
6399 Modifiers.METHOD_YIELDS |
6402 const int AllowedInterfaceModifiers =
6405 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6406 MemberName name, Attributes attrs, Accessor get_block,
6407 Accessor set_block, Location loc)
6408 : base (ds, type, mod,
6409 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6410 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6413 if (get_block == null)
6414 Get = new GetMethod (this);
6416 Get = new GetMethod (this, get_block);
6418 if (set_block == null)
6419 Set = new SetMethod (this);
6421 Set = new SetMethod (this, set_block);
6424 public override bool Define ()
6426 if (!base.Define ())
6432 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6436 GetBuilder = Get.Define (Parent);
6437 if (GetBuilder == null)
6441 // Setup iterator if we are one
6443 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6444 Iterator iterator = new Iterator (
6445 Parent, "get", MemberType,
6447 ModFlags, Get.Block, Location);
6449 if (!iterator.DefineIterator ())
6451 Get.Block = iterator.Block;
6456 SetBuilder = Set.Define (Parent);
6457 if (SetBuilder == null)
6460 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6463 // FIXME - PropertyAttributes.HasDefault ?
6465 PropertyAttributes prop_attr = PropertyAttributes.None;
6467 prop_attr |= PropertyAttributes.RTSpecialName |
6468 PropertyAttributes.SpecialName;
6470 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6471 Name, prop_attr, MemberType, null);
6474 PropertyBuilder.SetGetMethod (GetBuilder);
6477 PropertyBuilder.SetSetMethod (SetBuilder);
6479 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6483 public void SetYields ()
6485 ModFlags |= Modifiers.METHOD_YIELDS;
6490 /// Gigantic workaround for lameness in SRE follows :
6491 /// This class derives from EventInfo and attempts to basically
6492 /// wrap around the EventBuilder so that FindMembers can quickly
6493 /// return this in it search for members
6495 public class MyEventBuilder : EventInfo {
6498 // We use this to "point" to our Builder which is
6499 // not really a MemberInfo
6501 EventBuilder MyBuilder;
6504 // We "catch" and wrap these methods
6506 MethodInfo raise, remove, add;
6508 EventAttributes attributes;
6509 Type declaring_type, reflected_type, event_type;
6514 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6516 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6518 // And now store the values in our own fields.
6520 declaring_type = type_builder;
6522 reflected_type = type_builder;
6524 attributes = event_attr;
6527 this.event_type = event_type;
6531 // Methods that you have to override. Note that you only need
6532 // to "implement" the variants that take the argument (those are
6533 // the "abstract" methods, the others (GetAddMethod()) are
6536 public override MethodInfo GetAddMethod (bool nonPublic)
6541 public override MethodInfo GetRemoveMethod (bool nonPublic)
6546 public override MethodInfo GetRaiseMethod (bool nonPublic)
6552 // These methods make "MyEventInfo" look like a Builder
6554 public void SetRaiseMethod (MethodBuilder raiseMethod)
6556 raise = raiseMethod;
6557 MyBuilder.SetRaiseMethod (raiseMethod);
6560 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6562 remove = removeMethod;
6563 MyBuilder.SetRemoveOnMethod (removeMethod);
6566 public void SetAddOnMethod (MethodBuilder addMethod)
6569 MyBuilder.SetAddOnMethod (addMethod);
6572 public void SetCustomAttribute (CustomAttributeBuilder cb)
6574 MyBuilder.SetCustomAttribute (cb);
6577 public override object [] GetCustomAttributes (bool inherit)
6579 // FIXME : There's nothing which can be seemingly done here because
6580 // we have no way of getting at the custom attribute objects of the
6585 public override object [] GetCustomAttributes (Type t, bool inherit)
6587 // FIXME : Same here !
6591 public override bool IsDefined (Type t, bool b)
6596 public override EventAttributes Attributes {
6602 public override string Name {
6608 public override Type DeclaringType {
6610 return declaring_type;
6614 public override Type ReflectedType {
6616 return reflected_type;
6620 public Type EventType {
6626 public void SetUsed ()
6628 if (my_event != null) {
6629 my_event.status = FieldBase.Status.ASSIGNED;
6630 my_event.SetMemberIsUsed ();
6636 /// For case when event is declared like property (with add and remove accessors).
6638 public class EventProperty: Event {
6640 static string[] attribute_targets = new string [] { "event", "property" };
6642 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6643 bool is_iface, MemberName name, Object init,
6644 Attributes attrs, Accessor add, Accessor remove,
6646 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6648 Add = new AddDelegateMethod (this, add);
6649 Remove = new RemoveDelegateMethod (this, remove);
6651 // For this event syntax we don't report error CS0067
6652 // because it is hard to do it.
6656 public override string[] ValidAttributeTargets {
6658 return attribute_targets;
6664 /// Event is declared like field.
6666 public class EventField: Event {
6668 static string[] attribute_targets = new string [] { "event", "field", "method" };
6669 static string[] attribute_targets_interface = new string[] { "event", "method" };
6671 public EventField (TypeContainer parent, Expression type, int mod_flags,
6672 bool is_iface, MemberName name, Object init,
6673 Attributes attrs, Location loc)
6674 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6676 Add = new AddDelegateMethod (this);
6677 Remove = new RemoveDelegateMethod (this);
6680 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6682 if (a.Target == AttributeTargets.Field) {
6683 FieldBuilder.SetCustomAttribute (cb);
6687 if (a.Target == AttributeTargets.Method) {
6688 Add.ApplyAttributeBuilder (a, cb);
6689 Remove.ApplyAttributeBuilder (a, cb);
6693 base.ApplyAttributeBuilder (a, cb);
6696 public override string[] ValidAttributeTargets {
6698 return IsInterface ? attribute_targets_interface : attribute_targets;
6703 public abstract class Event : FieldBase {
6705 protected sealed class AddDelegateMethod: DelegateMethod
6708 public AddDelegateMethod (Event method):
6709 base (method, "add_")
6713 public AddDelegateMethod (Event method, Accessor accessor):
6714 base (method, accessor, "add_")
6718 protected override MethodInfo DelegateMethodInfo {
6720 return TypeManager.delegate_combine_delegate_delegate;
6726 protected sealed class RemoveDelegateMethod: DelegateMethod
6728 public RemoveDelegateMethod (Event method):
6729 base (method, "remove_")
6733 public RemoveDelegateMethod (Event method, Accessor accessor):
6734 base (method, accessor, "remove_")
6738 protected override MethodInfo DelegateMethodInfo {
6740 return TypeManager.delegate_remove_delegate_delegate;
6746 public abstract class DelegateMethod: AbstractPropertyEventMethod
6748 protected readonly Event method;
6749 ImplicitParameter param_attr;
6751 static string[] attribute_targets = new string [] { "method", "param", "return" };
6753 public DelegateMethod (Event method, string prefix)
6754 : base (method, prefix)
6756 this.method = method;
6759 public DelegateMethod (Event method, Accessor accessor, string prefix)
6760 : base (method, accessor, prefix)
6762 this.method = method;
6765 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6767 if (a.Target == AttributeTargets.Parameter) {
6768 if (param_attr == null)
6769 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6771 param_attr.ApplyAttributeBuilder (a, cb);
6775 base.ApplyAttributeBuilder (a, cb);
6778 public override AttributeTargets AttributeTargets {
6780 return AttributeTargets.Method;
6784 public override bool IsClsCompliaceRequired(DeclSpace ds)
6786 return method.IsClsCompliaceRequired (ds);
6789 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6791 method_data = new MethodData (method, ip, method.ModFlags,
6792 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6794 if (!method_data.Define (container))
6797 MethodBuilder mb = method_data.MethodBuilder;
6798 mb.DefineParameter (1, ParameterAttributes.None, "value");
6803 protected override void EmitMethod (TypeContainer tc)
6805 if (block != null) {
6806 base.EmitMethod (tc);
6810 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6813 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6814 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6816 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6817 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6818 ig.Emit (OpCodes.Ldsfld, field_info);
6819 ig.Emit (OpCodes.Ldarg_0);
6820 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6821 ig.Emit (OpCodes.Castclass, method.MemberType);
6822 ig.Emit (OpCodes.Stsfld, field_info);
6824 ig.Emit (OpCodes.Ldarg_0);
6825 ig.Emit (OpCodes.Ldarg_0);
6826 ig.Emit (OpCodes.Ldfld, field_info);
6827 ig.Emit (OpCodes.Ldarg_1);
6828 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6829 ig.Emit (OpCodes.Castclass, method.MemberType);
6830 ig.Emit (OpCodes.Stfld, field_info);
6832 ig.Emit (OpCodes.Ret);
6835 protected abstract MethodInfo DelegateMethodInfo { get; }
6837 public override Type[] ParameterTypes {
6839 return new Type[] { method.MemberType };
6843 public override Type ReturnType {
6845 return TypeManager.void_type;
6849 public override EmitContext CreateEmitContext (TypeContainer tc,
6852 return new EmitContext (
6853 tc, method.Parent, Location, ig, ReturnType,
6854 method.ModFlags, false);
6857 public override string GetSignatureForError (TypeContainer tc)
6859 return String.Concat (tc.Name, '.', method.Name);
6862 public override ObsoleteAttribute GetObsoleteAttribute ()
6864 return method.GetObsoleteAttribute (method.Parent);
6867 public override string[] ValidAttributeTargets {
6869 return attribute_targets;
6875 const int AllowedModifiers =
6878 Modifiers.PROTECTED |
6879 Modifiers.INTERNAL |
6884 Modifiers.OVERRIDE |
6888 const int AllowedInterfaceModifiers =
6891 public DelegateMethod Add, Remove;
6892 public MyEventBuilder EventBuilder;
6893 public MethodBuilder AddBuilder, RemoveBuilder;
6895 public Event (TypeContainer parent, Expression type, int mod_flags,
6896 bool is_iface, MemberName name, Object init, Attributes attrs,
6898 : base (parent, type, mod_flags,
6899 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6900 name, init, attrs, loc)
6902 IsInterface = is_iface;
6905 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6907 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6908 a.Error_InvalidSecurityParent ();
6912 EventBuilder.SetCustomAttribute (cb);
6915 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6917 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6920 public override AttributeTargets AttributeTargets {
6922 return AttributeTargets.Event;
6926 public override bool Define ()
6928 EventAttributes e_attr;
6929 e_attr = EventAttributes.None;
6934 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6935 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6936 "': abstract event can not have an initializer");
6940 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6941 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6942 "' : event must be of a delegate type");
6946 EmitContext ec = Parent.EmitContext;
6948 throw new InternalErrorException ("Event.Define called too early?");
6949 bool old_unsafe = ec.InUnsafe;
6950 ec.InUnsafe = InUnsafe;
6952 Parameter [] parms = new Parameter [1];
6953 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6954 Parameters parameters = new Parameters (parms, null, Location);
6955 Type [] types = parameters.GetParameterInfo (ec);
6956 InternalParameters ip = new InternalParameters (types, parameters);
6958 ec.InUnsafe = old_unsafe;
6964 // Now define the accessors
6967 AddBuilder = Add.Define (Parent, ip);
6968 if (AddBuilder == null)
6971 RemoveBuilder = Remove.Define (Parent, ip);
6972 if (RemoveBuilder == null)
6975 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6977 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6978 FieldBuilder = Parent.TypeBuilder.DefineField (
6980 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6981 TypeManager.RegisterPrivateFieldOfEvent (
6982 (EventInfo) EventBuilder, FieldBuilder);
6983 TypeManager.RegisterFieldBase (FieldBuilder, this);
6986 EventBuilder.SetAddOnMethod (AddBuilder);
6987 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6989 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6993 protected override bool CheckBase ()
6995 if (!base.CheckBase ())
6998 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6999 if (!(conflict_symbol is EventInfo)) {
7000 Report.SymbolRelatedToPreviousError (conflict_symbol);
7001 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
7009 public override void Emit ()
7011 if (OptAttributes != null) {
7012 EmitContext ec = new EmitContext (
7013 Parent, Location, null, MemberType, ModFlags);
7014 OptAttributes.Emit (ec, this);
7018 Remove.Emit (Parent);
7023 public override string GetSignatureForError ()
7025 if (EventBuilder == null)
7026 return base.GetSignatureForError (Parent);
7028 return TypeManager.GetFullNameSignature (EventBuilder);
7032 // Represents header string for documentation comment.
7034 public override string DocCommentHeader {
7035 get { return "E:"; }
7040 public class Indexer : PropertyBase {
7042 class GetIndexerMethod: GetMethod
7044 public GetIndexerMethod (MethodCore method):
7049 public GetIndexerMethod (MethodCore method, Accessor accessor):
7050 base (method, accessor)
7054 // TODO: one GetSignatureForError is enough (reuse Parent member)
7055 public override string GetSignatureForError (TypeContainer tc)
7057 string core = base.GetSignatureForError (tc);
7058 return core.Replace (TypeContainer.DefaultIndexerName,
7059 String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
7062 public override Type[] ParameterTypes {
7064 return method.ParameterTypes;
7069 class SetIndexerMethod: SetMethod
7071 readonly Parameters parameters;
7073 public SetIndexerMethod (MethodCore method):
7078 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7079 base (method, accessor)
7081 this.parameters = parameters;
7084 public override Type[] ParameterTypes {
7086 int top = method.ParameterTypes.Length;
7087 Type [] set_pars = new Type [top + 1];
7088 method.ParameterTypes.CopyTo (set_pars, 0);
7089 set_pars [top] = method.MemberType;
7094 protected override InternalParameters GetParameterInfo (EmitContext ec)
7096 Parameter [] fixed_parms = parameters.FixedParameters;
7098 if (fixed_parms == null){
7099 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7100 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7101 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7103 // Here is the problem: the `value' parameter has
7104 // to come *after* the array parameter in the declaration
7106 // X (object [] x, Type value)
7109 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7110 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7114 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7116 fixed_parms.CopyTo (tmp, 0);
7117 tmp [fixed_parms.Length] = new Parameter (
7118 method.Type, "value", Parameter.Modifier.NONE, null);
7120 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7121 Type [] types = set_formal_params.GetParameterInfo (ec);
7123 return new InternalParameters (types, set_formal_params);
7128 const int AllowedModifiers =
7131 Modifiers.PROTECTED |
7132 Modifiers.INTERNAL |
7136 Modifiers.OVERRIDE |
7141 const int AllowedInterfaceModifiers =
7145 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7146 bool is_iface, Parameters parameters, Attributes attrs,
7147 Accessor get_block, Accessor set_block, Location loc)
7148 : base (ds, type, mod,
7149 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7150 is_iface, name, parameters, attrs, loc)
7152 if (get_block == null)
7153 Get = new GetIndexerMethod (this);
7155 Get = new GetIndexerMethod (this, get_block);
7157 if (set_block == null)
7158 Set = new SetIndexerMethod (this);
7160 Set = new SetIndexerMethod (this, parameters, set_block);
7163 public override bool Define ()
7165 PropertyAttributes prop_attr =
7166 PropertyAttributes.RTSpecialName |
7167 PropertyAttributes.SpecialName;
7169 if (!base.Define ())
7172 if (MemberType == TypeManager.void_type) {
7173 Report.Error (620, Location, "Indexers cannot have void type");
7177 if (OptAttributes != null) {
7178 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7179 if (indexer_attr != null) {
7180 // Remove the attribute from the list because it is not emitted
7181 OptAttributes.Attrs.Remove (indexer_attr);
7183 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7185 if (IsExplicitImpl) {
7186 Report.Error (415, indexer_attr.Location,
7187 "The 'IndexerName' attribute is valid only on an " +
7188 "indexer that is not an explicit interface member declaration");
7192 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7193 Report.Error (609, indexer_attr.Location,
7194 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7198 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7199 Report.Error (633, indexer_attr.Location,
7200 "The argument to the 'IndexerName' attribute must be a valid identifier");
7206 if (InterfaceType != null) {
7207 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7208 if (base_IndexerName != Name)
7209 ShortName = base_IndexerName;
7212 if (!Parent.AddToMemberContainer (this) ||
7213 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7219 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7221 GetBuilder = Get.Define (Parent);
7222 if (GetBuilder == null)
7227 SetBuilder = Set.Define (Parent);
7228 if (SetBuilder == null)
7233 // Now name the parameters
7235 Parameter [] p = Parameters.FixedParameters;
7237 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7238 Report.Error (631, Location, "ref and out are not valid in this context");
7244 for (i = 0; i < p.Length; ++i) {
7246 GetBuilder.DefineParameter (
7247 i + 1, p [i].Attributes, p [i].Name);
7250 SetBuilder.DefineParameter (
7251 i + 1, p [i].Attributes, p [i].Name);
7255 SetBuilder.DefineParameter (
7256 i + 1, ParameterAttributes.None, "value");
7258 if (i != ParameterTypes.Length) {
7259 Parameter array_param = Parameters.ArrayParameter;
7261 SetBuilder.DefineParameter (
7262 i + 1, array_param.Attributes, array_param.Name);
7266 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7267 Name, prop_attr, MemberType, ParameterTypes);
7270 PropertyBuilder.SetGetMethod (GetBuilder);
7273 PropertyBuilder.SetSetMethod (SetBuilder);
7275 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7280 public override string GetSignatureForError ()
7282 if (PropertyBuilder == null)
7283 return GetSignatureForError (Parent);
7285 return TypeManager.CSharpSignature (PropertyBuilder, true);
7288 public override string GetSignatureForError(TypeContainer tc)
7290 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7293 public override bool MarkForDuplicationCheck ()
7295 caching_flags |= Flags.TestMethodDuplication;
7301 public class Operator : MethodCore, IIteratorContainer {
7303 const int AllowedModifiers =
7309 public enum OpType : byte {
7319 // Unary and Binary operators
7342 // Implicit and Explicit
7347 public readonly OpType OperatorType;
7348 public MethodBuilder OperatorMethodBuilder;
7350 public Method OperatorMethod;
7352 static string[] attribute_targets = new string [] { "method", "return" };
7354 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7355 int mod_flags, Parameters parameters,
7356 ToplevelBlock block, Attributes attrs, Location loc)
7357 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7358 new MemberName ("op_" + type), attrs, parameters, loc)
7360 OperatorType = type;
7364 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7366 OperatorMethod.ApplyAttributeBuilder (a, cb);
7369 public override AttributeTargets AttributeTargets {
7371 return AttributeTargets.Method;
7375 protected override bool CheckForDuplications()
7377 ArrayList ar = Parent.Operators;
7379 int arLen = ar.Count;
7381 for (int i = 0; i < arLen; i++) {
7382 Operator o = (Operator) ar [i];
7383 if (IsDuplicateImplementation (o))
7388 ar = Parent.Methods;
7390 int arLen = ar.Count;
7392 for (int i = 0; i < arLen; i++) {
7393 Method m = (Method) ar [i];
7394 if (IsDuplicateImplementation (m))
7402 public override bool Define ()
7405 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7406 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7407 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7414 if (MemberType == TypeManager.void_type) {
7415 Report.Error (590, Location, "User-defined operators cannot return void");
7419 OperatorMethod = new Method (
7420 Parent, Type, ModFlags, false, MemberName,
7421 Parameters, OptAttributes, Location);
7423 OperatorMethod.Block = Block;
7424 OperatorMethod.IsOperator = true;
7425 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7426 OperatorMethod.Define ();
7428 if (OperatorMethod.MethodBuilder == null)
7431 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7433 parameter_types = OperatorMethod.ParameterTypes;
7434 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7435 Type return_type = OperatorMethod.ReturnType;
7436 Type first_arg_type = parameter_types [0];
7441 // Rules for conversion operators
7443 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7444 if (first_arg_type == return_type && first_arg_type == declaring_type){
7447 "User-defined conversion cannot take an object of the " +
7448 "enclosing type and convert to an object of the enclosing" +
7453 if (first_arg_type != declaring_type && return_type != declaring_type){
7456 "User-defined conversion must convert to or from the " +
7461 if (first_arg_type == TypeManager.object_type ||
7462 return_type == TypeManager.object_type){
7465 "User-defined conversion cannot convert to or from " +
7470 if (first_arg_type.IsInterface || return_type.IsInterface){
7473 "User-defined conversion cannot convert to or from an " +
7478 if (first_arg_type.IsSubclassOf (return_type)
7479 || return_type.IsSubclassOf (first_arg_type)){
7480 if (declaring_type.IsSubclassOf (return_type)) {
7481 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7484 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7487 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7488 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7489 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");
7492 } else if (Parameters.FixedParameters.Length == 1) {
7493 // Checks for Unary operators
7495 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7496 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7497 Report.Error (448, Location,
7498 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7501 if (first_arg_type != declaring_type) {
7503 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7508 if (first_arg_type != declaring_type){
7511 "The parameter of a unary operator must be the " +
7516 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7517 if (return_type != TypeManager.bool_type){
7520 "The return type of operator True or False " +
7527 // Checks for Binary operators
7529 if (first_arg_type != declaring_type &&
7530 parameter_types [1] != declaring_type){
7533 "One of the parameters of a binary operator must " +
7534 "be the containing type");
7542 public override void Emit ()
7545 // abstract or extern methods have no bodies
7547 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7550 OperatorMethod.Emit ();
7554 // Operator cannot be override
7555 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7560 public static string GetName (OpType ot)
7563 case OpType.LogicalNot:
7565 case OpType.OnesComplement:
7567 case OpType.Increment:
7569 case OpType.Decrement:
7575 case OpType.Addition:
7577 case OpType.Subtraction:
7579 case OpType.UnaryPlus:
7581 case OpType.UnaryNegation:
7583 case OpType.Multiply:
7585 case OpType.Division:
7587 case OpType.Modulus:
7589 case OpType.BitwiseAnd:
7591 case OpType.BitwiseOr:
7593 case OpType.ExclusiveOr:
7595 case OpType.LeftShift:
7597 case OpType.RightShift:
7599 case OpType.Equality:
7601 case OpType.Inequality:
7603 case OpType.GreaterThan:
7605 case OpType.LessThan:
7607 case OpType.GreaterThanOrEqual:
7609 case OpType.LessThanOrEqual:
7611 case OpType.Implicit:
7613 case OpType.Explicit:
7619 public override string GetSignatureForError (TypeContainer tc)
7621 StringBuilder sb = new StringBuilder ();
7622 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7623 Parameters.FixedParameters [0].GetSignatureForError ());
7625 if (Parameters.FixedParameters.Length > 1) {
7627 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7630 return sb.ToString ();
7633 public override string GetSignatureForError ()
7638 public override bool MarkForDuplicationCheck ()
7640 caching_flags |= Flags.TestMethodDuplication;
7644 public override string ToString ()
7646 if (OperatorMethod == null)
7649 Type return_type = OperatorMethod.ReturnType;
7650 Type [] param_types = OperatorMethod.ParameterTypes;
7652 if (Parameters.FixedParameters.Length == 1)
7653 return String.Format (
7654 "{0} operator {1}({2})",
7655 TypeManager.CSharpName (return_type),
7656 GetName (OperatorType),
7659 return String.Format (
7660 "{0} operator {1}({2}, {3})",
7661 TypeManager.CSharpName (return_type),
7662 GetName (OperatorType),
7663 param_types [0], param_types [1]);
7666 public override string[] ValidAttributeTargets {
7668 return attribute_targets;
7672 public void SetYields ()
7674 ModFlags |= Modifiers.METHOD_YIELDS;
7679 // This is used to compare method signatures
7681 struct MethodSignature {
7683 public Type RetType;
7684 public Type [] Parameters;
7687 /// This delegate is used to extract methods which have the
7688 /// same signature as the argument
7690 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7692 public MethodSignature (string name, Type ret_type, Type [] parameters)
7697 if (parameters == null)
7698 Parameters = TypeManager.NoTypes;
7700 Parameters = parameters;
7703 public override string ToString ()
7706 if (Parameters.Length != 0){
7707 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7708 for (int i = 0; i < Parameters.Length; i++){
7709 sb.Append (Parameters [i]);
7710 if (i+1 < Parameters.Length)
7713 pars = sb.ToString ();
7716 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7719 public override int GetHashCode ()
7721 return Name.GetHashCode ();
7724 public override bool Equals (Object o)
7726 MethodSignature other = (MethodSignature) o;
7728 if (other.Name != Name)
7731 if (other.RetType != RetType)
7734 if (Parameters == null){
7735 if (other.Parameters == null)
7740 if (other.Parameters == null)
7743 int c = Parameters.Length;
7744 if (other.Parameters.Length != c)
7747 for (int i = 0; i < c; i++)
7748 if (other.Parameters [i] != Parameters [i])
7754 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7756 MethodSignature sig = (MethodSignature) filter_criteria;
7758 if (m.Name != sig.Name)
7762 MethodInfo mi = m as MethodInfo;
7763 PropertyInfo pi = m as PropertyInfo;
7766 ReturnType = mi.ReturnType;
7767 else if (pi != null)
7768 ReturnType = pi.PropertyType;
7773 // we use sig.RetType == null to mean `do not check the
7774 // method return value.
7776 if (sig.RetType != null)
7777 if (ReturnType != sig.RetType)
7782 args = TypeManager.GetArgumentTypes (mi);
7784 args = TypeManager.GetArgumentTypes (pi);
7785 Type [] sigp = sig.Parameters;
7787 if (args.Length != sigp.Length)
7790 for (int i = args.Length; i > 0; ){
7792 if (args [i] != sigp [i])