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 // Whether we have at least one non-static field
447 bool have_nonstatic_fields = false;
450 // This one is computed after we can distinguish interfaces
451 // from classes from the arraylist `type_bases'
453 string base_class_name;
455 TypeExpr[] iface_exprs;
457 ArrayList type_bases;
459 bool members_defined;
460 bool members_defined_ok;
462 // The interfaces we implement.
463 protected Type[] ifaces;
464 protected Type ptype;
466 // The base member cache and our member cache
467 MemberCache base_cache;
468 MemberCache member_cache;
470 public const string DefaultIndexerName = "Item";
472 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
473 Attributes attrs, Kind kind, Location l)
474 : base (ns, parent, name, attrs, l)
476 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
477 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
481 types = new ArrayList ();
483 base_class_name = null;
486 public bool AddToMemberContainer (MemberCore symbol)
488 return AddToContainer (symbol, symbol.Name);
491 bool AddToTypeContainer (DeclSpace ds)
493 // Parent == null ==> this == RootContext.Tree.Types
494 return AddToContainer (ds, (Parent == null) ? ds.Name : ds.Basename);
497 public void AddConstant (Const constant)
499 if (!AddToMemberContainer (constant))
502 if (constants == null)
503 constants = new MemberCoreArrayList ();
505 constants.Add (constant);
508 public void AddEnum (Mono.CSharp.Enum e)
510 if (!AddToTypeContainer (e))
514 enums = new MemberCoreArrayList ();
519 public void AddClassOrStruct (TypeContainer c)
521 if (!AddToTypeContainer (c))
527 public void AddDelegate (Delegate d)
529 if (!AddToTypeContainer (d))
532 if (delegates == null)
533 delegates = new MemberCoreArrayList ();
538 public void AddMethod (Method method)
540 if (!AddToMemberContainer (method))
544 methods = new MethodArrayList (this);
546 if (method.MemberName.Left != null)
547 methods.Insert (0, method);
549 methods.Add (method);
552 public void AddConstructor (Constructor c)
554 if (c.Name != Basename) {
555 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
558 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
561 if (default_static_constructor != null) {
562 Report.SymbolRelatedToPreviousError (default_static_constructor);
563 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
567 default_static_constructor = c;
570 if (default_constructor != null) {
571 Report.SymbolRelatedToPreviousError (default_constructor);
572 Report.Error (111, c.Location, Error111, c.Location, c.GetSignatureForError ());
575 default_constructor = c;
578 if (instance_constructors == null)
579 instance_constructors = new MemberCoreArrayList ();
581 instance_constructors.Add (c);
585 internal static string Error111 {
587 return "`{0}' is already defined. Rename this member or use different parameter types";
591 public void AddInterface (TypeContainer iface)
593 if (!AddToTypeContainer (iface))
596 if (interfaces == null) {
597 interfaces = new MemberCoreArrayList ();
600 interfaces.Add (iface);
603 public void AddField (FieldMember field)
605 if (!AddToMemberContainer (field))
609 fields = new MemberCoreArrayList ();
613 if (field.HasInitializer)
614 RegisterFieldForInitialization (field);
616 if ((field.ModFlags & Modifiers.STATIC) == 0)
617 have_nonstatic_fields = true;
620 public void AddProperty (Property prop)
622 if (!AddToMemberContainer (prop) ||
623 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
626 if (properties == null)
627 properties = new MemberCoreArrayList ();
629 if (prop.MemberName.Left != null)
630 properties.Insert (0, prop);
632 properties.Add (prop);
635 public void AddEvent (Event e)
637 if (!AddToMemberContainer (e))
640 if (e is EventProperty) {
641 if (!AddToMemberContainer (e.Add))
644 if (!AddToMemberContainer (e.Remove))
649 events = new MemberCoreArrayList ();
656 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
658 public void AddIndexer (Indexer i)
660 if (indexers == null)
661 indexers = new IndexerArrayList (this);
663 if (i.IsExplicitImpl)
664 indexers.Insert (0, i);
669 public void AddOperator (Operator op)
671 if (!AddToMemberContainer (op))
674 if (operators == null)
675 operators = new OperatorArrayList (this);
680 public void AddIterator (Iterator i)
682 if (iterators == null)
683 iterators = new ArrayList ();
688 public void AddType (TypeContainer tc)
693 public void AddPart (ClassPart part)
696 parts = new ArrayList ();
701 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
703 if (a.Type == TypeManager.default_member_type) {
704 if (Indexers != null) {
705 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
710 base.ApplyAttributeBuilder (a, cb);
713 public override AttributeTargets AttributeTargets {
717 return AttributeTargets.Class;
719 return AttributeTargets.Struct;
721 return AttributeTargets.Interface;
723 throw new NotSupportedException ();
728 public ArrayList Types {
734 public MethodArrayList Methods {
740 public ArrayList Constants {
746 public ArrayList Interfaces {
752 public ArrayList Iterators {
760 return base_class_name;
764 public ArrayList Bases {
774 public ArrayList Fields {
780 public ArrayList InstanceConstructors {
782 return instance_constructors;
786 public ArrayList Properties {
792 public ArrayList Events {
798 public ArrayList Enums {
804 public ArrayList Indexers {
810 public ArrayList Operators {
816 public ArrayList Delegates {
822 public ArrayList Parts {
828 protected override TypeAttributes TypeAttr {
830 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
834 public string IndexerName {
836 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
840 public virtual void RegisterFieldForInitialization (FieldMember field)
842 if ((field.ModFlags & Modifiers.STATIC) != 0){
843 if (initialized_static_fields == null)
844 initialized_static_fields = new ArrayList ();
846 initialized_static_fields.Add (field);
848 if (initialized_fields == null)
849 initialized_fields = new ArrayList ();
851 initialized_fields.Add (field);
856 // Emits the instance field initializers
858 public virtual bool EmitFieldInitializers (EmitContext ec)
861 Expression instance_expr;
864 fields = initialized_static_fields;
865 instance_expr = null;
867 fields = initialized_fields;
868 instance_expr = new This (Location.Null).Resolve (ec);
874 foreach (FieldMember f in fields){
875 Expression e = f.GetInitializerExpression (ec);
879 Location l = f.Location;
880 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
881 fe.InstanceExpression = instance_expr;
882 ExpressionStatement a = new Assign (fe, e, l);
884 a = a.ResolveStatement (ec);
888 Constant c = e as Constant;
890 if (c.IsDefaultValue)
894 a.EmitStatement (ec);
901 // Defines the default constructors
903 protected void DefineDefaultConstructor (bool is_static)
907 // The default constructor is public
908 // If the class is abstract, the default constructor is protected
909 // The default static constructor is private
911 int mods = Modifiers.PUBLIC;
913 mods = Modifiers.STATIC | Modifiers.PRIVATE;
914 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
915 mods = Modifiers.PROTECTED;
917 TypeContainer constructor_parent = this;
919 constructor_parent = (TypeContainer) Parts [0];
921 c = new Constructor (constructor_parent, Basename, mods,
922 Parameters.EmptyReadOnlyParameters,
923 new ConstructorBaseInitializer (
924 null, Parameters.EmptyReadOnlyParameters,
930 c.Block = new ToplevelBlock (null, Location);
935 /// The pending methods that need to be implemented
936 // (interfaces or abstract methods)
938 public PendingImplementation Pending;
940 public abstract PendingImplementation GetPendingImplementations ();
942 TypeExpr[] GetPartialBases (out TypeExpr base_class)
944 ArrayList ifaces = new ArrayList ();
947 Location base_loc = Location.Null;
949 foreach (ClassPart part in parts) {
950 TypeExpr new_base_class;
951 TypeExpr[] new_ifaces;
953 new_ifaces = part.GetClassBases (out new_base_class);
954 if (new_ifaces == null && new_base_class != null)
957 if ((base_class != null) && (new_base_class != null) &&
958 !base_class.Equals (new_base_class)) {
959 Report.Error (263, part.Location,
960 "Partial declarations of `{0}' must " +
961 "not specify different base classes",
964 if (!Location.IsNull (base_loc))
965 Report.LocationOfPreviousError (base_loc);
970 if ((base_class == null) && (new_base_class != null)) {
971 base_class = new_base_class;
972 base_loc = part.Location;
975 if (new_ifaces == null)
978 foreach (TypeExpr iface in new_ifaces) {
980 foreach (TypeExpr old_iface in ifaces) {
981 if (old_iface.Equals (iface)) {
992 TypeExpr[] retval = new TypeExpr [ifaces.Count];
993 ifaces.CopyTo (retval, 0);
997 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1001 int count = Bases.Count;
1002 int start = 0, i, j;
1004 if (Kind == Kind.Class){
1005 TypeExpr name = ResolveBaseTypeExpr (
1006 (Expression) Bases [0], false, Location);
1012 if (!name.IsInterface) {
1013 // base_class could be a class, struct, enum, delegate.
1014 // This is validated in GetClassBases.
1020 TypeExpr [] ifaces = new TypeExpr [count-start];
1022 for (i = start, j = 0; i < count; i++, j++){
1023 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1024 if (resolved == null) {
1028 ifaces [j] = resolved;
1035 /// This function computes the Base class and also the
1036 /// list of interfaces that the class or struct @c implements.
1038 /// The return value is an array (might be null) of
1039 /// interfaces implemented (as Types).
1041 /// The @base_class argument is set to the base object or null
1042 /// if this is `System.Object'.
1044 TypeExpr [] GetClassBases (out TypeExpr base_class)
1051 ifaces = GetPartialBases (out base_class);
1052 else if (Bases == null){
1056 ifaces = GetNormalBases (out base_class);
1061 if ((base_class != null) && (Kind == Kind.Class)){
1063 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1064 Report.Error (1521, base_class.Location, "Invalid base type");
1068 if (base_class.IsSealed){
1069 Report.SymbolRelatedToPreviousError (base_class.Type);
1070 if (base_class.Type.IsAbstract) {
1071 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
1072 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1074 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
1075 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1080 if (!base_class.CanInheritFrom ()){
1081 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
1082 GetSignatureForError (), base_class.GetSignatureForError ());
1086 if (!base_class.AsAccessible (this, ModFlags)) {
1087 Report.SymbolRelatedToPreviousError (base_class.Type);
1088 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
1089 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1093 if (base_class != null)
1094 base_class_name = base_class.Name;
1099 int count = ifaces != null ? ifaces.Length : 0;
1101 for (i = 0; i < count; i++) {
1102 TypeExpr iface = (TypeExpr) ifaces [i];
1104 if (!iface.IsInterface) {
1105 if (Kind != Kind.Class) {
1106 // TODO: location of symbol related ....
1107 Error_TypeInListIsNotInterface (Location, iface.FullName);
1109 else if (base_class != null)
1110 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1111 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1113 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1114 GetSignatureForError (), iface.GetSignatureForError ());
1119 for (int x = 0; x < i; x++) {
1120 if (iface.Equals (ifaces [x])) {
1121 Report.Error (528, Location,
1122 "`{0}' is already listed in " +
1123 "interface list", iface.Name);
1128 if ((Kind == Kind.Interface) &&
1129 !iface.AsAccessible (Parent, ModFlags)) {
1130 Report.Error (61, Location,
1131 "Inconsistent accessibility: base " +
1132 "interface `{0}' is less accessible " +
1133 "than interface `{1}'", iface.Name,
1143 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1145 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1149 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1151 public override TypeBuilder DefineType ()
1156 if (TypeBuilder != null)
1159 TypeAttributes type_attributes = TypeAttr;
1163 if (TypeManager.NamespaceClash (Name, Location)) {
1168 ModuleBuilder builder = CodeGen.Module.Builder;
1169 TypeBuilder = builder.DefineType (
1170 Name, type_attributes, null, null);
1172 TypeBuilder builder = Parent.TypeBuilder;
1173 if (builder == null) {
1178 TypeBuilder = builder.DefineNestedType (
1179 Basename, type_attributes, ptype, null);
1181 } catch (ArgumentException) {
1182 Report.RuntimeMissingSupport (Location, "static classes");
1187 TypeManager.AddUserType (Name, TypeBuilder, this);
1189 if (Parts != null) {
1191 foreach (ClassPart part in Parts) {
1192 part.TypeBuilder = TypeBuilder;
1194 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1195 part.ec.ContainerType = TypeBuilder;
1199 // Normally, we create the EmitContext here.
1200 // The only exception is if we're an Iterator - in this case,
1201 // we already have the `ec', so we don't want to create a new one.
1204 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1205 ec.ContainerType = TypeBuilder;
1208 iface_exprs = GetClassBases (out base_type);
1209 if (iface_exprs == null && base_type != null) {
1214 if (base_type == null) {
1215 if (Kind == Kind.Class){
1216 if (RootContext.StdLib)
1217 base_type = TypeManager.system_object_expr;
1218 else if (Name != "System.Object")
1219 base_type = TypeManager.system_object_expr;
1220 } else if (Kind == Kind.Struct) {
1222 // If we are compiling our runtime,
1223 // and we are defining ValueType, then our
1224 // base is `System.Object'.
1226 if (!RootContext.StdLib && Name == "System.ValueType")
1227 base_type = TypeManager.system_object_expr;
1229 base_type = TypeManager.system_valuetype_expr;
1233 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1234 throw new Exception ();
1236 if (base_type != null) {
1237 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1238 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1239 ptype = base_type.ResolveType (TypeResolveEmitContext);
1240 if (ptype == null) {
1246 if (!CheckRecursiveDefinition (this)) {
1252 TypeBuilder.SetParent (ptype);
1254 // add interfaces that were not added at type creation
1255 if (iface_exprs != null) {
1256 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1257 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1258 TypeResolveEmitContext.ContainerType = TypeBuilder;
1259 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1260 if (ifaces == null) {
1265 foreach (Type itype in ifaces)
1266 TypeBuilder.AddInterfaceImplementation (itype);
1268 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1271 if (!(this is Iterator))
1272 RootContext.RegisterOrder (this);
1274 if (!DefineNestedTypes ()) {
1282 protected virtual bool DefineNestedTypes ()
1284 if (Interfaces != null) {
1285 foreach (TypeContainer iface in Interfaces)
1286 if (iface.DefineType () == null)
1290 if (Types != null) {
1291 foreach (TypeContainer tc in Types)
1292 if (tc.DefineType () == null)
1296 if (Delegates != null) {
1297 foreach (Delegate d in Delegates)
1298 if (d.DefineType () == null)
1302 if (Enums != null) {
1303 foreach (Enum en in Enums)
1304 if (en.DefineType () == null)
1311 TypeContainer InTransit;
1313 protected bool CheckRecursiveDefinition (TypeContainer tc)
1315 if (InTransit != null) {
1316 Report.SymbolRelatedToPreviousError (this);
1317 if (this is Interface)
1319 529, tc.Location, "Inherited interface `{0}' causes a " +
1320 "cycle in the interface hierarchy of `{1}'",
1321 GetSignatureForError (), tc.GetSignatureForError ());
1324 146, tc.Location, "Circular base class dependency " +
1325 "involving `{0}' and `{1}'",
1326 tc.GetSignatureForError (), GetSignatureForError ());
1332 Type parent = ptype;
1333 if (parent != null) {
1334 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1335 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1339 if (iface_exprs != null) {
1340 foreach (TypeExpr iface in iface_exprs) {
1341 Type itype = iface.Type;
1343 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1344 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1353 public static void Error_KeywordNotAllowed (Location loc)
1355 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1359 /// Populates our TypeBuilder with fields and methods
1361 public override bool DefineMembers (TypeContainer container)
1363 if (members_defined)
1364 return members_defined_ok;
1366 if (!base.DefineMembers (container))
1369 members_defined_ok = DoDefineMembers ();
1370 members_defined = true;
1372 return members_defined_ok;
1375 protected virtual bool DoDefineMembers ()
1378 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1379 if (conflict_symbol == null) {
1380 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1381 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1383 if ((ModFlags & Modifiers.NEW) == 0) {
1384 Report.SymbolRelatedToPreviousError (conflict_symbol);
1385 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1386 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1391 DefineContainerMembers (constants);
1392 DefineContainerMembers (fields);
1394 if ((Kind == Kind.Class) && !(this is ClassPart)){
1395 if ((instance_constructors == null) &&
1396 !(this is StaticClass)) {
1397 if (default_constructor == null)
1398 DefineDefaultConstructor (false);
1401 if (initialized_static_fields != null &&
1402 default_static_constructor == null)
1403 DefineDefaultConstructor (true);
1406 if (Kind == Kind.Struct){
1408 // Structs can not have initialized instance
1411 if (initialized_static_fields != null &&
1412 default_static_constructor == null)
1413 DefineDefaultConstructor (true);
1415 if (initialized_fields != null)
1416 ReportStructInitializedInstanceError ();
1419 Pending = GetPendingImplementations ();
1421 if (parts != null) {
1422 foreach (ClassPart part in parts) {
1423 if (!part.DefineMembers (this))
1429 // Constructors are not in the defined_names array
1431 DefineContainerMembers (instance_constructors);
1433 if (default_static_constructor != null)
1434 default_static_constructor.Define ();
1436 DefineContainerMembers (properties);
1437 DefineContainerMembers (events);
1438 DefineContainerMembers (indexers);
1439 DefineContainerMembers (methods);
1440 DefineContainerMembers (operators);
1441 DefineContainerMembers (enums);
1442 DefineContainerMembers (delegates);
1445 if (!(this is ClassPart))
1446 member_cache = new MemberCache (this);
1449 if (parts != null) {
1450 foreach (ClassPart part in parts)
1451 part.member_cache = member_cache;
1454 if (iterators != null) {
1455 foreach (Iterator iterator in iterators) {
1456 if (iterator.DefineType () == null)
1460 foreach (Iterator iterator in iterators) {
1461 if (!iterator.DefineMembers (this))
1469 void ReportStructInitializedInstanceError ()
1471 string n = TypeBuilder.FullName;
1473 foreach (Field f in initialized_fields){
1474 Report.Error (573, Location,
1475 "`{0}': Structs cannot have instance field initializers",
1476 f.GetSignatureForError ());
1480 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1483 mcal.DefineContainerMembers ();
1486 public override bool Define ()
1488 if (parts != null) {
1489 foreach (ClassPart part in parts) {
1490 if (!part.Define ())
1495 if (iterators != null) {
1496 foreach (Iterator iterator in iterators) {
1497 if (!iterator.Define ())
1505 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1507 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1511 /// This function is based by a delegate to the FindMembers routine
1513 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1519 /// This filter is used by FindMembers, and we just keep
1520 /// a global for the filter to `AlwaysAccept'
1522 static MemberFilter accepting_filter;
1525 static TypeContainer ()
1527 accepting_filter = new MemberFilter (AlwaysAccept);
1530 public MethodInfo[] GetMethods ()
1532 ArrayList members = new ArrayList ();
1534 DefineMembers (null);
1536 if (methods != null) {
1537 int len = methods.Count;
1538 for (int i = 0; i < len; i++) {
1539 Method m = (Method) methods [i];
1541 members.Add (m.MethodBuilder);
1545 if (operators != null) {
1546 int len = operators.Count;
1547 for (int i = 0; i < len; i++) {
1548 Operator o = (Operator) operators [i];
1550 members.Add (o.OperatorMethodBuilder);
1554 if (properties != null) {
1555 int len = properties.Count;
1556 for (int i = 0; i < len; i++) {
1557 Property p = (Property) properties [i];
1559 if (p.GetBuilder != null)
1560 members.Add (p.GetBuilder);
1561 if (p.SetBuilder != null)
1562 members.Add (p.SetBuilder);
1566 if (indexers != null) {
1567 int len = indexers.Count;
1568 for (int i = 0; i < len; i++) {
1569 Indexer ix = (Indexer) indexers [i];
1571 if (ix.GetBuilder != null)
1572 members.Add (ix.GetBuilder);
1573 if (ix.SetBuilder != null)
1574 members.Add (ix.SetBuilder);
1578 if (events != null) {
1579 int len = events.Count;
1580 for (int i = 0; i < len; i++) {
1581 Event e = (Event) events [i];
1583 if (e.AddBuilder != null)
1584 members.Add (e.AddBuilder);
1585 if (e.RemoveBuilder != null)
1586 members.Add (e.RemoveBuilder);
1590 MethodInfo[] retMethods = new MethodInfo [members.Count];
1591 members.CopyTo (retMethods, 0);
1595 // Indicated whether container has StructLayout attribute set Explicit
1596 public virtual bool HasExplicitLayout {
1602 public override Type FindNestedType (string name)
1604 ArrayList [] lists = { types, enums, delegates, interfaces };
1606 for (int j = 0; j < lists.Length; ++j) {
1607 ArrayList list = lists [j];
1611 int len = list.Count;
1612 for (int i = 0; i < len; ++i) {
1613 DeclSpace ds = (DeclSpace) list [i];
1614 if (ds.Basename == name) {
1616 return ds.TypeBuilder;
1624 private void FindMembers_NestedTypes (int modflags,
1625 BindingFlags bf, MemberFilter filter, object criteria,
1626 ref ArrayList members)
1628 ArrayList [] lists = { types, enums, delegates, interfaces };
1630 for (int j = 0; j < lists.Length; ++j) {
1631 ArrayList list = lists [j];
1635 int len = list.Count;
1636 for (int i = 0; i < len; i++) {
1637 DeclSpace ds = (DeclSpace) list [i];
1639 if ((ds.ModFlags & modflags) == 0)
1642 TypeBuilder tb = ds.TypeBuilder;
1644 if (!(criteria is string) || ds.Basename.Equals (criteria))
1645 tb = ds.DefineType ();
1648 if (tb != null && (filter (tb, criteria) == true)) {
1649 if (members == null)
1650 members = new ArrayList ();
1659 /// This method returns the members of this type just like Type.FindMembers would
1660 /// Only, we need to use this for types which are _being_ defined because MS'
1661 /// implementation can't take care of that.
1664 // FIXME: return an empty static array instead of null, that cleans up
1665 // some code and is consistent with some coding conventions I just found
1669 // Notice that in various cases we check if our field is non-null,
1670 // something that would normally mean that there was a bug elsewhere.
1672 // The problem happens while we are defining p-invoke methods, as those
1673 // will trigger a FindMembers, but this happens before things are defined
1675 // Since the whole process is a no-op, it is fine to check for null here.
1677 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1678 MemberFilter filter, object criteria)
1680 ArrayList members = null;
1683 if ((bf & BindingFlags.Public) != 0)
1684 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1686 if ((bf & BindingFlags.NonPublic) != 0)
1687 modflags |= Modifiers.PRIVATE;
1689 int static_mask = 0, static_flags = 0;
1690 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1691 case BindingFlags.Static:
1692 static_mask = static_flags = Modifiers.STATIC;
1695 case BindingFlags.Instance:
1696 static_mask = Modifiers.STATIC;
1701 static_mask = static_flags = 0;
1705 Timer.StartTimer (TimerType.TcFindMembers);
1708 filter = accepting_filter;
1710 if ((mt & MemberTypes.Field) != 0) {
1711 if (fields != null) {
1712 int len = fields.Count;
1713 for (int i = 0; i < len; i++) {
1714 FieldMember f = (FieldMember) fields [i];
1716 if ((f.ModFlags & modflags) == 0)
1718 if ((f.ModFlags & static_mask) != static_flags)
1721 FieldBuilder fb = f.FieldBuilder;
1722 if (fb != null && filter (fb, criteria) == true) {
1723 if (members == null)
1724 members = new ArrayList ();
1731 if (constants != null) {
1732 int len = constants.Count;
1733 for (int i = 0; i < len; i++) {
1734 Const con = (Const) constants [i];
1736 if ((con.ModFlags & modflags) == 0)
1738 if ((con.ModFlags & static_mask) != static_flags)
1741 FieldBuilder fb = con.FieldBuilder;
1744 fb = con.FieldBuilder;
1746 if (fb != null && filter (fb, criteria) == true) {
1747 if (members == null)
1748 members = new ArrayList ();
1756 if ((mt & MemberTypes.Method) != 0) {
1757 if (methods != null) {
1758 int len = methods.Count;
1759 for (int i = 0; i < len; i++) {
1760 Method m = (Method) methods [i];
1762 if ((m.ModFlags & modflags) == 0)
1764 if ((m.ModFlags & static_mask) != static_flags)
1767 MethodBuilder mb = m.MethodBuilder;
1769 if (mb != null && filter (mb, criteria) == true) {
1770 if (members == null)
1771 members = new ArrayList ();
1778 if (operators != null) {
1779 int len = operators.Count;
1780 for (int i = 0; i < len; i++) {
1781 Operator o = (Operator) operators [i];
1783 if ((o.ModFlags & modflags) == 0)
1785 if ((o.ModFlags & static_mask) != static_flags)
1788 MethodBuilder ob = o.OperatorMethodBuilder;
1789 if (ob != null && filter (ob, criteria) == true) {
1790 if (members == null)
1791 members = new ArrayList ();
1798 if (properties != null) {
1799 int len = properties.Count;
1800 for (int i = 0; i < len; i++) {
1801 Property p = (Property) properties [i];
1803 if ((p.ModFlags & modflags) == 0)
1805 if ((p.ModFlags & static_mask) != static_flags)
1811 if (b != null && filter (b, criteria) == true) {
1812 if (members == null)
1813 members = new ArrayList ();
1819 if (b != null && filter (b, criteria) == true) {
1820 if (members == null)
1821 members = new ArrayList ();
1828 if (indexers != null) {
1829 int len = indexers.Count;
1830 for (int i = 0; i < len; i++) {
1831 Indexer ix = (Indexer) indexers [i];
1833 if ((ix.ModFlags & modflags) == 0)
1835 if ((ix.ModFlags & static_mask) != static_flags)
1841 if (b != null && filter (b, criteria) == true) {
1842 if (members == null)
1843 members = new ArrayList ();
1849 if (b != null && filter (b, criteria) == true) {
1850 if (members == null)
1851 members = new ArrayList ();
1859 if ((mt & MemberTypes.Event) != 0) {
1860 if (events != null) {
1861 int len = events.Count;
1862 for (int i = 0; i < len; i++) {
1863 Event e = (Event) events [i];
1865 if ((e.ModFlags & modflags) == 0)
1867 if ((e.ModFlags & static_mask) != static_flags)
1870 MemberInfo eb = e.EventBuilder;
1871 if (eb != null && filter (eb, criteria) == true) {
1872 if (members == null)
1873 members = new ArrayList ();
1875 members.Add (e.EventBuilder);
1881 if ((mt & MemberTypes.Property) != 0){
1882 if (properties != null) {
1883 int len = properties.Count;
1884 for (int i = 0; i < len; i++) {
1885 Property p = (Property) properties [i];
1887 if ((p.ModFlags & modflags) == 0)
1889 if ((p.ModFlags & static_mask) != static_flags)
1892 MemberInfo pb = p.PropertyBuilder;
1893 if (pb != null && filter (pb, criteria) == true) {
1894 if (members == null)
1895 members = new ArrayList ();
1897 members.Add (p.PropertyBuilder);
1902 if (indexers != null) {
1903 int len = indexers.Count;
1904 for (int i = 0; i < len; i++) {
1905 Indexer ix = (Indexer) indexers [i];
1907 if ((ix.ModFlags & modflags) == 0)
1909 if ((ix.ModFlags & static_mask) != static_flags)
1912 MemberInfo ib = ix.PropertyBuilder;
1913 if (ib != null && filter (ib, criteria) == true) {
1914 if (members == null)
1915 members = new ArrayList ();
1917 members.Add (ix.PropertyBuilder);
1923 if ((mt & MemberTypes.NestedType) != 0)
1924 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1926 if ((mt & MemberTypes.Constructor) != 0){
1927 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1928 int len = instance_constructors.Count;
1929 for (int i = 0; i < len; i++) {
1930 Constructor c = (Constructor) instance_constructors [i];
1932 ConstructorBuilder cb = c.ConstructorBuilder;
1933 if (cb != null && filter (cb, criteria) == true) {
1934 if (members == null)
1935 members = new ArrayList ();
1942 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1943 ConstructorBuilder cb =
1944 default_static_constructor.ConstructorBuilder;
1946 if (cb != null && filter (cb, criteria) == true) {
1947 if (members == null)
1948 members = new ArrayList ();
1956 // Lookup members in base if requested.
1958 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1959 if (TypeBuilder.BaseType != null) {
1960 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1961 if (list.Count > 0) {
1962 if (members == null)
1963 members = new ArrayList ();
1965 members.AddRange (list);
1968 if (ifaces != null) {
1969 foreach (Type base_type in ifaces) {
1970 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1972 if (list.Count > 0) {
1973 if (members == null)
1974 members = new ArrayList ();
1975 members.AddRange (list);
1981 Timer.StopTimer (TimerType.TcFindMembers);
1983 if (members == null)
1984 return MemberList.Empty;
1986 return new MemberList (members);
1989 public override MemberCache MemberCache {
1991 return member_cache;
1995 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1996 MemberFilter filter, object criteria)
1998 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2001 return ds.FindMembers (mt, bf, filter, criteria);
2003 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2008 // FindMethods will look for methods not only in the type `t', but in
2009 // any interfaces implemented by the type.
2011 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2012 MemberFilter filter, object criteria)
2018 /// Emits the values for the constants
2020 public void EmitConstants ()
2022 if (constants != null)
2023 foreach (Const con in constants)
2028 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2033 foreach (MemberCore mc in al) {
2034 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2038 Report.Warning (169, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2043 public virtual void VerifyMembers ()
2046 // Check for internal or private fields that were never assigned
2048 if (RootContext.WarningLevel >= 3) {
2049 CheckMemberUsage (properties, "property");
2050 CheckMemberUsage (methods, "method");
2051 CheckMemberUsage (constants, "constant");
2053 if (fields != null){
2054 foreach (FieldMember f in fields) {
2055 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2059 Report.Warning (169, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2064 // Only report 649 on level 4
2066 if (RootContext.WarningLevel < 4)
2069 if ((f.status & Field.Status.ASSIGNED) != 0)
2072 Report.Warning (649, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2073 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2080 /// Emits the code, this step is performed after all
2081 /// the types, enumerations, constructors
2083 public void EmitType ()
2085 if (OptAttributes != null)
2086 OptAttributes.Emit (ec, this);
2089 // Structs with no fields need to have at least one byte.
2090 // The right thing would be to set the PackingSize in a DefineType
2091 // but there are no functions that allow interfaces *and* the size to
2095 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
2096 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2097 FieldAttributes.Private);
2099 if (HasExplicitLayout){
2100 object [] ctor_args = new object [1];
2103 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2104 TypeManager.field_offset_attribute_ctor, ctor_args);
2105 fb.SetCustomAttribute (cba);
2111 if (instance_constructors != null) {
2112 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2113 bool has_compliant_args = false;
2115 foreach (Constructor c in instance_constructors) {
2118 if (has_compliant_args)
2121 has_compliant_args = c.HasCompliantArgs;
2123 if (!has_compliant_args)
2124 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2126 foreach (Constructor c in instance_constructors)
2131 // Can not continue if constants are broken
2133 if (Report.Errors > 0)
2136 if (default_static_constructor != null)
2137 default_static_constructor.Emit ();
2139 if (methods != null)
2140 foreach (Method m in methods)
2143 if (operators != null)
2144 foreach (Operator o in operators)
2147 if (properties != null)
2148 foreach (Property p in properties)
2151 if (indexers != null){
2156 foreach (FieldMember f in fields)
2159 if (events != null){
2160 foreach (Event e in Events)
2164 if (delegates != null) {
2165 foreach (Delegate d in Delegates) {
2170 if (enums != null) {
2171 foreach (Enum e in enums) {
2176 if (parts != null) {
2177 foreach (ClassPart part in parts)
2181 if ((Pending != null) && !(this is ClassPart))
2182 if (Pending.VerifyPendingMethods ())
2185 if (iterators != null)
2186 foreach (Iterator iterator in iterators)
2187 iterator.EmitType ();
2189 // if (types != null)
2190 // foreach (TypeContainer tc in types)
2194 public override void CloseType ()
2196 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2200 caching_flags |= Flags.CloseTypeCreated;
2201 TypeBuilder.CreateType ();
2202 } catch (TypeLoadException){
2204 // This is fine, the code still created the type
2206 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2207 // Console.WriteLine (e.Message);
2209 Console.WriteLine ("In type: " + Name);
2214 foreach (Enum en in Enums)
2218 foreach (TypeContainer tc in Types)
2219 if (tc.Kind == Kind.Struct)
2222 foreach (TypeContainer tc in Types)
2223 if (tc.Kind != Kind.Struct)
2227 if (Delegates != null)
2228 foreach (Delegate d in Delegates)
2231 if (Iterators != null)
2232 foreach (Iterator i in Iterators)
2240 initialized_fields = null;
2241 initialized_static_fields = null;
2250 default_constructor = null;
2251 default_static_constructor = null;
2253 OptAttributes = null;
2256 member_cache = null;
2260 // Performs the validation on a Method's modifiers (properties have
2261 // the same properties).
2263 public bool MethodModifiersValid (MemberCore mc)
2265 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2266 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2267 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2269 int flags = mc.ModFlags;
2272 // At most one of static, virtual or override
2274 if ((flags & Modifiers.STATIC) != 0){
2275 if ((flags & vao) != 0){
2276 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2277 mc.GetSignatureForError ());
2282 if (Kind == Kind.Struct){
2283 if ((flags & va) != 0){
2284 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2289 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2290 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2291 mc.GetSignatureForError ());
2296 // If the declaration includes the abstract modifier, then the
2297 // declaration does not include static, virtual or extern
2299 if ((flags & Modifiers.ABSTRACT) != 0){
2300 if ((flags & Modifiers.EXTERN) != 0){
2302 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2306 if ((flags & Modifiers.SEALED) != 0) {
2307 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2311 if ((flags & Modifiers.VIRTUAL) != 0){
2312 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2316 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2317 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2322 if ((flags & Modifiers.PRIVATE) != 0){
2323 if ((flags & vao) != 0){
2324 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2329 if ((flags & Modifiers.SEALED) != 0){
2330 if ((flags & Modifiers.OVERRIDE) == 0){
2331 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2339 public bool UserDefinedStaticConstructor {
2341 return default_static_constructor != null;
2345 public Constructor DefaultStaticConstructor {
2346 get { return default_static_constructor; }
2349 protected override bool VerifyClsCompliance (DeclSpace ds)
2351 if (!base.VerifyClsCompliance (ds))
2356 Type base_type = TypeBuilder.BaseType;
2357 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2358 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2361 if (!Parent.IsClsCompliaceRequired (ds)) {
2362 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type `{1}'",
2363 GetSignatureForError (), Parent.GetSignatureForError ());
2370 /// Checks whether container name is CLS Compliant
2372 void VerifyClsName ()
2374 Hashtable base_members = base_cache == null ?
2376 base_cache.GetPublicMembers ();
2377 Hashtable this_members = new Hashtable ();
2379 foreach (DictionaryEntry entry in defined_names) {
2380 MemberCore mc = (MemberCore)entry.Value;
2381 if (!mc.IsClsCompliaceRequired (this))
2384 string name = (string)entry.Key;
2385 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2387 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2388 object found = base_members [lcase];
2389 if (found == null) {
2390 found = this_members [lcase];
2391 if (found == null) {
2392 this_members.Add (lcase, mc);
2397 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2400 if (found is MemberInfo) {
2401 if (basename == ((MemberInfo)found).Name)
2403 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2405 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2407 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2413 /// Performs checks for an explicit interface implementation. First it
2414 /// checks whether the `interface_type' is a base inteface implementation.
2415 /// Then it checks whether `name' exists in the interface type.
2417 public virtual bool VerifyImplements (MemberBase mb)
2419 if (ifaces != null) {
2420 foreach (Type t in ifaces){
2421 if (t == mb.InterfaceType)
2426 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2427 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2431 protected override void VerifyObsoleteAttribute()
2433 CheckUsageOfObsoleteAttribute (ptype);
2438 foreach (Type iface in ifaces) {
2439 CheckUsageOfObsoleteAttribute (iface);
2448 string IMemberContainer.Name {
2454 Type IMemberContainer.Type {
2460 MemberCache IMemberContainer.MemberCache {
2462 return member_cache;
2466 bool IMemberContainer.IsInterface {
2468 return Kind == Kind.Interface;
2472 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2474 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2478 // Generates xml doc comments (if any), and if required,
2479 // handle warning report.
2481 internal override void GenerateDocComment (DeclSpace ds)
2483 DocUtil.GenerateTypeDocComment (this, ds);
2486 public override string DocCommentHeader {
2487 get { return "T:"; }
2490 public virtual MemberCache BaseCache {
2492 if (base_cache != null)
2494 if (TypeBuilder.BaseType != null)
2495 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2496 if (TypeBuilder.IsInterface)
2497 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2503 public class PartialContainer : TypeContainer {
2505 public readonly Namespace Namespace;
2506 public readonly int OriginalModFlags;
2507 public readonly int AllowedModifiers;
2508 public readonly TypeAttributes DefaultTypeAttributes;
2510 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2511 MemberName member_name, int mod_flags, Kind kind,
2514 PartialContainer pc;
2515 DeclSpace ds = RootContext.Tree.GetDecl (member_name);
2517 pc = ds as PartialContainer;
2520 Report.LocationOfPreviousError (loc);
2521 Report.Error (260, ds.Location,
2522 "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
2523 member_name.GetPartialName());
2528 if (pc.Kind != kind) {
2530 261, loc, "Partial declarations of `{0}' " +
2531 "must be all classes, all structs or " +
2532 "all interfaces", member_name.GetPartialName ());
2536 if (pc.OriginalModFlags != mod_flags) {
2538 262, loc, "Partial declarations of `{0}' " +
2539 "have conflicting accessibility modifiers",
2540 member_name.GetPartialName ());
2547 if (parent is ClassPart)
2548 parent = ((ClassPart) parent).PartialContainer;
2550 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2551 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2553 if (kind == Kind.Interface)
2554 parent.AddInterface (pc);
2555 else if (kind == Kind.Class || kind == Kind.Struct)
2556 parent.AddClassOrStruct (pc);
2558 throw new InvalidOperationException ();
2563 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2564 MemberName name, int mod, Attributes attrs,
2565 Kind kind, Location loc)
2567 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2569 // An error occured; create a dummy container, but don't
2571 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2574 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2579 protected PartialContainer (Namespace ns, TypeContainer parent,
2580 MemberName name, int mod, Kind kind, Location l)
2581 : base (null, parent, name, null, kind, l)
2583 this.Namespace = ns;
2587 AllowedModifiers = Class.AllowedModifiers;
2588 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2592 AllowedModifiers = Struct.AllowedModifiers;
2593 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2596 case Kind.Interface:
2597 AllowedModifiers = Interface.AllowedModifiers;
2598 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2602 throw new InvalidOperationException ();
2606 if (parent.Parent == null)
2607 accmods = Modifiers.INTERNAL;
2609 accmods = Modifiers.PRIVATE;
2611 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2612 this.OriginalModFlags = mod;
2615 public override PendingImplementation GetPendingImplementations ()
2617 return PendingImplementation.GetPendingImplementations (this);
2620 protected override TypeAttributes TypeAttr {
2622 return base.TypeAttr | DefaultTypeAttributes;
2627 public class ClassPart : TypeContainer, IMemberContainer {
2628 public readonly PartialContainer PartialContainer;
2629 public readonly bool IsPartial;
2631 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2632 int mod, Attributes attrs, Kind kind, Location l)
2633 : base (ns, parent, pc.MemberName, attrs, kind, l)
2635 this.PartialContainer = pc;
2636 this.IsPartial = true;
2639 if (parent == null || parent == RootContext.Tree.Types)
2640 accmods = Modifiers.INTERNAL;
2642 accmods = Modifiers.PRIVATE;
2644 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2647 public override PendingImplementation GetPendingImplementations ()
2649 return PartialContainer.Pending;
2652 public override bool VerifyImplements (MemberBase mb)
2654 return PartialContainer.VerifyImplements (mb);
2658 public override void RegisterFieldForInitialization (FieldMember field)
2660 PartialContainer.RegisterFieldForInitialization (field);
2663 public override bool EmitFieldInitializers (EmitContext ec)
2665 return PartialContainer.EmitFieldInitializers (ec);
2668 public override Type FindNestedType (string name)
2670 return PartialContainer.FindNestedType (name);
2673 public override MemberCache BaseCache {
2675 return PartialContainer.BaseCache;
2679 public override TypeBuilder DefineType ()
2681 throw new InternalErrorException ("Should not get here");
2686 public abstract class ClassOrStruct : TypeContainer {
2687 bool has_explicit_layout = false;
2688 ListDictionary declarative_security;
2690 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2691 MemberName name, Attributes attrs, Kind kind,
2693 : base (ns, parent, name, attrs, kind, l)
2697 public override PendingImplementation GetPendingImplementations ()
2699 return PendingImplementation.GetPendingImplementations (this);
2702 public override bool HasExplicitLayout {
2704 return has_explicit_layout;
2708 public override void VerifyMembers ()
2710 base.VerifyMembers ();
2712 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2713 foreach (Event e in events){
2715 Report.Warning (67, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2720 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2722 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2723 if (declarative_security == null)
2724 declarative_security = new ListDictionary ();
2726 a.ExtractSecurityPermissionSet (declarative_security);
2730 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2731 has_explicit_layout = true;
2733 base.ApplyAttributeBuilder (a, cb);
2736 public override void Emit()
2740 if (declarative_security != null) {
2741 foreach (DictionaryEntry de in declarative_security) {
2742 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2749 /// Class handles static classes declaration
2751 public sealed class StaticClass: Class {
2752 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2753 Attributes attrs, Location l)
2754 : base (ns, parent, name, mod, attrs, l)
2756 if (RootContext.Version == LanguageVersion.ISO_1) {
2757 Report.FeatureIsNotStandardized (l, "static classes");
2761 protected override int AllowedModifiersProp {
2763 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2764 Modifiers.STATIC | Modifiers.UNSAFE;
2768 protected override void DefineContainerMembers (MemberCoreArrayList list)
2773 foreach (MemberCore m in list) {
2774 if (m is Operator) {
2775 Report.Error (715, m.Location, "`{0}': static classes cannot contain user-defined operators", m.GetSignatureForError ());
2779 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2780 Report.Warning (-628, 4, m.Location, "`{0}': new protected member declared in static class", m.GetSignatureForError ());
2783 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2787 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2790 if (m is Constructor) {
2791 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2795 if (m is Destructor) {
2796 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2800 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2803 base.DefineContainerMembers (list);
2806 public override TypeBuilder DefineType()
2808 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2809 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2813 TypeBuilder tb = base.DefineType ();
2817 if (ptype != TypeManager.object_type) {
2818 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2822 if (ifaces != null) {
2823 foreach (Type t in ifaces)
2824 Report.SymbolRelatedToPreviousError (t);
2825 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2830 protected override TypeAttributes TypeAttr {
2832 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2837 public class Class : ClassOrStruct {
2838 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2839 public const int AllowedModifiers =
2842 Modifiers.PROTECTED |
2843 Modifiers.INTERNAL |
2845 Modifiers.ABSTRACT |
2849 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2850 Attributes attrs, Location l)
2851 : base (ns, parent, name, attrs, Kind.Class, l)
2853 this.ModFlags = mod;
2856 virtual protected int AllowedModifiersProp {
2858 return AllowedModifiers;
2862 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2864 if (a.Type == TypeManager.attribute_usage_type) {
2865 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2866 TypeBuilder.FullName != "System.Attribute") {
2867 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.Name);
2871 if (a.Type == TypeManager.conditional_attribute_type &&
2872 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
2873 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2877 if (AttributeTester.IsAttributeExcluded (a.Type))
2880 base.ApplyAttributeBuilder (a, cb);
2883 public const TypeAttributes DefaultTypeAttributes =
2884 TypeAttributes.AutoLayout | TypeAttributes.Class;
2886 public override TypeBuilder DefineType()
2888 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2889 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2893 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2894 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2896 return base.DefineType ();
2899 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2900 /// Valid only for attribute classes.
2901 public bool IsExcluded ()
2903 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2904 return (caching_flags & Flags.Excluded) != 0;
2906 caching_flags &= ~Flags.Excluded_Undetected;
2908 if (OptAttributes == null)
2911 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
2916 foreach (Attribute a in attrs) {
2917 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
2918 if (RootContext.AllDefines.Contains (condition))
2922 caching_flags |= Flags.Excluded;
2927 // FIXME: How do we deal with the user specifying a different
2930 protected override TypeAttributes TypeAttr {
2932 return base.TypeAttr | DefaultTypeAttributes;
2937 public class Struct : ClassOrStruct {
2939 // Modifiers allowed in a struct declaration
2941 public const int AllowedModifiers =
2944 Modifiers.PROTECTED |
2945 Modifiers.INTERNAL |
2949 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2950 int mod, Attributes attrs, Location l)
2951 : base (ns, parent, name, attrs, Kind.Struct, l)
2955 if (parent.Parent == null)
2956 accmods = Modifiers.INTERNAL;
2958 accmods = Modifiers.PRIVATE;
2960 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2962 this.ModFlags |= Modifiers.SEALED;
2965 public const TypeAttributes DefaultTypeAttributes =
2966 TypeAttributes.SequentialLayout |
2967 TypeAttributes.Sealed |
2968 TypeAttributes.BeforeFieldInit;
2971 // FIXME: Allow the user to specify a different set of attributes
2972 // in some cases (Sealed for example is mandatory for a class,
2973 // but what SequentialLayout can be changed
2975 protected override TypeAttributes TypeAttr {
2977 return base.TypeAttr | DefaultTypeAttributes;
2985 public class Interface : TypeContainer, IMemberContainer {
2988 /// Modifiers allowed in a class declaration
2990 public const int AllowedModifiers =
2993 Modifiers.PROTECTED |
2994 Modifiers.INTERNAL |
2998 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2999 Attributes attrs, Location l)
3000 : base (ns, parent, name, attrs, Kind.Interface, l)
3004 if (parent.Parent == null)
3005 accmods = Modifiers.INTERNAL;
3007 accmods = Modifiers.PRIVATE;
3009 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3012 public override PendingImplementation GetPendingImplementations ()
3017 public const TypeAttributes DefaultTypeAttributes =
3018 TypeAttributes.AutoLayout |
3019 TypeAttributes.Abstract |
3020 TypeAttributes.Interface;
3022 protected override TypeAttributes TypeAttr {
3024 return base.TypeAttr | DefaultTypeAttributes;
3028 protected override bool VerifyClsCompliance (DeclSpace ds)
3030 if (!base.VerifyClsCompliance (ds))
3033 if (ifaces != null) {
3034 foreach (Type t in ifaces) {
3035 if (AttributeTester.IsClsCompliant (t))
3038 Report.SymbolRelatedToPreviousError (t);
3039 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3040 GetSignatureForError (), TypeManager.CSharpName (t));
3048 public abstract class MethodCore : MemberBase {
3049 public readonly Parameters Parameters;
3050 protected ToplevelBlock block;
3053 // Parameters, cached for semantic analysis.
3055 protected InternalParameters parameter_info;
3056 protected Type [] parameter_types;
3058 // Whether this is an operator method.
3059 public Operator IsOperator;
3062 // The method we're overriding if this is an override method.
3064 protected MethodInfo base_method = null;
3066 static string[] attribute_targets = new string [] { "method", "return" };
3068 public MethodCore (TypeContainer parent, Expression type, int mod,
3069 int allowed_mod, bool is_interface, MemberName name,
3070 Attributes attrs, Parameters parameters, Location loc)
3071 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3074 Parameters = parameters;
3075 IsInterface = is_interface;
3079 // Returns the System.Type array for the parameters of this method
3081 public Type [] ParameterTypes {
3083 return parameter_types;
3087 public InternalParameters ParameterInfo
3090 return parameter_info;
3094 public ToplevelBlock Block {
3104 // TODO: why is it done in extra call ?
3105 public void SetYields ()
3107 ModFlags |= Modifiers.METHOD_YIELDS;
3110 protected override bool CheckBase ()
3112 if (!base.CheckBase ())
3115 // Check whether arguments were correct.
3116 if (!DoDefineParameters ())
3119 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3125 // Is null for System.Object while compiling corlib and base interfaces
3126 if (Parent.BaseCache == null) {
3127 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3128 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3133 Type base_ret_type = null;
3134 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3136 // method is override
3137 if (base_method != null) {
3139 if (!CheckMethodAgainstBase ())
3142 if ((ModFlags & Modifiers.NEW) == 0) {
3143 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3144 Report.SymbolRelatedToPreviousError (base_method);
3145 if (this is PropertyBase) {
3146 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3147 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3150 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3151 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3156 if (base_method.IsAbstract && !IsInterface) {
3157 Report.SymbolRelatedToPreviousError (base_method);
3158 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3159 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3164 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3165 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3169 if (RootContext.WarningLevel > 2) {
3170 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3171 Parent.Methods.HasEquals = true;
3172 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3173 Parent.Methods.HasGetHashCode = true;
3176 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3177 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3179 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3180 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3181 Report.SymbolRelatedToPreviousError (base_method);
3182 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3183 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3190 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3191 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3192 if (conflict_symbol != null) {
3193 Report.SymbolRelatedToPreviousError (conflict_symbol);
3194 if (this is PropertyBase)
3195 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3197 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3199 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3203 if (conflict_symbol == null) {
3204 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3205 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3210 if ((ModFlags & Modifiers.NEW) == 0) {
3211 if (this is Method && conflict_symbol is MethodBase)
3214 Report.SymbolRelatedToPreviousError (conflict_symbol);
3215 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3216 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3223 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3224 // that have been defined.
3226 // `name' is the user visible name for reporting errors (this is used to
3227 // provide the right name regarding method names and properties)
3229 bool CheckMethodAgainstBase ()
3233 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3234 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3235 Report.Error (506, Location,
3236 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3237 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3241 // Now we check that the overriden method is not final
3243 if (base_method.IsFinal) {
3244 Report.SymbolRelatedToPreviousError (base_method);
3245 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3246 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3250 // Check that the permissions are not being changed
3252 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3253 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3255 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3256 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3261 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3262 ModFlags |= Modifiers.NEW;
3263 Report.SymbolRelatedToPreviousError (base_method);
3264 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3265 if (RootContext.WarningLevel >= 2)
3266 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));
3268 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3269 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3276 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3278 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3280 // when overriding protected internal, the method can be declared
3281 // protected internal only within the same assembly
3284 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3285 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3287 // assemblies differ - report an error
3291 } else if (thisp != base_classp) {
3293 // same assembly, but other attributes differ - report an error
3298 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3300 // if it's not "protected internal", it must be "protected"
3304 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3306 // protected within the same assembly - an error
3309 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3310 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3312 // protected ok, but other attributes differ - report an error
3318 return (thisp == base_classp);
3322 public bool CheckAbstractAndExtern (bool has_block)
3324 if (Parent.Kind == Kind.Interface)
3328 if ((ModFlags & Modifiers.EXTERN) != 0) {
3329 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3330 GetSignatureForError ());
3334 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3335 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3336 GetSignatureForError ());
3340 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3341 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3342 GetSignatureForError ());
3350 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3352 Report.SymbolRelatedToPreviousError (base_method);
3353 string base_name = TypeManager.GetFullNameSignature (base_method);
3354 string this_name = GetSignatureForError ();
3355 if (suffix != null) {
3356 base_name += suffix;
3357 this_name += suffix;
3360 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3361 this_name, Modifiers.GetDescription (ma), base_name);
3364 protected static string Error722 {
3366 return "`{0}': static types cannot be used as return types";
3371 /// For custom member duplication search in a container
3373 protected abstract bool CheckForDuplications ();
3376 /// Gets base method and its return type
3378 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3380 protected virtual bool DoDefineParameters ()
3382 EmitContext ec = Parent.EmitContext;
3384 throw new InternalErrorException ("DoDefineParameters invoked too early");
3386 bool old_unsafe = ec.InUnsafe;
3387 ec.InUnsafe = InUnsafe;
3388 // Check if arguments were correct
3389 parameter_types = Parameters.GetParameterInfo (ec);
3390 ec.InUnsafe = old_unsafe;
3392 if ((parameter_types == null) ||
3393 !CheckParameters (Parent, parameter_types))
3396 parameter_info = new InternalParameters (parameter_types, Parameters);
3398 Parameter array_param = Parameters.ArrayParameter;
3399 if ((array_param != null) &&
3400 (!array_param.ParameterType.IsArray ||
3401 (array_param.ParameterType.GetArrayRank () != 1))) {
3402 Report.Error (225, Location, "The params parameter must be a single dimensional array");
3409 public override string[] ValidAttributeTargets {
3411 return attribute_targets;
3415 protected override bool VerifyClsCompliance (DeclSpace ds)
3417 if (!base.VerifyClsCompliance (ds)) {
3418 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3419 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3424 if (Parameters.HasArglist) {
3425 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3428 if (!AttributeTester.IsClsCompliant (MemberType)) {
3429 if (this is PropertyBase)
3430 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3431 GetSignatureForError ());
3433 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3434 GetSignatureForError ());
3437 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3442 protected bool IsDuplicateImplementation (MethodCore method)
3444 if ((method == this) || (method.Name != Name))
3447 Type[] param_types = method.ParameterTypes;
3448 if (param_types == null)
3451 if (param_types.Length != ParameterTypes.Length)
3454 for (int i = 0; i < param_types.Length; i++)
3455 if (param_types [i] != ParameterTypes [i])
3458 // TODO: make operator compatible with MethodCore to avoid this
3459 if (this is Operator && method is Operator) {
3460 if (MemberType != method.MemberType)
3465 // Try to report 663: method only differs on out/ref
3467 ParameterData info = ParameterInfo;
3468 ParameterData other_info = method.ParameterInfo;
3469 for (int i = 0; i < info.Count; i++){
3470 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3471 Report.SymbolRelatedToPreviousError (method);
3472 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3473 GetSignatureForError ());
3478 Report.SymbolRelatedToPreviousError (method);
3479 if (this is Operator && method is Operator)
3480 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3482 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3486 public override bool IsUsed
3497 // Returns a string that represents the signature for this
3498 // member which should be used in XML documentation.
3500 public override string GetDocCommentName (DeclSpace ds)
3502 return DocUtil.GetMethodDocCommentName (this, ds);
3506 // Raised (and passed an XmlElement that contains the comment)
3507 // when GenerateDocComment is writing documentation expectedly.
3509 // FIXME: with a few effort, it could be done with XmlReader,
3510 // that means removal of DOM use.
3512 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3514 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3518 // Represents header string for documentation comment.
3520 public override string DocCommentHeader {
3521 get { return "M:"; }
3524 protected override void VerifyObsoleteAttribute()
3526 base.VerifyObsoleteAttribute ();
3528 if (parameter_types == null)
3531 foreach (Type type in parameter_types) {
3532 CheckUsageOfObsoleteAttribute (type);
3537 public class SourceMethod : ISourceMethod
3539 TypeContainer container;
3542 protected SourceMethod (TypeContainer container, MethodBase builder,
3543 ISourceFile file, Location start, Location end)
3545 this.container = container;
3546 this.builder = builder;
3548 CodeGen.SymbolWriter.OpenMethod (
3549 file, this, start.Row, 0, end.Row, 0);
3552 public string Name {
3553 get { return builder.Name; }
3556 public int NamespaceID {
3557 get { return container.NamespaceEntry.SymbolFileID; }
3562 if (builder is MethodBuilder)
3563 return ((MethodBuilder) builder).GetToken ().Token;
3564 else if (builder is ConstructorBuilder)
3565 return ((ConstructorBuilder) builder).GetToken ().Token;
3567 throw new NotSupportedException ();
3571 public void CloseMethod ()
3573 if (CodeGen.SymbolWriter != null)
3574 CodeGen.SymbolWriter.CloseMethod ();
3577 public static SourceMethod Create (TypeContainer parent,
3578 MethodBase builder, Block block)
3580 if (CodeGen.SymbolWriter == null)
3585 Location start_loc = block.StartLocation;
3586 if (Location.IsNull (start_loc))
3589 Location end_loc = block.EndLocation;
3590 if (Location.IsNull (end_loc))
3593 ISourceFile file = start_loc.SourceFile;
3597 return new SourceMethod (
3598 parent, builder, file, start_loc, end_loc);
3602 public class Method : MethodCore, IIteratorContainer, IMethodData {
3603 public MethodBuilder MethodBuilder;
3604 public MethodData MethodData;
3605 ReturnParameter return_attributes;
3606 ListDictionary declarative_security;
3609 /// Modifiers allowed in a class declaration
3611 const int AllowedModifiers =
3614 Modifiers.PROTECTED |
3615 Modifiers.INTERNAL |
3620 Modifiers.OVERRIDE |
3621 Modifiers.ABSTRACT |
3623 Modifiers.METHOD_YIELDS |
3626 const int AllowedInterfaceModifiers =
3627 Modifiers.NEW | Modifiers.UNSAFE;
3630 // return_type can be "null" for VOID values.
3632 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3633 MemberName name, Parameters parameters, Attributes attrs,
3635 : base (ds, return_type, mod,
3636 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3637 is_iface, name, attrs, parameters, l)
3641 public override AttributeTargets AttributeTargets {
3643 return AttributeTargets.Method;
3647 public override string GetSignatureForError()
3649 if (IsOperator != null)
3650 return IsOperator.GetSignatureForError ();
3652 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3655 void DuplicateEntryPoint (MethodInfo b, Location location)
3659 "Program `" + CodeGen.FileName +
3660 "' has more than one entry point defined: `" +
3661 TypeManager.CSharpSignature(b) + "'");
3664 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3666 if (b.ReturnType != TypeManager.void_type &&
3667 b.ReturnType != TypeManager.int32_type)
3670 if (pinfo.Count == 0)
3673 if (pinfo.Count > 1)
3676 Type t = pinfo.ParameterType(0);
3678 (t.GetArrayRank() == 1) &&
3679 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3680 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3686 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3688 if (a.Target == AttributeTargets.ReturnValue) {
3689 if (return_attributes == null)
3690 return_attributes = new ReturnParameter (MethodBuilder, Location);
3692 return_attributes.ApplyAttributeBuilder (a, cb);
3696 if (a.Type == TypeManager.methodimpl_attr_type &&
3697 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3698 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3701 if (a.Type == TypeManager.dllimport_type) {
3702 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3703 if ((ModFlags & extern_static) != extern_static) {
3704 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3710 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3711 if (declarative_security == null)
3712 declarative_security = new ListDictionary ();
3713 a.ExtractSecurityPermissionSet (declarative_security);
3717 if (a.Type == TypeManager.conditional_attribute_type) {
3718 if (IsOperator != null || IsExplicitImpl) {
3719 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3720 GetSignatureForError ());
3724 if (ReturnType != TypeManager.void_type) {
3725 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
3729 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3730 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
3735 Report.Error (582, Location, "Conditional not valid on interface members");
3739 if (MethodData.implementing != null) {
3740 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
3741 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
3745 for (int i = 0; i < parameter_info.Count; ++i) {
3746 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3747 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
3753 MethodBuilder.SetCustomAttribute (cb);
3756 protected override bool CheckForDuplications ()
3758 ArrayList ar = Parent.Methods;
3760 int arLen = ar.Count;
3762 for (int i = 0; i < arLen; i++) {
3763 Method m = (Method) ar [i];
3764 if (IsDuplicateImplementation (m))
3769 ar = Parent.Properties;
3771 for (int i = 0; i < ar.Count; ++i) {
3772 PropertyBase pb = (PropertyBase) ar [i];
3773 if (pb.AreAccessorsDuplicateImplementation (this))
3778 ar = Parent.Indexers;
3780 for (int i = 0; i < ar.Count; ++i) {
3781 PropertyBase pb = (PropertyBase) ar [i];
3782 if (pb.AreAccessorsDuplicateImplementation (this))
3789 for (int i = 0; i < ar.Count; ++i) {
3790 Event ev = (Event) ar [i];
3791 if (ev.AreAccessorsDuplicateImplementation (this))
3802 public override bool Define ()
3807 if (!CheckAbstractAndExtern (block != null))
3810 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3811 Error1599 (Location, ReturnType);
3818 if (IsOperator != null)
3819 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3821 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3823 if (!MethodData.Define (Parent))
3826 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3827 Name == "Finalize" && !(this is Destructor)) {
3828 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3832 // Setup iterator if we are one
3834 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3835 Iterator iterator = new Iterator (this,
3837 ParameterInfo, ModFlags);
3839 if (!iterator.DefineIterator ())
3843 MethodBuilder = MethodData.MethodBuilder;
3846 // This is used to track the Entry Point,
3848 if (Name == "Main" &&
3849 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3850 (RootContext.MainClass == null ||
3851 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3852 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3853 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3854 md.SetMemberIsUsed ();
3856 if (RootContext.EntryPoint == null) {
3857 RootContext.EntryPoint = MethodBuilder;
3858 RootContext.EntryPointLocation = Location;
3860 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3861 DuplicateEntryPoint (MethodBuilder, Location);
3864 if (RootContext.WarningLevel >= 4)
3865 Report.Warning (28, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3869 if (MemberType.IsAbstract && MemberType.IsSealed) {
3870 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3880 public override void Emit ()
3882 MethodData.Emit (Parent, this);
3885 if (declarative_security != null) {
3886 foreach (DictionaryEntry de in declarative_security) {
3887 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3895 public static void Error1599 (Location loc, Type t)
3897 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
3900 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3902 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3903 container.TypeBuilder, Name, ParameterTypes, false);
3908 base_ret_type = mi.ReturnType;
3912 public override bool MarkForDuplicationCheck ()
3914 caching_flags |= Flags.TestMethodDuplication;
3918 protected override bool VerifyClsCompliance(DeclSpace ds)
3920 if (!base.VerifyClsCompliance (ds))
3923 if (parameter_types.Length > 0) {
3924 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3926 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3932 #region IMethodData Members
3934 public CallingConventions CallingConventions {
3936 CallingConventions cc = Parameters.GetCallingConvention ();
3937 if (Parameters.HasArglist)
3938 block.HasVarargs = true;
3941 if ((ModFlags & Modifiers.STATIC) == 0)
3942 cc |= CallingConventions.HasThis;
3944 // FIXME: How is `ExplicitThis' used in C#?
3950 public Type ReturnType {
3956 public MemberName MethodName {
3962 public new Location Location {
3964 return base.Location;
3968 protected override bool CheckBase() {
3969 if (!base.CheckBase ())
3972 // TODO: Destructor should derive from MethodCore
3973 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3974 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3975 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3982 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3984 EmitContext ec = new EmitContext (
3985 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3987 ec.CurrentIterator = tc as Iterator;
3988 if (ec.CurrentIterator != null)
3989 ec.CurrentAnonymousMethod = ec.CurrentIterator.Host;
3994 public ObsoleteAttribute GetObsoleteAttribute ()
3996 return GetObsoleteAttribute (Parent);
4000 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4002 public bool IsExcluded (EmitContext ec)
4004 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4005 return (caching_flags & Flags.Excluded) != 0;
4007 caching_flags &= ~Flags.Excluded_Undetected;
4009 if (base_method == null) {
4010 if (OptAttributes == null)
4013 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4018 foreach (Attribute a in attrs) {
4019 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4020 if (RootContext.AllDefines.Contains (condition))
4024 caching_flags |= Flags.Excluded;
4028 IMethodData md = TypeManager.GetMethod (base_method);
4030 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4031 caching_flags |= Flags.Excluded;
4037 if (md.IsExcluded (ec)) {
4038 caching_flags |= Flags.Excluded;
4047 public abstract class ConstructorInitializer {
4048 ArrayList argument_list;
4049 protected ConstructorInfo base_constructor;
4050 Parameters parameters;
4053 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4056 this.argument_list = argument_list;
4057 this.parameters = parameters;
4061 public ArrayList Arguments {
4063 return argument_list;
4067 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4069 Expression base_constructor_group;
4073 ec.CurrentBlock = block;
4075 if (argument_list != null){
4076 foreach (Argument a in argument_list){
4077 if (!a.Resolve (ec, loc))
4081 ec.CurrentBlock = null;
4083 if (this is ConstructorBaseInitializer) {
4084 if (ec.ContainerType.BaseType == null)
4087 t = ec.ContainerType.BaseType;
4088 if (ec.ContainerType.IsValueType) {
4089 Report.Error (522, loc,
4090 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4094 t = ec.ContainerType;
4096 base_constructor_group = Expression.MemberLookup (
4097 ec, t, ".ctor", MemberTypes.Constructor,
4098 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4101 if (base_constructor_group == null){
4103 base_constructor_group = Expression.MemberLookup (
4104 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4105 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4109 int errors = Report.Errors;
4110 if (base_constructor_group != null)
4111 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4112 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4115 if (base_constructor == null) {
4116 if (errors == Report.Errors)
4117 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4118 argument_list.Count);
4123 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4124 base_constructor = null;
4128 if (base_constructor == caller_builder){
4129 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4136 public void Emit (EmitContext ec)
4138 if (base_constructor != null){
4139 ec.Mark (loc, false);
4141 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4143 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4148 public class ConstructorBaseInitializer : ConstructorInitializer {
4149 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4150 base (argument_list, pars, l)
4155 public class ConstructorThisInitializer : ConstructorInitializer {
4156 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4157 base (argument_list, pars, l)
4162 public class Constructor : MethodCore, IMethodData {
4163 public ConstructorBuilder ConstructorBuilder;
4164 public ConstructorInitializer Initializer;
4165 ListDictionary declarative_security;
4168 // Modifiers allowed for a constructor.
4170 public const int AllowedModifiers =
4172 Modifiers.PROTECTED |
4173 Modifiers.INTERNAL |
4179 bool has_compliant_args = false;
4181 // The spec claims that static is not permitted, but
4182 // my very own code has static constructors.
4184 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4185 ConstructorInitializer init, Location l)
4186 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4192 public bool HasCompliantArgs {
4194 return has_compliant_args;
4198 public override AttributeTargets AttributeTargets {
4200 return AttributeTargets.Constructor;
4206 // Returns true if this is a default constructor
4208 public bool IsDefault ()
4210 if ((ModFlags & Modifiers.STATIC) != 0)
4211 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4212 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4215 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4216 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4217 (Initializer is ConstructorBaseInitializer) &&
4218 (Initializer.Arguments == null);
4221 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4223 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4224 if (declarative_security == null) {
4225 declarative_security = new ListDictionary ();
4227 a.ExtractSecurityPermissionSet (declarative_security);
4231 ConstructorBuilder.SetCustomAttribute (cb);
4234 protected override bool CheckForDuplications ()
4236 ArrayList ar = Parent.InstanceConstructors;
4238 int arLen = ar.Count;
4240 for (int i = 0; i < arLen; i++) {
4241 Constructor m = (Constructor) ar [i];
4242 if (IsDuplicateImplementation (m))
4249 protected override bool CheckBase ()
4251 // Check whether arguments were correct.
4252 if (!DoDefineParameters ())
4255 // TODO: skip the rest for generated ctor
4256 if ((ModFlags & Modifiers.STATIC) != 0)
4259 if (!CheckForDuplications ())
4262 if (Parent.Kind == Kind.Struct) {
4263 if (ParameterTypes.Length == 0) {
4264 Report.Error (568, Location,
4265 "Structs cannot contain explicit parameterless constructors");
4269 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4270 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4275 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4276 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4283 // Creates the ConstructorBuilder
4285 public override bool Define ()
4287 if (ConstructorBuilder != null)
4290 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4291 MethodAttributes.SpecialName);
4293 if ((ModFlags & Modifiers.STATIC) != 0) {
4294 ca |= MethodAttributes.Static | MethodAttributes.Private;
4296 ca |= MethodAttributes.HideBySig;
4298 if ((ModFlags & Modifiers.PUBLIC) != 0)
4299 ca |= MethodAttributes.Public;
4300 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4301 if ((ModFlags & Modifiers.INTERNAL) != 0)
4302 ca |= MethodAttributes.FamORAssem;
4304 ca |= MethodAttributes.Family;
4305 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4306 ca |= MethodAttributes.Assembly;
4307 else if (IsDefault ())
4308 ca |= MethodAttributes.Public;
4310 ca |= MethodAttributes.Private;
4313 if (!CheckAbstractAndExtern (block != null))
4316 // Check if arguments were correct.
4320 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4321 ca, CallingConventions,
4324 if ((ModFlags & Modifiers.UNSAFE) != 0)
4325 ConstructorBuilder.InitLocals = false;
4327 TypeManager.AddMethod (ConstructorBuilder, this);
4330 // HACK because System.Reflection.Emit is lame
4332 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4340 public override void Emit ()
4342 EmitContext ec = CreateEmitContext (null, null);
4344 // If this is a non-static `struct' constructor and doesn't have any
4345 // initializer, it must initialize all of the struct's fields.
4346 if ((Parent.Kind == Kind.Struct) &&
4347 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4348 Block.AddThisVariable (Parent, Location);
4351 block.ResolveMeta (ec, ParameterInfo);
4353 if ((ModFlags & Modifiers.STATIC) == 0){
4354 if (Parent.Kind == Kind.Class && Initializer == null)
4355 Initializer = new ConstructorBaseInitializer (
4356 null, Parameters.EmptyReadOnlyParameters, Location);
4360 // Spec mandates that Initializers will not have
4364 if ((Initializer != null) &&
4365 !Initializer.Resolve (ConstructorBuilder, block, ec))
4367 ec.IsStatic = false;
4370 Parameters.LabelParameters (ec, ConstructorBuilder);
4372 SourceMethod source = SourceMethod.Create (
4373 Parent, ConstructorBuilder, block);
4376 // Classes can have base initializers and instance field initializers.
4378 if (Parent.Kind == Kind.Class){
4379 if ((ModFlags & Modifiers.STATIC) == 0){
4382 // If we use a "this (...)" constructor initializer, then
4383 // do not emit field initializers, they are initialized in the other constructor
4385 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4386 Parent.EmitFieldInitializers (ec);
4389 if (Initializer != null) {
4390 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4391 ec.TestObsoleteMethodUsage = false;
4393 Initializer.Emit (ec);
4396 if ((ModFlags & Modifiers.STATIC) != 0)
4397 Parent.EmitFieldInitializers (ec);
4399 if (OptAttributes != null)
4400 OptAttributes.Emit (ec, this);
4402 ec.EmitTopBlock (this, block, ParameterInfo);
4405 source.CloseMethod ();
4409 if (declarative_security != null) {
4410 foreach (DictionaryEntry de in declarative_security) {
4411 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4418 // Is never override
4419 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4424 public override string GetSignatureForError()
4426 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4429 protected override bool VerifyClsCompliance (DeclSpace ds)
4431 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4435 if (parameter_types.Length > 0) {
4436 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4438 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4440 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4441 foreach (Type param in parameter_types) {
4442 if (param.IsArray) {
4448 has_compliant_args = true;
4452 #region IMethodData Members
4454 public System.Reflection.CallingConventions CallingConventions {
4456 CallingConventions cc = Parameters.GetCallingConvention ();
4458 if (Parent.Kind == Kind.Class)
4459 if ((ModFlags & Modifiers.STATIC) == 0)
4460 cc |= CallingConventions.HasThis;
4462 // FIXME: How is `ExplicitThis' used in C#?
4468 public new Location Location {
4470 return base.Location;
4474 public MemberName MethodName {
4480 public Type ReturnType {
4486 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4488 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4489 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4492 public ObsoleteAttribute GetObsoleteAttribute ()
4494 return GetObsoleteAttribute (Parent);
4497 public bool IsExcluded(EmitContext ec)
4506 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4508 public interface IMethodData
4510 CallingConventions CallingConventions { get; }
4511 Location Location { get; }
4512 MemberName MethodName { get; }
4513 Type[] ParameterTypes { get; }
4514 Type ReturnType { get; }
4516 Attributes OptAttributes { get; }
4517 ToplevelBlock Block { get; set; }
4519 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4520 ObsoleteAttribute GetObsoleteAttribute ();
4521 string GetSignatureForError ();
4522 bool IsExcluded (EmitContext ec);
4523 bool IsClsCompliaceRequired (DeclSpace ds);
4524 void SetMemberIsUsed ();
4528 // Encapsulates most of the Method's state
4530 public class MethodData {
4532 readonly IMethodData method;
4535 // The return type of this method
4537 public readonly InternalParameters ParameterInfo;
4540 // Are we implementing an interface ?
4542 public MethodInfo implementing;
4547 protected MemberBase member;
4548 protected int modifiers;
4549 protected MethodAttributes flags;
4551 MethodBuilder builder = null;
4552 public MethodBuilder MethodBuilder {
4558 public MethodData (MemberBase member, InternalParameters parameters,
4559 int modifiers, MethodAttributes flags, IMethodData method)
4561 this.member = member;
4562 this.ParameterInfo = parameters;
4563 this.modifiers = modifiers;
4566 this.method = method;
4569 public bool Define (TypeContainer container)
4571 string name = method.MethodName.Name;
4572 string method_name = name;
4574 Type[] ParameterTypes = method.ParameterTypes;
4576 if (container.Pending != null){
4577 if (member is Indexer) // TODO: test it, but it should work without this IF
4578 implementing = container.Pending.IsInterfaceIndexer (
4579 member.InterfaceType, method.ReturnType, ParameterInfo);
4581 implementing = container.Pending.IsInterfaceMethod (
4582 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4584 if (member.InterfaceType != null){
4585 if (implementing == null){
4586 if (member is PropertyBase) {
4587 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4588 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4589 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4592 Report.Error (539, method.Location,
4593 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4594 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4598 if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
4599 Report.SymbolRelatedToPreviousError (implementing);
4600 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4601 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4604 method_name = member.InterfaceType.FullName + "." + name;
4606 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
4607 Report.SymbolRelatedToPreviousError (implementing);
4608 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4609 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4616 // For implicit implementations, make sure we are public, for
4617 // explicit implementations, make sure we are private.
4619 if (implementing != null){
4621 // Setting null inside this block will trigger a more
4622 // verbose error reporting for missing interface implementations
4624 // The "candidate" function has been flagged already
4625 // but it wont get cleared
4627 if (member.IsExplicitImpl){
4628 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4629 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4630 implementing = null;
4632 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4633 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4635 // If this is an interface method implementation,
4636 // check for public accessibility
4638 implementing = null;
4639 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4640 // We may never be private.
4641 implementing = null;
4642 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4644 // We may be protected if we're overriding something.
4646 implementing = null;
4651 // Static is not allowed
4653 if ((modifiers & Modifiers.STATIC) != 0){
4654 implementing = null;
4655 Modifiers.Error_InvalidModifier (method.Location, "static");
4660 // If implementing is still valid, set flags
4662 if (implementing != null){
4664 // When implementing interface methods, set NewSlot
4665 // unless, we are overwriting a method.
4667 if (implementing.DeclaringType.IsInterface){
4668 if ((modifiers & Modifiers.OVERRIDE) == 0)
4669 flags |= MethodAttributes.NewSlot;
4672 MethodAttributes.Virtual |
4673 MethodAttributes.HideBySig;
4675 // Set Final unless we're virtual, abstract or already overriding a method.
4676 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4677 flags |= MethodAttributes.Final;
4680 EmitContext ec = method.CreateEmitContext (container, null);
4682 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4684 if (builder == null)
4687 if ((modifiers & Modifiers.UNSAFE) != 0)
4688 builder.InitLocals = false;
4690 if (implementing != null){
4692 // clear the pending implemntation flag
4694 if (member is Indexer) {
4695 container.Pending.ImplementIndexer (
4696 member.InterfaceType, builder, method.ReturnType,
4697 ParameterInfo, member.IsExplicitImpl);
4699 container.Pending.ImplementMethod (
4700 member.InterfaceType, name, method.ReturnType,
4701 ParameterInfo, member.IsExplicitImpl);
4703 if (member.IsExplicitImpl)
4704 container.TypeBuilder.DefineMethodOverride (
4705 builder, implementing);
4709 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4710 TypeManager.AddMethod (builder, method);
4717 /// Create the MethodBuilder for the method
4719 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4721 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4723 if ((modifiers & extern_static) == extern_static) {
4725 if (method.OptAttributes != null) {
4726 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4727 if (dllimport_attribute != null) {
4728 flags |= MethodAttributes.PinvokeImpl;
4729 builder = dllimport_attribute.DefinePInvokeMethod (
4730 ec, container.TypeBuilder, method_name, flags,
4731 method.ReturnType, ParameterTypes);
4737 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4738 // We are more strict than Microsoft and report CS0626 like error
4739 if (method.OptAttributes == null ||
4740 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4741 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",
4742 method.GetSignatureForError ());
4747 builder = container.TypeBuilder.DefineMethod (
4748 method_name, flags, method.CallingConventions,
4749 method.ReturnType, ParameterTypes);
4755 public void Emit (TypeContainer container, Attributable kind)
4758 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4759 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4761 ec = method.CreateEmitContext (container, null);
4763 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
4764 ec.TestObsoleteMethodUsage = false;
4766 Attributes OptAttributes = method.OptAttributes;
4768 if (OptAttributes != null)
4769 OptAttributes.Emit (ec, kind);
4771 if (member is MethodCore)
4772 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
4774 ToplevelBlock block = method.Block;
4776 SourceMethod source = SourceMethod.Create (
4777 container, MethodBuilder, method.Block);
4780 // Handle destructors specially
4782 // FIXME: This code generates buggy code
4784 if (member is Destructor)
4785 EmitDestructor (ec, block);
4787 ec.EmitTopBlock (method, block, ParameterInfo);
4790 source.CloseMethod ();
4793 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4795 ILGenerator ig = ec.ig;
4797 Label finish = ig.DefineLabel ();
4799 block.SetDestructor ();
4801 ig.BeginExceptionBlock ();
4802 ec.ReturnLabel = finish;
4803 ec.HasReturnLabel = true;
4804 ec.EmitTopBlock (method, block, null);
4806 // ig.MarkLabel (finish);
4807 ig.BeginFinallyBlock ();
4809 if (ec.ContainerType.BaseType != null) {
4810 Expression member_lookup = Expression.MemberLookup (
4811 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4812 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4814 if (member_lookup != null){
4815 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4817 ig.Emit (OpCodes.Ldarg_0);
4818 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4822 ig.EndExceptionBlock ();
4823 //ig.MarkLabel (ec.ReturnLabel);
4824 ig.Emit (OpCodes.Ret);
4828 // TODO: Should derive from MethodCore
4829 public class Destructor : Method {
4831 public Destructor (TypeContainer ds, Expression return_type, int mod,
4832 string name, Parameters parameters, Attributes attrs,
4834 : base (ds, return_type, mod, false, new MemberName (name),
4835 parameters, attrs, l)
4838 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4840 if (a.Type == TypeManager.conditional_attribute_type) {
4841 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4842 GetSignatureForError ());
4846 base.ApplyAttributeBuilder (a, cb);
4849 public override string GetSignatureForError ()
4851 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
4856 abstract public class MemberBase : MemberCore {
4857 public Expression Type;
4859 public MethodAttributes flags;
4861 protected readonly int explicit_mod_flags;
4864 // The "short" name of this property / indexer / event. This is the
4865 // name without the explicit interface.
4867 public string ShortName {
4868 get { return MemberName.Name; }
4870 SetMemberName (new MemberName (MemberName.Left, value));
4875 // The type of this property / indexer / event
4878 public Type MemberType {
4880 if (member_type == null && Type != null) {
4881 EmitContext ec = Parent.EmitContext;
4882 bool old_unsafe = ec.InUnsafe;
4883 ec.InUnsafe = InUnsafe;
4884 Type = Type.ResolveAsTypeTerminal (ec, false);
4885 ec.InUnsafe = old_unsafe;
4887 member_type = Type == null ? null : Type.Type;
4894 // Whether this is an interface member.
4896 public bool IsInterface;
4899 // If true, this is an explicit interface implementation
4901 public bool IsExplicitImpl;
4904 // The interface type we are explicitly implementing
4906 public Type InterfaceType = null;
4909 // The constructor is only exposed to our children
4911 protected MemberBase (TypeContainer parent, Expression type, int mod,
4912 int allowed_mod, int def_mod, MemberName name,
4913 Attributes attrs, Location loc)
4914 : base (parent, name, attrs, loc)
4916 explicit_mod_flags = mod;
4918 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4919 IsExplicitImpl = (MemberName.Left != null);
4922 protected virtual bool CheckBase ()
4924 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4925 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4929 if ((RootContext.WarningLevel >= 4) &&
4930 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4931 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4932 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4933 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4938 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4942 foreach (Type partype in parameters){
4943 if (partype == TypeManager.void_type) {
4945 1547, Location, "Keyword 'void' cannot " +
4946 "be used in this context");
4950 if (partype.IsPointer){
4953 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4957 if (ds.AsAccessible (partype, ModFlags))
4960 if (this is Indexer)
4961 Report.Error (55, Location,
4962 "Inconsistent accessibility: parameter type `" +
4963 TypeManager.CSharpName (partype) + "' is less " +
4964 "accessible than indexer `" + GetSignatureForError () + "'");
4965 else if ((this is Method) && ((Method) this).IsOperator != null)
4966 Report.Error (57, Location,
4967 "Inconsistent accessibility: parameter type `" +
4968 TypeManager.CSharpName (partype) + "' is less " +
4969 "accessible than operator `" + GetSignatureForError () + "'");
4971 Report.Error (51, Location,
4972 "Inconsistent accessibility: parameter type `" +
4973 TypeManager.CSharpName (partype) + "' is less " +
4974 "accessible than method `" + GetSignatureForError () + "'");
4981 protected virtual bool DoDefine ()
4983 EmitContext ec = Parent.EmitContext;
4985 throw new InternalErrorException ("MemberBase.DoDefine called too early");
4988 throw new InternalErrorException ();
4991 ModFlags = Modifiers.PUBLIC |
4992 Modifiers.ABSTRACT |
4993 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
4995 flags = MethodAttributes.Public |
4996 MethodAttributes.Abstract |
4997 MethodAttributes.HideBySig |
4998 MethodAttributes.NewSlot |
4999 MethodAttributes.Virtual;
5001 if (!Parent.MethodModifiersValid (this))
5004 flags = Modifiers.MethodAttr (ModFlags);
5007 if (MemberType == null)
5010 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5011 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5012 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5013 GetSignatureForError (), Parent.GetSignatureForError ());
5017 // verify accessibility
5018 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5019 Report.SymbolRelatedToPreviousError (MemberType);
5020 if (this is Property)
5021 Report.Error (53, Location,
5022 "Inconsistent accessibility: property type `" +
5023 TypeManager.CSharpName (MemberType) + "' is less " +
5024 "accessible than property `" + GetSignatureForError () + "'");
5025 else if (this is Indexer)
5026 Report.Error (54, Location,
5027 "Inconsistent accessibility: indexer return type `" +
5028 TypeManager.CSharpName (MemberType) + "' is less " +
5029 "accessible than indexer `" + GetSignatureForError () + "'");
5030 else if (this is MethodCore) {
5031 if (this is Operator)
5032 Report.Error (56, Location,
5033 "Inconsistent accessibility: return type `" +
5034 TypeManager.CSharpName (MemberType) + "' is less " +
5035 "accessible than operator `" + GetSignatureForError () + "'");
5037 Report.Error (50, Location,
5038 "Inconsistent accessibility: return type `" +
5039 TypeManager.CSharpName (MemberType) + "' is less " +
5040 "accessible than method `" + GetSignatureForError () + "'");
5042 Report.Error (52, Location,
5043 "Inconsistent accessibility: field type `" +
5044 TypeManager.CSharpName (MemberType) + "' is less " +
5045 "accessible than field `" + GetSignatureForError () + "'");
5050 if (MemberType.IsPointer && !UnsafeOK (Parent))
5053 if (IsExplicitImpl) {
5054 Expression expr = MemberName.Left.GetTypeExpression (Location);
5055 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5059 InterfaceType = texpr.ResolveType (ec);
5061 if (!InterfaceType.IsInterface) {
5062 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5066 if (!Parent.VerifyImplements (this))
5069 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5075 protected bool IsTypePermitted ()
5077 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5078 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5084 protected override bool VerifyClsCompliance(DeclSpace ds)
5086 if (base.VerifyClsCompliance (ds)) {
5090 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5091 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5096 protected override void VerifyObsoleteAttribute()
5098 CheckUsageOfObsoleteAttribute (MemberType);
5103 // Fields and Events both generate FieldBuilders, we use this to share
5104 // their common bits. This is also used to flag usage of the field
5106 abstract public class FieldBase : MemberBase {
5107 public FieldBuilder FieldBuilder;
5108 public Status status;
5111 public enum Status : byte {
5113 HAS_OFFSET = 4 // Used by FieldMember.
5116 static string[] attribute_targets = new string [] { "field" };
5119 /// Symbol with same name in base class/struct
5121 public MemberInfo conflict_symbol;
5124 // The constructor is only exposed to our children
5126 protected FieldBase (TypeContainer parent, Expression type, int mod,
5127 int allowed_mod, MemberName name, object init,
5128 Attributes attrs, Location loc)
5129 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5135 public override AttributeTargets AttributeTargets {
5137 return AttributeTargets.Field;
5141 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5143 if (a.Type == TypeManager.marshal_as_attr_type) {
5144 UnmanagedMarshal marshal = a.GetMarshal (this);
5145 if (marshal != null) {
5146 FieldBuilder.SetMarshal (marshal);
5151 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5152 a.Error_InvalidSecurityParent ();
5156 FieldBuilder.SetCustomAttribute (cb);
5160 // Whether this field has an initializer.
5162 public bool HasInitializer {
5164 return init != null;
5168 protected readonly Object init;
5171 Expression init_expr;
5172 bool init_expr_initialized = false;
5175 // Resolves and returns the field initializer.
5177 public Expression GetInitializerExpression (EmitContext ec)
5179 if (init_expr_initialized)
5183 if (init is Expression)
5184 e = (Expression) init;
5186 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5188 // TODO: Any reason why we are using parent EC ?
5189 EmitContext parent_ec = Parent.EmitContext;
5191 bool old_is_static = parent_ec.IsStatic;
5192 bool old_is_ctor = parent_ec.IsConstructor;
5193 parent_ec.IsStatic = ec.IsStatic;
5194 parent_ec.IsConstructor = ec.IsConstructor;
5195 parent_ec.IsFieldInitializer = true;
5196 e = e.DoResolve (parent_ec);
5197 parent_ec.IsFieldInitializer = false;
5198 parent_ec.IsStatic = old_is_static;
5199 parent_ec.IsConstructor = old_is_ctor;
5202 init_expr_initialized = true;
5207 protected override bool CheckBase ()
5209 if (!base.CheckBase ())
5216 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5217 if (conflict_symbol == null) {
5218 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5219 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5224 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5225 Report.SymbolRelatedToPreviousError (conflict_symbol);
5226 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5227 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5233 protected virtual bool IsFieldClsCompliant {
5235 if (FieldBuilder == null)
5238 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5242 public override string[] ValidAttributeTargets {
5244 return attribute_targets;
5248 protected override bool VerifyClsCompliance (DeclSpace ds)
5250 if (!base.VerifyClsCompliance (ds))
5253 if (!IsFieldClsCompliant) {
5254 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5260 public void SetAssigned ()
5262 status |= Status.ASSIGNED;
5266 public abstract class FieldMember: FieldBase
5268 protected FieldMember (TypeContainer parent, Expression type, int mod,
5269 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5270 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5272 if ((mod & Modifiers.ABSTRACT) != 0)
5273 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5276 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5278 if (a.Type == TypeManager.field_offset_attribute_type)
5280 status |= Status.HAS_OFFSET;
5282 if (!Parent.HasExplicitLayout) {
5283 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5287 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5288 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5294 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5295 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5300 base.ApplyAttributeBuilder (a, cb);
5304 public override bool Define()
5306 EmitContext ec = Parent.EmitContext;
5308 throw new InternalErrorException ("FieldMember.Define called too early");
5310 if (MemberType == null)
5313 if (MemberType == TypeManager.void_type) {
5314 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5321 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5322 Report.Error (52, Location,
5323 "Inconsistent accessibility: field type `" +
5324 TypeManager.CSharpName (MemberType) + "' is less " +
5325 "accessible than field `" + GetSignatureForError () + "'");
5329 if (!IsTypePermitted ())
5332 if (MemberType.IsPointer && !UnsafeOK (Parent))
5338 public override void Emit ()
5340 if (OptAttributes != null) {
5341 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5342 OptAttributes.Emit (ec, this);
5345 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5346 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5353 // Represents header string for documentation comment.
5355 public override string DocCommentHeader {
5356 get { return "F:"; }
5360 interface IFixedBuffer
5362 FieldInfo Element { get; }
5363 Type ElementType { get; }
5366 public class FixedFieldExternal: IFixedBuffer
5368 FieldInfo element_field;
5370 public FixedFieldExternal (FieldInfo fi)
5372 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5375 #region IFixedField Members
5377 public FieldInfo Element {
5379 return element_field;
5383 public Type ElementType {
5385 return element_field.FieldType;
5393 /// Fixed buffer implementation
5395 public class FixedField: FieldMember, IFixedBuffer
5397 public const string FixedElementName = "FixedElementField";
5398 static int GlobalCounter = 0;
5399 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5400 static FieldInfo[] fi;
5402 TypeBuilder fixed_buffer_type;
5403 FieldBuilder element;
5404 Expression size_expr;
5407 const int AllowedModifiers =
5410 Modifiers.PROTECTED |
5411 Modifiers.INTERNAL |
5414 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5415 Expression size_expr, Attributes attrs, Location loc):
5416 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5418 if (RootContext.Version == LanguageVersion.ISO_1)
5419 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5421 this.size_expr = size_expr;
5424 public override bool Define()
5427 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5428 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5431 if (Parent.Kind != Kind.Struct) {
5432 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5433 GetSignatureForError ());
5437 if (!base.Define ())
5440 if (!TypeManager.IsPrimitiveType (MemberType)) {
5441 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",
5442 GetSignatureForError ());
5446 Expression e = size_expr.Resolve (Parent.EmitContext);
5450 Constant c = e as Constant;
5452 Report.Error (133, Location, "The expression being assigned to `{0}' must be constant", GetSignatureForError ());
5456 IntConstant buffer_size_const = c.ToInt (Location);
5457 if (buffer_size_const == null)
5460 buffer_size = buffer_size_const.Value;
5462 if (buffer_size <= 0) {
5463 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5467 int type_size = Expression.GetTypeSize (MemberType);
5469 if (buffer_size > int.MaxValue / type_size) {
5470 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5471 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5475 buffer_size *= type_size;
5478 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5480 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5481 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5482 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5483 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5485 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5486 TypeManager.RegisterFieldBase (FieldBuilder, this);
5491 public override void Emit()
5494 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5496 object[] fi_val = new object[1];
5497 fi_val [0] = buffer_size;
5499 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5500 ctor_args, fi, fi_val);
5501 fixed_buffer_type.SetCustomAttribute (cab);
5504 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5505 FieldBuilder.SetCustomAttribute (cab);
5510 protected override bool IsFieldClsCompliant {
5516 #region IFixedField Members
5518 public FieldInfo Element {
5524 public Type ElementType {
5534 // The Field class is used to represents class/struct fields during parsing.
5536 public class Field : FieldMember {
5538 // Modifiers allowed in a class declaration
5540 const int AllowedModifiers =
5543 Modifiers.PROTECTED |
5544 Modifiers.INTERNAL |
5547 Modifiers.VOLATILE |
5551 public Field (TypeContainer parent, Expression type, int mod, string name,
5552 Object expr_or_array_init, Attributes attrs, Location loc)
5553 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5554 expr_or_array_init, attrs, loc)
5558 public override bool Define ()
5560 if (!base.Define ())
5563 if (RootContext.WarningLevel > 1){
5564 Type ptype = Parent.TypeBuilder.BaseType;
5566 // ptype is only null for System.Object while compiling corlib.
5568 TypeContainer.FindMembers (
5569 ptype, MemberTypes.Method,
5570 BindingFlags.Public |
5571 BindingFlags.Static | BindingFlags.Instance,
5572 System.Type.FilterName, Name);
5576 if ((ModFlags & Modifiers.VOLATILE) != 0){
5577 if (!MemberType.IsClass){
5578 Type vt = MemberType;
5580 if (TypeManager.IsEnumType (vt))
5581 vt = TypeManager.EnumToUnderlying (MemberType);
5583 if (!((vt == TypeManager.bool_type) ||
5584 (vt == TypeManager.sbyte_type) ||
5585 (vt == TypeManager.byte_type) ||
5586 (vt == TypeManager.short_type) ||
5587 (vt == TypeManager.ushort_type) ||
5588 (vt == TypeManager.int32_type) ||
5589 (vt == TypeManager.uint32_type) ||
5590 (vt == TypeManager.char_type) ||
5591 (vt == TypeManager.float_type) ||
5592 (!vt.IsValueType))){
5593 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5594 GetSignatureForError (), TypeManager.CSharpName (vt));
5599 if ((ModFlags & Modifiers.READONLY) != 0){
5600 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5601 GetSignatureForError ());
5606 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5608 if (Parent.Kind == Kind.Struct &&
5609 ((fa & FieldAttributes.Static) == 0) &&
5610 MemberType == Parent.TypeBuilder &&
5611 !TypeManager.IsBuiltinType (MemberType)){
5612 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5613 "' causes a cycle in the structure layout");
5618 FieldBuilder = Parent.TypeBuilder.DefineField (
5619 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5621 TypeManager.RegisterFieldBase (FieldBuilder, this);
5623 catch (ArgumentException) {
5624 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5631 protected override bool VerifyClsCompliance (DeclSpace ds)
5633 if (!base.VerifyClsCompliance (ds))
5636 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5637 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5645 // `set' and `get' accessors are represented with an Accessor.
5647 public class Accessor {
5649 // Null if the accessor is empty, or a Block if not
5651 public const int AllowedModifiers =
5653 Modifiers.PROTECTED |
5654 Modifiers.INTERNAL |
5657 public ToplevelBlock Block;
5658 public Attributes Attributes;
5659 public Location Location;
5660 public int ModFlags;
5662 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5667 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5672 // Ooouh Martin, templates are missing here.
5673 // When it will be possible move here a lot of child code and template method type.
5674 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5675 protected MethodData method_data;
5676 protected ToplevelBlock block;
5677 protected ListDictionary declarative_security;
5679 // The accessor are created event if they are not wanted.
5680 // But we need them because their names are reserved.
5681 // Field says whether accessor will be emited or not
5682 public readonly bool IsDummy;
5684 protected readonly string prefix;
5686 ReturnParameter return_attributes;
5688 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5689 : base (null, SetupName (prefix, member), null, member.Location)
5691 this.prefix = prefix;
5695 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5697 : base (null, SetupName (prefix, member),
5698 accessor.Attributes, accessor.Location)
5700 this.prefix = prefix;
5701 this.block = accessor.Block;
5704 static MemberName SetupName (string prefix, MemberBase member)
5706 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
5709 public void UpdateName (MemberBase member)
5711 SetMemberName (SetupName (prefix, member));
5714 #region IMethodData Members
5716 public ToplevelBlock Block {
5726 public CallingConventions CallingConventions {
5728 return CallingConventions.Standard;
5732 public bool IsExcluded (EmitContext ec)
5737 public MemberName MethodName {
5743 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5744 public abstract Type[] ParameterTypes { get; }
5745 public abstract Type ReturnType { get; }
5746 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5750 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5752 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5753 a.Type == TypeManager.conditional_attribute_type) {
5754 Report.Error (1667, a.Location,
5755 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5756 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5760 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5761 if (declarative_security == null)
5762 declarative_security = new ListDictionary ();
5763 a.ExtractSecurityPermissionSet (declarative_security);
5767 if (a.Target == AttributeTargets.Method) {
5768 method_data.MethodBuilder.SetCustomAttribute (cb);
5772 if (a.Target == AttributeTargets.ReturnValue) {
5773 if (return_attributes == null)
5774 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5776 return_attributes.ApplyAttributeBuilder (a, cb);
5780 ApplyToExtraTarget (a, cb);
5783 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5785 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5788 public override bool Define()
5790 throw new NotSupportedException ();
5793 public virtual void Emit (TypeContainer container)
5795 EmitMethod (container);
5797 if (declarative_security != null) {
5798 foreach (DictionaryEntry de in declarative_security) {
5799 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5806 protected virtual void EmitMethod (TypeContainer container)
5808 method_data.Emit (container, this);
5811 public override bool IsClsCompliaceRequired(DeclSpace ds)
5816 public bool IsDuplicateImplementation (MethodCore method)
5818 if (Name != method.Name)
5821 Type[] param_types = method.ParameterTypes;
5823 if (param_types.Length != ParameterTypes.Length)
5826 for (int i = 0; i < param_types.Length; i++)
5827 if (param_types [i] != ParameterTypes [i])
5830 Report.SymbolRelatedToPreviousError (method);
5831 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
5835 public override bool IsUsed
5845 public new Location Location {
5847 return base.Location;
5852 // Represents header string for documentation comment.
5854 public override string DocCommentHeader {
5855 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5858 protected override void VerifyObsoleteAttribute()
5865 // Properties and Indexers both generate PropertyBuilders, we use this to share
5866 // their common bits.
5868 abstract public class PropertyBase : MethodCore {
5870 public class GetMethod: PropertyMethod
5872 static string[] attribute_targets = new string [] { "method", "return" };
5874 public GetMethod (MethodCore method):
5875 base (method, "get_")
5879 public GetMethod (MethodCore method, Accessor accessor):
5880 base (method, accessor, "get_")
5884 public override MethodBuilder Define(TypeContainer container)
5886 base.Define (container);
5888 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5890 if (!method_data.Define (container))
5893 return method_data.MethodBuilder;
5896 public override Type ReturnType {
5898 return method.MemberType;
5902 public override string[] ValidAttributeTargets {
5904 return attribute_targets;
5909 public class SetMethod: PropertyMethod {
5911 static string[] attribute_targets = new string [] { "method", "param", "return" };
5912 ImplicitParameter param_attr;
5914 public SetMethod (MethodCore method):
5915 base (method, "set_")
5919 public SetMethod (MethodCore method, Accessor accessor):
5920 base (method, accessor, "set_")
5924 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5926 if (a.Target == AttributeTargets.Parameter) {
5927 if (param_attr == null)
5928 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
5930 param_attr.ApplyAttributeBuilder (a, cb);
5934 base.ApplyAttributeBuilder (a, cb);
5937 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5939 Parameter [] parms = new Parameter [1];
5940 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
5941 Parameters parameters = new Parameters (parms, null);
5943 bool old_unsafe = ec.InUnsafe;
5944 ec.InUnsafe = InUnsafe;
5945 Type [] types = parameters.GetParameterInfo (ec);
5946 ec.InUnsafe = old_unsafe;
5948 return new InternalParameters (types, parameters);
5951 public override MethodBuilder Define (TypeContainer container)
5953 if (container.EmitContext == null)
5954 throw new InternalErrorException ("SetMethod.Define called too early");
5956 base.Define (container);
5958 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5960 if (!method_data.Define (container))
5963 return method_data.MethodBuilder;
5966 public override Type[] ParameterTypes {
5968 return new Type[] { method.MemberType };
5972 public override Type ReturnType {
5974 return TypeManager.void_type;
5978 public override string[] ValidAttributeTargets {
5980 return attribute_targets;
5985 static string[] attribute_targets = new string [] { "property" };
5987 public abstract class PropertyMethod: AbstractPropertyEventMethod
5989 protected readonly MethodCore method;
5990 protected MethodAttributes flags;
5992 public PropertyMethod (MethodCore method, string prefix)
5993 : base (method, prefix)
5995 this.method = method;
5996 Parent = method.Parent;
5999 public PropertyMethod (MethodCore method, Accessor accessor,
6001 : base (method, accessor, prefix)
6003 this.method = method;
6004 Parent = method.Parent;
6005 this.ModFlags = accessor.ModFlags;
6007 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6008 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6012 public override AttributeTargets AttributeTargets {
6014 return AttributeTargets.Method;
6018 public override bool IsClsCompliaceRequired(DeclSpace ds)
6020 return method.IsClsCompliaceRequired (ds);
6023 public InternalParameters ParameterInfo
6026 return method_data.ParameterInfo;
6030 public virtual MethodBuilder Define (TypeContainer container)
6032 if (!method.CheckAbstractAndExtern (block != null))
6036 // Check for custom access modifier
6038 if (ModFlags == 0) {
6039 ModFlags = method.ModFlags;
6040 flags = method.flags;
6042 if (container.Kind == Kind.Interface)
6043 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6044 GetSignatureForError ());
6046 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6047 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6050 CheckModifiers (container, ModFlags);
6051 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6052 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6053 flags = Modifiers.MethodAttr (ModFlags);
6054 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6058 // Setup iterator if we are one
6060 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6061 Iterator iterator = new Iterator (this,
6062 Parent, method.ParameterInfo, ModFlags);
6064 if (!iterator.DefineIterator ())
6071 public bool HasCustomAccessModifier
6074 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6078 public override Type[] ParameterTypes {
6080 return TypeManager.NoTypes;
6084 public override EmitContext CreateEmitContext (TypeContainer tc,
6087 return new EmitContext (
6088 tc, method.Parent, method.Location, ig, ReturnType,
6089 method.ModFlags, false);
6092 public override ObsoleteAttribute GetObsoleteAttribute ()
6094 return method.GetObsoleteAttribute (method.Parent);
6097 public override string GetSignatureForError()
6099 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6102 void CheckModifiers (TypeContainer container, int modflags)
6105 int mflags = method.ModFlags & Modifiers.Accessibility;
6107 if ((mflags & Modifiers.PUBLIC) != 0) {
6108 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6110 else if ((mflags & Modifiers.PROTECTED) != 0) {
6111 if ((mflags & Modifiers.INTERNAL) != 0)
6112 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6114 flags |= Modifiers.PRIVATE;
6116 else if ((mflags & Modifiers.INTERNAL) != 0)
6117 flags |= Modifiers.PRIVATE;
6119 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6120 Report.Error (273, Location,
6121 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6122 GetSignatureForError (), method.GetSignatureForError ());
6126 public override bool MarkForDuplicationCheck ()
6128 caching_flags |= Flags.TestMethodDuplication;
6134 public PropertyMethod Get, Set;
6135 public PropertyBuilder PropertyBuilder;
6136 public MethodBuilder GetBuilder, SetBuilder;
6138 protected EmitContext ec;
6140 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6141 int allowed_mod, bool is_iface, MemberName name,
6142 Parameters parameters, Attributes attrs,
6144 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6145 attrs, parameters, loc)
6149 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6151 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6152 a.Error_InvalidSecurityParent ();
6156 PropertyBuilder.SetCustomAttribute (cb);
6159 public override AttributeTargets AttributeTargets {
6161 return AttributeTargets.Property;
6165 public override bool Define ()
6170 if (!IsTypePermitted ())
6176 protected override bool DoDefine ()
6178 if (!base.DoDefine ())
6182 // Accessors modifiers check
6184 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6185 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6186 GetSignatureForError ());
6190 if ((Get.IsDummy || Set.IsDummy)
6191 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6192 Report.Error (276, Location,
6193 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6194 GetSignatureForError ());
6198 if (MemberType.IsAbstract && MemberType.IsSealed) {
6199 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6203 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6207 protected override bool CheckForDuplications ()
6209 ArrayList ar = Parent.Indexers;
6211 int arLen = ar.Count;
6213 for (int i = 0; i < arLen; i++) {
6214 Indexer m = (Indexer) ar [i];
6215 if (IsDuplicateImplementation (m))
6220 ar = Parent.Properties;
6222 int arLen = ar.Count;
6224 for (int i = 0; i < arLen; i++) {
6225 Property m = (Property) ar [i];
6226 if (IsDuplicateImplementation (m))
6234 // TODO: rename to Resolve......
6235 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6237 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6238 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6240 if (base_property == null)
6243 base_ret_type = base_property.PropertyType;
6244 MethodInfo get_accessor = base_property.GetGetMethod (true);
6245 MethodInfo set_accessor = base_property.GetSetMethod (true);
6246 MethodAttributes get_accessor_access, set_accessor_access;
6248 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6249 if (Get != null && !Get.IsDummy && get_accessor == null) {
6250 Report.SymbolRelatedToPreviousError (base_property);
6251 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6254 if (Set != null && !Set.IsDummy && set_accessor == null) {
6255 Report.SymbolRelatedToPreviousError (base_property);
6256 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6261 // Check base class accessors access
6264 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6265 get_accessor_access = set_accessor_access = 0;
6266 if ((ModFlags & Modifiers.NEW) == 0) {
6267 if (get_accessor != null) {
6268 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6269 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6271 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6272 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6275 if (set_accessor != null) {
6276 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6277 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6279 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6280 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6285 // Get the less restrictive access
6287 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6290 public override void Emit ()
6293 // The PropertyBuilder can be null for explicit implementations, in that
6294 // case, we do not actually emit the ".property", so there is nowhere to
6295 // put the attribute
6297 if (PropertyBuilder != null && OptAttributes != null)
6298 OptAttributes.Emit (ec, this);
6310 /// Tests whether accessors are not in collision with some method (CS0111)
6312 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6314 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6317 public override bool IsUsed
6323 return Get.IsUsed | Set.IsUsed;
6327 protected override void SetMemberName (MemberName new_name)
6329 base.SetMemberName (new_name);
6331 Get.UpdateName (this);
6332 Set.UpdateName (this);
6335 public override string[] ValidAttributeTargets {
6337 return attribute_targets;
6342 // Represents header string for documentation comment.
6344 public override string DocCommentHeader {
6345 get { return "P:"; }
6349 public class Property : PropertyBase, IIteratorContainer {
6350 const int AllowedModifiers =
6353 Modifiers.PROTECTED |
6354 Modifiers.INTERNAL |
6358 Modifiers.OVERRIDE |
6359 Modifiers.ABSTRACT |
6362 Modifiers.METHOD_YIELDS |
6365 const int AllowedInterfaceModifiers =
6368 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6369 MemberName name, Attributes attrs, Accessor get_block,
6370 Accessor set_block, Location loc)
6371 : base (ds, type, mod,
6372 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6373 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6376 if (get_block == null)
6377 Get = new GetMethod (this);
6379 Get = new GetMethod (this, get_block);
6381 if (set_block == null)
6382 Set = new SetMethod (this);
6384 Set = new SetMethod (this, set_block);
6387 public override bool Define ()
6389 if (!base.Define ())
6395 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6398 GetBuilder = Get.Define (Parent);
6399 if (GetBuilder == null)
6404 SetBuilder = Set.Define (Parent);
6405 if (SetBuilder == null)
6408 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6411 // FIXME - PropertyAttributes.HasDefault ?
6413 PropertyAttributes prop_attr = PropertyAttributes.None;
6415 prop_attr |= PropertyAttributes.RTSpecialName |
6416 PropertyAttributes.SpecialName;
6418 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6419 Name, prop_attr, MemberType, null);
6422 PropertyBuilder.SetGetMethod (GetBuilder);
6425 PropertyBuilder.SetSetMethod (SetBuilder);
6427 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6433 /// Gigantic workaround for lameness in SRE follows :
6434 /// This class derives from EventInfo and attempts to basically
6435 /// wrap around the EventBuilder so that FindMembers can quickly
6436 /// return this in it search for members
6438 public class MyEventBuilder : EventInfo {
6441 // We use this to "point" to our Builder which is
6442 // not really a MemberInfo
6444 EventBuilder MyBuilder;
6447 // We "catch" and wrap these methods
6449 MethodInfo raise, remove, add;
6451 EventAttributes attributes;
6452 Type declaring_type, reflected_type, event_type;
6457 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6459 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6461 // And now store the values in our own fields.
6463 declaring_type = type_builder;
6465 reflected_type = type_builder;
6467 attributes = event_attr;
6470 this.event_type = event_type;
6474 // Methods that you have to override. Note that you only need
6475 // to "implement" the variants that take the argument (those are
6476 // the "abstract" methods, the others (GetAddMethod()) are
6479 public override MethodInfo GetAddMethod (bool nonPublic)
6484 public override MethodInfo GetRemoveMethod (bool nonPublic)
6489 public override MethodInfo GetRaiseMethod (bool nonPublic)
6495 // These methods make "MyEventInfo" look like a Builder
6497 public void SetRaiseMethod (MethodBuilder raiseMethod)
6499 raise = raiseMethod;
6500 MyBuilder.SetRaiseMethod (raiseMethod);
6503 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6505 remove = removeMethod;
6506 MyBuilder.SetRemoveOnMethod (removeMethod);
6509 public void SetAddOnMethod (MethodBuilder addMethod)
6512 MyBuilder.SetAddOnMethod (addMethod);
6515 public void SetCustomAttribute (CustomAttributeBuilder cb)
6517 MyBuilder.SetCustomAttribute (cb);
6520 public override object [] GetCustomAttributes (bool inherit)
6522 // FIXME : There's nothing which can be seemingly done here because
6523 // we have no way of getting at the custom attribute objects of the
6528 public override object [] GetCustomAttributes (Type t, bool inherit)
6530 // FIXME : Same here !
6534 public override bool IsDefined (Type t, bool b)
6539 public override EventAttributes Attributes {
6545 public override string Name {
6551 public override Type DeclaringType {
6553 return declaring_type;
6557 public override Type ReflectedType {
6559 return reflected_type;
6563 public Type EventType {
6569 public void SetUsed ()
6571 if (my_event != null) {
6572 my_event.status = FieldBase.Status.ASSIGNED;
6573 my_event.SetMemberIsUsed ();
6579 /// For case when event is declared like property (with add and remove accessors).
6581 public class EventProperty: Event {
6583 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6585 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6586 bool is_iface, MemberName name, Object init,
6587 Attributes attrs, Accessor add, Accessor remove,
6589 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6591 Add = new AddDelegateMethod (this, add);
6592 Remove = new RemoveDelegateMethod (this, remove);
6594 // For this event syntax we don't report error CS0067
6595 // because it is hard to do it.
6599 public override string[] ValidAttributeTargets {
6601 return attribute_targets;
6607 /// Event is declared like field.
6609 public class EventField: Event {
6611 static string[] attribute_targets = new string [] { "event", "field", "method" };
6612 static string[] attribute_targets_interface = new string[] { "event", "method" };
6614 public EventField (TypeContainer parent, Expression type, int mod_flags,
6615 bool is_iface, MemberName name, Object init,
6616 Attributes attrs, Location loc)
6617 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6619 Add = new AddDelegateMethod (this);
6620 Remove = new RemoveDelegateMethod (this);
6623 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6625 if (a.Target == AttributeTargets.Field) {
6626 FieldBuilder.SetCustomAttribute (cb);
6630 if (a.Target == AttributeTargets.Method) {
6631 Add.ApplyAttributeBuilder (a, cb);
6632 Remove.ApplyAttributeBuilder (a, cb);
6636 base.ApplyAttributeBuilder (a, cb);
6639 public override string[] ValidAttributeTargets {
6641 return IsInterface ? attribute_targets_interface : attribute_targets;
6646 public abstract class Event : FieldBase {
6648 protected sealed class AddDelegateMethod: DelegateMethod
6651 public AddDelegateMethod (Event method):
6652 base (method, "add_")
6656 public AddDelegateMethod (Event method, Accessor accessor):
6657 base (method, accessor, "add_")
6661 protected override MethodInfo DelegateMethodInfo {
6663 return TypeManager.delegate_combine_delegate_delegate;
6669 protected sealed class RemoveDelegateMethod: DelegateMethod
6671 public RemoveDelegateMethod (Event method):
6672 base (method, "remove_")
6676 public RemoveDelegateMethod (Event method, Accessor accessor):
6677 base (method, accessor, "remove_")
6681 protected override MethodInfo DelegateMethodInfo {
6683 return TypeManager.delegate_remove_delegate_delegate;
6689 public abstract class DelegateMethod: AbstractPropertyEventMethod
6691 protected readonly Event method;
6692 ImplicitParameter param_attr;
6694 static string[] attribute_targets = new string [] { "method", "param", "return" };
6696 public DelegateMethod (Event method, string prefix)
6697 : base (method, prefix)
6699 this.method = method;
6702 public DelegateMethod (Event method, Accessor accessor, string prefix)
6703 : base (method, accessor, prefix)
6705 this.method = method;
6708 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6710 if (a.Target == AttributeTargets.Parameter) {
6711 if (param_attr == null)
6712 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6714 param_attr.ApplyAttributeBuilder (a, cb);
6718 base.ApplyAttributeBuilder (a, cb);
6721 public override AttributeTargets AttributeTargets {
6723 return AttributeTargets.Method;
6727 public override bool IsClsCompliaceRequired(DeclSpace ds)
6729 return method.IsClsCompliaceRequired (ds);
6732 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6734 method_data = new MethodData (method, ip, method.ModFlags,
6735 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6737 if (!method_data.Define (container))
6740 MethodBuilder mb = method_data.MethodBuilder;
6741 mb.DefineParameter (1, ParameterAttributes.None, "value");
6746 protected override void EmitMethod (TypeContainer tc)
6748 if (block != null) {
6749 base.EmitMethod (tc);
6753 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6756 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6757 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6759 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6760 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6761 ig.Emit (OpCodes.Ldsfld, field_info);
6762 ig.Emit (OpCodes.Ldarg_0);
6763 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6764 ig.Emit (OpCodes.Castclass, method.MemberType);
6765 ig.Emit (OpCodes.Stsfld, field_info);
6767 ig.Emit (OpCodes.Ldarg_0);
6768 ig.Emit (OpCodes.Ldarg_0);
6769 ig.Emit (OpCodes.Ldfld, field_info);
6770 ig.Emit (OpCodes.Ldarg_1);
6771 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6772 ig.Emit (OpCodes.Castclass, method.MemberType);
6773 ig.Emit (OpCodes.Stfld, field_info);
6775 ig.Emit (OpCodes.Ret);
6778 protected abstract MethodInfo DelegateMethodInfo { get; }
6780 public override Type[] ParameterTypes {
6782 return new Type[] { method.MemberType };
6786 public override Type ReturnType {
6788 return TypeManager.void_type;
6792 public override EmitContext CreateEmitContext (TypeContainer tc,
6795 return new EmitContext (
6796 tc, method.Parent, Location, ig, ReturnType,
6797 method.ModFlags, false);
6800 public override ObsoleteAttribute GetObsoleteAttribute ()
6802 return method.GetObsoleteAttribute (method.Parent);
6805 public override string[] ValidAttributeTargets {
6807 return attribute_targets;
6813 const int AllowedModifiers =
6816 Modifiers.PROTECTED |
6817 Modifiers.INTERNAL |
6822 Modifiers.OVERRIDE |
6826 const int AllowedInterfaceModifiers =
6829 public DelegateMethod Add, Remove;
6830 public MyEventBuilder EventBuilder;
6831 public MethodBuilder AddBuilder, RemoveBuilder;
6833 public Event (TypeContainer parent, Expression type, int mod_flags,
6834 bool is_iface, MemberName name, Object init, Attributes attrs,
6836 : base (parent, type, mod_flags,
6837 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6838 name, init, attrs, loc)
6840 IsInterface = is_iface;
6843 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6845 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6846 a.Error_InvalidSecurityParent ();
6850 EventBuilder.SetCustomAttribute (cb);
6853 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6855 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6858 public override AttributeTargets AttributeTargets {
6860 return AttributeTargets.Event;
6864 public override bool Define ()
6866 EventAttributes e_attr;
6867 e_attr = EventAttributes.None;
6872 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6873 Report.Error (74, Location, "`" + GetSignatureForError () +
6874 "': abstract event cannot have an initializer");
6878 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6879 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
6883 EmitContext ec = Parent.EmitContext;
6885 throw new InternalErrorException ("Event.Define called too early?");
6886 bool old_unsafe = ec.InUnsafe;
6887 ec.InUnsafe = InUnsafe;
6889 Parameter [] parms = new Parameter [1];
6890 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
6891 Parameters parameters = new Parameters (parms, null);
6892 Type [] types = parameters.GetParameterInfo (ec);
6893 InternalParameters ip = new InternalParameters (types, parameters);
6895 ec.InUnsafe = old_unsafe;
6901 // Now define the accessors
6904 AddBuilder = Add.Define (Parent, ip);
6905 if (AddBuilder == null)
6908 RemoveBuilder = Remove.Define (Parent, ip);
6909 if (RemoveBuilder == null)
6912 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6914 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6915 FieldBuilder = Parent.TypeBuilder.DefineField (
6917 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6918 TypeManager.RegisterPrivateFieldOfEvent (
6919 (EventInfo) EventBuilder, FieldBuilder);
6920 TypeManager.RegisterFieldBase (FieldBuilder, this);
6923 EventBuilder.SetAddOnMethod (AddBuilder);
6924 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6926 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6930 protected override bool CheckBase ()
6932 if (!base.CheckBase ())
6935 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6936 if (!(conflict_symbol is EventInfo)) {
6937 Report.SymbolRelatedToPreviousError (conflict_symbol);
6938 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
6946 public override void Emit ()
6948 if (OptAttributes != null) {
6949 EmitContext ec = new EmitContext (
6950 Parent, Location, null, MemberType, ModFlags);
6951 OptAttributes.Emit (ec, this);
6955 Remove.Emit (Parent);
6960 public override string GetSignatureForError ()
6962 return base.GetSignatureForError ();
6966 // Represents header string for documentation comment.
6968 public override string DocCommentHeader {
6969 get { return "E:"; }
6974 public class Indexer : PropertyBase {
6976 class GetIndexerMethod: GetMethod
6978 public GetIndexerMethod (MethodCore method):
6983 public GetIndexerMethod (MethodCore method, Accessor accessor):
6984 base (method, accessor)
6988 public override Type[] ParameterTypes {
6990 return method.ParameterTypes;
6995 class SetIndexerMethod: SetMethod
6997 readonly Parameters parameters;
6999 public SetIndexerMethod (MethodCore method):
7004 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7005 base (method, accessor)
7007 this.parameters = parameters;
7010 public override Type[] ParameterTypes {
7012 int top = method.ParameterTypes.Length;
7013 Type [] set_pars = new Type [top + 1];
7014 method.ParameterTypes.CopyTo (set_pars, 0);
7015 set_pars [top] = method.MemberType;
7020 protected override InternalParameters GetParameterInfo (EmitContext ec)
7022 Parameter [] fixed_parms = parameters.FixedParameters;
7024 if (fixed_parms == null){
7025 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7026 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7027 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7029 // Here is the problem: the `value' parameter has
7030 // to come *after* the array parameter in the declaration
7032 // X (object [] x, Type value)
7035 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7036 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7040 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7042 fixed_parms.CopyTo (tmp, 0);
7043 tmp [fixed_parms.Length] = new Parameter (
7044 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7046 Parameters set_formal_params = new Parameters (tmp, null);
7047 Type [] types = set_formal_params.GetParameterInfo (ec);
7049 return new InternalParameters (types, set_formal_params);
7054 const int AllowedModifiers =
7057 Modifiers.PROTECTED |
7058 Modifiers.INTERNAL |
7062 Modifiers.OVERRIDE |
7067 const int AllowedInterfaceModifiers =
7071 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7072 bool is_iface, Parameters parameters, Attributes attrs,
7073 Accessor get_block, Accessor set_block, Location loc)
7074 : base (ds, type, mod,
7075 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7076 is_iface, name, parameters, attrs, loc)
7078 if (get_block == null)
7079 Get = new GetIndexerMethod (this);
7081 Get = new GetIndexerMethod (this, get_block);
7083 if (set_block == null)
7084 Set = new SetIndexerMethod (this);
7086 Set = new SetIndexerMethod (this, parameters, set_block);
7089 public override bool Define ()
7091 PropertyAttributes prop_attr =
7092 PropertyAttributes.RTSpecialName |
7093 PropertyAttributes.SpecialName;
7095 if (!base.Define ())
7098 if (MemberType == TypeManager.void_type) {
7099 Report.Error (620, Location, "Indexers cannot have void type");
7103 if (OptAttributes != null) {
7104 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7105 if (indexer_attr != null) {
7106 // Remove the attribute from the list because it is not emitted
7107 OptAttributes.Attrs.Remove (indexer_attr);
7109 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7111 if (IsExplicitImpl) {
7112 Report.Error (415, indexer_attr.Location,
7113 "The `IndexerName' attribute is valid only on an " +
7114 "indexer that is not an explicit interface member declaration");
7118 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7119 Report.Error (609, indexer_attr.Location,
7120 "Cannot set the `IndexerName' attribute on an indexer marked override");
7124 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7125 Report.Error (633, indexer_attr.Location,
7126 "The argument to the `IndexerName' attribute must be a valid identifier");
7132 if (InterfaceType != null) {
7133 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7134 if (base_IndexerName != Name)
7135 ShortName = base_IndexerName;
7138 if (!Parent.AddToMemberContainer (this) ||
7139 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7145 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7147 GetBuilder = Get.Define (Parent);
7148 if (GetBuilder == null)
7153 SetBuilder = Set.Define (Parent);
7154 if (SetBuilder == null)
7159 // Now name the parameters
7161 Parameter [] p = Parameters.FixedParameters;
7163 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7164 Report.Error (631, Location, "ref and out are not valid in this context");
7170 for (i = 0; i < p.Length; ++i) {
7172 GetBuilder.DefineParameter (
7173 i + 1, p [i].Attributes, p [i].Name);
7176 SetBuilder.DefineParameter (
7177 i + 1, p [i].Attributes, p [i].Name);
7181 SetBuilder.DefineParameter (
7182 i + 1, ParameterAttributes.None, "value");
7184 if (i != ParameterTypes.Length) {
7185 Parameter array_param = Parameters.ArrayParameter;
7187 SetBuilder.DefineParameter (
7188 i + 1, array_param.Attributes, array_param.Name);
7192 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7193 Name, prop_attr, MemberType, ParameterTypes);
7196 PropertyBuilder.SetGetMethod (GetBuilder);
7199 PropertyBuilder.SetSetMethod (SetBuilder);
7201 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7206 public override string GetSignatureForError ()
7208 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7209 if (MemberName.Left != null) {
7211 sb.Append (MemberName.Left);
7214 sb.Append (".this");
7215 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7216 return sb.ToString ();
7219 public override bool MarkForDuplicationCheck ()
7221 caching_flags |= Flags.TestMethodDuplication;
7227 public class Operator : MethodCore, IIteratorContainer {
7229 const int AllowedModifiers =
7235 public enum OpType : byte {
7245 // Unary and Binary operators
7268 // Implicit and Explicit
7272 // Just because of enum
7276 public readonly OpType OperatorType;
7277 public MethodBuilder OperatorMethodBuilder;
7279 public Method OperatorMethod;
7281 static string[] attribute_targets = new string [] { "method", "return" };
7283 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7284 int mod_flags, Parameters parameters,
7285 ToplevelBlock block, Attributes attrs, Location loc)
7286 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7287 new MemberName ("op_" + type), attrs, parameters, loc)
7289 OperatorType = type;
7293 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7295 OperatorMethod.ApplyAttributeBuilder (a, cb);
7298 public override AttributeTargets AttributeTargets {
7300 return AttributeTargets.Method;
7304 protected override bool CheckForDuplications()
7306 ArrayList ar = Parent.Operators;
7308 int arLen = ar.Count;
7310 for (int i = 0; i < arLen; i++) {
7311 Operator o = (Operator) ar [i];
7312 if (IsDuplicateImplementation (o))
7317 ar = Parent.Methods;
7319 int arLen = ar.Count;
7321 for (int i = 0; i < arLen; i++) {
7322 Method m = (Method) ar [i];
7323 if (IsDuplicateImplementation (m))
7331 public override bool Define ()
7333 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7334 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7335 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7342 if (MemberType == TypeManager.void_type) {
7343 Report.Error (590, Location, "User-defined operators cannot return void");
7347 OperatorMethod = new Method (
7348 Parent, Type, ModFlags, false, MemberName,
7349 Parameters, OptAttributes, Location);
7351 OperatorMethod.Block = Block;
7352 OperatorMethod.IsOperator = this;
7353 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7354 OperatorMethod.Define ();
7356 if (OperatorMethod.MethodBuilder == null)
7359 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7361 parameter_types = OperatorMethod.ParameterTypes;
7362 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7363 Type return_type = OperatorMethod.ReturnType;
7364 Type first_arg_type = parameter_types [0];
7369 // Rules for conversion operators
7371 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7372 if (first_arg_type == return_type && first_arg_type == declaring_type){
7373 Report.Error (555, Location,
7374 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7378 if (first_arg_type != declaring_type && return_type != declaring_type){
7381 "User-defined conversion must convert to or from the " +
7386 if (first_arg_type == TypeManager.object_type ||
7387 return_type == TypeManager.object_type){
7390 "User-defined conversion cannot convert to or from " +
7395 if (first_arg_type.IsInterface || return_type.IsInterface){
7396 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7397 GetSignatureForError ());
7401 if (first_arg_type.IsSubclassOf (return_type)
7402 || return_type.IsSubclassOf (first_arg_type)){
7403 if (declaring_type.IsSubclassOf (return_type)) {
7404 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7405 GetSignatureForError ());
7408 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7409 GetSignatureForError ());
7412 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7413 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7414 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");
7417 } else if (Parameters.FixedParameters.Length == 1) {
7418 // Checks for Unary operators
7420 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7421 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7422 Report.Error (448, Location,
7423 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7426 if (first_arg_type != declaring_type) {
7428 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7433 if (first_arg_type != declaring_type){
7436 "The parameter of a unary operator must be the " +
7441 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7442 if (return_type != TypeManager.bool_type){
7445 "The return type of operator True or False " +
7452 // Checks for Binary operators
7454 if (first_arg_type != declaring_type &&
7455 parameter_types [1] != declaring_type){
7458 "One of the parameters of a binary operator must " +
7459 "be the containing type");
7467 public override void Emit ()
7470 // abstract or extern methods have no bodies
7472 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7475 OperatorMethod.Emit ();
7479 // Operator cannot be override
7480 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7485 public static string GetName (OpType ot)
7488 case OpType.LogicalNot:
7490 case OpType.OnesComplement:
7492 case OpType.Increment:
7494 case OpType.Decrement:
7500 case OpType.Addition:
7502 case OpType.Subtraction:
7504 case OpType.UnaryPlus:
7506 case OpType.UnaryNegation:
7508 case OpType.Multiply:
7510 case OpType.Division:
7512 case OpType.Modulus:
7514 case OpType.BitwiseAnd:
7516 case OpType.BitwiseOr:
7518 case OpType.ExclusiveOr:
7520 case OpType.LeftShift:
7522 case OpType.RightShift:
7524 case OpType.Equality:
7526 case OpType.Inequality:
7528 case OpType.GreaterThan:
7530 case OpType.LessThan:
7532 case OpType.GreaterThanOrEqual:
7534 case OpType.LessThanOrEqual:
7536 case OpType.Implicit:
7538 case OpType.Explicit:
7544 public static OpType GetOperatorType (string name)
7546 if (name.StartsWith ("op_")){
7547 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7548 if (Unary.oper_names [i] == name)
7552 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7553 if (Binary.oper_names [i] == name)
7560 public override string GetSignatureForError ()
7562 StringBuilder sb = new StringBuilder ();
7563 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7564 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7567 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7570 sb.Append (Parameters.GetSignatureForError ());
7571 return sb.ToString ();
7574 public override bool MarkForDuplicationCheck ()
7576 caching_flags |= Flags.TestMethodDuplication;
7580 public override string[] ValidAttributeTargets {
7582 return attribute_targets;
7588 // This is used to compare method signatures
7590 struct MethodSignature {
7592 public Type RetType;
7593 public Type [] Parameters;
7596 /// This delegate is used to extract methods which have the
7597 /// same signature as the argument
7599 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7601 public MethodSignature (string name, Type ret_type, Type [] parameters)
7606 if (parameters == null)
7607 Parameters = TypeManager.NoTypes;
7609 Parameters = parameters;
7612 public override string ToString ()
7615 if (Parameters.Length != 0){
7616 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7617 for (int i = 0; i < Parameters.Length; i++){
7618 sb.Append (Parameters [i]);
7619 if (i+1 < Parameters.Length)
7622 pars = sb.ToString ();
7625 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7628 public override int GetHashCode ()
7630 return Name.GetHashCode ();
7633 public override bool Equals (Object o)
7635 MethodSignature other = (MethodSignature) o;
7637 if (other.Name != Name)
7640 if (other.RetType != RetType)
7643 if (Parameters == null){
7644 if (other.Parameters == null)
7649 if (other.Parameters == null)
7652 int c = Parameters.Length;
7653 if (other.Parameters.Length != c)
7656 for (int i = 0; i < c; i++)
7657 if (other.Parameters [i] != Parameters [i])
7663 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7665 MethodSignature sig = (MethodSignature) filter_criteria;
7667 if (m.Name != sig.Name)
7671 MethodInfo mi = m as MethodInfo;
7672 PropertyInfo pi = m as PropertyInfo;
7675 ReturnType = mi.ReturnType;
7676 else if (pi != null)
7677 ReturnType = pi.PropertyType;
7682 // we use sig.RetType == null to mean `do not check the
7683 // method return value.
7685 if (sig.RetType != null)
7686 if (ReturnType != sig.RetType)
7691 args = TypeManager.GetArgumentTypes (mi);
7693 args = TypeManager.GetArgumentTypes (pi);
7694 Type [] sigp = sig.Parameters;
7696 if (args.Length != sigp.Length)
7699 for (int i = args.Length; i > 0; ){
7701 if (args [i] != sigp [i])