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 (null, Location),
945 c.Block = new ToplevelBlock (null, Location);
950 /// The pending methods that need to be implemented
951 // (interfaces or abstract methods)
953 public PendingImplementation Pending;
955 public abstract PendingImplementation GetPendingImplementations ();
957 TypeExpr[] GetPartialBases (out TypeExpr base_class)
959 ArrayList ifaces = new ArrayList ();
962 Location base_loc = Location.Null;
964 foreach (ClassPart part in parts) {
965 TypeExpr new_base_class;
966 TypeExpr[] new_ifaces;
968 new_ifaces = part.GetClassBases (out new_base_class);
969 if (new_ifaces == null && new_base_class != null)
972 if ((base_class != null) && (new_base_class != null) &&
973 !base_class.Equals (new_base_class)) {
974 Report.Error (263, part.Location,
975 "Partial declarations of `{0}' must " +
976 "not specify different base classes",
979 if (!Location.IsNull (base_loc))
980 Report.LocationOfPreviousError (base_loc);
985 if ((base_class == null) && (new_base_class != null)) {
986 base_class = new_base_class;
987 base_loc = part.Location;
990 if (new_ifaces == null)
993 foreach (TypeExpr iface in new_ifaces) {
995 foreach (TypeExpr old_iface in ifaces) {
996 if (old_iface.Equals (iface)) {
1007 TypeExpr[] retval = new TypeExpr [ifaces.Count];
1008 ifaces.CopyTo (retval, 0);
1012 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1016 int count = Bases.Count;
1017 int start = 0, i, j;
1019 if (Kind == Kind.Class){
1020 TypeExpr name = ResolveBaseTypeExpr (
1021 (Expression) Bases [0], false, Location);
1027 if (!name.IsInterface) {
1028 // base_class could be a class, struct, enum, delegate.
1029 // This is validated in GetClassBases.
1035 TypeExpr [] ifaces = new TypeExpr [count-start];
1037 for (i = start, j = 0; i < count; i++, j++){
1038 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1039 if (resolved == null) {
1043 ifaces [j] = resolved;
1050 /// This function computes the Base class and also the
1051 /// list of interfaces that the class or struct @c implements.
1053 /// The return value is an array (might be null) of
1054 /// interfaces implemented (as Types).
1056 /// The @base_class argument is set to the base object or null
1057 /// if this is `System.Object'.
1059 TypeExpr [] GetClassBases (out TypeExpr base_class)
1066 ifaces = GetPartialBases (out base_class);
1067 else if (Bases == null){
1071 ifaces = GetNormalBases (out base_class);
1076 if ((base_class != null) && (Kind == Kind.Class)){
1078 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1079 Report.Error (1521, base_class.Location, "Invalid base type");
1083 if (base_class.IsSealed){
1084 Report.SymbolRelatedToPreviousError (base_class.Type);
1085 if (base_class.Type.IsAbstract) {
1086 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
1087 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1089 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
1090 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1095 if (!base_class.CanInheritFrom ()){
1096 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
1097 GetSignatureForError (), base_class.GetSignatureForError ());
1101 if (!base_class.AsAccessible (this, ModFlags)) {
1102 Report.SymbolRelatedToPreviousError (base_class.Type);
1103 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
1104 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1108 if (base_class != null)
1109 base_class_name = base_class.Name;
1114 int count = ifaces != null ? ifaces.Length : 0;
1116 for (i = 0; i < count; i++) {
1117 TypeExpr iface = (TypeExpr) ifaces [i];
1119 if (!iface.IsInterface) {
1120 if (Kind != Kind.Class) {
1121 // TODO: location of symbol related ....
1122 Error_TypeInListIsNotInterface (Location, iface.FullName);
1124 else if (base_class != null)
1125 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1126 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1128 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1129 GetSignatureForError (), iface.GetSignatureForError ());
1134 for (int x = 0; x < i; x++) {
1135 if (iface.Equals (ifaces [x])) {
1136 Report.Error (528, Location,
1137 "`{0}' is already listed in " +
1138 "interface list", iface.Name);
1143 if ((Kind == Kind.Interface) &&
1144 !iface.AsAccessible (Parent, ModFlags)) {
1145 Report.Error (61, Location,
1146 "Inconsistent accessibility: base " +
1147 "interface `{0}' is less accessible " +
1148 "than interface `{1}'", iface.Name,
1158 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1160 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1164 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1166 public override TypeBuilder DefineType ()
1171 if (TypeBuilder != null)
1174 TypeAttributes type_attributes = TypeAttr;
1178 if (TypeManager.NamespaceClash (Name, Location)) {
1183 ModuleBuilder builder = CodeGen.Module.Builder;
1184 TypeBuilder = builder.DefineType (
1185 Name, type_attributes, null, null);
1187 TypeBuilder builder = Parent.TypeBuilder;
1188 if (builder == null) {
1193 TypeBuilder = builder.DefineNestedType (
1194 Basename, type_attributes, ptype, null);
1196 } catch (ArgumentException) {
1197 Report.RuntimeMissingSupport (Location, "static classes");
1202 TypeManager.AddUserType (Name, this);
1204 if (Parts != null) {
1206 foreach (ClassPart part in Parts) {
1207 part.TypeBuilder = TypeBuilder;
1209 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1210 part.ec.ContainerType = TypeBuilder;
1214 // Normally, we create the EmitContext here.
1215 // The only exception is if we're an Iterator - in this case,
1216 // we already have the `ec', so we don't want to create a new one.
1219 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1220 ec.ContainerType = TypeBuilder;
1223 iface_exprs = GetClassBases (out base_type);
1224 if (iface_exprs == null && base_type != null) {
1229 if (base_type == null) {
1230 if (Kind == Kind.Class){
1231 if (RootContext.StdLib)
1232 base_type = TypeManager.system_object_expr;
1233 else if (Name != "System.Object")
1234 base_type = TypeManager.system_object_expr;
1235 } else if (Kind == Kind.Struct) {
1237 // If we are compiling our runtime,
1238 // and we are defining ValueType, then our
1239 // base is `System.Object'.
1241 if (!RootContext.StdLib && Name == "System.ValueType")
1242 base_type = TypeManager.system_object_expr;
1244 base_type = TypeManager.system_valuetype_expr;
1248 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1249 throw new Exception ();
1251 if (base_type != null) {
1252 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1253 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1254 ptype = base_type.ResolveType (TypeResolveEmitContext);
1255 if (ptype == null) {
1261 if (!CheckRecursiveDefinition (this)) {
1267 TypeBuilder.SetParent (ptype);
1269 // add interfaces that were not added at type creation
1270 if (iface_exprs != null) {
1271 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1272 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1273 TypeResolveEmitContext.ContainerType = TypeBuilder;
1274 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1275 if (ifaces == null) {
1280 foreach (Type itype in ifaces)
1281 TypeBuilder.AddInterfaceImplementation (itype);
1283 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1286 if (!(this is Iterator))
1287 RootContext.RegisterOrder (this);
1289 if (!DefineNestedTypes ()) {
1297 protected virtual bool DefineNestedTypes ()
1299 if (Interfaces != null) {
1300 foreach (TypeContainer iface in Interfaces)
1301 if (iface.DefineType () == null)
1305 if (Types != null) {
1306 foreach (TypeContainer tc in Types)
1307 if (tc.DefineType () == null)
1311 if (Delegates != null) {
1312 foreach (Delegate d in Delegates)
1313 if (d.DefineType () == null)
1317 if (Enums != null) {
1318 foreach (Enum en in Enums)
1319 if (en.DefineType () == null)
1326 TypeContainer InTransit;
1328 protected bool CheckRecursiveDefinition (TypeContainer tc)
1330 if (InTransit != null) {
1331 Report.SymbolRelatedToPreviousError (this);
1332 if (this is Interface)
1334 529, tc.Location, "Inherited interface `{0}' causes a " +
1335 "cycle in the interface hierarchy of `{1}'",
1336 GetSignatureForError (), tc.GetSignatureForError ());
1339 146, tc.Location, "Circular base class dependency " +
1340 "involving `{0}' and `{1}'",
1341 tc.GetSignatureForError (), GetSignatureForError ());
1347 Type parent = ptype;
1348 if (parent != null) {
1349 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1350 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1354 if (iface_exprs != null) {
1355 foreach (TypeExpr iface in iface_exprs) {
1356 Type itype = iface.Type;
1358 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1359 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1368 public static void Error_KeywordNotAllowed (Location loc)
1370 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1374 /// Populates our TypeBuilder with fields and methods
1376 public override bool DefineMembers (TypeContainer container)
1378 if (members_defined)
1379 return members_defined_ok;
1381 if (!base.DefineMembers (container))
1384 members_defined_ok = DoDefineMembers ();
1385 members_defined = true;
1387 return members_defined_ok;
1390 protected virtual bool DoDefineMembers ()
1393 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1394 if (conflict_symbol == null) {
1395 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1396 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1398 if ((ModFlags & Modifiers.NEW) == 0) {
1399 Report.SymbolRelatedToPreviousError (conflict_symbol);
1400 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1401 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1406 DefineContainerMembers (constants);
1407 DefineContainerMembers (fields);
1409 if ((Kind == Kind.Class) && !(this is ClassPart)){
1410 if ((instance_constructors == null) &&
1411 !(this is StaticClass)) {
1412 if (default_constructor == null)
1413 DefineDefaultConstructor (false);
1416 if (initialized_static_fields != null &&
1417 default_static_constructor == null)
1418 DefineDefaultConstructor (true);
1421 if (Kind == Kind.Struct){
1423 // Structs can not have initialized instance
1426 if (initialized_static_fields != null &&
1427 default_static_constructor == null)
1428 DefineDefaultConstructor (true);
1430 if (initialized_fields != null)
1431 ReportStructInitializedInstanceError ();
1434 Pending = GetPendingImplementations ();
1436 if (parts != null) {
1437 foreach (ClassPart part in parts) {
1438 if (!part.DefineMembers (this))
1444 // Constructors are not in the defined_names array
1446 DefineContainerMembers (instance_constructors);
1448 if (default_static_constructor != null)
1449 default_static_constructor.Define ();
1451 DefineContainerMembers (properties);
1452 DefineContainerMembers (events);
1453 DefineContainerMembers (indexers);
1454 DefineContainerMembers (methods);
1455 DefineContainerMembers (operators);
1456 DefineContainerMembers (enums);
1457 DefineContainerMembers (delegates);
1460 if (!(this is ClassPart))
1461 member_cache = new MemberCache (this);
1464 if (parts != null) {
1465 foreach (ClassPart part in parts)
1466 part.member_cache = member_cache;
1469 if (iterators != null) {
1470 foreach (Iterator iterator in iterators) {
1471 if (iterator.DefineType () == null)
1475 foreach (Iterator iterator in iterators) {
1476 if (!iterator.DefineMembers (this))
1484 void ReportStructInitializedInstanceError ()
1486 foreach (Field f in initialized_fields){
1487 Report.Error (573, Location,
1488 "`{0}': Structs cannot have instance field initializers",
1489 f.GetSignatureForError ());
1493 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1496 mcal.DefineContainerMembers ();
1499 public override bool Define ()
1501 if (parts != null) {
1502 foreach (ClassPart part in parts) {
1503 if (!part.Define ())
1508 if (iterators != null) {
1509 foreach (Iterator iterator in iterators) {
1510 if (!iterator.Define ())
1518 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1520 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1524 /// This function is based by a delegate to the FindMembers routine
1526 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1532 /// This filter is used by FindMembers, and we just keep
1533 /// a global for the filter to `AlwaysAccept'
1535 static MemberFilter accepting_filter;
1538 static TypeContainer ()
1540 accepting_filter = new MemberFilter (AlwaysAccept);
1543 public MethodInfo[] GetMethods ()
1545 ArrayList members = new ArrayList ();
1547 DefineMembers (null);
1549 if (methods != null) {
1550 int len = methods.Count;
1551 for (int i = 0; i < len; i++) {
1552 Method m = (Method) methods [i];
1554 members.Add (m.MethodBuilder);
1558 if (operators != null) {
1559 int len = operators.Count;
1560 for (int i = 0; i < len; i++) {
1561 Operator o = (Operator) operators [i];
1563 members.Add (o.OperatorMethodBuilder);
1567 if (properties != null) {
1568 int len = properties.Count;
1569 for (int i = 0; i < len; i++) {
1570 Property p = (Property) properties [i];
1572 if (p.GetBuilder != null)
1573 members.Add (p.GetBuilder);
1574 if (p.SetBuilder != null)
1575 members.Add (p.SetBuilder);
1579 if (indexers != null) {
1580 int len = indexers.Count;
1581 for (int i = 0; i < len; i++) {
1582 Indexer ix = (Indexer) indexers [i];
1584 if (ix.GetBuilder != null)
1585 members.Add (ix.GetBuilder);
1586 if (ix.SetBuilder != null)
1587 members.Add (ix.SetBuilder);
1591 if (events != null) {
1592 int len = events.Count;
1593 for (int i = 0; i < len; i++) {
1594 Event e = (Event) events [i];
1596 if (e.AddBuilder != null)
1597 members.Add (e.AddBuilder);
1598 if (e.RemoveBuilder != null)
1599 members.Add (e.RemoveBuilder);
1603 MethodInfo[] retMethods = new MethodInfo [members.Count];
1604 members.CopyTo (retMethods, 0);
1608 // Indicated whether container has StructLayout attribute set Explicit
1609 public virtual bool HasExplicitLayout {
1615 public override Type FindNestedType (string name)
1617 ArrayList [] lists = { types, enums, delegates, interfaces };
1619 for (int j = 0; j < lists.Length; ++j) {
1620 ArrayList list = lists [j];
1624 int len = list.Count;
1625 for (int i = 0; i < len; ++i) {
1626 DeclSpace ds = (DeclSpace) list [i];
1627 if (ds.Basename == name) {
1629 return ds.TypeBuilder;
1637 private void FindMembers_NestedTypes (int modflags,
1638 BindingFlags bf, MemberFilter filter, object criteria,
1639 ref ArrayList members)
1641 ArrayList [] lists = { types, enums, delegates, interfaces };
1643 for (int j = 0; j < lists.Length; ++j) {
1644 ArrayList list = lists [j];
1648 int len = list.Count;
1649 for (int i = 0; i < len; i++) {
1650 DeclSpace ds = (DeclSpace) list [i];
1652 if ((ds.ModFlags & modflags) == 0)
1655 TypeBuilder tb = ds.TypeBuilder;
1657 if (!(criteria is string) || ds.Basename.Equals (criteria))
1658 tb = ds.DefineType ();
1661 if (tb != null && (filter (tb, criteria) == true)) {
1662 if (members == null)
1663 members = new ArrayList ();
1672 /// This method returns the members of this type just like Type.FindMembers would
1673 /// Only, we need to use this for types which are _being_ defined because MS'
1674 /// implementation can't take care of that.
1677 // FIXME: return an empty static array instead of null, that cleans up
1678 // some code and is consistent with some coding conventions I just found
1682 // Notice that in various cases we check if our field is non-null,
1683 // something that would normally mean that there was a bug elsewhere.
1685 // The problem happens while we are defining p-invoke methods, as those
1686 // will trigger a FindMembers, but this happens before things are defined
1688 // Since the whole process is a no-op, it is fine to check for null here.
1690 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1691 MemberFilter filter, object criteria)
1693 ArrayList members = null;
1696 if ((bf & BindingFlags.Public) != 0)
1697 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1699 if ((bf & BindingFlags.NonPublic) != 0)
1700 modflags |= Modifiers.PRIVATE;
1702 int static_mask = 0, static_flags = 0;
1703 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1704 case BindingFlags.Static:
1705 static_mask = static_flags = Modifiers.STATIC;
1708 case BindingFlags.Instance:
1709 static_mask = Modifiers.STATIC;
1714 static_mask = static_flags = 0;
1718 Timer.StartTimer (TimerType.TcFindMembers);
1721 filter = accepting_filter;
1723 if ((mt & MemberTypes.Field) != 0) {
1724 if (fields != null) {
1725 int len = fields.Count;
1726 for (int i = 0; i < len; i++) {
1727 FieldMember f = (FieldMember) fields [i];
1729 if ((f.ModFlags & modflags) == 0)
1731 if ((f.ModFlags & static_mask) != static_flags)
1734 FieldBuilder fb = f.FieldBuilder;
1735 if (fb != null && filter (fb, criteria) == true) {
1736 if (members == null)
1737 members = new ArrayList ();
1744 if (constants != null) {
1745 int len = constants.Count;
1746 for (int i = 0; i < len; i++) {
1747 Const con = (Const) constants [i];
1749 if ((con.ModFlags & modflags) == 0)
1751 if ((con.ModFlags & static_mask) != static_flags)
1754 FieldBuilder fb = con.FieldBuilder;
1757 fb = con.FieldBuilder;
1759 if (fb != null && filter (fb, criteria) == true) {
1760 if (members == null)
1761 members = new ArrayList ();
1769 if ((mt & MemberTypes.Method) != 0) {
1770 if (methods != null) {
1771 int len = methods.Count;
1772 for (int i = 0; i < len; i++) {
1773 Method m = (Method) methods [i];
1775 if ((m.ModFlags & modflags) == 0)
1777 if ((m.ModFlags & static_mask) != static_flags)
1780 MethodBuilder mb = m.MethodBuilder;
1782 if (mb != null && filter (mb, criteria) == true) {
1783 if (members == null)
1784 members = new ArrayList ();
1791 if (operators != null) {
1792 int len = operators.Count;
1793 for (int i = 0; i < len; i++) {
1794 Operator o = (Operator) operators [i];
1796 if ((o.ModFlags & modflags) == 0)
1798 if ((o.ModFlags & static_mask) != static_flags)
1801 MethodBuilder ob = o.OperatorMethodBuilder;
1802 if (ob != null && filter (ob, criteria) == true) {
1803 if (members == null)
1804 members = new ArrayList ();
1811 if (properties != null) {
1812 int len = properties.Count;
1813 for (int i = 0; i < len; i++) {
1814 Property p = (Property) properties [i];
1816 if ((p.ModFlags & modflags) == 0)
1818 if ((p.ModFlags & static_mask) != static_flags)
1824 if (b != null && filter (b, criteria) == true) {
1825 if (members == null)
1826 members = new ArrayList ();
1832 if (b != null && filter (b, criteria) == true) {
1833 if (members == null)
1834 members = new ArrayList ();
1841 if (indexers != null) {
1842 int len = indexers.Count;
1843 for (int i = 0; i < len; i++) {
1844 Indexer ix = (Indexer) indexers [i];
1846 if ((ix.ModFlags & modflags) == 0)
1848 if ((ix.ModFlags & static_mask) != static_flags)
1854 if (b != null && filter (b, criteria) == true) {
1855 if (members == null)
1856 members = new ArrayList ();
1862 if (b != null && filter (b, criteria) == true) {
1863 if (members == null)
1864 members = new ArrayList ();
1872 if ((mt & MemberTypes.Event) != 0) {
1873 if (events != null) {
1874 int len = events.Count;
1875 for (int i = 0; i < len; i++) {
1876 Event e = (Event) events [i];
1878 if ((e.ModFlags & modflags) == 0)
1880 if ((e.ModFlags & static_mask) != static_flags)
1883 MemberInfo eb = e.EventBuilder;
1884 if (eb != null && filter (eb, criteria) == true) {
1885 if (members == null)
1886 members = new ArrayList ();
1888 members.Add (e.EventBuilder);
1894 if ((mt & MemberTypes.Property) != 0){
1895 if (properties != null) {
1896 int len = properties.Count;
1897 for (int i = 0; i < len; i++) {
1898 Property p = (Property) properties [i];
1900 if ((p.ModFlags & modflags) == 0)
1902 if ((p.ModFlags & static_mask) != static_flags)
1905 MemberInfo pb = p.PropertyBuilder;
1906 if (pb != null && filter (pb, criteria) == true) {
1907 if (members == null)
1908 members = new ArrayList ();
1910 members.Add (p.PropertyBuilder);
1915 if (indexers != null) {
1916 int len = indexers.Count;
1917 for (int i = 0; i < len; i++) {
1918 Indexer ix = (Indexer) indexers [i];
1920 if ((ix.ModFlags & modflags) == 0)
1922 if ((ix.ModFlags & static_mask) != static_flags)
1925 MemberInfo ib = ix.PropertyBuilder;
1926 if (ib != null && filter (ib, criteria) == true) {
1927 if (members == null)
1928 members = new ArrayList ();
1930 members.Add (ix.PropertyBuilder);
1936 if ((mt & MemberTypes.NestedType) != 0)
1937 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1939 if ((mt & MemberTypes.Constructor) != 0){
1940 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1941 int len = instance_constructors.Count;
1942 for (int i = 0; i < len; i++) {
1943 Constructor c = (Constructor) instance_constructors [i];
1945 ConstructorBuilder cb = c.ConstructorBuilder;
1946 if (cb != null && filter (cb, criteria) == true) {
1947 if (members == null)
1948 members = new ArrayList ();
1955 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1956 ConstructorBuilder cb =
1957 default_static_constructor.ConstructorBuilder;
1959 if (cb != null && filter (cb, criteria) == true) {
1960 if (members == null)
1961 members = new ArrayList ();
1969 // Lookup members in base if requested.
1971 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1972 if (TypeBuilder.BaseType != null) {
1973 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1974 if (list.Count > 0) {
1975 if (members == null)
1976 members = new ArrayList ();
1978 members.AddRange (list);
1981 if (ifaces != null) {
1982 foreach (Type base_type in ifaces) {
1983 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1985 if (list.Count > 0) {
1986 if (members == null)
1987 members = new ArrayList ();
1988 members.AddRange (list);
1994 Timer.StopTimer (TimerType.TcFindMembers);
1996 if (members == null)
1997 return MemberList.Empty;
1999 return new MemberList (members);
2002 public override MemberCache MemberCache {
2004 return member_cache;
2008 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2009 MemberFilter filter, object criteria)
2011 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2014 return ds.FindMembers (mt, bf, filter, criteria);
2016 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2021 // FindMethods will look for methods not only in the type `t', but in
2022 // any interfaces implemented by the type.
2024 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2025 MemberFilter filter, object criteria)
2031 /// Emits the values for the constants
2033 public void EmitConstants ()
2035 if (constants != null)
2036 foreach (Const con in constants)
2041 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2046 foreach (MemberCore mc in al) {
2047 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2051 Report.Warning (169, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2056 public virtual void VerifyMembers ()
2059 // Check for internal or private fields that were never assigned
2061 if (RootContext.WarningLevel >= 3) {
2062 CheckMemberUsage (properties, "property");
2063 CheckMemberUsage (methods, "method");
2064 CheckMemberUsage (constants, "constant");
2066 if (fields != null){
2067 foreach (FieldMember f in fields) {
2068 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2072 if ((f.caching_flags & Flags.IsAssigned) == 0)
2073 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2075 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2076 f.GetSignatureForError ());
2081 // Only report 649 on level 4
2083 if (RootContext.WarningLevel < 4)
2086 if ((f.caching_flags & Flags.IsAssigned) != 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){
2731 if ((e.caching_flags & Flags.IsAssigned) == 0)
2732 Report.Warning (67, 3, 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.GetSignatureForError ());
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 public void SetYields ()
3123 ModFlags |= Modifiers.METHOD_YIELDS;
3126 protected override bool CheckBase ()
3128 if (!base.CheckBase ())
3131 // Check whether arguments were correct.
3132 if (!DoDefineParameters ())
3135 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3141 // Is null for System.Object while compiling corlib and base interfaces
3142 if (Parent.BaseCache == null) {
3143 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3144 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3149 Type base_ret_type = null;
3150 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3152 // method is override
3153 if (base_method != null) {
3155 if (!CheckMethodAgainstBase ())
3158 if ((ModFlags & Modifiers.NEW) == 0) {
3159 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3160 Report.SymbolRelatedToPreviousError (base_method);
3161 if (this is PropertyBase) {
3162 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3163 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3166 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3167 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3172 if (base_method.IsAbstract && !IsInterface) {
3173 Report.SymbolRelatedToPreviousError (base_method);
3174 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3175 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3180 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3181 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3185 if (RootContext.WarningLevel > 2) {
3186 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3187 Parent.Methods.HasEquals = true;
3188 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3189 Parent.Methods.HasGetHashCode = true;
3192 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3193 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3195 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3196 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3197 Report.SymbolRelatedToPreviousError (base_method);
3198 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3199 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3206 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3207 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3208 if (conflict_symbol != null) {
3209 Report.SymbolRelatedToPreviousError (conflict_symbol);
3210 if (this is PropertyBase)
3211 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3213 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3215 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3219 if (conflict_symbol == null) {
3220 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3221 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3226 if ((ModFlags & Modifiers.NEW) == 0) {
3227 if (this is Method && conflict_symbol is MethodBase)
3230 Report.SymbolRelatedToPreviousError (conflict_symbol);
3231 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3232 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3239 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3240 // that have been defined.
3242 // `name' is the user visible name for reporting errors (this is used to
3243 // provide the right name regarding method names and properties)
3245 bool CheckMethodAgainstBase ()
3249 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3250 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3251 Report.Error (506, Location,
3252 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3253 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3257 // Now we check that the overriden method is not final
3259 if (base_method.IsFinal) {
3260 Report.SymbolRelatedToPreviousError (base_method);
3261 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3262 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3266 // Check that the permissions are not being changed
3268 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3269 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3271 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3272 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3277 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3278 ModFlags |= Modifiers.NEW;
3279 Report.SymbolRelatedToPreviousError (base_method);
3280 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3281 if (RootContext.WarningLevel >= 2)
3282 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));
3284 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3285 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3292 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3294 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3296 // when overriding protected internal, the method can be declared
3297 // protected internal only within the same assembly
3300 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3301 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3303 // assemblies differ - report an error
3307 } else if (thisp != base_classp) {
3309 // same assembly, but other attributes differ - report an error
3314 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3316 // if it's not "protected internal", it must be "protected"
3320 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3322 // protected within the same assembly - an error
3325 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3326 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3328 // protected ok, but other attributes differ - report an error
3334 return (thisp == base_classp);
3338 public bool CheckAbstractAndExtern (bool has_block)
3340 if (Parent.Kind == Kind.Interface)
3344 if ((ModFlags & Modifiers.EXTERN) != 0) {
3345 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3346 GetSignatureForError ());
3350 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3351 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3352 GetSignatureForError ());
3356 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3357 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3358 GetSignatureForError ());
3366 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3368 Report.SymbolRelatedToPreviousError (base_method);
3369 string base_name = TypeManager.GetFullNameSignature (base_method);
3370 string this_name = GetSignatureForError ();
3371 if (suffix != null) {
3372 base_name += suffix;
3373 this_name += suffix;
3376 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3377 this_name, Modifiers.GetDescription (ma), base_name);
3380 protected static string Error722 {
3382 return "`{0}': static types cannot be used as return types";
3387 /// For custom member duplication search in a container
3389 protected abstract bool CheckForDuplications ();
3392 /// Gets base method and its return type
3394 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3396 protected virtual bool DoDefineParameters ()
3398 EmitContext ec = Parent.EmitContext;
3400 throw new InternalErrorException ("DoDefineParameters invoked too early");
3402 bool old_unsafe = ec.InUnsafe;
3403 ec.InUnsafe = InUnsafe;
3404 // Check if arguments were correct
3405 parameter_types = Parameters.GetParameterInfo (ec);
3406 ec.InUnsafe = old_unsafe;
3408 if ((parameter_types == null) ||
3409 !CheckParameters (Parent, parameter_types))
3412 parameter_info = new InternalParameters (parameter_types, Parameters);
3414 Parameter array_param = Parameters.ArrayParameter;
3415 if ((array_param != null) &&
3416 (!array_param.ParameterType.IsArray ||
3417 (array_param.ParameterType.GetArrayRank () != 1))) {
3418 Report.Error (225, Location, "The params parameter must be a single dimensional array");
3425 public override string[] ValidAttributeTargets {
3427 return attribute_targets;
3431 protected override bool VerifyClsCompliance (DeclSpace ds)
3433 if (!base.VerifyClsCompliance (ds)) {
3434 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3435 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3440 if (Parameters.HasArglist) {
3441 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3444 if (!AttributeTester.IsClsCompliant (MemberType)) {
3445 if (this is PropertyBase)
3446 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3447 GetSignatureForError ());
3449 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3450 GetSignatureForError ());
3453 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3458 protected bool IsDuplicateImplementation (MethodCore method)
3460 if (method == this || !(method.MemberName.Equals (MemberName)))
3463 Type[] param_types = method.ParameterTypes;
3464 if (param_types == null && ParameterTypes == null)
3466 if (param_types == null || ParameterTypes == null)
3469 if (param_types.Length != ParameterTypes.Length)
3472 for (int i = 0; i < param_types.Length; i++)
3473 if (param_types [i] != ParameterTypes [i])
3476 // TODO: make operator compatible with MethodCore to avoid this
3477 if (this is Operator && method is Operator) {
3478 if (MemberType != method.MemberType)
3483 // Try to report 663: method only differs on out/ref
3485 ParameterData info = ParameterInfo;
3486 ParameterData other_info = method.ParameterInfo;
3487 for (int i = 0; i < info.Count; i++){
3488 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3489 Report.SymbolRelatedToPreviousError (method);
3490 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3491 GetSignatureForError ());
3496 Report.SymbolRelatedToPreviousError (method);
3497 if (this is Operator && method is Operator)
3498 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3500 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3504 public override bool IsUsed {
3505 get { return IsExplicitImpl || base.IsUsed; }
3509 // Returns a string that represents the signature for this
3510 // member which should be used in XML documentation.
3512 public override string GetDocCommentName (DeclSpace ds)
3514 return DocUtil.GetMethodDocCommentName (this, ds);
3518 // Raised (and passed an XmlElement that contains the comment)
3519 // when GenerateDocComment is writing documentation expectedly.
3521 // FIXME: with a few effort, it could be done with XmlReader,
3522 // that means removal of DOM use.
3524 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3526 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3530 // Represents header string for documentation comment.
3532 public override string DocCommentHeader {
3533 get { return "M:"; }
3536 protected override void VerifyObsoleteAttribute()
3538 base.VerifyObsoleteAttribute ();
3540 if (parameter_types == null)
3543 foreach (Type type in parameter_types) {
3544 CheckUsageOfObsoleteAttribute (type);
3549 public class SourceMethod : ISourceMethod
3551 TypeContainer container;
3554 protected SourceMethod (TypeContainer container, MethodBase builder,
3555 ISourceFile file, Location start, Location end)
3557 this.container = container;
3558 this.builder = builder;
3560 CodeGen.SymbolWriter.OpenMethod (
3561 file, this, start.Row, 0, end.Row, 0);
3564 public string Name {
3565 get { return builder.Name; }
3568 public int NamespaceID {
3569 get { return container.NamespaceEntry.SymbolFileID; }
3574 if (builder is MethodBuilder)
3575 return ((MethodBuilder) builder).GetToken ().Token;
3576 else if (builder is ConstructorBuilder)
3577 return ((ConstructorBuilder) builder).GetToken ().Token;
3579 throw new NotSupportedException ();
3583 public void CloseMethod ()
3585 if (CodeGen.SymbolWriter != null)
3586 CodeGen.SymbolWriter.CloseMethod ();
3589 public static SourceMethod Create (TypeContainer parent,
3590 MethodBase builder, Block block)
3592 if (CodeGen.SymbolWriter == null)
3597 Location start_loc = block.StartLocation;
3598 if (Location.IsNull (start_loc))
3601 Location end_loc = block.EndLocation;
3602 if (Location.IsNull (end_loc))
3605 ISourceFile file = start_loc.SourceFile;
3609 return new SourceMethod (
3610 parent, builder, file, start_loc, end_loc);
3614 public class Method : MethodCore, IIteratorContainer, IMethodData {
3615 public MethodBuilder MethodBuilder;
3616 public MethodData MethodData;
3617 ReturnParameter return_attributes;
3618 ListDictionary declarative_security;
3621 /// Modifiers allowed in a class declaration
3623 const int AllowedModifiers =
3626 Modifiers.PROTECTED |
3627 Modifiers.INTERNAL |
3632 Modifiers.OVERRIDE |
3633 Modifiers.ABSTRACT |
3635 Modifiers.METHOD_YIELDS |
3638 const int AllowedInterfaceModifiers =
3639 Modifiers.NEW | Modifiers.UNSAFE;
3642 // return_type can be "null" for VOID values.
3644 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3645 MemberName name, Parameters parameters, Attributes attrs,
3647 : base (ds, return_type, mod,
3648 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3649 is_iface, name, attrs, parameters, l)
3653 public override AttributeTargets AttributeTargets {
3655 return AttributeTargets.Method;
3659 public override string GetSignatureForError()
3661 if (IsOperator != null)
3662 return IsOperator.GetSignatureForError ();
3664 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3667 void DuplicateEntryPoint (MethodInfo b, Location location)
3671 "Program `" + CodeGen.FileName +
3672 "' has more than one entry point defined: `" +
3673 TypeManager.CSharpSignature(b) + "'");
3676 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3678 if (b.ReturnType != TypeManager.void_type &&
3679 b.ReturnType != TypeManager.int32_type)
3682 if (pinfo.Count == 0)
3685 if (pinfo.Count > 1)
3688 Type t = pinfo.ParameterType(0);
3690 (t.GetArrayRank() == 1) &&
3691 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3692 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3698 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3700 if (a.Target == AttributeTargets.ReturnValue) {
3701 if (return_attributes == null)
3702 return_attributes = new ReturnParameter (MethodBuilder, Location);
3704 return_attributes.ApplyAttributeBuilder (a, cb);
3708 if (a.Type == TypeManager.methodimpl_attr_type &&
3709 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3710 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3713 if (a.Type == TypeManager.dllimport_type) {
3714 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3715 if ((ModFlags & extern_static) != extern_static) {
3716 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3722 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3723 if (declarative_security == null)
3724 declarative_security = new ListDictionary ();
3725 a.ExtractSecurityPermissionSet (declarative_security);
3729 if (a.Type == TypeManager.conditional_attribute_type) {
3730 if (IsOperator != null || IsExplicitImpl) {
3731 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3732 GetSignatureForError ());
3736 if (ReturnType != TypeManager.void_type) {
3737 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
3741 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3742 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
3747 Report.Error (582, Location, "Conditional not valid on interface members");
3751 if (MethodData.implementing != null) {
3752 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
3753 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
3757 for (int i = 0; i < parameter_info.Count; ++i) {
3758 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3759 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
3765 MethodBuilder.SetCustomAttribute (cb);
3768 protected override bool CheckForDuplications ()
3770 ArrayList ar = Parent.Methods;
3772 int arLen = ar.Count;
3774 for (int i = 0; i < arLen; i++) {
3775 Method m = (Method) ar [i];
3776 if (IsDuplicateImplementation (m))
3781 ar = Parent.Properties;
3783 for (int i = 0; i < ar.Count; ++i) {
3784 PropertyBase pb = (PropertyBase) ar [i];
3785 if (pb.AreAccessorsDuplicateImplementation (this))
3790 ar = Parent.Indexers;
3792 for (int i = 0; i < ar.Count; ++i) {
3793 PropertyBase pb = (PropertyBase) ar [i];
3794 if (pb.AreAccessorsDuplicateImplementation (this))
3801 for (int i = 0; i < ar.Count; ++i) {
3802 Event ev = (Event) ar [i];
3803 if (ev.AreAccessorsDuplicateImplementation (this))
3814 public override bool Define ()
3819 if (!CheckAbstractAndExtern (block != null))
3822 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3823 Error1599 (Location, ReturnType);
3830 if (IsOperator != null)
3831 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3833 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3835 if (!MethodData.Define (Parent))
3838 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3839 Name == "Finalize" && !(this is Destructor)) {
3840 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3844 // Setup iterator if we are one
3846 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3847 Iterator iterator = new Iterator (this,
3849 ParameterInfo, ModFlags);
3851 if (!iterator.DefineIterator ())
3855 MethodBuilder = MethodData.MethodBuilder;
3858 // This is used to track the Entry Point,
3860 if (Name == "Main" &&
3861 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3862 (RootContext.MainClass == null ||
3863 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3864 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3865 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3866 md.SetMemberIsUsed ();
3868 if (RootContext.EntryPoint == null) {
3869 RootContext.EntryPoint = MethodBuilder;
3870 RootContext.EntryPointLocation = Location;
3872 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3873 DuplicateEntryPoint (MethodBuilder, Location);
3876 if (RootContext.WarningLevel >= 4)
3877 Report.Warning (28, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3881 if (MemberType.IsAbstract && MemberType.IsSealed) {
3882 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3892 public override void Emit ()
3894 MethodData.Emit (Parent, this);
3897 if (declarative_security != null) {
3898 foreach (DictionaryEntry de in declarative_security) {
3899 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3907 public static void Error1599 (Location loc, Type t)
3909 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
3912 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3914 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3915 container.TypeBuilder, Name, ParameterTypes, false);
3920 base_ret_type = mi.ReturnType;
3924 public override bool MarkForDuplicationCheck ()
3926 caching_flags |= Flags.TestMethodDuplication;
3930 protected override bool VerifyClsCompliance(DeclSpace ds)
3932 if (!base.VerifyClsCompliance (ds))
3935 if (parameter_types.Length > 0) {
3936 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3938 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3944 #region IMethodData Members
3946 public CallingConventions CallingConventions {
3948 CallingConventions cc = Parameters.GetCallingConvention ();
3949 if (Parameters.HasArglist)
3950 block.HasVarargs = true;
3953 if ((ModFlags & Modifiers.STATIC) == 0)
3954 cc |= CallingConventions.HasThis;
3956 // FIXME: How is `ExplicitThis' used in C#?
3962 public Type ReturnType {
3968 public MemberName MethodName {
3974 public new Location Location {
3976 return base.Location;
3980 protected override bool CheckBase() {
3981 if (!base.CheckBase ())
3984 // TODO: Destructor should derive from MethodCore
3985 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3986 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3987 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3994 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3996 EmitContext ec = new EmitContext (
3997 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3999 ec.CurrentIterator = tc as Iterator;
4000 if (ec.CurrentIterator != null)
4001 ec.CurrentAnonymousMethod = ec.CurrentIterator.Host;
4006 public ObsoleteAttribute GetObsoleteAttribute ()
4008 return GetObsoleteAttribute (Parent);
4012 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4014 public bool IsExcluded (EmitContext ec)
4016 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4017 return (caching_flags & Flags.Excluded) != 0;
4019 caching_flags &= ~Flags.Excluded_Undetected;
4021 if (base_method == null) {
4022 if (OptAttributes == null)
4025 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4030 foreach (Attribute a in attrs) {
4031 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4032 if (RootContext.AllDefines.Contains (condition))
4036 caching_flags |= Flags.Excluded;
4040 IMethodData md = TypeManager.GetMethod (base_method);
4042 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4043 caching_flags |= Flags.Excluded;
4049 if (md.IsExcluded (ec)) {
4050 caching_flags |= Flags.Excluded;
4059 public abstract class ConstructorInitializer {
4060 ArrayList argument_list;
4061 protected ConstructorInfo base_constructor;
4064 public ConstructorInitializer (ArrayList argument_list, Location loc)
4066 this.argument_list = argument_list;
4070 public ArrayList Arguments {
4072 return argument_list;
4076 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4078 Expression base_constructor_group;
4082 ec.CurrentBlock = block;
4084 if (argument_list != null){
4085 foreach (Argument a in argument_list){
4086 if (!a.Resolve (ec, loc))
4090 ec.CurrentBlock = null;
4092 if (this is ConstructorBaseInitializer) {
4093 if (ec.ContainerType.BaseType == null)
4096 t = ec.ContainerType.BaseType;
4097 if (ec.ContainerType.IsValueType) {
4098 Report.Error (522, loc,
4099 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4103 t = ec.ContainerType;
4105 base_constructor_group = Expression.MemberLookup (
4106 ec, t, ".ctor", MemberTypes.Constructor,
4107 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4110 if (base_constructor_group == null){
4112 base_constructor_group = Expression.MemberLookup (
4113 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4114 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4118 int errors = Report.Errors;
4119 if (base_constructor_group != null)
4120 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4121 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4124 if (base_constructor == null) {
4125 if (errors == Report.Errors)
4126 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4127 argument_list.Count);
4132 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4133 base_constructor = null;
4137 if (base_constructor == caller_builder){
4138 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4145 public void Emit (EmitContext ec)
4147 if (base_constructor != null){
4148 ec.Mark (loc, false);
4150 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4152 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4157 public class ConstructorBaseInitializer : ConstructorInitializer {
4158 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4159 base (argument_list, l)
4164 public class ConstructorThisInitializer : ConstructorInitializer {
4165 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4166 base (argument_list, l)
4171 public class Constructor : MethodCore, IMethodData {
4172 public ConstructorBuilder ConstructorBuilder;
4173 public ConstructorInitializer Initializer;
4174 ListDictionary declarative_security;
4177 // Modifiers allowed for a constructor.
4179 public const int AllowedModifiers =
4181 Modifiers.PROTECTED |
4182 Modifiers.INTERNAL |
4188 bool has_compliant_args = false;
4190 // The spec claims that static is not permitted, but
4191 // my very own code has static constructors.
4193 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4194 ConstructorInitializer init, Location l)
4195 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4201 public bool HasCompliantArgs {
4203 return has_compliant_args;
4207 public override AttributeTargets AttributeTargets {
4209 return AttributeTargets.Constructor;
4215 // Returns true if this is a default constructor
4217 public bool IsDefault ()
4219 if ((ModFlags & Modifiers.STATIC) != 0)
4220 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4221 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4224 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4225 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4226 (Initializer is ConstructorBaseInitializer) &&
4227 (Initializer.Arguments == null);
4230 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4232 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4233 if (declarative_security == null) {
4234 declarative_security = new ListDictionary ();
4236 a.ExtractSecurityPermissionSet (declarative_security);
4240 ConstructorBuilder.SetCustomAttribute (cb);
4243 protected override bool CheckForDuplications ()
4245 ArrayList ar = Parent.InstanceConstructors;
4247 int arLen = ar.Count;
4249 for (int i = 0; i < arLen; i++) {
4250 Constructor m = (Constructor) ar [i];
4251 if (IsDuplicateImplementation (m))
4258 protected override bool CheckBase ()
4260 // Check whether arguments were correct.
4261 if (!DoDefineParameters ())
4264 // TODO: skip the rest for generated ctor
4265 if ((ModFlags & Modifiers.STATIC) != 0)
4268 if (!CheckForDuplications ())
4271 if (Parent.Kind == Kind.Struct) {
4272 if (ParameterTypes.Length == 0) {
4273 Report.Error (568, Location,
4274 "Structs cannot contain explicit parameterless constructors");
4278 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4279 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4284 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4285 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4292 // Creates the ConstructorBuilder
4294 public override bool Define ()
4296 if (ConstructorBuilder != null)
4299 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4300 MethodAttributes.SpecialName);
4302 if ((ModFlags & Modifiers.STATIC) != 0) {
4303 ca |= MethodAttributes.Static | MethodAttributes.Private;
4305 ca |= MethodAttributes.HideBySig;
4307 if ((ModFlags & Modifiers.PUBLIC) != 0)
4308 ca |= MethodAttributes.Public;
4309 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4310 if ((ModFlags & Modifiers.INTERNAL) != 0)
4311 ca |= MethodAttributes.FamORAssem;
4313 ca |= MethodAttributes.Family;
4314 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4315 ca |= MethodAttributes.Assembly;
4316 else if (IsDefault ())
4317 ca |= MethodAttributes.Public;
4319 ca |= MethodAttributes.Private;
4322 if (!CheckAbstractAndExtern (block != null))
4325 // Check if arguments were correct.
4329 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4330 ca, CallingConventions,
4333 if ((ModFlags & Modifiers.UNSAFE) != 0)
4334 ConstructorBuilder.InitLocals = false;
4336 TypeManager.AddMethod (ConstructorBuilder, this);
4339 // HACK because System.Reflection.Emit is lame
4341 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4349 public override void Emit ()
4351 EmitContext ec = CreateEmitContext (null, null);
4353 // If this is a non-static `struct' constructor and doesn't have any
4354 // initializer, it must initialize all of the struct's fields.
4355 if ((Parent.Kind == Kind.Struct) &&
4356 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4357 Block.AddThisVariable (Parent, Location);
4360 block.ResolveMeta (ec, ParameterInfo);
4362 if ((ModFlags & Modifiers.STATIC) == 0){
4363 if (Parent.Kind == Kind.Class && Initializer == null)
4364 Initializer = new ConstructorBaseInitializer (null, Location);
4368 // Spec mandates that Initializers will not have
4372 if ((Initializer != null) &&
4373 !Initializer.Resolve (ConstructorBuilder, block, ec))
4375 ec.IsStatic = false;
4378 Parameters.LabelParameters (ec, ConstructorBuilder);
4380 SourceMethod source = SourceMethod.Create (
4381 Parent, ConstructorBuilder, block);
4384 // Classes can have base initializers and instance field initializers.
4386 if (Parent.Kind == Kind.Class){
4387 if ((ModFlags & Modifiers.STATIC) == 0){
4390 // If we use a "this (...)" constructor initializer, then
4391 // do not emit field initializers, they are initialized in the other constructor
4393 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4394 Parent.EmitFieldInitializers (ec);
4397 if (Initializer != null) {
4398 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4399 ec.TestObsoleteMethodUsage = false;
4401 Initializer.Emit (ec);
4404 if ((ModFlags & Modifiers.STATIC) != 0)
4405 Parent.EmitFieldInitializers (ec);
4407 if (OptAttributes != null)
4408 OptAttributes.Emit (ec, this);
4410 ec.EmitTopBlock (this, block, ParameterInfo);
4413 source.CloseMethod ();
4417 if (declarative_security != null) {
4418 foreach (DictionaryEntry de in declarative_security) {
4419 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4426 // Is never override
4427 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4432 public override string GetSignatureForError()
4434 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4437 protected override bool VerifyClsCompliance (DeclSpace ds)
4439 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4443 if (parameter_types.Length > 0) {
4444 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4446 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4448 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4449 foreach (Type param in parameter_types) {
4450 if (param.IsArray) {
4456 has_compliant_args = true;
4460 #region IMethodData Members
4462 public System.Reflection.CallingConventions CallingConventions {
4464 CallingConventions cc = Parameters.GetCallingConvention ();
4466 if (Parent.Kind == Kind.Class)
4467 if ((ModFlags & Modifiers.STATIC) == 0)
4468 cc |= CallingConventions.HasThis;
4470 // FIXME: How is `ExplicitThis' used in C#?
4476 public new Location Location {
4478 return base.Location;
4482 public MemberName MethodName {
4488 public Type ReturnType {
4494 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4496 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4497 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4500 public ObsoleteAttribute GetObsoleteAttribute ()
4502 return GetObsoleteAttribute (Parent);
4505 public bool IsExcluded(EmitContext ec)
4514 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4516 public interface IMethodData
4518 CallingConventions CallingConventions { get; }
4519 Location Location { get; }
4520 MemberName MethodName { get; }
4521 Type[] ParameterTypes { get; }
4522 Type ReturnType { get; }
4524 Attributes OptAttributes { get; }
4525 ToplevelBlock Block { get; set; }
4527 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4528 ObsoleteAttribute GetObsoleteAttribute ();
4529 string GetSignatureForError ();
4530 bool IsExcluded (EmitContext ec);
4531 bool IsClsCompliaceRequired (DeclSpace ds);
4532 void SetMemberIsUsed ();
4536 // Encapsulates most of the Method's state
4538 public class MethodData {
4540 readonly IMethodData method;
4543 // The return type of this method
4545 public readonly InternalParameters ParameterInfo;
4548 // Are we implementing an interface ?
4550 public MethodInfo implementing;
4555 protected MemberBase member;
4556 protected int modifiers;
4557 protected MethodAttributes flags;
4559 MethodBuilder builder = null;
4560 public MethodBuilder MethodBuilder {
4566 public MethodData (MemberBase member, InternalParameters parameters,
4567 int modifiers, MethodAttributes flags, IMethodData method)
4569 this.member = member;
4570 this.ParameterInfo = parameters;
4571 this.modifiers = modifiers;
4574 this.method = method;
4577 public bool Define (TypeContainer container)
4579 string name = method.MethodName.Name;
4580 string method_name = name;
4582 Type[] ParameterTypes = method.ParameterTypes;
4584 if (container.Pending != null){
4585 if (member is Indexer) // TODO: test it, but it should work without this IF
4586 implementing = container.Pending.IsInterfaceIndexer (
4587 member.InterfaceType, method.ReturnType, ParameterInfo);
4589 implementing = container.Pending.IsInterfaceMethod (
4590 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4592 if (member.InterfaceType != null){
4593 if (implementing == null){
4594 if (member is PropertyBase) {
4595 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4596 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4597 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4600 Report.Error (539, method.Location,
4601 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4602 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4606 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4607 Report.SymbolRelatedToPreviousError (implementing);
4608 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4609 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4612 method_name = member.InterfaceType.FullName + "." + name;
4614 if (implementing != null) {
4615 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4616 if (prop_method != null) {
4617 if (!implementing.IsSpecialName) {
4618 Report.SymbolRelatedToPreviousError (implementing);
4619 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4620 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4623 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4624 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4625 Report.SymbolRelatedToPreviousError (implementing);
4626 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4627 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4636 // For implicit implementations, make sure we are public, for
4637 // explicit implementations, make sure we are private.
4639 if (implementing != null){
4641 // Setting null inside this block will trigger a more
4642 // verbose error reporting for missing interface implementations
4644 // The "candidate" function has been flagged already
4645 // but it wont get cleared
4647 if (member.IsExplicitImpl){
4648 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4649 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4650 implementing = null;
4652 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4653 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4655 // If this is an interface method implementation,
4656 // check for public accessibility
4658 implementing = null;
4659 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4660 // We may never be private.
4661 implementing = null;
4662 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4664 // We may be protected if we're overriding something.
4666 implementing = null;
4671 // Static is not allowed
4673 if ((modifiers & Modifiers.STATIC) != 0){
4674 implementing = null;
4679 // If implementing is still valid, set flags
4681 if (implementing != null){
4683 // When implementing interface methods, set NewSlot
4684 // unless, we are overwriting a method.
4686 if (implementing.DeclaringType.IsInterface){
4687 if ((modifiers & Modifiers.OVERRIDE) == 0)
4688 flags |= MethodAttributes.NewSlot;
4691 MethodAttributes.Virtual |
4692 MethodAttributes.HideBySig;
4694 // Set Final unless we're virtual, abstract or already overriding a method.
4695 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4696 flags |= MethodAttributes.Final;
4699 EmitContext ec = method.CreateEmitContext (container, null);
4701 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4703 if (builder == null)
4706 if ((modifiers & Modifiers.UNSAFE) != 0)
4707 builder.InitLocals = false;
4709 if (implementing != null){
4711 // clear the pending implemntation flag
4713 if (member is Indexer) {
4714 container.Pending.ImplementIndexer (
4715 member.InterfaceType, builder, method.ReturnType,
4716 ParameterInfo, member.IsExplicitImpl);
4718 container.Pending.ImplementMethod (
4719 member.InterfaceType, name, method.ReturnType,
4720 ParameterInfo, member.IsExplicitImpl);
4722 if (member.IsExplicitImpl)
4723 container.TypeBuilder.DefineMethodOverride (
4724 builder, implementing);
4728 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4729 TypeManager.AddMethod (builder, method);
4736 /// Create the MethodBuilder for the method
4738 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4740 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4742 if ((modifiers & extern_static) == extern_static) {
4744 if (method.OptAttributes != null) {
4745 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4746 if (dllimport_attribute != null) {
4747 flags |= MethodAttributes.PinvokeImpl;
4748 builder = dllimport_attribute.DefinePInvokeMethod (
4749 ec, container.TypeBuilder, method_name, flags,
4750 method.ReturnType, ParameterTypes);
4756 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4757 // We are more strict than Microsoft and report CS0626 like error
4758 if (method.OptAttributes == null ||
4759 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4760 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",
4761 method.GetSignatureForError ());
4766 builder = container.TypeBuilder.DefineMethod (
4767 method_name, flags, method.CallingConventions,
4768 method.ReturnType, ParameterTypes);
4774 public void Emit (TypeContainer container, Attributable kind)
4777 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4778 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4780 ec = method.CreateEmitContext (container, null);
4782 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
4783 ec.TestObsoleteMethodUsage = false;
4785 Attributes OptAttributes = method.OptAttributes;
4787 if (OptAttributes != null)
4788 OptAttributes.Emit (ec, kind);
4790 if (member is MethodCore)
4791 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
4793 ToplevelBlock block = method.Block;
4795 SourceMethod source = SourceMethod.Create (
4796 container, MethodBuilder, method.Block);
4799 // Handle destructors specially
4801 // FIXME: This code generates buggy code
4803 if (member is Destructor)
4804 EmitDestructor (ec, block);
4806 ec.EmitTopBlock (method, block, ParameterInfo);
4809 source.CloseMethod ();
4812 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4814 ILGenerator ig = ec.ig;
4816 Label finish = ig.DefineLabel ();
4818 block.SetDestructor ();
4820 ig.BeginExceptionBlock ();
4821 ec.ReturnLabel = finish;
4822 ec.HasReturnLabel = true;
4823 ec.EmitTopBlock (method, block, null);
4825 // ig.MarkLabel (finish);
4826 ig.BeginFinallyBlock ();
4828 if (ec.ContainerType.BaseType != null) {
4829 Expression member_lookup = Expression.MemberLookup (
4830 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4831 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4833 if (member_lookup != null){
4834 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4836 ig.Emit (OpCodes.Ldarg_0);
4837 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4841 ig.EndExceptionBlock ();
4842 //ig.MarkLabel (ec.ReturnLabel);
4843 ig.Emit (OpCodes.Ret);
4847 // TODO: Should derive from MethodCore
4848 public class Destructor : Method {
4850 public Destructor (TypeContainer ds, Expression return_type, int mod,
4851 string name, Parameters parameters, Attributes attrs,
4853 : base (ds, return_type, mod, false, new MemberName (name),
4854 parameters, attrs, l)
4857 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4859 if (a.Type == TypeManager.conditional_attribute_type) {
4860 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4861 GetSignatureForError ());
4865 base.ApplyAttributeBuilder (a, cb);
4868 public override string GetSignatureForError ()
4870 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
4875 abstract public class MemberBase : MemberCore {
4876 public Expression Type;
4878 public MethodAttributes flags;
4880 protected readonly int explicit_mod_flags;
4883 // The "short" name of this property / indexer / event. This is the
4884 // name without the explicit interface.
4886 public string ShortName {
4887 get { return MemberName.Name; }
4889 SetMemberName (new MemberName (MemberName.Left, value));
4894 // The type of this property / indexer / event
4897 public Type MemberType {
4899 if (member_type == null && Type != null) {
4900 EmitContext ec = Parent.EmitContext;
4901 bool old_unsafe = ec.InUnsafe;
4902 ec.InUnsafe = InUnsafe;
4903 Type = Type.ResolveAsTypeTerminal (ec, false);
4904 ec.InUnsafe = old_unsafe;
4906 member_type = Type == null ? null : Type.Type;
4913 // Whether this is an interface member.
4915 public bool IsInterface;
4918 // If true, this is an explicit interface implementation
4920 public bool IsExplicitImpl;
4923 // The interface type we are explicitly implementing
4925 public Type InterfaceType = null;
4928 // The constructor is only exposed to our children
4930 protected MemberBase (TypeContainer parent, Expression type, int mod,
4931 int allowed_mod, int def_mod, MemberName name,
4932 Attributes attrs, Location loc)
4933 : base (parent, name, attrs, loc)
4935 explicit_mod_flags = mod;
4937 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4938 IsExplicitImpl = (MemberName.Left != null);
4941 protected virtual bool CheckBase ()
4943 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4944 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4948 if ((RootContext.WarningLevel >= 4) &&
4949 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4950 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4951 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4952 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4957 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4961 foreach (Type partype in parameters){
4962 if (partype == TypeManager.void_type) {
4964 1547, Location, "Keyword 'void' cannot " +
4965 "be used in this context");
4969 if (partype.IsPointer){
4972 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4976 if (ds.AsAccessible (partype, ModFlags))
4979 if (this is Indexer)
4980 Report.Error (55, Location,
4981 "Inconsistent accessibility: parameter type `" +
4982 TypeManager.CSharpName (partype) + "' is less " +
4983 "accessible than indexer `" + GetSignatureForError () + "'");
4984 else if ((this is Method) && ((Method) this).IsOperator != null)
4985 Report.Error (57, Location,
4986 "Inconsistent accessibility: parameter type `" +
4987 TypeManager.CSharpName (partype) + "' is less " +
4988 "accessible than operator `" + GetSignatureForError () + "'");
4990 Report.Error (51, Location,
4991 "Inconsistent accessibility: parameter type `" +
4992 TypeManager.CSharpName (partype) + "' is less " +
4993 "accessible than method `" + GetSignatureForError () + "'");
5000 protected virtual bool DoDefine ()
5002 EmitContext ec = Parent.EmitContext;
5004 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5007 throw new InternalErrorException ();
5010 ModFlags = Modifiers.PUBLIC |
5011 Modifiers.ABSTRACT |
5012 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5014 flags = MethodAttributes.Public |
5015 MethodAttributes.Abstract |
5016 MethodAttributes.HideBySig |
5017 MethodAttributes.NewSlot |
5018 MethodAttributes.Virtual;
5020 if (!Parent.MethodModifiersValid (this))
5023 flags = Modifiers.MethodAttr (ModFlags);
5026 if (MemberType == null)
5029 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5030 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5031 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5032 GetSignatureForError (), Parent.GetSignatureForError ());
5036 // verify accessibility
5037 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5038 Report.SymbolRelatedToPreviousError (MemberType);
5039 if (this is Property)
5040 Report.Error (53, Location,
5041 "Inconsistent accessibility: property type `" +
5042 TypeManager.CSharpName (MemberType) + "' is less " +
5043 "accessible than property `" + GetSignatureForError () + "'");
5044 else if (this is Indexer)
5045 Report.Error (54, Location,
5046 "Inconsistent accessibility: indexer return type `" +
5047 TypeManager.CSharpName (MemberType) + "' is less " +
5048 "accessible than indexer `" + GetSignatureForError () + "'");
5049 else if (this is MethodCore) {
5050 if (this is Operator)
5051 Report.Error (56, Location,
5052 "Inconsistent accessibility: return type `" +
5053 TypeManager.CSharpName (MemberType) + "' is less " +
5054 "accessible than operator `" + GetSignatureForError () + "'");
5056 Report.Error (50, Location,
5057 "Inconsistent accessibility: return type `" +
5058 TypeManager.CSharpName (MemberType) + "' is less " +
5059 "accessible than method `" + GetSignatureForError () + "'");
5061 Report.Error (52, Location,
5062 "Inconsistent accessibility: field type `" +
5063 TypeManager.CSharpName (MemberType) + "' is less " +
5064 "accessible than field `" + GetSignatureForError () + "'");
5069 if (MemberType.IsPointer && !UnsafeOK (Parent))
5072 if (IsExplicitImpl) {
5073 Expression expr = MemberName.Left.GetTypeExpression (Location);
5074 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5078 InterfaceType = texpr.ResolveType (ec);
5080 if (!InterfaceType.IsInterface) {
5081 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5085 if (!Parent.VerifyImplements (this))
5088 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5094 protected bool IsTypePermitted ()
5096 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5097 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5103 protected override bool VerifyClsCompliance(DeclSpace ds)
5105 if (base.VerifyClsCompliance (ds)) {
5109 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5110 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5115 protected override void VerifyObsoleteAttribute()
5117 CheckUsageOfObsoleteAttribute (MemberType);
5122 // Fields and Events both generate FieldBuilders, we use this to share
5123 // their common bits. This is also used to flag usage of the field
5125 abstract public class FieldBase : MemberBase {
5126 public FieldBuilder FieldBuilder;
5127 public Status status;
5130 public enum Status : byte {
5131 HAS_OFFSET = 4 // Used by FieldMember.
5134 static string[] attribute_targets = new string [] { "field" };
5137 /// Symbol with same name in base class/struct
5139 public MemberInfo conflict_symbol;
5142 // The constructor is only exposed to our children
5144 protected FieldBase (TypeContainer parent, Expression type, int mod,
5145 int allowed_mod, MemberName name, object init,
5146 Attributes attrs, Location loc)
5147 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5153 public override AttributeTargets AttributeTargets {
5155 return AttributeTargets.Field;
5159 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5161 if (a.Type == TypeManager.marshal_as_attr_type) {
5162 UnmanagedMarshal marshal = a.GetMarshal (this);
5163 if (marshal != null) {
5164 FieldBuilder.SetMarshal (marshal);
5169 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5170 a.Error_InvalidSecurityParent ();
5174 FieldBuilder.SetCustomAttribute (cb);
5178 // Whether this field has an initializer.
5180 public bool HasInitializer {
5182 return init != null;
5186 protected readonly Object init;
5189 Expression init_expr;
5190 bool init_expr_initialized = false;
5193 // Resolves and returns the field initializer.
5195 public Expression GetInitializerExpression (EmitContext ec)
5197 if (init_expr_initialized)
5201 if (init is Expression)
5202 e = (Expression) init;
5204 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5206 // TODO: Any reason why we are using parent EC ?
5207 EmitContext parent_ec = Parent.EmitContext;
5209 bool old_is_static = parent_ec.IsStatic;
5210 bool old_is_ctor = parent_ec.IsConstructor;
5211 parent_ec.IsStatic = ec.IsStatic;
5212 parent_ec.IsConstructor = ec.IsConstructor;
5213 parent_ec.IsFieldInitializer = true;
5214 e = e.DoResolve (parent_ec);
5215 parent_ec.IsFieldInitializer = false;
5216 parent_ec.IsStatic = old_is_static;
5217 parent_ec.IsConstructor = old_is_ctor;
5220 init_expr_initialized = true;
5225 protected override bool CheckBase ()
5227 if (!base.CheckBase ())
5234 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5235 if (conflict_symbol == null) {
5236 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5237 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5242 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5243 Report.SymbolRelatedToPreviousError (conflict_symbol);
5244 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5245 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5251 protected virtual bool IsFieldClsCompliant {
5253 if (FieldBuilder == null)
5256 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5260 public override string[] ValidAttributeTargets {
5262 return attribute_targets;
5266 protected override bool VerifyClsCompliance (DeclSpace ds)
5268 if (!base.VerifyClsCompliance (ds))
5271 if (!IsFieldClsCompliant) {
5272 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5278 public void SetAssigned ()
5280 caching_flags |= Flags.IsAssigned;
5284 public abstract class FieldMember: FieldBase
5286 protected FieldMember (TypeContainer parent, Expression type, int mod,
5287 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5288 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5290 if ((mod & Modifiers.ABSTRACT) != 0)
5291 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5294 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5296 if (a.Type == TypeManager.field_offset_attribute_type)
5298 status |= Status.HAS_OFFSET;
5300 if (!Parent.HasExplicitLayout) {
5301 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5305 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5306 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5312 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5313 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5318 base.ApplyAttributeBuilder (a, cb);
5322 public override bool Define()
5324 EmitContext ec = Parent.EmitContext;
5326 throw new InternalErrorException ("FieldMember.Define called too early");
5328 if (MemberType == null)
5331 if (MemberType == TypeManager.void_type) {
5332 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5339 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5340 Report.Error (52, Location,
5341 "Inconsistent accessibility: field type `" +
5342 TypeManager.CSharpName (MemberType) + "' is less " +
5343 "accessible than field `" + GetSignatureForError () + "'");
5347 if (!IsTypePermitted ())
5350 if (MemberType.IsPointer && !UnsafeOK (Parent))
5356 public override void Emit ()
5358 if (OptAttributes != null) {
5359 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5360 OptAttributes.Emit (ec, this);
5363 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5364 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5371 // Represents header string for documentation comment.
5373 public override string DocCommentHeader {
5374 get { return "F:"; }
5378 interface IFixedBuffer
5380 FieldInfo Element { get; }
5381 Type ElementType { get; }
5384 public class FixedFieldExternal: IFixedBuffer
5386 FieldInfo element_field;
5388 public FixedFieldExternal (FieldInfo fi)
5390 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5393 #region IFixedField Members
5395 public FieldInfo Element {
5397 return element_field;
5401 public Type ElementType {
5403 return element_field.FieldType;
5411 /// Fixed buffer implementation
5413 public class FixedField: FieldMember, IFixedBuffer
5415 public const string FixedElementName = "FixedElementField";
5416 static int GlobalCounter = 0;
5417 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5418 static FieldInfo[] fi;
5420 TypeBuilder fixed_buffer_type;
5421 FieldBuilder element;
5422 Expression size_expr;
5425 const int AllowedModifiers =
5428 Modifiers.PROTECTED |
5429 Modifiers.INTERNAL |
5432 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5433 Expression size_expr, Attributes attrs, Location loc):
5434 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5436 if (RootContext.Version == LanguageVersion.ISO_1)
5437 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5439 this.size_expr = size_expr;
5442 public override bool Define()
5445 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5446 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5449 if (Parent.Kind != Kind.Struct) {
5450 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5451 GetSignatureForError ());
5455 if (!base.Define ())
5458 if (!TypeManager.IsPrimitiveType (MemberType)) {
5459 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",
5460 GetSignatureForError ());
5464 Expression e = size_expr.Resolve (Parent.EmitContext);
5468 Constant c = e as Constant;
5470 Const.Error_ExpressionMustBeConstant (e.Location, GetSignatureForError ());
5474 IntConstant buffer_size_const = c.ToInt (Location);
5475 if (buffer_size_const == null)
5478 buffer_size = buffer_size_const.Value;
5480 if (buffer_size <= 0) {
5481 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5485 int type_size = Expression.GetTypeSize (MemberType);
5487 if (buffer_size > int.MaxValue / type_size) {
5488 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5489 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5493 buffer_size *= type_size;
5496 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5498 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5499 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5500 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5501 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5503 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5504 TypeManager.RegisterFieldBase (FieldBuilder, this);
5509 public override void Emit()
5512 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5514 object[] fi_val = new object[1];
5515 fi_val [0] = buffer_size;
5517 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5518 ctor_args, fi, fi_val);
5519 fixed_buffer_type.SetCustomAttribute (cab);
5522 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5523 FieldBuilder.SetCustomAttribute (cab);
5528 protected override bool IsFieldClsCompliant {
5534 #region IFixedField Members
5536 public FieldInfo Element {
5542 public Type ElementType {
5552 // The Field class is used to represents class/struct fields during parsing.
5554 public class Field : FieldMember {
5556 // Modifiers allowed in a class declaration
5558 const int AllowedModifiers =
5561 Modifiers.PROTECTED |
5562 Modifiers.INTERNAL |
5565 Modifiers.VOLATILE |
5569 public Field (TypeContainer parent, Expression type, int mod, string name,
5570 Object expr_or_array_init, Attributes attrs, Location loc)
5571 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5572 expr_or_array_init, attrs, loc)
5576 public override bool Define ()
5578 if (!base.Define ())
5581 if (RootContext.WarningLevel > 1){
5582 Type ptype = Parent.TypeBuilder.BaseType;
5584 // ptype is only null for System.Object while compiling corlib.
5586 TypeContainer.FindMembers (
5587 ptype, MemberTypes.Method,
5588 BindingFlags.Public |
5589 BindingFlags.Static | BindingFlags.Instance,
5590 System.Type.FilterName, Name);
5594 if ((ModFlags & Modifiers.VOLATILE) != 0){
5595 if (!MemberType.IsClass){
5596 Type vt = MemberType;
5598 if (TypeManager.IsEnumType (vt))
5599 vt = TypeManager.EnumToUnderlying (MemberType);
5601 if (!((vt == TypeManager.bool_type) ||
5602 (vt == TypeManager.sbyte_type) ||
5603 (vt == TypeManager.byte_type) ||
5604 (vt == TypeManager.short_type) ||
5605 (vt == TypeManager.ushort_type) ||
5606 (vt == TypeManager.int32_type) ||
5607 (vt == TypeManager.uint32_type) ||
5608 (vt == TypeManager.char_type) ||
5609 (vt == TypeManager.float_type) ||
5610 (!vt.IsValueType))){
5611 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5612 GetSignatureForError (), TypeManager.CSharpName (vt));
5617 if ((ModFlags & Modifiers.READONLY) != 0){
5618 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5619 GetSignatureForError ());
5624 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5626 if (Parent.Kind == Kind.Struct &&
5627 ((fa & FieldAttributes.Static) == 0) &&
5628 MemberType == Parent.TypeBuilder &&
5629 !TypeManager.IsBuiltinType (MemberType)){
5630 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5631 "' causes a cycle in the structure layout");
5636 FieldBuilder = Parent.TypeBuilder.DefineField (
5637 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5639 TypeManager.RegisterFieldBase (FieldBuilder, this);
5641 catch (ArgumentException) {
5642 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5649 protected override bool VerifyClsCompliance (DeclSpace ds)
5651 if (!base.VerifyClsCompliance (ds))
5654 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5655 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5663 // `set' and `get' accessors are represented with an Accessor.
5665 public class Accessor : IIteratorContainer {
5667 // Null if the accessor is empty, or a Block if not
5669 public const int AllowedModifiers =
5671 Modifiers.PROTECTED |
5672 Modifiers.INTERNAL |
5675 public ToplevelBlock Block;
5676 public Attributes Attributes;
5677 public Location Location;
5678 public int ModFlags;
5681 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5686 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5689 public void SetYields ()
5695 // Ooouh Martin, templates are missing here.
5696 // When it will be possible move here a lot of child code and template method type.
5697 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5698 protected MethodData method_data;
5699 protected ToplevelBlock block;
5700 protected ListDictionary declarative_security;
5702 // The accessor are created event if they are not wanted.
5703 // But we need them because their names are reserved.
5704 // Field says whether accessor will be emited or not
5705 public readonly bool IsDummy;
5707 protected readonly string prefix;
5709 ReturnParameter return_attributes;
5711 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5712 : base (null, SetupName (prefix, member), null, member.Location)
5714 this.prefix = prefix;
5718 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5720 : base (null, SetupName (prefix, member),
5721 accessor.Attributes, accessor.Location)
5723 this.prefix = prefix;
5724 this.block = accessor.Block;
5727 static MemberName SetupName (string prefix, MemberBase member)
5729 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
5732 public void UpdateName (MemberBase member)
5734 SetMemberName (SetupName (prefix, member));
5737 #region IMethodData Members
5739 public ToplevelBlock Block {
5749 public CallingConventions CallingConventions {
5751 return CallingConventions.Standard;
5755 public bool IsExcluded (EmitContext ec)
5760 public MemberName MethodName {
5766 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5767 public abstract Type[] ParameterTypes { get; }
5768 public abstract Type ReturnType { get; }
5769 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5773 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5775 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5776 a.Type == TypeManager.conditional_attribute_type) {
5777 Report.Error (1667, a.Location,
5778 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5779 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5783 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5784 if (declarative_security == null)
5785 declarative_security = new ListDictionary ();
5786 a.ExtractSecurityPermissionSet (declarative_security);
5790 if (a.Target == AttributeTargets.Method) {
5791 method_data.MethodBuilder.SetCustomAttribute (cb);
5795 if (a.Target == AttributeTargets.ReturnValue) {
5796 if (return_attributes == null)
5797 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5799 return_attributes.ApplyAttributeBuilder (a, cb);
5803 ApplyToExtraTarget (a, cb);
5806 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5808 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5811 public override bool Define()
5813 throw new NotSupportedException ();
5816 public virtual void Emit (TypeContainer container)
5818 EmitMethod (container);
5820 if (declarative_security != null) {
5821 foreach (DictionaryEntry de in declarative_security) {
5822 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5829 protected virtual void EmitMethod (TypeContainer container)
5831 method_data.Emit (container, this);
5834 public override bool IsClsCompliaceRequired(DeclSpace ds)
5839 public bool IsDuplicateImplementation (MethodCore method)
5841 if (!MemberName.Equals (method.MemberName))
5844 Type[] param_types = method.ParameterTypes;
5846 if (param_types.Length != ParameterTypes.Length)
5849 for (int i = 0; i < param_types.Length; i++)
5850 if (param_types [i] != ParameterTypes [i])
5853 Report.SymbolRelatedToPreviousError (method);
5854 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
5858 public override bool IsUsed
5868 public new Location Location {
5870 return base.Location;
5875 // Represents header string for documentation comment.
5877 public override string DocCommentHeader {
5878 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5881 protected override void VerifyObsoleteAttribute()
5888 // Properties and Indexers both generate PropertyBuilders, we use this to share
5889 // their common bits.
5891 abstract public class PropertyBase : MethodCore {
5893 public class GetMethod: PropertyMethod
5895 static string[] attribute_targets = new string [] { "method", "return" };
5897 public GetMethod (MethodCore method):
5898 base (method, "get_")
5902 public GetMethod (MethodCore method, Accessor accessor):
5903 base (method, accessor, "get_")
5907 public override MethodBuilder Define(TypeContainer container)
5909 base.Define (container);
5911 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5913 if (!method_data.Define (container))
5916 return method_data.MethodBuilder;
5919 public override Type ReturnType {
5921 return method.MemberType;
5925 public override string[] ValidAttributeTargets {
5927 return attribute_targets;
5932 public class SetMethod: PropertyMethod {
5934 static string[] attribute_targets = new string [] { "method", "param", "return" };
5935 ImplicitParameter param_attr;
5937 public SetMethod (MethodCore method):
5938 base (method, "set_")
5942 public SetMethod (MethodCore method, Accessor accessor):
5943 base (method, accessor, "set_")
5947 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5949 if (a.Target == AttributeTargets.Parameter) {
5950 if (param_attr == null)
5951 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
5953 param_attr.ApplyAttributeBuilder (a, cb);
5957 base.ApplyAttributeBuilder (a, cb);
5960 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5962 Parameter [] parms = new Parameter [1];
5963 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
5964 Parameters parameters = new Parameters (parms, null);
5966 bool old_unsafe = ec.InUnsafe;
5967 ec.InUnsafe = InUnsafe;
5968 Type [] types = parameters.GetParameterInfo (ec);
5969 ec.InUnsafe = old_unsafe;
5971 return new InternalParameters (types, parameters);
5974 public override MethodBuilder Define (TypeContainer container)
5976 if (container.EmitContext == null)
5977 throw new InternalErrorException ("SetMethod.Define called too early");
5979 base.Define (container);
5981 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5983 if (!method_data.Define (container))
5986 return method_data.MethodBuilder;
5989 public override Type[] ParameterTypes {
5991 return new Type[] { method.MemberType };
5995 public override Type ReturnType {
5997 return TypeManager.void_type;
6001 public override string[] ValidAttributeTargets {
6003 return attribute_targets;
6008 static string[] attribute_targets = new string [] { "property" };
6010 public abstract class PropertyMethod: AbstractPropertyEventMethod
6012 protected readonly MethodCore method;
6013 protected MethodAttributes flags;
6016 public PropertyMethod (MethodCore method, string prefix)
6017 : base (method, prefix)
6019 this.method = method;
6020 Parent = method.Parent;
6023 public PropertyMethod (MethodCore method, Accessor accessor,
6025 : base (method, accessor, prefix)
6027 this.method = method;
6028 Parent = method.Parent;
6029 this.ModFlags = accessor.ModFlags;
6030 yields = accessor.Yields;
6032 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6033 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6037 public override AttributeTargets AttributeTargets {
6039 return AttributeTargets.Method;
6043 public override bool IsClsCompliaceRequired(DeclSpace ds)
6045 return method.IsClsCompliaceRequired (ds);
6048 public InternalParameters ParameterInfo
6051 return method_data.ParameterInfo;
6055 public virtual MethodBuilder Define (TypeContainer container)
6057 if (!method.CheckAbstractAndExtern (block != null))
6061 // Check for custom access modifier
6063 if (ModFlags == 0) {
6064 ModFlags = method.ModFlags;
6065 flags = method.flags;
6067 if (container.Kind == Kind.Interface)
6068 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6069 GetSignatureForError ());
6071 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6072 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6075 CheckModifiers (container, ModFlags);
6076 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6077 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6078 flags = Modifiers.MethodAttr (ModFlags);
6079 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6083 // Setup iterator if we are one
6086 Iterator iterator = new Iterator (this,
6087 Parent, method.ParameterInfo, ModFlags);
6089 if (!iterator.DefineIterator ())
6096 public bool HasCustomAccessModifier
6099 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6103 public override Type[] ParameterTypes {
6105 return TypeManager.NoTypes;
6109 public override EmitContext CreateEmitContext (TypeContainer tc,
6112 return new EmitContext (
6113 tc, method.Parent, method.Location, ig, ReturnType,
6114 method.ModFlags, false);
6117 public override ObsoleteAttribute GetObsoleteAttribute ()
6119 return method.GetObsoleteAttribute (method.Parent);
6122 public override string GetSignatureForError()
6124 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6127 void CheckModifiers (TypeContainer container, int modflags)
6130 int mflags = method.ModFlags & Modifiers.Accessibility;
6132 if ((mflags & Modifiers.PUBLIC) != 0) {
6133 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6135 else if ((mflags & Modifiers.PROTECTED) != 0) {
6136 if ((mflags & Modifiers.INTERNAL) != 0)
6137 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6139 flags |= Modifiers.PRIVATE;
6141 else if ((mflags & Modifiers.INTERNAL) != 0)
6142 flags |= Modifiers.PRIVATE;
6144 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6145 Report.Error (273, Location,
6146 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6147 GetSignatureForError (), method.GetSignatureForError ());
6151 public override bool MarkForDuplicationCheck ()
6153 caching_flags |= Flags.TestMethodDuplication;
6159 public PropertyMethod Get, Set;
6160 public PropertyBuilder PropertyBuilder;
6161 public MethodBuilder GetBuilder, SetBuilder;
6163 protected EmitContext ec;
6165 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6166 int allowed_mod, bool is_iface, MemberName name,
6167 Parameters parameters, Attributes attrs,
6169 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6170 attrs, parameters, loc)
6174 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6176 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6177 a.Error_InvalidSecurityParent ();
6181 PropertyBuilder.SetCustomAttribute (cb);
6184 public override AttributeTargets AttributeTargets {
6186 return AttributeTargets.Property;
6190 public override bool Define ()
6195 if (!IsTypePermitted ())
6201 protected override bool DoDefine ()
6203 if (!base.DoDefine ())
6207 // Accessors modifiers check
6209 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6210 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6211 GetSignatureForError ());
6215 if ((Get.IsDummy || Set.IsDummy)
6216 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6217 Report.Error (276, Location,
6218 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6219 GetSignatureForError ());
6223 if (MemberType.IsAbstract && MemberType.IsSealed) {
6224 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6228 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6232 protected override bool CheckForDuplications ()
6234 ArrayList ar = Parent.Indexers;
6236 int arLen = ar.Count;
6238 for (int i = 0; i < arLen; i++) {
6239 Indexer m = (Indexer) ar [i];
6240 if (IsDuplicateImplementation (m))
6245 ar = Parent.Properties;
6247 int arLen = ar.Count;
6249 for (int i = 0; i < arLen; i++) {
6250 Property m = (Property) ar [i];
6251 if (IsDuplicateImplementation (m))
6259 // TODO: rename to Resolve......
6260 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6262 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6263 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6265 if (base_property == null)
6268 base_ret_type = base_property.PropertyType;
6269 MethodInfo get_accessor = base_property.GetGetMethod (true);
6270 MethodInfo set_accessor = base_property.GetSetMethod (true);
6271 MethodAttributes get_accessor_access, set_accessor_access;
6273 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6274 if (Get != null && !Get.IsDummy && get_accessor == null) {
6275 Report.SymbolRelatedToPreviousError (base_property);
6276 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6279 if (Set != null && !Set.IsDummy && set_accessor == null) {
6280 Report.SymbolRelatedToPreviousError (base_property);
6281 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6286 // Check base class accessors access
6289 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6290 get_accessor_access = set_accessor_access = 0;
6291 if ((ModFlags & Modifiers.NEW) == 0) {
6292 if (get_accessor != null) {
6293 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6294 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6296 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6297 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6300 if (set_accessor != null) {
6301 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6302 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6304 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6305 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6310 // Get the less restrictive access
6312 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6315 public override void Emit ()
6318 // The PropertyBuilder can be null for explicit implementations, in that
6319 // case, we do not actually emit the ".property", so there is nowhere to
6320 // put the attribute
6322 if (PropertyBuilder != null && OptAttributes != null)
6323 OptAttributes.Emit (ec, this);
6335 /// Tests whether accessors are not in collision with some method (CS0111)
6337 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6339 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6342 public override bool IsUsed
6348 return Get.IsUsed | Set.IsUsed;
6352 protected override void SetMemberName (MemberName new_name)
6354 base.SetMemberName (new_name);
6356 Get.UpdateName (this);
6357 Set.UpdateName (this);
6360 public override string[] ValidAttributeTargets {
6362 return attribute_targets;
6367 // Represents header string for documentation comment.
6369 public override string DocCommentHeader {
6370 get { return "P:"; }
6374 public class Property : PropertyBase {
6375 const int AllowedModifiers =
6378 Modifiers.PROTECTED |
6379 Modifiers.INTERNAL |
6383 Modifiers.OVERRIDE |
6384 Modifiers.ABSTRACT |
6387 Modifiers.METHOD_YIELDS |
6390 const int AllowedInterfaceModifiers =
6393 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6394 MemberName name, Attributes attrs, Accessor get_block,
6395 Accessor set_block, Location loc)
6396 : base (ds, type, mod,
6397 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6398 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6401 if (get_block == null)
6402 Get = new GetMethod (this);
6404 Get = new GetMethod (this, get_block);
6406 if (set_block == null)
6407 Set = new SetMethod (this);
6409 Set = new SetMethod (this, set_block);
6412 public override bool Define ()
6414 if (!base.Define ())
6420 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6423 GetBuilder = Get.Define (Parent);
6424 if (GetBuilder == null)
6429 SetBuilder = Set.Define (Parent);
6430 if (SetBuilder == null)
6433 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6436 // FIXME - PropertyAttributes.HasDefault ?
6438 PropertyAttributes prop_attr = PropertyAttributes.None;
6440 prop_attr |= PropertyAttributes.RTSpecialName |
6441 PropertyAttributes.SpecialName;
6443 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6444 Name, prop_attr, MemberType, null);
6447 PropertyBuilder.SetGetMethod (GetBuilder);
6450 PropertyBuilder.SetSetMethod (SetBuilder);
6452 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6458 /// Gigantic workaround for lameness in SRE follows :
6459 /// This class derives from EventInfo and attempts to basically
6460 /// wrap around the EventBuilder so that FindMembers can quickly
6461 /// return this in it search for members
6463 public class MyEventBuilder : EventInfo {
6466 // We use this to "point" to our Builder which is
6467 // not really a MemberInfo
6469 EventBuilder MyBuilder;
6472 // We "catch" and wrap these methods
6474 MethodInfo raise, remove, add;
6476 EventAttributes attributes;
6477 Type declaring_type, reflected_type, event_type;
6482 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6484 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6486 // And now store the values in our own fields.
6488 declaring_type = type_builder;
6490 reflected_type = type_builder;
6492 attributes = event_attr;
6495 this.event_type = event_type;
6499 // Methods that you have to override. Note that you only need
6500 // to "implement" the variants that take the argument (those are
6501 // the "abstract" methods, the others (GetAddMethod()) are
6504 public override MethodInfo GetAddMethod (bool nonPublic)
6509 public override MethodInfo GetRemoveMethod (bool nonPublic)
6514 public override MethodInfo GetRaiseMethod (bool nonPublic)
6520 // These methods make "MyEventInfo" look like a Builder
6522 public void SetRaiseMethod (MethodBuilder raiseMethod)
6524 raise = raiseMethod;
6525 MyBuilder.SetRaiseMethod (raiseMethod);
6528 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6530 remove = removeMethod;
6531 MyBuilder.SetRemoveOnMethod (removeMethod);
6534 public void SetAddOnMethod (MethodBuilder addMethod)
6537 MyBuilder.SetAddOnMethod (addMethod);
6540 public void SetCustomAttribute (CustomAttributeBuilder cb)
6542 MyBuilder.SetCustomAttribute (cb);
6545 public override object [] GetCustomAttributes (bool inherit)
6547 // FIXME : There's nothing which can be seemingly done here because
6548 // we have no way of getting at the custom attribute objects of the
6553 public override object [] GetCustomAttributes (Type t, bool inherit)
6555 // FIXME : Same here !
6559 public override bool IsDefined (Type t, bool b)
6564 public override EventAttributes Attributes {
6570 public override string Name {
6576 public override Type DeclaringType {
6578 return declaring_type;
6582 public override Type ReflectedType {
6584 return reflected_type;
6588 public Type EventType {
6594 public void SetUsed ()
6596 if (my_event != null) {
6597 my_event.SetAssigned ();
6598 my_event.SetMemberIsUsed ();
6604 /// For case when event is declared like property (with add and remove accessors).
6606 public class EventProperty: Event {
6608 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6610 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6611 bool is_iface, MemberName name, Object init,
6612 Attributes attrs, Accessor add, Accessor remove,
6614 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6616 Add = new AddDelegateMethod (this, add);
6617 Remove = new RemoveDelegateMethod (this, remove);
6619 // For this event syntax we don't report error CS0067
6620 // because it is hard to do it.
6624 public override string[] ValidAttributeTargets {
6626 return attribute_targets;
6632 /// Event is declared like field.
6634 public class EventField: Event {
6636 static string[] attribute_targets = new string [] { "event", "field", "method" };
6637 static string[] attribute_targets_interface = new string[] { "event", "method" };
6639 public EventField (TypeContainer parent, Expression type, int mod_flags,
6640 bool is_iface, MemberName name, Object init,
6641 Attributes attrs, Location loc)
6642 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6644 Add = new AddDelegateMethod (this);
6645 Remove = new RemoveDelegateMethod (this);
6648 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6650 if (a.Target == AttributeTargets.Field) {
6651 FieldBuilder.SetCustomAttribute (cb);
6655 if (a.Target == AttributeTargets.Method) {
6656 Add.ApplyAttributeBuilder (a, cb);
6657 Remove.ApplyAttributeBuilder (a, cb);
6661 base.ApplyAttributeBuilder (a, cb);
6664 public override string[] ValidAttributeTargets {
6666 return IsInterface ? attribute_targets_interface : attribute_targets;
6671 public abstract class Event : FieldBase {
6673 protected sealed class AddDelegateMethod: DelegateMethod
6676 public AddDelegateMethod (Event method):
6677 base (method, "add_")
6681 public AddDelegateMethod (Event method, Accessor accessor):
6682 base (method, accessor, "add_")
6686 protected override MethodInfo DelegateMethodInfo {
6688 return TypeManager.delegate_combine_delegate_delegate;
6694 protected sealed class RemoveDelegateMethod: DelegateMethod
6696 public RemoveDelegateMethod (Event method):
6697 base (method, "remove_")
6701 public RemoveDelegateMethod (Event method, Accessor accessor):
6702 base (method, accessor, "remove_")
6706 protected override MethodInfo DelegateMethodInfo {
6708 return TypeManager.delegate_remove_delegate_delegate;
6714 public abstract class DelegateMethod: AbstractPropertyEventMethod
6716 protected readonly Event method;
6717 ImplicitParameter param_attr;
6719 static string[] attribute_targets = new string [] { "method", "param", "return" };
6721 public DelegateMethod (Event method, string prefix)
6722 : base (method, prefix)
6724 this.method = method;
6727 public DelegateMethod (Event method, Accessor accessor, string prefix)
6728 : base (method, accessor, prefix)
6730 this.method = method;
6733 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6735 if (a.Target == AttributeTargets.Parameter) {
6736 if (param_attr == null)
6737 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6739 param_attr.ApplyAttributeBuilder (a, cb);
6743 base.ApplyAttributeBuilder (a, cb);
6746 public override AttributeTargets AttributeTargets {
6748 return AttributeTargets.Method;
6752 public override bool IsClsCompliaceRequired(DeclSpace ds)
6754 return method.IsClsCompliaceRequired (ds);
6757 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6759 method_data = new MethodData (method, ip, method.ModFlags,
6760 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6762 if (!method_data.Define (container))
6765 MethodBuilder mb = method_data.MethodBuilder;
6766 mb.DefineParameter (1, ParameterAttributes.None, "value");
6771 protected override void EmitMethod (TypeContainer tc)
6773 if (block != null) {
6774 base.EmitMethod (tc);
6778 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6781 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6782 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6784 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6785 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6786 ig.Emit (OpCodes.Ldsfld, field_info);
6787 ig.Emit (OpCodes.Ldarg_0);
6788 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6789 ig.Emit (OpCodes.Castclass, method.MemberType);
6790 ig.Emit (OpCodes.Stsfld, field_info);
6792 ig.Emit (OpCodes.Ldarg_0);
6793 ig.Emit (OpCodes.Ldarg_0);
6794 ig.Emit (OpCodes.Ldfld, field_info);
6795 ig.Emit (OpCodes.Ldarg_1);
6796 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6797 ig.Emit (OpCodes.Castclass, method.MemberType);
6798 ig.Emit (OpCodes.Stfld, field_info);
6800 ig.Emit (OpCodes.Ret);
6803 protected abstract MethodInfo DelegateMethodInfo { get; }
6805 public override Type[] ParameterTypes {
6807 return new Type[] { method.MemberType };
6811 public override Type ReturnType {
6813 return TypeManager.void_type;
6817 public override EmitContext CreateEmitContext (TypeContainer tc,
6820 return new EmitContext (
6821 tc, method.Parent, Location, ig, ReturnType,
6822 method.ModFlags, false);
6825 public override ObsoleteAttribute GetObsoleteAttribute ()
6827 return method.GetObsoleteAttribute (method.Parent);
6830 public override string[] ValidAttributeTargets {
6832 return attribute_targets;
6838 const int AllowedModifiers =
6841 Modifiers.PROTECTED |
6842 Modifiers.INTERNAL |
6847 Modifiers.OVERRIDE |
6851 const int AllowedInterfaceModifiers =
6854 public DelegateMethod Add, Remove;
6855 public MyEventBuilder EventBuilder;
6856 public MethodBuilder AddBuilder, RemoveBuilder;
6858 public Event (TypeContainer parent, Expression type, int mod_flags,
6859 bool is_iface, MemberName name, Object init, Attributes attrs,
6861 : base (parent, type, mod_flags,
6862 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6863 name, init, attrs, loc)
6865 IsInterface = is_iface;
6868 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6870 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6871 a.Error_InvalidSecurityParent ();
6875 EventBuilder.SetCustomAttribute (cb);
6878 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6880 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6883 public override AttributeTargets AttributeTargets {
6885 return AttributeTargets.Event;
6889 public override bool Define ()
6891 EventAttributes e_attr;
6892 e_attr = EventAttributes.None;
6897 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6898 Report.Error (74, Location, "`" + GetSignatureForError () +
6899 "': abstract event cannot have an initializer");
6903 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6904 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
6908 EmitContext ec = Parent.EmitContext;
6910 throw new InternalErrorException ("Event.Define called too early?");
6911 bool old_unsafe = ec.InUnsafe;
6912 ec.InUnsafe = InUnsafe;
6914 Parameter [] parms = new Parameter [1];
6915 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
6916 Parameters parameters = new Parameters (parms, null);
6917 Type [] types = parameters.GetParameterInfo (ec);
6918 InternalParameters ip = new InternalParameters (types, parameters);
6920 ec.InUnsafe = old_unsafe;
6926 // Now define the accessors
6929 AddBuilder = Add.Define (Parent, ip);
6930 if (AddBuilder == null)
6933 RemoveBuilder = Remove.Define (Parent, ip);
6934 if (RemoveBuilder == null)
6937 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6939 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6940 FieldBuilder = Parent.TypeBuilder.DefineField (
6942 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6943 TypeManager.RegisterPrivateFieldOfEvent (
6944 (EventInfo) EventBuilder, FieldBuilder);
6945 TypeManager.RegisterFieldBase (FieldBuilder, this);
6948 EventBuilder.SetAddOnMethod (AddBuilder);
6949 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6951 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6955 protected override bool CheckBase ()
6957 if (!base.CheckBase ())
6960 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6961 if (!(conflict_symbol is EventInfo)) {
6962 Report.SymbolRelatedToPreviousError (conflict_symbol);
6963 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
6971 public override void Emit ()
6973 if (OptAttributes != null) {
6974 EmitContext ec = new EmitContext (
6975 Parent, Location, null, MemberType, ModFlags);
6976 OptAttributes.Emit (ec, this);
6980 Remove.Emit (Parent);
6985 public override string GetSignatureForError ()
6987 return base.GetSignatureForError ();
6991 // Represents header string for documentation comment.
6993 public override string DocCommentHeader {
6994 get { return "E:"; }
6999 public class Indexer : PropertyBase {
7001 class GetIndexerMethod: GetMethod
7003 public GetIndexerMethod (MethodCore method):
7008 public GetIndexerMethod (MethodCore method, Accessor accessor):
7009 base (method, accessor)
7013 public override Type[] ParameterTypes {
7015 return method.ParameterTypes;
7020 class SetIndexerMethod: SetMethod
7022 readonly Parameters parameters;
7024 public SetIndexerMethod (MethodCore method):
7029 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7030 base (method, accessor)
7032 this.parameters = parameters;
7035 public override Type[] ParameterTypes {
7037 int top = method.ParameterTypes.Length;
7038 Type [] set_pars = new Type [top + 1];
7039 method.ParameterTypes.CopyTo (set_pars, 0);
7040 set_pars [top] = method.MemberType;
7045 protected override InternalParameters GetParameterInfo (EmitContext ec)
7047 Parameter [] fixed_parms = parameters.FixedParameters;
7049 if (fixed_parms == null){
7050 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7051 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7052 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7054 // Here is the problem: the `value' parameter has
7055 // to come *after* the array parameter in the declaration
7057 // X (object [] x, Type value)
7060 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7061 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7065 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7067 fixed_parms.CopyTo (tmp, 0);
7068 tmp [fixed_parms.Length] = new Parameter (
7069 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7071 Parameters set_formal_params = new Parameters (tmp, null);
7072 Type [] types = set_formal_params.GetParameterInfo (ec);
7074 return new InternalParameters (types, set_formal_params);
7079 const int AllowedModifiers =
7082 Modifiers.PROTECTED |
7083 Modifiers.INTERNAL |
7087 Modifiers.OVERRIDE |
7092 const int AllowedInterfaceModifiers =
7096 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7097 bool is_iface, Parameters parameters, Attributes attrs,
7098 Accessor get_block, Accessor set_block, Location loc)
7099 : base (ds, type, mod,
7100 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7101 is_iface, name, parameters, attrs, loc)
7103 if (get_block == null)
7104 Get = new GetIndexerMethod (this);
7106 Get = new GetIndexerMethod (this, get_block);
7108 if (set_block == null)
7109 Set = new SetIndexerMethod (this);
7111 Set = new SetIndexerMethod (this, parameters, set_block);
7114 public override bool Define ()
7116 PropertyAttributes prop_attr =
7117 PropertyAttributes.RTSpecialName |
7118 PropertyAttributes.SpecialName;
7120 if (!base.Define ())
7123 if (MemberType == TypeManager.void_type) {
7124 Report.Error (620, Location, "Indexers cannot have void type");
7128 if (OptAttributes != null) {
7129 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7130 if (indexer_attr != null) {
7131 // Remove the attribute from the list because it is not emitted
7132 OptAttributes.Attrs.Remove (indexer_attr);
7134 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7136 if (IsExplicitImpl) {
7137 Report.Error (415, indexer_attr.Location,
7138 "The `IndexerName' attribute is valid only on an " +
7139 "indexer that is not an explicit interface member declaration");
7143 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7144 Report.Error (609, indexer_attr.Location,
7145 "Cannot set the `IndexerName' attribute on an indexer marked override");
7149 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7150 Report.Error (633, indexer_attr.Location,
7151 "The argument to the `IndexerName' attribute must be a valid identifier");
7157 if (InterfaceType != null) {
7158 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7159 if (base_IndexerName != Name)
7160 ShortName = base_IndexerName;
7163 if (!Parent.AddToMemberContainer (this) ||
7164 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7170 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7172 GetBuilder = Get.Define (Parent);
7173 if (GetBuilder == null)
7178 SetBuilder = Set.Define (Parent);
7179 if (SetBuilder == null)
7184 // Now name the parameters
7186 Parameter [] p = Parameters.FixedParameters;
7188 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7189 Report.Error (631, Location, "ref and out are not valid in this context");
7195 for (i = 0; i < p.Length; ++i) {
7197 GetBuilder.DefineParameter (
7198 i + 1, p [i].Attributes, p [i].Name);
7201 SetBuilder.DefineParameter (
7202 i + 1, p [i].Attributes, p [i].Name);
7206 SetBuilder.DefineParameter (
7207 i + 1, ParameterAttributes.None, "value");
7209 if (i != ParameterTypes.Length) {
7210 Parameter array_param = Parameters.ArrayParameter;
7212 SetBuilder.DefineParameter (
7213 i + 1, array_param.Attributes, array_param.Name);
7217 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7218 Name, prop_attr, MemberType, ParameterTypes);
7221 PropertyBuilder.SetGetMethod (GetBuilder);
7224 PropertyBuilder.SetSetMethod (SetBuilder);
7226 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7231 public override string GetSignatureForError ()
7233 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7234 if (MemberName.Left != null) {
7236 sb.Append (MemberName.Left);
7239 sb.Append (".this");
7240 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7241 return sb.ToString ();
7244 public override bool MarkForDuplicationCheck ()
7246 caching_flags |= Flags.TestMethodDuplication;
7252 public class Operator : MethodCore, IIteratorContainer {
7254 const int AllowedModifiers =
7260 public enum OpType : byte {
7270 // Unary and Binary operators
7293 // Implicit and Explicit
7297 // Just because of enum
7301 public readonly OpType OperatorType;
7302 public MethodBuilder OperatorMethodBuilder;
7304 public Method OperatorMethod;
7306 static string[] attribute_targets = new string [] { "method", "return" };
7308 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7309 int mod_flags, Parameters parameters,
7310 ToplevelBlock block, Attributes attrs, Location loc)
7311 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7312 new MemberName ("op_" + type), attrs, parameters, loc)
7314 OperatorType = type;
7318 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7320 OperatorMethod.ApplyAttributeBuilder (a, cb);
7323 public override AttributeTargets AttributeTargets {
7325 return AttributeTargets.Method;
7329 protected override bool CheckForDuplications()
7331 ArrayList ar = Parent.Operators;
7333 int arLen = ar.Count;
7335 for (int i = 0; i < arLen; i++) {
7336 Operator o = (Operator) ar [i];
7337 if (IsDuplicateImplementation (o))
7342 ar = Parent.Methods;
7344 int arLen = ar.Count;
7346 for (int i = 0; i < arLen; i++) {
7347 Method m = (Method) ar [i];
7348 if (IsDuplicateImplementation (m))
7356 public override bool Define ()
7358 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7359 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7360 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7367 if (MemberType == TypeManager.void_type) {
7368 Report.Error (590, Location, "User-defined operators cannot return void");
7372 OperatorMethod = new Method (
7373 Parent, Type, ModFlags, false, MemberName,
7374 Parameters, OptAttributes, Location);
7376 OperatorMethod.Block = Block;
7377 OperatorMethod.IsOperator = this;
7378 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7379 OperatorMethod.Define ();
7381 if (OperatorMethod.MethodBuilder == null)
7384 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7386 parameter_types = OperatorMethod.ParameterTypes;
7387 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7388 Type return_type = OperatorMethod.ReturnType;
7389 Type first_arg_type = parameter_types [0];
7394 // Rules for conversion operators
7396 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7397 if (first_arg_type == return_type && first_arg_type == declaring_type){
7398 Report.Error (555, Location,
7399 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7403 if (first_arg_type != declaring_type && return_type != declaring_type){
7406 "User-defined conversion must convert to or from the " +
7411 if (first_arg_type == TypeManager.object_type ||
7412 return_type == TypeManager.object_type){
7415 "User-defined conversion cannot convert to or from " +
7420 if (first_arg_type.IsInterface || return_type.IsInterface){
7421 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7422 GetSignatureForError ());
7426 if (first_arg_type.IsSubclassOf (return_type)
7427 || return_type.IsSubclassOf (first_arg_type)){
7428 if (declaring_type.IsSubclassOf (return_type)) {
7429 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7430 GetSignatureForError ());
7433 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7434 GetSignatureForError ());
7437 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7438 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7439 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");
7442 } else if (Parameters.FixedParameters.Length == 1) {
7443 // Checks for Unary operators
7445 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7446 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7447 Report.Error (448, Location,
7448 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7451 if (first_arg_type != declaring_type) {
7453 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7458 if (first_arg_type != declaring_type){
7461 "The parameter of a unary operator must be the " +
7466 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7467 if (return_type != TypeManager.bool_type){
7470 "The return type of operator True or False " +
7477 // Checks for Binary operators
7479 if (first_arg_type != declaring_type &&
7480 parameter_types [1] != declaring_type){
7483 "One of the parameters of a binary operator must " +
7484 "be the containing type");
7492 public override void Emit ()
7495 // abstract or extern methods have no bodies
7497 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7500 OperatorMethod.Emit ();
7504 // Operator cannot be override
7505 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7510 public static string GetName (OpType ot)
7513 case OpType.LogicalNot:
7515 case OpType.OnesComplement:
7517 case OpType.Increment:
7519 case OpType.Decrement:
7525 case OpType.Addition:
7527 case OpType.Subtraction:
7529 case OpType.UnaryPlus:
7531 case OpType.UnaryNegation:
7533 case OpType.Multiply:
7535 case OpType.Division:
7537 case OpType.Modulus:
7539 case OpType.BitwiseAnd:
7541 case OpType.BitwiseOr:
7543 case OpType.ExclusiveOr:
7545 case OpType.LeftShift:
7547 case OpType.RightShift:
7549 case OpType.Equality:
7551 case OpType.Inequality:
7553 case OpType.GreaterThan:
7555 case OpType.LessThan:
7557 case OpType.GreaterThanOrEqual:
7559 case OpType.LessThanOrEqual:
7561 case OpType.Implicit:
7563 case OpType.Explicit:
7569 public static OpType GetOperatorType (string name)
7571 if (name.StartsWith ("op_")){
7572 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7573 if (Unary.oper_names [i] == name)
7577 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7578 if (Binary.oper_names [i] == name)
7585 public override string GetSignatureForError ()
7587 StringBuilder sb = new StringBuilder ();
7588 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7589 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7592 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7595 sb.Append (Parameters.GetSignatureForError ());
7596 return sb.ToString ();
7599 public override bool MarkForDuplicationCheck ()
7601 caching_flags |= Flags.TestMethodDuplication;
7605 public override string[] ValidAttributeTargets {
7607 return attribute_targets;
7613 // This is used to compare method signatures
7615 struct MethodSignature {
7617 public Type RetType;
7618 public Type [] Parameters;
7621 /// This delegate is used to extract methods which have the
7622 /// same signature as the argument
7624 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7626 public MethodSignature (string name, Type ret_type, Type [] parameters)
7631 if (parameters == null)
7632 Parameters = TypeManager.NoTypes;
7634 Parameters = parameters;
7637 public override string ToString ()
7640 if (Parameters.Length != 0){
7641 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7642 for (int i = 0; i < Parameters.Length; i++){
7643 sb.Append (Parameters [i]);
7644 if (i+1 < Parameters.Length)
7647 pars = sb.ToString ();
7650 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7653 public override int GetHashCode ()
7655 return Name.GetHashCode ();
7658 public override bool Equals (Object o)
7660 MethodSignature other = (MethodSignature) o;
7662 if (other.Name != Name)
7665 if (other.RetType != RetType)
7668 if (Parameters == null){
7669 if (other.Parameters == null)
7674 if (other.Parameters == null)
7677 int c = Parameters.Length;
7678 if (other.Parameters.Length != c)
7681 for (int i = 0; i < c; i++)
7682 if (other.Parameters [i] != Parameters [i])
7688 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7690 MethodSignature sig = (MethodSignature) filter_criteria;
7692 if (m.Name != sig.Name)
7696 MethodInfo mi = m as MethodInfo;
7697 PropertyInfo pi = m as PropertyInfo;
7700 ReturnType = mi.ReturnType;
7701 else if (pi != null)
7702 ReturnType = pi.PropertyType;
7707 // we use sig.RetType == null to mean `do not check the
7708 // method return value.
7710 if (sig.RetType != null)
7711 if (ReturnType != sig.RetType)
7716 args = TypeManager.GetArgumentTypes (mi);
7718 args = TypeManager.GetArgumentTypes (pi);
7719 Type [] sigp = sig.Parameters;
7721 if (args.Length != sigp.Length)
7724 for (int i = args.Length; i > 0; ){
7726 if (args [i] != sigp [i])