2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 namespace Mono.CSharp {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
79 public virtual void Emit ()
81 foreach (MemberCore mc in this)
86 public class MethodArrayList: MemberCoreArrayList
94 CachedMethods cached_method;
95 TypeContainer container;
97 public MethodArrayList (TypeContainer container)
99 this.container = container;
103 /// Method container contains Equals method
105 public bool HasEquals {
107 cached_method |= CachedMethods.Equals;
111 return (cached_method & CachedMethods.Equals) != 0;
116 /// Method container contains GetHashCode method
118 public bool HasGetHashCode {
120 cached_method |= CachedMethods.GetHashCode;
124 return (cached_method & CachedMethods.GetHashCode) != 0;
128 public override void DefineContainerMembers ()
130 base.DefineContainerMembers ();
132 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
133 Report.Warning (659, container.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
139 public sealed class IndexerArrayList: MemberCoreArrayList
142 /// The indexer name for this container
144 public string IndexerName = DefaultIndexerName;
146 bool seen_normal_indexers = false;
148 TypeContainer container;
150 public IndexerArrayList (TypeContainer container)
152 this.container = container;
156 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
157 /// class is consistent. Either it is `Item' or it is the name defined by all the
158 /// indexers with the `IndexerName' attribute.
160 /// Turns out that the IndexerNameAttribute is applied to each indexer,
161 /// but it is never emitted, instead a DefaultMember attribute is attached
164 public override void DefineContainerMembers()
166 base.DefineContainerMembers ();
168 string class_indexer_name = null;
171 // If there's both an explicit and an implicit interface implementation, the
172 // explicit one actually implements the interface while the other one is just
173 // a normal indexer. See bug #37714.
176 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
177 foreach (Indexer i in this) {
178 if (i.InterfaceType != null) {
179 if (seen_normal_indexers)
180 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
184 seen_normal_indexers = true;
186 if (class_indexer_name == null) {
187 class_indexer_name = i.ShortName;
191 if (i.ShortName != class_indexer_name)
192 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
195 if (class_indexer_name != null)
196 IndexerName = class_indexer_name;
199 public override void Emit ()
203 if (!seen_normal_indexers)
206 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
207 container.TypeBuilder.SetCustomAttribute (cb);
211 public class OperatorArrayList: MemberCoreArrayList
213 TypeContainer container;
215 public OperatorArrayList (TypeContainer container)
217 this.container = container;
221 // Operator pair checking
226 public Type ret_type;
227 public Type type1, type2;
229 public Operator.OpType ot;
231 public OperatorEntry (int f, Operator o)
235 ret_type = o.OperatorMethod.ReturnType;
236 Type [] pt = o.OperatorMethod.ParameterTypes;
243 public override int GetHashCode ()
245 return ret_type.GetHashCode ();
248 public override bool Equals (object o)
250 OperatorEntry other = (OperatorEntry) o;
252 if (other.ret_type != ret_type)
254 if (other.type1 != type1)
256 if (other.type2 != type2)
263 // Checks that some operators come in pairs:
269 // They are matched based on the return type and the argument types
271 void CheckPairedOperators ()
273 Hashtable pairs = new Hashtable (null, null);
274 Operator true_op = null;
275 Operator false_op = null;
276 bool has_equality_or_inequality = false;
278 // Register all the operators we care about.
279 foreach (Operator op in this){
282 // Skip erroneous code.
283 if (op.OperatorMethod == null)
286 switch (op.OperatorType){
287 case Operator.OpType.Equality:
289 has_equality_or_inequality = true;
291 case Operator.OpType.Inequality:
293 has_equality_or_inequality = true;
296 case Operator.OpType.True:
299 case Operator.OpType.False:
303 case Operator.OpType.GreaterThan:
305 case Operator.OpType.LessThan:
308 case Operator.OpType.GreaterThanOrEqual:
310 case Operator.OpType.LessThanOrEqual:
316 OperatorEntry oe = new OperatorEntry (reg, op);
318 object o = pairs [oe];
322 oe = (OperatorEntry) o;
327 if (true_op != null){
328 if (false_op == null)
329 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
330 true_op.GetSignatureForError ());
331 } else if (false_op != null)
332 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
333 false_op.GetSignatureForError ());
336 // Look for the mistakes.
338 foreach (DictionaryEntry de in pairs){
339 OperatorEntry oe = (OperatorEntry) de.Key;
346 case Operator.OpType.Equality:
349 case Operator.OpType.Inequality:
352 case Operator.OpType.GreaterThan:
355 case Operator.OpType.LessThan:
358 case Operator.OpType.GreaterThanOrEqual:
361 case Operator.OpType.LessThanOrEqual:
365 Report.Error (216, oe.op.Location,
366 "The operator `{0}' requires a matching operator `{1}' to also be defined",
367 oe.op.GetSignatureForError (), s);
370 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
371 if (container.Methods == null || !container.Methods.HasEquals)
372 Report.Warning (660, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
374 if (container.Methods == null || !container.Methods.HasGetHashCode)
375 Report.Warning (661, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
379 public override void DefineContainerMembers ()
381 base.DefineContainerMembers ();
382 CheckPairedOperators ();
387 // Whether this is a struct, class or interface
388 public readonly Kind Kind;
390 // Holds a list of classes and structures
393 // Holds the list of properties
394 MemberCoreArrayList properties;
396 // Holds the list of enumerations
397 MemberCoreArrayList enums;
399 // Holds the list of delegates
400 MemberCoreArrayList delegates;
402 // Holds the list of constructors
403 protected MemberCoreArrayList instance_constructors;
405 // Holds the list of fields
406 MemberCoreArrayList fields;
408 // Holds a list of fields that have initializers
409 protected ArrayList initialized_fields;
411 // Holds a list of static fields that have initializers
412 protected ArrayList initialized_static_fields;
414 // Holds the list of constants
415 MemberCoreArrayList constants;
418 MemberCoreArrayList interfaces;
420 // Holds the methods.
421 MethodArrayList methods;
424 protected MemberCoreArrayList events;
426 // Holds the indexers
427 IndexerArrayList indexers;
429 // Holds the operators
430 MemberCoreArrayList operators;
432 // Holds the iterators
435 // Holds the parts of a partial class;
439 // Pointers to the default constructor and the default static constructor
441 protected Constructor default_constructor;
442 protected Constructor default_static_constructor;
445 // Points to the first non-static field added to the container.
447 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
448 // and the first one's as good as any.
450 FieldBase first_nonstatic_field = null;
453 // This one is computed after we can distinguish interfaces
454 // from classes from the arraylist `type_bases'
456 string base_class_name;
458 TypeExpr[] iface_exprs;
460 ArrayList type_bases;
462 bool members_defined;
463 bool members_defined_ok;
465 // The interfaces we implement.
466 protected Type[] ifaces;
467 protected Type ptype;
469 // The base member cache and our member cache
470 MemberCache base_cache;
471 MemberCache member_cache;
473 public const string DefaultIndexerName = "Item";
475 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
476 Attributes attrs, Kind kind, Location l)
477 : base (ns, parent, name, attrs, l)
479 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
480 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
484 types = new ArrayList ();
486 base_class_name = null;
489 public bool AddToMemberContainer (MemberCore symbol)
491 return AddToContainer (symbol, symbol.Name);
494 protected virtual bool AddToTypeContainer (DeclSpace ds)
496 return AddToContainer (ds, ds.Basename);
499 public void AddConstant (Const constant)
501 if (!AddToMemberContainer (constant))
504 if (constants == null)
505 constants = new MemberCoreArrayList ();
507 constants.Add (constant);
510 public void AddEnum (Mono.CSharp.Enum e)
512 if (!AddToTypeContainer (e))
516 enums = new MemberCoreArrayList ();
521 public bool AddClassOrStruct (TypeContainer c)
523 if (!AddToTypeContainer (c))
530 public void AddDelegate (Delegate d)
532 if (!AddToTypeContainer (d))
535 if (delegates == null)
536 delegates = new MemberCoreArrayList ();
541 public void AddMethod (Method method)
543 if (!AddToMemberContainer (method))
547 methods = new MethodArrayList (this);
549 if (method.MemberName.Left != null)
550 methods.Insert (0, method);
552 methods.Add (method);
555 public void AddConstructor (Constructor c)
557 if (c.Name != Basename) {
558 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
561 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
564 if (default_static_constructor != null) {
565 Report.SymbolRelatedToPreviousError (default_static_constructor);
566 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
570 default_static_constructor = c;
573 if (default_constructor != null) {
574 Report.SymbolRelatedToPreviousError (default_constructor);
575 Report.Error (111, c.Location, Error111, c.Location, c.GetSignatureForError ());
578 default_constructor = c;
581 if (instance_constructors == null)
582 instance_constructors = new MemberCoreArrayList ();
584 instance_constructors.Add (c);
588 internal static string Error111 {
590 return "`{0}' is already defined. Rename this member or use different parameter types";
594 public bool AddInterface (TypeContainer iface)
596 if (!AddToTypeContainer (iface))
599 if (interfaces == null) {
600 interfaces = new MemberCoreArrayList ();
603 interfaces.Add (iface);
607 public void AddField (FieldMember field)
609 if (!AddToMemberContainer (field))
613 fields = new MemberCoreArrayList ();
617 if (field.HasInitializer)
618 RegisterFieldForInitialization (field);
620 if ((field.ModFlags & Modifiers.STATIC) != 0)
623 if (first_nonstatic_field == null) {
624 first_nonstatic_field = field;
628 if (Kind == Kind.Struct &&
629 first_nonstatic_field.Parent != field.Parent &&
630 RootContext.WarningLevel >= 3) {
631 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
632 Report.Warning (282, field.Location,
633 "struct instance field `{0}' found in different declaration from instance field `{1}'",
634 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
638 public void AddProperty (Property prop)
640 if (!AddToMemberContainer (prop) ||
641 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
644 if (properties == null)
645 properties = new MemberCoreArrayList ();
647 if (prop.MemberName.Left != null)
648 properties.Insert (0, prop);
650 properties.Add (prop);
653 public void AddEvent (Event e)
655 if (!AddToMemberContainer (e))
658 if (e is EventProperty) {
659 if (!AddToMemberContainer (e.Add))
662 if (!AddToMemberContainer (e.Remove))
667 events = new MemberCoreArrayList ();
674 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
676 public void AddIndexer (Indexer i)
678 if (indexers == null)
679 indexers = new IndexerArrayList (this);
681 if (i.IsExplicitImpl)
682 indexers.Insert (0, i);
687 public void AddOperator (Operator op)
689 if (!AddToMemberContainer (op))
692 if (operators == null)
693 operators = new OperatorArrayList (this);
698 public void AddIterator (Iterator i)
700 if (iterators == null)
701 iterators = new ArrayList ();
706 public void AddType (TypeContainer tc)
711 public void AddPart (ClassPart part)
714 parts = new ArrayList ();
719 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
721 if (a.Type == TypeManager.default_member_type) {
722 if (Indexers != null) {
723 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
728 base.ApplyAttributeBuilder (a, cb);
731 public override AttributeTargets AttributeTargets {
735 return AttributeTargets.Class;
737 return AttributeTargets.Struct;
739 return AttributeTargets.Interface;
741 throw new NotSupportedException ();
746 public ArrayList Types {
752 public MethodArrayList Methods {
758 public ArrayList Constants {
764 public ArrayList Interfaces {
770 public ArrayList Iterators {
778 return base_class_name;
782 public ArrayList Bases {
792 public ArrayList Fields {
798 public ArrayList InstanceConstructors {
800 return instance_constructors;
804 public ArrayList Properties {
810 public ArrayList Events {
816 public ArrayList Enums {
822 public ArrayList Indexers {
828 public ArrayList Operators {
834 public ArrayList Delegates {
840 public ArrayList Parts {
846 protected override TypeAttributes TypeAttr {
848 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
852 public string IndexerName {
854 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
858 public virtual void RegisterFieldForInitialization (FieldMember field)
860 if ((field.ModFlags & Modifiers.STATIC) != 0){
861 if (initialized_static_fields == null)
862 initialized_static_fields = new ArrayList ();
864 initialized_static_fields.Add (field);
866 if (initialized_fields == null)
867 initialized_fields = new ArrayList ();
869 initialized_fields.Add (field);
874 // Emits the instance field initializers
876 public virtual bool EmitFieldInitializers (EmitContext ec)
879 Expression instance_expr;
882 fields = initialized_static_fields;
883 instance_expr = null;
885 fields = initialized_fields;
886 instance_expr = new This (Location.Null).Resolve (ec);
892 foreach (FieldMember f in fields){
893 Expression e = f.GetInitializerExpression (ec);
897 Location l = f.Location;
898 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
899 fe.InstanceExpression = instance_expr;
900 ExpressionStatement a = new Assign (fe, e, l);
902 a = a.ResolveStatement (ec);
906 Constant c = e as Constant;
908 if (c.IsDefaultValue)
912 a.EmitStatement (ec);
919 // Defines the default constructors
921 protected void DefineDefaultConstructor (bool is_static)
925 // The default constructor is public
926 // If the class is abstract, the default constructor is protected
927 // The default static constructor is private
929 int mods = Modifiers.PUBLIC;
931 mods = Modifiers.STATIC | Modifiers.PRIVATE;
932 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
933 mods = Modifiers.PROTECTED;
935 TypeContainer constructor_parent = this;
937 constructor_parent = (TypeContainer) Parts [0];
939 c = new Constructor (constructor_parent, Basename, mods,
940 Parameters.EmptyReadOnlyParameters,
941 new ConstructorBaseInitializer (null, Location),
946 c.Block = new ToplevelBlock (null, Location);
951 /// The pending methods that need to be implemented
952 // (interfaces or abstract methods)
954 public PendingImplementation Pending;
956 public abstract PendingImplementation GetPendingImplementations ();
958 TypeExpr[] GetPartialBases (out TypeExpr base_class)
960 ArrayList ifaces = new ArrayList ();
963 Location base_loc = Location.Null;
965 foreach (ClassPart part in parts) {
966 TypeExpr new_base_class;
967 TypeExpr[] new_ifaces;
969 new_ifaces = part.GetClassBases (out new_base_class);
970 if (new_ifaces == null && new_base_class != null)
973 if ((base_class != null) && (new_base_class != null) &&
974 !base_class.Equals (new_base_class)) {
975 Report.Error (263, part.Location,
976 "Partial declarations of `{0}' must " +
977 "not specify different base classes",
980 if (!Location.IsNull (base_loc))
981 Report.LocationOfPreviousError (base_loc);
986 if ((base_class == null) && (new_base_class != null)) {
987 base_class = new_base_class;
988 base_loc = part.Location;
991 if (new_ifaces == null)
994 foreach (TypeExpr iface in new_ifaces) {
996 foreach (TypeExpr old_iface in ifaces) {
997 if (old_iface.Equals (iface)) {
1008 TypeExpr[] retval = new TypeExpr [ifaces.Count];
1009 ifaces.CopyTo (retval, 0);
1013 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1017 int count = Bases.Count;
1018 int start = 0, i, j;
1020 if (Kind == Kind.Class){
1021 TypeExpr name = ResolveBaseTypeExpr (
1022 (Expression) Bases [0], false, Location);
1028 if (!name.IsInterface) {
1029 // base_class could be a class, struct, enum, delegate.
1030 // This is validated in GetClassBases.
1036 TypeExpr [] ifaces = new TypeExpr [count-start];
1038 for (i = start, j = 0; i < count; i++, j++){
1039 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1040 if (resolved == null) {
1044 ifaces [j] = resolved;
1051 /// This function computes the Base class and also the
1052 /// list of interfaces that the class or struct @c implements.
1054 /// The return value is an array (might be null) of
1055 /// interfaces implemented (as Types).
1057 /// The @base_class argument is set to the base object or null
1058 /// if this is `System.Object'.
1060 TypeExpr [] GetClassBases (out TypeExpr base_class)
1067 ifaces = GetPartialBases (out base_class);
1068 else if (Bases == null){
1072 ifaces = GetNormalBases (out base_class);
1077 if ((base_class != null) && (Kind == Kind.Class)){
1079 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1080 Report.Error (1521, base_class.Location, "Invalid base type");
1084 if (base_class.IsSealed){
1085 Report.SymbolRelatedToPreviousError (base_class.Type);
1086 if (base_class.Type.IsAbstract) {
1087 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
1088 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1090 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
1091 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1096 if (!base_class.CanInheritFrom ()){
1097 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
1098 GetSignatureForError (), base_class.GetSignatureForError ());
1102 if (!base_class.AsAccessible (this, ModFlags)) {
1103 Report.SymbolRelatedToPreviousError (base_class.Type);
1104 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
1105 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1109 if (base_class != null)
1110 base_class_name = base_class.Name;
1115 int count = ifaces != null ? ifaces.Length : 0;
1117 for (i = 0; i < count; i++) {
1118 TypeExpr iface = (TypeExpr) ifaces [i];
1120 if (!iface.IsInterface) {
1121 if (Kind != Kind.Class) {
1122 // TODO: location of symbol related ....
1123 Error_TypeInListIsNotInterface (Location, iface.FullName);
1125 else if (base_class != null)
1126 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1127 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1129 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1130 GetSignatureForError (), iface.GetSignatureForError ());
1135 for (int x = 0; x < i; x++) {
1136 if (iface.Equals (ifaces [x])) {
1137 Report.Error (528, Location,
1138 "`{0}' is already listed in " +
1139 "interface list", iface.Name);
1144 if ((Kind == Kind.Interface) &&
1145 !iface.AsAccessible (Parent, ModFlags)) {
1146 Report.Error (61, Location,
1147 "Inconsistent accessibility: base " +
1148 "interface `{0}' is less accessible " +
1149 "than interface `{1}'", iface.Name,
1159 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1161 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1165 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1167 public override TypeBuilder DefineType ()
1172 if (TypeBuilder != null)
1175 TypeAttributes type_attributes = TypeAttr;
1179 if (TypeManager.NamespaceClash (Name, Location)) {
1184 ModuleBuilder builder = CodeGen.Module.Builder;
1185 TypeBuilder = builder.DefineType (
1186 Name, type_attributes, null, null);
1188 TypeBuilder builder = Parent.TypeBuilder;
1189 if (builder == null) {
1194 TypeBuilder = builder.DefineNestedType (
1195 Basename, type_attributes, ptype, null);
1197 } catch (ArgumentException) {
1198 Report.RuntimeMissingSupport (Location, "static classes");
1203 TypeManager.AddUserType (Name, this);
1205 if (Parts != null) {
1207 foreach (ClassPart part in Parts) {
1208 part.TypeBuilder = TypeBuilder;
1210 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1211 part.ec.ContainerType = TypeBuilder;
1215 // Normally, we create the EmitContext here.
1216 // The only exception is if we're an Iterator - in this case,
1217 // we already have the `ec', so we don't want to create a new one.
1220 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1221 ec.ContainerType = TypeBuilder;
1224 iface_exprs = GetClassBases (out base_type);
1225 if (iface_exprs == null && base_type != null) {
1230 if (base_type == null) {
1231 if (Kind == Kind.Class){
1232 if (RootContext.StdLib)
1233 base_type = TypeManager.system_object_expr;
1234 else if (Name != "System.Object")
1235 base_type = TypeManager.system_object_expr;
1236 } else if (Kind == Kind.Struct) {
1238 // If we are compiling our runtime,
1239 // and we are defining ValueType, then our
1240 // base is `System.Object'.
1242 if (!RootContext.StdLib && Name == "System.ValueType")
1243 base_type = TypeManager.system_object_expr;
1245 base_type = TypeManager.system_valuetype_expr;
1249 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1250 throw new Exception ();
1252 if (base_type != null) {
1253 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1254 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1255 ptype = base_type.ResolveType (TypeResolveEmitContext);
1256 if (ptype == null) {
1262 if (!CheckRecursiveDefinition (this)) {
1268 TypeBuilder.SetParent (ptype);
1270 // add interfaces that were not added at type creation
1271 if (iface_exprs != null) {
1272 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1273 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1274 TypeResolveEmitContext.ContainerType = TypeBuilder;
1275 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1276 if (ifaces == null) {
1281 foreach (Type itype in ifaces)
1282 TypeBuilder.AddInterfaceImplementation (itype);
1284 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1287 if (!(this is Iterator))
1288 RootContext.RegisterOrder (this);
1290 if (!DefineNestedTypes ()) {
1298 protected virtual bool DefineNestedTypes ()
1300 if (Interfaces != null) {
1301 foreach (TypeContainer iface in Interfaces)
1302 if (iface.DefineType () == null)
1306 if (Types != null) {
1307 foreach (TypeContainer tc in Types)
1308 if (tc.DefineType () == null)
1312 if (Delegates != null) {
1313 foreach (Delegate d in Delegates)
1314 if (d.DefineType () == null)
1318 if (Enums != null) {
1319 foreach (Enum en in Enums)
1320 if (en.DefineType () == null)
1327 TypeContainer InTransit;
1329 protected bool CheckRecursiveDefinition (TypeContainer tc)
1331 if (InTransit != null) {
1332 Report.SymbolRelatedToPreviousError (this);
1333 if (this is Interface)
1335 529, tc.Location, "Inherited interface `{0}' causes a " +
1336 "cycle in the interface hierarchy of `{1}'",
1337 GetSignatureForError (), tc.GetSignatureForError ());
1340 146, tc.Location, "Circular base class dependency " +
1341 "involving `{0}' and `{1}'",
1342 tc.GetSignatureForError (), GetSignatureForError ());
1348 Type parent = ptype;
1349 if (parent != null) {
1350 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1351 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1355 if (iface_exprs != null) {
1356 foreach (TypeExpr iface in iface_exprs) {
1357 Type itype = iface.Type;
1359 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1360 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1369 public static void Error_KeywordNotAllowed (Location loc)
1371 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1375 /// Populates our TypeBuilder with fields and methods
1377 public override bool DefineMembers (TypeContainer container)
1379 if (members_defined)
1380 return members_defined_ok;
1382 if (!base.DefineMembers (container))
1385 members_defined_ok = DoDefineMembers ();
1386 members_defined = true;
1388 return members_defined_ok;
1391 protected virtual bool DoDefineMembers ()
1394 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1395 if (conflict_symbol == null) {
1396 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1397 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1399 if ((ModFlags & Modifiers.NEW) == 0) {
1400 Report.SymbolRelatedToPreviousError (conflict_symbol);
1401 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1402 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1407 DefineContainerMembers (constants);
1408 DefineContainerMembers (fields);
1410 if ((Kind == Kind.Class) && !(this is ClassPart)){
1411 if ((instance_constructors == null) &&
1412 !(this is StaticClass)) {
1413 if (default_constructor == null)
1414 DefineDefaultConstructor (false);
1417 if (initialized_static_fields != null &&
1418 default_static_constructor == null)
1419 DefineDefaultConstructor (true);
1422 if (Kind == Kind.Struct){
1424 // Structs can not have initialized instance
1427 if (initialized_static_fields != null &&
1428 default_static_constructor == null)
1429 DefineDefaultConstructor (true);
1431 if (initialized_fields != null)
1432 ReportStructInitializedInstanceError ();
1435 Pending = GetPendingImplementations ();
1437 if (parts != null) {
1438 foreach (ClassPart part in parts) {
1439 if (!part.DefineMembers (this))
1445 // Constructors are not in the defined_names array
1447 DefineContainerMembers (instance_constructors);
1449 if (default_static_constructor != null)
1450 default_static_constructor.Define ();
1452 DefineContainerMembers (properties);
1453 DefineContainerMembers (events);
1454 DefineContainerMembers (indexers);
1455 DefineContainerMembers (methods);
1456 DefineContainerMembers (operators);
1457 DefineContainerMembers (enums);
1458 DefineContainerMembers (delegates);
1461 if (!(this is ClassPart))
1462 member_cache = new MemberCache (this);
1465 if (parts != null) {
1466 foreach (ClassPart part in parts)
1467 part.member_cache = member_cache;
1470 if (iterators != null) {
1471 foreach (Iterator iterator in iterators) {
1472 if (iterator.DefineType () == null)
1476 foreach (Iterator iterator in iterators) {
1477 if (!iterator.DefineMembers (this))
1485 void ReportStructInitializedInstanceError ()
1487 foreach (Field f in initialized_fields){
1488 Report.Error (573, Location,
1489 "`{0}': Structs cannot have instance field initializers",
1490 f.GetSignatureForError ());
1494 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1497 mcal.DefineContainerMembers ();
1500 public override bool Define ()
1502 if (parts != null) {
1503 foreach (ClassPart part in parts) {
1504 if (!part.Define ())
1509 if (iterators != null) {
1510 foreach (Iterator iterator in iterators) {
1511 if (!iterator.Define ())
1519 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1521 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1525 /// This function is based by a delegate to the FindMembers routine
1527 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1533 /// This filter is used by FindMembers, and we just keep
1534 /// a global for the filter to `AlwaysAccept'
1536 static MemberFilter accepting_filter;
1539 static TypeContainer ()
1541 accepting_filter = new MemberFilter (AlwaysAccept);
1544 public MethodInfo[] GetMethods ()
1546 ArrayList members = new ArrayList ();
1548 DefineMembers (null);
1550 if (methods != null) {
1551 int len = methods.Count;
1552 for (int i = 0; i < len; i++) {
1553 Method m = (Method) methods [i];
1555 members.Add (m.MethodBuilder);
1559 if (operators != null) {
1560 int len = operators.Count;
1561 for (int i = 0; i < len; i++) {
1562 Operator o = (Operator) operators [i];
1564 members.Add (o.OperatorMethodBuilder);
1568 if (properties != null) {
1569 int len = properties.Count;
1570 for (int i = 0; i < len; i++) {
1571 Property p = (Property) properties [i];
1573 if (p.GetBuilder != null)
1574 members.Add (p.GetBuilder);
1575 if (p.SetBuilder != null)
1576 members.Add (p.SetBuilder);
1580 if (indexers != null) {
1581 int len = indexers.Count;
1582 for (int i = 0; i < len; i++) {
1583 Indexer ix = (Indexer) indexers [i];
1585 if (ix.GetBuilder != null)
1586 members.Add (ix.GetBuilder);
1587 if (ix.SetBuilder != null)
1588 members.Add (ix.SetBuilder);
1592 if (events != null) {
1593 int len = events.Count;
1594 for (int i = 0; i < len; i++) {
1595 Event e = (Event) events [i];
1597 if (e.AddBuilder != null)
1598 members.Add (e.AddBuilder);
1599 if (e.RemoveBuilder != null)
1600 members.Add (e.RemoveBuilder);
1604 MethodInfo[] retMethods = new MethodInfo [members.Count];
1605 members.CopyTo (retMethods, 0);
1609 // Indicated whether container has StructLayout attribute set Explicit
1610 public virtual bool HasExplicitLayout {
1616 public override Type FindNestedType (string name)
1618 ArrayList [] lists = { types, enums, delegates, interfaces };
1620 for (int j = 0; j < lists.Length; ++j) {
1621 ArrayList list = lists [j];
1625 int len = list.Count;
1626 for (int i = 0; i < len; ++i) {
1627 DeclSpace ds = (DeclSpace) list [i];
1628 if (ds.Basename == name) {
1630 return ds.TypeBuilder;
1638 private void FindMembers_NestedTypes (int modflags,
1639 BindingFlags bf, MemberFilter filter, object criteria,
1640 ref ArrayList members)
1642 ArrayList [] lists = { types, enums, delegates, interfaces };
1644 for (int j = 0; j < lists.Length; ++j) {
1645 ArrayList list = lists [j];
1649 int len = list.Count;
1650 for (int i = 0; i < len; i++) {
1651 DeclSpace ds = (DeclSpace) list [i];
1653 if ((ds.ModFlags & modflags) == 0)
1656 TypeBuilder tb = ds.TypeBuilder;
1658 if (!(criteria is string) || ds.Basename.Equals (criteria))
1659 tb = ds.DefineType ();
1662 if (tb != null && (filter (tb, criteria) == true)) {
1663 if (members == null)
1664 members = new ArrayList ();
1673 /// This method returns the members of this type just like Type.FindMembers would
1674 /// Only, we need to use this for types which are _being_ defined because MS'
1675 /// implementation can't take care of that.
1678 // FIXME: return an empty static array instead of null, that cleans up
1679 // some code and is consistent with some coding conventions I just found
1683 // Notice that in various cases we check if our field is non-null,
1684 // something that would normally mean that there was a bug elsewhere.
1686 // The problem happens while we are defining p-invoke methods, as those
1687 // will trigger a FindMembers, but this happens before things are defined
1689 // Since the whole process is a no-op, it is fine to check for null here.
1691 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1692 MemberFilter filter, object criteria)
1694 ArrayList members = null;
1697 if ((bf & BindingFlags.Public) != 0)
1698 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1700 if ((bf & BindingFlags.NonPublic) != 0)
1701 modflags |= Modifiers.PRIVATE;
1703 int static_mask = 0, static_flags = 0;
1704 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1705 case BindingFlags.Static:
1706 static_mask = static_flags = Modifiers.STATIC;
1709 case BindingFlags.Instance:
1710 static_mask = Modifiers.STATIC;
1715 static_mask = static_flags = 0;
1719 Timer.StartTimer (TimerType.TcFindMembers);
1722 filter = accepting_filter;
1724 if ((mt & MemberTypes.Field) != 0) {
1725 if (fields != null) {
1726 int len = fields.Count;
1727 for (int i = 0; i < len; i++) {
1728 FieldMember f = (FieldMember) fields [i];
1730 if ((f.ModFlags & modflags) == 0)
1732 if ((f.ModFlags & static_mask) != static_flags)
1735 FieldBuilder fb = f.FieldBuilder;
1736 if (fb != null && filter (fb, criteria) == true) {
1737 if (members == null)
1738 members = new ArrayList ();
1745 if (constants != null) {
1746 int len = constants.Count;
1747 for (int i = 0; i < len; i++) {
1748 Const con = (Const) constants [i];
1750 if ((con.ModFlags & modflags) == 0)
1752 if ((con.ModFlags & static_mask) != static_flags)
1755 FieldBuilder fb = con.FieldBuilder;
1758 fb = con.FieldBuilder;
1760 if (fb != null && filter (fb, criteria) == true) {
1761 if (members == null)
1762 members = new ArrayList ();
1770 if ((mt & MemberTypes.Method) != 0) {
1771 if (methods != null) {
1772 int len = methods.Count;
1773 for (int i = 0; i < len; i++) {
1774 Method m = (Method) methods [i];
1776 if ((m.ModFlags & modflags) == 0)
1778 if ((m.ModFlags & static_mask) != static_flags)
1781 MethodBuilder mb = m.MethodBuilder;
1783 if (mb != null && filter (mb, criteria) == true) {
1784 if (members == null)
1785 members = new ArrayList ();
1792 if (operators != null) {
1793 int len = operators.Count;
1794 for (int i = 0; i < len; i++) {
1795 Operator o = (Operator) operators [i];
1797 if ((o.ModFlags & modflags) == 0)
1799 if ((o.ModFlags & static_mask) != static_flags)
1802 MethodBuilder ob = o.OperatorMethodBuilder;
1803 if (ob != null && filter (ob, criteria) == true) {
1804 if (members == null)
1805 members = new ArrayList ();
1812 if (properties != null) {
1813 int len = properties.Count;
1814 for (int i = 0; i < len; i++) {
1815 Property p = (Property) properties [i];
1817 if ((p.ModFlags & modflags) == 0)
1819 if ((p.ModFlags & static_mask) != static_flags)
1825 if (b != null && filter (b, criteria) == true) {
1826 if (members == null)
1827 members = new ArrayList ();
1833 if (b != null && filter (b, criteria) == true) {
1834 if (members == null)
1835 members = new ArrayList ();
1842 if (indexers != null) {
1843 int len = indexers.Count;
1844 for (int i = 0; i < len; i++) {
1845 Indexer ix = (Indexer) indexers [i];
1847 if ((ix.ModFlags & modflags) == 0)
1849 if ((ix.ModFlags & static_mask) != static_flags)
1855 if (b != null && filter (b, criteria) == true) {
1856 if (members == null)
1857 members = new ArrayList ();
1863 if (b != null && filter (b, criteria) == true) {
1864 if (members == null)
1865 members = new ArrayList ();
1873 if ((mt & MemberTypes.Event) != 0) {
1874 if (events != null) {
1875 int len = events.Count;
1876 for (int i = 0; i < len; i++) {
1877 Event e = (Event) events [i];
1879 if ((e.ModFlags & modflags) == 0)
1881 if ((e.ModFlags & static_mask) != static_flags)
1884 MemberInfo eb = e.EventBuilder;
1885 if (eb != null && filter (eb, criteria) == true) {
1886 if (members == null)
1887 members = new ArrayList ();
1889 members.Add (e.EventBuilder);
1895 if ((mt & MemberTypes.Property) != 0){
1896 if (properties != null) {
1897 int len = properties.Count;
1898 for (int i = 0; i < len; i++) {
1899 Property p = (Property) properties [i];
1901 if ((p.ModFlags & modflags) == 0)
1903 if ((p.ModFlags & static_mask) != static_flags)
1906 MemberInfo pb = p.PropertyBuilder;
1907 if (pb != null && filter (pb, criteria) == true) {
1908 if (members == null)
1909 members = new ArrayList ();
1911 members.Add (p.PropertyBuilder);
1916 if (indexers != null) {
1917 int len = indexers.Count;
1918 for (int i = 0; i < len; i++) {
1919 Indexer ix = (Indexer) indexers [i];
1921 if ((ix.ModFlags & modflags) == 0)
1923 if ((ix.ModFlags & static_mask) != static_flags)
1926 MemberInfo ib = ix.PropertyBuilder;
1927 if (ib != null && filter (ib, criteria) == true) {
1928 if (members == null)
1929 members = new ArrayList ();
1931 members.Add (ix.PropertyBuilder);
1937 if ((mt & MemberTypes.NestedType) != 0)
1938 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1940 if ((mt & MemberTypes.Constructor) != 0){
1941 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1942 int len = instance_constructors.Count;
1943 for (int i = 0; i < len; i++) {
1944 Constructor c = (Constructor) instance_constructors [i];
1946 ConstructorBuilder cb = c.ConstructorBuilder;
1947 if (cb != null && filter (cb, criteria) == true) {
1948 if (members == null)
1949 members = new ArrayList ();
1956 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1957 ConstructorBuilder cb =
1958 default_static_constructor.ConstructorBuilder;
1960 if (cb != null && filter (cb, criteria) == true) {
1961 if (members == null)
1962 members = new ArrayList ();
1970 // Lookup members in base if requested.
1972 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1973 if (TypeBuilder.BaseType != null) {
1974 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1975 if (list.Count > 0) {
1976 if (members == null)
1977 members = new ArrayList ();
1979 members.AddRange (list);
1982 if (ifaces != null) {
1983 foreach (Type base_type in ifaces) {
1984 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1986 if (list.Count > 0) {
1987 if (members == null)
1988 members = new ArrayList ();
1989 members.AddRange (list);
1995 Timer.StopTimer (TimerType.TcFindMembers);
1997 if (members == null)
1998 return MemberList.Empty;
2000 return new MemberList (members);
2003 public override MemberCache MemberCache {
2005 return member_cache;
2009 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2010 MemberFilter filter, object criteria)
2012 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2015 return ds.FindMembers (mt, bf, filter, criteria);
2017 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2022 // FindMethods will look for methods not only in the type `t', but in
2023 // any interfaces implemented by the type.
2025 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2026 MemberFilter filter, object criteria)
2032 /// Emits the values for the constants
2034 public void EmitConstants ()
2036 if (constants != null)
2037 foreach (Const con in constants)
2042 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2047 foreach (MemberCore mc in al) {
2048 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2052 Report.Warning (169, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2057 public virtual void VerifyMembers ()
2060 // Check for internal or private fields that were never assigned
2062 if (RootContext.WarningLevel >= 3) {
2063 CheckMemberUsage (properties, "property");
2064 CheckMemberUsage (methods, "method");
2065 CheckMemberUsage (constants, "constant");
2067 if (fields != null){
2068 foreach (FieldMember f in fields) {
2069 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2073 if ((f.caching_flags & Flags.IsAssigned) == 0)
2074 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2077 const int error_code = 414;
2079 const int error_code = 169;
2081 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2082 f.GetSignatureForError ());
2088 // Only report 649 on level 4
2090 if (RootContext.WarningLevel < 4)
2093 if ((f.caching_flags & Flags.IsAssigned) != 0)
2096 Report.Warning (649, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2097 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2104 /// Emits the code, this step is performed after all
2105 /// the types, enumerations, constructors
2107 public void EmitType ()
2109 if (OptAttributes != null)
2110 OptAttributes.Emit (ec, this);
2113 // Structs with no fields need to have at least one byte.
2114 // The right thing would be to set the PackingSize in a DefineType
2115 // but there are no functions that allow interfaces *and* the size to
2119 if (Kind == Kind.Struct && first_nonstatic_field == null){
2120 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2121 FieldAttributes.Private);
2123 if (HasExplicitLayout){
2124 object [] ctor_args = new object [1];
2127 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2128 TypeManager.field_offset_attribute_ctor, ctor_args);
2129 fb.SetCustomAttribute (cba);
2135 if (instance_constructors != null) {
2136 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2137 bool has_compliant_args = false;
2139 foreach (Constructor c in instance_constructors) {
2142 if (has_compliant_args)
2145 has_compliant_args = c.HasCompliantArgs;
2147 if (!has_compliant_args)
2148 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2150 foreach (Constructor c in instance_constructors)
2155 // Can not continue if constants are broken
2157 if (Report.Errors > 0)
2160 if (default_static_constructor != null)
2161 default_static_constructor.Emit ();
2163 if (methods != null)
2164 foreach (Method m in methods)
2167 if (operators != null)
2168 foreach (Operator o in operators)
2171 if (properties != null)
2172 foreach (Property p in properties)
2175 if (indexers != null){
2180 foreach (FieldMember f in fields)
2183 if (events != null){
2184 foreach (Event e in Events)
2188 if (delegates != null) {
2189 foreach (Delegate d in Delegates) {
2194 if (enums != null) {
2195 foreach (Enum e in enums) {
2200 if (parts != null) {
2201 foreach (ClassPart part in parts)
2205 if ((Pending != null) && !(this is ClassPart))
2206 if (Pending.VerifyPendingMethods ())
2209 if (iterators != null)
2210 foreach (Iterator iterator in iterators)
2211 iterator.EmitType ();
2213 // if (types != null)
2214 // foreach (TypeContainer tc in types)
2218 public override void CloseType ()
2220 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2224 caching_flags |= Flags.CloseTypeCreated;
2225 TypeBuilder.CreateType ();
2226 } catch (TypeLoadException){
2228 // This is fine, the code still created the type
2230 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2231 // Console.WriteLine (e.Message);
2233 Console.WriteLine ("In type: " + Name);
2238 foreach (Enum en in Enums)
2242 foreach (TypeContainer tc in Types)
2243 if (tc.Kind == Kind.Struct)
2246 foreach (TypeContainer tc in Types)
2247 if (tc.Kind != Kind.Struct)
2251 if (Delegates != null)
2252 foreach (Delegate d in Delegates)
2255 if (Iterators != null)
2256 foreach (Iterator i in Iterators)
2264 initialized_fields = null;
2265 initialized_static_fields = null;
2274 default_constructor = null;
2275 default_static_constructor = null;
2277 OptAttributes = null;
2280 member_cache = null;
2284 // Performs the validation on a Method's modifiers (properties have
2285 // the same properties).
2287 public bool MethodModifiersValid (MemberCore mc)
2289 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2290 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2291 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2293 int flags = mc.ModFlags;
2296 // At most one of static, virtual or override
2298 if ((flags & Modifiers.STATIC) != 0){
2299 if ((flags & vao) != 0){
2300 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2301 mc.GetSignatureForError ());
2306 if (Kind == Kind.Struct){
2307 if ((flags & va) != 0){
2308 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2313 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2314 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2315 mc.GetSignatureForError ());
2320 // If the declaration includes the abstract modifier, then the
2321 // declaration does not include static, virtual or extern
2323 if ((flags & Modifiers.ABSTRACT) != 0){
2324 if ((flags & Modifiers.EXTERN) != 0){
2326 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2330 if ((flags & Modifiers.SEALED) != 0) {
2331 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2335 if ((flags & Modifiers.VIRTUAL) != 0){
2336 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2340 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2341 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2346 if ((flags & Modifiers.PRIVATE) != 0){
2347 if ((flags & vao) != 0){
2348 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2353 if ((flags & Modifiers.SEALED) != 0){
2354 if ((flags & Modifiers.OVERRIDE) == 0){
2355 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2363 public bool UserDefinedStaticConstructor {
2365 return default_static_constructor != null;
2369 public Constructor DefaultStaticConstructor {
2370 get { return default_static_constructor; }
2373 protected override bool VerifyClsCompliance (DeclSpace ds)
2375 if (!base.VerifyClsCompliance (ds))
2380 Type base_type = TypeBuilder.BaseType;
2381 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2382 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2385 if (!Parent.IsClsCompliaceRequired (ds)) {
2386 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type `{1}'",
2387 GetSignatureForError (), Parent.GetSignatureForError ());
2394 /// Checks whether container name is CLS Compliant
2396 void VerifyClsName ()
2398 Hashtable base_members = base_cache == null ?
2400 base_cache.GetPublicMembers ();
2401 Hashtable this_members = new Hashtable ();
2403 foreach (DictionaryEntry entry in defined_names) {
2404 MemberCore mc = (MemberCore)entry.Value;
2405 if (!mc.IsClsCompliaceRequired (this))
2408 string name = (string)entry.Key;
2409 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2411 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2412 object found = base_members [lcase];
2413 if (found == null) {
2414 found = this_members [lcase];
2415 if (found == null) {
2416 this_members.Add (lcase, mc);
2421 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2424 if (found is MemberInfo) {
2425 if (basename == ((MemberInfo)found).Name)
2427 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2429 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2431 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2437 /// Performs checks for an explicit interface implementation. First it
2438 /// checks whether the `interface_type' is a base inteface implementation.
2439 /// Then it checks whether `name' exists in the interface type.
2441 public virtual bool VerifyImplements (MemberBase mb)
2443 if (ifaces != null) {
2444 foreach (Type t in ifaces){
2445 if (t == mb.InterfaceType)
2450 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2451 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2455 protected override void VerifyObsoleteAttribute()
2457 CheckUsageOfObsoleteAttribute (ptype);
2462 foreach (Type iface in ifaces) {
2463 CheckUsageOfObsoleteAttribute (iface);
2472 string IMemberContainer.Name {
2478 Type IMemberContainer.Type {
2484 MemberCache IMemberContainer.MemberCache {
2486 return member_cache;
2490 bool IMemberContainer.IsInterface {
2492 return Kind == Kind.Interface;
2496 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2498 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2502 // Generates xml doc comments (if any), and if required,
2503 // handle warning report.
2505 internal override void GenerateDocComment (DeclSpace ds)
2507 DocUtil.GenerateTypeDocComment (this, ds);
2510 public override string DocCommentHeader {
2511 get { return "T:"; }
2514 public virtual MemberCache BaseCache {
2516 if (base_cache != null)
2518 if (TypeBuilder.BaseType != null)
2519 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2520 if (TypeBuilder.IsInterface)
2521 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2527 public class PartialContainer : TypeContainer {
2529 public readonly Namespace Namespace;
2530 public readonly int OriginalModFlags;
2531 public readonly int AllowedModifiers;
2532 public readonly TypeAttributes DefaultTypeAttributes;
2534 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2535 MemberName member_name, int mod_flags, Kind kind,
2538 PartialContainer pc = RootContext.Tree.GetDecl (member_name) as PartialContainer;
2540 if (pc.Kind != kind) {
2542 261, loc, "Partial declarations of `{0}' " +
2543 "must be all classes, all structs or " +
2544 "all interfaces", member_name.GetPartialName ());
2548 if (pc.OriginalModFlags != mod_flags) {
2550 262, loc, "Partial declarations of `{0}' " +
2551 "have conflicting accessibility modifiers",
2552 member_name.GetPartialName ());
2559 if (parent is ClassPart)
2560 parent = ((ClassPart) parent).PartialContainer;
2562 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2564 if (kind == Kind.Interface) {
2565 if (!parent.AddInterface (pc))
2567 } else if (kind == Kind.Class || kind == Kind.Struct) {
2568 if (!parent.AddClassOrStruct (pc))
2571 throw new InvalidOperationException ();
2573 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2577 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2578 MemberName name, int mod, Attributes attrs,
2579 Kind kind, Location loc)
2581 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2583 // An error occured; create a dummy container, but don't
2585 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2588 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2593 protected PartialContainer (Namespace ns, TypeContainer parent,
2594 MemberName name, int mod, Kind kind, Location l)
2595 : base (null, parent, name, null, kind, l)
2597 this.Namespace = ns;
2601 AllowedModifiers = Class.AllowedModifiers;
2602 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2606 AllowedModifiers = Struct.AllowedModifiers;
2607 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2610 case Kind.Interface:
2611 AllowedModifiers = Interface.AllowedModifiers;
2612 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2616 throw new InvalidOperationException ();
2620 if (parent.Parent == null)
2621 accmods = Modifiers.INTERNAL;
2623 accmods = Modifiers.PRIVATE;
2625 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2626 this.OriginalModFlags = mod;
2629 public override PendingImplementation GetPendingImplementations ()
2631 return PendingImplementation.GetPendingImplementations (this);
2634 public override bool MarkForDuplicationCheck ()
2639 protected override TypeAttributes TypeAttr {
2641 return base.TypeAttr | DefaultTypeAttributes;
2646 public class ClassPart : TypeContainer, IMemberContainer {
2647 public readonly PartialContainer PartialContainer;
2648 public readonly bool IsPartial;
2650 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2651 int mod, Attributes attrs, Kind kind, Location l)
2652 : base (ns, parent, pc.MemberName, attrs, kind, l)
2654 this.PartialContainer = pc;
2655 this.IsPartial = true;
2658 if (parent == null || parent == RootContext.Tree.Types)
2659 accmods = Modifiers.INTERNAL;
2661 accmods = Modifiers.PRIVATE;
2663 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2666 public override PendingImplementation GetPendingImplementations ()
2668 return PartialContainer.Pending;
2671 public override bool VerifyImplements (MemberBase mb)
2673 return PartialContainer.VerifyImplements (mb);
2677 public override void RegisterFieldForInitialization (FieldMember field)
2679 PartialContainer.RegisterFieldForInitialization (field);
2682 public override bool EmitFieldInitializers (EmitContext ec)
2684 return PartialContainer.EmitFieldInitializers (ec);
2687 public override Type FindNestedType (string name)
2689 return PartialContainer.FindNestedType (name);
2692 public override MemberCache BaseCache {
2694 return PartialContainer.BaseCache;
2698 public override TypeBuilder DefineType ()
2700 throw new InternalErrorException ("Should not get here");
2705 public abstract class ClassOrStruct : TypeContainer {
2706 bool has_explicit_layout = false;
2707 ListDictionary declarative_security;
2709 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2710 MemberName name, Attributes attrs, Kind kind,
2712 : base (ns, parent, name, attrs, kind, l)
2716 public override PendingImplementation GetPendingImplementations ()
2718 return PendingImplementation.GetPendingImplementations (this);
2721 public override bool HasExplicitLayout {
2723 return has_explicit_layout;
2727 public override void VerifyMembers ()
2729 base.VerifyMembers ();
2731 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2732 foreach (Event e in events){
2733 if ((e.caching_flags & Flags.IsAssigned) == 0)
2734 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2739 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2741 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2742 if (declarative_security == null)
2743 declarative_security = new ListDictionary ();
2745 a.ExtractSecurityPermissionSet (declarative_security);
2749 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2750 has_explicit_layout = true;
2752 base.ApplyAttributeBuilder (a, cb);
2755 public override void Emit()
2759 if (declarative_security != null) {
2760 foreach (DictionaryEntry de in declarative_security) {
2761 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2768 /// Class handles static classes declaration
2770 public sealed class StaticClass: Class {
2771 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2772 Attributes attrs, Location l)
2773 : base (ns, parent, name, mod, attrs, l)
2775 if (RootContext.Version == LanguageVersion.ISO_1) {
2776 Report.FeatureIsNotStandardized (l, "static classes");
2780 protected override int AllowedModifiersProp {
2782 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2783 Modifiers.STATIC | Modifiers.UNSAFE;
2787 protected override void DefineContainerMembers (MemberCoreArrayList list)
2792 foreach (MemberCore m in list) {
2793 if (m is Operator) {
2794 Report.Error (715, m.Location, "`{0}': static classes cannot contain user-defined operators", m.GetSignatureForError ());
2798 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2799 Report.Warning (-628, 4, m.Location, "`{0}': new protected member declared in static class", m.GetSignatureForError ());
2802 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2806 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2809 if (m is Constructor) {
2810 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2814 if (m is Destructor) {
2815 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2819 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2822 base.DefineContainerMembers (list);
2825 public override TypeBuilder DefineType()
2827 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2828 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2832 TypeBuilder tb = base.DefineType ();
2836 if (ptype != TypeManager.object_type) {
2837 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2841 if (ifaces != null) {
2842 foreach (Type t in ifaces)
2843 Report.SymbolRelatedToPreviousError (t);
2844 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2849 protected override TypeAttributes TypeAttr {
2851 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2856 public class Class : ClassOrStruct {
2857 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2858 public const int AllowedModifiers =
2861 Modifiers.PROTECTED |
2862 Modifiers.INTERNAL |
2864 Modifiers.ABSTRACT |
2868 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2869 Attributes attrs, Location l)
2870 : base (ns, parent, name, attrs, Kind.Class, l)
2872 this.ModFlags = mod;
2875 virtual protected int AllowedModifiersProp {
2877 return AllowedModifiers;
2881 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2883 if (a.Type == TypeManager.attribute_usage_type) {
2884 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2885 TypeBuilder.FullName != "System.Attribute") {
2886 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2890 if (a.Type == TypeManager.conditional_attribute_type &&
2891 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
2892 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2896 if (AttributeTester.IsAttributeExcluded (a.Type))
2899 base.ApplyAttributeBuilder (a, cb);
2902 public const TypeAttributes DefaultTypeAttributes =
2903 TypeAttributes.AutoLayout | TypeAttributes.Class;
2905 public override TypeBuilder DefineType()
2907 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2908 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2912 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2913 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2915 return base.DefineType ();
2918 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2919 /// Valid only for attribute classes.
2920 public bool IsExcluded ()
2922 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2923 return (caching_flags & Flags.Excluded) != 0;
2925 caching_flags &= ~Flags.Excluded_Undetected;
2927 if (OptAttributes == null)
2930 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
2935 foreach (Attribute a in attrs) {
2936 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
2937 if (RootContext.AllDefines.Contains (condition))
2941 caching_flags |= Flags.Excluded;
2946 // FIXME: How do we deal with the user specifying a different
2949 protected override TypeAttributes TypeAttr {
2951 return base.TypeAttr | DefaultTypeAttributes;
2956 public class Struct : ClassOrStruct {
2958 // Modifiers allowed in a struct declaration
2960 public const int AllowedModifiers =
2963 Modifiers.PROTECTED |
2964 Modifiers.INTERNAL |
2968 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2969 int mod, Attributes attrs, Location l)
2970 : base (ns, parent, name, attrs, Kind.Struct, l)
2974 if (parent.Parent == null)
2975 accmods = Modifiers.INTERNAL;
2977 accmods = Modifiers.PRIVATE;
2979 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2981 this.ModFlags |= Modifiers.SEALED;
2984 public const TypeAttributes DefaultTypeAttributes =
2985 TypeAttributes.SequentialLayout |
2986 TypeAttributes.Sealed |
2987 TypeAttributes.BeforeFieldInit;
2990 // FIXME: Allow the user to specify a different set of attributes
2991 // in some cases (Sealed for example is mandatory for a class,
2992 // but what SequentialLayout can be changed
2994 protected override TypeAttributes TypeAttr {
2996 return base.TypeAttr | DefaultTypeAttributes;
3004 public class Interface : TypeContainer, IMemberContainer {
3007 /// Modifiers allowed in a class declaration
3009 public const int AllowedModifiers =
3012 Modifiers.PROTECTED |
3013 Modifiers.INTERNAL |
3017 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3018 Attributes attrs, Location l)
3019 : base (ns, parent, name, attrs, Kind.Interface, l)
3023 if (parent.Parent == null)
3024 accmods = Modifiers.INTERNAL;
3026 accmods = Modifiers.PRIVATE;
3028 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3031 public override PendingImplementation GetPendingImplementations ()
3036 public const TypeAttributes DefaultTypeAttributes =
3037 TypeAttributes.AutoLayout |
3038 TypeAttributes.Abstract |
3039 TypeAttributes.Interface;
3041 protected override TypeAttributes TypeAttr {
3043 return base.TypeAttr | DefaultTypeAttributes;
3047 protected override bool VerifyClsCompliance (DeclSpace ds)
3049 if (!base.VerifyClsCompliance (ds))
3052 if (ifaces != null) {
3053 foreach (Type t in ifaces) {
3054 if (AttributeTester.IsClsCompliant (t))
3057 Report.SymbolRelatedToPreviousError (t);
3058 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3059 GetSignatureForError (), TypeManager.CSharpName (t));
3067 public abstract class MethodCore : MemberBase {
3068 public readonly Parameters Parameters;
3069 protected ToplevelBlock block;
3072 // Parameters, cached for semantic analysis.
3074 protected InternalParameters parameter_info;
3075 protected Type [] parameter_types;
3077 // Whether this is an operator method.
3078 public Operator IsOperator;
3081 // The method we're overriding if this is an override method.
3083 protected MethodInfo base_method = null;
3085 static string[] attribute_targets = new string [] { "method", "return" };
3087 public MethodCore (TypeContainer parent, Expression type, int mod,
3088 int allowed_mod, bool is_interface, MemberName name,
3089 Attributes attrs, Parameters parameters, Location loc)
3090 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3093 Parameters = parameters;
3094 IsInterface = is_interface;
3098 // Returns the System.Type array for the parameters of this method
3100 public Type [] ParameterTypes {
3102 return parameter_types;
3106 public InternalParameters ParameterInfo
3109 return parameter_info;
3113 public ToplevelBlock Block {
3123 public void SetYields ()
3125 ModFlags |= Modifiers.METHOD_YIELDS;
3128 protected override bool CheckBase ()
3130 if (!base.CheckBase ())
3133 // Check whether arguments were correct.
3134 if (!DoDefineParameters ())
3137 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3143 // Is null for System.Object while compiling corlib and base interfaces
3144 if (Parent.BaseCache == null) {
3145 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3146 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3151 Type base_ret_type = null;
3152 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3154 // method is override
3155 if (base_method != null) {
3157 if (!CheckMethodAgainstBase ())
3160 if ((ModFlags & Modifiers.NEW) == 0) {
3161 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3162 Report.SymbolRelatedToPreviousError (base_method);
3163 if (this is PropertyBase) {
3164 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3165 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3168 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3169 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3174 if (base_method.IsAbstract && !IsInterface) {
3175 Report.SymbolRelatedToPreviousError (base_method);
3176 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3177 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3182 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3183 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3187 if (RootContext.WarningLevel > 2) {
3188 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3189 Parent.Methods.HasEquals = true;
3190 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3191 Parent.Methods.HasGetHashCode = true;
3194 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3195 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3197 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3198 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3199 Report.SymbolRelatedToPreviousError (base_method);
3200 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3201 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3208 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3209 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3210 if (conflict_symbol != null) {
3211 Report.SymbolRelatedToPreviousError (conflict_symbol);
3212 if (this is PropertyBase)
3213 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3215 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3217 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3221 if (conflict_symbol == null) {
3222 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3223 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3228 if ((ModFlags & Modifiers.NEW) == 0) {
3229 if (this is Method && conflict_symbol is MethodBase)
3232 Report.SymbolRelatedToPreviousError (conflict_symbol);
3233 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3234 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3241 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3242 // that have been defined.
3244 // `name' is the user visible name for reporting errors (this is used to
3245 // provide the right name regarding method names and properties)
3247 bool CheckMethodAgainstBase ()
3251 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3252 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3253 Report.Error (506, Location,
3254 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3255 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3259 // Now we check that the overriden method is not final
3261 if (base_method.IsFinal) {
3262 Report.SymbolRelatedToPreviousError (base_method);
3263 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3264 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3268 // Check that the permissions are not being changed
3270 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3271 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3273 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3274 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3279 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3280 ModFlags |= Modifiers.NEW;
3281 Report.SymbolRelatedToPreviousError (base_method);
3282 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3283 if (RootContext.WarningLevel >= 2)
3284 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));
3286 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3287 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3294 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3296 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3298 // when overriding protected internal, the method can be declared
3299 // protected internal only within the same assembly
3302 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3303 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3305 // assemblies differ - report an error
3309 } else if (thisp != base_classp) {
3311 // same assembly, but other attributes differ - report an error
3316 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3318 // if it's not "protected internal", it must be "protected"
3322 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3324 // protected within the same assembly - an error
3327 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3328 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3330 // protected ok, but other attributes differ - report an error
3336 return (thisp == base_classp);
3340 public bool CheckAbstractAndExtern (bool has_block)
3342 if (Parent.Kind == Kind.Interface)
3346 if ((ModFlags & Modifiers.EXTERN) != 0) {
3347 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3348 GetSignatureForError ());
3352 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3353 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3354 GetSignatureForError ());
3358 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3359 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3360 GetSignatureForError ());
3368 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3370 Report.SymbolRelatedToPreviousError (base_method);
3371 string base_name = TypeManager.GetFullNameSignature (base_method);
3372 string this_name = GetSignatureForError ();
3373 if (suffix != null) {
3374 base_name += suffix;
3375 this_name += suffix;
3378 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3379 this_name, Modifiers.GetDescription (ma), base_name);
3382 protected static string Error722 {
3384 return "`{0}': static types cannot be used as return types";
3389 /// For custom member duplication search in a container
3391 protected abstract bool CheckForDuplications ();
3394 /// Gets base method and its return type
3396 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3398 protected virtual bool DoDefineParameters ()
3400 EmitContext ec = Parent.EmitContext;
3402 throw new InternalErrorException ("DoDefineParameters invoked too early");
3404 bool old_unsafe = ec.InUnsafe;
3405 ec.InUnsafe = InUnsafe;
3406 // Check if arguments were correct
3407 parameter_types = Parameters.GetParameterInfo (ec);
3408 ec.InUnsafe = old_unsafe;
3410 if ((parameter_types == null) ||
3411 !CheckParameters (Parent, parameter_types))
3414 parameter_info = new InternalParameters (parameter_types, Parameters);
3416 Parameter array_param = Parameters.ArrayParameter;
3417 if ((array_param != null) &&
3418 (!array_param.ParameterType.IsArray ||
3419 (array_param.ParameterType.GetArrayRank () != 1))) {
3420 Report.Error (225, Location, "The params parameter must be a single dimensional array");
3427 public override string[] ValidAttributeTargets {
3429 return attribute_targets;
3433 protected override bool VerifyClsCompliance (DeclSpace ds)
3435 if (!base.VerifyClsCompliance (ds)) {
3436 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3437 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3442 if (Parameters.HasArglist) {
3443 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3446 if (!AttributeTester.IsClsCompliant (MemberType)) {
3447 if (this is PropertyBase)
3448 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3449 GetSignatureForError ());
3451 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3452 GetSignatureForError ());
3455 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3460 protected bool IsDuplicateImplementation (MethodCore method)
3462 if (method == this || !(method.MemberName.Equals (MemberName)))
3465 Type[] param_types = method.ParameterTypes;
3466 if (param_types == null && ParameterTypes == null)
3468 if (param_types == null || ParameterTypes == null)
3471 if (param_types.Length != ParameterTypes.Length)
3474 for (int i = 0; i < param_types.Length; i++)
3475 if (param_types [i] != ParameterTypes [i])
3478 // TODO: make operator compatible with MethodCore to avoid this
3479 if (this is Operator && method is Operator) {
3480 if (MemberType != method.MemberType)
3485 // Try to report 663: method only differs on out/ref
3487 ParameterData info = ParameterInfo;
3488 ParameterData other_info = method.ParameterInfo;
3489 for (int i = 0; i < info.Count; i++){
3490 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3491 Report.SymbolRelatedToPreviousError (method);
3492 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3493 GetSignatureForError ());
3498 Report.SymbolRelatedToPreviousError (method);
3499 if (this is Operator && method is Operator)
3500 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3502 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3506 public override bool IsUsed {
3507 get { return IsExplicitImpl || base.IsUsed; }
3511 // Returns a string that represents the signature for this
3512 // member which should be used in XML documentation.
3514 public override string GetDocCommentName (DeclSpace ds)
3516 return DocUtil.GetMethodDocCommentName (this, ds);
3520 // Raised (and passed an XmlElement that contains the comment)
3521 // when GenerateDocComment is writing documentation expectedly.
3523 // FIXME: with a few effort, it could be done with XmlReader,
3524 // that means removal of DOM use.
3526 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3528 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3532 // Represents header string for documentation comment.
3534 public override string DocCommentHeader {
3535 get { return "M:"; }
3538 protected override void VerifyObsoleteAttribute()
3540 base.VerifyObsoleteAttribute ();
3542 if (parameter_types == null)
3545 foreach (Type type in parameter_types) {
3546 CheckUsageOfObsoleteAttribute (type);
3551 public class SourceMethod : ISourceMethod
3553 TypeContainer container;
3556 protected SourceMethod (TypeContainer container, MethodBase builder,
3557 ISourceFile file, Location start, Location end)
3559 this.container = container;
3560 this.builder = builder;
3562 CodeGen.SymbolWriter.OpenMethod (
3563 file, this, start.Row, 0, end.Row, 0);
3566 public string Name {
3567 get { return builder.Name; }
3570 public int NamespaceID {
3571 get { return container.NamespaceEntry.SymbolFileID; }
3576 if (builder is MethodBuilder)
3577 return ((MethodBuilder) builder).GetToken ().Token;
3578 else if (builder is ConstructorBuilder)
3579 return ((ConstructorBuilder) builder).GetToken ().Token;
3581 throw new NotSupportedException ();
3585 public void CloseMethod ()
3587 if (CodeGen.SymbolWriter != null)
3588 CodeGen.SymbolWriter.CloseMethod ();
3591 public static SourceMethod Create (TypeContainer parent,
3592 MethodBase builder, Block block)
3594 if (CodeGen.SymbolWriter == null)
3599 Location start_loc = block.StartLocation;
3600 if (Location.IsNull (start_loc))
3603 Location end_loc = block.EndLocation;
3604 if (Location.IsNull (end_loc))
3607 ISourceFile file = start_loc.SourceFile;
3611 return new SourceMethod (
3612 parent, builder, file, start_loc, end_loc);
3616 public class Method : MethodCore, IIteratorContainer, IMethodData {
3617 public MethodBuilder MethodBuilder;
3618 public MethodData MethodData;
3619 ReturnParameter return_attributes;
3620 ListDictionary declarative_security;
3623 /// Modifiers allowed in a class declaration
3625 const int AllowedModifiers =
3628 Modifiers.PROTECTED |
3629 Modifiers.INTERNAL |
3634 Modifiers.OVERRIDE |
3635 Modifiers.ABSTRACT |
3637 Modifiers.METHOD_YIELDS |
3640 const int AllowedInterfaceModifiers =
3641 Modifiers.NEW | Modifiers.UNSAFE;
3644 // return_type can be "null" for VOID values.
3646 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3647 MemberName name, Parameters parameters, Attributes attrs,
3649 : base (ds, return_type, mod,
3650 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3651 is_iface, name, attrs, parameters, l)
3655 public override AttributeTargets AttributeTargets {
3657 return AttributeTargets.Method;
3661 public override string GetSignatureForError()
3663 if (IsOperator != null)
3664 return IsOperator.GetSignatureForError ();
3666 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3669 void DuplicateEntryPoint (MethodInfo b, Location location)
3673 "Program `" + CodeGen.FileName +
3674 "' has more than one entry point defined: `" +
3675 TypeManager.CSharpSignature(b) + "'");
3678 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3680 if (b.ReturnType != TypeManager.void_type &&
3681 b.ReturnType != TypeManager.int32_type)
3684 if (pinfo.Count == 0)
3687 if (pinfo.Count > 1)
3690 Type t = pinfo.ParameterType(0);
3692 (t.GetArrayRank() == 1) &&
3693 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3694 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3700 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3702 if (a.Target == AttributeTargets.ReturnValue) {
3703 if (return_attributes == null)
3704 return_attributes = new ReturnParameter (MethodBuilder, Location);
3706 return_attributes.ApplyAttributeBuilder (a, cb);
3710 if (a.Type == TypeManager.methodimpl_attr_type &&
3711 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3712 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3715 if (a.Type == TypeManager.dllimport_type) {
3716 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3717 if ((ModFlags & extern_static) != extern_static) {
3718 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3724 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3725 if (declarative_security == null)
3726 declarative_security = new ListDictionary ();
3727 a.ExtractSecurityPermissionSet (declarative_security);
3731 if (a.Type == TypeManager.conditional_attribute_type) {
3732 if (IsOperator != null || IsExplicitImpl) {
3733 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3734 GetSignatureForError ());
3738 if (ReturnType != TypeManager.void_type) {
3739 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
3743 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3744 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
3749 Report.Error (582, Location, "Conditional not valid on interface members");
3753 if (MethodData.implementing != null) {
3754 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
3755 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
3759 for (int i = 0; i < parameter_info.Count; ++i) {
3760 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3761 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
3767 MethodBuilder.SetCustomAttribute (cb);
3770 protected override bool CheckForDuplications ()
3772 ArrayList ar = Parent.Methods;
3774 int arLen = ar.Count;
3776 for (int i = 0; i < arLen; i++) {
3777 Method m = (Method) ar [i];
3778 if (IsDuplicateImplementation (m))
3783 ar = Parent.Properties;
3785 for (int i = 0; i < ar.Count; ++i) {
3786 PropertyBase pb = (PropertyBase) ar [i];
3787 if (pb.AreAccessorsDuplicateImplementation (this))
3792 ar = Parent.Indexers;
3794 for (int i = 0; i < ar.Count; ++i) {
3795 PropertyBase pb = (PropertyBase) ar [i];
3796 if (pb.AreAccessorsDuplicateImplementation (this))
3803 for (int i = 0; i < ar.Count; ++i) {
3804 Event ev = (Event) ar [i];
3805 if (ev.AreAccessorsDuplicateImplementation (this))
3816 public override bool Define ()
3821 if (!CheckAbstractAndExtern (block != null))
3824 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3825 Error1599 (Location, ReturnType);
3832 if (IsOperator != null)
3833 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3835 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3837 if (!MethodData.Define (Parent))
3840 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3841 Name == "Finalize" && !(this is Destructor)) {
3842 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3846 // Setup iterator if we are one
3848 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3849 Iterator iterator = new Iterator (this,
3851 ParameterInfo, ModFlags);
3853 if (!iterator.DefineIterator ())
3857 MethodBuilder = MethodData.MethodBuilder;
3860 // This is used to track the Entry Point,
3862 if (Name == "Main" &&
3863 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3864 (RootContext.MainClass == null ||
3865 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3866 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3867 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3868 md.SetMemberIsUsed ();
3870 if (RootContext.EntryPoint == null) {
3871 RootContext.EntryPoint = MethodBuilder;
3872 RootContext.EntryPointLocation = Location;
3874 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3875 DuplicateEntryPoint (MethodBuilder, Location);
3878 if (RootContext.WarningLevel >= 4)
3879 Report.Warning (28, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3883 if (MemberType.IsAbstract && MemberType.IsSealed) {
3884 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3894 public override void Emit ()
3896 MethodData.Emit (Parent, this);
3899 if (declarative_security != null) {
3900 foreach (DictionaryEntry de in declarative_security) {
3901 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3909 public static void Error1599 (Location loc, Type t)
3911 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
3914 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3916 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3917 container.TypeBuilder, Name, ParameterTypes, false);
3922 base_ret_type = mi.ReturnType;
3926 public override bool MarkForDuplicationCheck ()
3928 caching_flags |= Flags.TestMethodDuplication;
3932 protected override bool VerifyClsCompliance(DeclSpace ds)
3934 if (!base.VerifyClsCompliance (ds))
3937 if (parameter_types.Length > 0) {
3938 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3940 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3946 #region IMethodData Members
3948 public CallingConventions CallingConventions {
3950 CallingConventions cc = Parameters.GetCallingConvention ();
3951 if (Parameters.HasArglist)
3952 block.HasVarargs = true;
3955 if ((ModFlags & Modifiers.STATIC) == 0)
3956 cc |= CallingConventions.HasThis;
3958 // FIXME: How is `ExplicitThis' used in C#?
3964 public Type ReturnType {
3970 public MemberName MethodName {
3976 public new Location Location {
3978 return base.Location;
3982 protected override bool CheckBase() {
3983 if (!base.CheckBase ())
3986 // TODO: Destructor should derive from MethodCore
3987 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3988 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3989 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3996 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3998 EmitContext ec = new EmitContext (
3999 tc, Parent, Location, ig, ReturnType, ModFlags, false);
4001 ec.CurrentIterator = tc as Iterator;
4002 if (ec.CurrentIterator != null)
4003 ec.CurrentAnonymousMethod = ec.CurrentIterator.Host;
4008 public ObsoleteAttribute GetObsoleteAttribute ()
4010 return GetObsoleteAttribute (Parent);
4014 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4016 public bool IsExcluded (EmitContext ec)
4018 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4019 return (caching_flags & Flags.Excluded) != 0;
4021 caching_flags &= ~Flags.Excluded_Undetected;
4023 if (base_method == null) {
4024 if (OptAttributes == null)
4027 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4032 foreach (Attribute a in attrs) {
4033 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4034 if (RootContext.AllDefines.Contains (condition))
4038 caching_flags |= Flags.Excluded;
4042 IMethodData md = TypeManager.GetMethod (base_method);
4044 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4045 caching_flags |= Flags.Excluded;
4051 if (md.IsExcluded (ec)) {
4052 caching_flags |= Flags.Excluded;
4061 public abstract class ConstructorInitializer {
4062 ArrayList argument_list;
4063 protected ConstructorInfo base_constructor;
4066 public ConstructorInitializer (ArrayList argument_list, Location loc)
4068 this.argument_list = argument_list;
4072 public ArrayList Arguments {
4074 return argument_list;
4078 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4080 Expression base_constructor_group;
4084 ec.CurrentBlock = block;
4086 if (argument_list != null){
4087 foreach (Argument a in argument_list){
4088 if (!a.Resolve (ec, loc))
4092 ec.CurrentBlock = null;
4094 if (this is ConstructorBaseInitializer) {
4095 if (ec.ContainerType.BaseType == null)
4098 t = ec.ContainerType.BaseType;
4099 if (ec.ContainerType.IsValueType) {
4100 Report.Error (522, loc,
4101 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4105 t = ec.ContainerType;
4107 base_constructor_group = Expression.MemberLookup (
4108 ec, t, ".ctor", MemberTypes.Constructor,
4109 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4112 if (base_constructor_group == null){
4114 base_constructor_group = Expression.MemberLookup (
4115 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4116 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4120 int errors = Report.Errors;
4121 if (base_constructor_group != null)
4122 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4123 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4126 if (base_constructor == null) {
4127 if (errors == Report.Errors)
4128 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4129 argument_list.Count);
4134 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4135 base_constructor = null;
4139 if (base_constructor == caller_builder){
4140 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4147 public void Emit (EmitContext ec)
4149 if (base_constructor != null){
4150 ec.Mark (loc, false);
4152 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4154 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4159 public class ConstructorBaseInitializer : ConstructorInitializer {
4160 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4161 base (argument_list, l)
4166 public class ConstructorThisInitializer : ConstructorInitializer {
4167 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4168 base (argument_list, l)
4173 public class Constructor : MethodCore, IMethodData {
4174 public ConstructorBuilder ConstructorBuilder;
4175 public ConstructorInitializer Initializer;
4176 ListDictionary declarative_security;
4179 // Modifiers allowed for a constructor.
4181 public const int AllowedModifiers =
4183 Modifiers.PROTECTED |
4184 Modifiers.INTERNAL |
4190 bool has_compliant_args = false;
4192 // The spec claims that static is not permitted, but
4193 // my very own code has static constructors.
4195 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4196 ConstructorInitializer init, Location l)
4197 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4203 public bool HasCompliantArgs {
4205 return has_compliant_args;
4209 public override AttributeTargets AttributeTargets {
4211 return AttributeTargets.Constructor;
4217 // Returns true if this is a default constructor
4219 public bool IsDefault ()
4221 if ((ModFlags & Modifiers.STATIC) != 0)
4222 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4223 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4226 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4227 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4228 (Initializer is ConstructorBaseInitializer) &&
4229 (Initializer.Arguments == null);
4232 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4234 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4235 if (declarative_security == null) {
4236 declarative_security = new ListDictionary ();
4238 a.ExtractSecurityPermissionSet (declarative_security);
4242 ConstructorBuilder.SetCustomAttribute (cb);
4245 protected override bool CheckForDuplications ()
4247 ArrayList ar = Parent.InstanceConstructors;
4249 int arLen = ar.Count;
4251 for (int i = 0; i < arLen; i++) {
4252 Constructor m = (Constructor) ar [i];
4253 if (IsDuplicateImplementation (m))
4260 protected override bool CheckBase ()
4262 // Check whether arguments were correct.
4263 if (!DoDefineParameters ())
4266 // TODO: skip the rest for generated ctor
4267 if ((ModFlags & Modifiers.STATIC) != 0)
4270 if (!CheckForDuplications ())
4273 if (Parent.Kind == Kind.Struct) {
4274 if (ParameterTypes.Length == 0) {
4275 Report.Error (568, Location,
4276 "Structs cannot contain explicit parameterless constructors");
4280 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4281 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4286 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4287 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4294 // Creates the ConstructorBuilder
4296 public override bool Define ()
4298 if (ConstructorBuilder != null)
4301 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4302 MethodAttributes.SpecialName);
4304 if ((ModFlags & Modifiers.STATIC) != 0) {
4305 ca |= MethodAttributes.Static | MethodAttributes.Private;
4307 ca |= MethodAttributes.HideBySig;
4309 if ((ModFlags & Modifiers.PUBLIC) != 0)
4310 ca |= MethodAttributes.Public;
4311 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4312 if ((ModFlags & Modifiers.INTERNAL) != 0)
4313 ca |= MethodAttributes.FamORAssem;
4315 ca |= MethodAttributes.Family;
4316 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4317 ca |= MethodAttributes.Assembly;
4318 else if (IsDefault ())
4319 ca |= MethodAttributes.Public;
4321 ca |= MethodAttributes.Private;
4324 if (!CheckAbstractAndExtern (block != null))
4327 // Check if arguments were correct.
4331 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4332 ca, CallingConventions,
4335 if ((ModFlags & Modifiers.UNSAFE) != 0)
4336 ConstructorBuilder.InitLocals = false;
4338 TypeManager.AddMethod (ConstructorBuilder, this);
4341 // HACK because System.Reflection.Emit is lame
4343 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4351 public override void Emit ()
4353 EmitContext ec = CreateEmitContext (null, null);
4355 // If this is a non-static `struct' constructor and doesn't have any
4356 // initializer, it must initialize all of the struct's fields.
4357 if ((Parent.Kind == Kind.Struct) &&
4358 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4359 Block.AddThisVariable (Parent, Location);
4361 if (block != null) {
4362 if (!block.ResolveMeta (ec, ParameterInfo))
4366 if ((ModFlags & Modifiers.STATIC) == 0){
4367 if (Parent.Kind == Kind.Class && Initializer == null)
4368 Initializer = new ConstructorBaseInitializer (null, Location);
4372 // Spec mandates that Initializers will not have
4376 if ((Initializer != null) &&
4377 !Initializer.Resolve (ConstructorBuilder, block, ec))
4379 ec.IsStatic = false;
4382 Parameters.LabelParameters (ec, ConstructorBuilder);
4384 SourceMethod source = SourceMethod.Create (
4385 Parent, ConstructorBuilder, block);
4388 // Classes can have base initializers and instance field initializers.
4390 if (Parent.Kind == Kind.Class){
4391 if ((ModFlags & Modifiers.STATIC) == 0){
4394 // If we use a "this (...)" constructor initializer, then
4395 // do not emit field initializers, they are initialized in the other constructor
4397 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4398 Parent.EmitFieldInitializers (ec);
4401 if (Initializer != null) {
4402 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4403 ec.TestObsoleteMethodUsage = false;
4405 Initializer.Emit (ec);
4408 if ((ModFlags & Modifiers.STATIC) != 0)
4409 Parent.EmitFieldInitializers (ec);
4411 if (OptAttributes != null)
4412 OptAttributes.Emit (ec, this);
4414 ec.EmitTopBlock (this, block, ParameterInfo);
4417 source.CloseMethod ();
4421 if (declarative_security != null) {
4422 foreach (DictionaryEntry de in declarative_security) {
4423 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4430 // Is never override
4431 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4436 public override string GetSignatureForError()
4438 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4441 protected override bool VerifyClsCompliance (DeclSpace ds)
4443 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4447 if (parameter_types.Length > 0) {
4448 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4450 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4452 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4453 foreach (Type param in parameter_types) {
4454 if (param.IsArray) {
4460 has_compliant_args = true;
4464 #region IMethodData Members
4466 public System.Reflection.CallingConventions CallingConventions {
4468 CallingConventions cc = Parameters.GetCallingConvention ();
4470 if (Parent.Kind == Kind.Class)
4471 if ((ModFlags & Modifiers.STATIC) == 0)
4472 cc |= CallingConventions.HasThis;
4474 // FIXME: How is `ExplicitThis' used in C#?
4480 public new Location Location {
4482 return base.Location;
4486 public MemberName MethodName {
4492 public Type ReturnType {
4498 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4500 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4501 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4504 public ObsoleteAttribute GetObsoleteAttribute ()
4506 return GetObsoleteAttribute (Parent);
4509 public bool IsExcluded(EmitContext ec)
4518 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4520 public interface IMethodData
4522 CallingConventions CallingConventions { get; }
4523 Location Location { get; }
4524 MemberName MethodName { get; }
4525 Type[] ParameterTypes { get; }
4526 Type ReturnType { get; }
4528 Attributes OptAttributes { get; }
4529 ToplevelBlock Block { get; set; }
4531 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4532 ObsoleteAttribute GetObsoleteAttribute ();
4533 string GetSignatureForError ();
4534 bool IsExcluded (EmitContext ec);
4535 bool IsClsCompliaceRequired (DeclSpace ds);
4536 void SetMemberIsUsed ();
4540 // Encapsulates most of the Method's state
4542 public class MethodData {
4544 readonly IMethodData method;
4547 // The return type of this method
4549 public readonly InternalParameters ParameterInfo;
4552 // Are we implementing an interface ?
4554 public MethodInfo implementing;
4559 protected MemberBase member;
4560 protected int modifiers;
4561 protected MethodAttributes flags;
4563 MethodBuilder builder = null;
4564 public MethodBuilder MethodBuilder {
4570 public MethodData (MemberBase member, InternalParameters parameters,
4571 int modifiers, MethodAttributes flags, IMethodData method)
4573 this.member = member;
4574 this.ParameterInfo = parameters;
4575 this.modifiers = modifiers;
4578 this.method = method;
4581 public bool Define (TypeContainer container)
4583 string name = method.MethodName.Name;
4584 string method_name = name;
4586 Type[] ParameterTypes = method.ParameterTypes;
4588 if (container.Pending != null){
4589 if (member is Indexer) // TODO: test it, but it should work without this IF
4590 implementing = container.Pending.IsInterfaceIndexer (
4591 member.InterfaceType, method.ReturnType, ParameterInfo);
4593 implementing = container.Pending.IsInterfaceMethod (
4594 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4596 if (member.InterfaceType != null){
4597 if (implementing == null){
4598 if (member is PropertyBase) {
4599 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4600 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4601 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4604 Report.Error (539, method.Location,
4605 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4606 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4610 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4611 Report.SymbolRelatedToPreviousError (implementing);
4612 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4613 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4616 method_name = member.InterfaceType.FullName + "." + name;
4618 if (implementing != null) {
4619 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4620 if (prop_method != null) {
4621 if (!implementing.IsSpecialName) {
4622 Report.SymbolRelatedToPreviousError (implementing);
4623 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4624 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4627 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4628 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4629 Report.SymbolRelatedToPreviousError (implementing);
4630 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4631 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4640 // For implicit implementations, make sure we are public, for
4641 // explicit implementations, make sure we are private.
4643 if (implementing != null){
4645 // Setting null inside this block will trigger a more
4646 // verbose error reporting for missing interface implementations
4648 // The "candidate" function has been flagged already
4649 // but it wont get cleared
4651 if (member.IsExplicitImpl){
4652 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4653 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4654 implementing = null;
4656 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4657 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4659 // If this is an interface method implementation,
4660 // check for public accessibility
4662 implementing = null;
4663 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4664 // We may never be private.
4665 implementing = null;
4666 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4668 // We may be protected if we're overriding something.
4670 implementing = null;
4675 // Static is not allowed
4677 if ((modifiers & Modifiers.STATIC) != 0){
4678 implementing = null;
4683 // If implementing is still valid, set flags
4685 if (implementing != null){
4687 // When implementing interface methods, set NewSlot
4688 // unless, we are overwriting a method.
4690 if (implementing.DeclaringType.IsInterface){
4691 if ((modifiers & Modifiers.OVERRIDE) == 0)
4692 flags |= MethodAttributes.NewSlot;
4695 MethodAttributes.Virtual |
4696 MethodAttributes.HideBySig;
4698 // Set Final unless we're virtual, abstract or already overriding a method.
4699 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4700 flags |= MethodAttributes.Final;
4703 EmitContext ec = method.CreateEmitContext (container, null);
4705 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4707 if (builder == null)
4710 if ((modifiers & Modifiers.UNSAFE) != 0)
4711 builder.InitLocals = false;
4713 if (implementing != null){
4715 // clear the pending implemntation flag
4717 if (member is Indexer) {
4718 container.Pending.ImplementIndexer (
4719 member.InterfaceType, builder, method.ReturnType,
4720 ParameterInfo, member.IsExplicitImpl);
4722 container.Pending.ImplementMethod (
4723 member.InterfaceType, name, method.ReturnType,
4724 ParameterInfo, member.IsExplicitImpl);
4726 if (member.IsExplicitImpl)
4727 container.TypeBuilder.DefineMethodOverride (
4728 builder, implementing);
4732 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4733 TypeManager.AddMethod (builder, method);
4740 /// Create the MethodBuilder for the method
4742 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4744 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4746 if ((modifiers & extern_static) == extern_static) {
4748 if (method.OptAttributes != null) {
4749 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4750 if (dllimport_attribute != null) {
4751 flags |= MethodAttributes.PinvokeImpl;
4752 builder = dllimport_attribute.DefinePInvokeMethod (
4753 ec, container.TypeBuilder, method_name, flags,
4754 method.ReturnType, ParameterTypes);
4760 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4761 // We are more strict than Microsoft and report CS0626 like error
4762 if (method.OptAttributes == null ||
4763 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4764 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",
4765 method.GetSignatureForError ());
4770 builder = container.TypeBuilder.DefineMethod (
4771 method_name, flags, method.CallingConventions,
4772 method.ReturnType, ParameterTypes);
4778 public void Emit (TypeContainer container, Attributable kind)
4781 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4782 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4784 ec = method.CreateEmitContext (container, null);
4786 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
4787 ec.TestObsoleteMethodUsage = false;
4789 Attributes OptAttributes = method.OptAttributes;
4791 if (OptAttributes != null)
4792 OptAttributes.Emit (ec, kind);
4794 if (member is MethodCore)
4795 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
4797 ToplevelBlock block = method.Block;
4799 SourceMethod source = SourceMethod.Create (
4800 container, MethodBuilder, method.Block);
4803 // Handle destructors specially
4805 // FIXME: This code generates buggy code
4807 if (member is Destructor)
4808 EmitDestructor (ec, block);
4810 ec.EmitTopBlock (method, block, ParameterInfo);
4813 source.CloseMethod ();
4816 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4818 ILGenerator ig = ec.ig;
4820 Label finish = ig.DefineLabel ();
4822 block.SetDestructor ();
4824 ig.BeginExceptionBlock ();
4825 ec.ReturnLabel = finish;
4826 ec.HasReturnLabel = true;
4827 ec.EmitTopBlock (method, block, null);
4829 // ig.MarkLabel (finish);
4830 ig.BeginFinallyBlock ();
4832 if (ec.ContainerType.BaseType != null) {
4833 Expression member_lookup = Expression.MemberLookup (
4834 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4835 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4837 if (member_lookup != null){
4838 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4840 ig.Emit (OpCodes.Ldarg_0);
4841 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4845 ig.EndExceptionBlock ();
4846 //ig.MarkLabel (ec.ReturnLabel);
4847 ig.Emit (OpCodes.Ret);
4851 // TODO: Should derive from MethodCore
4852 public class Destructor : Method {
4854 public Destructor (TypeContainer ds, Expression return_type, int mod,
4855 string name, Parameters parameters, Attributes attrs,
4857 : base (ds, return_type, mod, false, new MemberName (name),
4858 parameters, attrs, l)
4861 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4863 if (a.Type == TypeManager.conditional_attribute_type) {
4864 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4865 GetSignatureForError ());
4869 base.ApplyAttributeBuilder (a, cb);
4872 public override string GetSignatureForError ()
4874 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
4879 abstract public class MemberBase : MemberCore {
4880 public Expression Type;
4882 public MethodAttributes flags;
4884 protected readonly int explicit_mod_flags;
4887 // The "short" name of this property / indexer / event. This is the
4888 // name without the explicit interface.
4890 public string ShortName {
4891 get { return MemberName.Name; }
4893 SetMemberName (new MemberName (MemberName.Left, value));
4898 // The type of this property / indexer / event
4901 public Type MemberType {
4903 if (member_type == null && Type != null) {
4904 EmitContext ec = Parent.EmitContext;
4905 bool old_unsafe = ec.InUnsafe;
4906 ec.InUnsafe = InUnsafe;
4907 Type = Type.ResolveAsTypeTerminal (ec, false);
4908 ec.InUnsafe = old_unsafe;
4910 member_type = Type == null ? null : Type.Type;
4917 // Whether this is an interface member.
4919 public bool IsInterface;
4922 // If true, this is an explicit interface implementation
4924 public bool IsExplicitImpl;
4927 // The interface type we are explicitly implementing
4929 public Type InterfaceType = null;
4932 // The constructor is only exposed to our children
4934 protected MemberBase (TypeContainer parent, Expression type, int mod,
4935 int allowed_mod, int def_mod, MemberName name,
4936 Attributes attrs, Location loc)
4937 : base (parent, name, attrs, loc)
4939 explicit_mod_flags = mod;
4941 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4942 IsExplicitImpl = (MemberName.Left != null);
4945 protected virtual bool CheckBase ()
4947 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4948 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4952 if ((RootContext.WarningLevel >= 4) &&
4953 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4954 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4955 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4956 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4961 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4965 foreach (Type partype in parameters){
4966 if (partype == TypeManager.void_type) {
4968 1547, Location, "Keyword 'void' cannot " +
4969 "be used in this context");
4973 if (partype.IsPointer){
4976 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4980 if (ds.AsAccessible (partype, ModFlags))
4983 if (this is Indexer)
4984 Report.Error (55, Location,
4985 "Inconsistent accessibility: parameter type `" +
4986 TypeManager.CSharpName (partype) + "' is less " +
4987 "accessible than indexer `" + GetSignatureForError () + "'");
4988 else if ((this is Method) && ((Method) this).IsOperator != null)
4989 Report.Error (57, Location,
4990 "Inconsistent accessibility: parameter type `" +
4991 TypeManager.CSharpName (partype) + "' is less " +
4992 "accessible than operator `" + GetSignatureForError () + "'");
4994 Report.Error (51, Location,
4995 "Inconsistent accessibility: parameter type `" +
4996 TypeManager.CSharpName (partype) + "' is less " +
4997 "accessible than method `" + GetSignatureForError () + "'");
5004 protected virtual bool DoDefine ()
5006 EmitContext ec = Parent.EmitContext;
5008 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5011 throw new InternalErrorException ();
5014 ModFlags = Modifiers.PUBLIC |
5015 Modifiers.ABSTRACT |
5016 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5018 flags = MethodAttributes.Public |
5019 MethodAttributes.Abstract |
5020 MethodAttributes.HideBySig |
5021 MethodAttributes.NewSlot |
5022 MethodAttributes.Virtual;
5024 if (!Parent.MethodModifiersValid (this))
5027 flags = Modifiers.MethodAttr (ModFlags);
5030 if (MemberType == null)
5033 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5034 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5035 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5036 GetSignatureForError (), Parent.GetSignatureForError ());
5040 // verify accessibility
5041 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5042 Report.SymbolRelatedToPreviousError (MemberType);
5043 if (this is Property)
5044 Report.Error (53, Location,
5045 "Inconsistent accessibility: property type `" +
5046 TypeManager.CSharpName (MemberType) + "' is less " +
5047 "accessible than property `" + GetSignatureForError () + "'");
5048 else if (this is Indexer)
5049 Report.Error (54, Location,
5050 "Inconsistent accessibility: indexer return type `" +
5051 TypeManager.CSharpName (MemberType) + "' is less " +
5052 "accessible than indexer `" + GetSignatureForError () + "'");
5053 else if (this is MethodCore) {
5054 if (this is Operator)
5055 Report.Error (56, Location,
5056 "Inconsistent accessibility: return type `" +
5057 TypeManager.CSharpName (MemberType) + "' is less " +
5058 "accessible than operator `" + GetSignatureForError () + "'");
5060 Report.Error (50, Location,
5061 "Inconsistent accessibility: return type `" +
5062 TypeManager.CSharpName (MemberType) + "' is less " +
5063 "accessible than method `" + GetSignatureForError () + "'");
5065 Report.Error (52, Location,
5066 "Inconsistent accessibility: field type `" +
5067 TypeManager.CSharpName (MemberType) + "' is less " +
5068 "accessible than field `" + GetSignatureForError () + "'");
5073 if (MemberType.IsPointer && !UnsafeOK (Parent))
5076 if (IsExplicitImpl) {
5077 Expression expr = MemberName.Left.GetTypeExpression (Location);
5078 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5082 InterfaceType = texpr.ResolveType (ec);
5084 if (!InterfaceType.IsInterface) {
5085 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5089 if (!Parent.VerifyImplements (this))
5092 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5098 protected bool IsTypePermitted ()
5100 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5101 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5107 protected override bool VerifyClsCompliance(DeclSpace ds)
5109 if (base.VerifyClsCompliance (ds)) {
5113 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5114 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5119 protected override void VerifyObsoleteAttribute()
5121 CheckUsageOfObsoleteAttribute (MemberType);
5126 // Fields and Events both generate FieldBuilders, we use this to share
5127 // their common bits. This is also used to flag usage of the field
5129 abstract public class FieldBase : MemberBase {
5130 public FieldBuilder FieldBuilder;
5131 public Status status;
5134 public enum Status : byte {
5135 HAS_OFFSET = 4 // Used by FieldMember.
5138 static string[] attribute_targets = new string [] { "field" };
5141 /// Symbol with same name in base class/struct
5143 public MemberInfo conflict_symbol;
5146 // The constructor is only exposed to our children
5148 protected FieldBase (TypeContainer parent, Expression type, int mod,
5149 int allowed_mod, MemberName name, object init,
5150 Attributes attrs, Location loc)
5151 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5157 public override AttributeTargets AttributeTargets {
5159 return AttributeTargets.Field;
5163 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5165 if (a.Type == TypeManager.marshal_as_attr_type) {
5166 UnmanagedMarshal marshal = a.GetMarshal (this);
5167 if (marshal != null) {
5168 FieldBuilder.SetMarshal (marshal);
5173 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5174 a.Error_InvalidSecurityParent ();
5178 FieldBuilder.SetCustomAttribute (cb);
5182 // Whether this field has an initializer.
5184 public bool HasInitializer {
5186 return init != null;
5190 protected readonly Object init;
5193 Expression init_expr;
5194 bool init_expr_initialized = false;
5197 // Resolves and returns the field initializer.
5199 public Expression GetInitializerExpression (EmitContext ec)
5201 if (init_expr_initialized)
5205 if (init is Expression)
5206 e = (Expression) init;
5208 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5210 // TODO: Any reason why we are using parent EC ?
5211 EmitContext parent_ec = Parent.EmitContext;
5213 bool old_is_static = parent_ec.IsStatic;
5214 bool old_is_ctor = parent_ec.IsConstructor;
5215 parent_ec.IsStatic = ec.IsStatic;
5216 parent_ec.IsConstructor = ec.IsConstructor;
5217 parent_ec.IsFieldInitializer = true;
5218 e = e.DoResolve (parent_ec);
5219 parent_ec.IsFieldInitializer = false;
5220 parent_ec.IsStatic = old_is_static;
5221 parent_ec.IsConstructor = old_is_ctor;
5224 init_expr_initialized = true;
5229 protected override bool CheckBase ()
5231 if (!base.CheckBase ())
5238 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5239 if (conflict_symbol == null) {
5240 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5241 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5246 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5247 Report.SymbolRelatedToPreviousError (conflict_symbol);
5248 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5249 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5255 protected virtual bool IsFieldClsCompliant {
5257 if (FieldBuilder == null)
5260 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5264 public override string[] ValidAttributeTargets {
5266 return attribute_targets;
5270 protected override bool VerifyClsCompliance (DeclSpace ds)
5272 if (!base.VerifyClsCompliance (ds))
5275 if (!IsFieldClsCompliant) {
5276 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5282 public void SetAssigned ()
5284 caching_flags |= Flags.IsAssigned;
5288 public abstract class FieldMember: FieldBase
5290 protected FieldMember (TypeContainer parent, Expression type, int mod,
5291 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5292 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5294 if ((mod & Modifiers.ABSTRACT) != 0)
5295 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5298 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5300 if (a.Type == TypeManager.field_offset_attribute_type)
5302 status |= Status.HAS_OFFSET;
5304 if (!Parent.HasExplicitLayout) {
5305 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5309 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5310 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5316 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5317 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5322 base.ApplyAttributeBuilder (a, cb);
5326 public override bool Define()
5328 EmitContext ec = Parent.EmitContext;
5330 throw new InternalErrorException ("FieldMember.Define called too early");
5332 if (MemberType == null)
5335 if (MemberType == TypeManager.void_type) {
5336 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5343 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5344 Report.Error (52, Location,
5345 "Inconsistent accessibility: field type `" +
5346 TypeManager.CSharpName (MemberType) + "' is less " +
5347 "accessible than field `" + GetSignatureForError () + "'");
5351 if (!IsTypePermitted ())
5354 if (MemberType.IsPointer && !UnsafeOK (Parent))
5360 public override void Emit ()
5362 if (OptAttributes != null) {
5363 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5364 OptAttributes.Emit (ec, this);
5367 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5368 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5375 // Represents header string for documentation comment.
5377 public override string DocCommentHeader {
5378 get { return "F:"; }
5382 interface IFixedBuffer
5384 FieldInfo Element { get; }
5385 Type ElementType { get; }
5388 public class FixedFieldExternal: IFixedBuffer
5390 FieldInfo element_field;
5392 public FixedFieldExternal (FieldInfo fi)
5394 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5397 #region IFixedField Members
5399 public FieldInfo Element {
5401 return element_field;
5405 public Type ElementType {
5407 return element_field.FieldType;
5415 /// Fixed buffer implementation
5417 public class FixedField: FieldMember, IFixedBuffer
5419 public const string FixedElementName = "FixedElementField";
5420 static int GlobalCounter = 0;
5421 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5422 static FieldInfo[] fi;
5424 TypeBuilder fixed_buffer_type;
5425 FieldBuilder element;
5426 Expression size_expr;
5429 const int AllowedModifiers =
5432 Modifiers.PROTECTED |
5433 Modifiers.INTERNAL |
5436 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5437 Expression size_expr, Attributes attrs, Location loc):
5438 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5440 if (RootContext.Version == LanguageVersion.ISO_1)
5441 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5443 this.size_expr = size_expr;
5446 public override bool Define()
5449 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5450 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5453 if (Parent.Kind != Kind.Struct) {
5454 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5455 GetSignatureForError ());
5459 if (!base.Define ())
5462 if (!TypeManager.IsPrimitiveType (MemberType)) {
5463 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",
5464 GetSignatureForError ());
5468 Expression e = size_expr.Resolve (Parent.EmitContext);
5472 Constant c = e as Constant;
5474 Const.Error_ExpressionMustBeConstant (e.Location, GetSignatureForError ());
5478 IntConstant buffer_size_const = c.ToInt (Location);
5479 if (buffer_size_const == null)
5482 buffer_size = buffer_size_const.Value;
5484 if (buffer_size <= 0) {
5485 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5489 int type_size = Expression.GetTypeSize (MemberType);
5491 if (buffer_size > int.MaxValue / type_size) {
5492 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5493 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5497 buffer_size *= type_size;
5500 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5502 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5503 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5504 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5505 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5507 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5508 TypeManager.RegisterFieldBase (FieldBuilder, this);
5513 public override void Emit()
5516 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5518 object[] fi_val = new object[1];
5519 fi_val [0] = buffer_size;
5521 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5522 ctor_args, fi, fi_val);
5523 fixed_buffer_type.SetCustomAttribute (cab);
5526 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5527 FieldBuilder.SetCustomAttribute (cab);
5532 protected override bool IsFieldClsCompliant {
5538 #region IFixedField Members
5540 public FieldInfo Element {
5546 public Type ElementType {
5556 // The Field class is used to represents class/struct fields during parsing.
5558 public class Field : FieldMember {
5560 // Modifiers allowed in a class declaration
5562 const int AllowedModifiers =
5565 Modifiers.PROTECTED |
5566 Modifiers.INTERNAL |
5569 Modifiers.VOLATILE |
5573 public Field (TypeContainer parent, Expression type, int mod, string name,
5574 Object expr_or_array_init, Attributes attrs, Location loc)
5575 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5576 expr_or_array_init, attrs, loc)
5580 public override bool Define ()
5582 if (!base.Define ())
5585 if (RootContext.WarningLevel > 1){
5586 Type ptype = Parent.TypeBuilder.BaseType;
5588 // ptype is only null for System.Object while compiling corlib.
5590 TypeContainer.FindMembers (
5591 ptype, MemberTypes.Method,
5592 BindingFlags.Public |
5593 BindingFlags.Static | BindingFlags.Instance,
5594 System.Type.FilterName, Name);
5598 if ((ModFlags & Modifiers.VOLATILE) != 0){
5599 if (!MemberType.IsClass){
5600 Type vt = MemberType;
5602 if (TypeManager.IsEnumType (vt))
5603 vt = TypeManager.EnumToUnderlying (MemberType);
5605 if (!((vt == TypeManager.bool_type) ||
5606 (vt == TypeManager.sbyte_type) ||
5607 (vt == TypeManager.byte_type) ||
5608 (vt == TypeManager.short_type) ||
5609 (vt == TypeManager.ushort_type) ||
5610 (vt == TypeManager.int32_type) ||
5611 (vt == TypeManager.uint32_type) ||
5612 (vt == TypeManager.char_type) ||
5613 (vt == TypeManager.float_type) ||
5614 (!vt.IsValueType))){
5615 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5616 GetSignatureForError (), TypeManager.CSharpName (vt));
5621 if ((ModFlags & Modifiers.READONLY) != 0){
5622 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5623 GetSignatureForError ());
5628 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5630 if (Parent.Kind == Kind.Struct &&
5631 ((fa & FieldAttributes.Static) == 0) &&
5632 MemberType == Parent.TypeBuilder &&
5633 !TypeManager.IsBuiltinType (MemberType)){
5634 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5635 "' causes a cycle in the structure layout");
5640 FieldBuilder = Parent.TypeBuilder.DefineField (
5641 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5643 TypeManager.RegisterFieldBase (FieldBuilder, this);
5645 catch (ArgumentException) {
5646 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5653 protected override bool VerifyClsCompliance (DeclSpace ds)
5655 if (!base.VerifyClsCompliance (ds))
5658 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5659 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5667 // `set' and `get' accessors are represented with an Accessor.
5669 public class Accessor : IIteratorContainer {
5671 // Null if the accessor is empty, or a Block if not
5673 public const int AllowedModifiers =
5675 Modifiers.PROTECTED |
5676 Modifiers.INTERNAL |
5679 public ToplevelBlock Block;
5680 public Attributes Attributes;
5681 public Location Location;
5682 public int ModFlags;
5685 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5690 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5693 public void SetYields ()
5699 // Ooouh Martin, templates are missing here.
5700 // When it will be possible move here a lot of child code and template method type.
5701 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5702 protected MethodData method_data;
5703 protected ToplevelBlock block;
5704 protected ListDictionary declarative_security;
5706 // The accessor are created event if they are not wanted.
5707 // But we need them because their names are reserved.
5708 // Field says whether accessor will be emited or not
5709 public readonly bool IsDummy;
5711 protected readonly string prefix;
5713 ReturnParameter return_attributes;
5715 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5716 : base (null, SetupName (prefix, member), null, member.Location)
5718 this.prefix = prefix;
5722 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5724 : base (null, SetupName (prefix, member),
5725 accessor.Attributes, accessor.Location)
5727 this.prefix = prefix;
5728 this.block = accessor.Block;
5731 static MemberName SetupName (string prefix, MemberBase member)
5733 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
5736 public void UpdateName (MemberBase member)
5738 SetMemberName (SetupName (prefix, member));
5741 #region IMethodData Members
5743 public ToplevelBlock Block {
5753 public CallingConventions CallingConventions {
5755 return CallingConventions.Standard;
5759 public bool IsExcluded (EmitContext ec)
5764 public MemberName MethodName {
5770 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5771 public abstract Type[] ParameterTypes { get; }
5772 public abstract Type ReturnType { get; }
5773 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5777 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5779 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5780 a.Type == TypeManager.conditional_attribute_type) {
5781 Report.Error (1667, a.Location,
5782 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5783 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5787 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5788 if (declarative_security == null)
5789 declarative_security = new ListDictionary ();
5790 a.ExtractSecurityPermissionSet (declarative_security);
5794 if (a.Target == AttributeTargets.Method) {
5795 method_data.MethodBuilder.SetCustomAttribute (cb);
5799 if (a.Target == AttributeTargets.ReturnValue) {
5800 if (return_attributes == null)
5801 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5803 return_attributes.ApplyAttributeBuilder (a, cb);
5807 ApplyToExtraTarget (a, cb);
5810 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5812 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5815 public override bool Define()
5817 throw new NotSupportedException ();
5820 public virtual void Emit (TypeContainer container)
5822 EmitMethod (container);
5824 if (declarative_security != null) {
5825 foreach (DictionaryEntry de in declarative_security) {
5826 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5833 protected virtual void EmitMethod (TypeContainer container)
5835 method_data.Emit (container, this);
5838 public override bool IsClsCompliaceRequired(DeclSpace ds)
5843 public bool IsDuplicateImplementation (MethodCore method)
5845 if (!MemberName.Equals (method.MemberName))
5848 Type[] param_types = method.ParameterTypes;
5850 if (param_types.Length != ParameterTypes.Length)
5853 for (int i = 0; i < param_types.Length; i++)
5854 if (param_types [i] != ParameterTypes [i])
5857 Report.SymbolRelatedToPreviousError (method);
5858 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
5862 public override bool IsUsed
5872 public new Location Location {
5874 return base.Location;
5879 // Represents header string for documentation comment.
5881 public override string DocCommentHeader {
5882 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5885 protected override void VerifyObsoleteAttribute()
5892 // Properties and Indexers both generate PropertyBuilders, we use this to share
5893 // their common bits.
5895 abstract public class PropertyBase : MethodCore {
5897 public class GetMethod: PropertyMethod
5899 static string[] attribute_targets = new string [] { "method", "return" };
5901 public GetMethod (MethodCore method):
5902 base (method, "get_")
5906 public GetMethod (MethodCore method, Accessor accessor):
5907 base (method, accessor, "get_")
5911 public override MethodBuilder Define(TypeContainer container)
5913 base.Define (container);
5915 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5917 if (!method_data.Define (container))
5920 return method_data.MethodBuilder;
5923 public override Type ReturnType {
5925 return method.MemberType;
5929 public override string[] ValidAttributeTargets {
5931 return attribute_targets;
5936 public class SetMethod: PropertyMethod {
5938 static string[] attribute_targets = new string [] { "method", "param", "return" };
5939 ImplicitParameter param_attr;
5941 public SetMethod (MethodCore method):
5942 base (method, "set_")
5946 public SetMethod (MethodCore method, Accessor accessor):
5947 base (method, accessor, "set_")
5951 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5953 if (a.Target == AttributeTargets.Parameter) {
5954 if (param_attr == null)
5955 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
5957 param_attr.ApplyAttributeBuilder (a, cb);
5961 base.ApplyAttributeBuilder (a, cb);
5964 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5966 Parameter [] parms = new Parameter [1];
5967 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
5968 Parameters parameters = new Parameters (parms, null);
5970 bool old_unsafe = ec.InUnsafe;
5971 ec.InUnsafe = InUnsafe;
5972 Type [] types = parameters.GetParameterInfo (ec);
5973 ec.InUnsafe = old_unsafe;
5975 return new InternalParameters (types, parameters);
5978 public override MethodBuilder Define (TypeContainer container)
5980 if (container.EmitContext == null)
5981 throw new InternalErrorException ("SetMethod.Define called too early");
5983 base.Define (container);
5985 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5987 if (!method_data.Define (container))
5990 return method_data.MethodBuilder;
5993 public override Type[] ParameterTypes {
5995 return new Type[] { method.MemberType };
5999 public override Type ReturnType {
6001 return TypeManager.void_type;
6005 public override string[] ValidAttributeTargets {
6007 return attribute_targets;
6012 static string[] attribute_targets = new string [] { "property" };
6014 public abstract class PropertyMethod: AbstractPropertyEventMethod
6016 protected readonly MethodCore method;
6017 protected MethodAttributes flags;
6020 public PropertyMethod (MethodCore method, string prefix)
6021 : base (method, prefix)
6023 this.method = method;
6024 Parent = method.Parent;
6027 public PropertyMethod (MethodCore method, Accessor accessor,
6029 : base (method, accessor, prefix)
6031 this.method = method;
6032 Parent = method.Parent;
6033 this.ModFlags = accessor.ModFlags;
6034 yields = accessor.Yields;
6036 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6037 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6041 public override AttributeTargets AttributeTargets {
6043 return AttributeTargets.Method;
6047 public override bool IsClsCompliaceRequired(DeclSpace ds)
6049 return method.IsClsCompliaceRequired (ds);
6052 public InternalParameters ParameterInfo
6055 return method_data.ParameterInfo;
6059 public virtual MethodBuilder Define (TypeContainer container)
6061 if (!method.CheckAbstractAndExtern (block != null))
6065 // Check for custom access modifier
6067 if (ModFlags == 0) {
6068 ModFlags = method.ModFlags;
6069 flags = method.flags;
6071 if (container.Kind == Kind.Interface)
6072 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6073 GetSignatureForError ());
6075 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6076 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6079 CheckModifiers (container, ModFlags);
6080 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6081 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6082 flags = Modifiers.MethodAttr (ModFlags);
6083 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6087 // Setup iterator if we are one
6090 Iterator iterator = new Iterator (this,
6091 Parent, method.ParameterInfo, ModFlags);
6093 if (!iterator.DefineIterator ())
6100 public bool HasCustomAccessModifier
6103 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6107 public override Type[] ParameterTypes {
6109 return TypeManager.NoTypes;
6113 public override EmitContext CreateEmitContext (TypeContainer tc,
6116 return new EmitContext (
6117 tc, method.Parent, method.Location, ig, ReturnType,
6118 method.ModFlags, false);
6121 public override ObsoleteAttribute GetObsoleteAttribute ()
6123 return method.GetObsoleteAttribute (method.Parent);
6126 public override string GetSignatureForError()
6128 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6131 void CheckModifiers (TypeContainer container, int modflags)
6134 int mflags = method.ModFlags & Modifiers.Accessibility;
6136 if ((mflags & Modifiers.PUBLIC) != 0) {
6137 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6139 else if ((mflags & Modifiers.PROTECTED) != 0) {
6140 if ((mflags & Modifiers.INTERNAL) != 0)
6141 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6143 flags |= Modifiers.PRIVATE;
6145 else if ((mflags & Modifiers.INTERNAL) != 0)
6146 flags |= Modifiers.PRIVATE;
6148 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6149 Report.Error (273, Location,
6150 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6151 GetSignatureForError (), method.GetSignatureForError ());
6155 public override bool MarkForDuplicationCheck ()
6157 caching_flags |= Flags.TestMethodDuplication;
6163 public PropertyMethod Get, Set;
6164 public PropertyBuilder PropertyBuilder;
6165 public MethodBuilder GetBuilder, SetBuilder;
6167 protected EmitContext ec;
6169 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6170 int allowed_mod, bool is_iface, MemberName name,
6171 Parameters parameters, Attributes attrs,
6173 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6174 attrs, parameters, loc)
6178 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6180 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6181 a.Error_InvalidSecurityParent ();
6185 PropertyBuilder.SetCustomAttribute (cb);
6188 public override AttributeTargets AttributeTargets {
6190 return AttributeTargets.Property;
6194 public override bool Define ()
6199 if (!IsTypePermitted ())
6205 protected override bool DoDefine ()
6207 if (!base.DoDefine ())
6211 // Accessors modifiers check
6213 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6214 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6215 GetSignatureForError ());
6219 if ((Get.IsDummy || Set.IsDummy)
6220 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6221 Report.Error (276, Location,
6222 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6223 GetSignatureForError ());
6227 if (MemberType.IsAbstract && MemberType.IsSealed) {
6228 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6232 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6236 protected override bool CheckForDuplications ()
6238 ArrayList ar = Parent.Indexers;
6240 int arLen = ar.Count;
6242 for (int i = 0; i < arLen; i++) {
6243 Indexer m = (Indexer) ar [i];
6244 if (IsDuplicateImplementation (m))
6249 ar = Parent.Properties;
6251 int arLen = ar.Count;
6253 for (int i = 0; i < arLen; i++) {
6254 Property m = (Property) ar [i];
6255 if (IsDuplicateImplementation (m))
6263 // TODO: rename to Resolve......
6264 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6266 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6267 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6269 if (base_property == null)
6272 base_ret_type = base_property.PropertyType;
6273 MethodInfo get_accessor = base_property.GetGetMethod (true);
6274 MethodInfo set_accessor = base_property.GetSetMethod (true);
6275 MethodAttributes get_accessor_access, set_accessor_access;
6277 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6278 if (Get != null && !Get.IsDummy && get_accessor == null) {
6279 Report.SymbolRelatedToPreviousError (base_property);
6280 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6283 if (Set != null && !Set.IsDummy && set_accessor == null) {
6284 Report.SymbolRelatedToPreviousError (base_property);
6285 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6290 // Check base class accessors access
6293 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6294 get_accessor_access = set_accessor_access = 0;
6295 if ((ModFlags & Modifiers.NEW) == 0) {
6296 if (get_accessor != null) {
6297 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6298 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6300 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6301 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6304 if (set_accessor != null) {
6305 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6306 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6308 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6309 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6314 // Get the less restrictive access
6316 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6319 public override void Emit ()
6322 // The PropertyBuilder can be null for explicit implementations, in that
6323 // case, we do not actually emit the ".property", so there is nowhere to
6324 // put the attribute
6326 if (PropertyBuilder != null && OptAttributes != null)
6327 OptAttributes.Emit (ec, this);
6339 /// Tests whether accessors are not in collision with some method (CS0111)
6341 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6343 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6346 public override bool IsUsed
6352 return Get.IsUsed | Set.IsUsed;
6356 protected override void SetMemberName (MemberName new_name)
6358 base.SetMemberName (new_name);
6360 Get.UpdateName (this);
6361 Set.UpdateName (this);
6364 public override string[] ValidAttributeTargets {
6366 return attribute_targets;
6371 // Represents header string for documentation comment.
6373 public override string DocCommentHeader {
6374 get { return "P:"; }
6378 public class Property : PropertyBase {
6379 const int AllowedModifiers =
6382 Modifiers.PROTECTED |
6383 Modifiers.INTERNAL |
6387 Modifiers.OVERRIDE |
6388 Modifiers.ABSTRACT |
6391 Modifiers.METHOD_YIELDS |
6394 const int AllowedInterfaceModifiers =
6397 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6398 MemberName name, Attributes attrs, Accessor get_block,
6399 Accessor set_block, Location loc)
6400 : base (ds, type, mod,
6401 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6402 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6405 if (get_block == null)
6406 Get = new GetMethod (this);
6408 Get = new GetMethod (this, get_block);
6410 if (set_block == null)
6411 Set = new SetMethod (this);
6413 Set = new SetMethod (this, set_block);
6416 public override bool Define ()
6418 if (!base.Define ())
6424 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6427 GetBuilder = Get.Define (Parent);
6428 if (GetBuilder == null)
6433 SetBuilder = Set.Define (Parent);
6434 if (SetBuilder == null)
6437 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6440 // FIXME - PropertyAttributes.HasDefault ?
6442 PropertyAttributes prop_attr = PropertyAttributes.None;
6444 prop_attr |= PropertyAttributes.RTSpecialName |
6445 PropertyAttributes.SpecialName;
6447 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6448 Name, prop_attr, MemberType, null);
6451 PropertyBuilder.SetGetMethod (GetBuilder);
6454 PropertyBuilder.SetSetMethod (SetBuilder);
6456 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6462 /// Gigantic workaround for lameness in SRE follows :
6463 /// This class derives from EventInfo and attempts to basically
6464 /// wrap around the EventBuilder so that FindMembers can quickly
6465 /// return this in it search for members
6467 public class MyEventBuilder : EventInfo {
6470 // We use this to "point" to our Builder which is
6471 // not really a MemberInfo
6473 EventBuilder MyBuilder;
6476 // We "catch" and wrap these methods
6478 MethodInfo raise, remove, add;
6480 EventAttributes attributes;
6481 Type declaring_type, reflected_type, event_type;
6486 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6488 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6490 // And now store the values in our own fields.
6492 declaring_type = type_builder;
6494 reflected_type = type_builder;
6496 attributes = event_attr;
6499 this.event_type = event_type;
6503 // Methods that you have to override. Note that you only need
6504 // to "implement" the variants that take the argument (those are
6505 // the "abstract" methods, the others (GetAddMethod()) are
6508 public override MethodInfo GetAddMethod (bool nonPublic)
6513 public override MethodInfo GetRemoveMethod (bool nonPublic)
6518 public override MethodInfo GetRaiseMethod (bool nonPublic)
6524 // These methods make "MyEventInfo" look like a Builder
6526 public void SetRaiseMethod (MethodBuilder raiseMethod)
6528 raise = raiseMethod;
6529 MyBuilder.SetRaiseMethod (raiseMethod);
6532 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6534 remove = removeMethod;
6535 MyBuilder.SetRemoveOnMethod (removeMethod);
6538 public void SetAddOnMethod (MethodBuilder addMethod)
6541 MyBuilder.SetAddOnMethod (addMethod);
6544 public void SetCustomAttribute (CustomAttributeBuilder cb)
6546 MyBuilder.SetCustomAttribute (cb);
6549 public override object [] GetCustomAttributes (bool inherit)
6551 // FIXME : There's nothing which can be seemingly done here because
6552 // we have no way of getting at the custom attribute objects of the
6557 public override object [] GetCustomAttributes (Type t, bool inherit)
6559 // FIXME : Same here !
6563 public override bool IsDefined (Type t, bool b)
6568 public override EventAttributes Attributes {
6574 public override string Name {
6580 public override Type DeclaringType {
6582 return declaring_type;
6586 public override Type ReflectedType {
6588 return reflected_type;
6592 public Type EventType {
6598 public void SetUsed ()
6600 if (my_event != null) {
6601 my_event.SetAssigned ();
6602 my_event.SetMemberIsUsed ();
6608 /// For case when event is declared like property (with add and remove accessors).
6610 public class EventProperty: Event {
6612 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6614 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6615 bool is_iface, MemberName name, Object init,
6616 Attributes attrs, Accessor add, Accessor remove,
6618 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6620 Add = new AddDelegateMethod (this, add);
6621 Remove = new RemoveDelegateMethod (this, remove);
6623 // For this event syntax we don't report error CS0067
6624 // because it is hard to do it.
6628 public override string[] ValidAttributeTargets {
6630 return attribute_targets;
6636 /// Event is declared like field.
6638 public class EventField: Event {
6640 static string[] attribute_targets = new string [] { "event", "field", "method" };
6641 static string[] attribute_targets_interface = new string[] { "event", "method" };
6643 public EventField (TypeContainer parent, Expression type, int mod_flags,
6644 bool is_iface, MemberName name, Object init,
6645 Attributes attrs, Location loc)
6646 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6648 Add = new AddDelegateMethod (this);
6649 Remove = new RemoveDelegateMethod (this);
6652 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6654 if (a.Target == AttributeTargets.Field) {
6655 FieldBuilder.SetCustomAttribute (cb);
6659 if (a.Target == AttributeTargets.Method) {
6660 Add.ApplyAttributeBuilder (a, cb);
6661 Remove.ApplyAttributeBuilder (a, cb);
6665 base.ApplyAttributeBuilder (a, cb);
6668 public override string[] ValidAttributeTargets {
6670 return IsInterface ? attribute_targets_interface : attribute_targets;
6675 public abstract class Event : FieldBase {
6677 protected sealed class AddDelegateMethod: DelegateMethod
6680 public AddDelegateMethod (Event method):
6681 base (method, "add_")
6685 public AddDelegateMethod (Event method, Accessor accessor):
6686 base (method, accessor, "add_")
6690 protected override MethodInfo DelegateMethodInfo {
6692 return TypeManager.delegate_combine_delegate_delegate;
6698 protected sealed class RemoveDelegateMethod: DelegateMethod
6700 public RemoveDelegateMethod (Event method):
6701 base (method, "remove_")
6705 public RemoveDelegateMethod (Event method, Accessor accessor):
6706 base (method, accessor, "remove_")
6710 protected override MethodInfo DelegateMethodInfo {
6712 return TypeManager.delegate_remove_delegate_delegate;
6718 public abstract class DelegateMethod: AbstractPropertyEventMethod
6720 protected readonly Event method;
6721 ImplicitParameter param_attr;
6723 static string[] attribute_targets = new string [] { "method", "param", "return" };
6725 public DelegateMethod (Event method, string prefix)
6726 : base (method, prefix)
6728 this.method = method;
6731 public DelegateMethod (Event method, Accessor accessor, string prefix)
6732 : base (method, accessor, prefix)
6734 this.method = method;
6737 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6739 if (a.Target == AttributeTargets.Parameter) {
6740 if (param_attr == null)
6741 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6743 param_attr.ApplyAttributeBuilder (a, cb);
6747 base.ApplyAttributeBuilder (a, cb);
6750 public override AttributeTargets AttributeTargets {
6752 return AttributeTargets.Method;
6756 public override bool IsClsCompliaceRequired(DeclSpace ds)
6758 return method.IsClsCompliaceRequired (ds);
6761 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6763 method_data = new MethodData (method, ip, method.ModFlags,
6764 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6766 if (!method_data.Define (container))
6769 MethodBuilder mb = method_data.MethodBuilder;
6770 mb.DefineParameter (1, ParameterAttributes.None, "value");
6775 protected override void EmitMethod (TypeContainer tc)
6777 if (block != null) {
6778 base.EmitMethod (tc);
6782 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6785 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6786 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6788 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6789 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6790 ig.Emit (OpCodes.Ldsfld, field_info);
6791 ig.Emit (OpCodes.Ldarg_0);
6792 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6793 ig.Emit (OpCodes.Castclass, method.MemberType);
6794 ig.Emit (OpCodes.Stsfld, field_info);
6796 ig.Emit (OpCodes.Ldarg_0);
6797 ig.Emit (OpCodes.Ldarg_0);
6798 ig.Emit (OpCodes.Ldfld, field_info);
6799 ig.Emit (OpCodes.Ldarg_1);
6800 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6801 ig.Emit (OpCodes.Castclass, method.MemberType);
6802 ig.Emit (OpCodes.Stfld, field_info);
6804 ig.Emit (OpCodes.Ret);
6807 protected abstract MethodInfo DelegateMethodInfo { get; }
6809 public override Type[] ParameterTypes {
6811 return new Type[] { method.MemberType };
6815 public override Type ReturnType {
6817 return TypeManager.void_type;
6821 public override EmitContext CreateEmitContext (TypeContainer tc,
6824 return new EmitContext (
6825 tc, method.Parent, Location, ig, ReturnType,
6826 method.ModFlags, false);
6829 public override ObsoleteAttribute GetObsoleteAttribute ()
6831 return method.GetObsoleteAttribute (method.Parent);
6834 public override string[] ValidAttributeTargets {
6836 return attribute_targets;
6842 const int AllowedModifiers =
6845 Modifiers.PROTECTED |
6846 Modifiers.INTERNAL |
6851 Modifiers.OVERRIDE |
6855 const int AllowedInterfaceModifiers =
6858 public DelegateMethod Add, Remove;
6859 public MyEventBuilder EventBuilder;
6860 public MethodBuilder AddBuilder, RemoveBuilder;
6862 public Event (TypeContainer parent, Expression type, int mod_flags,
6863 bool is_iface, MemberName name, Object init, Attributes attrs,
6865 : base (parent, type, mod_flags,
6866 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6867 name, init, attrs, loc)
6869 IsInterface = is_iface;
6872 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6874 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6875 a.Error_InvalidSecurityParent ();
6879 EventBuilder.SetCustomAttribute (cb);
6882 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6884 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6887 public override AttributeTargets AttributeTargets {
6889 return AttributeTargets.Event;
6893 public override bool Define ()
6895 EventAttributes e_attr;
6896 e_attr = EventAttributes.None;
6901 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6902 Report.Error (74, Location, "`" + GetSignatureForError () +
6903 "': abstract event cannot have an initializer");
6907 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6908 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
6912 EmitContext ec = Parent.EmitContext;
6914 throw new InternalErrorException ("Event.Define called too early?");
6915 bool old_unsafe = ec.InUnsafe;
6916 ec.InUnsafe = InUnsafe;
6918 Parameter [] parms = new Parameter [1];
6919 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
6920 Parameters parameters = new Parameters (parms, null);
6921 Type [] types = parameters.GetParameterInfo (ec);
6922 InternalParameters ip = new InternalParameters (types, parameters);
6924 ec.InUnsafe = old_unsafe;
6930 // Now define the accessors
6933 AddBuilder = Add.Define (Parent, ip);
6934 if (AddBuilder == null)
6937 RemoveBuilder = Remove.Define (Parent, ip);
6938 if (RemoveBuilder == null)
6941 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6943 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6944 FieldBuilder = Parent.TypeBuilder.DefineField (
6946 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6947 TypeManager.RegisterPrivateFieldOfEvent (
6948 (EventInfo) EventBuilder, FieldBuilder);
6949 TypeManager.RegisterFieldBase (FieldBuilder, this);
6952 EventBuilder.SetAddOnMethod (AddBuilder);
6953 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6955 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6959 protected override bool CheckBase ()
6961 if (!base.CheckBase ())
6964 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6965 if (!(conflict_symbol is EventInfo)) {
6966 Report.SymbolRelatedToPreviousError (conflict_symbol);
6967 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
6975 public override void Emit ()
6977 if (OptAttributes != null) {
6978 EmitContext ec = new EmitContext (
6979 Parent, Location, null, MemberType, ModFlags);
6980 OptAttributes.Emit (ec, this);
6984 Remove.Emit (Parent);
6989 public override string GetSignatureForError ()
6991 return base.GetSignatureForError ();
6995 // Represents header string for documentation comment.
6997 public override string DocCommentHeader {
6998 get { return "E:"; }
7003 public class Indexer : PropertyBase {
7005 class GetIndexerMethod: GetMethod
7007 public GetIndexerMethod (MethodCore method):
7012 public GetIndexerMethod (MethodCore method, Accessor accessor):
7013 base (method, accessor)
7017 public override Type[] ParameterTypes {
7019 return method.ParameterTypes;
7024 class SetIndexerMethod: SetMethod
7026 readonly Parameters parameters;
7028 public SetIndexerMethod (MethodCore method):
7033 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7034 base (method, accessor)
7036 this.parameters = parameters;
7039 public override Type[] ParameterTypes {
7041 int top = method.ParameterTypes.Length;
7042 Type [] set_pars = new Type [top + 1];
7043 method.ParameterTypes.CopyTo (set_pars, 0);
7044 set_pars [top] = method.MemberType;
7049 protected override InternalParameters GetParameterInfo (EmitContext ec)
7051 Parameter [] fixed_parms = parameters.FixedParameters;
7053 if (fixed_parms == null){
7054 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7055 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7056 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7058 // Here is the problem: the `value' parameter has
7059 // to come *after* the array parameter in the declaration
7061 // X (object [] x, Type value)
7064 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7065 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7069 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7071 fixed_parms.CopyTo (tmp, 0);
7072 tmp [fixed_parms.Length] = new Parameter (
7073 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7075 Parameters set_formal_params = new Parameters (tmp, null);
7076 Type [] types = set_formal_params.GetParameterInfo (ec);
7078 return new InternalParameters (types, set_formal_params);
7083 const int AllowedModifiers =
7086 Modifiers.PROTECTED |
7087 Modifiers.INTERNAL |
7091 Modifiers.OVERRIDE |
7096 const int AllowedInterfaceModifiers =
7100 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7101 bool is_iface, Parameters parameters, Attributes attrs,
7102 Accessor get_block, Accessor set_block, Location loc)
7103 : base (ds, type, mod,
7104 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7105 is_iface, name, parameters, attrs, loc)
7107 if (get_block == null)
7108 Get = new GetIndexerMethod (this);
7110 Get = new GetIndexerMethod (this, get_block);
7112 if (set_block == null)
7113 Set = new SetIndexerMethod (this);
7115 Set = new SetIndexerMethod (this, parameters, set_block);
7118 public override bool Define ()
7120 PropertyAttributes prop_attr =
7121 PropertyAttributes.RTSpecialName |
7122 PropertyAttributes.SpecialName;
7124 if (!base.Define ())
7127 if (MemberType == TypeManager.void_type) {
7128 Report.Error (620, Location, "Indexers cannot have void type");
7132 if (OptAttributes != null) {
7133 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7134 if (indexer_attr != null) {
7135 // Remove the attribute from the list because it is not emitted
7136 OptAttributes.Attrs.Remove (indexer_attr);
7138 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7140 if (IsExplicitImpl) {
7141 Report.Error (415, indexer_attr.Location,
7142 "The `IndexerName' attribute is valid only on an " +
7143 "indexer that is not an explicit interface member declaration");
7147 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7148 Report.Error (609, indexer_attr.Location,
7149 "Cannot set the `IndexerName' attribute on an indexer marked override");
7153 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7154 Report.Error (633, indexer_attr.Location,
7155 "The argument to the `IndexerName' attribute must be a valid identifier");
7161 if (InterfaceType != null) {
7162 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7163 if (base_IndexerName != Name)
7164 ShortName = base_IndexerName;
7167 if (!Parent.AddToMemberContainer (this) ||
7168 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7174 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7176 GetBuilder = Get.Define (Parent);
7177 if (GetBuilder == null)
7182 SetBuilder = Set.Define (Parent);
7183 if (SetBuilder == null)
7188 // Now name the parameters
7190 Parameter [] p = Parameters.FixedParameters;
7192 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7193 Report.Error (631, Location, "ref and out are not valid in this context");
7199 for (i = 0; i < p.Length; ++i) {
7201 GetBuilder.DefineParameter (
7202 i + 1, p [i].Attributes, p [i].Name);
7205 SetBuilder.DefineParameter (
7206 i + 1, p [i].Attributes, p [i].Name);
7210 SetBuilder.DefineParameter (
7211 i + 1, ParameterAttributes.None, "value");
7213 if (i != ParameterTypes.Length) {
7214 Parameter array_param = Parameters.ArrayParameter;
7216 SetBuilder.DefineParameter (
7217 i + 1, array_param.Attributes, array_param.Name);
7221 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7222 Name, prop_attr, MemberType, ParameterTypes);
7225 PropertyBuilder.SetGetMethod (GetBuilder);
7228 PropertyBuilder.SetSetMethod (SetBuilder);
7230 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7235 public override string GetSignatureForError ()
7237 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7238 if (MemberName.Left != null) {
7240 sb.Append (MemberName.Left);
7243 sb.Append (".this");
7244 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7245 return sb.ToString ();
7248 public override bool MarkForDuplicationCheck ()
7250 caching_flags |= Flags.TestMethodDuplication;
7256 public class Operator : MethodCore, IIteratorContainer {
7258 const int AllowedModifiers =
7264 public enum OpType : byte {
7274 // Unary and Binary operators
7297 // Implicit and Explicit
7301 // Just because of enum
7305 public readonly OpType OperatorType;
7306 public MethodBuilder OperatorMethodBuilder;
7308 public Method OperatorMethod;
7310 static string[] attribute_targets = new string [] { "method", "return" };
7312 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7313 int mod_flags, Parameters parameters,
7314 ToplevelBlock block, Attributes attrs, Location loc)
7315 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7316 new MemberName ("op_" + type), attrs, parameters, loc)
7318 OperatorType = type;
7322 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7324 OperatorMethod.ApplyAttributeBuilder (a, cb);
7327 public override AttributeTargets AttributeTargets {
7329 return AttributeTargets.Method;
7333 protected override bool CheckForDuplications()
7335 ArrayList ar = Parent.Operators;
7337 int arLen = ar.Count;
7339 for (int i = 0; i < arLen; i++) {
7340 Operator o = (Operator) ar [i];
7341 if (IsDuplicateImplementation (o))
7346 ar = Parent.Methods;
7348 int arLen = ar.Count;
7350 for (int i = 0; i < arLen; i++) {
7351 Method m = (Method) ar [i];
7352 if (IsDuplicateImplementation (m))
7360 public override bool Define ()
7362 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7363 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7364 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7371 if (MemberType == TypeManager.void_type) {
7372 Report.Error (590, Location, "User-defined operators cannot return void");
7376 OperatorMethod = new Method (
7377 Parent, Type, ModFlags, false, MemberName,
7378 Parameters, OptAttributes, Location);
7380 OperatorMethod.Block = Block;
7381 OperatorMethod.IsOperator = this;
7382 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7383 OperatorMethod.Define ();
7385 if (OperatorMethod.MethodBuilder == null)
7388 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7390 parameter_types = OperatorMethod.ParameterTypes;
7391 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7392 Type return_type = OperatorMethod.ReturnType;
7393 Type first_arg_type = parameter_types [0];
7398 // Rules for conversion operators
7400 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7401 if (first_arg_type == return_type && first_arg_type == declaring_type){
7402 Report.Error (555, Location,
7403 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7407 if (first_arg_type != declaring_type && return_type != declaring_type){
7410 "User-defined conversion must convert to or from the " +
7415 if (first_arg_type == TypeManager.object_type ||
7416 return_type == TypeManager.object_type){
7419 "User-defined conversion cannot convert to or from " +
7424 if (first_arg_type.IsInterface || return_type.IsInterface){
7425 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7426 GetSignatureForError ());
7430 if (first_arg_type.IsSubclassOf (return_type)
7431 || return_type.IsSubclassOf (first_arg_type)){
7432 if (declaring_type.IsSubclassOf (return_type)) {
7433 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7434 GetSignatureForError ());
7437 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7438 GetSignatureForError ());
7441 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7442 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7443 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");
7446 } else if (Parameters.FixedParameters.Length == 1) {
7447 // Checks for Unary operators
7449 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7450 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7451 Report.Error (448, Location,
7452 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7455 if (first_arg_type != declaring_type) {
7457 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7462 if (first_arg_type != declaring_type){
7465 "The parameter of a unary operator must be the " +
7470 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7471 if (return_type != TypeManager.bool_type){
7474 "The return type of operator True or False " +
7481 // Checks for Binary operators
7483 if (first_arg_type != declaring_type &&
7484 parameter_types [1] != declaring_type){
7487 "One of the parameters of a binary operator must " +
7488 "be the containing type");
7496 public override void Emit ()
7499 // abstract or extern methods have no bodies
7501 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7504 OperatorMethod.Emit ();
7508 // Operator cannot be override
7509 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7514 public static string GetName (OpType ot)
7517 case OpType.LogicalNot:
7519 case OpType.OnesComplement:
7521 case OpType.Increment:
7523 case OpType.Decrement:
7529 case OpType.Addition:
7531 case OpType.Subtraction:
7533 case OpType.UnaryPlus:
7535 case OpType.UnaryNegation:
7537 case OpType.Multiply:
7539 case OpType.Division:
7541 case OpType.Modulus:
7543 case OpType.BitwiseAnd:
7545 case OpType.BitwiseOr:
7547 case OpType.ExclusiveOr:
7549 case OpType.LeftShift:
7551 case OpType.RightShift:
7553 case OpType.Equality:
7555 case OpType.Inequality:
7557 case OpType.GreaterThan:
7559 case OpType.LessThan:
7561 case OpType.GreaterThanOrEqual:
7563 case OpType.LessThanOrEqual:
7565 case OpType.Implicit:
7567 case OpType.Explicit:
7573 public static OpType GetOperatorType (string name)
7575 if (name.StartsWith ("op_")){
7576 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7577 if (Unary.oper_names [i] == name)
7581 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7582 if (Binary.oper_names [i] == name)
7589 public override string GetSignatureForError ()
7591 StringBuilder sb = new StringBuilder ();
7592 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7593 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7596 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7599 sb.Append (Parameters.GetSignatureForError ());
7600 return sb.ToString ();
7603 public override bool MarkForDuplicationCheck ()
7605 caching_flags |= Flags.TestMethodDuplication;
7609 public override string[] ValidAttributeTargets {
7611 return attribute_targets;
7617 // This is used to compare method signatures
7619 struct MethodSignature {
7621 public Type RetType;
7622 public Type [] Parameters;
7625 /// This delegate is used to extract methods which have the
7626 /// same signature as the argument
7628 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7630 public MethodSignature (string name, Type ret_type, Type [] parameters)
7635 if (parameters == null)
7636 Parameters = TypeManager.NoTypes;
7638 Parameters = parameters;
7641 public override string ToString ()
7644 if (Parameters.Length != 0){
7645 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7646 for (int i = 0; i < Parameters.Length; i++){
7647 sb.Append (Parameters [i]);
7648 if (i+1 < Parameters.Length)
7651 pars = sb.ToString ();
7654 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7657 public override int GetHashCode ()
7659 return Name.GetHashCode ();
7662 public override bool Equals (Object o)
7664 MethodSignature other = (MethodSignature) o;
7666 if (other.Name != Name)
7669 if (other.RetType != RetType)
7672 if (Parameters == null){
7673 if (other.Parameters == null)
7678 if (other.Parameters == null)
7681 int c = Parameters.Length;
7682 if (other.Parameters.Length != c)
7685 for (int i = 0; i < c; i++)
7686 if (other.Parameters [i] != Parameters [i])
7692 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7694 MethodSignature sig = (MethodSignature) filter_criteria;
7696 if (m.Name != sig.Name)
7700 MethodInfo mi = m as MethodInfo;
7701 PropertyInfo pi = m as PropertyInfo;
7704 ReturnType = mi.ReturnType;
7705 else if (pi != null)
7706 ReturnType = pi.PropertyType;
7711 // we use sig.RetType == null to mean `do not check the
7712 // method return value.
7714 if (sig.RetType != null)
7715 if (ReturnType != sig.RetType)
7720 args = TypeManager.GetArgumentTypes (mi);
7722 args = TypeManager.GetArgumentTypes (pi);
7723 Type [] sigp = sig.Parameters;
7725 if (args.Length != sigp.Length)
7728 for (int i = args.Length; i > 0; ){
7730 if (args [i] != sigp [i])