2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 namespace Mono.CSharp {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
79 public virtual void Emit ()
81 foreach (MemberCore mc in this)
86 public class MethodArrayList: MemberCoreArrayList
94 CachedMethods cached_method;
95 TypeContainer container;
97 public MethodArrayList (TypeContainer container)
99 this.container = container;
103 /// Method container contains Equals method
105 public bool HasEquals {
107 cached_method |= CachedMethods.Equals;
111 return (cached_method & CachedMethods.Equals) != 0;
116 /// Method container contains GetHashCode method
118 public bool HasGetHashCode {
120 cached_method |= CachedMethods.GetHashCode;
124 return (cached_method & CachedMethods.GetHashCode) != 0;
128 public override void DefineContainerMembers ()
130 base.DefineContainerMembers ();
132 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
133 Report.Warning (659, container.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
139 public sealed class IndexerArrayList: MemberCoreArrayList
142 /// The indexer name for this container
144 public string IndexerName = DefaultIndexerName;
146 bool seen_normal_indexers = false;
148 TypeContainer container;
150 public IndexerArrayList (TypeContainer container)
152 this.container = container;
156 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
157 /// class is consistent. Either it is `Item' or it is the name defined by all the
158 /// indexers with the `IndexerName' attribute.
160 /// Turns out that the IndexerNameAttribute is applied to each indexer,
161 /// but it is never emitted, instead a DefaultMember attribute is attached
164 public override void DefineContainerMembers()
166 base.DefineContainerMembers ();
168 string class_indexer_name = null;
171 // If there's both an explicit and an implicit interface implementation, the
172 // explicit one actually implements the interface while the other one is just
173 // a normal indexer. See bug #37714.
176 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
177 foreach (Indexer i in this) {
178 if (i.InterfaceType != null) {
179 if (seen_normal_indexers)
180 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
184 seen_normal_indexers = true;
186 if (class_indexer_name == null) {
187 class_indexer_name = i.ShortName;
191 if (i.ShortName != class_indexer_name)
192 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
195 if (class_indexer_name != null)
196 IndexerName = class_indexer_name;
199 public override void Emit ()
203 if (!seen_normal_indexers)
206 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
207 container.TypeBuilder.SetCustomAttribute (cb);
211 public class OperatorArrayList: MemberCoreArrayList
213 TypeContainer container;
215 public OperatorArrayList (TypeContainer container)
217 this.container = container;
221 // Operator pair checking
226 public Type ret_type;
227 public Type type1, type2;
229 public Operator.OpType ot;
231 public OperatorEntry (int f, Operator o)
235 ret_type = o.OperatorMethod.ReturnType;
236 Type [] pt = o.OperatorMethod.ParameterTypes;
243 public override int GetHashCode ()
245 return ret_type.GetHashCode ();
248 public override bool Equals (object o)
250 OperatorEntry other = (OperatorEntry) o;
252 if (other.ret_type != ret_type)
254 if (other.type1 != type1)
256 if (other.type2 != type2)
263 // Checks that some operators come in pairs:
269 // They are matched based on the return type and the argument types
271 void CheckPairedOperators ()
273 Hashtable pairs = new Hashtable (null, null);
274 Operator true_op = null;
275 Operator false_op = null;
276 bool has_equality_or_inequality = false;
278 // Register all the operators we care about.
279 foreach (Operator op in this){
282 // Skip erroneous code.
283 if (op.OperatorMethod == null)
286 switch (op.OperatorType){
287 case Operator.OpType.Equality:
289 has_equality_or_inequality = true;
291 case Operator.OpType.Inequality:
293 has_equality_or_inequality = true;
296 case Operator.OpType.True:
299 case Operator.OpType.False:
303 case Operator.OpType.GreaterThan:
305 case Operator.OpType.LessThan:
308 case Operator.OpType.GreaterThanOrEqual:
310 case Operator.OpType.LessThanOrEqual:
316 OperatorEntry oe = new OperatorEntry (reg, op);
318 object o = pairs [oe];
322 oe = (OperatorEntry) o;
327 if (true_op != null){
328 if (false_op == null)
329 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
330 true_op.GetSignatureForError ());
331 } else if (false_op != null)
332 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
333 false_op.GetSignatureForError ());
336 // Look for the mistakes.
338 foreach (DictionaryEntry de in pairs){
339 OperatorEntry oe = (OperatorEntry) de.Key;
346 case Operator.OpType.Equality:
349 case Operator.OpType.Inequality:
352 case Operator.OpType.GreaterThan:
355 case Operator.OpType.LessThan:
358 case Operator.OpType.GreaterThanOrEqual:
361 case Operator.OpType.LessThanOrEqual:
365 Report.Error (216, oe.op.Location,
366 "The operator `{0}' requires a matching operator `{1}' to also be defined",
367 oe.op.GetSignatureForError (), s);
370 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
371 if (container.Methods == null || !container.Methods.HasEquals)
372 Report.Warning (660, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
374 if (container.Methods == null || !container.Methods.HasGetHashCode)
375 Report.Warning (661, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
379 public override void DefineContainerMembers ()
381 base.DefineContainerMembers ();
382 CheckPairedOperators ();
387 // Whether this is a struct, class or interface
388 public readonly Kind Kind;
390 // Holds a list of classes and structures
393 // Holds the list of properties
394 MemberCoreArrayList properties;
396 // Holds the list of enumerations
397 MemberCoreArrayList enums;
399 // Holds the list of delegates
400 MemberCoreArrayList delegates;
402 // Holds the list of constructors
403 protected MemberCoreArrayList instance_constructors;
405 // Holds the list of fields
406 MemberCoreArrayList fields;
408 // Holds a list of fields that have initializers
409 protected ArrayList initialized_fields;
411 // Holds a list of static fields that have initializers
412 protected ArrayList initialized_static_fields;
414 // Holds the list of constants
415 MemberCoreArrayList constants;
418 MemberCoreArrayList interfaces;
420 // Holds the methods.
421 MethodArrayList methods;
424 protected MemberCoreArrayList events;
426 // Holds the indexers
427 IndexerArrayList indexers;
429 // Holds the operators
430 MemberCoreArrayList operators;
432 // Holds the iterators
435 // Holds the parts of a partial class;
439 // Pointers to the default constructor and the default static constructor
441 protected Constructor default_constructor;
442 protected Constructor default_static_constructor;
445 // Points to the first non-static field added to the container.
447 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
448 // and the first one's as good as any.
450 FieldBase first_nonstatic_field = null;
453 // This one is computed after we can distinguish interfaces
454 // from classes from the arraylist `type_bases'
456 string base_class_name;
458 TypeExpr[] iface_exprs;
460 ArrayList type_bases;
462 bool members_defined;
463 bool members_defined_ok;
465 // The interfaces we implement.
466 protected Type[] ifaces;
467 protected Type ptype;
469 // The base member cache and our member cache
470 MemberCache base_cache;
471 MemberCache member_cache;
473 public const string DefaultIndexerName = "Item";
475 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
476 Attributes attrs, Kind kind, Location l)
477 : base (ns, parent, name, attrs, l)
479 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
480 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
484 types = new ArrayList ();
486 base_class_name = null;
489 public bool AddToMemberContainer (MemberCore symbol)
491 return AddToContainer (symbol, symbol.Name);
494 bool AddToTypeContainer (DeclSpace ds)
496 // Parent == null ==> this == RootContext.Tree.Types
497 return AddToContainer (ds, (Parent == null) ? ds.Name : ds.Basename);
500 public void AddConstant (Const constant)
502 if (!AddToMemberContainer (constant))
505 if (constants == null)
506 constants = new MemberCoreArrayList ();
508 constants.Add (constant);
511 public void AddEnum (Mono.CSharp.Enum e)
513 if (!AddToTypeContainer (e))
517 enums = new MemberCoreArrayList ();
522 public void AddClassOrStruct (TypeContainer c)
524 if (!AddToTypeContainer (c))
530 public void AddDelegate (Delegate d)
532 if (!AddToTypeContainer (d))
535 if (delegates == null)
536 delegates = new MemberCoreArrayList ();
541 public void AddMethod (Method method)
543 if (!AddToMemberContainer (method))
547 methods = new MethodArrayList (this);
549 if (method.MemberName.Left != null)
550 methods.Insert (0, method);
552 methods.Add (method);
555 public void AddConstructor (Constructor c)
557 if (c.Name != Basename) {
558 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
561 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
564 if (default_static_constructor != null) {
565 Report.SymbolRelatedToPreviousError (default_static_constructor);
566 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
570 default_static_constructor = c;
573 if (default_constructor != null) {
574 Report.SymbolRelatedToPreviousError (default_constructor);
575 Report.Error (111, c.Location, Error111, c.Location, c.GetSignatureForError ());
578 default_constructor = c;
581 if (instance_constructors == null)
582 instance_constructors = new MemberCoreArrayList ();
584 instance_constructors.Add (c);
588 internal static string Error111 {
590 return "`{0}' is already defined. Rename this member or use different parameter types";
594 public void AddInterface (TypeContainer iface)
596 if (!AddToTypeContainer (iface))
599 if (interfaces == null) {
600 interfaces = new MemberCoreArrayList ();
603 interfaces.Add (iface);
606 public void AddField (FieldMember field)
608 if (!AddToMemberContainer (field))
612 fields = new MemberCoreArrayList ();
616 if (field.HasInitializer)
617 RegisterFieldForInitialization (field);
619 if ((field.ModFlags & Modifiers.STATIC) != 0)
622 if (first_nonstatic_field == null) {
623 first_nonstatic_field = field;
627 if (Kind == Kind.Struct &&
628 first_nonstatic_field.Parent != field.Parent &&
629 RootContext.WarningLevel >= 3) {
630 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
631 Report.Warning (282, field.Location,
632 "struct instance field `{0}' found in different declaration from instance field `{1}'",
633 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
637 public void AddProperty (Property prop)
639 if (!AddToMemberContainer (prop) ||
640 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
643 if (properties == null)
644 properties = new MemberCoreArrayList ();
646 if (prop.MemberName.Left != null)
647 properties.Insert (0, prop);
649 properties.Add (prop);
652 public void AddEvent (Event e)
654 if (!AddToMemberContainer (e))
657 if (e is EventProperty) {
658 if (!AddToMemberContainer (e.Add))
661 if (!AddToMemberContainer (e.Remove))
666 events = new MemberCoreArrayList ();
673 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
675 public void AddIndexer (Indexer i)
677 if (indexers == null)
678 indexers = new IndexerArrayList (this);
680 if (i.IsExplicitImpl)
681 indexers.Insert (0, i);
686 public void AddOperator (Operator op)
688 if (!AddToMemberContainer (op))
691 if (operators == null)
692 operators = new OperatorArrayList (this);
697 public void AddIterator (Iterator i)
699 if (iterators == null)
700 iterators = new ArrayList ();
705 public void AddType (TypeContainer tc)
710 public void AddPart (ClassPart part)
713 parts = new ArrayList ();
718 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
720 if (a.Type == TypeManager.default_member_type) {
721 if (Indexers != null) {
722 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
727 base.ApplyAttributeBuilder (a, cb);
730 public override AttributeTargets AttributeTargets {
734 return AttributeTargets.Class;
736 return AttributeTargets.Struct;
738 return AttributeTargets.Interface;
740 throw new NotSupportedException ();
745 public ArrayList Types {
751 public MethodArrayList Methods {
757 public ArrayList Constants {
763 public ArrayList Interfaces {
769 public ArrayList Iterators {
777 return base_class_name;
781 public ArrayList Bases {
791 public ArrayList Fields {
797 public ArrayList InstanceConstructors {
799 return instance_constructors;
803 public ArrayList Properties {
809 public ArrayList Events {
815 public ArrayList Enums {
821 public ArrayList Indexers {
827 public ArrayList Operators {
833 public ArrayList Delegates {
839 public ArrayList Parts {
845 protected override TypeAttributes TypeAttr {
847 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
851 public string IndexerName {
853 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
857 public virtual void RegisterFieldForInitialization (FieldMember field)
859 if ((field.ModFlags & Modifiers.STATIC) != 0){
860 if (initialized_static_fields == null)
861 initialized_static_fields = new ArrayList ();
863 initialized_static_fields.Add (field);
865 if (initialized_fields == null)
866 initialized_fields = new ArrayList ();
868 initialized_fields.Add (field);
873 // Emits the instance field initializers
875 public virtual bool EmitFieldInitializers (EmitContext ec)
878 Expression instance_expr;
881 fields = initialized_static_fields;
882 instance_expr = null;
884 fields = initialized_fields;
885 instance_expr = new This (Location.Null).Resolve (ec);
891 foreach (FieldMember f in fields){
892 Expression e = f.GetInitializerExpression (ec);
896 Location l = f.Location;
897 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
898 fe.InstanceExpression = instance_expr;
899 ExpressionStatement a = new Assign (fe, e, l);
901 a = a.ResolveStatement (ec);
905 Constant c = e as Constant;
907 if (c.IsDefaultValue)
911 a.EmitStatement (ec);
918 // Defines the default constructors
920 protected void DefineDefaultConstructor (bool is_static)
924 // The default constructor is public
925 // If the class is abstract, the default constructor is protected
926 // The default static constructor is private
928 int mods = Modifiers.PUBLIC;
930 mods = Modifiers.STATIC | Modifiers.PRIVATE;
931 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
932 mods = Modifiers.PROTECTED;
934 TypeContainer constructor_parent = this;
936 constructor_parent = (TypeContainer) Parts [0];
938 c = new Constructor (constructor_parent, Basename, mods,
939 Parameters.EmptyReadOnlyParameters,
940 new ConstructorBaseInitializer (
941 null, Parameters.EmptyReadOnlyParameters,
947 c.Block = new ToplevelBlock (null, Location);
952 /// The pending methods that need to be implemented
953 // (interfaces or abstract methods)
955 public PendingImplementation Pending;
957 public abstract PendingImplementation GetPendingImplementations ();
959 TypeExpr[] GetPartialBases (out TypeExpr base_class)
961 ArrayList ifaces = new ArrayList ();
964 Location base_loc = Location.Null;
966 foreach (ClassPart part in parts) {
967 TypeExpr new_base_class;
968 TypeExpr[] new_ifaces;
970 new_ifaces = part.GetClassBases (out new_base_class);
971 if (new_ifaces == null && new_base_class != null)
974 if ((base_class != null) && (new_base_class != null) &&
975 !base_class.Equals (new_base_class)) {
976 Report.Error (263, part.Location,
977 "Partial declarations of `{0}' must " +
978 "not specify different base classes",
981 if (!Location.IsNull (base_loc))
982 Report.LocationOfPreviousError (base_loc);
987 if ((base_class == null) && (new_base_class != null)) {
988 base_class = new_base_class;
989 base_loc = part.Location;
992 if (new_ifaces == null)
995 foreach (TypeExpr iface in new_ifaces) {
997 foreach (TypeExpr old_iface in ifaces) {
998 if (old_iface.Equals (iface)) {
1009 TypeExpr[] retval = new TypeExpr [ifaces.Count];
1010 ifaces.CopyTo (retval, 0);
1014 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1018 int count = Bases.Count;
1019 int start = 0, i, j;
1021 if (Kind == Kind.Class){
1022 TypeExpr name = ResolveBaseTypeExpr (
1023 (Expression) Bases [0], false, Location);
1029 if (!name.IsInterface) {
1030 // base_class could be a class, struct, enum, delegate.
1031 // This is validated in GetClassBases.
1037 TypeExpr [] ifaces = new TypeExpr [count-start];
1039 for (i = start, j = 0; i < count; i++, j++){
1040 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1041 if (resolved == null) {
1045 ifaces [j] = resolved;
1052 /// This function computes the Base class and also the
1053 /// list of interfaces that the class or struct @c implements.
1055 /// The return value is an array (might be null) of
1056 /// interfaces implemented (as Types).
1058 /// The @base_class argument is set to the base object or null
1059 /// if this is `System.Object'.
1061 TypeExpr [] GetClassBases (out TypeExpr base_class)
1068 ifaces = GetPartialBases (out base_class);
1069 else if (Bases == null){
1073 ifaces = GetNormalBases (out base_class);
1078 if ((base_class != null) && (Kind == Kind.Class)){
1080 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1081 Report.Error (1521, base_class.Location, "Invalid base type");
1085 if (base_class.IsSealed){
1086 Report.SymbolRelatedToPreviousError (base_class.Type);
1087 if (base_class.Type.IsAbstract) {
1088 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
1089 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1091 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
1092 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1097 if (!base_class.CanInheritFrom ()){
1098 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
1099 GetSignatureForError (), base_class.GetSignatureForError ());
1103 if (!base_class.AsAccessible (this, ModFlags)) {
1104 Report.SymbolRelatedToPreviousError (base_class.Type);
1105 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
1106 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1110 if (base_class != null)
1111 base_class_name = base_class.Name;
1116 int count = ifaces != null ? ifaces.Length : 0;
1118 for (i = 0; i < count; i++) {
1119 TypeExpr iface = (TypeExpr) ifaces [i];
1121 if (!iface.IsInterface) {
1122 if (Kind != Kind.Class) {
1123 // TODO: location of symbol related ....
1124 Error_TypeInListIsNotInterface (Location, iface.FullName);
1126 else if (base_class != null)
1127 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1128 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1130 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1131 GetSignatureForError (), iface.GetSignatureForError ());
1136 for (int x = 0; x < i; x++) {
1137 if (iface.Equals (ifaces [x])) {
1138 Report.Error (528, Location,
1139 "`{0}' is already listed in " +
1140 "interface list", iface.Name);
1145 if ((Kind == Kind.Interface) &&
1146 !iface.AsAccessible (Parent, ModFlags)) {
1147 Report.Error (61, Location,
1148 "Inconsistent accessibility: base " +
1149 "interface `{0}' is less accessible " +
1150 "than interface `{1}'", iface.Name,
1160 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1162 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1166 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1168 public override TypeBuilder DefineType ()
1173 if (TypeBuilder != null)
1176 TypeAttributes type_attributes = TypeAttr;
1180 if (TypeManager.NamespaceClash (Name, Location)) {
1185 ModuleBuilder builder = CodeGen.Module.Builder;
1186 TypeBuilder = builder.DefineType (
1187 Name, type_attributes, null, null);
1189 TypeBuilder builder = Parent.TypeBuilder;
1190 if (builder == null) {
1195 TypeBuilder = builder.DefineNestedType (
1196 Basename, type_attributes, ptype, null);
1198 } catch (ArgumentException) {
1199 Report.RuntimeMissingSupport (Location, "static classes");
1204 TypeManager.AddUserType (Name, TypeBuilder, this);
1206 if (Parts != null) {
1208 foreach (ClassPart part in Parts) {
1209 part.TypeBuilder = TypeBuilder;
1211 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1212 part.ec.ContainerType = TypeBuilder;
1216 // Normally, we create the EmitContext here.
1217 // The only exception is if we're an Iterator - in this case,
1218 // we already have the `ec', so we don't want to create a new one.
1221 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1222 ec.ContainerType = TypeBuilder;
1225 iface_exprs = GetClassBases (out base_type);
1226 if (iface_exprs == null && base_type != null) {
1231 if (base_type == null) {
1232 if (Kind == Kind.Class){
1233 if (RootContext.StdLib)
1234 base_type = TypeManager.system_object_expr;
1235 else if (Name != "System.Object")
1236 base_type = TypeManager.system_object_expr;
1237 } else if (Kind == Kind.Struct) {
1239 // If we are compiling our runtime,
1240 // and we are defining ValueType, then our
1241 // base is `System.Object'.
1243 if (!RootContext.StdLib && Name == "System.ValueType")
1244 base_type = TypeManager.system_object_expr;
1246 base_type = TypeManager.system_valuetype_expr;
1250 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1251 throw new Exception ();
1253 if (base_type != null) {
1254 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1255 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1256 ptype = base_type.ResolveType (TypeResolveEmitContext);
1257 if (ptype == null) {
1263 if (!CheckRecursiveDefinition (this)) {
1269 TypeBuilder.SetParent (ptype);
1271 // add interfaces that were not added at type creation
1272 if (iface_exprs != null) {
1273 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1274 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1275 TypeResolveEmitContext.ContainerType = TypeBuilder;
1276 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1277 if (ifaces == null) {
1282 foreach (Type itype in ifaces)
1283 TypeBuilder.AddInterfaceImplementation (itype);
1285 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1288 if (!(this is Iterator))
1289 RootContext.RegisterOrder (this);
1291 if (!DefineNestedTypes ()) {
1299 protected virtual bool DefineNestedTypes ()
1301 if (Interfaces != null) {
1302 foreach (TypeContainer iface in Interfaces)
1303 if (iface.DefineType () == null)
1307 if (Types != null) {
1308 foreach (TypeContainer tc in Types)
1309 if (tc.DefineType () == null)
1313 if (Delegates != null) {
1314 foreach (Delegate d in Delegates)
1315 if (d.DefineType () == null)
1319 if (Enums != null) {
1320 foreach (Enum en in Enums)
1321 if (en.DefineType () == null)
1328 TypeContainer InTransit;
1330 protected bool CheckRecursiveDefinition (TypeContainer tc)
1332 if (InTransit != null) {
1333 Report.SymbolRelatedToPreviousError (this);
1334 if (this is Interface)
1336 529, tc.Location, "Inherited interface `{0}' causes a " +
1337 "cycle in the interface hierarchy of `{1}'",
1338 GetSignatureForError (), tc.GetSignatureForError ());
1341 146, tc.Location, "Circular base class dependency " +
1342 "involving `{0}' and `{1}'",
1343 tc.GetSignatureForError (), GetSignatureForError ());
1349 Type parent = ptype;
1350 if (parent != null) {
1351 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1352 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1356 if (iface_exprs != null) {
1357 foreach (TypeExpr iface in iface_exprs) {
1358 Type itype = iface.Type;
1360 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1361 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1370 public static void Error_KeywordNotAllowed (Location loc)
1372 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1376 /// Populates our TypeBuilder with fields and methods
1378 public override bool DefineMembers (TypeContainer container)
1380 if (members_defined)
1381 return members_defined_ok;
1383 if (!base.DefineMembers (container))
1386 members_defined_ok = DoDefineMembers ();
1387 members_defined = true;
1389 return members_defined_ok;
1392 protected virtual bool DoDefineMembers ()
1395 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1396 if (conflict_symbol == null) {
1397 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1398 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1400 if ((ModFlags & Modifiers.NEW) == 0) {
1401 Report.SymbolRelatedToPreviousError (conflict_symbol);
1402 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1403 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1408 DefineContainerMembers (constants);
1409 DefineContainerMembers (fields);
1411 if ((Kind == Kind.Class) && !(this is ClassPart)){
1412 if ((instance_constructors == null) &&
1413 !(this is StaticClass)) {
1414 if (default_constructor == null)
1415 DefineDefaultConstructor (false);
1418 if (initialized_static_fields != null &&
1419 default_static_constructor == null)
1420 DefineDefaultConstructor (true);
1423 if (Kind == Kind.Struct){
1425 // Structs can not have initialized instance
1428 if (initialized_static_fields != null &&
1429 default_static_constructor == null)
1430 DefineDefaultConstructor (true);
1432 if (initialized_fields != null)
1433 ReportStructInitializedInstanceError ();
1436 Pending = GetPendingImplementations ();
1438 if (parts != null) {
1439 foreach (ClassPart part in parts) {
1440 if (!part.DefineMembers (this))
1446 // Constructors are not in the defined_names array
1448 DefineContainerMembers (instance_constructors);
1450 if (default_static_constructor != null)
1451 default_static_constructor.Define ();
1453 DefineContainerMembers (properties);
1454 DefineContainerMembers (events);
1455 DefineContainerMembers (indexers);
1456 DefineContainerMembers (methods);
1457 DefineContainerMembers (operators);
1458 DefineContainerMembers (enums);
1459 DefineContainerMembers (delegates);
1462 if (!(this is ClassPart))
1463 member_cache = new MemberCache (this);
1466 if (parts != null) {
1467 foreach (ClassPart part in parts)
1468 part.member_cache = member_cache;
1471 if (iterators != null) {
1472 foreach (Iterator iterator in iterators) {
1473 if (iterator.DefineType () == null)
1477 foreach (Iterator iterator in iterators) {
1478 if (!iterator.DefineMembers (this))
1486 void ReportStructInitializedInstanceError ()
1488 string n = TypeBuilder.FullName;
1490 foreach (Field f in initialized_fields){
1491 Report.Error (573, Location,
1492 "`{0}': Structs cannot have instance field initializers",
1493 f.GetSignatureForError ());
1497 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1500 mcal.DefineContainerMembers ();
1503 public override bool Define ()
1505 if (parts != null) {
1506 foreach (ClassPart part in parts) {
1507 if (!part.Define ())
1512 if (iterators != null) {
1513 foreach (Iterator iterator in iterators) {
1514 if (!iterator.Define ())
1522 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1524 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1528 /// This function is based by a delegate to the FindMembers routine
1530 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1536 /// This filter is used by FindMembers, and we just keep
1537 /// a global for the filter to `AlwaysAccept'
1539 static MemberFilter accepting_filter;
1542 static TypeContainer ()
1544 accepting_filter = new MemberFilter (AlwaysAccept);
1547 public MethodInfo[] GetMethods ()
1549 ArrayList members = new ArrayList ();
1551 DefineMembers (null);
1553 if (methods != null) {
1554 int len = methods.Count;
1555 for (int i = 0; i < len; i++) {
1556 Method m = (Method) methods [i];
1558 members.Add (m.MethodBuilder);
1562 if (operators != null) {
1563 int len = operators.Count;
1564 for (int i = 0; i < len; i++) {
1565 Operator o = (Operator) operators [i];
1567 members.Add (o.OperatorMethodBuilder);
1571 if (properties != null) {
1572 int len = properties.Count;
1573 for (int i = 0; i < len; i++) {
1574 Property p = (Property) properties [i];
1576 if (p.GetBuilder != null)
1577 members.Add (p.GetBuilder);
1578 if (p.SetBuilder != null)
1579 members.Add (p.SetBuilder);
1583 if (indexers != null) {
1584 int len = indexers.Count;
1585 for (int i = 0; i < len; i++) {
1586 Indexer ix = (Indexer) indexers [i];
1588 if (ix.GetBuilder != null)
1589 members.Add (ix.GetBuilder);
1590 if (ix.SetBuilder != null)
1591 members.Add (ix.SetBuilder);
1595 if (events != null) {
1596 int len = events.Count;
1597 for (int i = 0; i < len; i++) {
1598 Event e = (Event) events [i];
1600 if (e.AddBuilder != null)
1601 members.Add (e.AddBuilder);
1602 if (e.RemoveBuilder != null)
1603 members.Add (e.RemoveBuilder);
1607 MethodInfo[] retMethods = new MethodInfo [members.Count];
1608 members.CopyTo (retMethods, 0);
1612 // Indicated whether container has StructLayout attribute set Explicit
1613 public virtual bool HasExplicitLayout {
1619 public override Type FindNestedType (string name)
1621 ArrayList [] lists = { types, enums, delegates, interfaces };
1623 for (int j = 0; j < lists.Length; ++j) {
1624 ArrayList list = lists [j];
1628 int len = list.Count;
1629 for (int i = 0; i < len; ++i) {
1630 DeclSpace ds = (DeclSpace) list [i];
1631 if (ds.Basename == name) {
1633 return ds.TypeBuilder;
1641 private void FindMembers_NestedTypes (int modflags,
1642 BindingFlags bf, MemberFilter filter, object criteria,
1643 ref ArrayList members)
1645 ArrayList [] lists = { types, enums, delegates, interfaces };
1647 for (int j = 0; j < lists.Length; ++j) {
1648 ArrayList list = lists [j];
1652 int len = list.Count;
1653 for (int i = 0; i < len; i++) {
1654 DeclSpace ds = (DeclSpace) list [i];
1656 if ((ds.ModFlags & modflags) == 0)
1659 TypeBuilder tb = ds.TypeBuilder;
1661 if (!(criteria is string) || ds.Basename.Equals (criteria))
1662 tb = ds.DefineType ();
1665 if (tb != null && (filter (tb, criteria) == true)) {
1666 if (members == null)
1667 members = new ArrayList ();
1676 /// This method returns the members of this type just like Type.FindMembers would
1677 /// Only, we need to use this for types which are _being_ defined because MS'
1678 /// implementation can't take care of that.
1681 // FIXME: return an empty static array instead of null, that cleans up
1682 // some code and is consistent with some coding conventions I just found
1686 // Notice that in various cases we check if our field is non-null,
1687 // something that would normally mean that there was a bug elsewhere.
1689 // The problem happens while we are defining p-invoke methods, as those
1690 // will trigger a FindMembers, but this happens before things are defined
1692 // Since the whole process is a no-op, it is fine to check for null here.
1694 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1695 MemberFilter filter, object criteria)
1697 ArrayList members = null;
1700 if ((bf & BindingFlags.Public) != 0)
1701 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1703 if ((bf & BindingFlags.NonPublic) != 0)
1704 modflags |= Modifiers.PRIVATE;
1706 int static_mask = 0, static_flags = 0;
1707 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1708 case BindingFlags.Static:
1709 static_mask = static_flags = Modifiers.STATIC;
1712 case BindingFlags.Instance:
1713 static_mask = Modifiers.STATIC;
1718 static_mask = static_flags = 0;
1722 Timer.StartTimer (TimerType.TcFindMembers);
1725 filter = accepting_filter;
1727 if ((mt & MemberTypes.Field) != 0) {
1728 if (fields != null) {
1729 int len = fields.Count;
1730 for (int i = 0; i < len; i++) {
1731 FieldMember f = (FieldMember) fields [i];
1733 if ((f.ModFlags & modflags) == 0)
1735 if ((f.ModFlags & static_mask) != static_flags)
1738 FieldBuilder fb = f.FieldBuilder;
1739 if (fb != null && filter (fb, criteria) == true) {
1740 if (members == null)
1741 members = new ArrayList ();
1748 if (constants != null) {
1749 int len = constants.Count;
1750 for (int i = 0; i < len; i++) {
1751 Const con = (Const) constants [i];
1753 if ((con.ModFlags & modflags) == 0)
1755 if ((con.ModFlags & static_mask) != static_flags)
1758 FieldBuilder fb = con.FieldBuilder;
1761 fb = con.FieldBuilder;
1763 if (fb != null && filter (fb, criteria) == true) {
1764 if (members == null)
1765 members = new ArrayList ();
1773 if ((mt & MemberTypes.Method) != 0) {
1774 if (methods != null) {
1775 int len = methods.Count;
1776 for (int i = 0; i < len; i++) {
1777 Method m = (Method) methods [i];
1779 if ((m.ModFlags & modflags) == 0)
1781 if ((m.ModFlags & static_mask) != static_flags)
1784 MethodBuilder mb = m.MethodBuilder;
1786 if (mb != null && filter (mb, criteria) == true) {
1787 if (members == null)
1788 members = new ArrayList ();
1795 if (operators != null) {
1796 int len = operators.Count;
1797 for (int i = 0; i < len; i++) {
1798 Operator o = (Operator) operators [i];
1800 if ((o.ModFlags & modflags) == 0)
1802 if ((o.ModFlags & static_mask) != static_flags)
1805 MethodBuilder ob = o.OperatorMethodBuilder;
1806 if (ob != null && filter (ob, criteria) == true) {
1807 if (members == null)
1808 members = new ArrayList ();
1815 if (properties != null) {
1816 int len = properties.Count;
1817 for (int i = 0; i < len; i++) {
1818 Property p = (Property) properties [i];
1820 if ((p.ModFlags & modflags) == 0)
1822 if ((p.ModFlags & static_mask) != static_flags)
1828 if (b != null && filter (b, criteria) == true) {
1829 if (members == null)
1830 members = new ArrayList ();
1836 if (b != null && filter (b, criteria) == true) {
1837 if (members == null)
1838 members = new ArrayList ();
1845 if (indexers != null) {
1846 int len = indexers.Count;
1847 for (int i = 0; i < len; i++) {
1848 Indexer ix = (Indexer) indexers [i];
1850 if ((ix.ModFlags & modflags) == 0)
1852 if ((ix.ModFlags & static_mask) != static_flags)
1858 if (b != null && filter (b, criteria) == true) {
1859 if (members == null)
1860 members = new ArrayList ();
1866 if (b != null && filter (b, criteria) == true) {
1867 if (members == null)
1868 members = new ArrayList ();
1876 if ((mt & MemberTypes.Event) != 0) {
1877 if (events != null) {
1878 int len = events.Count;
1879 for (int i = 0; i < len; i++) {
1880 Event e = (Event) events [i];
1882 if ((e.ModFlags & modflags) == 0)
1884 if ((e.ModFlags & static_mask) != static_flags)
1887 MemberInfo eb = e.EventBuilder;
1888 if (eb != null && filter (eb, criteria) == true) {
1889 if (members == null)
1890 members = new ArrayList ();
1892 members.Add (e.EventBuilder);
1898 if ((mt & MemberTypes.Property) != 0){
1899 if (properties != null) {
1900 int len = properties.Count;
1901 for (int i = 0; i < len; i++) {
1902 Property p = (Property) properties [i];
1904 if ((p.ModFlags & modflags) == 0)
1906 if ((p.ModFlags & static_mask) != static_flags)
1909 MemberInfo pb = p.PropertyBuilder;
1910 if (pb != null && filter (pb, criteria) == true) {
1911 if (members == null)
1912 members = new ArrayList ();
1914 members.Add (p.PropertyBuilder);
1919 if (indexers != null) {
1920 int len = indexers.Count;
1921 for (int i = 0; i < len; i++) {
1922 Indexer ix = (Indexer) indexers [i];
1924 if ((ix.ModFlags & modflags) == 0)
1926 if ((ix.ModFlags & static_mask) != static_flags)
1929 MemberInfo ib = ix.PropertyBuilder;
1930 if (ib != null && filter (ib, criteria) == true) {
1931 if (members == null)
1932 members = new ArrayList ();
1934 members.Add (ix.PropertyBuilder);
1940 if ((mt & MemberTypes.NestedType) != 0)
1941 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1943 if ((mt & MemberTypes.Constructor) != 0){
1944 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1945 int len = instance_constructors.Count;
1946 for (int i = 0; i < len; i++) {
1947 Constructor c = (Constructor) instance_constructors [i];
1949 ConstructorBuilder cb = c.ConstructorBuilder;
1950 if (cb != null && filter (cb, criteria) == true) {
1951 if (members == null)
1952 members = new ArrayList ();
1959 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1960 ConstructorBuilder cb =
1961 default_static_constructor.ConstructorBuilder;
1963 if (cb != null && filter (cb, criteria) == true) {
1964 if (members == null)
1965 members = new ArrayList ();
1973 // Lookup members in base if requested.
1975 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1976 if (TypeBuilder.BaseType != null) {
1977 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1978 if (list.Count > 0) {
1979 if (members == null)
1980 members = new ArrayList ();
1982 members.AddRange (list);
1985 if (ifaces != null) {
1986 foreach (Type base_type in ifaces) {
1987 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1989 if (list.Count > 0) {
1990 if (members == null)
1991 members = new ArrayList ();
1992 members.AddRange (list);
1998 Timer.StopTimer (TimerType.TcFindMembers);
2000 if (members == null)
2001 return MemberList.Empty;
2003 return new MemberList (members);
2006 public override MemberCache MemberCache {
2008 return member_cache;
2012 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2013 MemberFilter filter, object criteria)
2015 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2018 return ds.FindMembers (mt, bf, filter, criteria);
2020 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2025 // FindMethods will look for methods not only in the type `t', but in
2026 // any interfaces implemented by the type.
2028 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2029 MemberFilter filter, object criteria)
2035 /// Emits the values for the constants
2037 public void EmitConstants ()
2039 if (constants != null)
2040 foreach (Const con in constants)
2045 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2050 foreach (MemberCore mc in al) {
2051 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2055 Report.Warning (169, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2060 public virtual void VerifyMembers ()
2063 // Check for internal or private fields that were never assigned
2065 if (RootContext.WarningLevel >= 3) {
2066 CheckMemberUsage (properties, "property");
2067 CheckMemberUsage (methods, "method");
2068 CheckMemberUsage (constants, "constant");
2070 if (fields != null){
2071 foreach (FieldMember f in fields) {
2072 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2076 Report.Warning (169, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2081 // Only report 649 on level 4
2083 if (RootContext.WarningLevel < 4)
2086 if ((f.status & Field.Status.ASSIGNED) != 0)
2089 Report.Warning (649, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2090 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2097 /// Emits the code, this step is performed after all
2098 /// the types, enumerations, constructors
2100 public void EmitType ()
2102 if (OptAttributes != null)
2103 OptAttributes.Emit (ec, this);
2106 // Structs with no fields need to have at least one byte.
2107 // The right thing would be to set the PackingSize in a DefineType
2108 // but there are no functions that allow interfaces *and* the size to
2112 if (Kind == Kind.Struct && first_nonstatic_field == null){
2113 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2114 FieldAttributes.Private);
2116 if (HasExplicitLayout){
2117 object [] ctor_args = new object [1];
2120 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2121 TypeManager.field_offset_attribute_ctor, ctor_args);
2122 fb.SetCustomAttribute (cba);
2128 if (instance_constructors != null) {
2129 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2130 bool has_compliant_args = false;
2132 foreach (Constructor c in instance_constructors) {
2135 if (has_compliant_args)
2138 has_compliant_args = c.HasCompliantArgs;
2140 if (!has_compliant_args)
2141 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2143 foreach (Constructor c in instance_constructors)
2148 // Can not continue if constants are broken
2150 if (Report.Errors > 0)
2153 if (default_static_constructor != null)
2154 default_static_constructor.Emit ();
2156 if (methods != null)
2157 foreach (Method m in methods)
2160 if (operators != null)
2161 foreach (Operator o in operators)
2164 if (properties != null)
2165 foreach (Property p in properties)
2168 if (indexers != null){
2173 foreach (FieldMember f in fields)
2176 if (events != null){
2177 foreach (Event e in Events)
2181 if (delegates != null) {
2182 foreach (Delegate d in Delegates) {
2187 if (enums != null) {
2188 foreach (Enum e in enums) {
2193 if (parts != null) {
2194 foreach (ClassPart part in parts)
2198 if ((Pending != null) && !(this is ClassPart))
2199 if (Pending.VerifyPendingMethods ())
2202 if (iterators != null)
2203 foreach (Iterator iterator in iterators)
2204 iterator.EmitType ();
2206 // if (types != null)
2207 // foreach (TypeContainer tc in types)
2211 public override void CloseType ()
2213 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2217 caching_flags |= Flags.CloseTypeCreated;
2218 TypeBuilder.CreateType ();
2219 } catch (TypeLoadException){
2221 // This is fine, the code still created the type
2223 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2224 // Console.WriteLine (e.Message);
2226 Console.WriteLine ("In type: " + Name);
2231 foreach (Enum en in Enums)
2235 foreach (TypeContainer tc in Types)
2236 if (tc.Kind == Kind.Struct)
2239 foreach (TypeContainer tc in Types)
2240 if (tc.Kind != Kind.Struct)
2244 if (Delegates != null)
2245 foreach (Delegate d in Delegates)
2248 if (Iterators != null)
2249 foreach (Iterator i in Iterators)
2257 initialized_fields = null;
2258 initialized_static_fields = null;
2267 default_constructor = null;
2268 default_static_constructor = null;
2270 OptAttributes = null;
2273 member_cache = null;
2277 // Performs the validation on a Method's modifiers (properties have
2278 // the same properties).
2280 public bool MethodModifiersValid (MemberCore mc)
2282 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2283 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2284 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2286 int flags = mc.ModFlags;
2289 // At most one of static, virtual or override
2291 if ((flags & Modifiers.STATIC) != 0){
2292 if ((flags & vao) != 0){
2293 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2294 mc.GetSignatureForError ());
2299 if (Kind == Kind.Struct){
2300 if ((flags & va) != 0){
2301 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2306 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2307 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2308 mc.GetSignatureForError ());
2313 // If the declaration includes the abstract modifier, then the
2314 // declaration does not include static, virtual or extern
2316 if ((flags & Modifiers.ABSTRACT) != 0){
2317 if ((flags & Modifiers.EXTERN) != 0){
2319 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2323 if ((flags & Modifiers.SEALED) != 0) {
2324 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2328 if ((flags & Modifiers.VIRTUAL) != 0){
2329 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2333 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2334 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2339 if ((flags & Modifiers.PRIVATE) != 0){
2340 if ((flags & vao) != 0){
2341 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2346 if ((flags & Modifiers.SEALED) != 0){
2347 if ((flags & Modifiers.OVERRIDE) == 0){
2348 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2356 public bool UserDefinedStaticConstructor {
2358 return default_static_constructor != null;
2362 public Constructor DefaultStaticConstructor {
2363 get { return default_static_constructor; }
2366 protected override bool VerifyClsCompliance (DeclSpace ds)
2368 if (!base.VerifyClsCompliance (ds))
2373 Type base_type = TypeBuilder.BaseType;
2374 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2375 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2378 if (!Parent.IsClsCompliaceRequired (ds)) {
2379 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type `{1}'",
2380 GetSignatureForError (), Parent.GetSignatureForError ());
2387 /// Checks whether container name is CLS Compliant
2389 void VerifyClsName ()
2391 Hashtable base_members = base_cache == null ?
2393 base_cache.GetPublicMembers ();
2394 Hashtable this_members = new Hashtable ();
2396 foreach (DictionaryEntry entry in defined_names) {
2397 MemberCore mc = (MemberCore)entry.Value;
2398 if (!mc.IsClsCompliaceRequired (this))
2401 string name = (string)entry.Key;
2402 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2404 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2405 object found = base_members [lcase];
2406 if (found == null) {
2407 found = this_members [lcase];
2408 if (found == null) {
2409 this_members.Add (lcase, mc);
2414 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2417 if (found is MemberInfo) {
2418 if (basename == ((MemberInfo)found).Name)
2420 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2422 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2424 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2430 /// Performs checks for an explicit interface implementation. First it
2431 /// checks whether the `interface_type' is a base inteface implementation.
2432 /// Then it checks whether `name' exists in the interface type.
2434 public virtual bool VerifyImplements (MemberBase mb)
2436 if (ifaces != null) {
2437 foreach (Type t in ifaces){
2438 if (t == mb.InterfaceType)
2443 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2444 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2448 protected override void VerifyObsoleteAttribute()
2450 CheckUsageOfObsoleteAttribute (ptype);
2455 foreach (Type iface in ifaces) {
2456 CheckUsageOfObsoleteAttribute (iface);
2465 string IMemberContainer.Name {
2471 Type IMemberContainer.Type {
2477 MemberCache IMemberContainer.MemberCache {
2479 return member_cache;
2483 bool IMemberContainer.IsInterface {
2485 return Kind == Kind.Interface;
2489 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2491 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2495 // Generates xml doc comments (if any), and if required,
2496 // handle warning report.
2498 internal override void GenerateDocComment (DeclSpace ds)
2500 DocUtil.GenerateTypeDocComment (this, ds);
2503 public override string DocCommentHeader {
2504 get { return "T:"; }
2507 public virtual MemberCache BaseCache {
2509 if (base_cache != null)
2511 if (TypeBuilder.BaseType != null)
2512 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2513 if (TypeBuilder.IsInterface)
2514 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2520 public class PartialContainer : TypeContainer {
2522 public readonly Namespace Namespace;
2523 public readonly int OriginalModFlags;
2524 public readonly int AllowedModifiers;
2525 public readonly TypeAttributes DefaultTypeAttributes;
2527 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2528 MemberName member_name, int mod_flags, Kind kind,
2531 PartialContainer pc;
2532 DeclSpace ds = RootContext.Tree.GetDecl (member_name);
2534 pc = ds as PartialContainer;
2537 Report.LocationOfPreviousError (loc);
2538 Report.Error (260, ds.Location,
2539 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
2540 member_name.GetPartialName());
2545 if (pc.Kind != kind) {
2547 261, loc, "Partial declarations of `{0}' " +
2548 "must be all classes, all structs or " +
2549 "all interfaces", member_name.GetPartialName ());
2553 if (pc.OriginalModFlags != mod_flags) {
2555 262, loc, "Partial declarations of `{0}' " +
2556 "have conflicting accessibility modifiers",
2557 member_name.GetPartialName ());
2564 if (parent is ClassPart)
2565 parent = ((ClassPart) parent).PartialContainer;
2567 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2568 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2570 if (kind == Kind.Interface)
2571 parent.AddInterface (pc);
2572 else if (kind == Kind.Class || kind == Kind.Struct)
2573 parent.AddClassOrStruct (pc);
2575 throw new InvalidOperationException ();
2580 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2581 MemberName name, int mod, Attributes attrs,
2582 Kind kind, Location loc)
2584 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2586 // An error occured; create a dummy container, but don't
2588 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2591 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2596 protected PartialContainer (Namespace ns, TypeContainer parent,
2597 MemberName name, int mod, Kind kind, Location l)
2598 : base (null, parent, name, null, kind, l)
2600 this.Namespace = ns;
2604 AllowedModifiers = Class.AllowedModifiers;
2605 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2609 AllowedModifiers = Struct.AllowedModifiers;
2610 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2613 case Kind.Interface:
2614 AllowedModifiers = Interface.AllowedModifiers;
2615 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2619 throw new InvalidOperationException ();
2623 if (parent.Parent == null)
2624 accmods = Modifiers.INTERNAL;
2626 accmods = Modifiers.PRIVATE;
2628 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2629 this.OriginalModFlags = mod;
2632 public override PendingImplementation GetPendingImplementations ()
2634 return PendingImplementation.GetPendingImplementations (this);
2637 protected override TypeAttributes TypeAttr {
2639 return base.TypeAttr | DefaultTypeAttributes;
2644 public class ClassPart : TypeContainer, IMemberContainer {
2645 public readonly PartialContainer PartialContainer;
2646 public readonly bool IsPartial;
2648 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2649 int mod, Attributes attrs, Kind kind, Location l)
2650 : base (ns, parent, pc.MemberName, attrs, kind, l)
2652 this.PartialContainer = pc;
2653 this.IsPartial = true;
2656 if (parent == null || parent == RootContext.Tree.Types)
2657 accmods = Modifiers.INTERNAL;
2659 accmods = Modifiers.PRIVATE;
2661 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2664 public override PendingImplementation GetPendingImplementations ()
2666 return PartialContainer.Pending;
2669 public override bool VerifyImplements (MemberBase mb)
2671 return PartialContainer.VerifyImplements (mb);
2675 public override void RegisterFieldForInitialization (FieldMember field)
2677 PartialContainer.RegisterFieldForInitialization (field);
2680 public override bool EmitFieldInitializers (EmitContext ec)
2682 return PartialContainer.EmitFieldInitializers (ec);
2685 public override Type FindNestedType (string name)
2687 return PartialContainer.FindNestedType (name);
2690 public override MemberCache BaseCache {
2692 return PartialContainer.BaseCache;
2696 public override TypeBuilder DefineType ()
2698 throw new InternalErrorException ("Should not get here");
2703 public abstract class ClassOrStruct : TypeContainer {
2704 bool has_explicit_layout = false;
2705 ListDictionary declarative_security;
2707 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2708 MemberName name, Attributes attrs, Kind kind,
2710 : base (ns, parent, name, attrs, kind, l)
2714 public override PendingImplementation GetPendingImplementations ()
2716 return PendingImplementation.GetPendingImplementations (this);
2719 public override bool HasExplicitLayout {
2721 return has_explicit_layout;
2725 public override void VerifyMembers ()
2727 base.VerifyMembers ();
2729 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2730 foreach (Event e in events){
2732 Report.Warning (67, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2737 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2739 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2740 if (declarative_security == null)
2741 declarative_security = new ListDictionary ();
2743 a.ExtractSecurityPermissionSet (declarative_security);
2747 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2748 has_explicit_layout = true;
2750 base.ApplyAttributeBuilder (a, cb);
2753 public override void Emit()
2757 if (declarative_security != null) {
2758 foreach (DictionaryEntry de in declarative_security) {
2759 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2766 /// Class handles static classes declaration
2768 public sealed class StaticClass: Class {
2769 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2770 Attributes attrs, Location l)
2771 : base (ns, parent, name, mod, attrs, l)
2773 if (RootContext.Version == LanguageVersion.ISO_1) {
2774 Report.FeatureIsNotStandardized (l, "static classes");
2778 protected override int AllowedModifiersProp {
2780 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2781 Modifiers.STATIC | Modifiers.UNSAFE;
2785 protected override void DefineContainerMembers (MemberCoreArrayList list)
2790 foreach (MemberCore m in list) {
2791 if (m is Operator) {
2792 Report.Error (715, m.Location, "`{0}': static classes cannot contain user-defined operators", m.GetSignatureForError ());
2796 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2797 Report.Warning (-628, 4, m.Location, "`{0}': new protected member declared in static class", m.GetSignatureForError ());
2800 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2804 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2807 if (m is Constructor) {
2808 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2812 if (m is Destructor) {
2813 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2817 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2820 base.DefineContainerMembers (list);
2823 public override TypeBuilder DefineType()
2825 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2826 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2830 TypeBuilder tb = base.DefineType ();
2834 if (ptype != TypeManager.object_type) {
2835 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2839 if (ifaces != null) {
2840 foreach (Type t in ifaces)
2841 Report.SymbolRelatedToPreviousError (t);
2842 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2847 protected override TypeAttributes TypeAttr {
2849 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2854 public class Class : ClassOrStruct {
2855 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2856 public const int AllowedModifiers =
2859 Modifiers.PROTECTED |
2860 Modifiers.INTERNAL |
2862 Modifiers.ABSTRACT |
2866 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2867 Attributes attrs, Location l)
2868 : base (ns, parent, name, attrs, Kind.Class, l)
2870 this.ModFlags = mod;
2873 virtual protected int AllowedModifiersProp {
2875 return AllowedModifiers;
2879 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2881 if (a.Type == TypeManager.attribute_usage_type) {
2882 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2883 TypeBuilder.FullName != "System.Attribute") {
2884 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.Name);
2888 if (a.Type == TypeManager.conditional_attribute_type &&
2889 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
2890 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2894 if (AttributeTester.IsAttributeExcluded (a.Type))
2897 base.ApplyAttributeBuilder (a, cb);
2900 public const TypeAttributes DefaultTypeAttributes =
2901 TypeAttributes.AutoLayout | TypeAttributes.Class;
2903 public override TypeBuilder DefineType()
2905 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2906 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2910 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2911 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2913 return base.DefineType ();
2916 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2917 /// Valid only for attribute classes.
2918 public bool IsExcluded ()
2920 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2921 return (caching_flags & Flags.Excluded) != 0;
2923 caching_flags &= ~Flags.Excluded_Undetected;
2925 if (OptAttributes == null)
2928 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
2933 foreach (Attribute a in attrs) {
2934 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
2935 if (RootContext.AllDefines.Contains (condition))
2939 caching_flags |= Flags.Excluded;
2944 // FIXME: How do we deal with the user specifying a different
2947 protected override TypeAttributes TypeAttr {
2949 return base.TypeAttr | DefaultTypeAttributes;
2954 public class Struct : ClassOrStruct {
2956 // Modifiers allowed in a struct declaration
2958 public const int AllowedModifiers =
2961 Modifiers.PROTECTED |
2962 Modifiers.INTERNAL |
2966 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2967 int mod, Attributes attrs, Location l)
2968 : base (ns, parent, name, attrs, Kind.Struct, l)
2972 if (parent.Parent == null)
2973 accmods = Modifiers.INTERNAL;
2975 accmods = Modifiers.PRIVATE;
2977 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2979 this.ModFlags |= Modifiers.SEALED;
2982 public const TypeAttributes DefaultTypeAttributes =
2983 TypeAttributes.SequentialLayout |
2984 TypeAttributes.Sealed |
2985 TypeAttributes.BeforeFieldInit;
2988 // FIXME: Allow the user to specify a different set of attributes
2989 // in some cases (Sealed for example is mandatory for a class,
2990 // but what SequentialLayout can be changed
2992 protected override TypeAttributes TypeAttr {
2994 return base.TypeAttr | DefaultTypeAttributes;
3002 public class Interface : TypeContainer, IMemberContainer {
3005 /// Modifiers allowed in a class declaration
3007 public const int AllowedModifiers =
3010 Modifiers.PROTECTED |
3011 Modifiers.INTERNAL |
3015 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3016 Attributes attrs, Location l)
3017 : base (ns, parent, name, attrs, Kind.Interface, l)
3021 if (parent.Parent == null)
3022 accmods = Modifiers.INTERNAL;
3024 accmods = Modifiers.PRIVATE;
3026 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3029 public override PendingImplementation GetPendingImplementations ()
3034 public const TypeAttributes DefaultTypeAttributes =
3035 TypeAttributes.AutoLayout |
3036 TypeAttributes.Abstract |
3037 TypeAttributes.Interface;
3039 protected override TypeAttributes TypeAttr {
3041 return base.TypeAttr | DefaultTypeAttributes;
3045 protected override bool VerifyClsCompliance (DeclSpace ds)
3047 if (!base.VerifyClsCompliance (ds))
3050 if (ifaces != null) {
3051 foreach (Type t in ifaces) {
3052 if (AttributeTester.IsClsCompliant (t))
3055 Report.SymbolRelatedToPreviousError (t);
3056 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3057 GetSignatureForError (), TypeManager.CSharpName (t));
3065 public abstract class MethodCore : MemberBase {
3066 public readonly Parameters Parameters;
3067 protected ToplevelBlock block;
3070 // Parameters, cached for semantic analysis.
3072 protected InternalParameters parameter_info;
3073 protected Type [] parameter_types;
3075 // Whether this is an operator method.
3076 public Operator IsOperator;
3079 // The method we're overriding if this is an override method.
3081 protected MethodInfo base_method = null;
3083 static string[] attribute_targets = new string [] { "method", "return" };
3085 public MethodCore (TypeContainer parent, Expression type, int mod,
3086 int allowed_mod, bool is_interface, MemberName name,
3087 Attributes attrs, Parameters parameters, Location loc)
3088 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3091 Parameters = parameters;
3092 IsInterface = is_interface;
3096 // Returns the System.Type array for the parameters of this method
3098 public Type [] ParameterTypes {
3100 return parameter_types;
3104 public InternalParameters ParameterInfo
3107 return parameter_info;
3111 public ToplevelBlock Block {
3121 // TODO: why is it done in extra call ?
3122 public void SetYields ()
3124 ModFlags |= Modifiers.METHOD_YIELDS;
3127 protected override bool CheckBase ()
3129 if (!base.CheckBase ())
3132 // Check whether arguments were correct.
3133 if (!DoDefineParameters ())
3136 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3142 // Is null for System.Object while compiling corlib and base interfaces
3143 if (Parent.BaseCache == null) {
3144 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3145 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3150 Type base_ret_type = null;
3151 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3153 // method is override
3154 if (base_method != null) {
3156 if (!CheckMethodAgainstBase ())
3159 if ((ModFlags & Modifiers.NEW) == 0) {
3160 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3161 Report.SymbolRelatedToPreviousError (base_method);
3162 if (this is PropertyBase) {
3163 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3164 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3167 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3168 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3173 if (base_method.IsAbstract && !IsInterface) {
3174 Report.SymbolRelatedToPreviousError (base_method);
3175 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3176 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3181 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3182 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3186 if (RootContext.WarningLevel > 2) {
3187 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3188 Parent.Methods.HasEquals = true;
3189 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3190 Parent.Methods.HasGetHashCode = true;
3193 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3194 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3196 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3197 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3198 Report.SymbolRelatedToPreviousError (base_method);
3199 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3200 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3207 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3208 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3209 if (conflict_symbol != null) {
3210 Report.SymbolRelatedToPreviousError (conflict_symbol);
3211 if (this is PropertyBase)
3212 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3214 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3216 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3220 if (conflict_symbol == null) {
3221 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3222 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3227 if ((ModFlags & Modifiers.NEW) == 0) {
3228 if (this is Method && conflict_symbol is MethodBase)
3231 Report.SymbolRelatedToPreviousError (conflict_symbol);
3232 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3233 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3240 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3241 // that have been defined.
3243 // `name' is the user visible name for reporting errors (this is used to
3244 // provide the right name regarding method names and properties)
3246 bool CheckMethodAgainstBase ()
3250 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3251 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3252 Report.Error (506, Location,
3253 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3254 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3258 // Now we check that the overriden method is not final
3260 if (base_method.IsFinal) {
3261 Report.SymbolRelatedToPreviousError (base_method);
3262 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3263 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3267 // Check that the permissions are not being changed
3269 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3270 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3272 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3273 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3278 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3279 ModFlags |= Modifiers.NEW;
3280 Report.SymbolRelatedToPreviousError (base_method);
3281 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3282 if (RootContext.WarningLevel >= 2)
3283 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 (), TypeManager.CSharpSignature (base_method));
3285 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3286 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3293 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3295 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3297 // when overriding protected internal, the method can be declared
3298 // protected internal only within the same assembly
3301 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3302 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3304 // assemblies differ - report an error
3308 } else if (thisp != base_classp) {
3310 // same assembly, but other attributes differ - report an error
3315 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3317 // if it's not "protected internal", it must be "protected"
3321 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3323 // protected within the same assembly - an error
3326 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3327 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3329 // protected ok, but other attributes differ - report an error
3335 return (thisp == base_classp);
3339 public bool CheckAbstractAndExtern (bool has_block)
3341 if (Parent.Kind == Kind.Interface)
3345 if ((ModFlags & Modifiers.EXTERN) != 0) {
3346 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3347 GetSignatureForError ());
3351 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3352 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3353 GetSignatureForError ());
3357 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3358 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3359 GetSignatureForError ());
3367 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3369 Report.SymbolRelatedToPreviousError (base_method);
3370 string base_name = TypeManager.GetFullNameSignature (base_method);
3371 string this_name = GetSignatureForError ();
3372 if (suffix != null) {
3373 base_name += suffix;
3374 this_name += suffix;
3377 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3378 this_name, Modifiers.GetDescription (ma), base_name);
3381 protected static string Error722 {
3383 return "`{0}': static types cannot be used as return types";
3388 /// For custom member duplication search in a container
3390 protected abstract bool CheckForDuplications ();
3393 /// Gets base method and its return type
3395 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3397 protected virtual bool DoDefineParameters ()
3399 EmitContext ec = Parent.EmitContext;
3401 throw new InternalErrorException ("DoDefineParameters invoked too early");
3403 bool old_unsafe = ec.InUnsafe;
3404 ec.InUnsafe = InUnsafe;
3405 // Check if arguments were correct
3406 parameter_types = Parameters.GetParameterInfo (ec);
3407 ec.InUnsafe = old_unsafe;
3409 if ((parameter_types == null) ||
3410 !CheckParameters (Parent, parameter_types))
3413 parameter_info = new InternalParameters (parameter_types, Parameters);
3415 Parameter array_param = Parameters.ArrayParameter;
3416 if ((array_param != null) &&
3417 (!array_param.ParameterType.IsArray ||
3418 (array_param.ParameterType.GetArrayRank () != 1))) {
3419 Report.Error (225, Location, "The params parameter must be a single dimensional array");
3426 public override string[] ValidAttributeTargets {
3428 return attribute_targets;
3432 protected override bool VerifyClsCompliance (DeclSpace ds)
3434 if (!base.VerifyClsCompliance (ds)) {
3435 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3436 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3441 if (Parameters.HasArglist) {
3442 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3445 if (!AttributeTester.IsClsCompliant (MemberType)) {
3446 if (this is PropertyBase)
3447 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3448 GetSignatureForError ());
3450 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3451 GetSignatureForError ());
3454 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3459 protected bool IsDuplicateImplementation (MethodCore method)
3461 if ((method == this) || (method.Name != Name))
3464 Type[] param_types = method.ParameterTypes;
3465 if (param_types == null)
3468 if (param_types.Length != ParameterTypes.Length)
3471 for (int i = 0; i < param_types.Length; i++)
3472 if (param_types [i] != ParameterTypes [i])
3475 // TODO: make operator compatible with MethodCore to avoid this
3476 if (this is Operator && method is Operator) {
3477 if (MemberType != method.MemberType)
3482 // Try to report 663: method only differs on out/ref
3484 ParameterData info = ParameterInfo;
3485 ParameterData other_info = method.ParameterInfo;
3486 for (int i = 0; i < info.Count; i++){
3487 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3488 Report.SymbolRelatedToPreviousError (method);
3489 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3490 GetSignatureForError ());
3495 Report.SymbolRelatedToPreviousError (method);
3496 if (this is Operator && method is Operator)
3497 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3499 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3503 public override bool IsUsed
3514 // Returns a string that represents the signature for this
3515 // member which should be used in XML documentation.
3517 public override string GetDocCommentName (DeclSpace ds)
3519 return DocUtil.GetMethodDocCommentName (this, ds);
3523 // Raised (and passed an XmlElement that contains the comment)
3524 // when GenerateDocComment is writing documentation expectedly.
3526 // FIXME: with a few effort, it could be done with XmlReader,
3527 // that means removal of DOM use.
3529 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3531 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3535 // Represents header string for documentation comment.
3537 public override string DocCommentHeader {
3538 get { return "M:"; }
3541 protected override void VerifyObsoleteAttribute()
3543 base.VerifyObsoleteAttribute ();
3545 if (parameter_types == null)
3548 foreach (Type type in parameter_types) {
3549 CheckUsageOfObsoleteAttribute (type);
3554 public class SourceMethod : ISourceMethod
3556 TypeContainer container;
3559 protected SourceMethod (TypeContainer container, MethodBase builder,
3560 ISourceFile file, Location start, Location end)
3562 this.container = container;
3563 this.builder = builder;
3565 CodeGen.SymbolWriter.OpenMethod (
3566 file, this, start.Row, 0, end.Row, 0);
3569 public string Name {
3570 get { return builder.Name; }
3573 public int NamespaceID {
3574 get { return container.NamespaceEntry.SymbolFileID; }
3579 if (builder is MethodBuilder)
3580 return ((MethodBuilder) builder).GetToken ().Token;
3581 else if (builder is ConstructorBuilder)
3582 return ((ConstructorBuilder) builder).GetToken ().Token;
3584 throw new NotSupportedException ();
3588 public void CloseMethod ()
3590 if (CodeGen.SymbolWriter != null)
3591 CodeGen.SymbolWriter.CloseMethod ();
3594 public static SourceMethod Create (TypeContainer parent,
3595 MethodBase builder, Block block)
3597 if (CodeGen.SymbolWriter == null)
3602 Location start_loc = block.StartLocation;
3603 if (Location.IsNull (start_loc))
3606 Location end_loc = block.EndLocation;
3607 if (Location.IsNull (end_loc))
3610 ISourceFile file = start_loc.SourceFile;
3614 return new SourceMethod (
3615 parent, builder, file, start_loc, end_loc);
3619 public class Method : MethodCore, IIteratorContainer, IMethodData {
3620 public MethodBuilder MethodBuilder;
3621 public MethodData MethodData;
3622 ReturnParameter return_attributes;
3623 ListDictionary declarative_security;
3626 /// Modifiers allowed in a class declaration
3628 const int AllowedModifiers =
3631 Modifiers.PROTECTED |
3632 Modifiers.INTERNAL |
3637 Modifiers.OVERRIDE |
3638 Modifiers.ABSTRACT |
3640 Modifiers.METHOD_YIELDS |
3643 const int AllowedInterfaceModifiers =
3644 Modifiers.NEW | Modifiers.UNSAFE;
3647 // return_type can be "null" for VOID values.
3649 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3650 MemberName name, Parameters parameters, Attributes attrs,
3652 : base (ds, return_type, mod,
3653 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3654 is_iface, name, attrs, parameters, l)
3658 public override AttributeTargets AttributeTargets {
3660 return AttributeTargets.Method;
3664 public override string GetSignatureForError()
3666 if (IsOperator != null)
3667 return IsOperator.GetSignatureForError ();
3669 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3672 void DuplicateEntryPoint (MethodInfo b, Location location)
3676 "Program `" + CodeGen.FileName +
3677 "' has more than one entry point defined: `" +
3678 TypeManager.CSharpSignature(b) + "'");
3681 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3683 if (b.ReturnType != TypeManager.void_type &&
3684 b.ReturnType != TypeManager.int32_type)
3687 if (pinfo.Count == 0)
3690 if (pinfo.Count > 1)
3693 Type t = pinfo.ParameterType(0);
3695 (t.GetArrayRank() == 1) &&
3696 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3697 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3703 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3705 if (a.Target == AttributeTargets.ReturnValue) {
3706 if (return_attributes == null)
3707 return_attributes = new ReturnParameter (MethodBuilder, Location);
3709 return_attributes.ApplyAttributeBuilder (a, cb);
3713 if (a.Type == TypeManager.methodimpl_attr_type &&
3714 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3715 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3718 if (a.Type == TypeManager.dllimport_type) {
3719 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3720 if ((ModFlags & extern_static) != extern_static) {
3721 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3727 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3728 if (declarative_security == null)
3729 declarative_security = new ListDictionary ();
3730 a.ExtractSecurityPermissionSet (declarative_security);
3734 if (a.Type == TypeManager.conditional_attribute_type) {
3735 if (IsOperator != null || IsExplicitImpl) {
3736 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3737 GetSignatureForError ());
3741 if (ReturnType != TypeManager.void_type) {
3742 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
3746 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3747 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
3752 Report.Error (582, Location, "Conditional not valid on interface members");
3756 if (MethodData.implementing != null) {
3757 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
3758 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
3762 for (int i = 0; i < parameter_info.Count; ++i) {
3763 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3764 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
3770 MethodBuilder.SetCustomAttribute (cb);
3773 protected override bool CheckForDuplications ()
3775 ArrayList ar = Parent.Methods;
3777 int arLen = ar.Count;
3779 for (int i = 0; i < arLen; i++) {
3780 Method m = (Method) ar [i];
3781 if (IsDuplicateImplementation (m))
3786 ar = Parent.Properties;
3788 for (int i = 0; i < ar.Count; ++i) {
3789 PropertyBase pb = (PropertyBase) ar [i];
3790 if (pb.AreAccessorsDuplicateImplementation (this))
3795 ar = Parent.Indexers;
3797 for (int i = 0; i < ar.Count; ++i) {
3798 PropertyBase pb = (PropertyBase) ar [i];
3799 if (pb.AreAccessorsDuplicateImplementation (this))
3806 for (int i = 0; i < ar.Count; ++i) {
3807 Event ev = (Event) ar [i];
3808 if (ev.AreAccessorsDuplicateImplementation (this))
3819 public override bool Define ()
3824 if (!CheckAbstractAndExtern (block != null))
3827 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3828 Error1599 (Location, ReturnType);
3835 if (IsOperator != null)
3836 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3838 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3840 if (!MethodData.Define (Parent))
3843 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3844 Name == "Finalize" && !(this is Destructor)) {
3845 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3849 // Setup iterator if we are one
3851 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3852 Iterator iterator = new Iterator (this,
3854 ParameterInfo, ModFlags);
3856 if (!iterator.DefineIterator ())
3860 MethodBuilder = MethodData.MethodBuilder;
3863 // This is used to track the Entry Point,
3865 if (Name == "Main" &&
3866 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3867 (RootContext.MainClass == null ||
3868 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3869 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3870 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3871 md.SetMemberIsUsed ();
3873 if (RootContext.EntryPoint == null) {
3874 RootContext.EntryPoint = MethodBuilder;
3875 RootContext.EntryPointLocation = Location;
3877 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3878 DuplicateEntryPoint (MethodBuilder, Location);
3881 if (RootContext.WarningLevel >= 4)
3882 Report.Warning (28, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3886 if (MemberType.IsAbstract && MemberType.IsSealed) {
3887 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3897 public override void Emit ()
3899 MethodData.Emit (Parent, this);
3902 if (declarative_security != null) {
3903 foreach (DictionaryEntry de in declarative_security) {
3904 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3912 public static void Error1599 (Location loc, Type t)
3914 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
3917 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3919 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3920 container.TypeBuilder, Name, ParameterTypes, false);
3925 base_ret_type = mi.ReturnType;
3929 public override bool MarkForDuplicationCheck ()
3931 caching_flags |= Flags.TestMethodDuplication;
3935 protected override bool VerifyClsCompliance(DeclSpace ds)
3937 if (!base.VerifyClsCompliance (ds))
3940 if (parameter_types.Length > 0) {
3941 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3943 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3949 #region IMethodData Members
3951 public CallingConventions CallingConventions {
3953 CallingConventions cc = Parameters.GetCallingConvention ();
3954 if (Parameters.HasArglist)
3955 block.HasVarargs = true;
3958 if ((ModFlags & Modifiers.STATIC) == 0)
3959 cc |= CallingConventions.HasThis;
3961 // FIXME: How is `ExplicitThis' used in C#?
3967 public Type ReturnType {
3973 public MemberName MethodName {
3979 public new Location Location {
3981 return base.Location;
3985 protected override bool CheckBase() {
3986 if (!base.CheckBase ())
3989 // TODO: Destructor should derive from MethodCore
3990 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3991 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3992 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3999 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4001 EmitContext ec = new EmitContext (
4002 tc, Parent, Location, ig, ReturnType, ModFlags, false);
4004 ec.CurrentIterator = tc as Iterator;
4005 if (ec.CurrentIterator != null)
4006 ec.CurrentAnonymousMethod = ec.CurrentIterator.Host;
4011 public ObsoleteAttribute GetObsoleteAttribute ()
4013 return GetObsoleteAttribute (Parent);
4017 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4019 public bool IsExcluded (EmitContext ec)
4021 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4022 return (caching_flags & Flags.Excluded) != 0;
4024 caching_flags &= ~Flags.Excluded_Undetected;
4026 if (base_method == null) {
4027 if (OptAttributes == null)
4030 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4035 foreach (Attribute a in attrs) {
4036 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4037 if (RootContext.AllDefines.Contains (condition))
4041 caching_flags |= Flags.Excluded;
4045 IMethodData md = TypeManager.GetMethod (base_method);
4047 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4048 caching_flags |= Flags.Excluded;
4054 if (md.IsExcluded (ec)) {
4055 caching_flags |= Flags.Excluded;
4064 public abstract class ConstructorInitializer {
4065 ArrayList argument_list;
4066 protected ConstructorInfo base_constructor;
4067 Parameters parameters;
4070 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4073 this.argument_list = argument_list;
4074 this.parameters = parameters;
4078 public ArrayList Arguments {
4080 return argument_list;
4084 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4086 Expression base_constructor_group;
4090 ec.CurrentBlock = block;
4092 if (argument_list != null){
4093 foreach (Argument a in argument_list){
4094 if (!a.Resolve (ec, loc))
4098 ec.CurrentBlock = null;
4100 if (this is ConstructorBaseInitializer) {
4101 if (ec.ContainerType.BaseType == null)
4104 t = ec.ContainerType.BaseType;
4105 if (ec.ContainerType.IsValueType) {
4106 Report.Error (522, loc,
4107 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4111 t = ec.ContainerType;
4113 base_constructor_group = Expression.MemberLookup (
4114 ec, t, ".ctor", MemberTypes.Constructor,
4115 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4118 if (base_constructor_group == null){
4120 base_constructor_group = Expression.MemberLookup (
4121 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4122 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4126 int errors = Report.Errors;
4127 if (base_constructor_group != null)
4128 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4129 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4132 if (base_constructor == null) {
4133 if (errors == Report.Errors)
4134 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4135 argument_list.Count);
4140 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4141 base_constructor = null;
4145 if (base_constructor == caller_builder){
4146 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4153 public void Emit (EmitContext ec)
4155 if (base_constructor != null){
4156 ec.Mark (loc, false);
4158 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4160 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4165 public class ConstructorBaseInitializer : ConstructorInitializer {
4166 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4167 base (argument_list, pars, l)
4172 public class ConstructorThisInitializer : ConstructorInitializer {
4173 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4174 base (argument_list, pars, l)
4179 public class Constructor : MethodCore, IMethodData {
4180 public ConstructorBuilder ConstructorBuilder;
4181 public ConstructorInitializer Initializer;
4182 ListDictionary declarative_security;
4185 // Modifiers allowed for a constructor.
4187 public const int AllowedModifiers =
4189 Modifiers.PROTECTED |
4190 Modifiers.INTERNAL |
4196 bool has_compliant_args = false;
4198 // The spec claims that static is not permitted, but
4199 // my very own code has static constructors.
4201 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4202 ConstructorInitializer init, Location l)
4203 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4209 public bool HasCompliantArgs {
4211 return has_compliant_args;
4215 public override AttributeTargets AttributeTargets {
4217 return AttributeTargets.Constructor;
4223 // Returns true if this is a default constructor
4225 public bool IsDefault ()
4227 if ((ModFlags & Modifiers.STATIC) != 0)
4228 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4229 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4232 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4233 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4234 (Initializer is ConstructorBaseInitializer) &&
4235 (Initializer.Arguments == null);
4238 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4240 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4241 if (declarative_security == null) {
4242 declarative_security = new ListDictionary ();
4244 a.ExtractSecurityPermissionSet (declarative_security);
4248 ConstructorBuilder.SetCustomAttribute (cb);
4251 protected override bool CheckForDuplications ()
4253 ArrayList ar = Parent.InstanceConstructors;
4255 int arLen = ar.Count;
4257 for (int i = 0; i < arLen; i++) {
4258 Constructor m = (Constructor) ar [i];
4259 if (IsDuplicateImplementation (m))
4266 protected override bool CheckBase ()
4268 // Check whether arguments were correct.
4269 if (!DoDefineParameters ())
4272 // TODO: skip the rest for generated ctor
4273 if ((ModFlags & Modifiers.STATIC) != 0)
4276 if (!CheckForDuplications ())
4279 if (Parent.Kind == Kind.Struct) {
4280 if (ParameterTypes.Length == 0) {
4281 Report.Error (568, Location,
4282 "Structs cannot contain explicit parameterless constructors");
4286 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4287 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4292 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4293 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4300 // Creates the ConstructorBuilder
4302 public override bool Define ()
4304 if (ConstructorBuilder != null)
4307 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4308 MethodAttributes.SpecialName);
4310 if ((ModFlags & Modifiers.STATIC) != 0) {
4311 ca |= MethodAttributes.Static | MethodAttributes.Private;
4313 ca |= MethodAttributes.HideBySig;
4315 if ((ModFlags & Modifiers.PUBLIC) != 0)
4316 ca |= MethodAttributes.Public;
4317 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4318 if ((ModFlags & Modifiers.INTERNAL) != 0)
4319 ca |= MethodAttributes.FamORAssem;
4321 ca |= MethodAttributes.Family;
4322 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4323 ca |= MethodAttributes.Assembly;
4324 else if (IsDefault ())
4325 ca |= MethodAttributes.Public;
4327 ca |= MethodAttributes.Private;
4330 if (!CheckAbstractAndExtern (block != null))
4333 // Check if arguments were correct.
4337 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4338 ca, CallingConventions,
4341 if ((ModFlags & Modifiers.UNSAFE) != 0)
4342 ConstructorBuilder.InitLocals = false;
4344 TypeManager.AddMethod (ConstructorBuilder, this);
4347 // HACK because System.Reflection.Emit is lame
4349 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4357 public override void Emit ()
4359 EmitContext ec = CreateEmitContext (null, null);
4361 // If this is a non-static `struct' constructor and doesn't have any
4362 // initializer, it must initialize all of the struct's fields.
4363 if ((Parent.Kind == Kind.Struct) &&
4364 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4365 Block.AddThisVariable (Parent, Location);
4368 block.ResolveMeta (ec, ParameterInfo);
4370 if ((ModFlags & Modifiers.STATIC) == 0){
4371 if (Parent.Kind == Kind.Class && Initializer == null)
4372 Initializer = new ConstructorBaseInitializer (
4373 null, Parameters.EmptyReadOnlyParameters, Location);
4377 // Spec mandates that Initializers will not have
4381 if ((Initializer != null) &&
4382 !Initializer.Resolve (ConstructorBuilder, block, ec))
4384 ec.IsStatic = false;
4387 Parameters.LabelParameters (ec, ConstructorBuilder);
4389 SourceMethod source = SourceMethod.Create (
4390 Parent, ConstructorBuilder, block);
4393 // Classes can have base initializers and instance field initializers.
4395 if (Parent.Kind == Kind.Class){
4396 if ((ModFlags & Modifiers.STATIC) == 0){
4399 // If we use a "this (...)" constructor initializer, then
4400 // do not emit field initializers, they are initialized in the other constructor
4402 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4403 Parent.EmitFieldInitializers (ec);
4406 if (Initializer != null) {
4407 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4408 ec.TestObsoleteMethodUsage = false;
4410 Initializer.Emit (ec);
4413 if ((ModFlags & Modifiers.STATIC) != 0)
4414 Parent.EmitFieldInitializers (ec);
4416 if (OptAttributes != null)
4417 OptAttributes.Emit (ec, this);
4419 ec.EmitTopBlock (this, block, ParameterInfo);
4422 source.CloseMethod ();
4426 if (declarative_security != null) {
4427 foreach (DictionaryEntry de in declarative_security) {
4428 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4435 // Is never override
4436 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4441 public override string GetSignatureForError()
4443 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4446 protected override bool VerifyClsCompliance (DeclSpace ds)
4448 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4452 if (parameter_types.Length > 0) {
4453 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4455 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4457 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4458 foreach (Type param in parameter_types) {
4459 if (param.IsArray) {
4465 has_compliant_args = true;
4469 #region IMethodData Members
4471 public System.Reflection.CallingConventions CallingConventions {
4473 CallingConventions cc = Parameters.GetCallingConvention ();
4475 if (Parent.Kind == Kind.Class)
4476 if ((ModFlags & Modifiers.STATIC) == 0)
4477 cc |= CallingConventions.HasThis;
4479 // FIXME: How is `ExplicitThis' used in C#?
4485 public new Location Location {
4487 return base.Location;
4491 public MemberName MethodName {
4497 public Type ReturnType {
4503 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4505 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4506 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4509 public ObsoleteAttribute GetObsoleteAttribute ()
4511 return GetObsoleteAttribute (Parent);
4514 public bool IsExcluded(EmitContext ec)
4523 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4525 public interface IMethodData
4527 CallingConventions CallingConventions { get; }
4528 Location Location { get; }
4529 MemberName MethodName { get; }
4530 Type[] ParameterTypes { get; }
4531 Type ReturnType { get; }
4533 Attributes OptAttributes { get; }
4534 ToplevelBlock Block { get; set; }
4536 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4537 ObsoleteAttribute GetObsoleteAttribute ();
4538 string GetSignatureForError ();
4539 bool IsExcluded (EmitContext ec);
4540 bool IsClsCompliaceRequired (DeclSpace ds);
4541 void SetMemberIsUsed ();
4545 // Encapsulates most of the Method's state
4547 public class MethodData {
4549 readonly IMethodData method;
4552 // The return type of this method
4554 public readonly InternalParameters ParameterInfo;
4557 // Are we implementing an interface ?
4559 public MethodInfo implementing;
4564 protected MemberBase member;
4565 protected int modifiers;
4566 protected MethodAttributes flags;
4568 MethodBuilder builder = null;
4569 public MethodBuilder MethodBuilder {
4575 public MethodData (MemberBase member, InternalParameters parameters,
4576 int modifiers, MethodAttributes flags, IMethodData method)
4578 this.member = member;
4579 this.ParameterInfo = parameters;
4580 this.modifiers = modifiers;
4583 this.method = method;
4586 public bool Define (TypeContainer container)
4588 string name = method.MethodName.Name;
4589 string method_name = name;
4591 Type[] ParameterTypes = method.ParameterTypes;
4593 if (container.Pending != null){
4594 if (member is Indexer) // TODO: test it, but it should work without this IF
4595 implementing = container.Pending.IsInterfaceIndexer (
4596 member.InterfaceType, method.ReturnType, ParameterInfo);
4598 implementing = container.Pending.IsInterfaceMethod (
4599 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4601 if (member.InterfaceType != null){
4602 if (implementing == null){
4603 if (member is PropertyBase) {
4604 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4605 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4606 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4609 Report.Error (539, method.Location,
4610 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4611 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4615 if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
4616 Report.SymbolRelatedToPreviousError (implementing);
4617 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4618 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4621 method_name = member.InterfaceType.FullName + "." + name;
4623 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
4624 Report.SymbolRelatedToPreviousError (implementing);
4625 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4626 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4633 // For implicit implementations, make sure we are public, for
4634 // explicit implementations, make sure we are private.
4636 if (implementing != null){
4638 // Setting null inside this block will trigger a more
4639 // verbose error reporting for missing interface implementations
4641 // The "candidate" function has been flagged already
4642 // but it wont get cleared
4644 if (member.IsExplicitImpl){
4645 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4646 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4647 implementing = null;
4649 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4650 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4652 // If this is an interface method implementation,
4653 // check for public accessibility
4655 implementing = null;
4656 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4657 // We may never be private.
4658 implementing = null;
4659 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4661 // We may be protected if we're overriding something.
4663 implementing = null;
4668 // Static is not allowed
4670 if ((modifiers & Modifiers.STATIC) != 0){
4671 implementing = null;
4672 Modifiers.Error_InvalidModifier (method.Location, "static");
4677 // If implementing is still valid, set flags
4679 if (implementing != null){
4681 // When implementing interface methods, set NewSlot
4682 // unless, we are overwriting a method.
4684 if (implementing.DeclaringType.IsInterface){
4685 if ((modifiers & Modifiers.OVERRIDE) == 0)
4686 flags |= MethodAttributes.NewSlot;
4689 MethodAttributes.Virtual |
4690 MethodAttributes.HideBySig;
4692 // Set Final unless we're virtual, abstract or already overriding a method.
4693 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4694 flags |= MethodAttributes.Final;
4697 EmitContext ec = method.CreateEmitContext (container, null);
4699 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4701 if (builder == null)
4704 if ((modifiers & Modifiers.UNSAFE) != 0)
4705 builder.InitLocals = false;
4707 if (implementing != null){
4709 // clear the pending implemntation flag
4711 if (member is Indexer) {
4712 container.Pending.ImplementIndexer (
4713 member.InterfaceType, builder, method.ReturnType,
4714 ParameterInfo, member.IsExplicitImpl);
4716 container.Pending.ImplementMethod (
4717 member.InterfaceType, name, method.ReturnType,
4718 ParameterInfo, member.IsExplicitImpl);
4720 if (member.IsExplicitImpl)
4721 container.TypeBuilder.DefineMethodOverride (
4722 builder, implementing);
4726 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4727 TypeManager.AddMethod (builder, method);
4734 /// Create the MethodBuilder for the method
4736 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4738 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4740 if ((modifiers & extern_static) == extern_static) {
4742 if (method.OptAttributes != null) {
4743 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4744 if (dllimport_attribute != null) {
4745 flags |= MethodAttributes.PinvokeImpl;
4746 builder = dllimport_attribute.DefinePInvokeMethod (
4747 ec, container.TypeBuilder, method_name, flags,
4748 method.ReturnType, ParameterTypes);
4754 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4755 // We are more strict than Microsoft and report CS0626 like error
4756 if (method.OptAttributes == null ||
4757 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4758 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",
4759 method.GetSignatureForError ());
4764 builder = container.TypeBuilder.DefineMethod (
4765 method_name, flags, method.CallingConventions,
4766 method.ReturnType, ParameterTypes);
4772 public void Emit (TypeContainer container, Attributable kind)
4775 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4776 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4778 ec = method.CreateEmitContext (container, null);
4780 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
4781 ec.TestObsoleteMethodUsage = false;
4783 Attributes OptAttributes = method.OptAttributes;
4785 if (OptAttributes != null)
4786 OptAttributes.Emit (ec, kind);
4788 if (member is MethodCore)
4789 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
4791 ToplevelBlock block = method.Block;
4793 SourceMethod source = SourceMethod.Create (
4794 container, MethodBuilder, method.Block);
4797 // Handle destructors specially
4799 // FIXME: This code generates buggy code
4801 if (member is Destructor)
4802 EmitDestructor (ec, block);
4804 ec.EmitTopBlock (method, block, ParameterInfo);
4807 source.CloseMethod ();
4810 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4812 ILGenerator ig = ec.ig;
4814 Label finish = ig.DefineLabel ();
4816 block.SetDestructor ();
4818 ig.BeginExceptionBlock ();
4819 ec.ReturnLabel = finish;
4820 ec.HasReturnLabel = true;
4821 ec.EmitTopBlock (method, block, null);
4823 // ig.MarkLabel (finish);
4824 ig.BeginFinallyBlock ();
4826 if (ec.ContainerType.BaseType != null) {
4827 Expression member_lookup = Expression.MemberLookup (
4828 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4829 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4831 if (member_lookup != null){
4832 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4834 ig.Emit (OpCodes.Ldarg_0);
4835 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4839 ig.EndExceptionBlock ();
4840 //ig.MarkLabel (ec.ReturnLabel);
4841 ig.Emit (OpCodes.Ret);
4845 // TODO: Should derive from MethodCore
4846 public class Destructor : Method {
4848 public Destructor (TypeContainer ds, Expression return_type, int mod,
4849 string name, Parameters parameters, Attributes attrs,
4851 : base (ds, return_type, mod, false, new MemberName (name),
4852 parameters, attrs, l)
4855 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4857 if (a.Type == TypeManager.conditional_attribute_type) {
4858 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4859 GetSignatureForError ());
4863 base.ApplyAttributeBuilder (a, cb);
4866 public override string GetSignatureForError ()
4868 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
4873 abstract public class MemberBase : MemberCore {
4874 public Expression Type;
4876 public MethodAttributes flags;
4878 protected readonly int explicit_mod_flags;
4881 // The "short" name of this property / indexer / event. This is the
4882 // name without the explicit interface.
4884 public string ShortName {
4885 get { return MemberName.Name; }
4887 SetMemberName (new MemberName (MemberName.Left, value));
4892 // The type of this property / indexer / event
4895 public Type MemberType {
4897 if (member_type == null && Type != null) {
4898 EmitContext ec = Parent.EmitContext;
4899 bool old_unsafe = ec.InUnsafe;
4900 ec.InUnsafe = InUnsafe;
4901 Type = Type.ResolveAsTypeTerminal (ec, false);
4902 ec.InUnsafe = old_unsafe;
4904 member_type = Type == null ? null : Type.Type;
4911 // Whether this is an interface member.
4913 public bool IsInterface;
4916 // If true, this is an explicit interface implementation
4918 public bool IsExplicitImpl;
4921 // The interface type we are explicitly implementing
4923 public Type InterfaceType = null;
4926 // The constructor is only exposed to our children
4928 protected MemberBase (TypeContainer parent, Expression type, int mod,
4929 int allowed_mod, int def_mod, MemberName name,
4930 Attributes attrs, Location loc)
4931 : base (parent, name, attrs, loc)
4933 explicit_mod_flags = mod;
4935 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4936 IsExplicitImpl = (MemberName.Left != null);
4939 protected virtual bool CheckBase ()
4941 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4942 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4946 if ((RootContext.WarningLevel >= 4) &&
4947 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4948 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4949 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4950 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4955 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4959 foreach (Type partype in parameters){
4960 if (partype == TypeManager.void_type) {
4962 1547, Location, "Keyword 'void' cannot " +
4963 "be used in this context");
4967 if (partype.IsPointer){
4970 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4974 if (ds.AsAccessible (partype, ModFlags))
4977 if (this is Indexer)
4978 Report.Error (55, Location,
4979 "Inconsistent accessibility: parameter type `" +
4980 TypeManager.CSharpName (partype) + "' is less " +
4981 "accessible than indexer `" + GetSignatureForError () + "'");
4982 else if ((this is Method) && ((Method) this).IsOperator != null)
4983 Report.Error (57, Location,
4984 "Inconsistent accessibility: parameter type `" +
4985 TypeManager.CSharpName (partype) + "' is less " +
4986 "accessible than operator `" + GetSignatureForError () + "'");
4988 Report.Error (51, Location,
4989 "Inconsistent accessibility: parameter type `" +
4990 TypeManager.CSharpName (partype) + "' is less " +
4991 "accessible than method `" + GetSignatureForError () + "'");
4998 protected virtual bool DoDefine ()
5000 EmitContext ec = Parent.EmitContext;
5002 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5005 throw new InternalErrorException ();
5008 ModFlags = Modifiers.PUBLIC |
5009 Modifiers.ABSTRACT |
5010 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5012 flags = MethodAttributes.Public |
5013 MethodAttributes.Abstract |
5014 MethodAttributes.HideBySig |
5015 MethodAttributes.NewSlot |
5016 MethodAttributes.Virtual;
5018 if (!Parent.MethodModifiersValid (this))
5021 flags = Modifiers.MethodAttr (ModFlags);
5024 if (MemberType == null)
5027 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5028 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5029 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5030 GetSignatureForError (), Parent.GetSignatureForError ());
5034 // verify accessibility
5035 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5036 Report.SymbolRelatedToPreviousError (MemberType);
5037 if (this is Property)
5038 Report.Error (53, Location,
5039 "Inconsistent accessibility: property type `" +
5040 TypeManager.CSharpName (MemberType) + "' is less " +
5041 "accessible than property `" + GetSignatureForError () + "'");
5042 else if (this is Indexer)
5043 Report.Error (54, Location,
5044 "Inconsistent accessibility: indexer return type `" +
5045 TypeManager.CSharpName (MemberType) + "' is less " +
5046 "accessible than indexer `" + GetSignatureForError () + "'");
5047 else if (this is MethodCore) {
5048 if (this is Operator)
5049 Report.Error (56, Location,
5050 "Inconsistent accessibility: return type `" +
5051 TypeManager.CSharpName (MemberType) + "' is less " +
5052 "accessible than operator `" + GetSignatureForError () + "'");
5054 Report.Error (50, Location,
5055 "Inconsistent accessibility: return type `" +
5056 TypeManager.CSharpName (MemberType) + "' is less " +
5057 "accessible than method `" + GetSignatureForError () + "'");
5059 Report.Error (52, Location,
5060 "Inconsistent accessibility: field type `" +
5061 TypeManager.CSharpName (MemberType) + "' is less " +
5062 "accessible than field `" + GetSignatureForError () + "'");
5067 if (MemberType.IsPointer && !UnsafeOK (Parent))
5070 if (IsExplicitImpl) {
5071 Expression expr = MemberName.Left.GetTypeExpression (Location);
5072 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5076 InterfaceType = texpr.ResolveType (ec);
5078 if (!InterfaceType.IsInterface) {
5079 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5083 if (!Parent.VerifyImplements (this))
5086 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5092 protected bool IsTypePermitted ()
5094 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5095 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5101 protected override bool VerifyClsCompliance(DeclSpace ds)
5103 if (base.VerifyClsCompliance (ds)) {
5107 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5108 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5113 protected override void VerifyObsoleteAttribute()
5115 CheckUsageOfObsoleteAttribute (MemberType);
5120 // Fields and Events both generate FieldBuilders, we use this to share
5121 // their common bits. This is also used to flag usage of the field
5123 abstract public class FieldBase : MemberBase {
5124 public FieldBuilder FieldBuilder;
5125 public Status status;
5128 public enum Status : byte {
5130 HAS_OFFSET = 4 // Used by FieldMember.
5133 static string[] attribute_targets = new string [] { "field" };
5136 /// Symbol with same name in base class/struct
5138 public MemberInfo conflict_symbol;
5141 // The constructor is only exposed to our children
5143 protected FieldBase (TypeContainer parent, Expression type, int mod,
5144 int allowed_mod, MemberName name, object init,
5145 Attributes attrs, Location loc)
5146 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5152 public override AttributeTargets AttributeTargets {
5154 return AttributeTargets.Field;
5158 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5160 if (a.Type == TypeManager.marshal_as_attr_type) {
5161 UnmanagedMarshal marshal = a.GetMarshal (this);
5162 if (marshal != null) {
5163 FieldBuilder.SetMarshal (marshal);
5168 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5169 a.Error_InvalidSecurityParent ();
5173 FieldBuilder.SetCustomAttribute (cb);
5177 // Whether this field has an initializer.
5179 public bool HasInitializer {
5181 return init != null;
5185 protected readonly Object init;
5188 Expression init_expr;
5189 bool init_expr_initialized = false;
5192 // Resolves and returns the field initializer.
5194 public Expression GetInitializerExpression (EmitContext ec)
5196 if (init_expr_initialized)
5200 if (init is Expression)
5201 e = (Expression) init;
5203 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5205 // TODO: Any reason why we are using parent EC ?
5206 EmitContext parent_ec = Parent.EmitContext;
5208 bool old_is_static = parent_ec.IsStatic;
5209 bool old_is_ctor = parent_ec.IsConstructor;
5210 parent_ec.IsStatic = ec.IsStatic;
5211 parent_ec.IsConstructor = ec.IsConstructor;
5212 parent_ec.IsFieldInitializer = true;
5213 e = e.DoResolve (parent_ec);
5214 parent_ec.IsFieldInitializer = false;
5215 parent_ec.IsStatic = old_is_static;
5216 parent_ec.IsConstructor = old_is_ctor;
5219 init_expr_initialized = true;
5224 protected override bool CheckBase ()
5226 if (!base.CheckBase ())
5233 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5234 if (conflict_symbol == null) {
5235 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5236 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5241 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5242 Report.SymbolRelatedToPreviousError (conflict_symbol);
5243 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5244 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5250 protected virtual bool IsFieldClsCompliant {
5252 if (FieldBuilder == null)
5255 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5259 public override string[] ValidAttributeTargets {
5261 return attribute_targets;
5265 protected override bool VerifyClsCompliance (DeclSpace ds)
5267 if (!base.VerifyClsCompliance (ds))
5270 if (!IsFieldClsCompliant) {
5271 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5277 public void SetAssigned ()
5279 status |= Status.ASSIGNED;
5283 public abstract class FieldMember: FieldBase
5285 protected FieldMember (TypeContainer parent, Expression type, int mod,
5286 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5287 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5289 if ((mod & Modifiers.ABSTRACT) != 0)
5290 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5293 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5295 if (a.Type == TypeManager.field_offset_attribute_type)
5297 status |= Status.HAS_OFFSET;
5299 if (!Parent.HasExplicitLayout) {
5300 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5304 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5305 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5311 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5312 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5317 base.ApplyAttributeBuilder (a, cb);
5321 public override bool Define()
5323 EmitContext ec = Parent.EmitContext;
5325 throw new InternalErrorException ("FieldMember.Define called too early");
5327 if (MemberType == null)
5330 if (MemberType == TypeManager.void_type) {
5331 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5338 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5339 Report.Error (52, Location,
5340 "Inconsistent accessibility: field type `" +
5341 TypeManager.CSharpName (MemberType) + "' is less " +
5342 "accessible than field `" + GetSignatureForError () + "'");
5346 if (!IsTypePermitted ())
5349 if (MemberType.IsPointer && !UnsafeOK (Parent))
5355 public override void Emit ()
5357 if (OptAttributes != null) {
5358 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5359 OptAttributes.Emit (ec, this);
5362 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5363 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5370 // Represents header string for documentation comment.
5372 public override string DocCommentHeader {
5373 get { return "F:"; }
5377 interface IFixedBuffer
5379 FieldInfo Element { get; }
5380 Type ElementType { get; }
5383 public class FixedFieldExternal: IFixedBuffer
5385 FieldInfo element_field;
5387 public FixedFieldExternal (FieldInfo fi)
5389 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5392 #region IFixedField Members
5394 public FieldInfo Element {
5396 return element_field;
5400 public Type ElementType {
5402 return element_field.FieldType;
5410 /// Fixed buffer implementation
5412 public class FixedField: FieldMember, IFixedBuffer
5414 public const string FixedElementName = "FixedElementField";
5415 static int GlobalCounter = 0;
5416 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5417 static FieldInfo[] fi;
5419 TypeBuilder fixed_buffer_type;
5420 FieldBuilder element;
5421 Expression size_expr;
5424 const int AllowedModifiers =
5427 Modifiers.PROTECTED |
5428 Modifiers.INTERNAL |
5431 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5432 Expression size_expr, Attributes attrs, Location loc):
5433 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5435 if (RootContext.Version == LanguageVersion.ISO_1)
5436 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5438 this.size_expr = size_expr;
5441 public override bool Define()
5444 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5445 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5448 if (Parent.Kind != Kind.Struct) {
5449 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5450 GetSignatureForError ());
5454 if (!base.Define ())
5457 if (!TypeManager.IsPrimitiveType (MemberType)) {
5458 Report.Error (1663, Location, "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
5459 GetSignatureForError ());
5463 Expression e = size_expr.Resolve (Parent.EmitContext);
5467 Constant c = e as Constant;
5469 Report.Error (133, Location, "The expression being assigned to `{0}' must be constant", GetSignatureForError ());
5473 IntConstant buffer_size_const = c.ToInt (Location);
5474 if (buffer_size_const == null)
5477 buffer_size = buffer_size_const.Value;
5479 if (buffer_size <= 0) {
5480 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5484 int type_size = Expression.GetTypeSize (MemberType);
5486 if (buffer_size > int.MaxValue / type_size) {
5487 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5488 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5492 buffer_size *= type_size;
5495 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5497 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5498 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5499 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5500 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5502 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5503 TypeManager.RegisterFieldBase (FieldBuilder, this);
5508 public override void Emit()
5511 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5513 object[] fi_val = new object[1];
5514 fi_val [0] = buffer_size;
5516 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5517 ctor_args, fi, fi_val);
5518 fixed_buffer_type.SetCustomAttribute (cab);
5521 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5522 FieldBuilder.SetCustomAttribute (cab);
5527 protected override bool IsFieldClsCompliant {
5533 #region IFixedField Members
5535 public FieldInfo Element {
5541 public Type ElementType {
5551 // The Field class is used to represents class/struct fields during parsing.
5553 public class Field : FieldMember {
5555 // Modifiers allowed in a class declaration
5557 const int AllowedModifiers =
5560 Modifiers.PROTECTED |
5561 Modifiers.INTERNAL |
5564 Modifiers.VOLATILE |
5568 public Field (TypeContainer parent, Expression type, int mod, string name,
5569 Object expr_or_array_init, Attributes attrs, Location loc)
5570 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5571 expr_or_array_init, attrs, loc)
5575 public override bool Define ()
5577 if (!base.Define ())
5580 if (RootContext.WarningLevel > 1){
5581 Type ptype = Parent.TypeBuilder.BaseType;
5583 // ptype is only null for System.Object while compiling corlib.
5585 TypeContainer.FindMembers (
5586 ptype, MemberTypes.Method,
5587 BindingFlags.Public |
5588 BindingFlags.Static | BindingFlags.Instance,
5589 System.Type.FilterName, Name);
5593 if ((ModFlags & Modifiers.VOLATILE) != 0){
5594 if (!MemberType.IsClass){
5595 Type vt = MemberType;
5597 if (TypeManager.IsEnumType (vt))
5598 vt = TypeManager.EnumToUnderlying (MemberType);
5600 if (!((vt == TypeManager.bool_type) ||
5601 (vt == TypeManager.sbyte_type) ||
5602 (vt == TypeManager.byte_type) ||
5603 (vt == TypeManager.short_type) ||
5604 (vt == TypeManager.ushort_type) ||
5605 (vt == TypeManager.int32_type) ||
5606 (vt == TypeManager.uint32_type) ||
5607 (vt == TypeManager.char_type) ||
5608 (vt == TypeManager.float_type) ||
5609 (!vt.IsValueType))){
5610 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5611 GetSignatureForError (), TypeManager.CSharpName (vt));
5616 if ((ModFlags & Modifiers.READONLY) != 0){
5617 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5618 GetSignatureForError ());
5623 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5625 if (Parent.Kind == Kind.Struct &&
5626 ((fa & FieldAttributes.Static) == 0) &&
5627 MemberType == Parent.TypeBuilder &&
5628 !TypeManager.IsBuiltinType (MemberType)){
5629 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5630 "' causes a cycle in the structure layout");
5635 FieldBuilder = Parent.TypeBuilder.DefineField (
5636 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5638 TypeManager.RegisterFieldBase (FieldBuilder, this);
5640 catch (ArgumentException) {
5641 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5648 protected override bool VerifyClsCompliance (DeclSpace ds)
5650 if (!base.VerifyClsCompliance (ds))
5653 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5654 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5662 // `set' and `get' accessors are represented with an Accessor.
5664 public class Accessor {
5666 // Null if the accessor is empty, or a Block if not
5668 public const int AllowedModifiers =
5670 Modifiers.PROTECTED |
5671 Modifiers.INTERNAL |
5674 public ToplevelBlock Block;
5675 public Attributes Attributes;
5676 public Location Location;
5677 public int ModFlags;
5679 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5684 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5689 // Ooouh Martin, templates are missing here.
5690 // When it will be possible move here a lot of child code and template method type.
5691 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5692 protected MethodData method_data;
5693 protected ToplevelBlock block;
5694 protected ListDictionary declarative_security;
5696 // The accessor are created event if they are not wanted.
5697 // But we need them because their names are reserved.
5698 // Field says whether accessor will be emited or not
5699 public readonly bool IsDummy;
5701 protected readonly string prefix;
5703 ReturnParameter return_attributes;
5705 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5706 : base (null, SetupName (prefix, member), null, member.Location)
5708 this.prefix = prefix;
5712 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5714 : base (null, SetupName (prefix, member),
5715 accessor.Attributes, accessor.Location)
5717 this.prefix = prefix;
5718 this.block = accessor.Block;
5721 static MemberName SetupName (string prefix, MemberBase member)
5723 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
5726 public void UpdateName (MemberBase member)
5728 SetMemberName (SetupName (prefix, member));
5731 #region IMethodData Members
5733 public ToplevelBlock Block {
5743 public CallingConventions CallingConventions {
5745 return CallingConventions.Standard;
5749 public bool IsExcluded (EmitContext ec)
5754 public MemberName MethodName {
5760 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5761 public abstract Type[] ParameterTypes { get; }
5762 public abstract Type ReturnType { get; }
5763 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5767 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5769 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5770 a.Type == TypeManager.conditional_attribute_type) {
5771 Report.Error (1667, a.Location,
5772 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5773 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5777 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5778 if (declarative_security == null)
5779 declarative_security = new ListDictionary ();
5780 a.ExtractSecurityPermissionSet (declarative_security);
5784 if (a.Target == AttributeTargets.Method) {
5785 method_data.MethodBuilder.SetCustomAttribute (cb);
5789 if (a.Target == AttributeTargets.ReturnValue) {
5790 if (return_attributes == null)
5791 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5793 return_attributes.ApplyAttributeBuilder (a, cb);
5797 ApplyToExtraTarget (a, cb);
5800 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5802 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5805 public override bool Define()
5807 throw new NotSupportedException ();
5810 public virtual void Emit (TypeContainer container)
5812 EmitMethod (container);
5814 if (declarative_security != null) {
5815 foreach (DictionaryEntry de in declarative_security) {
5816 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5823 protected virtual void EmitMethod (TypeContainer container)
5825 method_data.Emit (container, this);
5828 public override bool IsClsCompliaceRequired(DeclSpace ds)
5833 public bool IsDuplicateImplementation (MethodCore method)
5835 if (Name != method.Name)
5838 Type[] param_types = method.ParameterTypes;
5840 if (param_types.Length != ParameterTypes.Length)
5843 for (int i = 0; i < param_types.Length; i++)
5844 if (param_types [i] != ParameterTypes [i])
5847 Report.SymbolRelatedToPreviousError (method);
5848 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
5852 public override bool IsUsed
5862 public new Location Location {
5864 return base.Location;
5869 // Represents header string for documentation comment.
5871 public override string DocCommentHeader {
5872 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5875 protected override void VerifyObsoleteAttribute()
5882 // Properties and Indexers both generate PropertyBuilders, we use this to share
5883 // their common bits.
5885 abstract public class PropertyBase : MethodCore {
5887 public class GetMethod: PropertyMethod
5889 static string[] attribute_targets = new string [] { "method", "return" };
5891 public GetMethod (MethodCore method):
5892 base (method, "get_")
5896 public GetMethod (MethodCore method, Accessor accessor):
5897 base (method, accessor, "get_")
5901 public override MethodBuilder Define(TypeContainer container)
5903 base.Define (container);
5905 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5907 if (!method_data.Define (container))
5910 return method_data.MethodBuilder;
5913 public override Type ReturnType {
5915 return method.MemberType;
5919 public override string[] ValidAttributeTargets {
5921 return attribute_targets;
5926 public class SetMethod: PropertyMethod {
5928 static string[] attribute_targets = new string [] { "method", "param", "return" };
5929 ImplicitParameter param_attr;
5931 public SetMethod (MethodCore method):
5932 base (method, "set_")
5936 public SetMethod (MethodCore method, Accessor accessor):
5937 base (method, accessor, "set_")
5941 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5943 if (a.Target == AttributeTargets.Parameter) {
5944 if (param_attr == null)
5945 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
5947 param_attr.ApplyAttributeBuilder (a, cb);
5951 base.ApplyAttributeBuilder (a, cb);
5954 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5956 Parameter [] parms = new Parameter [1];
5957 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
5958 Parameters parameters = new Parameters (parms, null);
5960 bool old_unsafe = ec.InUnsafe;
5961 ec.InUnsafe = InUnsafe;
5962 Type [] types = parameters.GetParameterInfo (ec);
5963 ec.InUnsafe = old_unsafe;
5965 return new InternalParameters (types, parameters);
5968 public override MethodBuilder Define (TypeContainer container)
5970 if (container.EmitContext == null)
5971 throw new InternalErrorException ("SetMethod.Define called too early");
5973 base.Define (container);
5975 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5977 if (!method_data.Define (container))
5980 return method_data.MethodBuilder;
5983 public override Type[] ParameterTypes {
5985 return new Type[] { method.MemberType };
5989 public override Type ReturnType {
5991 return TypeManager.void_type;
5995 public override string[] ValidAttributeTargets {
5997 return attribute_targets;
6002 static string[] attribute_targets = new string [] { "property" };
6004 public abstract class PropertyMethod: AbstractPropertyEventMethod
6006 protected readonly MethodCore method;
6007 protected MethodAttributes flags;
6009 public PropertyMethod (MethodCore method, string prefix)
6010 : base (method, prefix)
6012 this.method = method;
6013 Parent = method.Parent;
6016 public PropertyMethod (MethodCore method, Accessor accessor,
6018 : base (method, accessor, prefix)
6020 this.method = method;
6021 Parent = method.Parent;
6022 this.ModFlags = accessor.ModFlags;
6024 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6025 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6029 public override AttributeTargets AttributeTargets {
6031 return AttributeTargets.Method;
6035 public override bool IsClsCompliaceRequired(DeclSpace ds)
6037 return method.IsClsCompliaceRequired (ds);
6040 public InternalParameters ParameterInfo
6043 return method_data.ParameterInfo;
6047 public virtual MethodBuilder Define (TypeContainer container)
6049 if (!method.CheckAbstractAndExtern (block != null))
6053 // Check for custom access modifier
6055 if (ModFlags == 0) {
6056 ModFlags = method.ModFlags;
6057 flags = method.flags;
6059 if (container.Kind == Kind.Interface)
6060 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6061 GetSignatureForError ());
6063 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6064 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6067 CheckModifiers (container, ModFlags);
6068 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6069 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6070 flags = Modifiers.MethodAttr (ModFlags);
6071 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6075 // Setup iterator if we are one
6077 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6078 Iterator iterator = new Iterator (this,
6079 Parent, method.ParameterInfo, ModFlags);
6081 if (!iterator.DefineIterator ())
6088 public bool HasCustomAccessModifier
6091 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6095 public override Type[] ParameterTypes {
6097 return TypeManager.NoTypes;
6101 public override EmitContext CreateEmitContext (TypeContainer tc,
6104 return new EmitContext (
6105 tc, method.Parent, method.Location, ig, ReturnType,
6106 method.ModFlags, false);
6109 public override ObsoleteAttribute GetObsoleteAttribute ()
6111 return method.GetObsoleteAttribute (method.Parent);
6114 public override string GetSignatureForError()
6116 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6119 void CheckModifiers (TypeContainer container, int modflags)
6122 int mflags = method.ModFlags & Modifiers.Accessibility;
6124 if ((mflags & Modifiers.PUBLIC) != 0) {
6125 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6127 else if ((mflags & Modifiers.PROTECTED) != 0) {
6128 if ((mflags & Modifiers.INTERNAL) != 0)
6129 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6131 flags |= Modifiers.PRIVATE;
6133 else if ((mflags & Modifiers.INTERNAL) != 0)
6134 flags |= Modifiers.PRIVATE;
6136 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6137 Report.Error (273, Location,
6138 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6139 GetSignatureForError (), method.GetSignatureForError ());
6143 public override bool MarkForDuplicationCheck ()
6145 caching_flags |= Flags.TestMethodDuplication;
6151 public PropertyMethod Get, Set;
6152 public PropertyBuilder PropertyBuilder;
6153 public MethodBuilder GetBuilder, SetBuilder;
6155 protected EmitContext ec;
6157 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6158 int allowed_mod, bool is_iface, MemberName name,
6159 Parameters parameters, Attributes attrs,
6161 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6162 attrs, parameters, loc)
6166 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6168 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6169 a.Error_InvalidSecurityParent ();
6173 PropertyBuilder.SetCustomAttribute (cb);
6176 public override AttributeTargets AttributeTargets {
6178 return AttributeTargets.Property;
6182 public override bool Define ()
6187 if (!IsTypePermitted ())
6193 protected override bool DoDefine ()
6195 if (!base.DoDefine ())
6199 // Accessors modifiers check
6201 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6202 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6203 GetSignatureForError ());
6207 if ((Get.IsDummy || Set.IsDummy)
6208 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6209 Report.Error (276, Location,
6210 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6211 GetSignatureForError ());
6215 if (MemberType.IsAbstract && MemberType.IsSealed) {
6216 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6220 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6224 protected override bool CheckForDuplications ()
6226 ArrayList ar = Parent.Indexers;
6228 int arLen = ar.Count;
6230 for (int i = 0; i < arLen; i++) {
6231 Indexer m = (Indexer) ar [i];
6232 if (IsDuplicateImplementation (m))
6237 ar = Parent.Properties;
6239 int arLen = ar.Count;
6241 for (int i = 0; i < arLen; i++) {
6242 Property m = (Property) ar [i];
6243 if (IsDuplicateImplementation (m))
6251 // TODO: rename to Resolve......
6252 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6254 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6255 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6257 if (base_property == null)
6260 base_ret_type = base_property.PropertyType;
6261 MethodInfo get_accessor = base_property.GetGetMethod (true);
6262 MethodInfo set_accessor = base_property.GetSetMethod (true);
6263 MethodAttributes get_accessor_access, set_accessor_access;
6265 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6266 if (Get != null && !Get.IsDummy && get_accessor == null) {
6267 Report.SymbolRelatedToPreviousError (base_property);
6268 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6271 if (Set != null && !Set.IsDummy && set_accessor == null) {
6272 Report.SymbolRelatedToPreviousError (base_property);
6273 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6278 // Check base class accessors access
6281 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6282 get_accessor_access = set_accessor_access = 0;
6283 if ((ModFlags & Modifiers.NEW) == 0) {
6284 if (get_accessor != null) {
6285 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6286 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6288 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6289 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6292 if (set_accessor != null) {
6293 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6294 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6296 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6297 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6302 // Get the less restrictive access
6304 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6307 public override void Emit ()
6310 // The PropertyBuilder can be null for explicit implementations, in that
6311 // case, we do not actually emit the ".property", so there is nowhere to
6312 // put the attribute
6314 if (PropertyBuilder != null && OptAttributes != null)
6315 OptAttributes.Emit (ec, this);
6327 /// Tests whether accessors are not in collision with some method (CS0111)
6329 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6331 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6334 public override bool IsUsed
6340 return Get.IsUsed | Set.IsUsed;
6344 protected override void SetMemberName (MemberName new_name)
6346 base.SetMemberName (new_name);
6348 Get.UpdateName (this);
6349 Set.UpdateName (this);
6352 public override string[] ValidAttributeTargets {
6354 return attribute_targets;
6359 // Represents header string for documentation comment.
6361 public override string DocCommentHeader {
6362 get { return "P:"; }
6366 public class Property : PropertyBase, IIteratorContainer {
6367 const int AllowedModifiers =
6370 Modifiers.PROTECTED |
6371 Modifiers.INTERNAL |
6375 Modifiers.OVERRIDE |
6376 Modifiers.ABSTRACT |
6379 Modifiers.METHOD_YIELDS |
6382 const int AllowedInterfaceModifiers =
6385 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6386 MemberName name, Attributes attrs, Accessor get_block,
6387 Accessor set_block, Location loc)
6388 : base (ds, type, mod,
6389 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6390 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6393 if (get_block == null)
6394 Get = new GetMethod (this);
6396 Get = new GetMethod (this, get_block);
6398 if (set_block == null)
6399 Set = new SetMethod (this);
6401 Set = new SetMethod (this, set_block);
6404 public override bool Define ()
6406 if (!base.Define ())
6412 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6415 GetBuilder = Get.Define (Parent);
6416 if (GetBuilder == null)
6421 SetBuilder = Set.Define (Parent);
6422 if (SetBuilder == null)
6425 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6428 // FIXME - PropertyAttributes.HasDefault ?
6430 PropertyAttributes prop_attr = PropertyAttributes.None;
6432 prop_attr |= PropertyAttributes.RTSpecialName |
6433 PropertyAttributes.SpecialName;
6435 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6436 Name, prop_attr, MemberType, null);
6439 PropertyBuilder.SetGetMethod (GetBuilder);
6442 PropertyBuilder.SetSetMethod (SetBuilder);
6444 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6450 /// Gigantic workaround for lameness in SRE follows :
6451 /// This class derives from EventInfo and attempts to basically
6452 /// wrap around the EventBuilder so that FindMembers can quickly
6453 /// return this in it search for members
6455 public class MyEventBuilder : EventInfo {
6458 // We use this to "point" to our Builder which is
6459 // not really a MemberInfo
6461 EventBuilder MyBuilder;
6464 // We "catch" and wrap these methods
6466 MethodInfo raise, remove, add;
6468 EventAttributes attributes;
6469 Type declaring_type, reflected_type, event_type;
6474 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6476 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6478 // And now store the values in our own fields.
6480 declaring_type = type_builder;
6482 reflected_type = type_builder;
6484 attributes = event_attr;
6487 this.event_type = event_type;
6491 // Methods that you have to override. Note that you only need
6492 // to "implement" the variants that take the argument (those are
6493 // the "abstract" methods, the others (GetAddMethod()) are
6496 public override MethodInfo GetAddMethod (bool nonPublic)
6501 public override MethodInfo GetRemoveMethod (bool nonPublic)
6506 public override MethodInfo GetRaiseMethod (bool nonPublic)
6512 // These methods make "MyEventInfo" look like a Builder
6514 public void SetRaiseMethod (MethodBuilder raiseMethod)
6516 raise = raiseMethod;
6517 MyBuilder.SetRaiseMethod (raiseMethod);
6520 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6522 remove = removeMethod;
6523 MyBuilder.SetRemoveOnMethod (removeMethod);
6526 public void SetAddOnMethod (MethodBuilder addMethod)
6529 MyBuilder.SetAddOnMethod (addMethod);
6532 public void SetCustomAttribute (CustomAttributeBuilder cb)
6534 MyBuilder.SetCustomAttribute (cb);
6537 public override object [] GetCustomAttributes (bool inherit)
6539 // FIXME : There's nothing which can be seemingly done here because
6540 // we have no way of getting at the custom attribute objects of the
6545 public override object [] GetCustomAttributes (Type t, bool inherit)
6547 // FIXME : Same here !
6551 public override bool IsDefined (Type t, bool b)
6556 public override EventAttributes Attributes {
6562 public override string Name {
6568 public override Type DeclaringType {
6570 return declaring_type;
6574 public override Type ReflectedType {
6576 return reflected_type;
6580 public Type EventType {
6586 public void SetUsed ()
6588 if (my_event != null) {
6589 my_event.status = FieldBase.Status.ASSIGNED;
6590 my_event.SetMemberIsUsed ();
6596 /// For case when event is declared like property (with add and remove accessors).
6598 public class EventProperty: Event {
6600 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6602 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6603 bool is_iface, MemberName name, Object init,
6604 Attributes attrs, Accessor add, Accessor remove,
6606 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6608 Add = new AddDelegateMethod (this, add);
6609 Remove = new RemoveDelegateMethod (this, remove);
6611 // For this event syntax we don't report error CS0067
6612 // because it is hard to do it.
6616 public override string[] ValidAttributeTargets {
6618 return attribute_targets;
6624 /// Event is declared like field.
6626 public class EventField: Event {
6628 static string[] attribute_targets = new string [] { "event", "field", "method" };
6629 static string[] attribute_targets_interface = new string[] { "event", "method" };
6631 public EventField (TypeContainer parent, Expression type, int mod_flags,
6632 bool is_iface, MemberName name, Object init,
6633 Attributes attrs, Location loc)
6634 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6636 Add = new AddDelegateMethod (this);
6637 Remove = new RemoveDelegateMethod (this);
6640 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6642 if (a.Target == AttributeTargets.Field) {
6643 FieldBuilder.SetCustomAttribute (cb);
6647 if (a.Target == AttributeTargets.Method) {
6648 Add.ApplyAttributeBuilder (a, cb);
6649 Remove.ApplyAttributeBuilder (a, cb);
6653 base.ApplyAttributeBuilder (a, cb);
6656 public override string[] ValidAttributeTargets {
6658 return IsInterface ? attribute_targets_interface : attribute_targets;
6663 public abstract class Event : FieldBase {
6665 protected sealed class AddDelegateMethod: DelegateMethod
6668 public AddDelegateMethod (Event method):
6669 base (method, "add_")
6673 public AddDelegateMethod (Event method, Accessor accessor):
6674 base (method, accessor, "add_")
6678 protected override MethodInfo DelegateMethodInfo {
6680 return TypeManager.delegate_combine_delegate_delegate;
6686 protected sealed class RemoveDelegateMethod: DelegateMethod
6688 public RemoveDelegateMethod (Event method):
6689 base (method, "remove_")
6693 public RemoveDelegateMethod (Event method, Accessor accessor):
6694 base (method, accessor, "remove_")
6698 protected override MethodInfo DelegateMethodInfo {
6700 return TypeManager.delegate_remove_delegate_delegate;
6706 public abstract class DelegateMethod: AbstractPropertyEventMethod
6708 protected readonly Event method;
6709 ImplicitParameter param_attr;
6711 static string[] attribute_targets = new string [] { "method", "param", "return" };
6713 public DelegateMethod (Event method, string prefix)
6714 : base (method, prefix)
6716 this.method = method;
6719 public DelegateMethod (Event method, Accessor accessor, string prefix)
6720 : base (method, accessor, prefix)
6722 this.method = method;
6725 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6727 if (a.Target == AttributeTargets.Parameter) {
6728 if (param_attr == null)
6729 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6731 param_attr.ApplyAttributeBuilder (a, cb);
6735 base.ApplyAttributeBuilder (a, cb);
6738 public override AttributeTargets AttributeTargets {
6740 return AttributeTargets.Method;
6744 public override bool IsClsCompliaceRequired(DeclSpace ds)
6746 return method.IsClsCompliaceRequired (ds);
6749 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6751 method_data = new MethodData (method, ip, method.ModFlags,
6752 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6754 if (!method_data.Define (container))
6757 MethodBuilder mb = method_data.MethodBuilder;
6758 mb.DefineParameter (1, ParameterAttributes.None, "value");
6763 protected override void EmitMethod (TypeContainer tc)
6765 if (block != null) {
6766 base.EmitMethod (tc);
6770 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6773 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6774 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6776 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6777 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6778 ig.Emit (OpCodes.Ldsfld, field_info);
6779 ig.Emit (OpCodes.Ldarg_0);
6780 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6781 ig.Emit (OpCodes.Castclass, method.MemberType);
6782 ig.Emit (OpCodes.Stsfld, field_info);
6784 ig.Emit (OpCodes.Ldarg_0);
6785 ig.Emit (OpCodes.Ldarg_0);
6786 ig.Emit (OpCodes.Ldfld, field_info);
6787 ig.Emit (OpCodes.Ldarg_1);
6788 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6789 ig.Emit (OpCodes.Castclass, method.MemberType);
6790 ig.Emit (OpCodes.Stfld, field_info);
6792 ig.Emit (OpCodes.Ret);
6795 protected abstract MethodInfo DelegateMethodInfo { get; }
6797 public override Type[] ParameterTypes {
6799 return new Type[] { method.MemberType };
6803 public override Type ReturnType {
6805 return TypeManager.void_type;
6809 public override EmitContext CreateEmitContext (TypeContainer tc,
6812 return new EmitContext (
6813 tc, method.Parent, Location, ig, ReturnType,
6814 method.ModFlags, false);
6817 public override ObsoleteAttribute GetObsoleteAttribute ()
6819 return method.GetObsoleteAttribute (method.Parent);
6822 public override string[] ValidAttributeTargets {
6824 return attribute_targets;
6830 const int AllowedModifiers =
6833 Modifiers.PROTECTED |
6834 Modifiers.INTERNAL |
6839 Modifiers.OVERRIDE |
6843 const int AllowedInterfaceModifiers =
6846 public DelegateMethod Add, Remove;
6847 public MyEventBuilder EventBuilder;
6848 public MethodBuilder AddBuilder, RemoveBuilder;
6850 public Event (TypeContainer parent, Expression type, int mod_flags,
6851 bool is_iface, MemberName name, Object init, Attributes attrs,
6853 : base (parent, type, mod_flags,
6854 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6855 name, init, attrs, loc)
6857 IsInterface = is_iface;
6860 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6862 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6863 a.Error_InvalidSecurityParent ();
6867 EventBuilder.SetCustomAttribute (cb);
6870 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6872 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6875 public override AttributeTargets AttributeTargets {
6877 return AttributeTargets.Event;
6881 public override bool Define ()
6883 EventAttributes e_attr;
6884 e_attr = EventAttributes.None;
6889 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6890 Report.Error (74, Location, "`" + GetSignatureForError () +
6891 "': abstract event cannot have an initializer");
6895 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6896 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
6900 EmitContext ec = Parent.EmitContext;
6902 throw new InternalErrorException ("Event.Define called too early?");
6903 bool old_unsafe = ec.InUnsafe;
6904 ec.InUnsafe = InUnsafe;
6906 Parameter [] parms = new Parameter [1];
6907 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
6908 Parameters parameters = new Parameters (parms, null);
6909 Type [] types = parameters.GetParameterInfo (ec);
6910 InternalParameters ip = new InternalParameters (types, parameters);
6912 ec.InUnsafe = old_unsafe;
6918 // Now define the accessors
6921 AddBuilder = Add.Define (Parent, ip);
6922 if (AddBuilder == null)
6925 RemoveBuilder = Remove.Define (Parent, ip);
6926 if (RemoveBuilder == null)
6929 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6931 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6932 FieldBuilder = Parent.TypeBuilder.DefineField (
6934 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6935 TypeManager.RegisterPrivateFieldOfEvent (
6936 (EventInfo) EventBuilder, FieldBuilder);
6937 TypeManager.RegisterFieldBase (FieldBuilder, this);
6940 EventBuilder.SetAddOnMethod (AddBuilder);
6941 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6943 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6947 protected override bool CheckBase ()
6949 if (!base.CheckBase ())
6952 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6953 if (!(conflict_symbol is EventInfo)) {
6954 Report.SymbolRelatedToPreviousError (conflict_symbol);
6955 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
6963 public override void Emit ()
6965 if (OptAttributes != null) {
6966 EmitContext ec = new EmitContext (
6967 Parent, Location, null, MemberType, ModFlags);
6968 OptAttributes.Emit (ec, this);
6972 Remove.Emit (Parent);
6977 public override string GetSignatureForError ()
6979 return base.GetSignatureForError ();
6983 // Represents header string for documentation comment.
6985 public override string DocCommentHeader {
6986 get { return "E:"; }
6991 public class Indexer : PropertyBase {
6993 class GetIndexerMethod: GetMethod
6995 public GetIndexerMethod (MethodCore method):
7000 public GetIndexerMethod (MethodCore method, Accessor accessor):
7001 base (method, accessor)
7005 public override Type[] ParameterTypes {
7007 return method.ParameterTypes;
7012 class SetIndexerMethod: SetMethod
7014 readonly Parameters parameters;
7016 public SetIndexerMethod (MethodCore method):
7021 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7022 base (method, accessor)
7024 this.parameters = parameters;
7027 public override Type[] ParameterTypes {
7029 int top = method.ParameterTypes.Length;
7030 Type [] set_pars = new Type [top + 1];
7031 method.ParameterTypes.CopyTo (set_pars, 0);
7032 set_pars [top] = method.MemberType;
7037 protected override InternalParameters GetParameterInfo (EmitContext ec)
7039 Parameter [] fixed_parms = parameters.FixedParameters;
7041 if (fixed_parms == null){
7042 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7043 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7044 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7046 // Here is the problem: the `value' parameter has
7047 // to come *after* the array parameter in the declaration
7049 // X (object [] x, Type value)
7052 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7053 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7057 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7059 fixed_parms.CopyTo (tmp, 0);
7060 tmp [fixed_parms.Length] = new Parameter (
7061 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7063 Parameters set_formal_params = new Parameters (tmp, null);
7064 Type [] types = set_formal_params.GetParameterInfo (ec);
7066 return new InternalParameters (types, set_formal_params);
7071 const int AllowedModifiers =
7074 Modifiers.PROTECTED |
7075 Modifiers.INTERNAL |
7079 Modifiers.OVERRIDE |
7084 const int AllowedInterfaceModifiers =
7088 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7089 bool is_iface, Parameters parameters, Attributes attrs,
7090 Accessor get_block, Accessor set_block, Location loc)
7091 : base (ds, type, mod,
7092 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7093 is_iface, name, parameters, attrs, loc)
7095 if (get_block == null)
7096 Get = new GetIndexerMethod (this);
7098 Get = new GetIndexerMethod (this, get_block);
7100 if (set_block == null)
7101 Set = new SetIndexerMethod (this);
7103 Set = new SetIndexerMethod (this, parameters, set_block);
7106 public override bool Define ()
7108 PropertyAttributes prop_attr =
7109 PropertyAttributes.RTSpecialName |
7110 PropertyAttributes.SpecialName;
7112 if (!base.Define ())
7115 if (MemberType == TypeManager.void_type) {
7116 Report.Error (620, Location, "Indexers cannot have void type");
7120 if (OptAttributes != null) {
7121 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7122 if (indexer_attr != null) {
7123 // Remove the attribute from the list because it is not emitted
7124 OptAttributes.Attrs.Remove (indexer_attr);
7126 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7128 if (IsExplicitImpl) {
7129 Report.Error (415, indexer_attr.Location,
7130 "The `IndexerName' attribute is valid only on an " +
7131 "indexer that is not an explicit interface member declaration");
7135 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7136 Report.Error (609, indexer_attr.Location,
7137 "Cannot set the `IndexerName' attribute on an indexer marked override");
7141 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7142 Report.Error (633, indexer_attr.Location,
7143 "The argument to the `IndexerName' attribute must be a valid identifier");
7149 if (InterfaceType != null) {
7150 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7151 if (base_IndexerName != Name)
7152 ShortName = base_IndexerName;
7155 if (!Parent.AddToMemberContainer (this) ||
7156 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7162 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7164 GetBuilder = Get.Define (Parent);
7165 if (GetBuilder == null)
7170 SetBuilder = Set.Define (Parent);
7171 if (SetBuilder == null)
7176 // Now name the parameters
7178 Parameter [] p = Parameters.FixedParameters;
7180 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7181 Report.Error (631, Location, "ref and out are not valid in this context");
7187 for (i = 0; i < p.Length; ++i) {
7189 GetBuilder.DefineParameter (
7190 i + 1, p [i].Attributes, p [i].Name);
7193 SetBuilder.DefineParameter (
7194 i + 1, p [i].Attributes, p [i].Name);
7198 SetBuilder.DefineParameter (
7199 i + 1, ParameterAttributes.None, "value");
7201 if (i != ParameterTypes.Length) {
7202 Parameter array_param = Parameters.ArrayParameter;
7204 SetBuilder.DefineParameter (
7205 i + 1, array_param.Attributes, array_param.Name);
7209 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7210 Name, prop_attr, MemberType, ParameterTypes);
7213 PropertyBuilder.SetGetMethod (GetBuilder);
7216 PropertyBuilder.SetSetMethod (SetBuilder);
7218 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7223 public override string GetSignatureForError ()
7225 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7226 if (MemberName.Left != null) {
7228 sb.Append (MemberName.Left);
7231 sb.Append (".this");
7232 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7233 return sb.ToString ();
7236 public override bool MarkForDuplicationCheck ()
7238 caching_flags |= Flags.TestMethodDuplication;
7244 public class Operator : MethodCore, IIteratorContainer {
7246 const int AllowedModifiers =
7252 public enum OpType : byte {
7262 // Unary and Binary operators
7285 // Implicit and Explicit
7289 // Just because of enum
7293 public readonly OpType OperatorType;
7294 public MethodBuilder OperatorMethodBuilder;
7296 public Method OperatorMethod;
7298 static string[] attribute_targets = new string [] { "method", "return" };
7300 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7301 int mod_flags, Parameters parameters,
7302 ToplevelBlock block, Attributes attrs, Location loc)
7303 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7304 new MemberName ("op_" + type), attrs, parameters, loc)
7306 OperatorType = type;
7310 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7312 OperatorMethod.ApplyAttributeBuilder (a, cb);
7315 public override AttributeTargets AttributeTargets {
7317 return AttributeTargets.Method;
7321 protected override bool CheckForDuplications()
7323 ArrayList ar = Parent.Operators;
7325 int arLen = ar.Count;
7327 for (int i = 0; i < arLen; i++) {
7328 Operator o = (Operator) ar [i];
7329 if (IsDuplicateImplementation (o))
7334 ar = Parent.Methods;
7336 int arLen = ar.Count;
7338 for (int i = 0; i < arLen; i++) {
7339 Method m = (Method) ar [i];
7340 if (IsDuplicateImplementation (m))
7348 public override bool Define ()
7350 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7351 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7352 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7359 if (MemberType == TypeManager.void_type) {
7360 Report.Error (590, Location, "User-defined operators cannot return void");
7364 OperatorMethod = new Method (
7365 Parent, Type, ModFlags, false, MemberName,
7366 Parameters, OptAttributes, Location);
7368 OperatorMethod.Block = Block;
7369 OperatorMethod.IsOperator = this;
7370 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7371 OperatorMethod.Define ();
7373 if (OperatorMethod.MethodBuilder == null)
7376 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7378 parameter_types = OperatorMethod.ParameterTypes;
7379 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7380 Type return_type = OperatorMethod.ReturnType;
7381 Type first_arg_type = parameter_types [0];
7386 // Rules for conversion operators
7388 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7389 if (first_arg_type == return_type && first_arg_type == declaring_type){
7390 Report.Error (555, Location,
7391 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7395 if (first_arg_type != declaring_type && return_type != declaring_type){
7398 "User-defined conversion must convert to or from the " +
7403 if (first_arg_type == TypeManager.object_type ||
7404 return_type == TypeManager.object_type){
7407 "User-defined conversion cannot convert to or from " +
7412 if (first_arg_type.IsInterface || return_type.IsInterface){
7413 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7414 GetSignatureForError ());
7418 if (first_arg_type.IsSubclassOf (return_type)
7419 || return_type.IsSubclassOf (first_arg_type)){
7420 if (declaring_type.IsSubclassOf (return_type)) {
7421 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7422 GetSignatureForError ());
7425 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7426 GetSignatureForError ());
7429 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7430 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7431 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");
7434 } else if (Parameters.FixedParameters.Length == 1) {
7435 // Checks for Unary operators
7437 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7438 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7439 Report.Error (448, Location,
7440 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7443 if (first_arg_type != declaring_type) {
7445 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7450 if (first_arg_type != declaring_type){
7453 "The parameter of a unary operator must be the " +
7458 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7459 if (return_type != TypeManager.bool_type){
7462 "The return type of operator True or False " +
7469 // Checks for Binary operators
7471 if (first_arg_type != declaring_type &&
7472 parameter_types [1] != declaring_type){
7475 "One of the parameters of a binary operator must " +
7476 "be the containing type");
7484 public override void Emit ()
7487 // abstract or extern methods have no bodies
7489 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7492 OperatorMethod.Emit ();
7496 // Operator cannot be override
7497 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7502 public static string GetName (OpType ot)
7505 case OpType.LogicalNot:
7507 case OpType.OnesComplement:
7509 case OpType.Increment:
7511 case OpType.Decrement:
7517 case OpType.Addition:
7519 case OpType.Subtraction:
7521 case OpType.UnaryPlus:
7523 case OpType.UnaryNegation:
7525 case OpType.Multiply:
7527 case OpType.Division:
7529 case OpType.Modulus:
7531 case OpType.BitwiseAnd:
7533 case OpType.BitwiseOr:
7535 case OpType.ExclusiveOr:
7537 case OpType.LeftShift:
7539 case OpType.RightShift:
7541 case OpType.Equality:
7543 case OpType.Inequality:
7545 case OpType.GreaterThan:
7547 case OpType.LessThan:
7549 case OpType.GreaterThanOrEqual:
7551 case OpType.LessThanOrEqual:
7553 case OpType.Implicit:
7555 case OpType.Explicit:
7561 public static OpType GetOperatorType (string name)
7563 if (name.StartsWith ("op_")){
7564 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7565 if (Unary.oper_names [i] == name)
7569 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7570 if (Binary.oper_names [i] == name)
7577 public override string GetSignatureForError ()
7579 StringBuilder sb = new StringBuilder ();
7580 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7581 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7584 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7587 sb.Append (Parameters.GetSignatureForError ());
7588 return sb.ToString ();
7591 public override bool MarkForDuplicationCheck ()
7593 caching_flags |= Flags.TestMethodDuplication;
7597 public override string[] ValidAttributeTargets {
7599 return attribute_targets;
7605 // This is used to compare method signatures
7607 struct MethodSignature {
7609 public Type RetType;
7610 public Type [] Parameters;
7613 /// This delegate is used to extract methods which have the
7614 /// same signature as the argument
7616 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7618 public MethodSignature (string name, Type ret_type, Type [] parameters)
7623 if (parameters == null)
7624 Parameters = TypeManager.NoTypes;
7626 Parameters = parameters;
7629 public override string ToString ()
7632 if (Parameters.Length != 0){
7633 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7634 for (int i = 0; i < Parameters.Length; i++){
7635 sb.Append (Parameters [i]);
7636 if (i+1 < Parameters.Length)
7639 pars = sb.ToString ();
7642 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7645 public override int GetHashCode ()
7647 return Name.GetHashCode ();
7650 public override bool Equals (Object o)
7652 MethodSignature other = (MethodSignature) o;
7654 if (other.Name != Name)
7657 if (other.RetType != RetType)
7660 if (Parameters == null){
7661 if (other.Parameters == null)
7666 if (other.Parameters == null)
7669 int c = Parameters.Length;
7670 if (other.Parameters.Length != c)
7673 for (int i = 0; i < c; i++)
7674 if (other.Parameters [i] != Parameters [i])
7680 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7682 MethodSignature sig = (MethodSignature) filter_criteria;
7684 if (m.Name != sig.Name)
7688 MethodInfo mi = m as MethodInfo;
7689 PropertyInfo pi = m as PropertyInfo;
7692 ReturnType = mi.ReturnType;
7693 else if (pi != null)
7694 ReturnType = pi.PropertyType;
7699 // we use sig.RetType == null to mean `do not check the
7700 // method return value.
7702 if (sig.RetType != null)
7703 if (ReturnType != sig.RetType)
7708 args = TypeManager.GetArgumentTypes (mi);
7710 args = TypeManager.GetArgumentTypes (pi);
7711 Type [] sigp = sig.Parameters;
7713 if (args.Length != sigp.Length)
7716 for (int i = args.Length; i > 0; ){
7718 if (args [i] != sigp [i])