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)
477 : base (ns, parent, name, attrs)
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 (!base_loc.IsNull)
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)
2537 PartialContainer pc = RootContext.Tree.GetDecl (member_name) as PartialContainer;
2539 if (pc.Kind != kind) {
2541 261, member_name.Location, "Partial declarations of `{0}' " +
2542 "must be all classes, all structs or " +
2543 "all interfaces", member_name.GetPartialName ());
2547 if (pc.OriginalModFlags != mod_flags) {
2549 262, member_name.Location, "Partial declarations of `{0}' " +
2550 "have conflicting accessibility modifiers",
2551 member_name.GetPartialName ());
2558 if (parent is ClassPart)
2559 parent = ((ClassPart) parent).PartialContainer;
2561 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind);
2563 if (kind == Kind.Interface) {
2564 if (!parent.AddInterface (pc))
2566 } else if (kind == Kind.Class || kind == Kind.Struct) {
2567 if (!parent.AddClassOrStruct (pc))
2570 throw new InvalidOperationException ();
2572 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2576 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2577 MemberName name, int mod, Attributes attrs,
2578 Kind kind, Location loc)
2580 PartialContainer pc = Create (ns, parent, name, mod, kind);
2582 // An error occured; create a dummy container, but don't
2584 pc = new PartialContainer (ns.NS, parent, name, mod, kind);
2587 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind);
2592 protected PartialContainer (Namespace ns, TypeContainer parent,
2593 MemberName name, int mod, Kind kind)
2594 : base (null, parent, name, null, kind)
2596 this.Namespace = ns;
2600 AllowedModifiers = Class.AllowedModifiers;
2601 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2605 AllowedModifiers = Struct.AllowedModifiers;
2606 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2609 case Kind.Interface:
2610 AllowedModifiers = Interface.AllowedModifiers;
2611 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2615 throw new InvalidOperationException ();
2619 if (parent.Parent == null)
2620 accmods = Modifiers.INTERNAL;
2622 accmods = Modifiers.PRIVATE;
2624 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2625 this.OriginalModFlags = mod;
2628 public override PendingImplementation GetPendingImplementations ()
2630 return PendingImplementation.GetPendingImplementations (this);
2633 public override bool MarkForDuplicationCheck ()
2638 protected override TypeAttributes TypeAttr {
2640 return base.TypeAttr | DefaultTypeAttributes;
2645 public class ClassPart : TypeContainer, IMemberContainer {
2646 public readonly PartialContainer PartialContainer;
2647 public readonly bool IsPartial;
2649 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2650 int mod, Attributes attrs, Kind kind)
2651 : base (ns, parent, pc.MemberName, attrs, kind)
2653 this.PartialContainer = pc;
2654 this.IsPartial = true;
2657 if (parent == null || parent == RootContext.Tree.Types)
2658 accmods = Modifiers.INTERNAL;
2660 accmods = Modifiers.PRIVATE;
2662 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, pc.MemberName.Location);
2665 public override PendingImplementation GetPendingImplementations ()
2667 return PartialContainer.Pending;
2670 public override bool VerifyImplements (MemberBase mb)
2672 return PartialContainer.VerifyImplements (mb);
2676 public override void RegisterFieldForInitialization (FieldMember field)
2678 PartialContainer.RegisterFieldForInitialization (field);
2681 public override bool EmitFieldInitializers (EmitContext ec)
2683 return PartialContainer.EmitFieldInitializers (ec);
2686 public override Type FindNestedType (string name)
2688 return PartialContainer.FindNestedType (name);
2691 public override MemberCache BaseCache {
2693 return PartialContainer.BaseCache;
2697 public override TypeBuilder DefineType ()
2699 throw new InternalErrorException ("Should not get here");
2704 public abstract class ClassOrStruct : TypeContainer {
2705 bool has_explicit_layout = false;
2706 ListDictionary declarative_security;
2708 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2709 MemberName name, Attributes attrs, Kind kind)
2710 : base (ns, parent, name, attrs, kind)
2714 public override PendingImplementation GetPendingImplementations ()
2716 return PendingImplementation.GetPendingImplementations (this);
2719 public override bool HasExplicitLayout {
2721 return has_explicit_layout;
2725 public override void VerifyMembers ()
2727 base.VerifyMembers ();
2729 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2730 foreach (Event e in events){
2731 if ((e.caching_flags & Flags.IsAssigned) == 0)
2732 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2737 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2739 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2740 if (declarative_security == null)
2741 declarative_security = new ListDictionary ();
2743 a.ExtractSecurityPermissionSet (declarative_security);
2747 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2748 has_explicit_layout = true;
2750 base.ApplyAttributeBuilder (a, cb);
2753 public override void Emit()
2757 if (declarative_security != null) {
2758 foreach (DictionaryEntry de in declarative_security) {
2759 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2766 /// Class handles static classes declaration
2768 public sealed class StaticClass: Class {
2769 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2771 : base (ns, parent, name, mod, attrs)
2773 if (RootContext.Version == LanguageVersion.ISO_1) {
2774 Report.FeatureIsNotStandardized (Location, "static classes");
2778 protected override int AllowedModifiersProp {
2780 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2781 Modifiers.STATIC | Modifiers.UNSAFE;
2785 protected override void DefineContainerMembers (MemberCoreArrayList list)
2790 foreach (MemberCore m in list) {
2791 if (m is Operator) {
2792 Report.Error (715, m.Location, "`{0}': static classes cannot contain user-defined operators", m.GetSignatureForError ());
2796 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2797 Report.Warning (-628, 4, m.Location, "`{0}': new protected member declared in static class", m.GetSignatureForError ());
2800 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2804 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2807 if (m is Constructor) {
2808 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2812 if (m is Destructor) {
2813 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2817 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2820 base.DefineContainerMembers (list);
2823 public override TypeBuilder DefineType()
2825 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2826 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2830 TypeBuilder tb = base.DefineType ();
2834 if (ptype != TypeManager.object_type) {
2835 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2839 if (ifaces != null) {
2840 foreach (Type t in ifaces)
2841 Report.SymbolRelatedToPreviousError (t);
2842 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2847 protected override TypeAttributes TypeAttr {
2849 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2854 public class Class : ClassOrStruct {
2855 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2856 public const int AllowedModifiers =
2859 Modifiers.PROTECTED |
2860 Modifiers.INTERNAL |
2862 Modifiers.ABSTRACT |
2866 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2868 : base (ns, parent, name, attrs, Kind.Class)
2870 this.ModFlags = mod;
2873 virtual protected int AllowedModifiersProp {
2875 return AllowedModifiers;
2879 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2881 if (a.Type == TypeManager.attribute_usage_type) {
2882 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2883 TypeBuilder.FullName != "System.Attribute") {
2884 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2888 if (a.Type == TypeManager.conditional_attribute_type &&
2889 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
2890 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2894 if (AttributeTester.IsAttributeExcluded (a.Type))
2897 base.ApplyAttributeBuilder (a, cb);
2900 public const TypeAttributes DefaultTypeAttributes =
2901 TypeAttributes.AutoLayout | TypeAttributes.Class;
2903 public override TypeBuilder DefineType()
2905 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2906 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2910 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2911 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2913 return base.DefineType ();
2916 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2917 /// Valid only for attribute classes.
2918 public bool IsExcluded ()
2920 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2921 return (caching_flags & Flags.Excluded) != 0;
2923 caching_flags &= ~Flags.Excluded_Undetected;
2925 if (OptAttributes == null)
2928 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
2933 foreach (Attribute a in attrs) {
2934 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
2935 if (RootContext.AllDefines.Contains (condition))
2939 caching_flags |= Flags.Excluded;
2944 // FIXME: How do we deal with the user specifying a different
2947 protected override TypeAttributes TypeAttr {
2949 return base.TypeAttr | DefaultTypeAttributes;
2954 public class Struct : ClassOrStruct {
2956 // Modifiers allowed in a struct declaration
2958 public const int AllowedModifiers =
2961 Modifiers.PROTECTED |
2962 Modifiers.INTERNAL |
2966 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2967 int mod, Attributes attrs)
2968 : base (ns, parent, name, attrs, Kind.Struct)
2972 if (parent.Parent == null)
2973 accmods = Modifiers.INTERNAL;
2975 accmods = Modifiers.PRIVATE;
2977 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2979 this.ModFlags |= Modifiers.SEALED;
2982 public const TypeAttributes DefaultTypeAttributes =
2983 TypeAttributes.SequentialLayout |
2984 TypeAttributes.Sealed |
2985 TypeAttributes.BeforeFieldInit;
2988 // FIXME: Allow the user to specify a different set of attributes
2989 // in some cases (Sealed for example is mandatory for a class,
2990 // but what SequentialLayout can be changed
2992 protected override TypeAttributes TypeAttr {
2994 return base.TypeAttr | DefaultTypeAttributes;
3002 public class Interface : TypeContainer, IMemberContainer {
3005 /// Modifiers allowed in a class declaration
3007 public const int AllowedModifiers =
3010 Modifiers.PROTECTED |
3011 Modifiers.INTERNAL |
3015 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3017 : base (ns, parent, name, attrs, Kind.Interface)
3021 if (parent.Parent == null)
3022 accmods = Modifiers.INTERNAL;
3024 accmods = Modifiers.PRIVATE;
3026 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3029 public override PendingImplementation GetPendingImplementations ()
3034 public const TypeAttributes DefaultTypeAttributes =
3035 TypeAttributes.AutoLayout |
3036 TypeAttributes.Abstract |
3037 TypeAttributes.Interface;
3039 protected override TypeAttributes TypeAttr {
3041 return base.TypeAttr | DefaultTypeAttributes;
3045 protected override bool VerifyClsCompliance (DeclSpace ds)
3047 if (!base.VerifyClsCompliance (ds))
3050 if (ifaces != null) {
3051 foreach (Type t in ifaces) {
3052 if (AttributeTester.IsClsCompliant (t))
3055 Report.SymbolRelatedToPreviousError (t);
3056 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3057 GetSignatureForError (), TypeManager.CSharpName (t));
3065 public abstract class MethodCore : MemberBase {
3066 public readonly Parameters Parameters;
3067 protected ToplevelBlock block;
3070 // Parameters, cached for semantic analysis.
3072 protected InternalParameters parameter_info;
3073 protected Type [] parameter_types;
3075 // Whether this is an operator method.
3076 public Operator IsOperator;
3079 // The method we're overriding if this is an override method.
3081 protected MethodInfo base_method = null;
3083 static string[] attribute_targets = new string [] { "method", "return" };
3085 public MethodCore (TypeContainer parent, Expression type, int mod,
3086 int allowed_mod, bool is_interface, MemberName name,
3087 Attributes attrs, Parameters parameters)
3088 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3091 Parameters = parameters;
3092 IsInterface = is_interface;
3096 // Returns the System.Type array for the parameters of this method
3098 public Type [] ParameterTypes {
3100 return parameter_types;
3104 public InternalParameters ParameterInfo
3107 return parameter_info;
3111 public ToplevelBlock Block {
3121 public void SetYields ()
3123 ModFlags |= Modifiers.METHOD_YIELDS;
3126 protected override bool CheckBase ()
3128 if (!base.CheckBase ())
3131 // Check whether arguments were correct.
3132 if (!DoDefineParameters ())
3135 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3141 // Is null for System.Object while compiling corlib and base interfaces
3142 if (Parent.BaseCache == null) {
3143 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3144 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3149 Type base_ret_type = null;
3150 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3152 // method is override
3153 if (base_method != null) {
3155 if (!CheckMethodAgainstBase ())
3158 if ((ModFlags & Modifiers.NEW) == 0) {
3159 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3160 Report.SymbolRelatedToPreviousError (base_method);
3161 if (this is PropertyBase) {
3162 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3163 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3166 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3167 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3172 if (base_method.IsAbstract && !IsInterface) {
3173 Report.SymbolRelatedToPreviousError (base_method);
3174 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3175 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3180 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3181 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3185 if (RootContext.WarningLevel > 2) {
3186 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3187 Parent.Methods.HasEquals = true;
3188 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3189 Parent.Methods.HasGetHashCode = true;
3192 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3193 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3195 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3196 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3197 Report.SymbolRelatedToPreviousError (base_method);
3198 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3199 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3206 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3207 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3208 if (conflict_symbol != null) {
3209 Report.SymbolRelatedToPreviousError (conflict_symbol);
3210 if (this is PropertyBase)
3211 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3213 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3215 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3219 if (conflict_symbol == null) {
3220 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3221 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3226 if ((ModFlags & Modifiers.NEW) == 0) {
3227 if (this is Method && conflict_symbol is MethodBase)
3230 Report.SymbolRelatedToPreviousError (conflict_symbol);
3231 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3232 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3239 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3240 // that have been defined.
3242 // `name' is the user visible name for reporting errors (this is used to
3243 // provide the right name regarding method names and properties)
3245 bool CheckMethodAgainstBase ()
3249 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3250 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3251 Report.Error (506, Location,
3252 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3253 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3257 // Now we check that the overriden method is not final
3259 if (base_method.IsFinal) {
3260 Report.SymbolRelatedToPreviousError (base_method);
3261 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3262 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3266 // Check that the permissions are not being changed
3268 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3269 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3271 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3272 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3277 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3278 ModFlags |= Modifiers.NEW;
3279 Report.SymbolRelatedToPreviousError (base_method);
3280 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3281 if (RootContext.WarningLevel >= 2)
3282 Report.Warning (114, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword", GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3284 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3285 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3292 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3294 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3296 // when overriding protected internal, the method can be declared
3297 // protected internal only within the same assembly
3300 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3301 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3303 // assemblies differ - report an error
3307 } else if (thisp != base_classp) {
3309 // same assembly, but other attributes differ - report an error
3314 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3316 // if it's not "protected internal", it must be "protected"
3320 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3322 // protected within the same assembly - an error
3325 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3326 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3328 // protected ok, but other attributes differ - report an error
3334 return (thisp == base_classp);
3338 public bool CheckAbstractAndExtern (bool has_block)
3340 if (Parent.Kind == Kind.Interface)
3344 if ((ModFlags & Modifiers.EXTERN) != 0) {
3345 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3346 GetSignatureForError ());
3350 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3351 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3352 GetSignatureForError ());
3356 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3357 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3358 GetSignatureForError ());
3366 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3368 Report.SymbolRelatedToPreviousError (base_method);
3369 string base_name = TypeManager.GetFullNameSignature (base_method);
3370 string this_name = GetSignatureForError ();
3371 if (suffix != null) {
3372 base_name += suffix;
3373 this_name += suffix;
3376 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3377 this_name, Modifiers.GetDescription (ma), base_name);
3380 protected static string Error722 {
3382 return "`{0}': static types cannot be used as return types";
3387 /// For custom member duplication search in a container
3389 protected abstract bool CheckForDuplications ();
3392 /// Gets base method and its return type
3394 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3396 protected virtual bool DoDefineParameters ()
3398 EmitContext ec = Parent.EmitContext;
3400 throw new InternalErrorException ("DoDefineParameters invoked too early");
3402 bool old_unsafe = ec.InUnsafe;
3403 ec.InUnsafe = InUnsafe;
3404 // Check if arguments were correct
3405 parameter_types = Parameters.GetParameterInfo (ec);
3406 ec.InUnsafe = old_unsafe;
3408 if ((parameter_types == null) ||
3409 !CheckParameters (Parent, parameter_types))
3412 parameter_info = new InternalParameters (parameter_types, Parameters);
3414 Parameter array_param = Parameters.ArrayParameter;
3415 if ((array_param != null) &&
3416 (!array_param.ParameterType.IsArray ||
3417 (array_param.ParameterType.GetArrayRank () != 1))) {
3418 Report.Error (225, Location, "The params parameter must be a single dimensional array");
3425 public override string[] ValidAttributeTargets {
3427 return attribute_targets;
3431 protected override bool VerifyClsCompliance (DeclSpace ds)
3433 if (!base.VerifyClsCompliance (ds)) {
3434 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3435 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3440 if (Parameters.HasArglist) {
3441 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3444 if (!AttributeTester.IsClsCompliant (MemberType)) {
3445 if (this is PropertyBase)
3446 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3447 GetSignatureForError ());
3449 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3450 GetSignatureForError ());
3453 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3458 protected bool IsDuplicateImplementation (MethodCore method)
3460 if (method == this || !(method.MemberName.Equals (MemberName)))
3463 Type[] param_types = method.ParameterTypes;
3464 if (param_types == null && ParameterTypes == null)
3466 if (param_types == null || ParameterTypes == null)
3469 if (param_types.Length != ParameterTypes.Length)
3472 for (int i = 0; i < param_types.Length; i++)
3473 if (param_types [i] != ParameterTypes [i])
3476 // TODO: make operator compatible with MethodCore to avoid this
3477 if (this is Operator && method is Operator) {
3478 if (MemberType != method.MemberType)
3483 // Try to report 663: method only differs on out/ref
3485 ParameterData info = ParameterInfo;
3486 ParameterData other_info = method.ParameterInfo;
3487 for (int i = 0; i < info.Count; i++){
3488 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3489 Report.SymbolRelatedToPreviousError (method);
3490 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3491 GetSignatureForError ());
3496 Report.SymbolRelatedToPreviousError (method);
3497 if (this is Operator && method is Operator)
3498 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3500 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3504 public override bool IsUsed {
3505 get { return IsExplicitImpl || base.IsUsed; }
3509 // Returns a string that represents the signature for this
3510 // member which should be used in XML documentation.
3512 public override string GetDocCommentName (DeclSpace ds)
3514 return DocUtil.GetMethodDocCommentName (this, ds);
3518 // Raised (and passed an XmlElement that contains the comment)
3519 // when GenerateDocComment is writing documentation expectedly.
3521 // FIXME: with a few effort, it could be done with XmlReader,
3522 // that means removal of DOM use.
3524 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3526 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3530 // Represents header string for documentation comment.
3532 public override string DocCommentHeader {
3533 get { return "M:"; }
3536 protected override void VerifyObsoleteAttribute()
3538 base.VerifyObsoleteAttribute ();
3540 if (parameter_types == null)
3543 foreach (Type type in parameter_types) {
3544 CheckUsageOfObsoleteAttribute (type);
3549 public class SourceMethod : ISourceMethod
3551 TypeContainer container;
3554 protected SourceMethod (TypeContainer container, MethodBase builder,
3555 ISourceFile file, Location start, Location end)
3557 this.container = container;
3558 this.builder = builder;
3560 CodeGen.SymbolWriter.OpenMethod (
3561 file, this, start.Row, start.Column, end.Row, start.Column);
3564 public string Name {
3565 get { return builder.Name; }
3568 public int NamespaceID {
3569 get { return container.NamespaceEntry.SymbolFileID; }
3574 if (builder is MethodBuilder)
3575 return ((MethodBuilder) builder).GetToken ().Token;
3576 else if (builder is ConstructorBuilder)
3577 return ((ConstructorBuilder) builder).GetToken ().Token;
3579 throw new NotSupportedException ();
3583 public void CloseMethod ()
3585 if (CodeGen.SymbolWriter != null)
3586 CodeGen.SymbolWriter.CloseMethod ();
3589 public static SourceMethod Create (TypeContainer parent,
3590 MethodBase builder, Block block)
3592 if (CodeGen.SymbolWriter == null)
3597 Location start_loc = block.StartLocation;
3598 if (start_loc.IsNull)
3601 Location end_loc = block.EndLocation;
3605 ISourceFile file = start_loc.SourceFile;
3609 return new SourceMethod (
3610 parent, builder, file, start_loc, end_loc);
3614 public class Method : MethodCore, IIteratorContainer, IMethodData {
3615 public MethodBuilder MethodBuilder;
3616 public MethodData MethodData;
3617 ReturnParameter return_attributes;
3618 ListDictionary declarative_security;
3621 /// Modifiers allowed in a class declaration
3623 const int AllowedModifiers =
3626 Modifiers.PROTECTED |
3627 Modifiers.INTERNAL |
3632 Modifiers.OVERRIDE |
3633 Modifiers.ABSTRACT |
3635 Modifiers.METHOD_YIELDS |
3638 const int AllowedInterfaceModifiers =
3639 Modifiers.NEW | Modifiers.UNSAFE;
3642 // return_type can be "null" for VOID values.
3644 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3645 MemberName name, Parameters parameters, Attributes attrs)
3646 : base (ds, return_type, mod,
3647 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3648 is_iface, name, attrs, parameters)
3652 public override AttributeTargets AttributeTargets {
3654 return AttributeTargets.Method;
3658 public override string GetSignatureForError()
3660 if (IsOperator != null)
3661 return IsOperator.GetSignatureForError ();
3663 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3666 void DuplicateEntryPoint (MethodInfo b, Location location)
3670 "Program `" + CodeGen.FileName +
3671 "' has more than one entry point defined: `" +
3672 TypeManager.CSharpSignature(b) + "'");
3675 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3677 if (b.ReturnType != TypeManager.void_type &&
3678 b.ReturnType != TypeManager.int32_type)
3681 if (pinfo.Count == 0)
3684 if (pinfo.Count > 1)
3687 Type t = pinfo.ParameterType(0);
3689 (t.GetArrayRank() == 1) &&
3690 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3691 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3697 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3699 if (a.Target == AttributeTargets.ReturnValue) {
3700 if (return_attributes == null)
3701 return_attributes = new ReturnParameter (MethodBuilder, Location);
3703 return_attributes.ApplyAttributeBuilder (a, cb);
3707 if (a.Type == TypeManager.methodimpl_attr_type &&
3708 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3709 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3712 if (a.Type == TypeManager.dllimport_type) {
3713 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3714 if ((ModFlags & extern_static) != extern_static) {
3715 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3721 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3722 if (declarative_security == null)
3723 declarative_security = new ListDictionary ();
3724 a.ExtractSecurityPermissionSet (declarative_security);
3728 if (a.Type == TypeManager.conditional_attribute_type) {
3729 if (IsOperator != null || IsExplicitImpl) {
3730 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3731 GetSignatureForError ());
3735 if (ReturnType != TypeManager.void_type) {
3736 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
3740 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3741 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
3746 Report.Error (582, Location, "Conditional not valid on interface members");
3750 if (MethodData.implementing != null) {
3751 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
3752 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
3756 for (int i = 0; i < parameter_info.Count; ++i) {
3757 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3758 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
3764 MethodBuilder.SetCustomAttribute (cb);
3767 protected override bool CheckForDuplications ()
3769 ArrayList ar = Parent.Methods;
3771 int arLen = ar.Count;
3773 for (int i = 0; i < arLen; i++) {
3774 Method m = (Method) ar [i];
3775 if (IsDuplicateImplementation (m))
3780 ar = Parent.Properties;
3782 for (int i = 0; i < ar.Count; ++i) {
3783 PropertyBase pb = (PropertyBase) ar [i];
3784 if (pb.AreAccessorsDuplicateImplementation (this))
3789 ar = Parent.Indexers;
3791 for (int i = 0; i < ar.Count; ++i) {
3792 PropertyBase pb = (PropertyBase) ar [i];
3793 if (pb.AreAccessorsDuplicateImplementation (this))
3800 for (int i = 0; i < ar.Count; ++i) {
3801 Event ev = (Event) ar [i];
3802 if (ev.AreAccessorsDuplicateImplementation (this))
3813 public override bool Define ()
3818 if (!CheckAbstractAndExtern (block != null))
3821 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3822 Error1599 (Location, ReturnType);
3829 if (IsOperator != null)
3830 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3832 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3834 if (!MethodData.Define (Parent))
3837 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3838 Name == "Finalize" && !(this is Destructor)) {
3839 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3843 // Setup iterator if we are one
3845 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3846 Iterator iterator = new Iterator (this,
3848 ParameterInfo, ModFlags);
3850 if (!iterator.DefineIterator ())
3854 MethodBuilder = MethodData.MethodBuilder;
3857 // This is used to track the Entry Point,
3859 if (Name == "Main" &&
3860 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3861 (RootContext.MainClass == null ||
3862 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3863 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3864 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3865 md.SetMemberIsUsed ();
3867 if (RootContext.EntryPoint == null) {
3868 RootContext.EntryPoint = MethodBuilder;
3869 RootContext.EntryPointLocation = Location;
3871 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3872 DuplicateEntryPoint (MethodBuilder, Location);
3875 if (RootContext.WarningLevel >= 4)
3876 Report.Warning (28, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3880 if (MemberType.IsAbstract && MemberType.IsSealed) {
3881 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3891 public override void Emit ()
3893 MethodData.Emit (Parent, this);
3896 if (declarative_security != null) {
3897 foreach (DictionaryEntry de in declarative_security) {
3898 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3906 public static void Error1599 (Location loc, Type t)
3908 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
3911 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3913 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3914 container.TypeBuilder, Name, ParameterTypes, false);
3919 base_ret_type = mi.ReturnType;
3923 public override bool MarkForDuplicationCheck ()
3925 caching_flags |= Flags.TestMethodDuplication;
3929 protected override bool VerifyClsCompliance(DeclSpace ds)
3931 if (!base.VerifyClsCompliance (ds))
3934 if (parameter_types.Length > 0) {
3935 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3937 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3943 #region IMethodData Members
3945 public CallingConventions CallingConventions {
3947 CallingConventions cc = Parameters.GetCallingConvention ();
3948 if (Parameters.HasArglist)
3949 block.HasVarargs = true;
3952 if ((ModFlags & Modifiers.STATIC) == 0)
3953 cc |= CallingConventions.HasThis;
3955 // FIXME: How is `ExplicitThis' used in C#?
3961 public Type ReturnType {
3967 public MemberName MethodName {
3973 public new Location Location {
3975 return base.Location;
3979 protected override bool CheckBase() {
3980 if (!base.CheckBase ())
3983 // TODO: Destructor should derive from MethodCore
3984 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3985 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3986 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3993 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3995 EmitContext ec = new EmitContext (
3996 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3998 ec.CurrentIterator = tc as Iterator;
3999 if (ec.CurrentIterator != null)
4000 ec.CurrentAnonymousMethod = ec.CurrentIterator.Host;
4005 public ObsoleteAttribute GetObsoleteAttribute ()
4007 return GetObsoleteAttribute (Parent);
4011 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4013 public bool IsExcluded (EmitContext ec)
4015 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4016 return (caching_flags & Flags.Excluded) != 0;
4018 caching_flags &= ~Flags.Excluded_Undetected;
4020 if (base_method == null) {
4021 if (OptAttributes == null)
4024 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4029 foreach (Attribute a in attrs) {
4030 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4031 if (RootContext.AllDefines.Contains (condition))
4035 caching_flags |= Flags.Excluded;
4039 IMethodData md = TypeManager.GetMethod (base_method);
4041 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4042 caching_flags |= Flags.Excluded;
4048 if (md.IsExcluded (ec)) {
4049 caching_flags |= Flags.Excluded;
4058 public abstract class ConstructorInitializer {
4059 ArrayList argument_list;
4060 protected ConstructorInfo base_constructor;
4063 public ConstructorInitializer (ArrayList argument_list, Location loc)
4065 this.argument_list = argument_list;
4069 public ArrayList Arguments {
4071 return argument_list;
4075 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4077 Expression base_constructor_group;
4081 ec.CurrentBlock = block;
4083 if (argument_list != null){
4084 foreach (Argument a in argument_list){
4085 if (!a.Resolve (ec, loc))
4089 ec.CurrentBlock = null;
4091 if (this is ConstructorBaseInitializer) {
4092 if (ec.ContainerType.BaseType == null)
4095 t = ec.ContainerType.BaseType;
4096 if (ec.ContainerType.IsValueType) {
4097 Report.Error (522, loc,
4098 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4102 t = ec.ContainerType;
4104 base_constructor_group = Expression.MemberLookup (
4105 ec, t, ".ctor", MemberTypes.Constructor,
4106 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4109 if (base_constructor_group == null){
4111 base_constructor_group = Expression.MemberLookup (
4112 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4113 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4117 int errors = Report.Errors;
4118 if (base_constructor_group != null)
4119 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4120 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4123 if (base_constructor == null) {
4124 if (errors == Report.Errors)
4125 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4126 argument_list.Count);
4131 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4132 base_constructor = null;
4136 if (base_constructor == caller_builder){
4137 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4144 public void Emit (EmitContext ec)
4146 if (base_constructor != null){
4147 ec.Mark (loc, false);
4149 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4151 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4156 public class ConstructorBaseInitializer : ConstructorInitializer {
4157 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4158 base (argument_list, l)
4163 public class ConstructorThisInitializer : ConstructorInitializer {
4164 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4165 base (argument_list, l)
4170 public class Constructor : MethodCore, IMethodData {
4171 public ConstructorBuilder ConstructorBuilder;
4172 public ConstructorInitializer Initializer;
4173 ListDictionary declarative_security;
4176 // Modifiers allowed for a constructor.
4178 public const int AllowedModifiers =
4180 Modifiers.PROTECTED |
4181 Modifiers.INTERNAL |
4187 bool has_compliant_args = false;
4189 // The spec claims that static is not permitted, but
4190 // my very own code has static constructors.
4192 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4193 ConstructorInitializer init, Location loc)
4194 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name, loc),
4200 public bool HasCompliantArgs {
4202 return has_compliant_args;
4206 public override AttributeTargets AttributeTargets {
4208 return AttributeTargets.Constructor;
4214 // Returns true if this is a default constructor
4216 public bool IsDefault ()
4218 if ((ModFlags & Modifiers.STATIC) != 0)
4219 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4220 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4223 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4224 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4225 (Initializer is ConstructorBaseInitializer) &&
4226 (Initializer.Arguments == null);
4229 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4231 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4232 if (declarative_security == null) {
4233 declarative_security = new ListDictionary ();
4235 a.ExtractSecurityPermissionSet (declarative_security);
4239 ConstructorBuilder.SetCustomAttribute (cb);
4242 protected override bool CheckForDuplications ()
4244 ArrayList ar = Parent.InstanceConstructors;
4246 int arLen = ar.Count;
4248 for (int i = 0; i < arLen; i++) {
4249 Constructor m = (Constructor) ar [i];
4250 if (IsDuplicateImplementation (m))
4257 protected override bool CheckBase ()
4259 // Check whether arguments were correct.
4260 if (!DoDefineParameters ())
4263 // TODO: skip the rest for generated ctor
4264 if ((ModFlags & Modifiers.STATIC) != 0)
4267 if (!CheckForDuplications ())
4270 if (Parent.Kind == Kind.Struct) {
4271 if (ParameterTypes.Length == 0) {
4272 Report.Error (568, Location,
4273 "Structs cannot contain explicit parameterless constructors");
4277 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4278 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4283 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4284 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4291 // Creates the ConstructorBuilder
4293 public override bool Define ()
4295 if (ConstructorBuilder != null)
4298 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4299 MethodAttributes.SpecialName);
4301 if ((ModFlags & Modifiers.STATIC) != 0) {
4302 ca |= MethodAttributes.Static | MethodAttributes.Private;
4304 ca |= MethodAttributes.HideBySig;
4306 if ((ModFlags & Modifiers.PUBLIC) != 0)
4307 ca |= MethodAttributes.Public;
4308 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4309 if ((ModFlags & Modifiers.INTERNAL) != 0)
4310 ca |= MethodAttributes.FamORAssem;
4312 ca |= MethodAttributes.Family;
4313 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4314 ca |= MethodAttributes.Assembly;
4315 else if (IsDefault ())
4316 ca |= MethodAttributes.Public;
4318 ca |= MethodAttributes.Private;
4321 if (!CheckAbstractAndExtern (block != null))
4324 // Check if arguments were correct.
4328 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4329 ca, CallingConventions,
4332 if ((ModFlags & Modifiers.UNSAFE) != 0)
4333 ConstructorBuilder.InitLocals = false;
4335 TypeManager.AddMethod (ConstructorBuilder, this);
4338 // HACK because System.Reflection.Emit is lame
4340 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4348 public override void Emit ()
4350 EmitContext ec = CreateEmitContext (null, null);
4352 // If this is a non-static `struct' constructor and doesn't have any
4353 // initializer, it must initialize all of the struct's fields.
4354 if ((Parent.Kind == Kind.Struct) &&
4355 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4356 Block.AddThisVariable (Parent, Location);
4358 if (block != null) {
4359 if (!block.ResolveMeta (ec, ParameterInfo))
4363 if ((ModFlags & Modifiers.STATIC) == 0){
4364 if (Parent.Kind == Kind.Class && Initializer == null)
4365 Initializer = new ConstructorBaseInitializer (null, Location);
4369 // Spec mandates that Initializers will not have
4373 if ((Initializer != null) &&
4374 !Initializer.Resolve (ConstructorBuilder, block, ec))
4376 ec.IsStatic = false;
4379 Parameters.LabelParameters (ec, ConstructorBuilder);
4381 SourceMethod source = SourceMethod.Create (
4382 Parent, ConstructorBuilder, block);
4385 // Classes can have base initializers and instance field initializers.
4387 if (Parent.Kind == Kind.Class){
4388 if ((ModFlags & Modifiers.STATIC) == 0){
4391 // If we use a "this (...)" constructor initializer, then
4392 // do not emit field initializers, they are initialized in the other constructor
4394 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4395 Parent.EmitFieldInitializers (ec);
4398 if (Initializer != null) {
4399 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4400 ec.TestObsoleteMethodUsage = false;
4402 Initializer.Emit (ec);
4405 if ((ModFlags & Modifiers.STATIC) != 0)
4406 Parent.EmitFieldInitializers (ec);
4408 if (OptAttributes != null)
4409 OptAttributes.Emit (ec, this);
4411 ec.EmitTopBlock (this, block, ParameterInfo);
4414 source.CloseMethod ();
4418 if (declarative_security != null) {
4419 foreach (DictionaryEntry de in declarative_security) {
4420 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4427 // Is never override
4428 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4433 public override string GetSignatureForError()
4435 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4438 protected override bool VerifyClsCompliance (DeclSpace ds)
4440 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4444 if (parameter_types.Length > 0) {
4445 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4447 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4449 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4450 foreach (Type param in parameter_types) {
4451 if (param.IsArray) {
4457 has_compliant_args = true;
4461 #region IMethodData Members
4463 public System.Reflection.CallingConventions CallingConventions {
4465 CallingConventions cc = Parameters.GetCallingConvention ();
4467 if (Parent.Kind == Kind.Class)
4468 if ((ModFlags & Modifiers.STATIC) == 0)
4469 cc |= CallingConventions.HasThis;
4471 // FIXME: How is `ExplicitThis' used in C#?
4477 public new Location Location {
4479 return base.Location;
4483 public MemberName MethodName {
4489 public Type ReturnType {
4495 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4497 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4498 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4501 public ObsoleteAttribute GetObsoleteAttribute ()
4503 return GetObsoleteAttribute (Parent);
4506 public bool IsExcluded(EmitContext ec)
4515 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4517 public interface IMethodData
4519 CallingConventions CallingConventions { get; }
4520 Location Location { get; }
4521 MemberName MethodName { get; }
4522 Type[] ParameterTypes { get; }
4523 Type ReturnType { get; }
4525 Attributes OptAttributes { get; }
4526 ToplevelBlock Block { get; set; }
4528 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4529 ObsoleteAttribute GetObsoleteAttribute ();
4530 string GetSignatureForError ();
4531 bool IsExcluded (EmitContext ec);
4532 bool IsClsCompliaceRequired (DeclSpace ds);
4533 void SetMemberIsUsed ();
4537 // Encapsulates most of the Method's state
4539 public class MethodData {
4541 readonly IMethodData method;
4544 // The return type of this method
4546 public readonly InternalParameters ParameterInfo;
4549 // Are we implementing an interface ?
4551 public MethodInfo implementing;
4556 protected MemberBase member;
4557 protected int modifiers;
4558 protected MethodAttributes flags;
4560 MethodBuilder builder = null;
4561 public MethodBuilder MethodBuilder {
4567 public MethodData (MemberBase member, InternalParameters parameters,
4568 int modifiers, MethodAttributes flags, IMethodData method)
4570 this.member = member;
4571 this.ParameterInfo = parameters;
4572 this.modifiers = modifiers;
4575 this.method = method;
4578 public bool Define (TypeContainer container)
4580 string name = method.MethodName.Name;
4581 string method_name = name;
4583 Type[] ParameterTypes = method.ParameterTypes;
4585 if (container.Pending != null){
4586 if (member is Indexer) // TODO: test it, but it should work without this IF
4587 implementing = container.Pending.IsInterfaceIndexer (
4588 member.InterfaceType, method.ReturnType, ParameterInfo);
4590 implementing = container.Pending.IsInterfaceMethod (
4591 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4593 if (member.InterfaceType != null){
4594 if (implementing == null){
4595 if (member is PropertyBase) {
4596 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4597 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4598 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4601 Report.Error (539, method.Location,
4602 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4603 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4607 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4608 Report.SymbolRelatedToPreviousError (implementing);
4609 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4610 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4613 method_name = member.InterfaceType.FullName + "." + name;
4615 if (implementing != null) {
4616 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4617 if (prop_method != null) {
4618 if (!implementing.IsSpecialName) {
4619 Report.SymbolRelatedToPreviousError (implementing);
4620 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4621 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4624 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4625 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4626 Report.SymbolRelatedToPreviousError (implementing);
4627 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4628 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4637 // For implicit implementations, make sure we are public, for
4638 // explicit implementations, make sure we are private.
4640 if (implementing != null){
4642 // Setting null inside this block will trigger a more
4643 // verbose error reporting for missing interface implementations
4645 // The "candidate" function has been flagged already
4646 // but it wont get cleared
4648 if (member.IsExplicitImpl){
4649 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4650 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4651 implementing = null;
4653 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4654 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4656 // If this is an interface method implementation,
4657 // check for public accessibility
4659 implementing = null;
4660 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4661 // We may never be private.
4662 implementing = null;
4663 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4665 // We may be protected if we're overriding something.
4667 implementing = null;
4672 // Static is not allowed
4674 if ((modifiers & Modifiers.STATIC) != 0){
4675 implementing = null;
4680 // If implementing is still valid, set flags
4682 if (implementing != null){
4684 // When implementing interface methods, set NewSlot
4685 // unless, we are overwriting a method.
4687 if (implementing.DeclaringType.IsInterface){
4688 if ((modifiers & Modifiers.OVERRIDE) == 0)
4689 flags |= MethodAttributes.NewSlot;
4692 MethodAttributes.Virtual |
4693 MethodAttributes.HideBySig;
4695 // Set Final unless we're virtual, abstract or already overriding a method.
4696 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4697 flags |= MethodAttributes.Final;
4700 EmitContext ec = method.CreateEmitContext (container, null);
4702 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4704 if (builder == null)
4707 if ((modifiers & Modifiers.UNSAFE) != 0)
4708 builder.InitLocals = false;
4710 if (implementing != null){
4712 // clear the pending implemntation flag
4714 if (member is Indexer) {
4715 container.Pending.ImplementIndexer (
4716 member.InterfaceType, builder, method.ReturnType,
4717 ParameterInfo, member.IsExplicitImpl);
4719 container.Pending.ImplementMethod (
4720 member.InterfaceType, name, method.ReturnType,
4721 ParameterInfo, member.IsExplicitImpl);
4723 if (member.IsExplicitImpl)
4724 container.TypeBuilder.DefineMethodOverride (
4725 builder, implementing);
4729 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4730 TypeManager.AddMethod (builder, method);
4737 /// Create the MethodBuilder for the method
4739 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4741 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4743 if ((modifiers & extern_static) == extern_static) {
4745 if (method.OptAttributes != null) {
4746 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4747 if (dllimport_attribute != null) {
4748 flags |= MethodAttributes.PinvokeImpl;
4749 builder = dllimport_attribute.DefinePInvokeMethod (
4750 ec, container.TypeBuilder, method_name, flags,
4751 method.ReturnType, ParameterTypes);
4757 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4758 // We are more strict than Microsoft and report CS0626 like error
4759 if (method.OptAttributes == null ||
4760 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4761 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",
4762 method.GetSignatureForError ());
4767 builder = container.TypeBuilder.DefineMethod (
4768 method_name, flags, method.CallingConventions,
4769 method.ReturnType, ParameterTypes);
4775 public void Emit (TypeContainer container, Attributable kind)
4778 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4779 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4781 ec = method.CreateEmitContext (container, null);
4783 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
4784 ec.TestObsoleteMethodUsage = false;
4786 Attributes OptAttributes = method.OptAttributes;
4788 if (OptAttributes != null)
4789 OptAttributes.Emit (ec, kind);
4791 if (member is MethodCore)
4792 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
4794 ToplevelBlock block = method.Block;
4796 SourceMethod source = SourceMethod.Create (
4797 container, MethodBuilder, method.Block);
4800 // Handle destructors specially
4802 // FIXME: This code generates buggy code
4804 if (member is Destructor)
4805 EmitDestructor (ec, block);
4807 ec.EmitTopBlock (method, block, ParameterInfo);
4810 source.CloseMethod ();
4813 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4815 ILGenerator ig = ec.ig;
4817 Label finish = ig.DefineLabel ();
4819 block.SetDestructor ();
4821 ig.BeginExceptionBlock ();
4822 ec.ReturnLabel = finish;
4823 ec.HasReturnLabel = true;
4824 ec.EmitTopBlock (method, block, null);
4826 // ig.MarkLabel (finish);
4827 ig.BeginFinallyBlock ();
4829 if (ec.ContainerType.BaseType != null) {
4830 Expression member_lookup = Expression.MemberLookup (
4831 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4832 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4834 if (member_lookup != null){
4835 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4837 ig.Emit (OpCodes.Ldarg_0);
4838 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4842 ig.EndExceptionBlock ();
4843 //ig.MarkLabel (ec.ReturnLabel);
4844 ig.Emit (OpCodes.Ret);
4848 // TODO: Should derive from MethodCore
4849 public class Destructor : Method {
4851 public Destructor (TypeContainer ds, Expression return_type, int mod,
4852 string name, Parameters parameters, Attributes attrs,
4854 : base (ds, return_type, mod, false, new MemberName (name, l),
4858 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4860 if (a.Type == TypeManager.conditional_attribute_type) {
4861 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4862 GetSignatureForError ());
4866 base.ApplyAttributeBuilder (a, cb);
4869 public override string GetSignatureForError ()
4871 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
4876 abstract public class MemberBase : MemberCore {
4877 public Expression Type;
4879 public MethodAttributes flags;
4881 protected readonly int explicit_mod_flags;
4884 // The "short" name of this property / indexer / event. This is the
4885 // name without the explicit interface.
4887 public string ShortName {
4888 get { return MemberName.Name; }
4890 SetMemberName (new MemberName (MemberName.Left, value));
4895 // The type of this property / indexer / event
4898 public Type MemberType {
4900 if (member_type == null && Type != null) {
4901 EmitContext ec = Parent.EmitContext;
4902 bool old_unsafe = ec.InUnsafe;
4903 ec.InUnsafe = InUnsafe;
4904 Type = Type.ResolveAsTypeTerminal (ec, false);
4905 ec.InUnsafe = old_unsafe;
4907 member_type = Type == null ? null : Type.Type;
4914 // Whether this is an interface member.
4916 public bool IsInterface;
4919 // If true, this is an explicit interface implementation
4921 public bool IsExplicitImpl;
4924 // The interface type we are explicitly implementing
4926 public Type InterfaceType = null;
4929 // The constructor is only exposed to our children
4931 protected MemberBase (TypeContainer parent, Expression type, int mod,
4932 int allowed_mod, int def_mod, MemberName name,
4934 : base (parent, name, attrs)
4936 explicit_mod_flags = mod;
4938 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
4939 IsExplicitImpl = (MemberName.Left != null);
4942 protected virtual bool CheckBase ()
4944 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4945 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4949 if ((RootContext.WarningLevel >= 4) &&
4950 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4951 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4952 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4953 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4958 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4962 foreach (Type partype in parameters){
4963 if (partype == TypeManager.void_type) {
4965 1547, Location, "Keyword 'void' cannot " +
4966 "be used in this context");
4970 if (partype.IsPointer){
4973 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4977 if (ds.AsAccessible (partype, ModFlags))
4980 if (this is Indexer)
4981 Report.Error (55, Location,
4982 "Inconsistent accessibility: parameter type `" +
4983 TypeManager.CSharpName (partype) + "' is less " +
4984 "accessible than indexer `" + GetSignatureForError () + "'");
4985 else if ((this is Method) && ((Method) this).IsOperator != null)
4986 Report.Error (57, Location,
4987 "Inconsistent accessibility: parameter type `" +
4988 TypeManager.CSharpName (partype) + "' is less " +
4989 "accessible than operator `" + GetSignatureForError () + "'");
4991 Report.Error (51, Location,
4992 "Inconsistent accessibility: parameter type `" +
4993 TypeManager.CSharpName (partype) + "' is less " +
4994 "accessible than method `" + GetSignatureForError () + "'");
5001 protected virtual bool DoDefine ()
5003 EmitContext ec = Parent.EmitContext;
5005 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5008 throw new InternalErrorException ();
5011 ModFlags = Modifiers.PUBLIC |
5012 Modifiers.ABSTRACT |
5013 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5015 flags = MethodAttributes.Public |
5016 MethodAttributes.Abstract |
5017 MethodAttributes.HideBySig |
5018 MethodAttributes.NewSlot |
5019 MethodAttributes.Virtual;
5021 if (!Parent.MethodModifiersValid (this))
5024 flags = Modifiers.MethodAttr (ModFlags);
5027 if (MemberType == null)
5030 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5031 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5032 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5033 GetSignatureForError (), Parent.GetSignatureForError ());
5037 // verify accessibility
5038 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5039 Report.SymbolRelatedToPreviousError (MemberType);
5040 if (this is Property)
5041 Report.Error (53, Location,
5042 "Inconsistent accessibility: property type `" +
5043 TypeManager.CSharpName (MemberType) + "' is less " +
5044 "accessible than property `" + GetSignatureForError () + "'");
5045 else if (this is Indexer)
5046 Report.Error (54, Location,
5047 "Inconsistent accessibility: indexer return type `" +
5048 TypeManager.CSharpName (MemberType) + "' is less " +
5049 "accessible than indexer `" + GetSignatureForError () + "'");
5050 else if (this is MethodCore) {
5051 if (this is Operator)
5052 Report.Error (56, Location,
5053 "Inconsistent accessibility: return type `" +
5054 TypeManager.CSharpName (MemberType) + "' is less " +
5055 "accessible than operator `" + GetSignatureForError () + "'");
5057 Report.Error (50, Location,
5058 "Inconsistent accessibility: return type `" +
5059 TypeManager.CSharpName (MemberType) + "' is less " +
5060 "accessible than method `" + GetSignatureForError () + "'");
5062 Report.Error (52, Location,
5063 "Inconsistent accessibility: field type `" +
5064 TypeManager.CSharpName (MemberType) + "' is less " +
5065 "accessible than field `" + GetSignatureForError () + "'");
5070 if (MemberType.IsPointer && !UnsafeOK (Parent))
5073 if (IsExplicitImpl) {
5074 Expression expr = MemberName.Left.GetTypeExpression ();
5075 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5079 InterfaceType = texpr.ResolveType (ec);
5081 if (!InterfaceType.IsInterface) {
5082 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5086 if (!Parent.VerifyImplements (this))
5089 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5095 protected bool IsTypePermitted ()
5097 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5098 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5104 protected override bool VerifyClsCompliance(DeclSpace ds)
5106 if (base.VerifyClsCompliance (ds)) {
5110 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5111 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5116 protected override void VerifyObsoleteAttribute()
5118 CheckUsageOfObsoleteAttribute (MemberType);
5123 // Fields and Events both generate FieldBuilders, we use this to share
5124 // their common bits. This is also used to flag usage of the field
5126 abstract public class FieldBase : MemberBase {
5127 public FieldBuilder FieldBuilder;
5128 public Status status;
5131 public enum Status : byte {
5132 HAS_OFFSET = 4 // Used by FieldMember.
5135 static string[] attribute_targets = new string [] { "field" };
5138 /// Symbol with same name in base class/struct
5140 public MemberInfo conflict_symbol;
5143 // The constructor is only exposed to our children
5145 protected FieldBase (TypeContainer parent, Expression type, int mod,
5146 int allowed_mod, MemberName name, object init,
5148 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5154 public override AttributeTargets AttributeTargets {
5156 return AttributeTargets.Field;
5160 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5162 if (a.Type == TypeManager.marshal_as_attr_type) {
5163 UnmanagedMarshal marshal = a.GetMarshal (this);
5164 if (marshal != null) {
5165 FieldBuilder.SetMarshal (marshal);
5170 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5171 a.Error_InvalidSecurityParent ();
5175 FieldBuilder.SetCustomAttribute (cb);
5179 // Whether this field has an initializer.
5181 public bool HasInitializer {
5183 return init != null;
5187 protected readonly Object init;
5190 Expression init_expr;
5191 bool init_expr_initialized = false;
5194 // Resolves and returns the field initializer.
5196 public Expression GetInitializerExpression (EmitContext ec)
5198 if (init_expr_initialized)
5202 if (init is Expression)
5203 e = (Expression) init;
5205 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5207 // TODO: Any reason why we are using parent EC ?
5208 EmitContext parent_ec = Parent.EmitContext;
5210 bool old_is_static = parent_ec.IsStatic;
5211 bool old_is_ctor = parent_ec.IsConstructor;
5212 parent_ec.IsStatic = ec.IsStatic;
5213 parent_ec.IsConstructor = ec.IsConstructor;
5214 parent_ec.IsFieldInitializer = true;
5215 e = e.DoResolve (parent_ec);
5216 parent_ec.IsFieldInitializer = false;
5217 parent_ec.IsStatic = old_is_static;
5218 parent_ec.IsConstructor = old_is_ctor;
5221 init_expr_initialized = true;
5226 protected override bool CheckBase ()
5228 if (!base.CheckBase ())
5235 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5236 if (conflict_symbol == null) {
5237 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5238 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5243 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5244 Report.SymbolRelatedToPreviousError (conflict_symbol);
5245 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5246 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5252 protected virtual bool IsFieldClsCompliant {
5254 if (FieldBuilder == null)
5257 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5261 public override string[] ValidAttributeTargets {
5263 return attribute_targets;
5267 protected override bool VerifyClsCompliance (DeclSpace ds)
5269 if (!base.VerifyClsCompliance (ds))
5272 if (!IsFieldClsCompliant) {
5273 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5279 public void SetAssigned ()
5281 caching_flags |= Flags.IsAssigned;
5285 public abstract class FieldMember: FieldBase
5287 protected FieldMember (TypeContainer parent, Expression type, int mod,
5288 int allowed_mod, MemberName name, object init, Attributes attrs)
5289 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs)
5291 if ((mod & Modifiers.ABSTRACT) != 0)
5292 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5295 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5297 if (a.Type == TypeManager.field_offset_attribute_type)
5299 status |= Status.HAS_OFFSET;
5301 if (!Parent.HasExplicitLayout) {
5302 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5306 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5307 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5313 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5314 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5319 base.ApplyAttributeBuilder (a, cb);
5323 public override bool Define()
5325 EmitContext ec = Parent.EmitContext;
5327 throw new InternalErrorException ("FieldMember.Define called too early");
5329 if (MemberType == null)
5332 if (MemberType == TypeManager.void_type) {
5333 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5340 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5341 Report.Error (52, Location,
5342 "Inconsistent accessibility: field type `" +
5343 TypeManager.CSharpName (MemberType) + "' is less " +
5344 "accessible than field `" + GetSignatureForError () + "'");
5348 if (!IsTypePermitted ())
5351 if (MemberType.IsPointer && !UnsafeOK (Parent))
5357 public override void Emit ()
5359 if (OptAttributes != null) {
5360 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5361 OptAttributes.Emit (ec, this);
5364 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5365 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5372 // Represents header string for documentation comment.
5374 public override string DocCommentHeader {
5375 get { return "F:"; }
5379 interface IFixedBuffer
5381 FieldInfo Element { get; }
5382 Type ElementType { get; }
5385 public class FixedFieldExternal: IFixedBuffer
5387 FieldInfo element_field;
5389 public FixedFieldExternal (FieldInfo fi)
5391 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5394 #region IFixedField Members
5396 public FieldInfo Element {
5398 return element_field;
5402 public Type ElementType {
5404 return element_field.FieldType;
5412 /// Fixed buffer implementation
5414 public class FixedField: FieldMember, IFixedBuffer
5416 public const string FixedElementName = "FixedElementField";
5417 static int GlobalCounter = 0;
5418 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5419 static FieldInfo[] fi;
5421 TypeBuilder fixed_buffer_type;
5422 FieldBuilder element;
5423 Expression size_expr;
5426 const int AllowedModifiers =
5429 Modifiers.PROTECTED |
5430 Modifiers.INTERNAL |
5433 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5434 Expression size_expr, Attributes attrs, Location loc):
5435 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), null, attrs)
5437 if (RootContext.Version == LanguageVersion.ISO_1)
5438 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5440 this.size_expr = size_expr;
5443 public override bool Define()
5446 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5447 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5450 if (Parent.Kind != Kind.Struct) {
5451 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5452 GetSignatureForError ());
5456 if (!base.Define ())
5459 if (!TypeManager.IsPrimitiveType (MemberType)) {
5460 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",
5461 GetSignatureForError ());
5465 Constant c = size_expr.ResolveAsConstant (Parent.EmitContext, this);
5469 IntConstant buffer_size_const = c.ToInt (Location);
5470 if (buffer_size_const == null)
5473 buffer_size = buffer_size_const.Value;
5475 if (buffer_size <= 0) {
5476 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5480 int type_size = Expression.GetTypeSize (MemberType);
5482 if (buffer_size > int.MaxValue / type_size) {
5483 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5484 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5488 buffer_size *= type_size;
5491 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5493 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5494 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5495 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5496 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5498 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5499 TypeManager.RegisterFieldBase (FieldBuilder, this);
5504 public override void Emit()
5507 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5509 object[] fi_val = new object[1];
5510 fi_val [0] = buffer_size;
5512 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5513 ctor_args, fi, fi_val);
5514 fixed_buffer_type.SetCustomAttribute (cab);
5517 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5518 FieldBuilder.SetCustomAttribute (cab);
5523 protected override bool IsFieldClsCompliant {
5529 #region IFixedField Members
5531 public FieldInfo Element {
5537 public Type ElementType {
5547 // The Field class is used to represents class/struct fields during parsing.
5549 public class Field : FieldMember {
5551 // Modifiers allowed in a class declaration
5553 const int AllowedModifiers =
5556 Modifiers.PROTECTED |
5557 Modifiers.INTERNAL |
5560 Modifiers.VOLATILE |
5564 public Field (TypeContainer parent, Expression type, int mod, string name,
5565 Object expr_or_array_init, Attributes attrs, Location loc)
5566 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5567 expr_or_array_init, attrs)
5571 public override bool Define ()
5573 if (!base.Define ())
5576 if (RootContext.WarningLevel > 1){
5577 Type ptype = Parent.TypeBuilder.BaseType;
5579 // ptype is only null for System.Object while compiling corlib.
5581 TypeContainer.FindMembers (
5582 ptype, MemberTypes.Method,
5583 BindingFlags.Public |
5584 BindingFlags.Static | BindingFlags.Instance,
5585 System.Type.FilterName, Name);
5589 if ((ModFlags & Modifiers.VOLATILE) != 0){
5590 if (!MemberType.IsClass){
5591 Type vt = MemberType;
5593 if (TypeManager.IsEnumType (vt))
5594 vt = TypeManager.EnumToUnderlying (MemberType);
5596 if (!((vt == TypeManager.bool_type) ||
5597 (vt == TypeManager.sbyte_type) ||
5598 (vt == TypeManager.byte_type) ||
5599 (vt == TypeManager.short_type) ||
5600 (vt == TypeManager.ushort_type) ||
5601 (vt == TypeManager.int32_type) ||
5602 (vt == TypeManager.uint32_type) ||
5603 (vt == TypeManager.char_type) ||
5604 (vt == TypeManager.float_type) ||
5605 (!vt.IsValueType))){
5606 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5607 GetSignatureForError (), TypeManager.CSharpName (vt));
5612 if ((ModFlags & Modifiers.READONLY) != 0){
5613 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5614 GetSignatureForError ());
5619 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5621 if (Parent.Kind == Kind.Struct &&
5622 ((fa & FieldAttributes.Static) == 0) &&
5623 MemberType == Parent.TypeBuilder &&
5624 !TypeManager.IsBuiltinType (MemberType)){
5625 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5626 "' causes a cycle in the structure layout");
5631 FieldBuilder = Parent.TypeBuilder.DefineField (
5632 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5634 TypeManager.RegisterFieldBase (FieldBuilder, this);
5636 catch (ArgumentException) {
5637 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5644 protected override bool VerifyClsCompliance (DeclSpace ds)
5646 if (!base.VerifyClsCompliance (ds))
5649 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5650 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5658 // `set' and `get' accessors are represented with an Accessor.
5660 public class Accessor : IIteratorContainer {
5662 // Null if the accessor is empty, or a Block if not
5664 public const int AllowedModifiers =
5666 Modifiers.PROTECTED |
5667 Modifiers.INTERNAL |
5670 public ToplevelBlock Block;
5671 public Attributes Attributes;
5672 public Location Location;
5673 public int ModFlags;
5676 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5681 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5684 public void SetYields ()
5690 // Ooouh Martin, templates are missing here.
5691 // When it will be possible move here a lot of child code and template method type.
5692 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5693 protected MethodData method_data;
5694 protected ToplevelBlock block;
5695 protected ListDictionary declarative_security;
5697 // The accessor are created event if they are not wanted.
5698 // But we need them because their names are reserved.
5699 // Field says whether accessor will be emited or not
5700 public readonly bool IsDummy;
5702 protected readonly string prefix;
5704 ReturnParameter return_attributes;
5706 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5707 : base (null, SetupName (prefix, member), null)
5709 this.prefix = prefix;
5713 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5715 : base (null, SetupName (prefix, member),
5716 accessor.Attributes)
5718 this.prefix = prefix;
5719 this.block = accessor.Block;
5722 static MemberName SetupName (string prefix, MemberBase member)
5724 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
5727 public void UpdateName (MemberBase member)
5729 SetMemberName (SetupName (prefix, member));
5732 #region IMethodData Members
5734 public ToplevelBlock Block {
5744 public CallingConventions CallingConventions {
5746 return CallingConventions.Standard;
5750 public bool IsExcluded (EmitContext ec)
5755 public MemberName MethodName {
5761 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5762 public abstract Type[] ParameterTypes { get; }
5763 public abstract Type ReturnType { get; }
5764 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5768 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5770 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5771 a.Type == TypeManager.conditional_attribute_type) {
5772 Report.Error (1667, a.Location,
5773 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5774 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5778 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5779 if (declarative_security == null)
5780 declarative_security = new ListDictionary ();
5781 a.ExtractSecurityPermissionSet (declarative_security);
5785 if (a.Target == AttributeTargets.Method) {
5786 method_data.MethodBuilder.SetCustomAttribute (cb);
5790 if (a.Target == AttributeTargets.ReturnValue) {
5791 if (return_attributes == null)
5792 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5794 return_attributes.ApplyAttributeBuilder (a, cb);
5798 ApplyToExtraTarget (a, cb);
5801 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5803 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5806 public override bool Define()
5808 throw new NotSupportedException ();
5811 public virtual void Emit (TypeContainer container)
5813 EmitMethod (container);
5815 if (declarative_security != null) {
5816 foreach (DictionaryEntry de in declarative_security) {
5817 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5824 protected virtual void EmitMethod (TypeContainer container)
5826 method_data.Emit (container, this);
5829 public override bool IsClsCompliaceRequired(DeclSpace ds)
5834 public bool IsDuplicateImplementation (MethodCore method)
5836 if (!MemberName.Equals (method.MemberName))
5839 Type[] param_types = method.ParameterTypes;
5841 if (param_types.Length != ParameterTypes.Length)
5844 for (int i = 0; i < param_types.Length; i++)
5845 if (param_types [i] != ParameterTypes [i])
5848 Report.SymbolRelatedToPreviousError (method);
5849 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
5853 public override bool IsUsed
5863 public new Location Location {
5865 return base.Location;
5870 // Represents header string for documentation comment.
5872 public override string DocCommentHeader {
5873 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5876 protected override void VerifyObsoleteAttribute()
5883 // Properties and Indexers both generate PropertyBuilders, we use this to share
5884 // their common bits.
5886 abstract public class PropertyBase : MethodCore {
5888 public class GetMethod: PropertyMethod
5890 static string[] attribute_targets = new string [] { "method", "return" };
5892 public GetMethod (MethodCore method):
5893 base (method, "get_")
5897 public GetMethod (MethodCore method, Accessor accessor):
5898 base (method, accessor, "get_")
5902 public override MethodBuilder Define(TypeContainer container)
5904 base.Define (container);
5906 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5908 if (!method_data.Define (container))
5911 return method_data.MethodBuilder;
5914 public override Type ReturnType {
5916 return method.MemberType;
5920 public override string[] ValidAttributeTargets {
5922 return attribute_targets;
5927 public class SetMethod: PropertyMethod {
5929 static string[] attribute_targets = new string [] { "method", "param", "return" };
5930 ImplicitParameter param_attr;
5932 public SetMethod (MethodCore method):
5933 base (method, "set_")
5937 public SetMethod (MethodCore method, Accessor accessor):
5938 base (method, accessor, "set_")
5942 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5944 if (a.Target == AttributeTargets.Parameter) {
5945 if (param_attr == null)
5946 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
5948 param_attr.ApplyAttributeBuilder (a, cb);
5952 base.ApplyAttributeBuilder (a, cb);
5955 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5957 Parameter [] parms = new Parameter [1];
5958 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
5959 Parameters parameters = new Parameters (parms, null);
5961 bool old_unsafe = ec.InUnsafe;
5962 ec.InUnsafe = InUnsafe;
5963 Type [] types = parameters.GetParameterInfo (ec);
5964 ec.InUnsafe = old_unsafe;
5966 return new InternalParameters (types, parameters);
5969 public override MethodBuilder Define (TypeContainer container)
5971 if (container.EmitContext == null)
5972 throw new InternalErrorException ("SetMethod.Define called too early");
5974 base.Define (container);
5976 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5978 if (!method_data.Define (container))
5981 return method_data.MethodBuilder;
5984 public override Type[] ParameterTypes {
5986 return new Type[] { method.MemberType };
5990 public override Type ReturnType {
5992 return TypeManager.void_type;
5996 public override string[] ValidAttributeTargets {
5998 return attribute_targets;
6003 static string[] attribute_targets = new string [] { "property" };
6005 public abstract class PropertyMethod: AbstractPropertyEventMethod
6007 protected readonly MethodCore method;
6008 protected MethodAttributes flags;
6011 public PropertyMethod (MethodCore method, string prefix)
6012 : base (method, prefix)
6014 this.method = method;
6015 Parent = method.Parent;
6018 public PropertyMethod (MethodCore method, Accessor accessor,
6020 : base (method, accessor, prefix)
6022 this.method = method;
6023 Parent = method.Parent;
6024 this.ModFlags = accessor.ModFlags;
6025 yields = accessor.Yields;
6027 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6028 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6032 public override AttributeTargets AttributeTargets {
6034 return AttributeTargets.Method;
6038 public override bool IsClsCompliaceRequired(DeclSpace ds)
6040 return method.IsClsCompliaceRequired (ds);
6043 public InternalParameters ParameterInfo
6046 return method_data.ParameterInfo;
6050 public virtual MethodBuilder Define (TypeContainer container)
6052 if (!method.CheckAbstractAndExtern (block != null))
6056 // Check for custom access modifier
6058 if (ModFlags == 0) {
6059 ModFlags = method.ModFlags;
6060 flags = method.flags;
6062 if (container.Kind == Kind.Interface)
6063 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6064 GetSignatureForError ());
6066 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6067 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6070 CheckModifiers (container, ModFlags);
6071 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6072 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6073 flags = Modifiers.MethodAttr (ModFlags);
6074 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6078 // Setup iterator if we are one
6081 Iterator iterator = new Iterator (this,
6082 Parent, method.ParameterInfo, ModFlags);
6084 if (!iterator.DefineIterator ())
6091 public bool HasCustomAccessModifier
6094 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6098 public override Type[] ParameterTypes {
6100 return TypeManager.NoTypes;
6104 public override EmitContext CreateEmitContext (TypeContainer tc,
6107 return new EmitContext (
6108 tc, method.Parent, method.Location, ig, ReturnType,
6109 method.ModFlags, false);
6112 public override ObsoleteAttribute GetObsoleteAttribute ()
6114 return method.GetObsoleteAttribute (method.Parent);
6117 public override string GetSignatureForError()
6119 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6122 void CheckModifiers (TypeContainer container, int modflags)
6125 int mflags = method.ModFlags & Modifiers.Accessibility;
6127 if ((mflags & Modifiers.PUBLIC) != 0) {
6128 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6130 else if ((mflags & Modifiers.PROTECTED) != 0) {
6131 if ((mflags & Modifiers.INTERNAL) != 0)
6132 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6134 flags |= Modifiers.PRIVATE;
6136 else if ((mflags & Modifiers.INTERNAL) != 0)
6137 flags |= Modifiers.PRIVATE;
6139 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6140 Report.Error (273, Location,
6141 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6142 GetSignatureForError (), method.GetSignatureForError ());
6146 public override bool MarkForDuplicationCheck ()
6148 caching_flags |= Flags.TestMethodDuplication;
6154 public PropertyMethod Get, Set;
6155 public PropertyBuilder PropertyBuilder;
6156 public MethodBuilder GetBuilder, SetBuilder;
6158 protected EmitContext ec;
6160 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6161 int allowed_mod, bool is_iface, MemberName name,
6162 Parameters parameters, Attributes attrs)
6163 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6168 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6170 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6171 a.Error_InvalidSecurityParent ();
6175 PropertyBuilder.SetCustomAttribute (cb);
6178 public override AttributeTargets AttributeTargets {
6180 return AttributeTargets.Property;
6184 public override bool Define ()
6189 if (!IsTypePermitted ())
6195 protected override bool DoDefine ()
6197 if (!base.DoDefine ())
6201 // Accessors modifiers check
6203 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6204 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6205 GetSignatureForError ());
6209 if ((Get.IsDummy || Set.IsDummy)
6210 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6211 Report.Error (276, Location,
6212 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6213 GetSignatureForError ());
6217 if (MemberType.IsAbstract && MemberType.IsSealed) {
6218 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6222 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6226 protected override bool CheckForDuplications ()
6228 ArrayList ar = Parent.Indexers;
6230 int arLen = ar.Count;
6232 for (int i = 0; i < arLen; i++) {
6233 Indexer m = (Indexer) ar [i];
6234 if (IsDuplicateImplementation (m))
6239 ar = Parent.Properties;
6241 int arLen = ar.Count;
6243 for (int i = 0; i < arLen; i++) {
6244 Property m = (Property) ar [i];
6245 if (IsDuplicateImplementation (m))
6253 // TODO: rename to Resolve......
6254 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6256 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6257 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6259 if (base_property == null)
6262 base_ret_type = base_property.PropertyType;
6263 MethodInfo get_accessor = base_property.GetGetMethod (true);
6264 MethodInfo set_accessor = base_property.GetSetMethod (true);
6265 MethodAttributes get_accessor_access, set_accessor_access;
6267 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6268 if (Get != null && !Get.IsDummy && get_accessor == null) {
6269 Report.SymbolRelatedToPreviousError (base_property);
6270 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6273 if (Set != null && !Set.IsDummy && set_accessor == null) {
6274 Report.SymbolRelatedToPreviousError (base_property);
6275 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6280 // Check base class accessors access
6283 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6284 get_accessor_access = set_accessor_access = 0;
6285 if ((ModFlags & Modifiers.NEW) == 0) {
6286 if (get_accessor != null) {
6287 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6288 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6290 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6291 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6294 if (set_accessor != null) {
6295 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6296 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6298 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6299 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6304 // Get the less restrictive access
6306 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6309 public override void Emit ()
6312 // The PropertyBuilder can be null for explicit implementations, in that
6313 // case, we do not actually emit the ".property", so there is nowhere to
6314 // put the attribute
6316 if (PropertyBuilder != null && OptAttributes != null)
6317 OptAttributes.Emit (ec, this);
6329 /// Tests whether accessors are not in collision with some method (CS0111)
6331 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6333 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6336 public override bool IsUsed
6342 return Get.IsUsed | Set.IsUsed;
6346 protected override void SetMemberName (MemberName new_name)
6348 base.SetMemberName (new_name);
6350 Get.UpdateName (this);
6351 Set.UpdateName (this);
6354 public override string[] ValidAttributeTargets {
6356 return attribute_targets;
6361 // Represents header string for documentation comment.
6363 public override string DocCommentHeader {
6364 get { return "P:"; }
6368 public class Property : PropertyBase {
6369 const int AllowedModifiers =
6372 Modifiers.PROTECTED |
6373 Modifiers.INTERNAL |
6377 Modifiers.OVERRIDE |
6378 Modifiers.ABSTRACT |
6381 Modifiers.METHOD_YIELDS |
6384 const int AllowedInterfaceModifiers =
6387 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6388 MemberName name, Attributes attrs, Accessor get_block,
6390 : base (ds, type, mod,
6391 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6392 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6394 if (get_block == null)
6395 Get = new GetMethod (this);
6397 Get = new GetMethod (this, get_block);
6399 if (set_block == null)
6400 Set = new SetMethod (this);
6402 Set = new SetMethod (this, set_block);
6405 public override bool Define ()
6407 if (!base.Define ())
6413 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6416 GetBuilder = Get.Define (Parent);
6417 if (GetBuilder == null)
6422 SetBuilder = Set.Define (Parent);
6423 if (SetBuilder == null)
6426 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6429 // FIXME - PropertyAttributes.HasDefault ?
6431 PropertyAttributes prop_attr = PropertyAttributes.None;
6433 prop_attr |= PropertyAttributes.RTSpecialName |
6434 PropertyAttributes.SpecialName;
6436 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6437 Name, prop_attr, MemberType, null);
6440 PropertyBuilder.SetGetMethod (GetBuilder);
6443 PropertyBuilder.SetSetMethod (SetBuilder);
6445 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6451 /// Gigantic workaround for lameness in SRE follows :
6452 /// This class derives from EventInfo and attempts to basically
6453 /// wrap around the EventBuilder so that FindMembers can quickly
6454 /// return this in it search for members
6456 public class MyEventBuilder : EventInfo {
6459 // We use this to "point" to our Builder which is
6460 // not really a MemberInfo
6462 EventBuilder MyBuilder;
6465 // We "catch" and wrap these methods
6467 MethodInfo raise, remove, add;
6469 EventAttributes attributes;
6470 Type declaring_type, reflected_type, event_type;
6475 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6477 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6479 // And now store the values in our own fields.
6481 declaring_type = type_builder;
6483 reflected_type = type_builder;
6485 attributes = event_attr;
6488 this.event_type = event_type;
6492 // Methods that you have to override. Note that you only need
6493 // to "implement" the variants that take the argument (those are
6494 // the "abstract" methods, the others (GetAddMethod()) are
6497 public override MethodInfo GetAddMethod (bool nonPublic)
6502 public override MethodInfo GetRemoveMethod (bool nonPublic)
6507 public override MethodInfo GetRaiseMethod (bool nonPublic)
6513 // These methods make "MyEventInfo" look like a Builder
6515 public void SetRaiseMethod (MethodBuilder raiseMethod)
6517 raise = raiseMethod;
6518 MyBuilder.SetRaiseMethod (raiseMethod);
6521 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6523 remove = removeMethod;
6524 MyBuilder.SetRemoveOnMethod (removeMethod);
6527 public void SetAddOnMethod (MethodBuilder addMethod)
6530 MyBuilder.SetAddOnMethod (addMethod);
6533 public void SetCustomAttribute (CustomAttributeBuilder cb)
6535 MyBuilder.SetCustomAttribute (cb);
6538 public override object [] GetCustomAttributes (bool inherit)
6540 // FIXME : There's nothing which can be seemingly done here because
6541 // we have no way of getting at the custom attribute objects of the
6546 public override object [] GetCustomAttributes (Type t, bool inherit)
6548 // FIXME : Same here !
6552 public override bool IsDefined (Type t, bool b)
6557 public override EventAttributes Attributes {
6563 public override string Name {
6569 public override Type DeclaringType {
6571 return declaring_type;
6575 public override Type ReflectedType {
6577 return reflected_type;
6581 public Type EventType {
6587 public void SetUsed ()
6589 if (my_event != null) {
6590 my_event.SetAssigned ();
6591 my_event.SetMemberIsUsed ();
6597 /// For case when event is declared like property (with add and remove accessors).
6599 public class EventProperty: Event {
6601 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6603 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6604 bool is_iface, MemberName name, Object init,
6605 Attributes attrs, Accessor add, Accessor remove)
6606 : base (parent, type, mod_flags, is_iface, name, init, attrs)
6608 Add = new AddDelegateMethod (this, add);
6609 Remove = new RemoveDelegateMethod (this, remove);
6611 // For this event syntax we don't report error CS0067
6612 // because it is hard to do it.
6616 public override string[] ValidAttributeTargets {
6618 return attribute_targets;
6624 /// Event is declared like field.
6626 public class EventField: Event {
6628 static string[] attribute_targets = new string [] { "event", "field", "method" };
6629 static string[] attribute_targets_interface = new string[] { "event", "method" };
6631 public EventField (TypeContainer parent, Expression type, int mod_flags,
6632 bool is_iface, MemberName name, Object init,
6634 : base (parent, type, mod_flags, is_iface, name, init, attrs)
6636 Add = new AddDelegateMethod (this);
6637 Remove = new RemoveDelegateMethod (this);
6640 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6642 if (a.Target == AttributeTargets.Field) {
6643 FieldBuilder.SetCustomAttribute (cb);
6647 if (a.Target == AttributeTargets.Method) {
6648 Add.ApplyAttributeBuilder (a, cb);
6649 Remove.ApplyAttributeBuilder (a, cb);
6653 base.ApplyAttributeBuilder (a, cb);
6656 public override string[] ValidAttributeTargets {
6658 return IsInterface ? attribute_targets_interface : attribute_targets;
6663 public abstract class Event : FieldBase {
6665 protected sealed class AddDelegateMethod: DelegateMethod
6668 public AddDelegateMethod (Event method):
6669 base (method, "add_")
6673 public AddDelegateMethod (Event method, Accessor accessor):
6674 base (method, accessor, "add_")
6678 protected override MethodInfo DelegateMethodInfo {
6680 return TypeManager.delegate_combine_delegate_delegate;
6686 protected sealed class RemoveDelegateMethod: DelegateMethod
6688 public RemoveDelegateMethod (Event method):
6689 base (method, "remove_")
6693 public RemoveDelegateMethod (Event method, Accessor accessor):
6694 base (method, accessor, "remove_")
6698 protected override MethodInfo DelegateMethodInfo {
6700 return TypeManager.delegate_remove_delegate_delegate;
6706 public abstract class DelegateMethod: AbstractPropertyEventMethod
6708 protected readonly Event method;
6709 ImplicitParameter param_attr;
6711 static string[] attribute_targets = new string [] { "method", "param", "return" };
6713 public DelegateMethod (Event method, string prefix)
6714 : base (method, prefix)
6716 this.method = method;
6719 public DelegateMethod (Event method, Accessor accessor, string prefix)
6720 : base (method, accessor, prefix)
6722 this.method = method;
6725 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6727 if (a.Target == AttributeTargets.Parameter) {
6728 if (param_attr == null)
6729 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6731 param_attr.ApplyAttributeBuilder (a, cb);
6735 base.ApplyAttributeBuilder (a, cb);
6738 public override AttributeTargets AttributeTargets {
6740 return AttributeTargets.Method;
6744 public override bool IsClsCompliaceRequired(DeclSpace ds)
6746 return method.IsClsCompliaceRequired (ds);
6749 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6751 method_data = new MethodData (method, ip, method.ModFlags,
6752 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6754 if (!method_data.Define (container))
6757 MethodBuilder mb = method_data.MethodBuilder;
6758 mb.DefineParameter (1, ParameterAttributes.None, "value");
6763 protected override void EmitMethod (TypeContainer tc)
6765 if (block != null) {
6766 base.EmitMethod (tc);
6770 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6773 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6774 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6776 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6777 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6778 ig.Emit (OpCodes.Ldsfld, field_info);
6779 ig.Emit (OpCodes.Ldarg_0);
6780 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6781 ig.Emit (OpCodes.Castclass, method.MemberType);
6782 ig.Emit (OpCodes.Stsfld, field_info);
6784 ig.Emit (OpCodes.Ldarg_0);
6785 ig.Emit (OpCodes.Ldarg_0);
6786 ig.Emit (OpCodes.Ldfld, field_info);
6787 ig.Emit (OpCodes.Ldarg_1);
6788 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6789 ig.Emit (OpCodes.Castclass, method.MemberType);
6790 ig.Emit (OpCodes.Stfld, field_info);
6792 ig.Emit (OpCodes.Ret);
6795 protected abstract MethodInfo DelegateMethodInfo { get; }
6797 public override Type[] ParameterTypes {
6799 return new Type[] { method.MemberType };
6803 public override Type ReturnType {
6805 return TypeManager.void_type;
6809 public override EmitContext CreateEmitContext (TypeContainer tc,
6812 return new EmitContext (
6813 tc, method.Parent, Location, ig, ReturnType,
6814 method.ModFlags, false);
6817 public override ObsoleteAttribute GetObsoleteAttribute ()
6819 return method.GetObsoleteAttribute (method.Parent);
6822 public override string[] ValidAttributeTargets {
6824 return attribute_targets;
6830 const int AllowedModifiers =
6833 Modifiers.PROTECTED |
6834 Modifiers.INTERNAL |
6839 Modifiers.OVERRIDE |
6843 const int AllowedInterfaceModifiers =
6846 public DelegateMethod Add, Remove;
6847 public MyEventBuilder EventBuilder;
6848 public MethodBuilder AddBuilder, RemoveBuilder;
6850 public Event (TypeContainer parent, Expression type, int mod_flags,
6851 bool is_iface, MemberName name, Object init, Attributes attrs)
6852 : base (parent, type, mod_flags,
6853 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6856 IsInterface = is_iface;
6859 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6861 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6862 a.Error_InvalidSecurityParent ();
6866 EventBuilder.SetCustomAttribute (cb);
6869 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6871 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6874 public override AttributeTargets AttributeTargets {
6876 return AttributeTargets.Event;
6880 public override bool Define ()
6882 EventAttributes e_attr;
6883 e_attr = EventAttributes.None;
6888 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6889 Report.Error (74, Location, "`" + GetSignatureForError () +
6890 "': abstract event cannot have an initializer");
6894 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6895 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
6899 EmitContext ec = Parent.EmitContext;
6901 throw new InternalErrorException ("Event.Define called too early?");
6902 bool old_unsafe = ec.InUnsafe;
6903 ec.InUnsafe = InUnsafe;
6905 Parameter [] parms = new Parameter [1];
6906 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
6907 Parameters parameters = new Parameters (parms, null);
6908 Type [] types = parameters.GetParameterInfo (ec);
6909 InternalParameters ip = new InternalParameters (types, parameters);
6911 ec.InUnsafe = old_unsafe;
6917 // Now define the accessors
6920 AddBuilder = Add.Define (Parent, ip);
6921 if (AddBuilder == null)
6924 RemoveBuilder = Remove.Define (Parent, ip);
6925 if (RemoveBuilder == null)
6928 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6930 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6931 FieldBuilder = Parent.TypeBuilder.DefineField (
6933 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6934 TypeManager.RegisterPrivateFieldOfEvent (
6935 (EventInfo) EventBuilder, FieldBuilder);
6936 TypeManager.RegisterFieldBase (FieldBuilder, this);
6939 EventBuilder.SetAddOnMethod (AddBuilder);
6940 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6942 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6946 protected override bool CheckBase ()
6948 if (!base.CheckBase ())
6951 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6952 if (!(conflict_symbol is EventInfo)) {
6953 Report.SymbolRelatedToPreviousError (conflict_symbol);
6954 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
6962 public override void Emit ()
6964 if (OptAttributes != null) {
6965 EmitContext ec = new EmitContext (
6966 Parent, Location, null, MemberType, ModFlags);
6967 OptAttributes.Emit (ec, this);
6971 Remove.Emit (Parent);
6976 public override string GetSignatureForError ()
6978 return base.GetSignatureForError ();
6982 // Represents header string for documentation comment.
6984 public override string DocCommentHeader {
6985 get { return "E:"; }
6990 public class Indexer : PropertyBase {
6992 class GetIndexerMethod: GetMethod
6994 public GetIndexerMethod (MethodCore method):
6999 public GetIndexerMethod (MethodCore method, Accessor accessor):
7000 base (method, accessor)
7004 public override Type[] ParameterTypes {
7006 return method.ParameterTypes;
7011 class SetIndexerMethod: SetMethod
7013 readonly Parameters parameters;
7015 public SetIndexerMethod (MethodCore method):
7020 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7021 base (method, accessor)
7023 this.parameters = parameters;
7026 public override Type[] ParameterTypes {
7028 int top = method.ParameterTypes.Length;
7029 Type [] set_pars = new Type [top + 1];
7030 method.ParameterTypes.CopyTo (set_pars, 0);
7031 set_pars [top] = method.MemberType;
7036 protected override InternalParameters GetParameterInfo (EmitContext ec)
7038 Parameter [] fixed_parms = parameters.FixedParameters;
7040 if (fixed_parms == null){
7041 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7042 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7043 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7045 // Here is the problem: the `value' parameter has
7046 // to come *after* the array parameter in the declaration
7048 // X (object [] x, Type value)
7051 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7052 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7056 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7058 fixed_parms.CopyTo (tmp, 0);
7059 tmp [fixed_parms.Length] = new Parameter (
7060 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7062 Parameters set_formal_params = new Parameters (tmp, null);
7063 Type [] types = set_formal_params.GetParameterInfo (ec);
7065 return new InternalParameters (types, set_formal_params);
7070 const int AllowedModifiers =
7073 Modifiers.PROTECTED |
7074 Modifiers.INTERNAL |
7078 Modifiers.OVERRIDE |
7083 const int AllowedInterfaceModifiers =
7087 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7088 bool is_iface, Parameters parameters, Attributes attrs,
7089 Accessor get_block, Accessor set_block)
7090 : base (ds, type, mod,
7091 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7092 is_iface, name, parameters, attrs)
7094 if (get_block == null)
7095 Get = new GetIndexerMethod (this);
7097 Get = new GetIndexerMethod (this, get_block);
7099 if (set_block == null)
7100 Set = new SetIndexerMethod (this);
7102 Set = new SetIndexerMethod (this, parameters, set_block);
7105 public override bool Define ()
7107 PropertyAttributes prop_attr =
7108 PropertyAttributes.RTSpecialName |
7109 PropertyAttributes.SpecialName;
7111 if (!base.Define ())
7114 if (MemberType == TypeManager.void_type) {
7115 Report.Error (620, Location, "Indexers cannot have void type");
7119 if (OptAttributes != null) {
7120 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7121 if (indexer_attr != null) {
7122 // Remove the attribute from the list because it is not emitted
7123 OptAttributes.Attrs.Remove (indexer_attr);
7125 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7127 if (IsExplicitImpl) {
7128 Report.Error (415, indexer_attr.Location,
7129 "The `IndexerName' attribute is valid only on an " +
7130 "indexer that is not an explicit interface member declaration");
7134 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7135 Report.Error (609, indexer_attr.Location,
7136 "Cannot set the `IndexerName' attribute on an indexer marked override");
7140 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7141 Report.Error (633, indexer_attr.Location,
7142 "The argument to the `IndexerName' attribute must be a valid identifier");
7148 if (InterfaceType != null) {
7149 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7150 if (base_IndexerName != Name)
7151 ShortName = base_IndexerName;
7154 if (!Parent.AddToMemberContainer (this) ||
7155 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7161 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7163 GetBuilder = Get.Define (Parent);
7164 if (GetBuilder == null)
7169 SetBuilder = Set.Define (Parent);
7170 if (SetBuilder == null)
7175 // Now name the parameters
7177 Parameter [] p = Parameters.FixedParameters;
7179 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7180 Report.Error (631, Location, "ref and out are not valid in this context");
7186 for (i = 0; i < p.Length; ++i) {
7188 GetBuilder.DefineParameter (
7189 i + 1, p [i].Attributes, p [i].Name);
7192 SetBuilder.DefineParameter (
7193 i + 1, p [i].Attributes, p [i].Name);
7197 SetBuilder.DefineParameter (
7198 i + 1, ParameterAttributes.None, "value");
7200 if (i != ParameterTypes.Length) {
7201 Parameter array_param = Parameters.ArrayParameter;
7203 SetBuilder.DefineParameter (
7204 i + 1, array_param.Attributes, array_param.Name);
7208 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7209 Name, prop_attr, MemberType, ParameterTypes);
7212 PropertyBuilder.SetGetMethod (GetBuilder);
7215 PropertyBuilder.SetSetMethod (SetBuilder);
7217 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7222 public override string GetSignatureForError ()
7224 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7225 if (MemberName.Left != null) {
7227 sb.Append (MemberName.Left);
7230 sb.Append (".this");
7231 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7232 return sb.ToString ();
7235 public override bool MarkForDuplicationCheck ()
7237 caching_flags |= Flags.TestMethodDuplication;
7243 public class Operator : MethodCore, IIteratorContainer {
7245 const int AllowedModifiers =
7251 public enum OpType : byte {
7261 // Unary and Binary operators
7284 // Implicit and Explicit
7288 // Just because of enum
7292 public readonly OpType OperatorType;
7293 public MethodBuilder OperatorMethodBuilder;
7295 public Method OperatorMethod;
7297 static string[] attribute_targets = new string [] { "method", "return" };
7299 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7300 int mod_flags, Parameters parameters,
7301 ToplevelBlock block, Attributes attrs, Location loc)
7302 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7303 new MemberName ("op_" + type, loc), attrs, parameters)
7305 OperatorType = type;
7309 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7311 OperatorMethod.ApplyAttributeBuilder (a, cb);
7314 public override AttributeTargets AttributeTargets {
7316 return AttributeTargets.Method;
7320 protected override bool CheckForDuplications()
7322 ArrayList ar = Parent.Operators;
7324 int arLen = ar.Count;
7326 for (int i = 0; i < arLen; i++) {
7327 Operator o = (Operator) ar [i];
7328 if (IsDuplicateImplementation (o))
7333 ar = Parent.Methods;
7335 int arLen = ar.Count;
7337 for (int i = 0; i < arLen; i++) {
7338 Method m = (Method) ar [i];
7339 if (IsDuplicateImplementation (m))
7347 public override bool Define ()
7349 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7350 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7351 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7358 if (MemberType == TypeManager.void_type) {
7359 Report.Error (590, Location, "User-defined operators cannot return void");
7363 OperatorMethod = new Method (
7364 Parent, Type, ModFlags, false, MemberName,
7365 Parameters, OptAttributes);
7367 OperatorMethod.Block = Block;
7368 OperatorMethod.IsOperator = this;
7369 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7370 OperatorMethod.Define ();
7372 if (OperatorMethod.MethodBuilder == null)
7375 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7377 parameter_types = OperatorMethod.ParameterTypes;
7378 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7379 Type return_type = OperatorMethod.ReturnType;
7380 Type first_arg_type = parameter_types [0];
7385 // Rules for conversion operators
7387 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7388 if (first_arg_type == return_type && first_arg_type == declaring_type){
7389 Report.Error (555, Location,
7390 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7394 if (first_arg_type != declaring_type && return_type != declaring_type){
7397 "User-defined conversion must convert to or from the " +
7402 if (first_arg_type == TypeManager.object_type ||
7403 return_type == TypeManager.object_type){
7406 "User-defined conversion cannot convert to or from " +
7411 if (first_arg_type.IsInterface || return_type.IsInterface){
7412 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7413 GetSignatureForError ());
7417 if (first_arg_type.IsSubclassOf (return_type)
7418 || return_type.IsSubclassOf (first_arg_type)){
7419 if (declaring_type.IsSubclassOf (return_type)) {
7420 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7421 GetSignatureForError ());
7424 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7425 GetSignatureForError ());
7428 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7429 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7430 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");
7433 } else if (Parameters.FixedParameters.Length == 1) {
7434 // Checks for Unary operators
7436 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7437 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7438 Report.Error (448, Location,
7439 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7442 if (first_arg_type != declaring_type) {
7444 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7449 if (first_arg_type != declaring_type){
7452 "The parameter of a unary operator must be the " +
7457 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7458 if (return_type != TypeManager.bool_type){
7461 "The return type of operator True or False " +
7468 // Checks for Binary operators
7470 if (first_arg_type != declaring_type &&
7471 parameter_types [1] != declaring_type){
7474 "One of the parameters of a binary operator must " +
7475 "be the containing type");
7483 public override void Emit ()
7486 // abstract or extern methods have no bodies
7488 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7491 OperatorMethod.Emit ();
7495 // Operator cannot be override
7496 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7501 public static string GetName (OpType ot)
7504 case OpType.LogicalNot:
7506 case OpType.OnesComplement:
7508 case OpType.Increment:
7510 case OpType.Decrement:
7516 case OpType.Addition:
7518 case OpType.Subtraction:
7520 case OpType.UnaryPlus:
7522 case OpType.UnaryNegation:
7524 case OpType.Multiply:
7526 case OpType.Division:
7528 case OpType.Modulus:
7530 case OpType.BitwiseAnd:
7532 case OpType.BitwiseOr:
7534 case OpType.ExclusiveOr:
7536 case OpType.LeftShift:
7538 case OpType.RightShift:
7540 case OpType.Equality:
7542 case OpType.Inequality:
7544 case OpType.GreaterThan:
7546 case OpType.LessThan:
7548 case OpType.GreaterThanOrEqual:
7550 case OpType.LessThanOrEqual:
7552 case OpType.Implicit:
7554 case OpType.Explicit:
7560 public static OpType GetOperatorType (string name)
7562 if (name.StartsWith ("op_")){
7563 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7564 if (Unary.oper_names [i] == name)
7568 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7569 if (Binary.oper_names [i] == name)
7576 public override string GetSignatureForError ()
7578 StringBuilder sb = new StringBuilder ();
7579 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7580 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7583 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7586 sb.Append (Parameters.GetSignatureForError ());
7587 return sb.ToString ();
7590 public override bool MarkForDuplicationCheck ()
7592 caching_flags |= Flags.TestMethodDuplication;
7596 public override string[] ValidAttributeTargets {
7598 return attribute_targets;
7604 // This is used to compare method signatures
7606 struct MethodSignature {
7608 public Type RetType;
7609 public Type [] Parameters;
7612 /// This delegate is used to extract methods which have the
7613 /// same signature as the argument
7615 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7617 public MethodSignature (string name, Type ret_type, Type [] parameters)
7622 if (parameters == null)
7623 Parameters = TypeManager.NoTypes;
7625 Parameters = parameters;
7628 public override string ToString ()
7631 if (Parameters.Length != 0){
7632 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7633 for (int i = 0; i < Parameters.Length; i++){
7634 sb.Append (Parameters [i]);
7635 if (i+1 < Parameters.Length)
7638 pars = sb.ToString ();
7641 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7644 public override int GetHashCode ()
7646 return Name.GetHashCode ();
7649 public override bool Equals (Object o)
7651 MethodSignature other = (MethodSignature) o;
7653 if (other.Name != Name)
7656 if (other.RetType != RetType)
7659 if (Parameters == null){
7660 if (other.Parameters == null)
7665 if (other.Parameters == null)
7668 int c = Parameters.Length;
7669 if (other.Parameters.Length != c)
7672 for (int i = 0; i < c; i++)
7673 if (other.Parameters [i] != Parameters [i])
7679 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7681 MethodSignature sig = (MethodSignature) filter_criteria;
7683 if (m.Name != sig.Name)
7687 MethodInfo mi = m as MethodInfo;
7688 PropertyInfo pi = m as PropertyInfo;
7691 ReturnType = mi.ReturnType;
7692 else if (pi != null)
7693 ReturnType = pi.PropertyType;
7698 // we use sig.RetType == null to mean `do not check the
7699 // method return value.
7701 if (sig.RetType != null)
7702 if (ReturnType != sig.RetType)
7707 args = TypeManager.GetArgumentTypes (mi);
7709 args = TypeManager.GetArgumentTypes (pi);
7710 Type [] sigp = sig.Parameters;
7712 if (args.Length != sigp.Length)
7715 for (int i = args.Length; i > 0; ){
7717 if (args [i] != sigp [i])