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 switch (op.OperatorType){
283 case Operator.OpType.Equality:
285 has_equality_or_inequality = true;
287 case Operator.OpType.Inequality:
289 has_equality_or_inequality = true;
292 case Operator.OpType.True:
295 case Operator.OpType.False:
299 case Operator.OpType.GreaterThan:
301 case Operator.OpType.LessThan:
304 case Operator.OpType.GreaterThanOrEqual:
306 case Operator.OpType.LessThanOrEqual:
312 OperatorEntry oe = new OperatorEntry (reg, op);
314 object o = pairs [oe];
318 oe = (OperatorEntry) o;
323 if (true_op != null){
324 if (false_op == null)
325 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
326 } else if (false_op != null)
327 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
330 // Look for the mistakes.
332 foreach (DictionaryEntry de in pairs){
333 OperatorEntry oe = (OperatorEntry) de.Key;
340 case Operator.OpType.Equality:
343 case Operator.OpType.Inequality:
346 case Operator.OpType.GreaterThan:
349 case Operator.OpType.LessThan:
352 case Operator.OpType.GreaterThanOrEqual:
355 case Operator.OpType.LessThanOrEqual:
359 Report.Error (216, oe.op.Location,
360 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
363 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
364 if (container.Methods == null || !container.Methods.HasEquals)
365 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
367 if (container.Methods == null || !container.Methods.HasGetHashCode)
368 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
372 public override void DefineContainerMembers ()
374 base.DefineContainerMembers ();
375 CheckPairedOperators ();
380 // Whether this is a struct, class or interface
381 public readonly Kind Kind;
383 // Holds a list of classes and structures
386 // Holds the list of properties
387 MemberCoreArrayList properties;
389 // Holds the list of enumerations
390 MemberCoreArrayList enums;
392 // Holds the list of delegates
393 MemberCoreArrayList delegates;
395 // Holds the list of constructors
396 protected MemberCoreArrayList instance_constructors;
398 // Holds the list of fields
399 MemberCoreArrayList fields;
401 // Holds a list of fields that have initializers
402 protected ArrayList initialized_fields;
404 // Holds a list of static fields that have initializers
405 protected ArrayList initialized_static_fields;
407 // Holds the list of constants
408 MemberCoreArrayList constants;
411 MemberCoreArrayList interfaces;
413 // Holds the methods.
414 MethodArrayList methods;
417 protected MemberCoreArrayList events;
419 // Holds the indexers
420 IndexerArrayList indexers;
422 // Holds the operators
423 MemberCoreArrayList operators;
425 // Holds the iterators
428 // Holds the parts of a partial class;
432 // Pointers to the default constructor and the default static constructor
434 protected Constructor default_constructor;
435 protected Constructor default_static_constructor;
438 // Whether we have at least one non-static field
440 bool have_nonstatic_fields = false;
443 // This one is computed after we can distinguish interfaces
444 // from classes from the arraylist `type_bases'
446 string base_class_name;
449 ArrayList type_bases;
451 bool members_defined;
452 bool members_defined_ok;
454 // The interfaces we implement.
455 protected Type [] ifaces;
456 protected Type ptype;
458 // The base member cache and our member cache
459 MemberCache base_cache;
460 MemberCache member_cache;
462 public const string DefaultIndexerName = "Item";
464 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
465 Attributes attrs, Kind kind, Location l)
466 : base (ns, parent, name, attrs, l)
470 types = new ArrayList ();
472 base_class_name = null;
475 public bool AddToMemberContainer (MemberCore symbol)
477 return AddToContainer (symbol, String.Concat (Name, '.', symbol.Name), symbol.Name);
480 bool AddToTypeContainer (DeclSpace ds)
482 return AddToContainer (ds, ds.Name, ds.Basename);
485 public void AddConstant (Const constant)
487 if (!AddToMemberContainer (constant))
490 if (constants == null)
491 constants = new MemberCoreArrayList ();
493 constants.Add (constant);
496 public void AddEnum (Mono.CSharp.Enum e)
498 if (!AddToTypeContainer (e))
502 enums = new MemberCoreArrayList ();
507 public void AddClassOrStruct (TypeContainer c)
509 if (!AddToTypeContainer (c))
515 public void AddDelegate (Delegate d)
517 if (!AddToTypeContainer (d))
520 if (delegates == null)
521 delegates = new MemberCoreArrayList ();
526 public void AddMethod (Method method)
528 if (!AddToMemberContainer (method))
532 methods = new MethodArrayList (this);
534 if (method.Name.IndexOf ('.') != -1)
535 methods.Insert (0, method);
537 methods.Add (method);
540 public void AddConstructor (Constructor c)
542 if (c.Name != Basename) {
543 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
546 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
549 if (default_static_constructor != null) {
550 Report.SymbolRelatedToPreviousError (default_static_constructor);
551 Report.Error (111, c.Location, Error111, Name, c.Name);
555 default_static_constructor = c;
558 if (default_constructor != null) {
559 Report.SymbolRelatedToPreviousError (default_constructor);
560 Report.Error (111, c.Location, Error111, c.Location, Name, c.Name);
563 default_constructor = c;
566 if (instance_constructors == null)
567 instance_constructors = new MemberCoreArrayList ();
569 instance_constructors.Add (c);
573 internal static string Error111 {
575 return "Type '{0}' already defines a member called '{1}' with the same parameter types";
579 public void AddInterface (TypeContainer iface)
581 if (!AddToTypeContainer (iface))
584 if (interfaces == null) {
585 interfaces = new MemberCoreArrayList ();
588 interfaces.Add (iface);
591 public void AddField (FieldMember field)
593 if (!AddToMemberContainer (field))
597 fields = new MemberCoreArrayList ();
601 if (field.HasInitializer){
602 if ((field.ModFlags & Modifiers.STATIC) != 0){
603 if (initialized_static_fields == null)
604 initialized_static_fields = new ArrayList ();
606 initialized_static_fields.Add (field);
608 if (initialized_fields == null)
609 initialized_fields = new ArrayList ();
611 initialized_fields.Add (field);
615 if ((field.ModFlags & Modifiers.STATIC) == 0)
616 have_nonstatic_fields = true;
619 public void AddProperty (Property prop)
621 if (!AddToMemberContainer (prop) ||
622 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
625 if (properties == null)
626 properties = new MemberCoreArrayList ();
628 if (prop.Name.IndexOf ('.') != -1)
629 properties.Insert (0, prop);
631 properties.Add (prop);
634 public void AddEvent (Event e)
636 if (!AddToMemberContainer (e))
639 if (e is EventProperty) {
640 if (!AddToMemberContainer (e.Add))
643 if (!AddToMemberContainer (e.Remove))
648 events = new MemberCoreArrayList ();
655 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
657 public void AddIndexer (Indexer i)
659 if (indexers == null)
660 indexers = new IndexerArrayList (this);
662 if (i.IsExplicitImpl)
663 indexers.Insert (0, i);
668 public void AddOperator (Operator op)
670 if (!AddToMemberContainer (op))
673 if (operators == null)
674 operators = new OperatorArrayList (this);
679 public void AddIterator (Iterator i)
681 if (iterators == null)
682 iterators = new ArrayList ();
687 public void AddType (TypeContainer tc)
692 public void AddPart (ClassPart part)
695 parts = new ArrayList ();
700 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
702 if (a.Type == TypeManager.default_member_type) {
703 if (Indexers != null) {
704 Report.Error (646, a.Location,
705 "Cannot specify the DefaultMember attribute on" +
706 " a type containing an indexer");
711 base.ApplyAttributeBuilder (a, cb);
714 public override AttributeTargets AttributeTargets {
718 return AttributeTargets.Class;
720 return AttributeTargets.Struct;
722 return AttributeTargets.Interface;
724 throw new NotSupportedException ();
729 public ArrayList Types {
735 public MethodArrayList Methods {
741 public ArrayList Constants {
747 public ArrayList Interfaces {
753 public ArrayList Iterators {
761 return base_class_name;
765 public ArrayList Bases {
775 public ArrayList Fields {
781 public ArrayList InstanceConstructors {
783 return instance_constructors;
787 public ArrayList Properties {
793 public ArrayList Events {
799 public ArrayList Enums {
805 public ArrayList Indexers {
811 public ArrayList Operators {
817 public ArrayList Delegates {
823 public ArrayList Parts {
829 public virtual TypeAttributes TypeAttr {
831 return Modifiers.TypeAttr (ModFlags, this);
835 public string IndexerName {
837 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
842 // Emits the instance field initializers
844 public bool EmitFieldInitializers (EmitContext ec)
847 Expression instance_expr;
850 fields = initialized_static_fields;
851 instance_expr = null;
853 fields = initialized_fields;
854 instance_expr = new This (Location.Null).Resolve (ec);
860 foreach (Field f in fields){
861 Expression e = f.GetInitializerExpression (ec);
865 Location l = f.Location;
866 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
867 fe.InstanceExpression = instance_expr;
868 ExpressionStatement a = new Assign (fe, e, l);
870 a = a.ResolveStatement (ec);
874 if (RootContext.Optimize) {
875 Constant c = e as Constant;
877 if (c.IsDefaultValue)
882 a.EmitStatement (ec);
889 // Defines the default constructors
891 protected void DefineDefaultConstructor (bool is_static)
895 // The default constructor is public
896 // If the class is abstract, the default constructor is protected
897 // The default static constructor is private
899 int mods = Modifiers.PUBLIC;
901 mods = Modifiers.STATIC | Modifiers.PRIVATE;
902 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
903 mods = Modifiers.PROTECTED;
905 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
906 new ConstructorBaseInitializer (
907 null, Parameters.EmptyReadOnlyParameters,
913 c.Block = new ToplevelBlock (null, Location);
918 /// The pending methods that need to be implemented
919 // (interfaces or abstract methods)
921 public PendingImplementation Pending;
923 public abstract void Register ();
925 public abstract PendingImplementation GetPendingImplementations ();
927 TypeExpr[] GetPartialBases (out TypeExpr base_class, out bool error)
929 ArrayList ifaces = new ArrayList ();
932 Location base_loc = Location.Null;
934 foreach (ClassPart part in parts) {
935 TypeExpr new_base_class;
936 TypeExpr[] new_ifaces;
938 new_ifaces = part.GetClassBases (out new_base_class, out error);
942 if ((base_class != null) && (new_base_class != null) &&
943 !base_class.Equals (new_base_class)) {
944 Report.Error (263, part.Location,
945 "Partial declarations of `{0}' must " +
946 "not specify different base classes",
949 if (!Location.IsNull (base_loc))
950 Report.LocationOfPreviousError (base_loc);
956 if ((base_class == null) && (new_base_class != null)) {
957 base_class = new_base_class;
958 base_loc = part.Location;
961 if (new_ifaces == null)
964 foreach (TypeExpr iface in new_ifaces) {
966 foreach (TypeExpr old_iface in ifaces) {
967 if (old_iface.Equals (iface)) {
980 TypeExpr[] retval = new TypeExpr [ifaces.Count];
981 ifaces.CopyTo (retval, 0);
985 TypeExpr[] GetNormalBases (out TypeExpr base_class, out bool error)
989 int count = Bases.Count;
992 if (Kind == Kind.Class){
993 TypeExpr name = ResolveBaseTypeExpr (
994 (Expression) Bases [0], false, Location);
1001 if (!name.IsInterface) {
1002 // base_class could be a class, struct, enum, delegate.
1003 // This is validated in GetClassBases.
1009 TypeExpr [] ifaces = new TypeExpr [count-start];
1011 for (i = start, j = 0; i < count; i++, j++){
1012 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1013 if (resolved == null) {
1018 ifaces [j] = resolved;
1026 /// This function computes the Base class and also the
1027 /// list of interfaces that the class or struct @c implements.
1029 /// The return value is an array (might be null) of
1030 /// interfaces implemented (as Types).
1032 /// The @base_class argument is set to the base object or null
1033 /// if this is `System.Object'.
1035 TypeExpr [] GetClassBases (out TypeExpr base_class, out bool error)
1044 ifaces = GetPartialBases (out base_class, out error);
1045 else if (Bases == null){
1049 ifaces = GetNormalBases (out base_class, out error);
1054 if ((base_class != null) && (Kind == Kind.Class)){
1056 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1057 Report.Error (1521, base_class.Location, "Invalid base type");
1062 if (base_class.IsSealed){
1064 Report.SymbolRelatedToPreviousError (base_class.Type);
1065 if (base_class.Type.IsAbstract) {
1066 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1068 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1073 if (!base_class.CanInheritFrom ()){
1074 Report.Error (644, Location,
1075 "`{0}' cannot inherit from special class `{1}'",
1076 Name, base_class.Name);
1081 if (!base_class.AsAccessible (this, ModFlags)) {
1082 Report.SymbolRelatedToPreviousError (base_class.Type);
1083 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1084 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1088 if (base_class != null)
1089 base_class_name = base_class.Name;
1094 int count = ifaces != null ? ifaces.Length : 0;
1096 for (i = 0; i < count; i++) {
1097 TypeExpr iface = (TypeExpr) ifaces [i];
1099 if (!iface.IsInterface) {
1101 if (Kind != Kind.Class) {
1102 string what = Kind == Kind.Struct ? "Struct" : "Interface";
1104 Report.Error (527, Location,
1105 "In {0} `{1}', type `{2}' is not "+
1106 "an interface", what, Name, iface.Name);
1108 else if (base_class != null)
1109 Report.Error (1721, Location,
1110 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1113 Report.Error (1722, Location,
1114 "In Class `{0}', `{1}' is not " +
1115 "an interface, a base class must be listed first", Name, iface.Name);
1120 for (int x = 0; x < i; x++) {
1121 if (iface.Equals (ifaces [x])) {
1122 Report.Error (528, Location,
1123 "`{0}' is already listed in " +
1124 "interface list", iface.Name);
1129 if ((Kind == Kind.Interface) &&
1130 !iface.AsAccessible (Parent, ModFlags)) {
1131 Report.Error (61, Location,
1132 "Inconsistent accessibility: base " +
1133 "interface `{0}' is less accessible " +
1134 "than interface `{1}'", iface.Name,
1149 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1151 public override TypeBuilder DefineType ()
1153 if (TypeBuilder != null)
1160 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
1167 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1169 TypeExpr[] iface_exprs = GetClassBases (out base_type, out error);
1173 if (base_type == null) {
1174 if (Kind == Kind.Class){
1175 if (RootContext.StdLib)
1176 base_type = TypeManager.system_object_expr;
1177 else if (Name != "System.Object")
1178 base_type = TypeManager.system_object_expr;
1179 } else if (Kind == Kind.Struct) {
1181 // If we are compiling our runtime,
1182 // and we are defining ValueType, then our
1183 // base is `System.Object'.
1185 if (!RootContext.StdLib && Name == "System.ValueType")
1186 base_type = TypeManager.system_object_expr;
1188 base_type = TypeManager.system_valuetype_expr;
1192 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1193 throw new Exception ();
1195 TypeAttributes type_attributes = TypeAttr;
1197 if (base_type != null) {
1198 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1199 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1200 ptype = base_type.ResolveType (ec);
1201 if (ptype == null) {
1209 if (TypeManager.NamespaceClash (Name, Location)) {
1214 ModuleBuilder builder = CodeGen.Module.Builder;
1215 TypeBuilder = builder.DefineType (
1216 Name, type_attributes, ptype, null);
1219 TypeBuilder builder = Parent.DefineType ();
1220 if (builder == null)
1223 TypeBuilder = builder.DefineNestedType (
1224 Basename, type_attributes, ptype, null);
1227 catch (ArgumentException) {
1228 Report.RuntimeMissingSupport (Location, "static classes");
1233 // Structs with no fields need to have at least one byte.
1234 // The right thing would be to set the PackingSize in a DefineType
1235 // but there are no functions that allow interfaces *and* the size to
1239 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1240 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1241 FieldAttributes.Private);
1244 // add interfaces that were not added at type creation
1245 if (iface_exprs != null) {
1246 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1247 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1248 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1249 if (ifaces == null) {
1254 foreach (Type itype in ifaces)
1255 TypeBuilder.AddInterfaceImplementation (itype);
1257 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1261 // Finish the setup for the EmitContext
1263 ec.ContainerType = TypeBuilder;
1265 TypeManager.AddUserType (Name, TypeBuilder, this);
1267 if (!(this is Iterator))
1268 RootContext.RegisterOrder (this);
1270 if (!DefineNestedTypes ()) {
1279 protected virtual bool DefineNestedTypes ()
1281 if (Interfaces != null) {
1282 foreach (TypeContainer iface in Interfaces)
1283 if (iface.DefineType () == null)
1287 if (Types != null) {
1288 foreach (TypeContainer tc in Types)
1289 if (tc.DefineType () == null)
1293 if (Delegates != null) {
1294 foreach (Delegate d in Delegates)
1295 if (d.DefineType () == null)
1299 if (Enums != null) {
1300 foreach (Enum en in Enums)
1301 if (en.DefineType () == null)
1305 if (Parts != null) {
1306 foreach (ClassPart part in Parts) {
1307 part.TypeBuilder = TypeBuilder;
1309 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1316 static void Error_KeywordNotAllowed (Location loc)
1318 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1322 /// Populates our TypeBuilder with fields and methods
1324 public override bool DefineMembers (TypeContainer container)
1326 if (members_defined)
1327 return members_defined_ok;
1329 members_defined_ok = DoDefineMembers ();
1330 members_defined = true;
1332 return members_defined_ok;
1335 bool DoDefineMembers ()
1338 if ((ModFlags & Modifiers.NEW) != 0)
1339 Error_KeywordNotAllowed (Location);
1341 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1342 if (conflict_symbol == null) {
1343 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1344 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1346 if ((ModFlags & Modifiers.NEW) == 0) {
1347 Report.SymbolRelatedToPreviousError (conflict_symbol);
1348 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1353 DefineContainerMembers (constants);
1354 DefineContainerMembers (fields);
1356 if ((Kind == Kind.Class) && !(this is ClassPart) && !(this is StaticClass)){
1357 if ((instance_constructors == null) &&
1358 !(this is StaticClass)) {
1359 if (default_constructor == null)
1360 DefineDefaultConstructor (false);
1363 if (initialized_static_fields != null &&
1364 default_static_constructor == null)
1365 DefineDefaultConstructor (true);
1368 if (Kind == Kind.Struct){
1370 // Structs can not have initialized instance
1373 if (initialized_static_fields != null &&
1374 default_static_constructor == null)
1375 DefineDefaultConstructor (true);
1377 if (initialized_fields != null)
1378 ReportStructInitializedInstanceError ();
1381 Pending = GetPendingImplementations ();
1383 if (parts != null) {
1384 foreach (ClassPart part in parts) {
1385 if (!part.DefineMembers (this))
1391 // Constructors are not in the defined_names array
1393 DefineContainerMembers (instance_constructors);
1395 if (default_static_constructor != null)
1396 default_static_constructor.Define ();
1398 DefineContainerMembers (properties);
1399 DefineContainerMembers (events);
1400 DefineContainerMembers (indexers);
1401 DefineContainerMembers (methods);
1402 DefineContainerMembers (operators);
1403 DefineContainerMembers (enums);
1404 DefineContainerMembers (delegates);
1407 if (!(this is ClassPart))
1408 member_cache = new MemberCache (this);
1411 if (parts != null) {
1412 foreach (ClassPart part in parts)
1413 part.member_cache = member_cache;
1416 if (iterators != null) {
1417 foreach (Iterator iterator in iterators) {
1418 if (iterator.DefineType () == null)
1422 foreach (Iterator iterator in iterators) {
1423 if (!iterator.DefineMembers (this))
1431 void ReportStructInitializedInstanceError ()
1433 string n = TypeBuilder.FullName;
1435 foreach (Field f in initialized_fields){
1438 "`" + n + "." + f.Name + "': can not have " +
1439 "instance field initializers in structs");
1443 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1446 mcal.DefineContainerMembers ();
1449 public override bool Define ()
1451 if (parts != null) {
1452 foreach (ClassPart part in parts) {
1453 if (!part.Define ())
1461 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1463 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1467 /// This function is based by a delegate to the FindMembers routine
1469 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1475 /// This filter is used by FindMembers, and we just keep
1476 /// a global for the filter to `AlwaysAccept'
1478 static MemberFilter accepting_filter;
1481 static TypeContainer ()
1483 accepting_filter = new MemberFilter (AlwaysAccept);
1486 public MethodInfo[] GetMethods ()
1488 ArrayList members = new ArrayList ();
1490 DefineMembers (null);
1492 if (methods != null) {
1493 int len = methods.Count;
1494 for (int i = 0; i < len; i++) {
1495 Method m = (Method) methods [i];
1497 members.Add (m.MethodBuilder);
1501 if (operators != null) {
1502 int len = operators.Count;
1503 for (int i = 0; i < len; i++) {
1504 Operator o = (Operator) operators [i];
1506 members.Add (o.OperatorMethodBuilder);
1510 if (properties != null) {
1511 int len = properties.Count;
1512 for (int i = 0; i < len; i++) {
1513 Property p = (Property) properties [i];
1515 if (p.GetBuilder != null)
1516 members.Add (p.GetBuilder);
1517 if (p.SetBuilder != null)
1518 members.Add (p.SetBuilder);
1522 if (indexers != null) {
1523 int len = indexers.Count;
1524 for (int i = 0; i < len; i++) {
1525 Indexer ix = (Indexer) indexers [i];
1527 if (ix.GetBuilder != null)
1528 members.Add (ix.GetBuilder);
1529 if (ix.SetBuilder != null)
1530 members.Add (ix.SetBuilder);
1534 if (events != null) {
1535 int len = events.Count;
1536 for (int i = 0; i < len; i++) {
1537 Event e = (Event) events [i];
1539 if (e.AddBuilder != null)
1540 members.Add (e.AddBuilder);
1541 if (e.RemoveBuilder != null)
1542 members.Add (e.RemoveBuilder);
1546 MethodInfo[] retMethods = new MethodInfo [members.Count];
1547 members.CopyTo (retMethods, 0);
1551 // Indicated whether container has StructLayout attribute set Explicit
1552 public virtual bool HasExplicitLayout {
1559 /// This method returns the members of this type just like Type.FindMembers would
1560 /// Only, we need to use this for types which are _being_ defined because MS'
1561 /// implementation can't take care of that.
1564 // FIXME: return an empty static array instead of null, that cleans up
1565 // some code and is consistent with some coding conventions I just found
1569 // Notice that in various cases we check if our field is non-null,
1570 // something that would normally mean that there was a bug elsewhere.
1572 // The problem happens while we are defining p-invoke methods, as those
1573 // will trigger a FindMembers, but this happens before things are defined
1575 // Since the whole process is a no-op, it is fine to check for null here.
1577 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1578 MemberFilter filter, object criteria)
1580 ArrayList members = null;
1583 if ((bf & BindingFlags.Public) != 0)
1584 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1586 if ((bf & BindingFlags.NonPublic) != 0)
1587 modflags |= Modifiers.PRIVATE;
1589 int static_mask = 0, static_flags = 0;
1590 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1591 case BindingFlags.Static:
1592 static_mask = static_flags = Modifiers.STATIC;
1595 case BindingFlags.Instance:
1596 static_mask = Modifiers.STATIC;
1601 static_mask = static_flags = 0;
1605 Timer.StartTimer (TimerType.TcFindMembers);
1608 filter = accepting_filter;
1610 if ((mt & MemberTypes.Field) != 0) {
1611 if (fields != null) {
1612 int len = fields.Count;
1613 for (int i = 0; i < len; i++) {
1614 FieldMember f = (FieldMember) fields [i];
1616 if ((f.ModFlags & modflags) == 0)
1618 if ((f.ModFlags & static_mask) != static_flags)
1621 FieldBuilder fb = f.FieldBuilder;
1622 if (fb != null && filter (fb, criteria) == true) {
1623 if (members == null)
1624 members = new ArrayList ();
1631 if (constants != null) {
1632 int len = constants.Count;
1633 for (int i = 0; i < len; i++) {
1634 Const con = (Const) constants [i];
1636 if ((con.ModFlags & modflags) == 0)
1638 if ((con.ModFlags & static_mask) != static_flags)
1641 FieldBuilder fb = con.FieldBuilder;
1644 fb = con.FieldBuilder;
1646 if (fb != null && filter (fb, criteria) == true) {
1647 if (members == null)
1648 members = new ArrayList ();
1656 if ((mt & MemberTypes.Method) != 0) {
1657 if (methods != null) {
1658 int len = methods.Count;
1659 for (int i = 0; i < len; i++) {
1660 Method m = (Method) methods [i];
1662 if ((m.ModFlags & modflags) == 0)
1664 if ((m.ModFlags & static_mask) != static_flags)
1667 MethodBuilder mb = m.MethodBuilder;
1669 if (mb != null && filter (mb, criteria) == true) {
1670 if (members == null)
1671 members = new ArrayList ();
1678 if (operators != null) {
1679 int len = operators.Count;
1680 for (int i = 0; i < len; i++) {
1681 Operator o = (Operator) operators [i];
1683 if ((o.ModFlags & modflags) == 0)
1685 if ((o.ModFlags & static_mask) != static_flags)
1688 MethodBuilder ob = o.OperatorMethodBuilder;
1689 if (ob != null && filter (ob, criteria) == true) {
1690 if (members == null)
1691 members = new ArrayList ();
1698 if (properties != null) {
1699 int len = properties.Count;
1700 for (int i = 0; i < len; i++) {
1701 Property p = (Property) properties [i];
1703 if ((p.ModFlags & modflags) == 0)
1705 if ((p.ModFlags & static_mask) != static_flags)
1711 if (b != null && filter (b, criteria) == true) {
1712 if (members == null)
1713 members = new ArrayList ();
1719 if (b != null && filter (b, criteria) == true) {
1720 if (members == null)
1721 members = new ArrayList ();
1728 if (indexers != null) {
1729 int len = indexers.Count;
1730 for (int i = 0; i < len; i++) {
1731 Indexer ix = (Indexer) indexers [i];
1733 if ((ix.ModFlags & modflags) == 0)
1735 if ((ix.ModFlags & static_mask) != static_flags)
1741 if (b != null && filter (b, criteria) == true) {
1742 if (members == null)
1743 members = new ArrayList ();
1749 if (b != null && filter (b, criteria) == true) {
1750 if (members == null)
1751 members = new ArrayList ();
1759 if ((mt & MemberTypes.Event) != 0) {
1760 if (events != null) {
1761 int len = events.Count;
1762 for (int i = 0; i < len; i++) {
1763 Event e = (Event) events [i];
1765 if ((e.ModFlags & modflags) == 0)
1767 if ((e.ModFlags & static_mask) != static_flags)
1770 MemberInfo eb = e.EventBuilder;
1771 if (eb != null && filter (eb, criteria) == true) {
1772 if (members == null)
1773 members = new ArrayList ();
1775 members.Add (e.EventBuilder);
1781 if ((mt & MemberTypes.Property) != 0){
1782 if (properties != null) {
1783 int len = properties.Count;
1784 for (int i = 0; i < len; i++) {
1785 Property p = (Property) properties [i];
1787 if ((p.ModFlags & modflags) == 0)
1789 if ((p.ModFlags & static_mask) != static_flags)
1792 MemberInfo pb = p.PropertyBuilder;
1793 if (pb != null && filter (pb, criteria) == true) {
1794 if (members == null)
1795 members = new ArrayList ();
1797 members.Add (p.PropertyBuilder);
1802 if (indexers != null) {
1803 int len = indexers.Count;
1804 for (int i = 0; i < len; i++) {
1805 Indexer ix = (Indexer) indexers [i];
1807 if ((ix.ModFlags & modflags) == 0)
1809 if ((ix.ModFlags & static_mask) != static_flags)
1812 MemberInfo ib = ix.PropertyBuilder;
1813 if (ib != null && filter (ib, criteria) == true) {
1814 if (members == null)
1815 members = new ArrayList ();
1817 members.Add (ix.PropertyBuilder);
1823 if ((mt & MemberTypes.NestedType) != 0) {
1824 if (types != null) {
1825 int len = types.Count;
1826 for (int i = 0; i < len; i++) {
1827 TypeContainer t = (TypeContainer) types [i];
1829 if ((t.ModFlags & modflags) == 0)
1832 TypeBuilder tb = t.TypeBuilder;
1834 tb = t.DefineType ();
1836 if (tb != null && (filter (tb, criteria) == true)) {
1837 if (members == null)
1838 members = new ArrayList ();
1845 if (enums != null) {
1846 int len = enums.Count;
1847 for (int i = 0; i < len; i++) {
1848 Enum en = (Enum) enums [i];
1850 if ((en.ModFlags & modflags) == 0)
1853 TypeBuilder tb = en.TypeBuilder;
1854 if (tb != null && (filter (tb, criteria) == true)) {
1855 if (members == null)
1856 members = new ArrayList ();
1863 if (delegates != null) {
1864 int len = delegates.Count;
1865 for (int i = 0; i < len; i++) {
1866 Delegate d = (Delegate) delegates [i];
1868 if ((d.ModFlags & modflags) == 0)
1871 TypeBuilder tb = d.TypeBuilder;
1872 if (tb != null && (filter (tb, criteria) == true)) {
1873 if (members == null)
1874 members = new ArrayList ();
1881 if (interfaces != null) {
1882 int len = interfaces.Count;
1883 for (int i = 0; i < len; i++) {
1884 TypeContainer iface = (TypeContainer) interfaces [i];
1886 if ((iface.ModFlags & modflags) == 0)
1889 TypeBuilder tb = iface.TypeBuilder;
1890 if (tb != null && (filter (tb, criteria) == true)) {
1891 if (members == null)
1892 members = new ArrayList ();
1900 if ((mt & MemberTypes.Constructor) != 0){
1901 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1902 int len = instance_constructors.Count;
1903 for (int i = 0; i < len; i++) {
1904 Constructor c = (Constructor) instance_constructors [i];
1906 ConstructorBuilder cb = c.ConstructorBuilder;
1907 if (cb != null && filter (cb, criteria) == true) {
1908 if (members == null)
1909 members = new ArrayList ();
1916 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1917 ConstructorBuilder cb =
1918 default_static_constructor.ConstructorBuilder;
1920 if (cb != null && filter (cb, criteria) == true) {
1921 if (members == null)
1922 members = new ArrayList ();
1930 // Lookup members in base if requested.
1932 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1933 if (TypeBuilder.BaseType != null) {
1934 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1935 if (list.Count > 0) {
1936 if (members == null)
1937 members = new ArrayList ();
1939 members.AddRange (list);
1942 if (ifaces != null) {
1943 foreach (Type base_type in ifaces) {
1944 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1946 if (list.Count > 0) {
1947 if (members == null)
1948 members = new ArrayList ();
1949 members.AddRange (list);
1955 Timer.StopTimer (TimerType.TcFindMembers);
1957 if (members == null)
1958 return MemberList.Empty;
1960 return new MemberList (members);
1963 public override MemberCache MemberCache {
1965 return member_cache;
1969 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1970 MemberFilter filter, object criteria)
1972 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1975 return ds.FindMembers (mt, bf, filter, criteria);
1977 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1982 // FindMethods will look for methods not only in the type `t', but in
1983 // any interfaces implemented by the type.
1985 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1986 MemberFilter filter, object criteria)
1992 /// Emits the values for the constants
1994 public void EmitConstants ()
1996 if (constants != null)
1997 foreach (Const con in constants)
2002 protected virtual void VerifyMembers (EmitContext ec)
2005 // Check for internal or private fields that were never assigned
2007 if (RootContext.WarningLevel >= 4) {
2008 if (fields != null){
2009 foreach (Field f in fields) {
2010 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2013 if ((f.status & Field.Status.USED) == 0){
2014 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2019 // Only report 649 on level 4
2021 if (RootContext.WarningLevel < 4)
2024 if ((f.status & Field.Status.ASSIGNED) != 0)
2027 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2034 /// Emits the code, this step is performed after all
2035 /// the types, enumerations, constructors
2037 public void EmitType ()
2039 if (OptAttributes != null)
2040 OptAttributes.Emit (ec, this);
2044 if (instance_constructors != null) {
2045 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2046 bool has_compliant_args = false;
2048 foreach (Constructor c in instance_constructors) {
2051 if (has_compliant_args)
2054 has_compliant_args = c.HasCompliantArgs;
2056 if (!has_compliant_args)
2057 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2059 foreach (Constructor c in instance_constructors)
2066 if (default_static_constructor != null)
2067 default_static_constructor.Emit ();
2069 if (methods != null)
2070 foreach (Method m in methods)
2073 if (operators != null)
2074 foreach (Operator o in operators)
2077 if (properties != null)
2078 foreach (Property p in properties)
2081 if (indexers != null){
2086 foreach (FieldMember f in fields)
2089 if (events != null){
2090 foreach (Event e in Events)
2094 if (delegates != null) {
2095 foreach (Delegate d in Delegates) {
2100 if (enums != null) {
2101 foreach (Enum e in enums) {
2106 if (parts != null) {
2107 foreach (ClassPart part in parts)
2111 if ((Pending != null) && !(this is ClassPart))
2112 if (Pending.VerifyPendingMethods ())
2117 if (iterators != null)
2118 foreach (Iterator iterator in iterators)
2119 iterator.EmitType ();
2121 // if (types != null)
2122 // foreach (TypeContainer tc in types)
2126 public override void CloseType ()
2128 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2132 caching_flags |= Flags.CloseTypeCreated;
2133 TypeBuilder.CreateType ();
2134 } catch (TypeLoadException){
2136 // This is fine, the code still created the type
2138 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2139 // Console.WriteLine (e.Message);
2141 Console.WriteLine ("In type: " + Name);
2146 foreach (Enum en in Enums)
2150 foreach (TypeContainer tc in Types)
2151 if (tc.Kind == Kind.Struct)
2154 foreach (TypeContainer tc in Types)
2155 if (tc.Kind != Kind.Struct)
2159 if (Delegates != null)
2160 foreach (Delegate d in Delegates)
2163 if (Iterators != null)
2164 foreach (Iterator i in Iterators)
2172 initialized_fields = null;
2173 initialized_static_fields = null;
2182 default_constructor = null;
2183 default_static_constructor = null;
2185 OptAttributes = null;
2188 member_cache = null;
2191 // TODO: make it obsolete and use GetSignatureForError
2192 public string MakeName (string n)
2194 return "`" + Name + "." + n + "'";
2198 // Performs the validation on a Method's modifiers (properties have
2199 // the same properties).
2201 public bool MethodModifiersValid (MemberCore mc)
2203 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2204 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2205 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2207 int flags = mc.ModFlags;
2210 // At most one of static, virtual or override
2212 if ((flags & Modifiers.STATIC) != 0){
2213 if ((flags & vao) != 0){
2214 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2215 GetSignatureForError ());
2220 if (Kind == Kind.Struct){
2221 if ((flags & va) != 0){
2222 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2227 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2228 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2233 // If the declaration includes the abstract modifier, then the
2234 // declaration does not include static, virtual or extern
2236 if ((flags & Modifiers.ABSTRACT) != 0){
2237 if ((flags & Modifiers.EXTERN) != 0){
2239 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2243 if ((flags & Modifiers.SEALED) != 0) {
2244 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2248 if ((flags & Modifiers.VIRTUAL) != 0){
2249 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2253 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2254 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2259 if ((flags & Modifiers.PRIVATE) != 0){
2260 if ((flags & vao) != 0){
2261 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2266 if ((flags & Modifiers.SEALED) != 0){
2267 if ((flags & Modifiers.OVERRIDE) == 0){
2268 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2276 public bool UserDefinedStaticConstructor {
2278 return default_static_constructor != null;
2282 public Constructor DefaultStaticConstructor {
2283 get { return default_static_constructor; }
2286 protected override bool VerifyClsCompliance (DeclSpace ds)
2288 if (!base.VerifyClsCompliance (ds))
2293 Type base_type = TypeBuilder.BaseType;
2294 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2295 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2298 if (!Parent.IsClsCompliaceRequired (ds)) {
2299 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2300 GetSignatureForError (), Parent.GetSignatureForError ());
2307 /// Checks whether container name is CLS Compliant
2309 void VerifyClsName ()
2311 Hashtable base_members = base_cache == null ?
2313 base_cache.GetPublicMembers ();
2314 Hashtable this_members = new Hashtable ();
2316 foreach (DictionaryEntry entry in defined_names) {
2317 MemberCore mc = (MemberCore)entry.Value;
2318 if (!mc.IsClsCompliaceRequired (this))
2321 string name = (string)entry.Key;
2322 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2324 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2325 object found = base_members [lcase];
2326 if (found == null) {
2327 found = this_members [lcase];
2328 if (found == null) {
2329 this_members.Add (lcase, mc);
2334 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2337 if (found is MemberInfo) {
2338 if (basename == ((MemberInfo)found).Name)
2340 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2342 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2344 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2350 /// Performs checks for an explicit interface implementation. First it
2351 /// checks whether the `interface_type' is a base inteface implementation.
2352 /// Then it checks whether `name' exists in the interface type.
2354 public virtual bool VerifyImplements (Type interface_type, string full,
2355 string name, Location loc)
2359 if (ifaces != null){
2360 foreach (Type t in ifaces){
2361 if (t == interface_type){
2369 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2370 full, interface_type.FullName);
2377 protected override void VerifyObsoleteAttribute()
2379 CheckUsageOfObsoleteAttribute (ptype);
2384 foreach (Type iface in ifaces) {
2385 CheckUsageOfObsoleteAttribute (iface);
2394 string IMemberContainer.Name {
2400 Type IMemberContainer.Type {
2406 MemberCache IMemberContainer.MemberCache {
2408 return member_cache;
2412 bool IMemberContainer.IsInterface {
2414 return Kind == Kind.Interface;
2418 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2420 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2424 // Generates xml doc comments (if any), and if required,
2425 // handle warning report.
2427 internal override void GenerateDocComment (DeclSpace ds)
2429 DocUtil.GenerateTypeDocComment (this, ds);
2432 public override string DocCommentHeader {
2433 get { return "T:"; }
2436 public virtual MemberCache BaseCache {
2438 if (base_cache != null)
2440 if (TypeBuilder.BaseType != null)
2441 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2442 if (TypeBuilder.IsInterface)
2443 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2449 public class PartialContainer : TypeContainer {
2451 public readonly Namespace Namespace;
2452 public readonly int OriginalModFlags;
2453 public readonly int AllowedModifiers;
2454 public readonly TypeAttributes DefaultTypeAttributes;
2456 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2457 MemberName member_name, int mod_flags, Kind kind,
2460 PartialContainer pc;
2461 string full_name = member_name.GetName (true);
2462 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2464 pc = ds as PartialContainer;
2468 260, ds.Location, "Missing partial modifier " +
2469 "on declaration of type `{0}'; another " +
2470 "partial implementation of this type exists",
2471 member_name.GetPartialName());
2473 Report.LocationOfPreviousError (loc);
2477 if (pc.Kind != kind) {
2479 261, loc, "Partial declarations of `{0}' " +
2480 "must be all classes, all structs or " +
2481 "all interfaces", member_name.GetPartialName ());
2485 if (pc.OriginalModFlags != mod_flags) {
2487 262, loc, "Partial declarations of `{0}' " +
2488 "have conflicting accessibility modifiers",
2489 member_name.GetPartialName ());
2496 pc = new PartialContainer (ns, parent, member_name, mod_flags, kind, loc);
2497 RootContext.Tree.RecordDecl (full_name, pc);
2498 parent.AddType (pc);
2503 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2504 MemberName name, int mod, Attributes attrs,
2505 Kind kind, Location loc)
2507 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2509 // An error occured; create a dummy container, but don't
2511 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2514 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2519 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2520 MemberName name, int mod, Kind kind, Location l)
2521 : base (ns, parent, name, null, kind, l)
2523 this.Namespace = ns.NS;
2527 AllowedModifiers = Class.AllowedModifiers;
2528 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2532 AllowedModifiers = Struct.AllowedModifiers;
2533 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2536 case Kind.Interface:
2537 AllowedModifiers = Interface.AllowedModifiers;
2538 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2542 throw new InvalidOperationException ();
2546 if (parent.Parent == null)
2547 accmods = Modifiers.INTERNAL;
2549 accmods = Modifiers.PRIVATE;
2551 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2552 this.OriginalModFlags = mod;
2555 public override void Register ()
2557 if (Kind == Kind.Interface)
2558 Parent.AddInterface (this);
2559 else if (Kind == Kind.Class || Kind == Kind.Struct)
2560 Parent.AddClassOrStruct (this);
2562 throw new InvalidOperationException ();
2565 public override PendingImplementation GetPendingImplementations ()
2567 return PendingImplementation.GetPendingImplementations (this);
2570 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2573 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
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 parent,
2590 int mod, Attributes attrs, Kind kind, Location l)
2591 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2593 this.PartialContainer = parent;
2594 this.IsPartial = true;
2597 if (parent.Parent == null)
2598 accmods = Modifiers.INTERNAL;
2600 accmods = Modifiers.PRIVATE;
2602 this.ModFlags = Modifiers.Check (
2603 parent.AllowedModifiers, mod, accmods, l);
2606 public override void Register ()
2610 public override PendingImplementation GetPendingImplementations ()
2612 return PartialContainer.Pending;
2615 public override bool VerifyImplements (Type interface_type, string full,
2616 string name, Location loc)
2618 return PartialContainer.VerifyImplements (
2619 interface_type, full, name, loc);
2622 public override MemberCache BaseCache {
2624 return PartialContainer.BaseCache;
2629 public abstract class ClassOrStruct : TypeContainer {
2630 bool hasExplicitLayout = false;
2631 ListDictionary declarative_security;
2633 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2634 MemberName name, Attributes attrs, Kind kind,
2636 : base (ns, parent, name, attrs, kind, l)
2640 public override PendingImplementation GetPendingImplementations ()
2642 return PendingImplementation.GetPendingImplementations (this);
2645 public override bool HasExplicitLayout {
2647 return hasExplicitLayout;
2651 protected override void VerifyMembers (EmitContext ec)
2653 base.VerifyMembers (ec);
2655 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2656 foreach (Event e in events){
2658 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2663 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2665 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2666 if (declarative_security == null)
2667 declarative_security = new ListDictionary ();
2669 a.ExtractSecurityPermissionSet (declarative_security);
2673 if (a.Type == TypeManager.struct_layout_attribute_type &&
2674 a.GetLayoutKindValue () == LayoutKind.Explicit)
2675 hasExplicitLayout = true;
2677 base.ApplyAttributeBuilder (a, cb);
2680 public override void Emit()
2684 if (declarative_security != null) {
2685 foreach (DictionaryEntry de in declarative_security) {
2686 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2691 public override void Register ()
2693 Parent.AddClassOrStruct (this);
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");
2707 Environment.Exit (1);
2711 protected override int AllowedModifiersProp {
2713 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2714 Modifiers.STATIC | Modifiers.UNSAFE;
2718 protected override void DefineContainerMembers (MemberCoreArrayList list)
2723 foreach (MemberCore m in list) {
2724 if (m is Operator) {
2725 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2729 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2732 if (m is Constructor) {
2733 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2737 if (m is Destructor) {
2738 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2742 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2745 base.DefineContainerMembers (list);
2748 public override TypeBuilder DefineType()
2750 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2751 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2755 TypeBuilder tb = base.DefineType ();
2759 if (ptype != TypeManager.object_type) {
2760 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2764 if (ifaces != null) {
2765 foreach (Type t in ifaces)
2766 Report.SymbolRelatedToPreviousError (t);
2767 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2772 public override TypeAttributes TypeAttr {
2774 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2779 public class Class : ClassOrStruct {
2780 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2781 public const int AllowedModifiers =
2784 Modifiers.PROTECTED |
2785 Modifiers.INTERNAL |
2787 Modifiers.ABSTRACT |
2791 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2792 Attributes attrs, Location l)
2793 : base (ns, parent, name, attrs, Kind.Class, l)
2795 this.ModFlags = mod;
2798 virtual protected int AllowedModifiersProp {
2800 return AllowedModifiers;
2804 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2806 if (a.Type == TypeManager.attribute_usage_type) {
2807 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2808 TypeBuilder.FullName != "System.Attribute") {
2809 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2813 base.ApplyAttributeBuilder (a, cb);
2816 public const TypeAttributes DefaultTypeAttributes =
2817 TypeAttributes.AutoLayout | TypeAttributes.Class;
2819 public override TypeBuilder DefineType()
2821 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2822 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2826 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2827 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2829 return base.DefineType ();
2833 // FIXME: How do we deal with the user specifying a different
2836 public override TypeAttributes TypeAttr {
2838 return base.TypeAttr | DefaultTypeAttributes;
2843 public class Struct : ClassOrStruct {
2845 // Modifiers allowed in a struct declaration
2847 public const int AllowedModifiers =
2850 Modifiers.PROTECTED |
2851 Modifiers.INTERNAL |
2855 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2856 int mod, Attributes attrs, Location l)
2857 : base (ns, parent, name, attrs, Kind.Struct, l)
2861 if (parent.Parent == null)
2862 accmods = Modifiers.INTERNAL;
2864 accmods = Modifiers.PRIVATE;
2866 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2868 this.ModFlags |= Modifiers.SEALED;
2871 public const TypeAttributes DefaultTypeAttributes =
2872 TypeAttributes.SequentialLayout |
2873 TypeAttributes.Sealed |
2874 TypeAttributes.BeforeFieldInit;
2877 // FIXME: Allow the user to specify a different set of attributes
2878 // in some cases (Sealed for example is mandatory for a class,
2879 // but what SequentialLayout can be changed
2881 public override TypeAttributes TypeAttr {
2883 return base.TypeAttr | DefaultTypeAttributes;
2891 public class Interface : TypeContainer, IMemberContainer {
2893 /// Modifiers allowed in a class declaration
2895 public const int AllowedModifiers =
2898 Modifiers.PROTECTED |
2899 Modifiers.INTERNAL |
2903 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2904 Attributes attrs, Location l)
2905 : base (ns, parent, name, attrs, Kind.Interface, l)
2909 if (parent.Parent == null)
2910 accmods = Modifiers.INTERNAL;
2912 accmods = Modifiers.PRIVATE;
2914 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2917 public override void Register ()
2919 Parent.AddInterface (this);
2922 public override PendingImplementation GetPendingImplementations ()
2927 public const TypeAttributes DefaultTypeAttributes =
2928 TypeAttributes.AutoLayout |
2929 TypeAttributes.Abstract |
2930 TypeAttributes.Interface;
2932 public override TypeAttributes TypeAttr {
2934 return base.TypeAttr | DefaultTypeAttributes;
2939 public abstract class MethodCore : MemberBase {
2940 public readonly Parameters Parameters;
2941 protected ToplevelBlock block;
2944 // Parameters, cached for semantic analysis.
2946 protected InternalParameters parameter_info;
2947 protected Type [] parameter_types;
2949 // Whether this is an operator method.
2950 public bool IsOperator;
2953 // The method we're overriding if this is an override method.
2955 protected MethodInfo base_method = null;
2957 static string[] attribute_targets = new string [] { "method", "return" };
2959 public MethodCore (TypeContainer parent, Expression type, int mod,
2960 int allowed_mod, bool is_interface, MemberName name,
2961 Attributes attrs, Parameters parameters, Location loc)
2962 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
2965 Parameters = parameters;
2966 IsInterface = is_interface;
2970 // Returns the System.Type array for the parameters of this method
2972 public Type [] ParameterTypes {
2974 return parameter_types;
2978 public InternalParameters ParameterInfo
2981 return parameter_info;
2985 public ToplevelBlock Block {
2995 protected override bool CheckBase ()
2997 if (!base.CheckBase ())
3000 // Check whether arguments were correct.
3001 if (!DoDefineParameters ())
3004 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3010 // Is null for System.Object while compiling corlib and base interfaces
3011 if (Parent.BaseCache == null) {
3012 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3013 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3018 Type base_ret_type = null;
3019 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3021 // method is override
3022 if (base_method != null) {
3024 if (!CheckMethodAgainstBase ())
3027 if ((ModFlags & Modifiers.NEW) == 0) {
3028 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3029 Report.SymbolRelatedToPreviousError (base_method);
3030 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3031 "change return type when overriding inherited member");
3035 if (base_method.IsAbstract && !IsInterface) {
3036 Report.SymbolRelatedToPreviousError (base_method);
3037 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3042 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3043 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3047 if (RootContext.WarningLevel > 2) {
3048 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3049 Parent.Methods.HasEquals = true;
3050 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3051 Parent.Methods.HasGetHashCode = true;
3054 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3055 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3057 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3058 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3059 Report.SymbolRelatedToPreviousError (base_method);
3060 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3067 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3068 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3069 if (conflict_symbol != null) {
3070 Report.SymbolRelatedToPreviousError (conflict_symbol);
3071 if (this is PropertyBase)
3072 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3074 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3076 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3080 if (conflict_symbol == null) {
3081 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3082 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3087 if ((ModFlags & Modifiers.NEW) == 0) {
3088 if (this is Method && conflict_symbol is MethodBase)
3091 Report.SymbolRelatedToPreviousError (conflict_symbol);
3092 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3100 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3101 // that have been defined.
3103 // `name' is the user visible name for reporting errors (this is used to
3104 // provide the right name regarding method names and properties)
3106 bool CheckMethodAgainstBase ()
3110 // TODO: replace with GetSignatureForError
3111 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3113 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3114 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3116 506, Location, Parent.MakeName (Name) +
3117 ": cannot override inherited member `" +
3118 name + "' because it is not " +
3119 "virtual, abstract or override");
3123 // Now we check that the overriden method is not final
3125 if (base_method.IsFinal) {
3126 Report.SymbolRelatedToPreviousError (base_method);
3127 Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
3128 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3132 // Check that the permissions are not being changed
3134 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3135 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3137 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3138 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3143 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3144 ModFlags |= Modifiers.NEW;
3145 Report.SymbolRelatedToPreviousError (base_method);
3146 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3147 if (RootContext.WarningLevel >= 2)
3148 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));
3150 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3156 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3158 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3160 // when overriding protected internal, the method can be declared
3161 // protected internal only within the same assembly
3164 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3165 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3167 // assemblies differ - report an error
3171 } else if (thisp != base_classp) {
3173 // same assembly, but other attributes differ - report an error
3178 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3180 // if it's not "protected internal", it must be "protected"
3184 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3186 // protected within the same assembly - an error
3189 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3190 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3192 // protected ok, but other attributes differ - report an error
3198 return (thisp == base_classp);
3202 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3205 // FIXME: report the old/new permissions?
3208 507, Location, parent.MakeName (Name) +
3209 ": can't change the access modifiers when overriding inherited " +
3210 "member `" + name + "'");
3213 protected static string Error722 {
3215 return "'{0}': static types cannot be used as return types";
3220 /// For custom member duplication search in a container
3222 protected abstract bool CheckForDuplications ();
3225 /// Gets base method and its return type
3227 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3229 protected virtual bool DoDefineParameters ()
3231 EmitContext ec = Parent.EmitContext;
3233 throw new InternalErrorException ("DoDefineParameters invoked too early");
3235 bool old_unsafe = ec.InUnsafe;
3236 ec.InUnsafe = InUnsafe;
3237 // Check if arguments were correct
3238 parameter_types = Parameters.GetParameterInfo (ec);
3239 ec.InUnsafe = old_unsafe;
3241 if ((parameter_types == null) ||
3242 !CheckParameters (Parent, parameter_types))
3245 parameter_info = new InternalParameters (parameter_types, Parameters);
3247 Parameter array_param = Parameters.ArrayParameter;
3248 if ((array_param != null) &&
3249 (!array_param.ParameterType.IsArray ||
3250 (array_param.ParameterType.GetArrayRank () != 1))) {
3251 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3258 public override string[] ValidAttributeTargets {
3260 return attribute_targets;
3264 protected override bool VerifyClsCompliance (DeclSpace ds)
3266 if (!base.VerifyClsCompliance (ds)) {
3267 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3268 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3273 if (Parameters.HasArglist) {
3274 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3277 if (!AttributeTester.IsClsCompliant (MemberType)) {
3278 if (this is PropertyBase)
3279 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3280 GetSignatureForError ());
3282 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3283 GetSignatureForError ());
3286 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3291 protected bool IsDuplicateImplementation (MethodCore method)
3293 if ((method == this) || (method.Name != Name))
3296 Type[] param_types = method.ParameterTypes;
3297 if (param_types == null)
3300 if (param_types.Length != ParameterTypes.Length)
3303 for (int i = 0; i < param_types.Length; i++)
3304 if (param_types [i] != ParameterTypes [i])
3307 // TODO: make operator compatible with MethodCore to avoid this
3308 if (this is Operator && method is Operator) {
3309 if (MemberType != method.MemberType)
3314 // Try to report 663: method only differs on out/ref
3316 ParameterData info = ParameterInfo;
3317 ParameterData other_info = method.ParameterInfo;
3318 for (int i = 0; i < info.Count; i++){
3319 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3320 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3325 Report.SymbolRelatedToPreviousError (method);
3326 if (this is Operator && method is Operator)
3327 Report.Error (557, Location, "Duplicate user-defined conversion in type '{0}'", Parent.Name);
3329 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3334 // Returns a string that represents the signature for this
3335 // member which should be used in XML documentation.
3337 public override string GetDocCommentName (DeclSpace ds)
3339 return DocUtil.GetMethodDocCommentName (this, ds);
3343 // Raised (and passed an XmlElement that contains the comment)
3344 // when GenerateDocComment is writing documentation expectedly.
3346 // FIXME: with a few effort, it could be done with XmlReader,
3347 // that means removal of DOM use.
3349 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3351 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3355 // Represents header string for documentation comment.
3357 public override string DocCommentHeader {
3358 get { return "M:"; }
3361 protected override void VerifyObsoleteAttribute()
3363 base.VerifyObsoleteAttribute ();
3365 if (parameter_types == null)
3368 foreach (Type type in parameter_types) {
3369 CheckUsageOfObsoleteAttribute (type);
3374 public class SourceMethod : ISourceMethod
3376 TypeContainer container;
3379 protected SourceMethod (TypeContainer container, MethodBase builder,
3380 ISourceFile file, Location start, Location end)
3382 this.container = container;
3383 this.builder = builder;
3385 CodeGen.SymbolWriter.OpenMethod (
3386 file, this, start.Row, 0, end.Row, 0);
3389 public string Name {
3390 get { return builder.Name; }
3393 public int NamespaceID {
3394 get { return container.NamespaceEntry.SymbolFileID; }
3399 if (builder is MethodBuilder)
3400 return ((MethodBuilder) builder).GetToken ().Token;
3401 else if (builder is ConstructorBuilder)
3402 return ((ConstructorBuilder) builder).GetToken ().Token;
3404 throw new NotSupportedException ();
3408 public void CloseMethod ()
3410 if (CodeGen.SymbolWriter != null)
3411 CodeGen.SymbolWriter.CloseMethod ();
3414 public static SourceMethod Create (TypeContainer parent,
3415 MethodBase builder, Block block)
3417 if (CodeGen.SymbolWriter == null)
3422 Location start_loc = block.StartLocation;
3423 if (Location.IsNull (start_loc))
3426 Location end_loc = block.EndLocation;
3427 if (Location.IsNull (end_loc))
3430 ISourceFile file = start_loc.SourceFile;
3434 return new SourceMethod (
3435 parent, builder, file, start_loc, end_loc);
3439 public class Method : MethodCore, IIteratorContainer, IMethodData {
3440 public MethodBuilder MethodBuilder;
3441 public MethodData MethodData;
3442 ReturnParameter return_attributes;
3443 ListDictionary declarative_security;
3446 /// Modifiers allowed in a class declaration
3448 const int AllowedModifiers =
3451 Modifiers.PROTECTED |
3452 Modifiers.INTERNAL |
3457 Modifiers.OVERRIDE |
3458 Modifiers.ABSTRACT |
3460 Modifiers.METHOD_YIELDS |
3463 const int AllowedInterfaceModifiers =
3464 Modifiers.NEW | Modifiers.UNSAFE;
3467 // return_type can be "null" for VOID values.
3469 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3470 MemberName name, Parameters parameters, Attributes attrs,
3472 : base (ds, return_type, mod,
3473 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3474 is_iface, name, attrs, parameters, l)
3478 public override AttributeTargets AttributeTargets {
3480 return AttributeTargets.Method;
3484 public override string GetSignatureForError()
3486 if (MethodBuilder == null) {
3487 return GetSignatureForError (Parent);
3489 return TypeManager.CSharpSignature (MethodBuilder);
3493 /// Use this method when MethodBuilder is null
3495 public override string GetSignatureForError (TypeContainer tc)
3497 // TODO: get params from somewhere
3498 if (parameter_info == null)
3499 return base.GetSignatureForError (tc);
3501 // TODO: move to parameters
3502 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3503 if (parameter_info.Parameters.FixedParameters != null) {
3504 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3505 Parameter p = parameter_info.Parameters.FixedParameters [i];
3506 args.Append (p.GetSignatureForError ());
3508 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3513 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3516 void DuplicateEntryPoint (MethodInfo b, Location location)
3520 "Program `" + CodeGen.FileName +
3521 "' has more than one entry point defined: `" +
3522 TypeManager.CSharpSignature(b) + "'");
3525 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3527 if (b.ReturnType != TypeManager.void_type &&
3528 b.ReturnType != TypeManager.int32_type)
3531 if (pinfo.Count == 0)
3534 if (pinfo.Count > 1)
3537 Type t = pinfo.ParameterType(0);
3539 (t.GetArrayRank() == 1) &&
3540 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3541 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3547 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3549 if (a.Target == AttributeTargets.ReturnValue) {
3550 if (return_attributes == null)
3551 return_attributes = new ReturnParameter (MethodBuilder, Location);
3553 return_attributes.ApplyAttributeBuilder (a, cb);
3557 if (a.Type == TypeManager.methodimpl_attr_type &&
3558 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3559 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3562 if (a.Type == TypeManager.dllimport_type) {
3563 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3564 if ((ModFlags & extern_static) != extern_static) {
3565 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3571 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3572 if (declarative_security == null)
3573 declarative_security = new ListDictionary ();
3574 a.ExtractSecurityPermissionSet (declarative_security);
3578 if (a.Type == TypeManager.conditional_attribute_type) {
3579 if (IsOperator || IsExplicitImpl) {
3580 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3584 if (ReturnType != TypeManager.void_type) {
3585 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3589 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3590 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3595 Report.Error (582, Location, "Conditional not valid on interface members");
3599 if (MethodData.IsImplementing) {
3600 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3604 for (int i = 0; i < parameter_info.Count; ++i) {
3605 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3606 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3612 MethodBuilder.SetCustomAttribute (cb);
3615 protected override bool CheckForDuplications ()
3617 ArrayList ar = Parent.Methods;
3619 int arLen = ar.Count;
3621 for (int i = 0; i < arLen; i++) {
3622 Method m = (Method) ar [i];
3623 if (IsDuplicateImplementation (m))
3628 ar = Parent.Properties;
3630 for (int i = 0; i < ar.Count; ++i) {
3631 PropertyBase pb = (PropertyBase) ar [i];
3632 if (pb.AreAccessorsDuplicateImplementation (this))
3637 ar = Parent.Indexers;
3639 for (int i = 0; i < ar.Count; ++i) {
3640 PropertyBase pb = (PropertyBase) ar [i];
3641 if (pb.AreAccessorsDuplicateImplementation (this))
3648 for (int i = 0; i < ar.Count; ++i) {
3649 Event ev = (Event) ar [i];
3650 if (ev.AreAccessorsDuplicateImplementation (this))
3661 public override bool Define ()
3666 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3667 Error1599 (Location, ReturnType);
3675 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3677 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3679 if (!MethodData.Define (Parent))
3683 // Setup iterator if we are one
3685 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3686 Iterator iterator = new Iterator (
3687 Parent, Name, MemberType, ParameterTypes,
3688 ParameterInfo, ModFlags, block, Location);
3690 if (!iterator.DefineIterator ())
3693 block = iterator.Block;
3696 MethodBuilder = MethodData.MethodBuilder;
3699 // This is used to track the Entry Point,
3701 if (Name == "Main" &&
3702 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3703 (RootContext.MainClass == null ||
3704 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3705 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3706 if (RootContext.EntryPoint == null) {
3707 RootContext.EntryPoint = MethodBuilder;
3708 RootContext.EntryPointLocation = Location;
3710 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3711 DuplicateEntryPoint (MethodBuilder, Location);
3714 if (RootContext.WarningLevel >= 4)
3715 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3719 if (MemberType.IsAbstract && MemberType.IsSealed) {
3720 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3730 public override void Emit ()
3732 MethodData.Emit (Parent, this);
3735 if (declarative_security != null) {
3736 foreach (DictionaryEntry de in declarative_security) {
3737 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3745 public static void Error1599 (Location loc, Type t)
3747 Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
3750 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3752 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3753 container.TypeBuilder, Name, ParameterTypes, false);
3758 base_ret_type = mi.ReturnType;
3762 public override bool MarkForDuplicationCheck ()
3764 caching_flags |= Flags.TestMethodDuplication;
3768 protected override bool VerifyClsCompliance(DeclSpace ds)
3770 if (!base.VerifyClsCompliance (ds))
3773 if (parameter_types.Length > 0) {
3774 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3776 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3783 void IIteratorContainer.SetYields ()
3785 ModFlags |= Modifiers.METHOD_YIELDS;
3788 #region IMethodData Members
3790 public CallingConventions CallingConventions {
3792 CallingConventions cc = Parameters.GetCallingConvention ();
3793 if (Parameters.HasArglist)
3794 block.HasVarargs = true;
3797 if ((ModFlags & Modifiers.STATIC) == 0)
3798 cc |= CallingConventions.HasThis;
3800 // FIXME: How is `ExplicitThis' used in C#?
3806 public Type ReturnType {
3812 public MemberName MethodName {
3818 public new Location Location {
3820 return base.Location;
3824 protected override bool CheckBase() {
3825 if (!base.CheckBase ())
3828 // TODO: Destructor should derive from MethodCore
3829 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3830 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3831 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3838 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3840 return new EmitContext (
3841 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3844 public ObsoleteAttribute GetObsoleteAttribute ()
3846 return GetObsoleteAttribute (Parent);
3850 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3852 public bool IsExcluded (EmitContext ec)
3854 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3855 return (caching_flags & Flags.Excluded) != 0;
3857 caching_flags &= ~Flags.Excluded_Undetected;
3859 if (base_method == null) {
3860 if (OptAttributes == null)
3863 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3868 foreach (Attribute a in attrs) {
3869 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3870 if (RootContext.AllDefines.Contains (condition))
3874 caching_flags |= Flags.Excluded;
3878 IMethodData md = TypeManager.GetMethod (base_method);
3880 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
3881 caching_flags |= Flags.Excluded;
3887 if (md.IsExcluded (ec)) {
3888 caching_flags |= Flags.Excluded;
3897 public abstract class ConstructorInitializer {
3898 ArrayList argument_list;
3899 protected ConstructorInfo base_constructor;
3900 Parameters parameters;
3903 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
3906 this.argument_list = argument_list;
3907 this.parameters = parameters;
3911 public ArrayList Arguments {
3913 return argument_list;
3917 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
3919 Expression base_constructor_group;
3923 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
3925 if (argument_list != null){
3926 foreach (Argument a in argument_list){
3927 if (!a.Resolve (ec, loc))
3931 ec.CurrentBlock = null;
3933 if (this is ConstructorBaseInitializer) {
3934 if (ec.ContainerType.BaseType == null)
3937 t = ec.ContainerType.BaseType;
3938 if (ec.ContainerType.IsValueType) {
3939 Report.Error (522, loc,
3940 "structs cannot call base class constructors");
3944 t = ec.ContainerType;
3946 base_constructor_group = Expression.MemberLookup (
3947 ec, t, ".ctor", MemberTypes.Constructor,
3948 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3951 if (base_constructor_group == null){
3953 base_constructor_group = Expression.MemberLookup (
3954 ec, t, null, t, ".ctor", MemberTypes.Constructor,
3955 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3959 int errors = Report.Errors;
3960 if (base_constructor_group != null)
3961 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
3962 ec, (MethodGroupExpr) base_constructor_group, argument_list,
3965 if (base_constructor == null) {
3966 if (errors == Report.Errors)
3967 Report.Error (1501, loc, "Can not find a constructor for this argument list");
3972 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
3973 TypeManager.CSharpSignature (base_constructor));
3974 base_constructor = null;
3978 if (base_constructor == caller_builder){
3979 Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
3986 public void Emit (EmitContext ec)
3988 if (base_constructor != null){
3989 ec.Mark (loc, false);
3991 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
3993 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
3998 /// Method search for base ctor. (We do not cache it).
4000 Constructor GetOverloadedConstructor (TypeContainer tc)
4002 if (tc.InstanceConstructors == null)
4005 foreach (Constructor c in tc.InstanceConstructors) {
4006 if (Arguments == null) {
4007 if (c.ParameterTypes.Length == 0)
4015 int count = c.ParameterInfo.Count;
4017 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4018 for (int i = 0; i < count-1; i++)
4019 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4024 if (c.ParameterTypes.Length != Arguments.Count)
4027 for (int i = 0; i < Arguments.Count; ++i)
4028 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4043 //TODO: implement caching when it will be necessary
4044 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4046 Constructor ctor = GetOverloadedConstructor (tc);
4050 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4054 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4058 public class ConstructorBaseInitializer : ConstructorInitializer {
4059 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4060 base (argument_list, pars, l)
4064 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4065 if (base_constructor == null)
4068 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4069 if (type_ds == null) {
4070 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (base_constructor);
4073 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (base_constructor), loc);
4078 base.CheckObsoleteAttribute (type_ds, loc);
4083 public class ConstructorThisInitializer : ConstructorInitializer {
4084 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4085 base (argument_list, pars, l)
4090 public class Constructor : MethodCore, IMethodData {
4091 public ConstructorBuilder ConstructorBuilder;
4092 public ConstructorInitializer Initializer;
4093 ListDictionary declarative_security;
4096 // Modifiers allowed for a constructor.
4098 public const int AllowedModifiers =
4100 Modifiers.PROTECTED |
4101 Modifiers.INTERNAL |
4107 bool has_compliant_args = false;
4109 // The spec claims that static is not permitted, but
4110 // my very own code has static constructors.
4112 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4113 ConstructorInitializer init, Location l)
4114 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4120 public override string GetSignatureForError()
4122 if (ConstructorBuilder == null)
4123 return GetSignatureForError (Parent);
4125 return TypeManager.CSharpSignature (ConstructorBuilder);
4128 public bool HasCompliantArgs {
4130 return has_compliant_args;
4134 public override AttributeTargets AttributeTargets {
4136 return AttributeTargets.Constructor;
4142 // Returns true if this is a default constructor
4144 public bool IsDefault ()
4146 if ((ModFlags & Modifiers.STATIC) != 0)
4147 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4148 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4151 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4152 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4153 (Initializer is ConstructorBaseInitializer) &&
4154 (Initializer.Arguments == null);
4157 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4159 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4160 if (declarative_security == null) {
4161 declarative_security = new ListDictionary ();
4163 a.ExtractSecurityPermissionSet (declarative_security);
4167 ConstructorBuilder.SetCustomAttribute (cb);
4170 protected override bool CheckForDuplications ()
4172 ArrayList ar = Parent.InstanceConstructors;
4174 int arLen = ar.Count;
4176 for (int i = 0; i < arLen; i++) {
4177 Constructor m = (Constructor) ar [i];
4178 if (IsDuplicateImplementation (m))
4185 protected override bool CheckBase ()
4187 // Check whether arguments were correct.
4188 if (!DoDefineParameters ())
4191 // TODO: skip the rest for generated ctor
4192 if ((ModFlags & Modifiers.STATIC) != 0)
4195 if (!CheckForDuplications ())
4198 if (Parent.Kind == Kind.Struct) {
4199 if (ParameterTypes.Length == 0) {
4200 Report.Error (568, Location,
4201 "Structs can not contain explicit parameterless " +
4206 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4207 Report.Error (666, Location, "Protected member in struct declaration");
4212 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4213 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4220 // Creates the ConstructorBuilder
4222 public override bool Define ()
4224 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4225 MethodAttributes.SpecialName);
4227 if ((ModFlags & Modifiers.STATIC) != 0) {
4228 ca |= MethodAttributes.Static | MethodAttributes.Private;
4230 ca |= MethodAttributes.HideBySig;
4232 if ((ModFlags & Modifiers.PUBLIC) != 0)
4233 ca |= MethodAttributes.Public;
4234 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4235 if ((ModFlags & Modifiers.INTERNAL) != 0)
4236 ca |= MethodAttributes.FamORAssem;
4238 ca |= MethodAttributes.Family;
4239 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4240 ca |= MethodAttributes.Assembly;
4241 else if (IsDefault ())
4242 ca |= MethodAttributes.Public;
4244 ca |= MethodAttributes.Private;
4247 // Check if arguments were correct.
4251 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4252 ca, CallingConventions,
4255 if ((ModFlags & Modifiers.UNSAFE) != 0)
4256 ConstructorBuilder.InitLocals = false;
4258 TypeManager.AddMethod (ConstructorBuilder, this);
4261 // HACK because System.Reflection.Emit is lame
4263 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4271 public override void Emit ()
4273 EmitContext ec = CreateEmitContext (null, null);
4276 // extern methods have no bodies
4278 if ((ModFlags & Modifiers.EXTERN) != 0) {
4279 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4281 179, Location, "External constructor `" +
4282 TypeManager.CSharpSignature (ConstructorBuilder) +
4283 "' can not have a body");
4286 } else if (block == null) {
4288 501, Location, "Constructor `" +
4289 TypeManager.CSharpSignature (ConstructorBuilder) +
4290 "' must declare a body since it is not marked extern");
4294 if ((ModFlags & Modifiers.STATIC) == 0){
4295 if (Parent.Kind == Kind.Class && Initializer == null)
4296 Initializer = new ConstructorBaseInitializer (
4297 null, Parameters.EmptyReadOnlyParameters, Location);
4301 // Spec mandates that Initializers will not have
4305 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4307 ec.IsStatic = false;
4310 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4312 SourceMethod source = SourceMethod.Create (
4313 Parent, ConstructorBuilder, block);
4316 // Classes can have base initializers and instance field initializers.
4318 if (Parent.Kind == Kind.Class){
4319 if ((ModFlags & Modifiers.STATIC) == 0){
4322 // If we use a "this (...)" constructor initializer, then
4323 // do not emit field initializers, they are initialized in the other constructor
4325 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4326 Parent.EmitFieldInitializers (ec);
4329 if (Initializer != null) {
4330 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4331 Initializer.CheckObsoleteAttribute (Parent, Location);
4333 ec.TestObsoleteMethodUsage = false;
4334 Initializer.Emit (ec);
4337 if ((ModFlags & Modifiers.STATIC) != 0)
4338 Parent.EmitFieldInitializers (ec);
4340 if (OptAttributes != null)
4341 OptAttributes.Emit (ec, this);
4343 // If this is a non-static `struct' constructor and doesn't have any
4344 // initializer, it must initialize all of the struct's fields.
4345 if ((Parent.Kind == Kind.Struct) &&
4346 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4347 Block.AddThisVariable (Parent, Location);
4349 ec.EmitTopBlock (block, ParameterInfo, Location);
4352 source.CloseMethod ();
4356 if (declarative_security != null) {
4357 foreach (DictionaryEntry de in declarative_security) {
4358 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4365 // Is never override
4366 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4371 protected override bool VerifyClsCompliance (DeclSpace ds)
4373 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4377 if (parameter_types.Length > 0) {
4378 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4380 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4382 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4383 foreach (Type param in parameter_types) {
4384 if (param.IsArray) {
4390 has_compliant_args = true;
4394 #region IMethodData Members
4396 public System.Reflection.CallingConventions CallingConventions {
4398 CallingConventions cc = Parameters.GetCallingConvention ();
4400 if (Parent.Kind == Kind.Class)
4401 if ((ModFlags & Modifiers.STATIC) == 0)
4402 cc |= CallingConventions.HasThis;
4404 // FIXME: How is `ExplicitThis' used in C#?
4410 public new Location Location {
4412 return base.Location;
4416 public MemberName MethodName {
4422 public Type ReturnType {
4428 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4430 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4431 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4434 public ObsoleteAttribute GetObsoleteAttribute ()
4439 public bool IsExcluded(EmitContext ec)
4448 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4450 public interface IMethodData
4452 CallingConventions CallingConventions { get; }
4453 Location Location { get; }
4454 MemberName MethodName { get; }
4455 Type[] ParameterTypes { get; }
4456 Type ReturnType { get; }
4458 Attributes OptAttributes { get; }
4459 ToplevelBlock Block { get; }
4461 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4462 ObsoleteAttribute GetObsoleteAttribute ();
4463 string GetSignatureForError (TypeContainer tc);
4464 bool IsExcluded (EmitContext ec);
4465 bool IsClsCompliaceRequired (DeclSpace ds);
4469 // Encapsulates most of the Method's state
4471 public class MethodData {
4473 readonly IMethodData method;
4476 // The return type of this method
4478 public readonly InternalParameters ParameterInfo;
4481 // Are we implementing an interface ?
4483 public bool IsImplementing = false;
4488 protected MemberBase member;
4489 protected int modifiers;
4490 protected MethodAttributes flags;
4492 MethodBuilder builder = null;
4493 public MethodBuilder MethodBuilder {
4499 public MethodData (MemberBase member, InternalParameters parameters,
4500 int modifiers, MethodAttributes flags, IMethodData method)
4502 this.member = member;
4503 this.ParameterInfo = parameters;
4504 this.modifiers = modifiers;
4507 this.method = method;
4510 public bool Define (TypeContainer container)
4512 MethodInfo implementing = null;
4514 string name = method.MethodName.Name;
4515 string method_name = name;
4517 Type[] ParameterTypes = method.ParameterTypes;
4519 if (container.Pending != null){
4520 if (member is Indexer) // TODO: test it, but it should work without this IF
4521 implementing = container.Pending.IsInterfaceIndexer (
4522 member.InterfaceType, method.ReturnType, ParameterTypes);
4524 implementing = container.Pending.IsInterfaceMethod (
4525 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4527 if (member.InterfaceType != null){
4528 if (implementing == null){
4529 if (member is PropertyBase) {
4530 Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
4531 method.GetSignatureForError (container), member.ExplicitInterfaceName);
4534 Report.Error (539, method.Location,
4535 "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
4539 method_name = member.InterfaceType.FullName + "." + name;
4541 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
4542 Report.SymbolRelatedToPreviousError (implementing);
4543 Report.Error (688, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
4544 method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4551 // For implicit implementations, make sure we are public, for
4552 // explicit implementations, make sure we are private.
4554 if (implementing != null){
4556 // Setting null inside this block will trigger a more
4557 // verbose error reporting for missing interface implementations
4559 // The "candidate" function has been flagged already
4560 // but it wont get cleared
4562 if (member.IsExplicitImpl){
4563 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4564 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4565 implementing = null;
4567 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4568 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4570 // If this is an interface method implementation,
4571 // check for public accessibility
4573 implementing = null;
4574 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4575 // We may never be private.
4576 implementing = null;
4577 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4579 // We may be protected if we're overriding something.
4581 implementing = null;
4586 // Static is not allowed
4588 if ((modifiers & Modifiers.STATIC) != 0){
4589 implementing = null;
4590 Modifiers.Error_InvalidModifier (method.Location, "static");
4595 // If implementing is still valid, set flags
4597 if (implementing != null){
4599 // When implementing interface methods, set NewSlot
4600 // unless, we are overwriting a method.
4602 if (implementing.DeclaringType.IsInterface){
4603 if ((modifiers & Modifiers.OVERRIDE) == 0)
4604 flags |= MethodAttributes.NewSlot;
4607 MethodAttributes.Virtual |
4608 MethodAttributes.HideBySig;
4610 // Set Final unless we're virtual, abstract or already overriding a method.
4611 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4612 flags |= MethodAttributes.Final;
4614 IsImplementing = true;
4617 EmitContext ec = method.CreateEmitContext (container, null);
4619 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4621 if (builder == null)
4624 if ((modifiers & Modifiers.UNSAFE) != 0)
4625 builder.InitLocals = false;
4627 if (IsImplementing){
4629 // clear the pending implemntation flag
4631 if (member is Indexer) {
4632 container.Pending.ImplementIndexer (
4633 member.InterfaceType, builder, method.ReturnType,
4634 ParameterTypes, member.IsExplicitImpl);
4636 container.Pending.ImplementMethod (
4637 member.InterfaceType, name, method.ReturnType,
4638 ParameterTypes, member.IsExplicitImpl);
4640 if (member.IsExplicitImpl)
4641 container.TypeBuilder.DefineMethodOverride (
4642 builder, implementing);
4646 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4647 TypeManager.AddMethod (builder, method);
4654 /// Create the MethodBuilder for the method
4656 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4658 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4660 if ((modifiers & extern_static) == extern_static) {
4662 if (method.OptAttributes != null) {
4663 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4664 if (dllimport_attribute != null) {
4665 flags |= MethodAttributes.PinvokeImpl;
4666 builder = dllimport_attribute.DefinePInvokeMethod (
4667 ec, container.TypeBuilder, method_name, flags,
4668 method.ReturnType, ParameterTypes);
4674 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4675 // We are more strict than Microsoft and report CS0626 like error
4676 if (method.OptAttributes == null ||
4677 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4678 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));
4683 builder = container.TypeBuilder.DefineMethod (
4684 method_name, flags, method.CallingConventions,
4685 method.ReturnType, ParameterTypes);
4691 public void Emit (TypeContainer container, Attributable kind)
4694 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4695 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4697 ec = method.CreateEmitContext (container, null);
4699 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container.Parent) != null)
4700 ec.TestObsoleteMethodUsage = false;
4702 Location loc = method.Location;
4703 Attributes OptAttributes = method.OptAttributes;
4705 if (OptAttributes != null)
4706 OptAttributes.Emit (ec, kind);
4708 if (member is MethodCore)
4709 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4711 ToplevelBlock block = method.Block;
4714 // abstract or extern methods have no bodies
4716 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4721 // abstract or extern methods have no bodies.
4723 if ((modifiers & Modifiers.ABSTRACT) != 0)
4725 500, method.Location, "Abstract method `" +
4726 TypeManager.CSharpSignature (builder) +
4727 "' can not have a body");
4729 if ((modifiers & Modifiers.EXTERN) != 0)
4731 179, method.Location, "External method `" +
4732 TypeManager.CSharpSignature (builder) +
4733 "' can not have a body");
4739 // Methods must have a body unless they're extern or abstract
4741 if (block == null) {
4743 501, method.Location, "Method `" +
4744 TypeManager.CSharpSignature (builder) +
4745 "' must declare a body since it is not marked " +
4746 "abstract or extern");
4750 SourceMethod source = SourceMethod.Create (
4751 container, MethodBuilder, method.Block);
4754 // Handle destructors specially
4756 // FIXME: This code generates buggy code
4758 if (member is Destructor)
4759 EmitDestructor (ec, block);
4761 ec.EmitTopBlock (block, ParameterInfo, loc);
4764 source.CloseMethod ();
4767 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4769 ILGenerator ig = ec.ig;
4771 Label finish = ig.DefineLabel ();
4773 block.SetDestructor ();
4775 ig.BeginExceptionBlock ();
4776 ec.ReturnLabel = finish;
4777 ec.HasReturnLabel = true;
4778 ec.EmitTopBlock (block, null, method.Location);
4780 // ig.MarkLabel (finish);
4781 ig.BeginFinallyBlock ();
4783 if (ec.ContainerType.BaseType != null) {
4784 Expression member_lookup = Expression.MemberLookup (
4785 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4786 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4788 if (member_lookup != null){
4789 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4791 ig.Emit (OpCodes.Ldarg_0);
4792 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4796 ig.EndExceptionBlock ();
4797 //ig.MarkLabel (ec.ReturnLabel);
4798 ig.Emit (OpCodes.Ret);
4802 // Should derive from MethodCore
4803 public class Destructor : Method {
4805 public Destructor (TypeContainer ds, Expression return_type, int mod,
4806 string name, Parameters parameters, Attributes attrs,
4808 : base (ds, return_type, mod, false, new MemberName (name),
4809 parameters, attrs, l)
4812 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4814 if (a.Type == TypeManager.conditional_attribute_type) {
4815 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4819 base.ApplyAttributeBuilder (a, cb);
4823 abstract public class MemberBase : MemberCore {
4824 public Expression Type;
4826 public MethodAttributes flags;
4828 protected readonly int explicit_mod_flags;
4831 // The "short" name of this property / indexer / event. This is the
4832 // name without the explicit interface.
4834 public string ShortName;
4837 // The type of this property / indexer / event
4839 public Type MemberType;
4842 // If true, this is an explicit interface implementation
4844 public bool IsExplicitImpl = false;
4847 // The name of the interface we are explicitly implementing
4849 public MemberName ExplicitInterfaceName = null;
4852 // Whether this is an interface member.
4854 public bool IsInterface;
4857 // If true, the interface type we are explicitly implementing
4859 public Type InterfaceType = null;
4862 // The constructor is only exposed to our children
4864 protected MemberBase (TypeContainer parent, Expression type, int mod,
4865 int allowed_mod, int def_mod, MemberName name,
4866 Attributes attrs, Location loc)
4867 : base (parent, name, attrs, loc)
4869 explicit_mod_flags = mod;
4871 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4873 // Check for explicit interface implementation
4874 if (MemberName.Left != null) {
4875 ExplicitInterfaceName = MemberName.Left;
4876 ShortName = MemberName.Name;
4877 IsExplicitImpl = true;
4882 protected virtual bool CheckBase ()
4884 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4885 Report.Error (666, Location, "Protected member in struct declaration");
4889 if ((RootContext.WarningLevel >= 4) &&
4890 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4891 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4892 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4893 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4898 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4902 foreach (Type partype in parameters){
4903 if (partype == TypeManager.void_type) {
4905 1547, Location, "Keyword 'void' cannot " +
4906 "be used in this context");
4910 if (partype.IsPointer){
4913 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4917 if (ds.AsAccessible (partype, ModFlags))
4920 if (this is Indexer)
4921 Report.Error (55, Location,
4922 "Inconsistent accessibility: parameter type `" +
4923 TypeManager.CSharpName (partype) + "' is less " +
4924 "accessible than indexer `" + Name + "'");
4925 else if ((this is Method) && ((Method) this).IsOperator)
4926 Report.Error (57, Location,
4927 "Inconsistent accessibility: parameter type `" +
4928 TypeManager.CSharpName (partype) + "' is less " +
4929 "accessible than operator `" + Name + "'");
4931 Report.Error (51, Location,
4932 "Inconsistent accessibility: parameter type `" +
4933 TypeManager.CSharpName (partype) + "' is less " +
4934 "accessible than method `" + Name + "'");
4941 protected virtual bool DoDefine ()
4943 EmitContext ec = Parent.EmitContext;
4945 throw new InternalErrorException ("MemberBase.DoDefine called too early");
4948 throw new InternalErrorException ();
4951 ModFlags = Modifiers.PUBLIC |
4952 Modifiers.ABSTRACT |
4953 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
4955 flags = MethodAttributes.Public |
4956 MethodAttributes.Abstract |
4957 MethodAttributes.HideBySig |
4958 MethodAttributes.NewSlot |
4959 MethodAttributes.Virtual;
4961 if (!Parent.MethodModifiersValid (this))
4964 flags = Modifiers.MethodAttr (ModFlags);
4967 // Lookup Type, verify validity
4968 bool old_unsafe = ec.InUnsafe;
4969 ec.InUnsafe = InUnsafe;
4970 Type = Type.ResolveAsTypeTerminal (ec, false);
4971 ec.InUnsafe = old_unsafe;
4976 MemberType = Type.Type;
4978 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
4979 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
4980 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
4985 // verify accessibility
4986 if (!Parent.AsAccessible (MemberType, ModFlags)) {
4987 Report.SymbolRelatedToPreviousError (MemberType);
4988 if (this is Property)
4989 Report.Error (53, Location,
4990 "Inconsistent accessibility: property type `" +
4991 TypeManager.CSharpName (MemberType) + "' is less " +
4992 "accessible than property `" + GetSignatureForError () + "'");
4993 else if (this is Indexer)
4994 Report.Error (54, Location,
4995 "Inconsistent accessibility: indexer return type `" +
4996 TypeManager.CSharpName (MemberType) + "' is less " +
4997 "accessible than indexer `" + Name + "'");
4998 else if (this is MethodCore) {
4999 if (this is Operator)
5000 Report.Error (56, Location,
5001 "Inconsistent accessibility: return type `" +
5002 TypeManager.CSharpName (MemberType) + "' is less " +
5003 "accessible than operator `" + Name + "'");
5005 Report.Error (50, Location,
5006 "Inconsistent accessibility: return type `" +
5007 TypeManager.CSharpName (MemberType) + "' is less " +
5008 "accessible than method `" + Name + "'");
5010 Report.Error (52, Location,
5011 "Inconsistent accessibility: field type `" +
5012 TypeManager.CSharpName (MemberType) + "' is less " +
5013 "accessible than field `" + Name + "'");
5018 if (MemberType.IsPointer && !UnsafeOK (Parent))
5021 if (IsExplicitImpl) {
5022 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
5023 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5027 InterfaceType = texpr.ResolveType (ec);
5029 if (!InterfaceType.IsInterface) {
5030 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5035 // Compute the full name that we need to export.
5036 if (InterfaceType.FullName != ExplicitInterfaceName) {
5037 ExplicitInterfaceName = InterfaceType.FullName;
5038 UpdateMemberName ();
5042 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5045 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5052 /// The name of the member can be changed during definition (see IndexerName attribute)
5054 protected virtual void UpdateMemberName ()
5056 MemberName.Name = ShortName;
5059 public override string GetSignatureForError (TypeContainer tc)
5061 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5064 protected bool IsTypePermitted ()
5066 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5067 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5073 protected override bool VerifyClsCompliance(DeclSpace ds)
5075 if (base.VerifyClsCompliance (ds)) {
5079 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5080 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5085 protected override void VerifyObsoleteAttribute()
5087 CheckUsageOfObsoleteAttribute (MemberType);
5092 // Fields and Events both generate FieldBuilders, we use this to share
5093 // their common bits. This is also used to flag usage of the field
5095 abstract public class FieldBase : MemberBase {
5096 public FieldBuilder FieldBuilder;
5097 public Status status;
5100 public enum Status : byte {
5103 HAS_OFFSET = 4 // Used by FieldMember.
5106 static string[] attribute_targets = new string [] { "field" };
5109 /// Symbol with same name in base class/struct
5111 public MemberInfo conflict_symbol;
5114 // The constructor is only exposed to our children
5116 protected FieldBase (TypeContainer parent, Expression type, int mod,
5117 int allowed_mod, MemberName name, object init,
5118 Attributes attrs, Location loc)
5119 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5125 public override AttributeTargets AttributeTargets {
5127 return AttributeTargets.Field;
5131 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5133 if (a.Type == TypeManager.marshal_as_attr_type) {
5134 UnmanagedMarshal marshal = a.GetMarshal (this);
5135 if (marshal != null) {
5136 FieldBuilder.SetMarshal (marshal);
5141 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5142 a.Error_InvalidSecurityParent ();
5146 FieldBuilder.SetCustomAttribute (cb);
5150 // Whether this field has an initializer.
5152 public bool HasInitializer {
5154 return init != null;
5158 protected readonly Object init;
5161 Expression init_expr;
5162 bool init_expr_initialized = false;
5165 // Resolves and returns the field initializer.
5167 public Expression GetInitializerExpression (EmitContext ec)
5169 if (init_expr_initialized)
5173 if (init is Expression)
5174 e = (Expression) init;
5176 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5178 ec.IsFieldInitializer = true;
5179 e = e.DoResolve (ec);
5180 ec.IsFieldInitializer = false;
5183 init_expr_initialized = true;
5188 protected override bool CheckBase ()
5190 if (!base.CheckBase ())
5197 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5198 if (conflict_symbol == null) {
5199 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5200 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5205 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5206 Report.SymbolRelatedToPreviousError (conflict_symbol);
5207 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5213 public override string GetSignatureForError ()
5215 if (FieldBuilder == null) {
5216 return base.GetSignatureForError (Parent);
5218 return TypeManager.GetFullNameSignature (FieldBuilder);
5221 protected virtual bool IsFieldClsCompliant {
5223 if (FieldBuilder == null)
5226 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5230 public override string[] ValidAttributeTargets {
5232 return attribute_targets;
5236 protected override bool VerifyClsCompliance (DeclSpace ds)
5238 if (!base.VerifyClsCompliance (ds))
5241 if (!IsFieldClsCompliant) {
5242 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5248 public void SetAssigned ()
5250 status |= Status.ASSIGNED;
5254 public abstract class FieldMember: FieldBase
5258 protected FieldMember (TypeContainer parent, Expression type, int mod,
5259 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5260 : base (parent, type, mod, allowed_mod, name, init, attrs, loc)
5264 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5266 if (a.Type == TypeManager.field_offset_attribute_type)
5268 status |= Status.HAS_OFFSET;
5270 if (!Parent.HasExplicitLayout) {
5271 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5275 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5276 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5280 base.ApplyAttributeBuilder (a, cb);
5284 public override bool Define()
5286 EmitContext ec = Parent.EmitContext;
5288 throw new InternalErrorException ("FieldMember.Define called too early");
5290 bool old_unsafe = ec.InUnsafe;
5291 ec.InUnsafe = InUnsafe;
5292 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
5296 MemberType = texpr.ResolveType (ec);
5298 ec.InUnsafe = old_unsafe;
5300 if (MemberType == TypeManager.void_type) {
5301 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5308 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5309 Report.Error (52, Location,
5310 "Inconsistent accessibility: field type `" +
5311 TypeManager.CSharpName (MemberType) + "' is less " +
5312 "accessible than field `" + Name + "'");
5316 if (!IsTypePermitted ())
5319 if (MemberType.IsPointer && !UnsafeOK (Parent))
5325 public override void Emit ()
5327 if (OptAttributes != null) {
5328 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5329 OptAttributes.Emit (ec, this);
5332 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5333 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5340 // Represents header string for documentation comment.
5342 public override string DocCommentHeader {
5343 get { return "F:"; }
5347 interface IFixedBuffer
5349 FieldInfo Element { get; }
5350 Type ElementType { get; }
5353 public class FixedFieldExternal: IFixedBuffer
5355 FieldInfo element_field;
5357 public FixedFieldExternal (FieldInfo fi)
5359 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5362 #region IFixedField Members
5364 public FieldInfo Element {
5366 return element_field;
5370 public Type ElementType {
5372 return element_field.FieldType;
5380 /// Fixed buffer implementation
5382 public class FixedField: FieldMember, IFixedBuffer
5384 public const string FixedElementName = "FixedElementField";
5385 static int GlobalCounter = 0;
5386 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5387 static FieldInfo[] fi;
5389 TypeBuilder fixed_buffer_type;
5390 FieldBuilder element;
5391 Expression size_expr;
5394 const int AllowedModifiers =
5397 Modifiers.PROTECTED |
5398 Modifiers.INTERNAL |
5401 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5402 Expression size_expr, Attributes attrs, Location loc):
5403 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5405 if (RootContext.Version == LanguageVersion.ISO_1)
5406 Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
5408 this.size_expr = size_expr;
5411 public override bool Define()
5414 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5415 Report.Warning (-23, Location, "Only not private or internal fixed sized buffers are supported by .NET 1.x");
5418 if (Parent.Kind != Kind.Struct) {
5419 Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
5423 if (!base.Define ())
5426 if (!MemberType.IsPrimitive) {
5427 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");
5431 Expression e = size_expr.Resolve (Parent.EmitContext);
5435 Constant c = e as Constant;
5437 Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
5441 buffer_size = (int)c.GetValue ();
5442 if (buffer_size <= 0) {
5443 Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
5446 buffer_size *= Expression.GetTypeSize (MemberType);
5449 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5451 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5452 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5453 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5454 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5456 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5457 TypeManager.RegisterFieldBase (FieldBuilder, this);
5462 public override void Emit()
5465 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5467 object[] fi_val = new object[1];
5468 fi_val [0] = buffer_size;
5470 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5471 ctor_args, fi, fi_val);
5472 fixed_buffer_type.SetCustomAttribute (cab);
5475 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5476 FieldBuilder.SetCustomAttribute (cab);
5481 protected override bool IsFieldClsCompliant {
5487 #region IFixedField Members
5489 public FieldInfo Element {
5495 public Type ElementType {
5505 // The Field class is used to represents class/struct fields during parsing.
5507 public class Field : FieldMember {
5509 // Modifiers allowed in a class declaration
5511 const int AllowedModifiers =
5514 Modifiers.PROTECTED |
5515 Modifiers.INTERNAL |
5518 Modifiers.VOLATILE |
5522 public Field (TypeContainer parent, Expression type, int mod, string name,
5523 Object expr_or_array_init, Attributes attrs, Location loc)
5524 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5525 expr_or_array_init, attrs, loc)
5529 public override bool Define ()
5531 if (!base.Define ())
5534 if (RootContext.WarningLevel > 1){
5535 Type ptype = Parent.TypeBuilder.BaseType;
5537 // ptype is only null for System.Object while compiling corlib.
5539 TypeContainer.FindMembers (
5540 ptype, MemberTypes.Method,
5541 BindingFlags.Public |
5542 BindingFlags.Static | BindingFlags.Instance,
5543 System.Type.FilterName, Name);
5547 if ((ModFlags & Modifiers.VOLATILE) != 0){
5548 if (!MemberType.IsClass){
5549 Type vt = MemberType;
5551 if (TypeManager.IsEnumType (vt))
5552 vt = TypeManager.EnumToUnderlying (MemberType);
5554 if (!((vt == TypeManager.bool_type) ||
5555 (vt == TypeManager.sbyte_type) ||
5556 (vt == TypeManager.byte_type) ||
5557 (vt == TypeManager.short_type) ||
5558 (vt == TypeManager.ushort_type) ||
5559 (vt == TypeManager.int32_type) ||
5560 (vt == TypeManager.uint32_type) ||
5561 (vt == TypeManager.char_type) ||
5562 (vt == TypeManager.float_type) ||
5563 (!vt.IsValueType))){
5565 677, Location, Parent.MakeName (Name) +
5566 " A volatile field can not be of type `" +
5567 TypeManager.CSharpName (vt) + "'");
5572 if ((ModFlags & Modifiers.READONLY) != 0){
5575 "A field can not be both volatile and readonly");
5580 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5582 if (Parent.Kind == Kind.Struct &&
5583 ((fa & FieldAttributes.Static) == 0) &&
5584 MemberType == Parent.TypeBuilder &&
5585 !TypeManager.IsBuiltinType (MemberType)){
5586 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5587 "' causes a cycle in the structure layout");
5592 FieldBuilder = Parent.TypeBuilder.DefineField (
5593 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5595 TypeManager.RegisterFieldBase (FieldBuilder, this);
5597 catch (ArgumentException) {
5598 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5607 // `set' and `get' accessors are represented with an Accessor.
5609 public class Accessor {
5611 // Null if the accessor is empty, or a Block if not
5613 public const int AllowedModifiers =
5615 Modifiers.PROTECTED |
5616 Modifiers.INTERNAL |
5619 public ToplevelBlock Block;
5620 public Attributes Attributes;
5621 public Location Location;
5622 public int ModFlags;
5624 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5629 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5634 // Ooouh Martin, templates are missing here.
5635 // When it will be possible move here a lot of child code and template method type.
5636 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5637 protected MethodData method_data;
5638 protected ToplevelBlock block;
5639 protected ListDictionary declarative_security;
5641 // The accessor are created event if they are not wanted.
5642 // But we need them because their names are reserved.
5643 // Field says whether accessor will be emited or not
5644 public readonly bool IsDummy;
5646 protected readonly string prefix;
5648 ReturnParameter return_attributes;
5650 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5651 : base (null, SetupName (prefix, member), null, member.Location)
5653 this.prefix = prefix;
5657 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5659 : base (null, SetupName (prefix, member),
5660 accessor.Attributes, accessor.Location)
5662 this.prefix = prefix;
5663 this.block = accessor.Block;
5666 static MemberName SetupName (string prefix, MemberBase member)
5668 MemberName name = member.MemberName.Clone ();
5669 name.Name = prefix + member.ShortName;
5673 public void UpdateName (MemberBase member)
5675 MemberName.Name = prefix + member.ShortName;
5678 #region IMethodData Members
5680 public ToplevelBlock Block {
5690 public CallingConventions CallingConventions {
5692 return CallingConventions.Standard;
5696 public bool IsExcluded (EmitContext ec)
5701 public MemberName MethodName {
5707 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5708 public abstract Type[] ParameterTypes { get; }
5709 public abstract Type ReturnType { get; }
5710 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5714 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5716 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5717 a.Type == TypeManager.conditional_attribute_type) {
5718 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 ());
5722 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5723 if (declarative_security == null)
5724 declarative_security = new ListDictionary ();
5725 a.ExtractSecurityPermissionSet (declarative_security);
5729 if (a.Target == AttributeTargets.Method) {
5730 method_data.MethodBuilder.SetCustomAttribute (cb);
5734 if (a.Target == AttributeTargets.ReturnValue) {
5735 if (return_attributes == null)
5736 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5738 return_attributes.ApplyAttributeBuilder (a, cb);
5742 ApplyToExtraTarget (a, cb);
5745 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5747 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5750 public override bool Define()
5752 throw new NotSupportedException ();
5755 public virtual void Emit (TypeContainer container)
5757 method_data.Emit (container, this);
5759 if (declarative_security != null) {
5760 foreach (DictionaryEntry de in declarative_security) {
5761 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5768 public override bool IsClsCompliaceRequired(DeclSpace ds)
5773 public bool IsDuplicateImplementation (MethodCore method)
5775 if (Name != method.Name)
5778 Type[] param_types = method.ParameterTypes;
5780 if (param_types.Length != ParameterTypes.Length)
5783 for (int i = 0; i < param_types.Length; i++)
5784 if (param_types [i] != ParameterTypes [i])
5787 Report.SymbolRelatedToPreviousError (method);
5788 Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
5792 public new Location Location {
5794 return base.Location;
5799 // Represents header string for documentation comment.
5801 public override string DocCommentHeader {
5802 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5805 protected override void VerifyObsoleteAttribute()
5812 // Properties and Indexers both generate PropertyBuilders, we use this to share
5813 // their common bits.
5815 abstract public class PropertyBase : MethodCore {
5817 public class GetMethod: PropertyMethod
5819 static string[] attribute_targets = new string [] { "method", "return" };
5821 public GetMethod (MethodCore method):
5822 base (method, "get_")
5826 public GetMethod (MethodCore method, Accessor accessor):
5827 base (method, accessor, "get_")
5831 public override MethodBuilder Define(TypeContainer container)
5833 base.Define (container);
5835 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5837 if (!method_data.Define (container))
5840 return method_data.MethodBuilder;
5843 public override string GetSignatureForError (TypeContainer tc)
5845 return String.Concat (base.GetSignatureForError (tc), ".get");
5848 public override Type ReturnType {
5850 return method.MemberType;
5854 public override string[] ValidAttributeTargets {
5856 return attribute_targets;
5861 public class SetMethod: PropertyMethod {
5863 static string[] attribute_targets = new string [] { "method", "param", "return" };
5864 ImplicitParameter param_attr;
5866 public SetMethod (MethodCore method):
5867 base (method, "set_")
5871 public SetMethod (MethodCore method, Accessor accessor):
5872 base (method, accessor, "set_")
5876 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5878 if (a.Target == AttributeTargets.Parameter) {
5879 if (param_attr == null)
5880 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5882 param_attr.ApplyAttributeBuilder (a, cb);
5886 base.ApplyAttributeBuilder (a, cb);
5889 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5891 Parameter [] parms = new Parameter [1];
5892 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
5893 Parameters parameters = new Parameters (parms, null, method.Location);
5895 bool old_unsafe = ec.InUnsafe;
5896 ec.InUnsafe = InUnsafe;
5897 Type [] types = parameters.GetParameterInfo (ec);
5898 ec.InUnsafe = old_unsafe;
5900 return new InternalParameters (types, parameters);
5903 public override MethodBuilder Define (TypeContainer container)
5905 if (container.EmitContext == null)
5906 throw new InternalErrorException ("SetMethod.Define called too early");
5908 base.Define (container);
5910 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5912 if (!method_data.Define (container))
5915 return method_data.MethodBuilder;
5918 public override string GetSignatureForError (TypeContainer tc)
5920 return String.Concat (base.GetSignatureForError (tc), ".set");
5923 public override Type[] ParameterTypes {
5925 return new Type[] { method.MemberType };
5929 public override Type ReturnType {
5931 return TypeManager.void_type;
5935 public override string[] ValidAttributeTargets {
5937 return attribute_targets;
5942 static string[] attribute_targets = new string [] { "property" };
5944 public abstract class PropertyMethod: AbstractPropertyEventMethod
5946 protected readonly MethodCore method;
5947 protected MethodAttributes flags;
5949 public PropertyMethod (MethodCore method, string prefix)
5950 : base (method, prefix)
5952 this.method = method;
5953 Parent = method.Parent;
5956 public PropertyMethod (MethodCore method, Accessor accessor,
5958 : base (method, accessor, prefix)
5960 this.method = method;
5961 Parent = method.Parent;
5962 this.ModFlags = accessor.ModFlags;
5964 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
5965 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
5966 Environment.Exit (1);
5970 public override AttributeTargets AttributeTargets {
5972 return AttributeTargets.Method;
5976 public override bool IsClsCompliaceRequired(DeclSpace ds)
5978 return method.IsClsCompliaceRequired (ds);
5981 public InternalParameters ParameterInfo
5984 return method_data.ParameterInfo;
5988 public virtual MethodBuilder Define (TypeContainer container)
5991 // Check for custom access modifier
5993 if (ModFlags == 0) {
5994 ModFlags = method.ModFlags;
5995 flags = method.flags;
5997 CheckModifiers (container, ModFlags);
5998 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
5999 flags = Modifiers.MethodAttr (ModFlags);
6000 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6007 public override Type[] ParameterTypes {
6009 return TypeManager.NoTypes;
6013 public override EmitContext CreateEmitContext (TypeContainer tc,
6016 return new EmitContext (
6017 tc, method.Parent, method.Location, ig, ReturnType,
6018 method.ModFlags, false);
6021 public override ObsoleteAttribute GetObsoleteAttribute ()
6023 return method.GetObsoleteAttribute (method.Parent);
6026 public override string GetSignatureForError (TypeContainer tc)
6028 return String.Concat (tc.Name, '.', method.Name);
6031 void CheckModifiers (TypeContainer container, int modflags)
6034 int mflags = method.ModFlags & Modifiers.Accessibility;
6036 if ((mflags & Modifiers.PUBLIC) != 0) {
6037 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6039 else if ((mflags & Modifiers.PROTECTED) != 0) {
6040 if ((mflags & Modifiers.INTERNAL) != 0)
6041 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6043 flags |= Modifiers.PRIVATE;
6045 else if ((mflags & Modifiers.INTERNAL) != 0)
6046 flags |= Modifiers.PRIVATE;
6048 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6049 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6050 GetSignatureForError (container));
6053 public override bool MarkForDuplicationCheck ()
6055 caching_flags |= Flags.TestMethodDuplication;
6061 public PropertyMethod Get, Set;
6062 public PropertyBuilder PropertyBuilder;
6063 public MethodBuilder GetBuilder, SetBuilder;
6065 protected EmitContext ec;
6067 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6068 int allowed_mod, bool is_iface, MemberName name,
6069 Parameters parameters, Attributes attrs,
6071 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6072 attrs, parameters, loc)
6076 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6078 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6079 a.Error_InvalidSecurityParent ();
6083 PropertyBuilder.SetCustomAttribute (cb);
6086 public override AttributeTargets AttributeTargets {
6088 return AttributeTargets.Property;
6092 public override bool Define ()
6097 if (!IsTypePermitted ())
6103 protected override bool DoDefine ()
6105 if (!base.DoDefine ())
6109 // Accessors modifiers check
6111 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6112 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6113 GetSignatureForError ());
6117 if ((Get.IsDummy || Set.IsDummy)
6118 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6119 Report.Error (276, Location,
6120 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6121 GetSignatureForError ());
6125 if (MemberType.IsAbstract && MemberType.IsSealed) {
6126 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6130 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6134 public override string GetSignatureForError()
6136 if (PropertyBuilder == null)
6137 return GetSignatureForError (Parent);
6139 return TypeManager.CSharpSignature (PropertyBuilder, false);
6142 protected override bool CheckForDuplications ()
6144 ArrayList ar = Parent.Indexers;
6146 int arLen = ar.Count;
6148 for (int i = 0; i < arLen; i++) {
6149 Indexer m = (Indexer) ar [i];
6150 if (IsDuplicateImplementation (m))
6155 ar = Parent.Properties;
6157 int arLen = ar.Count;
6159 for (int i = 0; i < arLen; i++) {
6160 Property m = (Property) ar [i];
6161 if (IsDuplicateImplementation (m))
6169 // TODO: rename to Resolve......
6170 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6172 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6173 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6175 if (base_property == null)
6178 base_ret_type = base_property.PropertyType;
6179 MethodInfo get_accessor = base_property.GetGetMethod (true);
6180 MethodInfo set_accessor = base_property.GetSetMethod (true);
6181 MethodAttributes get_accessor_access, set_accessor_access;
6183 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6184 if (Get != null && !Get.IsDummy && get_accessor == null) {
6185 Report.SymbolRelatedToPreviousError (base_property);
6186 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6189 if (Set != null && !Set.IsDummy && set_accessor == null) {
6190 Report.SymbolRelatedToPreviousError (base_property);
6191 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6196 // Check base class accessors access
6198 get_accessor_access = set_accessor_access = 0;
6199 if ((ModFlags & Modifiers.NEW) == 0) {
6200 if (get_accessor != null) {
6201 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6202 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6204 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6205 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6206 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6209 if (set_accessor != null) {
6210 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6211 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6213 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6214 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6215 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6220 // Get the less restrictive access
6222 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6225 public override void Emit ()
6228 // The PropertyBuilder can be null for explicit implementations, in that
6229 // case, we do not actually emit the ".property", so there is nowhere to
6230 // put the attribute
6232 if (PropertyBuilder != null && OptAttributes != null)
6233 OptAttributes.Emit (ec, this);
6245 /// Tests whether accessors are not in collision with some method (CS0111)
6247 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6249 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6252 protected override void UpdateMemberName ()
6254 base.UpdateMemberName ();
6256 Get.UpdateName (this);
6257 Set.UpdateName (this);
6260 protected override bool VerifyClsCompliance (DeclSpace ds)
6262 if (!base.VerifyClsCompliance (ds))
6265 if ((Get.ModFlags != ModFlags && !Get.IsDummy) || (Set.ModFlags != ModFlags && !Set.IsDummy)) {
6266 Report.Error (3025, Get.ModFlags != ModFlags ? Get.Location : Set.Location,
6267 "CLS-compliant accessors must have the same accessibility as their property");
6272 public override string[] ValidAttributeTargets {
6274 return attribute_targets;
6279 // Represents header string for documentation comment.
6281 public override string DocCommentHeader {
6282 get { return "P:"; }
6286 public class Property : PropertyBase, IIteratorContainer {
6287 const int AllowedModifiers =
6290 Modifiers.PROTECTED |
6291 Modifiers.INTERNAL |
6295 Modifiers.OVERRIDE |
6296 Modifiers.ABSTRACT |
6299 Modifiers.METHOD_YIELDS |
6302 const int AllowedInterfaceModifiers =
6305 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6306 MemberName name, Attributes attrs, Accessor get_block,
6307 Accessor set_block, Location loc)
6308 : base (ds, type, mod,
6309 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6310 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6313 if (get_block == null)
6314 Get = new GetMethod (this);
6316 Get = new GetMethod (this, get_block);
6318 if (set_block == null)
6319 Set = new SetMethod (this);
6321 Set = new SetMethod (this, set_block);
6324 public override bool Define ()
6326 if (!base.Define ())
6332 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6336 GetBuilder = Get.Define (Parent);
6337 if (GetBuilder == null)
6341 // Setup iterator if we are one
6343 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6344 Iterator iterator = new Iterator (
6345 Parent, "get", MemberType,
6346 TypeManager.NoTypes, Get.ParameterInfo,
6347 ModFlags, Get.Block, Location);
6349 if (!iterator.DefineIterator ())
6351 Get.Block = iterator.Block;
6356 SetBuilder = Set.Define (Parent);
6357 if (SetBuilder == null)
6360 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6363 // FIXME - PropertyAttributes.HasDefault ?
6365 PropertyAttributes prop_attr = PropertyAttributes.None;
6367 prop_attr |= PropertyAttributes.RTSpecialName |
6368 PropertyAttributes.SpecialName;
6370 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6371 Name, prop_attr, MemberType, null);
6374 PropertyBuilder.SetGetMethod (GetBuilder);
6377 PropertyBuilder.SetSetMethod (SetBuilder);
6379 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6383 public void SetYields ()
6385 ModFlags |= Modifiers.METHOD_YIELDS;
6390 /// Gigantic workaround for lameness in SRE follows :
6391 /// This class derives from EventInfo and attempts to basically
6392 /// wrap around the EventBuilder so that FindMembers can quickly
6393 /// return this in it search for members
6395 public class MyEventBuilder : EventInfo {
6398 // We use this to "point" to our Builder which is
6399 // not really a MemberInfo
6401 EventBuilder MyBuilder;
6404 // We "catch" and wrap these methods
6406 MethodInfo raise, remove, add;
6408 EventAttributes attributes;
6409 Type declaring_type, reflected_type, event_type;
6414 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6416 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6418 // And now store the values in our own fields.
6420 declaring_type = type_builder;
6422 reflected_type = type_builder;
6424 attributes = event_attr;
6427 this.event_type = event_type;
6431 // Methods that you have to override. Note that you only need
6432 // to "implement" the variants that take the argument (those are
6433 // the "abstract" methods, the others (GetAddMethod()) are
6436 public override MethodInfo GetAddMethod (bool nonPublic)
6441 public override MethodInfo GetRemoveMethod (bool nonPublic)
6446 public override MethodInfo GetRaiseMethod (bool nonPublic)
6452 // These methods make "MyEventInfo" look like a Builder
6454 public void SetRaiseMethod (MethodBuilder raiseMethod)
6456 raise = raiseMethod;
6457 MyBuilder.SetRaiseMethod (raiseMethod);
6460 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6462 remove = removeMethod;
6463 MyBuilder.SetRemoveOnMethod (removeMethod);
6466 public void SetAddOnMethod (MethodBuilder addMethod)
6469 MyBuilder.SetAddOnMethod (addMethod);
6472 public void SetCustomAttribute (CustomAttributeBuilder cb)
6474 MyBuilder.SetCustomAttribute (cb);
6477 public override object [] GetCustomAttributes (bool inherit)
6479 // FIXME : There's nothing which can be seemingly done here because
6480 // we have no way of getting at the custom attribute objects of the
6485 public override object [] GetCustomAttributes (Type t, bool inherit)
6487 // FIXME : Same here !
6491 public override bool IsDefined (Type t, bool b)
6496 public override EventAttributes Attributes {
6502 public override string Name {
6508 public override Type DeclaringType {
6510 return declaring_type;
6514 public override Type ReflectedType {
6516 return reflected_type;
6520 public Type EventType {
6526 public void SetUsed ()
6528 if (my_event != null)
6529 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6534 /// For case when event is declared like property (with add and remove accessors).
6536 public class EventProperty: Event {
6538 static string[] attribute_targets = new string [] { "event", "property" };
6540 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6541 bool is_iface, MemberName name, Object init,
6542 Attributes attrs, Accessor add, Accessor remove,
6544 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6546 Add = new AddDelegateMethod (this, add);
6547 Remove = new RemoveDelegateMethod (this, remove);
6549 // For this event syntax we don't report error CS0067
6550 // because it is hard to do it.
6554 public override string[] ValidAttributeTargets {
6556 return attribute_targets;
6562 /// Event is declared like field.
6564 public class EventField: Event {
6566 static string[] attribute_targets = new string [] { "event", "field", "method" };
6567 static string[] attribute_targets_interface = new string[] { "event", "method" };
6569 public EventField (TypeContainer parent, Expression type, int mod_flags,
6570 bool is_iface, MemberName name, Object init,
6571 Attributes attrs, Location loc)
6572 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6574 Add = new AddDelegateMethod (this);
6575 Remove = new RemoveDelegateMethod (this);
6578 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6580 if (a.Target == AttributeTargets.Field) {
6581 FieldBuilder.SetCustomAttribute (cb);
6585 if (a.Target == AttributeTargets.Method) {
6586 Add.ApplyAttributeBuilder (a, cb);
6587 Remove.ApplyAttributeBuilder (a, cb);
6591 base.ApplyAttributeBuilder (a, cb);
6594 public override string[] ValidAttributeTargets {
6596 return IsInterface ? attribute_targets_interface : attribute_targets;
6601 public abstract class Event : FieldBase {
6603 protected sealed class AddDelegateMethod: DelegateMethod
6606 public AddDelegateMethod (Event method):
6607 base (method, "add_")
6611 public AddDelegateMethod (Event method, Accessor accessor):
6612 base (method, accessor, "add_")
6616 protected override MethodInfo DelegateMethodInfo {
6618 return TypeManager.delegate_combine_delegate_delegate;
6624 protected sealed class RemoveDelegateMethod: DelegateMethod
6626 public RemoveDelegateMethod (Event method):
6627 base (method, "remove_")
6631 public RemoveDelegateMethod (Event method, Accessor accessor):
6632 base (method, accessor, "remove_")
6636 protected override MethodInfo DelegateMethodInfo {
6638 return TypeManager.delegate_remove_delegate_delegate;
6644 public abstract class DelegateMethod: AbstractPropertyEventMethod
6646 protected readonly Event method;
6647 ImplicitParameter param_attr;
6649 static string[] attribute_targets = new string [] { "method", "param", "return" };
6651 public DelegateMethod (Event method, string prefix)
6652 : base (method, prefix)
6654 this.method = method;
6657 public DelegateMethod (Event method, Accessor accessor, string prefix)
6658 : base (method, accessor, prefix)
6660 this.method = method;
6663 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6665 if (a.Target == AttributeTargets.Parameter) {
6666 if (param_attr == null)
6667 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6669 param_attr.ApplyAttributeBuilder (a, cb);
6673 base.ApplyAttributeBuilder (a, cb);
6676 public override AttributeTargets AttributeTargets {
6678 return AttributeTargets.Method;
6682 public override bool IsClsCompliaceRequired(DeclSpace ds)
6684 return method.IsClsCompliaceRequired (ds);
6687 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6689 method_data = new MethodData (method, ip, method.ModFlags,
6690 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6692 if (!method_data.Define (container))
6695 MethodBuilder mb = method_data.MethodBuilder;
6696 mb.DefineParameter (1, ParameterAttributes.None, "value");
6701 public override void Emit (TypeContainer tc)
6703 if (block != null) {
6708 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6709 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6711 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6712 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6713 ig.Emit (OpCodes.Ldsfld, field_info);
6714 ig.Emit (OpCodes.Ldarg_0);
6715 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6716 ig.Emit (OpCodes.Castclass, method.MemberType);
6717 ig.Emit (OpCodes.Stsfld, field_info);
6719 ig.Emit (OpCodes.Ldarg_0);
6720 ig.Emit (OpCodes.Ldarg_0);
6721 ig.Emit (OpCodes.Ldfld, field_info);
6722 ig.Emit (OpCodes.Ldarg_1);
6723 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6724 ig.Emit (OpCodes.Castclass, method.MemberType);
6725 ig.Emit (OpCodes.Stfld, field_info);
6727 ig.Emit (OpCodes.Ret);
6730 protected abstract MethodInfo DelegateMethodInfo { get; }
6732 public override Type[] ParameterTypes {
6734 return new Type[] { method.MemberType };
6738 public override Type ReturnType {
6740 return TypeManager.void_type;
6744 public override EmitContext CreateEmitContext (TypeContainer tc,
6747 return new EmitContext (
6748 tc, method.Parent, Location, ig, ReturnType,
6749 method.ModFlags, false);
6752 public override string GetSignatureForError (TypeContainer tc)
6754 return String.Concat (tc.Name, '.', method.Name);
6757 public override ObsoleteAttribute GetObsoleteAttribute ()
6759 return method.GetObsoleteAttribute (method.Parent);
6762 public override string[] ValidAttributeTargets {
6764 return attribute_targets;
6770 const int AllowedModifiers =
6773 Modifiers.PROTECTED |
6774 Modifiers.INTERNAL |
6779 Modifiers.OVERRIDE |
6783 const int AllowedInterfaceModifiers =
6786 public DelegateMethod Add, Remove;
6787 public MyEventBuilder EventBuilder;
6788 public MethodBuilder AddBuilder, RemoveBuilder;
6790 public Event (TypeContainer parent, Expression type, int mod_flags,
6791 bool is_iface, MemberName name, Object init, Attributes attrs,
6793 : base (parent, type, mod_flags,
6794 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6795 name, init, attrs, loc)
6797 IsInterface = is_iface;
6800 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6802 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6803 a.Error_InvalidSecurityParent ();
6807 EventBuilder.SetCustomAttribute (cb);
6810 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6812 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6815 public override AttributeTargets AttributeTargets {
6817 return AttributeTargets.Event;
6821 public override bool Define ()
6823 EventAttributes e_attr;
6824 e_attr = EventAttributes.None;
6829 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6830 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6831 "': abstract event can not have an initializer");
6835 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6836 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6837 "' : event must be of a delegate type");
6841 EmitContext ec = Parent.EmitContext;
6843 throw new InternalErrorException ("Event.Define called too early?");
6844 bool old_unsafe = ec.InUnsafe;
6845 ec.InUnsafe = InUnsafe;
6847 Parameter [] parms = new Parameter [1];
6848 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6849 Parameters parameters = new Parameters (parms, null, Location);
6850 Type [] types = parameters.GetParameterInfo (ec);
6851 InternalParameters ip = new InternalParameters (types, parameters);
6853 ec.InUnsafe = old_unsafe;
6859 // Now define the accessors
6862 AddBuilder = Add.Define (Parent, ip);
6863 if (AddBuilder == null)
6866 RemoveBuilder = Remove.Define (Parent, ip);
6867 if (RemoveBuilder == null)
6870 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6872 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6873 FieldBuilder = Parent.TypeBuilder.DefineField (
6875 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6876 TypeManager.RegisterPrivateFieldOfEvent (
6877 (EventInfo) EventBuilder, FieldBuilder);
6878 TypeManager.RegisterFieldBase (FieldBuilder, this);
6881 EventBuilder.SetAddOnMethod (AddBuilder);
6882 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6884 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6888 protected override bool CheckBase ()
6890 if (!base.CheckBase ())
6893 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6894 if (!(conflict_symbol is EventInfo)) {
6895 Report.SymbolRelatedToPreviousError (conflict_symbol);
6896 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6904 public override void Emit ()
6906 if (OptAttributes != null) {
6907 EmitContext ec = new EmitContext (
6908 Parent, Location, null, MemberType, ModFlags);
6909 OptAttributes.Emit (ec, this);
6914 Remove.Emit (Parent);
6920 public override string GetSignatureForError ()
6922 if (EventBuilder == null)
6923 return base.GetSignatureForError (Parent);
6925 return TypeManager.GetFullNameSignature (EventBuilder);
6929 // Represents header string for documentation comment.
6931 public override string DocCommentHeader {
6932 get { return "E:"; }
6937 public class Indexer : PropertyBase {
6939 class GetIndexerMethod: GetMethod
6941 public GetIndexerMethod (MethodCore method):
6946 public GetIndexerMethod (MethodCore method, Accessor accessor):
6947 base (method, accessor)
6951 // TODO: one GetSignatureForError is enough (reuse Parent member)
6952 public override string GetSignatureForError (TypeContainer tc)
6954 string core = base.GetSignatureForError (tc);
6955 return core.Replace (TypeContainer.DefaultIndexerName,
6956 String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
6959 public override Type[] ParameterTypes {
6961 return method.ParameterTypes;
6966 class SetIndexerMethod: SetMethod
6968 readonly Parameters parameters;
6970 public SetIndexerMethod (MethodCore method):
6975 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
6976 base (method, accessor)
6978 this.parameters = parameters;
6981 public override Type[] ParameterTypes {
6983 int top = method.ParameterTypes.Length;
6984 Type [] set_pars = new Type [top + 1];
6985 method.ParameterTypes.CopyTo (set_pars, 0);
6986 set_pars [top] = method.MemberType;
6991 protected override InternalParameters GetParameterInfo (EmitContext ec)
6993 Parameter [] fixed_parms = parameters.FixedParameters;
6995 if (fixed_parms == null){
6996 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
6997 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6998 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7000 // Here is the problem: the `value' parameter has
7001 // to come *after* the array parameter in the declaration
7003 // X (object [] x, Type value)
7006 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7007 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7011 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7013 fixed_parms.CopyTo (tmp, 0);
7014 tmp [fixed_parms.Length] = new Parameter (
7015 method.Type, "value", Parameter.Modifier.NONE, null);
7017 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7018 Type [] types = set_formal_params.GetParameterInfo (ec);
7020 return new InternalParameters (types, set_formal_params);
7025 const int AllowedModifiers =
7028 Modifiers.PROTECTED |
7029 Modifiers.INTERNAL |
7033 Modifiers.OVERRIDE |
7038 const int AllowedInterfaceModifiers =
7042 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7043 bool is_iface, Parameters parameters, Attributes attrs,
7044 Accessor get_block, Accessor set_block, Location loc)
7045 : base (ds, type, mod,
7046 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7047 is_iface, name, parameters, attrs, loc)
7049 if (get_block == null)
7050 Get = new GetIndexerMethod (this);
7052 Get = new GetIndexerMethod (this, get_block);
7054 if (set_block == null)
7055 Set = new SetIndexerMethod (this);
7057 Set = new SetIndexerMethod (this, parameters, set_block);
7060 public override bool Define ()
7062 PropertyAttributes prop_attr =
7063 PropertyAttributes.RTSpecialName |
7064 PropertyAttributes.SpecialName;
7066 if (!base.Define ())
7069 if (MemberType == TypeManager.void_type) {
7070 Report.Error (620, Location, "Indexers cannot have void type");
7074 if (OptAttributes != null) {
7075 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7076 if (indexer_attr != null) {
7077 // Remove the attribute from the list because it is not emitted
7078 OptAttributes.Attrs.Remove (indexer_attr);
7080 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7082 if (IsExplicitImpl) {
7083 Report.Error (415, indexer_attr.Location,
7084 "The 'IndexerName' attribute is valid only on an " +
7085 "indexer that is not an explicit interface member declaration");
7089 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7090 Report.Error (609, indexer_attr.Location,
7091 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7095 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7096 Report.Error (633, indexer_attr.Location,
7097 "The argument to the 'IndexerName' attribute must be a valid identifier");
7101 UpdateMemberName ();
7105 if (InterfaceType != null) {
7106 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7107 if (base_IndexerName != Name)
7108 ShortName = base_IndexerName;
7109 UpdateMemberName ();
7112 if (!Parent.AddToMemberContainer (this) ||
7113 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7119 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7121 GetBuilder = Get.Define (Parent);
7122 if (GetBuilder == null)
7127 SetBuilder = Set.Define (Parent);
7128 if (SetBuilder == null)
7133 // Now name the parameters
7135 Parameter [] p = Parameters.FixedParameters;
7137 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7138 Report.Error (631, Location, "ref and out are not valid in this context");
7144 for (i = 0; i < p.Length; ++i) {
7146 GetBuilder.DefineParameter (
7147 i + 1, p [i].Attributes, p [i].Name);
7150 SetBuilder.DefineParameter (
7151 i + 1, p [i].Attributes, p [i].Name);
7155 SetBuilder.DefineParameter (
7156 i + 1, ParameterAttributes.None, "value");
7158 if (i != ParameterTypes.Length) {
7159 Parameter array_param = Parameters.ArrayParameter;
7161 SetBuilder.DefineParameter (
7162 i + 1, array_param.Attributes, array_param.Name);
7166 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7167 Name, prop_attr, MemberType, ParameterTypes);
7170 PropertyBuilder.SetGetMethod (GetBuilder);
7173 PropertyBuilder.SetSetMethod (SetBuilder);
7175 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7180 public override string GetSignatureForError ()
7182 if (PropertyBuilder == null)
7183 return GetSignatureForError (Parent);
7185 return TypeManager.CSharpSignature (PropertyBuilder, true);
7188 public override string GetSignatureForError(TypeContainer tc)
7190 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7193 public override bool MarkForDuplicationCheck ()
7195 caching_flags |= Flags.TestMethodDuplication;
7201 public class Operator : MethodCore, IIteratorContainer {
7203 const int AllowedModifiers =
7209 public enum OpType : byte {
7219 // Unary and Binary operators
7242 // Implicit and Explicit
7247 public readonly OpType OperatorType;
7248 public MethodBuilder OperatorMethodBuilder;
7250 public Method OperatorMethod;
7252 static string[] attribute_targets = new string [] { "method", "return" };
7254 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7255 int mod_flags, Parameters parameters,
7256 ToplevelBlock block, Attributes attrs, Location loc)
7257 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7258 new MemberName ("op_" + type), attrs, parameters, loc)
7260 OperatorType = type;
7264 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7266 OperatorMethod.ApplyAttributeBuilder (a, cb);
7269 public override AttributeTargets AttributeTargets {
7271 return AttributeTargets.Method;
7275 protected override bool CheckForDuplications()
7277 ArrayList ar = Parent.Operators;
7279 int arLen = ar.Count;
7281 for (int i = 0; i < arLen; i++) {
7282 Operator o = (Operator) ar [i];
7283 if (IsDuplicateImplementation (o))
7288 ar = Parent.Methods;
7290 int arLen = ar.Count;
7292 for (int i = 0; i < arLen; i++) {
7293 Method m = (Method) ar [i];
7294 if (IsDuplicateImplementation (m))
7302 public override bool Define ()
7305 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7306 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7307 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7314 if (MemberType == TypeManager.void_type) {
7315 Report.Error (590, Location, "User-defined operators cannot return void");
7319 OperatorMethod = new Method (
7320 Parent, Type, ModFlags, false, MemberName,
7321 Parameters, OptAttributes, Location);
7323 OperatorMethod.Block = Block;
7324 OperatorMethod.IsOperator = true;
7325 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7326 OperatorMethod.Define ();
7328 if (OperatorMethod.MethodBuilder == null)
7331 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7333 parameter_types = OperatorMethod.ParameterTypes;
7334 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7335 Type return_type = OperatorMethod.ReturnType;
7336 Type first_arg_type = parameter_types [0];
7341 // Rules for conversion operators
7343 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7344 if (first_arg_type == return_type && first_arg_type == declaring_type){
7347 "User-defined conversion cannot take an object of the " +
7348 "enclosing type and convert to an object of the enclosing" +
7353 if (first_arg_type != declaring_type && return_type != declaring_type){
7356 "User-defined conversion must convert to or from the " +
7361 if (first_arg_type == TypeManager.object_type ||
7362 return_type == TypeManager.object_type){
7365 "User-defined conversion cannot convert to or from " +
7370 if (first_arg_type.IsInterface || return_type.IsInterface){
7373 "User-defined conversion cannot convert to or from an " +
7378 if (first_arg_type.IsSubclassOf (return_type)
7379 || return_type.IsSubclassOf (first_arg_type)){
7380 if (declaring_type.IsSubclassOf (return_type)) {
7381 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7384 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7387 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7388 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7389 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");
7392 } else if (Parameters.FixedParameters.Length == 1) {
7393 // Checks for Unary operators
7395 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7396 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7397 Report.Error (448, Location,
7398 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7401 if (first_arg_type != declaring_type) {
7403 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7408 if (first_arg_type != declaring_type){
7411 "The parameter of a unary operator must be the " +
7416 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7417 if (return_type != TypeManager.bool_type){
7420 "The return type of operator True or False " +
7427 // Checks for Binary operators
7429 if (first_arg_type != declaring_type &&
7430 parameter_types [1] != declaring_type){
7433 "One of the parameters of a binary operator must " +
7434 "be the containing type");
7442 public override void Emit ()
7445 // abstract or extern methods have no bodies
7447 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7450 OperatorMethod.Emit ();
7454 // Operator cannot be override
7455 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7460 public static string GetName (OpType ot)
7463 case OpType.LogicalNot:
7465 case OpType.OnesComplement:
7467 case OpType.Increment:
7469 case OpType.Decrement:
7475 case OpType.Addition:
7477 case OpType.Subtraction:
7479 case OpType.UnaryPlus:
7481 case OpType.UnaryNegation:
7483 case OpType.Multiply:
7485 case OpType.Division:
7487 case OpType.Modulus:
7489 case OpType.BitwiseAnd:
7491 case OpType.BitwiseOr:
7493 case OpType.ExclusiveOr:
7495 case OpType.LeftShift:
7497 case OpType.RightShift:
7499 case OpType.Equality:
7501 case OpType.Inequality:
7503 case OpType.GreaterThan:
7505 case OpType.LessThan:
7507 case OpType.GreaterThanOrEqual:
7509 case OpType.LessThanOrEqual:
7511 case OpType.Implicit:
7513 case OpType.Explicit:
7519 public override string GetSignatureForError (TypeContainer tc)
7521 StringBuilder sb = new StringBuilder ();
7522 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7523 Parameters.FixedParameters [0].GetSignatureForError ());
7525 if (Parameters.FixedParameters.Length > 1) {
7527 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7530 return sb.ToString ();
7533 public override string GetSignatureForError ()
7538 public override bool MarkForDuplicationCheck ()
7540 caching_flags |= Flags.TestMethodDuplication;
7544 public override string ToString ()
7546 if (OperatorMethod == null)
7549 Type return_type = OperatorMethod.ReturnType;
7550 Type [] param_types = OperatorMethod.ParameterTypes;
7552 if (Parameters.FixedParameters.Length == 1)
7553 return String.Format (
7554 "{0} operator {1}({2})",
7555 TypeManager.CSharpName (return_type),
7556 GetName (OperatorType),
7559 return String.Format (
7560 "{0} operator {1}({2}, {3})",
7561 TypeManager.CSharpName (return_type),
7562 GetName (OperatorType),
7563 param_types [0], param_types [1]);
7566 public override string[] ValidAttributeTargets {
7568 return attribute_targets;
7572 public void SetYields ()
7574 ModFlags |= Modifiers.METHOD_YIELDS;
7579 // This is used to compare method signatures
7581 struct MethodSignature {
7583 public Type RetType;
7584 public Type [] Parameters;
7587 /// This delegate is used to extract methods which have the
7588 /// same signature as the argument
7590 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7592 public MethodSignature (string name, Type ret_type, Type [] parameters)
7597 if (parameters == null)
7598 Parameters = TypeManager.NoTypes;
7600 Parameters = parameters;
7603 public override string ToString ()
7606 if (Parameters.Length != 0){
7607 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7608 for (int i = 0; i < Parameters.Length; i++){
7609 sb.Append (Parameters [i]);
7610 if (i+1 < Parameters.Length)
7613 pars = sb.ToString ();
7616 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7619 public override int GetHashCode ()
7621 return Name.GetHashCode ();
7624 public override bool Equals (Object o)
7626 MethodSignature other = (MethodSignature) o;
7628 if (other.Name != Name)
7631 if (other.RetType != RetType)
7634 if (Parameters == null){
7635 if (other.Parameters == null)
7640 if (other.Parameters == null)
7643 int c = Parameters.Length;
7644 if (other.Parameters.Length != c)
7647 for (int i = 0; i < c; i++)
7648 if (other.Parameters [i] != Parameters [i])
7654 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7656 MethodSignature sig = (MethodSignature) filter_criteria;
7658 if (m.Name != sig.Name)
7662 MethodInfo mi = m as MethodInfo;
7663 PropertyInfo pi = m as PropertyInfo;
7666 ReturnType = mi.ReturnType;
7667 else if (pi != null)
7668 ReturnType = pi.PropertyType;
7673 // we use sig.RetType == null to mean `do not check the
7674 // method return value.
7676 if (sig.RetType != null)
7677 if (ReturnType != sig.RetType)
7682 args = TypeManager.GetArgumentTypes (mi);
7684 args = TypeManager.GetArgumentTypes (pi);
7685 Type [] sigp = sig.Parameters;
7687 if (args.Length != sigp.Length)
7690 for (int i = args.Length; i > 0; ){
7692 if (args [i] != sigp [i])