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);
873 bool CanElideInitializer (Type field_type, Constant c)
875 if (field_type == c.Type)
877 if (TypeManager.IsValueType (field_type) || TypeManager.HasElementType (field_type))
879 // Reference type with null initializer.
880 return c.Type == TypeManager.null_type;
884 // Emits the instance field initializers
886 public virtual bool EmitFieldInitializers (EmitContext ec)
889 Expression instance_expr;
892 fields = initialized_static_fields;
893 instance_expr = null;
895 fields = initialized_fields;
896 instance_expr = new This (Location.Null).Resolve (ec);
902 foreach (FieldMember f in fields){
903 Expression e = f.GetInitializerExpression (ec);
907 Location l = f.Location;
908 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
909 fe.InstanceExpression = instance_expr;
910 ExpressionStatement a = new Assign (fe, e, l);
912 a = a.ResolveStatement (ec);
916 Constant c = e as Constant;
917 if (c != null && c.IsDefaultValue && CanElideInitializer (f.MemberType, c))
920 a.EmitStatement (ec);
927 // Defines the default constructors
929 protected void DefineDefaultConstructor (bool is_static)
933 // The default constructor is public
934 // If the class is abstract, the default constructor is protected
935 // The default static constructor is private
937 int mods = Modifiers.PUBLIC;
939 mods = Modifiers.STATIC | Modifiers.PRIVATE;
940 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
941 mods = Modifiers.PROTECTED;
943 TypeContainer constructor_parent = this;
945 constructor_parent = (TypeContainer) Parts [0];
947 c = new Constructor (constructor_parent, Basename, mods,
948 Parameters.EmptyReadOnlyParameters,
949 new GeneratedBaseInitializer (Location),
954 c.Block = new ToplevelBlock (null, Location);
959 /// The pending methods that need to be implemented
960 // (interfaces or abstract methods)
962 public PendingImplementation Pending;
964 public abstract PendingImplementation GetPendingImplementations ();
966 TypeExpr[] GetPartialBases (out TypeExpr base_class)
968 ArrayList ifaces = new ArrayList ();
971 Location base_loc = Location.Null;
973 foreach (ClassPart part in parts) {
974 TypeExpr new_base_class;
975 TypeExpr[] new_ifaces;
977 new_ifaces = part.GetClassBases (out new_base_class);
978 if (new_ifaces == null && new_base_class != null)
981 if ((base_class != null) && (new_base_class != null) &&
982 !base_class.Equals (new_base_class)) {
983 Report.Error (263, part.Location,
984 "Partial declarations of `{0}' must " +
985 "not specify different base classes",
988 if (!base_loc.IsNull)
989 Report.LocationOfPreviousError (base_loc);
994 if ((base_class == null) && (new_base_class != null)) {
995 base_class = new_base_class;
996 base_loc = part.Location;
999 if (new_ifaces == null)
1002 foreach (TypeExpr iface in new_ifaces) {
1004 foreach (TypeExpr old_iface in ifaces) {
1005 if (old_iface.Equals (iface)) {
1016 TypeExpr[] retval = new TypeExpr [ifaces.Count];
1017 ifaces.CopyTo (retval, 0);
1021 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1025 int count = Bases.Count;
1026 int start = 0, i, j;
1028 if (Kind == Kind.Class){
1029 TypeExpr name = ResolveBaseTypeExpr (
1030 (Expression) Bases [0], false, Location);
1036 if (!name.IsInterface) {
1037 // base_class could be a class, struct, enum, delegate.
1038 // This is validated in GetClassBases.
1044 TypeExpr [] ifaces = new TypeExpr [count-start];
1046 for (i = start, j = 0; i < count; i++, j++){
1047 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1048 if (resolved == null) {
1052 ifaces [j] = resolved;
1059 /// This function computes the Base class and also the
1060 /// list of interfaces that the class or struct @c implements.
1062 /// The return value is an array (might be null) of
1063 /// interfaces implemented (as Types).
1065 /// The @base_class argument is set to the base object or null
1066 /// if this is `System.Object'.
1068 TypeExpr [] GetClassBases (out TypeExpr base_class)
1075 ifaces = GetPartialBases (out base_class);
1076 else if (Bases == null){
1080 ifaces = GetNormalBases (out base_class);
1085 if ((base_class != null) && (Kind == Kind.Class)){
1087 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1088 Report.Error (1521, base_class.Location, "Invalid base type");
1092 if (base_class.IsSealed){
1093 Report.SymbolRelatedToPreviousError (base_class.Type);
1094 if (base_class.Type.IsAbstract) {
1095 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
1096 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1098 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
1099 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1104 if (!base_class.CanInheritFrom ()){
1105 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
1106 GetSignatureForError (), base_class.GetSignatureForError ());
1110 if (!base_class.AsAccessible (this, ModFlags)) {
1111 Report.SymbolRelatedToPreviousError (base_class.Type);
1112 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
1113 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1117 if (base_class != null)
1118 base_class_name = base_class.Name;
1123 int count = ifaces != null ? ifaces.Length : 0;
1125 for (i = 0; i < count; i++) {
1126 TypeExpr iface = (TypeExpr) ifaces [i];
1128 if (!iface.IsInterface) {
1129 if (Kind != Kind.Class) {
1130 // TODO: location of symbol related ....
1131 Error_TypeInListIsNotInterface (Location, iface.FullName);
1133 else if (base_class != null)
1134 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1135 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1137 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1138 GetSignatureForError (), iface.GetSignatureForError ());
1143 for (int x = 0; x < i; x++) {
1144 if (iface.Equals (ifaces [x])) {
1145 Report.Error (528, Location,
1146 "`{0}' is already listed in " +
1147 "interface list", iface.Name);
1152 if ((Kind == Kind.Interface) &&
1153 !iface.AsAccessible (Parent, ModFlags)) {
1154 Report.Error (61, Location,
1155 "Inconsistent accessibility: base " +
1156 "interface `{0}' is less accessible " +
1157 "than interface `{1}'", iface.Name,
1167 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1169 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1173 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1175 public override TypeBuilder DefineType ()
1180 if (TypeBuilder != null)
1183 TypeAttributes type_attributes = TypeAttr;
1187 if (TypeManager.NamespaceClash (Name, Location)) {
1192 ModuleBuilder builder = CodeGen.Module.Builder;
1193 TypeBuilder = builder.DefineType (
1194 Name, type_attributes, null, null);
1196 TypeBuilder builder = Parent.TypeBuilder;
1197 if (builder == null) {
1202 TypeBuilder = builder.DefineNestedType (
1203 Basename, type_attributes, ptype, null);
1205 } catch (ArgumentException) {
1206 Report.RuntimeMissingSupport (Location, "static classes");
1211 TypeManager.AddUserType (Name, this);
1213 if (Parts != null) {
1215 foreach (ClassPart part in Parts) {
1216 part.TypeBuilder = TypeBuilder;
1218 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1219 part.ec.ContainerType = TypeBuilder;
1223 // Normally, we create the EmitContext here.
1224 // The only exception is if we're an Iterator - in this case,
1225 // we already have the `ec', so we don't want to create a new one.
1228 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1229 ec.ContainerType = TypeBuilder;
1232 iface_exprs = GetClassBases (out base_type);
1233 if (iface_exprs == null && base_type != null) {
1238 if (base_type == null) {
1239 if (Kind == Kind.Class){
1240 if (RootContext.StdLib)
1241 base_type = TypeManager.system_object_expr;
1242 else if (Name != "System.Object")
1243 base_type = TypeManager.system_object_expr;
1244 } else if (Kind == Kind.Struct) {
1246 // If we are compiling our runtime,
1247 // and we are defining ValueType, then our
1248 // base is `System.Object'.
1250 if (!RootContext.StdLib && Name == "System.ValueType")
1251 base_type = TypeManager.system_object_expr;
1253 base_type = TypeManager.system_valuetype_expr;
1257 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1258 throw new Exception ();
1260 // Avoid attributes check when parent is not set
1261 TypeResolveEmitContext.TestObsoleteMethodUsage = false;
1263 if (base_type != null) {
1264 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1265 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1266 ptype = base_type.ResolveType (TypeResolveEmitContext);
1267 if (ptype == null) {
1273 if (!CheckRecursiveDefinition (this)) {
1278 if (ptype != null) {
1279 TypeBuilder.SetParent (ptype);
1282 // Attribute is undefined at the begining of corlib compilation
1283 if (TypeManager.obsolete_attribute_type != null) {
1284 TypeResolveEmitContext.TestObsoleteMethodUsage = GetObsoleteAttribute () == null;
1285 if (ptype != null && TypeResolveEmitContext.TestObsoleteMethodUsage) {
1286 CheckObsoleteType (base_type);
1290 // add interfaces that were not added at type creation
1291 if (iface_exprs != null) {
1292 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1293 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1294 TypeResolveEmitContext.ContainerType = TypeBuilder;
1295 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1296 if (ifaces == null) {
1301 foreach (Type itype in ifaces)
1302 TypeBuilder.AddInterfaceImplementation (itype);
1304 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1307 if (!(this is Iterator))
1308 RootContext.RegisterOrder (this);
1310 if (!DefineNestedTypes ()) {
1318 protected virtual bool DefineNestedTypes ()
1320 if (Interfaces != null) {
1321 foreach (TypeContainer iface in Interfaces)
1322 if (iface.DefineType () == null)
1326 if (Types != null) {
1327 foreach (TypeContainer tc in Types)
1328 if (tc.DefineType () == null)
1332 if (Delegates != null) {
1333 foreach (Delegate d in Delegates)
1334 if (d.DefineType () == null)
1338 if (Enums != null) {
1339 foreach (Enum en in Enums)
1340 if (en.DefineType () == null)
1347 TypeContainer InTransit;
1349 protected bool CheckRecursiveDefinition (TypeContainer tc)
1351 if (InTransit != null) {
1352 Report.SymbolRelatedToPreviousError (this);
1353 if (this is Interface)
1355 529, tc.Location, "Inherited interface `{0}' causes a " +
1356 "cycle in the interface hierarchy of `{1}'",
1357 GetSignatureForError (), tc.GetSignatureForError ());
1360 146, tc.Location, "Circular base class dependency " +
1361 "involving `{0}' and `{1}'",
1362 tc.GetSignatureForError (), GetSignatureForError ());
1368 Type parent = ptype;
1369 if (parent != null) {
1370 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1371 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1375 if (iface_exprs != null) {
1376 foreach (TypeExpr iface in iface_exprs) {
1377 Type itype = iface.Type;
1379 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1380 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1389 public static void Error_KeywordNotAllowed (Location loc)
1391 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1395 /// Populates our TypeBuilder with fields and methods
1397 public override bool DefineMembers (TypeContainer container)
1399 if (members_defined)
1400 return members_defined_ok;
1402 if (!base.DefineMembers (container))
1405 members_defined_ok = DoDefineMembers ();
1406 members_defined = true;
1408 return members_defined_ok;
1411 protected virtual bool DoDefineMembers ()
1414 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1415 if (conflict_symbol == null) {
1416 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1417 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1419 if ((ModFlags & Modifiers.NEW) == 0) {
1420 Report.SymbolRelatedToPreviousError (conflict_symbol);
1421 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1422 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1427 DefineContainerMembers (constants);
1428 DefineContainerMembers (fields);
1430 if ((Kind == Kind.Class) && !(this is ClassPart)){
1431 if ((instance_constructors == null) &&
1432 !(this is StaticClass)) {
1433 if (default_constructor == null)
1434 DefineDefaultConstructor (false);
1437 if (initialized_static_fields != null &&
1438 default_static_constructor == null)
1439 DefineDefaultConstructor (true);
1442 if (Kind == Kind.Struct){
1444 // Structs can not have initialized instance
1447 if (initialized_static_fields != null &&
1448 default_static_constructor == null)
1449 DefineDefaultConstructor (true);
1451 if (initialized_fields != null)
1452 ReportStructInitializedInstanceError ();
1455 Pending = GetPendingImplementations ();
1457 if (parts != null) {
1458 foreach (ClassPart part in parts) {
1459 if (!part.DefineMembers (this))
1465 // Constructors are not in the defined_names array
1467 DefineContainerMembers (instance_constructors);
1469 if (default_static_constructor != null)
1470 default_static_constructor.Define ();
1472 DefineContainerMembers (properties);
1473 DefineContainerMembers (events);
1474 DefineContainerMembers (indexers);
1475 DefineContainerMembers (methods);
1476 DefineContainerMembers (operators);
1477 DefineContainerMembers (enums);
1478 DefineContainerMembers (delegates);
1481 if (!(this is ClassPart))
1482 member_cache = new MemberCache (this);
1485 if (parts != null) {
1486 foreach (ClassPart part in parts)
1487 part.member_cache = member_cache;
1490 if (iterators != null) {
1491 foreach (Iterator iterator in iterators) {
1492 if (iterator.DefineType () == null)
1496 foreach (Iterator iterator in iterators) {
1497 if (!iterator.DefineMembers (this))
1505 void ReportStructInitializedInstanceError ()
1507 foreach (Field f in initialized_fields){
1508 Report.Error (573, Location,
1509 "`{0}': Structs cannot have instance field initializers",
1510 f.GetSignatureForError ());
1514 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1517 mcal.DefineContainerMembers ();
1520 public override bool Define ()
1522 if (parts != null) {
1523 foreach (ClassPart part in parts) {
1524 if (!part.Define ())
1529 if (iterators != null) {
1530 foreach (Iterator iterator in iterators) {
1531 if (!iterator.Define ())
1539 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1541 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1545 /// This function is based by a delegate to the FindMembers routine
1547 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1553 /// This filter is used by FindMembers, and we just keep
1554 /// a global for the filter to `AlwaysAccept'
1556 static MemberFilter accepting_filter;
1559 static TypeContainer ()
1561 accepting_filter = new MemberFilter (AlwaysAccept);
1564 public MethodInfo[] GetMethods ()
1566 ArrayList members = new ArrayList ();
1568 DefineMembers (null);
1570 if (methods != null) {
1571 int len = methods.Count;
1572 for (int i = 0; i < len; i++) {
1573 Method m = (Method) methods [i];
1575 members.Add (m.MethodBuilder);
1579 if (operators != null) {
1580 int len = operators.Count;
1581 for (int i = 0; i < len; i++) {
1582 Operator o = (Operator) operators [i];
1584 members.Add (o.OperatorMethodBuilder);
1588 if (properties != null) {
1589 int len = properties.Count;
1590 for (int i = 0; i < len; i++) {
1591 Property p = (Property) properties [i];
1593 if (p.GetBuilder != null)
1594 members.Add (p.GetBuilder);
1595 if (p.SetBuilder != null)
1596 members.Add (p.SetBuilder);
1600 if (indexers != null) {
1601 int len = indexers.Count;
1602 for (int i = 0; i < len; i++) {
1603 Indexer ix = (Indexer) indexers [i];
1605 if (ix.GetBuilder != null)
1606 members.Add (ix.GetBuilder);
1607 if (ix.SetBuilder != null)
1608 members.Add (ix.SetBuilder);
1612 if (events != null) {
1613 int len = events.Count;
1614 for (int i = 0; i < len; i++) {
1615 Event e = (Event) events [i];
1617 if (e.AddBuilder != null)
1618 members.Add (e.AddBuilder);
1619 if (e.RemoveBuilder != null)
1620 members.Add (e.RemoveBuilder);
1624 MethodInfo[] retMethods = new MethodInfo [members.Count];
1625 members.CopyTo (retMethods, 0);
1629 // Indicated whether container has StructLayout attribute set Explicit
1630 public virtual bool HasExplicitLayout {
1636 public override Type FindNestedType (string name)
1638 ArrayList [] lists = { types, enums, delegates, interfaces };
1640 for (int j = 0; j < lists.Length; ++j) {
1641 ArrayList list = lists [j];
1645 int len = list.Count;
1646 for (int i = 0; i < len; ++i) {
1647 DeclSpace ds = (DeclSpace) list [i];
1648 if (ds.Basename == name) {
1650 return ds.TypeBuilder;
1658 private void FindMembers_NestedTypes (int modflags,
1659 BindingFlags bf, MemberFilter filter, object criteria,
1660 ref ArrayList members)
1662 ArrayList [] lists = { types, enums, delegates, interfaces };
1664 for (int j = 0; j < lists.Length; ++j) {
1665 ArrayList list = lists [j];
1669 int len = list.Count;
1670 for (int i = 0; i < len; i++) {
1671 DeclSpace ds = (DeclSpace) list [i];
1673 if ((ds.ModFlags & modflags) == 0)
1676 TypeBuilder tb = ds.TypeBuilder;
1678 if (!(criteria is string) || ds.Basename.Equals (criteria))
1679 tb = ds.DefineType ();
1682 if (tb != null && (filter (tb, criteria) == true)) {
1683 if (members == null)
1684 members = new ArrayList ();
1693 /// This method returns the members of this type just like Type.FindMembers would
1694 /// Only, we need to use this for types which are _being_ defined because MS'
1695 /// implementation can't take care of that.
1698 // FIXME: return an empty static array instead of null, that cleans up
1699 // some code and is consistent with some coding conventions I just found
1703 // Notice that in various cases we check if our field is non-null,
1704 // something that would normally mean that there was a bug elsewhere.
1706 // The problem happens while we are defining p-invoke methods, as those
1707 // will trigger a FindMembers, but this happens before things are defined
1709 // Since the whole process is a no-op, it is fine to check for null here.
1711 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1712 MemberFilter filter, object criteria)
1714 ArrayList members = null;
1717 if ((bf & BindingFlags.Public) != 0)
1718 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1720 if ((bf & BindingFlags.NonPublic) != 0)
1721 modflags |= Modifiers.PRIVATE;
1723 int static_mask = 0, static_flags = 0;
1724 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1725 case BindingFlags.Static:
1726 static_mask = static_flags = Modifiers.STATIC;
1729 case BindingFlags.Instance:
1730 static_mask = Modifiers.STATIC;
1735 static_mask = static_flags = 0;
1739 Timer.StartTimer (TimerType.TcFindMembers);
1742 filter = accepting_filter;
1744 if ((mt & MemberTypes.Field) != 0) {
1745 if (fields != null) {
1746 int len = fields.Count;
1747 for (int i = 0; i < len; i++) {
1748 FieldMember f = (FieldMember) fields [i];
1750 if ((f.ModFlags & modflags) == 0)
1752 if ((f.ModFlags & static_mask) != static_flags)
1755 FieldBuilder fb = f.FieldBuilder;
1756 if (fb != null && filter (fb, criteria) == true) {
1757 if (members == null)
1758 members = new ArrayList ();
1765 if (constants != null) {
1766 int len = constants.Count;
1767 for (int i = 0; i < len; i++) {
1768 Const con = (Const) constants [i];
1770 if ((con.ModFlags & modflags) == 0)
1772 if ((con.ModFlags & static_mask) != static_flags)
1775 FieldBuilder fb = con.FieldBuilder;
1778 fb = con.FieldBuilder;
1780 if (fb != null && filter (fb, criteria) == true) {
1781 if (members == null)
1782 members = new ArrayList ();
1790 if ((mt & MemberTypes.Method) != 0) {
1791 if (methods != null) {
1792 int len = methods.Count;
1793 for (int i = 0; i < len; i++) {
1794 Method m = (Method) methods [i];
1796 if ((m.ModFlags & modflags) == 0)
1798 if ((m.ModFlags & static_mask) != static_flags)
1801 MethodBuilder mb = m.MethodBuilder;
1803 if (mb != null && filter (mb, criteria) == true) {
1804 if (members == null)
1805 members = new ArrayList ();
1812 if (operators != null) {
1813 int len = operators.Count;
1814 for (int i = 0; i < len; i++) {
1815 Operator o = (Operator) operators [i];
1817 if ((o.ModFlags & modflags) == 0)
1819 if ((o.ModFlags & static_mask) != static_flags)
1822 MethodBuilder ob = o.OperatorMethodBuilder;
1823 if (ob != null && filter (ob, criteria) == true) {
1824 if (members == null)
1825 members = new ArrayList ();
1832 if (properties != null) {
1833 int len = properties.Count;
1834 for (int i = 0; i < len; i++) {
1835 Property p = (Property) properties [i];
1837 if ((p.ModFlags & modflags) == 0)
1839 if ((p.ModFlags & static_mask) != static_flags)
1845 if (b != null && filter (b, criteria) == true) {
1846 if (members == null)
1847 members = new ArrayList ();
1853 if (b != null && filter (b, criteria) == true) {
1854 if (members == null)
1855 members = new ArrayList ();
1862 if (indexers != null) {
1863 int len = indexers.Count;
1864 for (int i = 0; i < len; i++) {
1865 Indexer ix = (Indexer) indexers [i];
1867 if ((ix.ModFlags & modflags) == 0)
1869 if ((ix.ModFlags & static_mask) != static_flags)
1875 if (b != null && filter (b, criteria) == true) {
1876 if (members == null)
1877 members = new ArrayList ();
1883 if (b != null && filter (b, criteria) == true) {
1884 if (members == null)
1885 members = new ArrayList ();
1893 if ((mt & MemberTypes.Event) != 0) {
1894 if (events != null) {
1895 int len = events.Count;
1896 for (int i = 0; i < len; i++) {
1897 Event e = (Event) events [i];
1899 if ((e.ModFlags & modflags) == 0)
1901 if ((e.ModFlags & static_mask) != static_flags)
1904 MemberInfo eb = e.EventBuilder;
1905 if (eb != null && filter (eb, criteria) == true) {
1906 if (members == null)
1907 members = new ArrayList ();
1909 members.Add (e.EventBuilder);
1915 if ((mt & MemberTypes.Property) != 0){
1916 if (properties != null) {
1917 int len = properties.Count;
1918 for (int i = 0; i < len; i++) {
1919 Property p = (Property) properties [i];
1921 if ((p.ModFlags & modflags) == 0)
1923 if ((p.ModFlags & static_mask) != static_flags)
1926 MemberInfo pb = p.PropertyBuilder;
1927 if (pb != null && filter (pb, criteria) == true) {
1928 if (members == null)
1929 members = new ArrayList ();
1931 members.Add (p.PropertyBuilder);
1936 if (indexers != null) {
1937 int len = indexers.Count;
1938 for (int i = 0; i < len; i++) {
1939 Indexer ix = (Indexer) indexers [i];
1941 if ((ix.ModFlags & modflags) == 0)
1943 if ((ix.ModFlags & static_mask) != static_flags)
1946 MemberInfo ib = ix.PropertyBuilder;
1947 if (ib != null && filter (ib, criteria) == true) {
1948 if (members == null)
1949 members = new ArrayList ();
1951 members.Add (ix.PropertyBuilder);
1957 if ((mt & MemberTypes.NestedType) != 0)
1958 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1960 if ((mt & MemberTypes.Constructor) != 0){
1961 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1962 int len = instance_constructors.Count;
1963 for (int i = 0; i < len; i++) {
1964 Constructor c = (Constructor) instance_constructors [i];
1966 ConstructorBuilder cb = c.ConstructorBuilder;
1967 if (cb != null && filter (cb, criteria) == true) {
1968 if (members == null)
1969 members = new ArrayList ();
1976 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1977 ConstructorBuilder cb =
1978 default_static_constructor.ConstructorBuilder;
1980 if (cb != null && filter (cb, criteria) == true) {
1981 if (members == null)
1982 members = new ArrayList ();
1990 // Lookup members in base if requested.
1992 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1993 if (TypeBuilder.BaseType != null) {
1994 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1995 if (list.Count > 0) {
1996 if (members == null)
1997 members = new ArrayList ();
1999 members.AddRange (list);
2002 if (ifaces != null) {
2003 foreach (Type base_type in ifaces) {
2004 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
2006 if (list.Count > 0) {
2007 if (members == null)
2008 members = new ArrayList ();
2009 members.AddRange (list);
2015 Timer.StopTimer (TimerType.TcFindMembers);
2017 if (members == null)
2018 return MemberList.Empty;
2020 return new MemberList (members);
2023 public override MemberCache MemberCache {
2025 return member_cache;
2029 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2030 MemberFilter filter, object criteria)
2032 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2035 return ds.FindMembers (mt, bf, filter, criteria);
2037 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2042 // FindMethods will look for methods not only in the type `t', but in
2043 // any interfaces implemented by the type.
2045 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2046 MemberFilter filter, object criteria)
2052 /// Emits the values for the constants
2054 public void EmitConstants ()
2056 if (constants != null)
2057 foreach (Const con in constants)
2062 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2067 foreach (MemberCore mc in al) {
2068 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2072 Report.Warning (169, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2077 public virtual void VerifyMembers ()
2080 // Check for internal or private fields that were never assigned
2082 if (RootContext.WarningLevel >= 3) {
2083 CheckMemberUsage (properties, "property");
2084 CheckMemberUsage (methods, "method");
2085 CheckMemberUsage (constants, "constant");
2087 if (fields != null){
2088 foreach (FieldMember f in fields) {
2089 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2093 if ((f.caching_flags & Flags.IsAssigned) == 0)
2094 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2097 const int error_code = 414;
2099 const int error_code = 169;
2101 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2102 f.GetSignatureForError ());
2108 // Only report 649 on level 4
2110 if (RootContext.WarningLevel < 4)
2113 if ((f.caching_flags & Flags.IsAssigned) != 0)
2116 Report.Warning (649, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2117 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2124 /// Emits the code, this step is performed after all
2125 /// the types, enumerations, constructors
2127 public void EmitType ()
2129 if (OptAttributes != null)
2130 OptAttributes.Emit (ec, this);
2133 // Structs with no fields need to have at least one byte.
2134 // The right thing would be to set the PackingSize in a DefineType
2135 // but there are no functions that allow interfaces *and* the size to
2139 if (Kind == Kind.Struct && first_nonstatic_field == null){
2140 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2141 FieldAttributes.Private);
2143 if (HasExplicitLayout){
2144 object [] ctor_args = new object [1];
2147 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2148 TypeManager.field_offset_attribute_ctor, ctor_args);
2149 fb.SetCustomAttribute (cba);
2155 if (instance_constructors != null) {
2156 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2157 bool has_compliant_args = false;
2159 foreach (Constructor c in instance_constructors) {
2162 if (has_compliant_args)
2165 has_compliant_args = c.HasCompliantArgs;
2167 if (!has_compliant_args)
2168 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2170 foreach (Constructor c in instance_constructors)
2175 // Can not continue if constants are broken
2177 if (Report.Errors > 0)
2180 if (default_static_constructor != null)
2181 default_static_constructor.Emit ();
2183 if (methods != null)
2184 foreach (Method m in methods)
2187 if (operators != null)
2188 foreach (Operator o in operators)
2191 if (properties != null)
2192 foreach (Property p in properties)
2195 if (indexers != null){
2200 foreach (FieldMember f in fields)
2203 if (events != null){
2204 foreach (Event e in Events)
2208 if (delegates != null) {
2209 foreach (Delegate d in Delegates) {
2214 if (enums != null) {
2215 foreach (Enum e in enums) {
2220 if (parts != null) {
2221 foreach (ClassPart part in parts)
2225 if ((Pending != null) && !(this is ClassPart))
2226 if (Pending.VerifyPendingMethods ())
2229 if (iterators != null)
2230 foreach (Iterator iterator in iterators)
2231 iterator.EmitType ();
2233 // if (types != null)
2234 // foreach (TypeContainer tc in types)
2238 public override void CloseType ()
2240 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2244 caching_flags |= Flags.CloseTypeCreated;
2245 TypeBuilder.CreateType ();
2246 } catch (TypeLoadException){
2248 // This is fine, the code still created the type
2250 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2251 // Console.WriteLine (e.Message);
2253 Console.WriteLine ("In type: " + Name);
2258 foreach (Enum en in Enums)
2262 foreach (TypeContainer tc in Types)
2263 if (tc.Kind == Kind.Struct)
2266 foreach (TypeContainer tc in Types)
2267 if (tc.Kind != Kind.Struct)
2271 if (Delegates != null)
2272 foreach (Delegate d in Delegates)
2275 if (Iterators != null)
2276 foreach (Iterator i in Iterators)
2284 initialized_fields = null;
2285 initialized_static_fields = null;
2294 default_constructor = null;
2295 default_static_constructor = null;
2297 OptAttributes = null;
2300 member_cache = null;
2304 // Performs the validation on a Method's modifiers (properties have
2305 // the same properties).
2307 public bool MethodModifiersValid (MemberCore mc)
2309 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2310 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2311 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2313 int flags = mc.ModFlags;
2316 // At most one of static, virtual or override
2318 if ((flags & Modifiers.STATIC) != 0){
2319 if ((flags & vao) != 0){
2320 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2321 mc.GetSignatureForError ());
2326 if (Kind == Kind.Struct){
2327 if ((flags & va) != 0){
2328 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2333 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2334 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2335 mc.GetSignatureForError ());
2340 // If the declaration includes the abstract modifier, then the
2341 // declaration does not include static, virtual or extern
2343 if ((flags & Modifiers.ABSTRACT) != 0){
2344 if ((flags & Modifiers.EXTERN) != 0){
2346 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2350 if ((flags & Modifiers.SEALED) != 0) {
2351 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2355 if ((flags & Modifiers.VIRTUAL) != 0){
2356 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2360 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2361 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2366 if ((flags & Modifiers.PRIVATE) != 0){
2367 if ((flags & vao) != 0){
2368 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2373 if ((flags & Modifiers.SEALED) != 0){
2374 if ((flags & Modifiers.OVERRIDE) == 0){
2375 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2383 public bool UserDefinedStaticConstructor {
2385 return default_static_constructor != null;
2389 public Constructor DefaultStaticConstructor {
2390 get { return default_static_constructor; }
2393 protected override bool VerifyClsCompliance (DeclSpace ds)
2395 if (!base.VerifyClsCompliance (ds))
2400 Type base_type = TypeBuilder.BaseType;
2401 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2402 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2405 if (!Parent.IsClsCompliaceRequired (ds)) {
2406 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
2407 GetSignatureForError (), Parent.GetSignatureForError ());
2414 /// Checks whether container name is CLS Compliant
2416 void VerifyClsName ()
2418 Hashtable base_members = base_cache == null ?
2420 base_cache.GetPublicMembers ();
2421 Hashtable this_members = new Hashtable ();
2423 foreach (DictionaryEntry entry in defined_names) {
2424 MemberCore mc = (MemberCore)entry.Value;
2425 if (!mc.IsClsCompliaceRequired (mc.Parent))
2428 string name = (string) entry.Key;
2429 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2431 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2432 object found = base_members [lcase];
2433 if (found == null) {
2434 found = this_members [lcase];
2435 if (found == null) {
2436 this_members.Add (lcase, mc);
2441 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2444 if (found is MemberInfo) {
2445 if (basename == ((MemberInfo) found).Name)
2447 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2449 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2451 Report.Error (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2457 /// Performs checks for an explicit interface implementation. First it
2458 /// checks whether the `interface_type' is a base inteface implementation.
2459 /// Then it checks whether `name' exists in the interface type.
2461 public virtual bool VerifyImplements (MemberBase mb)
2463 if (ifaces != null) {
2464 foreach (Type t in ifaces){
2465 if (t == mb.InterfaceType)
2470 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2471 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2480 string IMemberContainer.Name {
2486 Type IMemberContainer.Type {
2492 MemberCache IMemberContainer.MemberCache {
2494 return member_cache;
2498 bool IMemberContainer.IsInterface {
2500 return Kind == Kind.Interface;
2504 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2506 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2510 // Generates xml doc comments (if any), and if required,
2511 // handle warning report.
2513 internal override void GenerateDocComment (DeclSpace ds)
2515 DocUtil.GenerateTypeDocComment (this, ds);
2518 public override string DocCommentHeader {
2519 get { return "T:"; }
2522 public virtual MemberCache BaseCache {
2524 if (base_cache != null)
2526 if (TypeBuilder.BaseType != null)
2527 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2528 if (TypeBuilder.IsInterface)
2529 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2535 public class PartialContainer : TypeContainer {
2537 public readonly Namespace Namespace;
2538 public readonly int OriginalModFlags;
2539 public readonly int AllowedModifiers;
2540 public readonly TypeAttributes DefaultTypeAttributes;
2542 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2543 MemberName member_name, int mod_flags, Kind kind)
2546 if (!CheckModFlags (0, mod_flags, member_name))
2549 PartialContainer pc = RootContext.Tree.GetDecl (member_name) as PartialContainer;
2551 if (pc.Kind != kind) {
2553 261, member_name.Location, "Partial declarations of `{0}' " +
2554 "must be all classes, all structs or " +
2555 "all interfaces", member_name.GetPartialName ());
2559 if (!CheckModFlags (pc.OriginalModFlags, mod_flags, member_name))
2561 pc.ModFlags |= (mod_flags & pc.AllowedModifiers);
2566 if (parent is ClassPart)
2567 parent = ((ClassPart) parent).PartialContainer;
2569 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind);
2571 if (kind == Kind.Interface) {
2572 if (!parent.AddInterface (pc))
2574 } else if (kind == Kind.Class || kind == Kind.Struct) {
2575 if (!parent.AddClassOrStruct (pc))
2578 throw new InvalidOperationException ();
2580 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2584 static bool CheckModFlags (int flags_org, int flags, MemberName member_name)
2586 // Check (abstract|static|sealed) sanity.
2587 int tmp = (flags_org | flags) & (Modifiers.ABSTRACT | Modifiers.SEALED | Modifiers.STATIC);
2588 if ((tmp & Modifiers.ABSTRACT) != 0) {
2589 if ((tmp & (Modifiers.STATIC | Modifiers.SEALED)) != 0) {
2591 418, member_name.Location,
2592 "`{0}': an abstract class cannot be sealed or static", member_name.ToString ());
2595 } else if (tmp == (Modifiers.SEALED | Modifiers.STATIC)) {
2596 Report.Error (441, member_name.Location, "`{0}': a class cannot be both static and sealed", member_name.ToString ());
2604 if (0 != ((flags_org ^ flags) & (0xFFFFFFFF ^ (Modifiers.SEALED | Modifiers.ABSTRACT)))) {
2606 262, member_name.Location, "Partial declarations of `{0}' " +
2607 "have conflicting accessibility modifiers",
2608 member_name.GetPartialName ());
2614 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2615 MemberName name, int mod, Attributes attrs,
2616 Kind kind, Location loc)
2618 PartialContainer pc = Create (ns, parent, name, mod, kind);
2620 // An error occured; create a dummy container, but don't
2622 pc = new PartialContainer (ns.NS, parent, name, mod, kind);
2625 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind);
2630 protected PartialContainer (Namespace ns, TypeContainer parent,
2631 MemberName name, int mod, Kind kind)
2632 : base (null, parent, name, null, kind)
2634 this.Namespace = ns;
2638 AllowedModifiers = Class.AllowedModifiers;
2639 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2643 AllowedModifiers = Struct.AllowedModifiers;
2644 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2647 case Kind.Interface:
2648 AllowedModifiers = Interface.AllowedModifiers;
2649 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2653 throw new InvalidOperationException ();
2657 if (parent.Parent == null)
2658 accmods = Modifiers.INTERNAL;
2660 accmods = Modifiers.PRIVATE;
2662 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2663 this.OriginalModFlags = mod;
2666 public override PendingImplementation GetPendingImplementations ()
2668 return PendingImplementation.GetPendingImplementations (this);
2671 public override bool MarkForDuplicationCheck ()
2676 protected override TypeAttributes TypeAttr {
2678 return base.TypeAttr | DefaultTypeAttributes;
2683 public class ClassPart : TypeContainer, IMemberContainer {
2684 public readonly PartialContainer PartialContainer;
2685 public readonly bool IsPartial;
2687 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2688 int mod, Attributes attrs, Kind kind)
2689 : base (ns, parent, pc.MemberName, attrs, kind)
2691 this.PartialContainer = pc;
2692 this.IsPartial = true;
2695 if (parent == null || parent == RootContext.Tree.Types)
2696 accmods = Modifiers.INTERNAL;
2698 accmods = Modifiers.PRIVATE;
2700 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, pc.MemberName.Location);
2703 public override PendingImplementation GetPendingImplementations ()
2705 return PartialContainer.Pending;
2708 public override bool VerifyImplements (MemberBase mb)
2710 return PartialContainer.VerifyImplements (mb);
2714 public override void RegisterFieldForInitialization (FieldMember field)
2716 PartialContainer.RegisterFieldForInitialization (field);
2719 public override bool EmitFieldInitializers (EmitContext ec)
2721 return PartialContainer.EmitFieldInitializers (ec);
2724 public override Type FindNestedType (string name)
2726 return PartialContainer.FindNestedType (name);
2729 public override MemberCache BaseCache {
2731 return PartialContainer.BaseCache;
2735 public override TypeBuilder DefineType ()
2737 throw new InternalErrorException ("Should not get here");
2742 public abstract class ClassOrStruct : TypeContainer {
2743 bool has_explicit_layout = false;
2744 ListDictionary declarative_security;
2746 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2747 MemberName name, Attributes attrs, Kind kind)
2748 : base (ns, parent, name, attrs, kind)
2752 public override PendingImplementation GetPendingImplementations ()
2754 return PendingImplementation.GetPendingImplementations (this);
2757 public override bool HasExplicitLayout {
2759 return has_explicit_layout;
2763 public override void VerifyMembers ()
2765 base.VerifyMembers ();
2767 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2768 foreach (Event e in events){
2769 if ((e.caching_flags & Flags.IsAssigned) == 0)
2770 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2775 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2777 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2778 if (declarative_security == null)
2779 declarative_security = new ListDictionary ();
2781 a.ExtractSecurityPermissionSet (declarative_security);
2785 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2786 has_explicit_layout = true;
2788 base.ApplyAttributeBuilder (a, cb);
2791 public override void Emit()
2795 if (declarative_security != null) {
2796 foreach (DictionaryEntry de in declarative_security) {
2797 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2804 /// Class handles static classes declaration
2806 public sealed class StaticClass: Class {
2807 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2809 : base (ns, parent, name, mod, attrs)
2811 if (RootContext.Version == LanguageVersion.ISO_1) {
2812 Report.FeatureIsNotStandardized (Location, "static classes");
2816 protected override int AllowedModifiersProp {
2818 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2819 Modifiers.STATIC | Modifiers.UNSAFE;
2823 protected override void DefineContainerMembers (MemberCoreArrayList list)
2828 foreach (MemberCore m in list) {
2829 if (m is Operator) {
2830 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2834 if (m is Destructor) {
2835 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2839 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2840 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
2845 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2849 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2852 if (m is Constructor) {
2853 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2857 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2860 base.DefineContainerMembers (list);
2863 public override TypeBuilder DefineType()
2865 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2866 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2870 TypeBuilder tb = base.DefineType ();
2874 if (ptype != TypeManager.object_type) {
2875 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2879 if (ifaces != null) {
2880 foreach (Type t in ifaces)
2881 Report.SymbolRelatedToPreviousError (t);
2882 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2887 protected override TypeAttributes TypeAttr {
2889 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2894 public class Class : ClassOrStruct {
2895 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2896 public const int AllowedModifiers =
2899 Modifiers.PROTECTED |
2900 Modifiers.INTERNAL |
2902 Modifiers.ABSTRACT |
2906 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2908 : base (ns, parent, name, attrs, Kind.Class)
2910 this.ModFlags = mod;
2913 virtual protected int AllowedModifiersProp {
2915 return AllowedModifiers;
2919 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2921 if (a.Type == TypeManager.attribute_usage_type) {
2922 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2923 TypeBuilder.FullName != "System.Attribute") {
2924 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2928 if (a.Type == TypeManager.conditional_attribute_type &&
2929 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
2930 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2934 if (AttributeTester.IsAttributeExcluded (a.Type))
2937 base.ApplyAttributeBuilder (a, cb);
2940 public const TypeAttributes DefaultTypeAttributes =
2941 TypeAttributes.AutoLayout | TypeAttributes.Class;
2943 public override TypeBuilder DefineType()
2945 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2946 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2950 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2951 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2953 return base.DefineType ();
2956 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2957 /// Valid only for attribute classes.
2958 public bool IsExcluded ()
2960 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2961 return (caching_flags & Flags.Excluded) != 0;
2963 caching_flags &= ~Flags.Excluded_Undetected;
2965 if (OptAttributes == null)
2968 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
2973 foreach (Attribute a in attrs) {
2974 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
2975 if (RootContext.AllDefines.Contains (condition))
2979 caching_flags |= Flags.Excluded;
2984 // FIXME: How do we deal with the user specifying a different
2987 protected override TypeAttributes TypeAttr {
2989 return base.TypeAttr | DefaultTypeAttributes;
2994 public class Struct : ClassOrStruct {
2996 // Modifiers allowed in a struct declaration
2998 public const int AllowedModifiers =
3001 Modifiers.PROTECTED |
3002 Modifiers.INTERNAL |
3006 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
3007 int mod, Attributes attrs)
3008 : base (ns, parent, name, attrs, Kind.Struct)
3012 if (parent.Parent == null)
3013 accmods = Modifiers.INTERNAL;
3015 accmods = Modifiers.PRIVATE;
3017 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3019 this.ModFlags |= Modifiers.SEALED;
3022 public const TypeAttributes DefaultTypeAttributes =
3023 TypeAttributes.SequentialLayout |
3024 TypeAttributes.Sealed |
3025 TypeAttributes.BeforeFieldInit;
3028 // FIXME: Allow the user to specify a different set of attributes
3029 // in some cases (Sealed for example is mandatory for a class,
3030 // but what SequentialLayout can be changed
3032 protected override TypeAttributes TypeAttr {
3034 return base.TypeAttr | DefaultTypeAttributes;
3042 public class Interface : TypeContainer, IMemberContainer {
3045 /// Modifiers allowed in a class declaration
3047 public const int AllowedModifiers =
3050 Modifiers.PROTECTED |
3051 Modifiers.INTERNAL |
3055 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3057 : base (ns, parent, name, attrs, Kind.Interface)
3061 if (parent.Parent == null)
3062 accmods = Modifiers.INTERNAL;
3064 accmods = Modifiers.PRIVATE;
3066 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3069 public override PendingImplementation GetPendingImplementations ()
3074 public const TypeAttributes DefaultTypeAttributes =
3075 TypeAttributes.AutoLayout |
3076 TypeAttributes.Abstract |
3077 TypeAttributes.Interface;
3079 protected override TypeAttributes TypeAttr {
3081 return base.TypeAttr | DefaultTypeAttributes;
3085 protected override bool VerifyClsCompliance (DeclSpace ds)
3087 if (!base.VerifyClsCompliance (ds))
3090 if (ifaces != null) {
3091 foreach (Type t in ifaces) {
3092 if (AttributeTester.IsClsCompliant (t))
3095 Report.SymbolRelatedToPreviousError (t);
3096 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3097 GetSignatureForError (), TypeManager.CSharpName (t));
3105 public abstract class MethodCore : MemberBase {
3106 public readonly Parameters Parameters;
3107 protected ToplevelBlock block;
3110 // Parameters, cached for semantic analysis.
3112 protected InternalParameters parameter_info;
3113 protected Type [] parameter_types;
3115 // Whether this is an operator method.
3116 public Operator IsOperator;
3119 // The method we're overriding if this is an override method.
3121 protected MethodInfo base_method = null;
3123 static string[] attribute_targets = new string [] { "method", "return" };
3125 public MethodCore (TypeContainer parent, Expression type, int mod,
3126 int allowed_mod, bool is_interface, MemberName name,
3127 Attributes attrs, Parameters parameters)
3128 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3131 Parameters = parameters;
3132 IsInterface = is_interface;
3136 // Returns the System.Type array for the parameters of this method
3138 public Type [] ParameterTypes {
3140 return parameter_types;
3144 public InternalParameters ParameterInfo
3147 return parameter_info;
3151 public ToplevelBlock Block {
3161 public void SetYields ()
3163 ModFlags |= Modifiers.METHOD_YIELDS;
3166 protected override bool CheckBase ()
3168 if (!base.CheckBase ())
3171 // Check whether arguments were correct.
3172 if (!DoDefineParameters ())
3175 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3181 // Is null for System.Object while compiling corlib and base interfaces
3182 if (Parent.BaseCache == null) {
3183 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3184 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3189 Type base_ret_type = null;
3190 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3192 // method is override
3193 if (base_method != null) {
3195 if (!CheckMethodAgainstBase ())
3198 if ((ModFlags & Modifiers.NEW) == 0) {
3199 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3200 Report.SymbolRelatedToPreviousError (base_method);
3201 if (this is PropertyBase) {
3202 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3203 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3206 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3207 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3212 if (base_method.IsAbstract && !IsInterface) {
3213 Report.SymbolRelatedToPreviousError (base_method);
3214 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3215 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3220 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3221 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3225 if (RootContext.WarningLevel > 2) {
3226 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3227 Parent.Methods.HasEquals = true;
3228 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3229 Parent.Methods.HasGetHashCode = true;
3232 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3233 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3235 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3236 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3237 Report.SymbolRelatedToPreviousError (base_method);
3238 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3239 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3246 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3247 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3248 if (conflict_symbol != null) {
3249 Report.SymbolRelatedToPreviousError (conflict_symbol);
3250 if (this is PropertyBase)
3251 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3253 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3255 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3259 if (conflict_symbol == null) {
3260 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3261 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3266 if ((ModFlags & Modifiers.NEW) == 0) {
3267 if (this is Method && conflict_symbol is MethodBase)
3270 Report.SymbolRelatedToPreviousError (conflict_symbol);
3271 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3272 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3279 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3280 // that have been defined.
3282 // `name' is the user visible name for reporting errors (this is used to
3283 // provide the right name regarding method names and properties)
3285 bool CheckMethodAgainstBase ()
3289 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3290 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3291 Report.Error (506, Location,
3292 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3293 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3297 // Now we check that the overriden method is not final
3299 if (base_method.IsFinal) {
3300 Report.SymbolRelatedToPreviousError (base_method);
3301 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3302 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3306 // Check that the permissions are not being changed
3308 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3309 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3311 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3312 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3317 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3318 ModFlags |= Modifiers.NEW;
3319 Report.SymbolRelatedToPreviousError (base_method);
3320 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3321 if (RootContext.WarningLevel >= 2)
3322 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));
3324 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3325 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3332 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3334 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3336 // when overriding protected internal, the method can be declared
3337 // protected internal only within the same assembly
3340 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3341 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3343 // assemblies differ - report an error
3347 } else if (thisp != base_classp) {
3349 // same assembly, but other attributes differ - report an error
3354 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3356 // if it's not "protected internal", it must be "protected"
3360 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3362 // protected within the same assembly - an error
3365 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3366 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3368 // protected ok, but other attributes differ - report an error
3374 return (thisp == base_classp);
3378 public bool CheckAbstractAndExtern (bool has_block)
3380 if (Parent.Kind == Kind.Interface)
3384 if ((ModFlags & Modifiers.EXTERN) != 0) {
3385 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3386 GetSignatureForError ());
3390 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3391 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3392 GetSignatureForError ());
3396 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3397 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3398 GetSignatureForError ());
3406 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3408 Report.SymbolRelatedToPreviousError (base_method);
3409 string base_name = TypeManager.GetFullNameSignature (base_method);
3410 string this_name = GetSignatureForError ();
3411 if (suffix != null) {
3412 base_name += suffix;
3413 this_name += suffix;
3416 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3417 this_name, Modifiers.GetDescription (ma), base_name);
3420 protected static string Error722 {
3422 return "`{0}': static types cannot be used as return types";
3427 /// For custom member duplication search in a container
3429 protected abstract bool CheckForDuplications ();
3432 /// Gets base method and its return type
3434 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3436 protected virtual bool DoDefineParameters ()
3438 EmitContext ec = Parent.EmitContext;
3440 throw new InternalErrorException ("DoDefineParameters invoked too early");
3442 bool old_unsafe = ec.InUnsafe;
3443 ec.InUnsafe = InUnsafe;
3444 // Check if arguments were correct
3445 parameter_types = Parameters.GetParameterInfo (ec);
3446 ec.InUnsafe = old_unsafe;
3448 if ((parameter_types == null) ||
3449 !CheckParameters (Parent, parameter_types))
3452 parameter_info = new InternalParameters (parameter_types, Parameters);
3454 Parameter array_param = Parameters.ArrayParameter;
3455 if ((array_param != null) &&
3456 (!array_param.ParameterType.IsArray ||
3457 (array_param.ParameterType.GetArrayRank () != 1))) {
3458 Report.Error (225, Location, "The params parameter must be a single dimensional array");
3465 public override string[] ValidAttributeTargets {
3467 return attribute_targets;
3471 protected override bool VerifyClsCompliance (DeclSpace ds)
3473 if (!base.VerifyClsCompliance (ds)) {
3474 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3475 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3480 if (Parameters.HasArglist) {
3481 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3484 if (!AttributeTester.IsClsCompliant (MemberType)) {
3485 if (this is PropertyBase)
3486 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3487 GetSignatureForError ());
3489 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3490 GetSignatureForError ());
3493 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3498 protected bool IsDuplicateImplementation (MethodCore method)
3500 if (method == this || !(method.MemberName.Equals (MemberName)))
3503 Type[] param_types = method.ParameterTypes;
3504 if (param_types == null && ParameterTypes == null)
3506 if (param_types == null || ParameterTypes == null)
3509 if (param_types.Length != ParameterTypes.Length)
3512 for (int i = 0; i < param_types.Length; i++)
3513 if (param_types [i] != ParameterTypes [i])
3516 // TODO: make operator compatible with MethodCore to avoid this
3517 if (this is Operator && method is Operator) {
3518 if (MemberType != method.MemberType)
3523 // Try to report 663: method only differs on out/ref
3525 ParameterData info = ParameterInfo;
3526 ParameterData other_info = method.ParameterInfo;
3527 for (int i = 0; i < info.Count; i++){
3528 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3529 Report.SymbolRelatedToPreviousError (method);
3530 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3531 GetSignatureForError ());
3536 Report.SymbolRelatedToPreviousError (method);
3537 if (this is Operator && method is Operator)
3538 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3540 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3544 public override bool IsUsed {
3545 get { return IsExplicitImpl || base.IsUsed; }
3549 // Returns a string that represents the signature for this
3550 // member which should be used in XML documentation.
3552 public override string GetDocCommentName (DeclSpace ds)
3554 return DocUtil.GetMethodDocCommentName (this, ds);
3558 // Raised (and passed an XmlElement that contains the comment)
3559 // when GenerateDocComment is writing documentation expectedly.
3561 // FIXME: with a few effort, it could be done with XmlReader,
3562 // that means removal of DOM use.
3564 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3566 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3570 // Represents header string for documentation comment.
3572 public override string DocCommentHeader {
3573 get { return "M:"; }
3578 public class SourceMethod : ISourceMethod
3580 TypeContainer container;
3583 protected SourceMethod (TypeContainer container, MethodBase builder,
3584 ISourceFile file, Location start, Location end)
3586 this.container = container;
3587 this.builder = builder;
3589 CodeGen.SymbolWriter.OpenMethod (
3590 file, this, start.Row, start.Column, end.Row, start.Column);
3593 public string Name {
3594 get { return builder.Name; }
3597 public int NamespaceID {
3598 get { return container.NamespaceEntry.SymbolFileID; }
3603 if (builder is MethodBuilder)
3604 return ((MethodBuilder) builder).GetToken ().Token;
3605 else if (builder is ConstructorBuilder)
3606 return ((ConstructorBuilder) builder).GetToken ().Token;
3608 throw new NotSupportedException ();
3612 public void CloseMethod ()
3614 if (CodeGen.SymbolWriter != null)
3615 CodeGen.SymbolWriter.CloseMethod ();
3618 public static SourceMethod Create (TypeContainer parent,
3619 MethodBase builder, Block block)
3621 if (CodeGen.SymbolWriter == null)
3626 Location start_loc = block.StartLocation;
3627 if (start_loc.IsNull)
3630 Location end_loc = block.EndLocation;
3634 ISourceFile file = start_loc.SourceFile;
3638 return new SourceMethod (
3639 parent, builder, file, start_loc, end_loc);
3643 public class Method : MethodCore, IIteratorContainer, IMethodData {
3644 public MethodBuilder MethodBuilder;
3645 public MethodData MethodData;
3646 ReturnParameter return_attributes;
3647 ListDictionary declarative_security;
3650 /// Modifiers allowed in a class declaration
3652 const int AllowedModifiers =
3655 Modifiers.PROTECTED |
3656 Modifiers.INTERNAL |
3661 Modifiers.OVERRIDE |
3662 Modifiers.ABSTRACT |
3664 Modifiers.METHOD_YIELDS |
3667 const int AllowedInterfaceModifiers =
3668 Modifiers.NEW | Modifiers.UNSAFE;
3671 // return_type can be "null" for VOID values.
3673 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3674 MemberName name, Parameters parameters, Attributes attrs)
3675 : base (ds, return_type, mod,
3676 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3677 is_iface, name, attrs, parameters)
3681 public override AttributeTargets AttributeTargets {
3683 return AttributeTargets.Method;
3687 public override string GetSignatureForError()
3689 if (IsOperator != null)
3690 return IsOperator.GetSignatureForError ();
3692 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3695 void DuplicateEntryPoint (MethodInfo b, Location location)
3699 "Program `" + CodeGen.FileName +
3700 "' has more than one entry point defined: `" +
3701 TypeManager.CSharpSignature(b) + "'");
3704 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3706 if (b.ReturnType != TypeManager.void_type &&
3707 b.ReturnType != TypeManager.int32_type)
3710 if (pinfo.Count == 0)
3713 if (pinfo.Count > 1)
3716 Type t = pinfo.ParameterType(0);
3718 (t.GetArrayRank() == 1) &&
3719 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3720 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3726 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3728 if (a.Target == AttributeTargets.ReturnValue) {
3729 if (return_attributes == null)
3730 return_attributes = new ReturnParameter (MethodBuilder, Location);
3732 return_attributes.ApplyAttributeBuilder (a, cb);
3736 if (a.Type == TypeManager.methodimpl_attr_type &&
3737 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3738 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3741 if (a.Type == TypeManager.dllimport_type) {
3742 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3743 if ((ModFlags & extern_static) != extern_static) {
3744 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3750 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3751 if (declarative_security == null)
3752 declarative_security = new ListDictionary ();
3753 a.ExtractSecurityPermissionSet (declarative_security);
3757 if (a.Type == TypeManager.conditional_attribute_type) {
3758 if (IsOperator != null || IsExplicitImpl) {
3759 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3760 GetSignatureForError ());
3764 if (ReturnType != TypeManager.void_type) {
3765 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
3769 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3770 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
3775 Report.Error (582, Location, "Conditional not valid on interface members");
3779 if (MethodData.implementing != null) {
3780 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
3781 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
3785 for (int i = 0; i < parameter_info.Count; ++i) {
3786 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3787 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
3793 MethodBuilder.SetCustomAttribute (cb);
3796 protected override bool CheckForDuplications ()
3798 ArrayList ar = Parent.Methods;
3800 int arLen = ar.Count;
3802 for (int i = 0; i < arLen; i++) {
3803 Method m = (Method) ar [i];
3804 if (IsDuplicateImplementation (m))
3809 ar = Parent.Properties;
3811 for (int i = 0; i < ar.Count; ++i) {
3812 PropertyBase pb = (PropertyBase) ar [i];
3813 if (pb.AreAccessorsDuplicateImplementation (this))
3818 ar = Parent.Indexers;
3820 for (int i = 0; i < ar.Count; ++i) {
3821 PropertyBase pb = (PropertyBase) ar [i];
3822 if (pb.AreAccessorsDuplicateImplementation (this))
3829 for (int i = 0; i < ar.Count; ++i) {
3830 Event ev = (Event) ar [i];
3831 if (ev.AreAccessorsDuplicateImplementation (this))
3842 public override bool Define ()
3847 if (!CheckAbstractAndExtern (block != null))
3850 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3851 Error1599 (Location, ReturnType);
3858 if (IsOperator != null)
3859 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3861 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3863 if (!MethodData.Define (Parent))
3866 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3867 Name == "Finalize" && !(this is Destructor)) {
3868 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3872 // Setup iterator if we are one
3874 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3875 Iterator iterator = new Iterator (this,
3877 ParameterInfo, ModFlags);
3879 if (!iterator.DefineIterator ())
3883 MethodBuilder = MethodData.MethodBuilder;
3886 // This is used to track the Entry Point,
3888 if (Name == "Main" &&
3889 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3890 (RootContext.MainClass == null ||
3891 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3892 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3893 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3894 md.SetMemberIsUsed ();
3896 if (RootContext.EntryPoint == null) {
3897 RootContext.EntryPoint = MethodBuilder;
3898 RootContext.EntryPointLocation = Location;
3900 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3901 DuplicateEntryPoint (MethodBuilder, Location);
3904 if (RootContext.WarningLevel >= 4)
3905 Report.Warning (28, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3909 if (MemberType.IsAbstract && MemberType.IsSealed) {
3910 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3920 public override void Emit ()
3922 MethodData.Emit (Parent, this);
3925 if (declarative_security != null) {
3926 foreach (DictionaryEntry de in declarative_security) {
3927 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3935 public static void Error1599 (Location loc, Type t)
3937 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
3940 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3942 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3943 container.TypeBuilder, Name, ParameterTypes, false);
3948 base_ret_type = mi.ReturnType;
3952 public override bool MarkForDuplicationCheck ()
3954 caching_flags |= Flags.TestMethodDuplication;
3958 protected override bool VerifyClsCompliance(DeclSpace ds)
3960 if (!base.VerifyClsCompliance (ds))
3963 if (parameter_types.Length > 0) {
3964 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3966 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3972 #region IMethodData Members
3974 public CallingConventions CallingConventions {
3976 CallingConventions cc = Parameters.GetCallingConvention ();
3977 if (Parameters.HasArglist)
3978 block.HasVarargs = true;
3981 if ((ModFlags & Modifiers.STATIC) == 0)
3982 cc |= CallingConventions.HasThis;
3984 // FIXME: How is `ExplicitThis' used in C#?
3990 public Type ReturnType {
3996 public MemberName MethodName {
4002 public new Location Location {
4004 return base.Location;
4008 protected override bool CheckBase() {
4009 if (!base.CheckBase ())
4012 // TODO: Destructor should derive from MethodCore
4013 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4014 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4015 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4022 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4024 EmitContext ec = new EmitContext (
4025 tc, Parent, Location, ig, ReturnType, ModFlags, false);
4027 ec.CurrentIterator = tc as Iterator;
4028 if (ec.CurrentIterator != null)
4029 ec.CurrentAnonymousMethod = ec.CurrentIterator.Host;
4035 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4037 public bool IsExcluded (EmitContext ec)
4039 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4040 return (caching_flags & Flags.Excluded) != 0;
4042 caching_flags &= ~Flags.Excluded_Undetected;
4044 if (base_method == null) {
4045 if (OptAttributes == null)
4048 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4053 foreach (Attribute a in attrs) {
4054 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4055 if (RootContext.AllDefines.Contains (condition))
4059 caching_flags |= Flags.Excluded;
4063 IMethodData md = TypeManager.GetMethod (base_method);
4065 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4066 caching_flags |= Flags.Excluded;
4072 if (md.IsExcluded (ec)) {
4073 caching_flags |= Flags.Excluded;
4082 public abstract class ConstructorInitializer {
4083 ArrayList argument_list;
4084 protected ConstructorInfo base_constructor;
4087 public ConstructorInitializer (ArrayList argument_list, Location loc)
4089 this.argument_list = argument_list;
4093 public ArrayList Arguments {
4095 return argument_list;
4099 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4101 Expression base_constructor_group;
4105 ec.CurrentBlock = block;
4107 if (argument_list != null){
4108 foreach (Argument a in argument_list){
4109 if (!a.Resolve (ec, loc))
4113 ec.CurrentBlock = null;
4115 if (this is ConstructorBaseInitializer) {
4116 if (ec.ContainerType.BaseType == null)
4119 t = ec.ContainerType.BaseType;
4120 if (ec.ContainerType.IsValueType) {
4121 Report.Error (522, loc,
4122 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4126 t = ec.ContainerType;
4128 base_constructor_group = Expression.MemberLookup (
4129 ec, t, ".ctor", MemberTypes.Constructor,
4130 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4133 if (base_constructor_group == null){
4135 base_constructor_group = Expression.MemberLookup (
4136 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4137 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4141 int errors = Report.Errors;
4142 if (base_constructor_group != null)
4143 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4144 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4147 if (base_constructor == null) {
4148 if (errors == Report.Errors)
4149 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4150 argument_list.Count);
4155 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4156 base_constructor = null;
4160 if (base_constructor == caller_builder){
4161 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4168 public virtual void Emit (EmitContext ec)
4170 if (base_constructor != null){
4171 ec.Mark (loc, false);
4173 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4175 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4180 public class ConstructorBaseInitializer : ConstructorInitializer {
4181 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4182 base (argument_list, l)
4187 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4188 public GeneratedBaseInitializer (Location loc):
4193 public override void Emit(EmitContext ec)
4195 bool old = ec.TestObsoleteMethodUsage;
4196 ec.TestObsoleteMethodUsage = false;
4198 ec.TestObsoleteMethodUsage = old;
4202 public class ConstructorThisInitializer : ConstructorInitializer {
4203 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4204 base (argument_list, l)
4209 public class Constructor : MethodCore, IMethodData {
4210 public ConstructorBuilder ConstructorBuilder;
4211 public ConstructorInitializer Initializer;
4212 ListDictionary declarative_security;
4215 // Modifiers allowed for a constructor.
4217 public const int AllowedModifiers =
4219 Modifiers.PROTECTED |
4220 Modifiers.INTERNAL |
4226 bool has_compliant_args = false;
4228 // The spec claims that static is not permitted, but
4229 // my very own code has static constructors.
4231 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4232 ConstructorInitializer init, Location loc)
4233 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name, loc),
4239 public bool HasCompliantArgs {
4241 return has_compliant_args;
4245 public override AttributeTargets AttributeTargets {
4247 return AttributeTargets.Constructor;
4253 // Returns true if this is a default constructor
4255 public bool IsDefault ()
4257 if ((ModFlags & Modifiers.STATIC) != 0)
4258 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4259 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4262 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4263 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4264 (Initializer is ConstructorBaseInitializer) &&
4265 (Initializer.Arguments == null);
4268 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4270 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4271 if (declarative_security == null) {
4272 declarative_security = new ListDictionary ();
4274 a.ExtractSecurityPermissionSet (declarative_security);
4278 ConstructorBuilder.SetCustomAttribute (cb);
4281 protected override bool CheckForDuplications ()
4283 ArrayList ar = Parent.InstanceConstructors;
4285 int arLen = ar.Count;
4287 for (int i = 0; i < arLen; i++) {
4288 Constructor m = (Constructor) ar [i];
4289 if (IsDuplicateImplementation (m))
4296 protected override bool CheckBase ()
4298 // Check whether arguments were correct.
4299 if (!DoDefineParameters ())
4302 // TODO: skip the rest for generated ctor
4303 if ((ModFlags & Modifiers.STATIC) != 0)
4306 if (!CheckForDuplications ())
4309 if (Parent.Kind == Kind.Struct) {
4310 if (ParameterTypes.Length == 0) {
4311 Report.Error (568, Location,
4312 "Structs cannot contain explicit parameterless constructors");
4316 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4317 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4322 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4323 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4330 // Creates the ConstructorBuilder
4332 public override bool Define ()
4334 if (ConstructorBuilder != null)
4337 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4338 MethodAttributes.SpecialName);
4340 if ((ModFlags & Modifiers.STATIC) != 0) {
4341 ca |= MethodAttributes.Static | MethodAttributes.Private;
4343 ca |= MethodAttributes.HideBySig;
4345 if ((ModFlags & Modifiers.PUBLIC) != 0)
4346 ca |= MethodAttributes.Public;
4347 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4348 if ((ModFlags & Modifiers.INTERNAL) != 0)
4349 ca |= MethodAttributes.FamORAssem;
4351 ca |= MethodAttributes.Family;
4352 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4353 ca |= MethodAttributes.Assembly;
4354 else if (IsDefault ())
4355 ca |= MethodAttributes.Public;
4357 ca |= MethodAttributes.Private;
4360 if (!CheckAbstractAndExtern (block != null))
4363 // Check if arguments were correct.
4367 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4368 ca, CallingConventions,
4371 if ((ModFlags & Modifiers.UNSAFE) != 0)
4372 ConstructorBuilder.InitLocals = false;
4374 TypeManager.AddMethod (ConstructorBuilder, this);
4377 // HACK because System.Reflection.Emit is lame
4379 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4387 public override void Emit ()
4389 EmitContext ec = CreateEmitContext (null, null);
4391 // If this is a non-static `struct' constructor and doesn't have any
4392 // initializer, it must initialize all of the struct's fields.
4393 if ((Parent.Kind == Kind.Struct) &&
4394 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4395 Block.AddThisVariable (Parent, Location);
4397 if (block != null) {
4398 if (!block.ResolveMeta (ec, ParameterInfo))
4402 if ((ModFlags & Modifiers.STATIC) == 0){
4403 if (Parent.Kind == Kind.Class && Initializer == null)
4404 Initializer = new GeneratedBaseInitializer (Location);
4408 // Spec mandates that Initializers will not have
4412 if ((Initializer != null) &&
4413 !Initializer.Resolve (ConstructorBuilder, block, ec))
4415 ec.IsStatic = false;
4418 Parameters.LabelParameters (ec, ConstructorBuilder);
4420 SourceMethod source = SourceMethod.Create (
4421 Parent, ConstructorBuilder, block);
4424 // Classes can have base initializers and instance field initializers.
4426 if (Parent.Kind == Kind.Class){
4427 if ((ModFlags & Modifiers.STATIC) == 0){
4430 // If we use a "this (...)" constructor initializer, then
4431 // do not emit field initializers, they are initialized in the other constructor
4433 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4434 Parent.EmitFieldInitializers (ec);
4437 if (Initializer != null) {
4438 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute () != null)
4439 ec.TestObsoleteMethodUsage = false;
4441 Initializer.Emit (ec);
4444 if ((ModFlags & Modifiers.STATIC) != 0)
4445 Parent.EmitFieldInitializers (ec);
4447 if (OptAttributes != null)
4448 OptAttributes.Emit (ec, this);
4450 ec.EmitTopBlock (this, block, ParameterInfo);
4453 source.CloseMethod ();
4457 if (declarative_security != null) {
4458 foreach (DictionaryEntry de in declarative_security) {
4459 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4466 // Is never override
4467 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4472 public override string GetSignatureForError()
4474 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4477 protected override bool VerifyClsCompliance (DeclSpace ds)
4479 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4483 if (parameter_types.Length > 0) {
4484 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4486 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4488 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4489 foreach (Type param in parameter_types) {
4490 if (param.IsArray) {
4496 has_compliant_args = true;
4500 #region IMethodData Members
4502 public System.Reflection.CallingConventions CallingConventions {
4504 CallingConventions cc = Parameters.GetCallingConvention ();
4506 if (Parent.Kind == Kind.Class)
4507 if ((ModFlags & Modifiers.STATIC) == 0)
4508 cc |= CallingConventions.HasThis;
4510 // FIXME: How is `ExplicitThis' used in C#?
4516 public new Location Location {
4518 return base.Location;
4522 public MemberName MethodName {
4528 public Type ReturnType {
4534 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4536 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4537 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4540 public bool IsExcluded(EmitContext ec)
4549 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4551 public interface IMethodData
4553 CallingConventions CallingConventions { get; }
4554 Location Location { get; }
4555 MemberName MethodName { get; }
4556 Type[] ParameterTypes { get; }
4557 Type ReturnType { get; }
4559 Attributes OptAttributes { get; }
4560 ToplevelBlock Block { get; set; }
4562 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4563 ObsoleteAttribute GetObsoleteAttribute ();
4564 string GetSignatureForError ();
4565 bool IsExcluded (EmitContext ec);
4566 bool IsClsCompliaceRequired (DeclSpace ds);
4567 void SetMemberIsUsed ();
4571 // Encapsulates most of the Method's state
4573 public class MethodData {
4575 readonly IMethodData method;
4578 // The return type of this method
4580 public readonly InternalParameters ParameterInfo;
4583 // Are we implementing an interface ?
4585 public MethodInfo implementing;
4590 protected MemberBase member;
4591 protected int modifiers;
4592 protected MethodAttributes flags;
4594 MethodBuilder builder = null;
4595 public MethodBuilder MethodBuilder {
4601 public MethodData (MemberBase member, InternalParameters parameters,
4602 int modifiers, MethodAttributes flags, IMethodData method)
4604 this.member = member;
4605 this.ParameterInfo = parameters;
4606 this.modifiers = modifiers;
4609 this.method = method;
4612 public bool Define (TypeContainer container)
4614 string name = method.MethodName.Name;
4615 string method_name = name;
4617 Type[] ParameterTypes = method.ParameterTypes;
4619 if (container.Pending != null){
4620 if (member is Indexer) // TODO: test it, but it should work without this IF
4621 implementing = container.Pending.IsInterfaceIndexer (
4622 member.InterfaceType, method.ReturnType, ParameterInfo);
4624 implementing = container.Pending.IsInterfaceMethod (
4625 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4627 if (member.InterfaceType != null){
4628 if (implementing == null){
4629 if (member is PropertyBase) {
4630 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4631 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4632 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4635 Report.Error (539, method.Location,
4636 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4637 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4641 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4642 Report.SymbolRelatedToPreviousError (implementing);
4643 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4644 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4647 method_name = member.InterfaceType.FullName + "." + name;
4649 if (implementing != null) {
4650 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4651 if (prop_method != null) {
4652 if (!implementing.IsSpecialName) {
4653 Report.SymbolRelatedToPreviousError (implementing);
4654 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4655 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4658 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4659 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4660 Report.SymbolRelatedToPreviousError (implementing);
4661 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4662 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4671 // For implicit implementations, make sure we are public, for
4672 // explicit implementations, make sure we are private.
4674 if (implementing != null){
4676 // Setting null inside this block will trigger a more
4677 // verbose error reporting for missing interface implementations
4679 // The "candidate" function has been flagged already
4680 // but it wont get cleared
4682 if (member.IsExplicitImpl){
4683 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4684 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4685 implementing = null;
4687 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4688 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4690 // If this is an interface method implementation,
4691 // check for public accessibility
4693 implementing = null;
4694 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4695 // We may never be private.
4696 implementing = null;
4697 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4699 // We may be protected if we're overriding something.
4701 implementing = null;
4706 // Static is not allowed
4708 if ((modifiers & Modifiers.STATIC) != 0){
4709 implementing = null;
4714 // If implementing is still valid, set flags
4716 if (implementing != null){
4718 // When implementing interface methods, set NewSlot
4719 // unless, we are overwriting a method.
4721 if (implementing.DeclaringType.IsInterface){
4722 if ((modifiers & Modifiers.OVERRIDE) == 0)
4723 flags |= MethodAttributes.NewSlot;
4726 MethodAttributes.Virtual |
4727 MethodAttributes.HideBySig;
4729 // Set Final unless we're virtual, abstract or already overriding a method.
4730 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4731 flags |= MethodAttributes.Final;
4734 EmitContext ec = method.CreateEmitContext (container, null);
4736 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4738 if (builder == null)
4741 if ((modifiers & Modifiers.UNSAFE) != 0)
4742 builder.InitLocals = false;
4744 if (implementing != null){
4746 // clear the pending implemntation flag
4748 if (member is Indexer) {
4749 container.Pending.ImplementIndexer (
4750 member.InterfaceType, builder, method.ReturnType,
4751 ParameterInfo, member.IsExplicitImpl);
4753 container.Pending.ImplementMethod (
4754 member.InterfaceType, name, method.ReturnType,
4755 ParameterInfo, member.IsExplicitImpl);
4757 if (member.IsExplicitImpl)
4758 container.TypeBuilder.DefineMethodOverride (
4759 builder, implementing);
4763 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4764 TypeManager.AddMethod (builder, method);
4771 /// Create the MethodBuilder for the method
4773 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4775 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4777 if ((modifiers & extern_static) == extern_static) {
4779 if (method.OptAttributes != null) {
4780 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4781 if (dllimport_attribute != null) {
4782 flags |= MethodAttributes.PinvokeImpl;
4783 builder = dllimport_attribute.DefinePInvokeMethod (
4784 ec, container.TypeBuilder, method_name, flags,
4785 method.ReturnType, ParameterTypes);
4791 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4792 // We are more strict than Microsoft and report CS0626 like error
4793 if (method.OptAttributes == null ||
4794 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4795 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",
4796 method.GetSignatureForError ());
4801 builder = container.TypeBuilder.DefineMethod (
4802 method_name, flags, method.CallingConventions,
4803 method.ReturnType, ParameterTypes);
4809 public void Emit (TypeContainer container, Attributable kind)
4812 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4813 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4815 ec = method.CreateEmitContext (container, null);
4817 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute () != null)
4818 ec.TestObsoleteMethodUsage = false;
4820 Attributes OptAttributes = method.OptAttributes;
4822 if (OptAttributes != null)
4823 OptAttributes.Emit (ec, kind);
4825 if (member is MethodCore)
4826 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
4828 ToplevelBlock block = method.Block;
4830 SourceMethod source = SourceMethod.Create (
4831 container, MethodBuilder, method.Block);
4834 // Handle destructors specially
4836 // FIXME: This code generates buggy code
4838 if (member is Destructor)
4839 EmitDestructor (ec, block);
4841 ec.EmitTopBlock (method, block, ParameterInfo);
4844 source.CloseMethod ();
4847 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4849 ILGenerator ig = ec.ig;
4851 Label finish = ig.DefineLabel ();
4853 block.SetDestructor ();
4855 ig.BeginExceptionBlock ();
4856 ec.ReturnLabel = finish;
4857 ec.HasReturnLabel = true;
4858 ec.EmitTopBlock (method, block, null);
4860 // ig.MarkLabel (finish);
4861 ig.BeginFinallyBlock ();
4863 if (ec.ContainerType.BaseType != null) {
4864 Expression member_lookup = Expression.MemberLookup (
4865 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4866 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4868 if (member_lookup != null){
4869 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4871 ig.Emit (OpCodes.Ldarg_0);
4872 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4876 ig.EndExceptionBlock ();
4877 //ig.MarkLabel (ec.ReturnLabel);
4878 ig.Emit (OpCodes.Ret);
4882 // TODO: Should derive from MethodCore
4883 public class Destructor : Method {
4885 public Destructor (TypeContainer ds, Expression return_type, int mod,
4886 string name, Parameters parameters, Attributes attrs,
4888 : base (ds, return_type, mod, false, new MemberName (name, l),
4892 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4894 if (a.Type == TypeManager.conditional_attribute_type) {
4895 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4896 GetSignatureForError ());
4900 base.ApplyAttributeBuilder (a, cb);
4903 public override string GetSignatureForError ()
4905 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
4910 abstract public class MemberBase : MemberCore {
4911 public Expression Type;
4913 public MethodAttributes flags;
4915 protected readonly int explicit_mod_flags;
4918 // The "short" name of this property / indexer / event. This is the
4919 // name without the explicit interface.
4921 public string ShortName {
4922 get { return MemberName.Name; }
4924 SetMemberName (new MemberName (MemberName.Left, value, Location));
4929 // The type of this property / indexer / event
4932 public Type MemberType {
4934 if (member_type == null && Type != null) {
4935 EmitContext ec = Parent.EmitContext;
4936 bool old_unsafe = ec.InUnsafe;
4937 ec.InUnsafe = InUnsafe;
4938 Type = Type.ResolveAsTypeTerminal (ec, false);
4939 ec.InUnsafe = old_unsafe;
4941 member_type = Type.Type;
4949 // Whether this is an interface member.
4951 public bool IsInterface;
4954 // If true, this is an explicit interface implementation
4956 public bool IsExplicitImpl;
4959 // The interface type we are explicitly implementing
4961 public Type InterfaceType = null;
4964 // The constructor is only exposed to our children
4966 protected MemberBase (TypeContainer parent, Expression type, int mod,
4967 int allowed_mod, int def_mod, MemberName name,
4969 : base (parent, name, attrs)
4971 explicit_mod_flags = mod;
4973 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
4974 IsExplicitImpl = (MemberName.Left != null);
4977 protected virtual bool CheckBase ()
4979 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4980 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4984 if ((RootContext.WarningLevel >= 4) &&
4985 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4986 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4987 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4988 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4993 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4997 foreach (Type partype in parameters){
4998 if (partype == TypeManager.void_type) {
5000 1547, Location, "Keyword 'void' cannot " +
5001 "be used in this context");
5005 if (partype.IsPointer){
5008 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5012 if (ds.AsAccessible (partype, ModFlags))
5015 if (this is Indexer)
5016 Report.Error (55, Location,
5017 "Inconsistent accessibility: parameter type `" +
5018 TypeManager.CSharpName (partype) + "' is less " +
5019 "accessible than indexer `" + GetSignatureForError () + "'");
5020 else if ((this is Method) && ((Method) this).IsOperator != null)
5021 Report.Error (57, Location,
5022 "Inconsistent accessibility: parameter type `" +
5023 TypeManager.CSharpName (partype) + "' is less " +
5024 "accessible than operator `" + GetSignatureForError () + "'");
5026 Report.Error (51, Location,
5027 "Inconsistent accessibility: parameter type `" +
5028 TypeManager.CSharpName (partype) + "' is less " +
5029 "accessible than method `" + GetSignatureForError () + "'");
5036 protected virtual bool DoDefine ()
5038 EmitContext ec = Parent.EmitContext;
5040 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5043 throw new InternalErrorException ();
5046 ModFlags = Modifiers.PUBLIC |
5047 Modifiers.ABSTRACT |
5048 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5050 flags = MethodAttributes.Public |
5051 MethodAttributes.Abstract |
5052 MethodAttributes.HideBySig |
5053 MethodAttributes.NewSlot |
5054 MethodAttributes.Virtual;
5056 if (!Parent.MethodModifiersValid (this))
5059 flags = Modifiers.MethodAttr (ModFlags);
5062 if (MemberType == null)
5065 CheckObsoleteType (Type);
5067 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5068 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5069 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5070 GetSignatureForError (), Parent.GetSignatureForError ());
5074 // verify accessibility
5075 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5076 Report.SymbolRelatedToPreviousError (MemberType);
5077 if (this is Property)
5078 Report.Error (53, Location,
5079 "Inconsistent accessibility: property type `" +
5080 TypeManager.CSharpName (MemberType) + "' is less " +
5081 "accessible than property `" + GetSignatureForError () + "'");
5082 else if (this is Indexer)
5083 Report.Error (54, Location,
5084 "Inconsistent accessibility: indexer return type `" +
5085 TypeManager.CSharpName (MemberType) + "' is less " +
5086 "accessible than indexer `" + GetSignatureForError () + "'");
5087 else if (this is MethodCore) {
5088 if (this is Operator)
5089 Report.Error (56, Location,
5090 "Inconsistent accessibility: return type `" +
5091 TypeManager.CSharpName (MemberType) + "' is less " +
5092 "accessible than operator `" + GetSignatureForError () + "'");
5094 Report.Error (50, Location,
5095 "Inconsistent accessibility: return type `" +
5096 TypeManager.CSharpName (MemberType) + "' is less " +
5097 "accessible than method `" + GetSignatureForError () + "'");
5099 Report.Error (52, Location,
5100 "Inconsistent accessibility: field type `" +
5101 TypeManager.CSharpName (MemberType) + "' is less " +
5102 "accessible than field `" + GetSignatureForError () + "'");
5107 if (MemberType.IsPointer && !UnsafeOK (Parent))
5110 if (IsExplicitImpl) {
5111 Expression expr = MemberName.Left.GetTypeExpression ();
5112 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5116 InterfaceType = texpr.ResolveType (ec);
5118 if (!InterfaceType.IsInterface) {
5119 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5123 if (!Parent.VerifyImplements (this))
5126 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5132 protected bool IsTypePermitted ()
5134 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5135 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5141 protected override bool VerifyClsCompliance(DeclSpace ds)
5143 if (base.VerifyClsCompliance (ds)) {
5147 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5148 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5156 // Fields and Events both generate FieldBuilders, we use this to share
5157 // their common bits. This is also used to flag usage of the field
5159 abstract public class FieldBase : MemberBase {
5160 public FieldBuilder FieldBuilder;
5161 public Status status;
5164 public enum Status : byte {
5165 HAS_OFFSET = 4 // Used by FieldMember.
5168 static string[] attribute_targets = new string [] { "field" };
5171 /// Symbol with same name in base class/struct
5173 public MemberInfo conflict_symbol;
5176 // The constructor is only exposed to our children
5178 protected FieldBase (TypeContainer parent, Expression type, int mod,
5179 int allowed_mod, MemberName name, object init,
5181 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5187 public override AttributeTargets AttributeTargets {
5189 return AttributeTargets.Field;
5193 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5195 if (a.Type == TypeManager.marshal_as_attr_type) {
5196 UnmanagedMarshal marshal = a.GetMarshal (this);
5197 if (marshal != null) {
5198 FieldBuilder.SetMarshal (marshal);
5203 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5204 a.Error_InvalidSecurityParent ();
5208 FieldBuilder.SetCustomAttribute (cb);
5212 // Whether this field has an initializer.
5214 public bool HasInitializer {
5216 return init != null;
5220 protected readonly Object init;
5223 Expression init_expr;
5224 bool init_expr_initialized = false;
5227 // Resolves and returns the field initializer.
5229 public Expression GetInitializerExpression (EmitContext ec)
5231 if (init_expr_initialized)
5235 if (init is Expression)
5236 e = (Expression) init;
5238 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5240 // TODO: Any reason why we are using parent EC ?
5241 EmitContext parent_ec = Parent.EmitContext;
5243 bool old_is_static = parent_ec.IsStatic;
5244 bool old_is_ctor = parent_ec.IsConstructor;
5245 parent_ec.IsStatic = ec.IsStatic;
5246 parent_ec.IsConstructor = ec.IsConstructor;
5247 parent_ec.IsFieldInitializer = true;
5248 e = e.DoResolve (parent_ec);
5249 parent_ec.IsFieldInitializer = false;
5250 parent_ec.IsStatic = old_is_static;
5251 parent_ec.IsConstructor = old_is_ctor;
5254 init_expr_initialized = true;
5259 protected override bool CheckBase ()
5261 if (!base.CheckBase ())
5268 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5269 if (conflict_symbol == null) {
5270 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5271 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5276 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5277 Report.SymbolRelatedToPreviousError (conflict_symbol);
5278 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5279 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5285 protected virtual bool IsFieldClsCompliant {
5287 if (FieldBuilder == null)
5290 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5294 public override string[] ValidAttributeTargets {
5296 return attribute_targets;
5300 protected override bool VerifyClsCompliance (DeclSpace ds)
5302 if (!base.VerifyClsCompliance (ds))
5305 if (!IsFieldClsCompliant) {
5306 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5312 public void SetAssigned ()
5314 caching_flags |= Flags.IsAssigned;
5318 public abstract class FieldMember: FieldBase
5320 protected FieldMember (TypeContainer parent, Expression type, int mod,
5321 int allowed_mod, MemberName name, object init, Attributes attrs)
5322 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs)
5324 if ((mod & Modifiers.ABSTRACT) != 0)
5325 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5328 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5330 if (a.Type == TypeManager.field_offset_attribute_type)
5332 status |= Status.HAS_OFFSET;
5334 if (!Parent.HasExplicitLayout) {
5335 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5339 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5340 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5346 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5347 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5352 base.ApplyAttributeBuilder (a, cb);
5356 public override bool Define()
5358 EmitContext ec = Parent.EmitContext;
5360 throw new InternalErrorException ("FieldMember.Define called too early");
5362 if (MemberType == null || Type == null)
5365 CheckObsoleteType (Type);
5367 if (MemberType == TypeManager.void_type) {
5368 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5375 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5376 Report.Error (52, Location,
5377 "Inconsistent accessibility: field type `" +
5378 TypeManager.CSharpName (MemberType) + "' is less " +
5379 "accessible than field `" + GetSignatureForError () + "'");
5383 if (!IsTypePermitted ())
5386 if (MemberType.IsPointer && !UnsafeOK (Parent))
5392 public override void Emit ()
5394 if (OptAttributes != null) {
5395 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5396 OptAttributes.Emit (ec, this);
5399 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5400 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5407 // Represents header string for documentation comment.
5409 public override string DocCommentHeader {
5410 get { return "F:"; }
5414 interface IFixedBuffer
5416 FieldInfo Element { get; }
5417 Type ElementType { get; }
5420 public class FixedFieldExternal: IFixedBuffer
5422 FieldInfo element_field;
5424 public FixedFieldExternal (FieldInfo fi)
5426 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5429 #region IFixedField Members
5431 public FieldInfo Element {
5433 return element_field;
5437 public Type ElementType {
5439 return element_field.FieldType;
5447 /// Fixed buffer implementation
5449 public class FixedField: FieldMember, IFixedBuffer
5451 public const string FixedElementName = "FixedElementField";
5452 static int GlobalCounter = 0;
5453 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5454 static FieldInfo[] fi;
5456 TypeBuilder fixed_buffer_type;
5457 FieldBuilder element;
5458 Expression size_expr;
5461 const int AllowedModifiers =
5464 Modifiers.PROTECTED |
5465 Modifiers.INTERNAL |
5468 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5469 Expression size_expr, Attributes attrs, Location loc):
5470 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), null, attrs)
5472 if (RootContext.Version == LanguageVersion.ISO_1)
5473 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5475 this.size_expr = size_expr;
5478 public override bool Define()
5481 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5482 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5485 if (Parent.Kind != Kind.Struct) {
5486 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5487 GetSignatureForError ());
5491 if (!base.Define ())
5494 if (!TypeManager.IsPrimitiveType (MemberType)) {
5495 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",
5496 GetSignatureForError ());
5500 Constant c = size_expr.ResolveAsConstant (Parent.EmitContext, this);
5504 IntConstant buffer_size_const = c.ToInt (Location);
5505 if (buffer_size_const == null)
5508 buffer_size = buffer_size_const.Value;
5510 if (buffer_size <= 0) {
5511 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5515 int type_size = Expression.GetTypeSize (MemberType);
5517 if (buffer_size > int.MaxValue / type_size) {
5518 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5519 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5523 buffer_size *= type_size;
5526 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5528 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5529 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5530 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5531 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5533 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5534 TypeManager.RegisterFieldBase (FieldBuilder, this);
5539 public override void Emit()
5542 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5544 object[] fi_val = new object[1];
5545 fi_val [0] = buffer_size;
5547 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5548 ctor_args, fi, fi_val);
5549 fixed_buffer_type.SetCustomAttribute (cab);
5552 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5553 FieldBuilder.SetCustomAttribute (cab);
5558 protected override bool IsFieldClsCompliant {
5564 #region IFixedField Members
5566 public FieldInfo Element {
5572 public Type ElementType {
5582 // The Field class is used to represents class/struct fields during parsing.
5584 public class Field : FieldMember {
5586 // Modifiers allowed in a class declaration
5588 const int AllowedModifiers =
5591 Modifiers.PROTECTED |
5592 Modifiers.INTERNAL |
5595 Modifiers.VOLATILE |
5599 public Field (TypeContainer parent, Expression type, int mod, string name,
5600 Object expr_or_array_init, Attributes attrs, Location loc)
5601 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5602 expr_or_array_init, attrs)
5606 public override bool Define ()
5608 if (!base.Define ())
5611 if (RootContext.WarningLevel > 1){
5612 Type ptype = Parent.TypeBuilder.BaseType;
5614 // ptype is only null for System.Object while compiling corlib.
5616 TypeContainer.FindMembers (
5617 ptype, MemberTypes.Method,
5618 BindingFlags.Public |
5619 BindingFlags.Static | BindingFlags.Instance,
5620 System.Type.FilterName, Name);
5624 if ((ModFlags & Modifiers.VOLATILE) != 0){
5625 if (!MemberType.IsClass){
5626 Type vt = MemberType;
5628 if (TypeManager.IsEnumType (vt))
5629 vt = TypeManager.EnumToUnderlying (MemberType);
5631 if (!((vt == TypeManager.bool_type) ||
5632 (vt == TypeManager.sbyte_type) ||
5633 (vt == TypeManager.byte_type) ||
5634 (vt == TypeManager.short_type) ||
5635 (vt == TypeManager.ushort_type) ||
5636 (vt == TypeManager.int32_type) ||
5637 (vt == TypeManager.uint32_type) ||
5638 (vt == TypeManager.char_type) ||
5639 (vt == TypeManager.float_type) ||
5640 (!vt.IsValueType))){
5641 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5642 GetSignatureForError (), TypeManager.CSharpName (vt));
5647 if ((ModFlags & Modifiers.READONLY) != 0){
5648 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5649 GetSignatureForError ());
5654 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5656 if (Parent.Kind == Kind.Struct &&
5657 ((fa & FieldAttributes.Static) == 0) &&
5658 MemberType == Parent.TypeBuilder &&
5659 !TypeManager.IsBuiltinType (MemberType)){
5660 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5661 "' causes a cycle in the structure layout");
5666 FieldBuilder = Parent.TypeBuilder.DefineField (
5667 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5669 TypeManager.RegisterFieldBase (FieldBuilder, this);
5671 catch (ArgumentException) {
5672 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5679 protected override bool VerifyClsCompliance (DeclSpace ds)
5681 if (!base.VerifyClsCompliance (ds))
5684 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5685 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5693 // `set' and `get' accessors are represented with an Accessor.
5695 public class Accessor : IIteratorContainer {
5697 // Null if the accessor is empty, or a Block if not
5699 public const int AllowedModifiers =
5701 Modifiers.PROTECTED |
5702 Modifiers.INTERNAL |
5705 public ToplevelBlock Block;
5706 public Attributes Attributes;
5707 public Location Location;
5708 public int ModFlags;
5711 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5716 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5719 public void SetYields ()
5725 // Ooouh Martin, templates are missing here.
5726 // When it will be possible move here a lot of child code and template method type.
5727 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5728 protected MethodData method_data;
5729 protected ToplevelBlock block;
5730 protected ListDictionary declarative_security;
5732 // The accessor are created event if they are not wanted.
5733 // But we need them because their names are reserved.
5734 // Field says whether accessor will be emited or not
5735 public readonly bool IsDummy;
5737 protected readonly string prefix;
5739 ReturnParameter return_attributes;
5741 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5742 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5744 this.prefix = prefix;
5748 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5750 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5751 accessor.Attributes)
5753 this.prefix = prefix;
5754 this.block = accessor.Block;
5757 static MemberName SetupName (string prefix, MemberBase member, Location loc)
5759 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5762 public void UpdateName (MemberBase member)
5764 SetMemberName (SetupName (prefix, member, Location));
5767 #region IMethodData Members
5769 public ToplevelBlock Block {
5779 public CallingConventions CallingConventions {
5781 return CallingConventions.Standard;
5785 public bool IsExcluded (EmitContext ec)
5790 public MemberName MethodName {
5796 public abstract Type[] ParameterTypes { get; }
5797 public abstract Type ReturnType { get; }
5798 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5802 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5804 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5805 a.Type == TypeManager.conditional_attribute_type) {
5806 Report.Error (1667, a.Location,
5807 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5808 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5812 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5813 if (declarative_security == null)
5814 declarative_security = new ListDictionary ();
5815 a.ExtractSecurityPermissionSet (declarative_security);
5819 if (a.Target == AttributeTargets.Method) {
5820 method_data.MethodBuilder.SetCustomAttribute (cb);
5824 if (a.Target == AttributeTargets.ReturnValue) {
5825 if (return_attributes == null)
5826 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5828 return_attributes.ApplyAttributeBuilder (a, cb);
5832 ApplyToExtraTarget (a, cb);
5835 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5837 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5840 public override bool Define()
5842 throw new NotSupportedException ();
5845 public virtual void Emit (TypeContainer container)
5847 EmitMethod (container);
5849 if (declarative_security != null) {
5850 foreach (DictionaryEntry de in declarative_security) {
5851 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5858 protected virtual void EmitMethod (TypeContainer container)
5860 method_data.Emit (container, this);
5863 public override bool IsClsCompliaceRequired(DeclSpace ds)
5868 public bool IsDuplicateImplementation (MethodCore method)
5870 if (!MemberName.Equals (method.MemberName))
5873 Type[] param_types = method.ParameterTypes;
5875 if (param_types.Length != ParameterTypes.Length)
5878 for (int i = 0; i < param_types.Length; i++)
5879 if (param_types [i] != ParameterTypes [i])
5882 Report.SymbolRelatedToPreviousError (method);
5883 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
5887 public override bool IsUsed
5897 public new Location Location {
5899 return base.Location;
5904 // Represents header string for documentation comment.
5906 public override string DocCommentHeader {
5907 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5913 // Properties and Indexers both generate PropertyBuilders, we use this to share
5914 // their common bits.
5916 abstract public class PropertyBase : MethodCore {
5918 public class GetMethod: PropertyMethod
5920 static string[] attribute_targets = new string [] { "method", "return" };
5922 public GetMethod (MethodCore method):
5923 base (method, "get_")
5927 public GetMethod (MethodCore method, Accessor accessor):
5928 base (method, accessor, "get_")
5932 public override MethodBuilder Define(TypeContainer container)
5934 base.Define (container);
5936 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5938 if (!method_data.Define (container))
5941 return method_data.MethodBuilder;
5944 public override Type ReturnType {
5946 return method.MemberType;
5950 public override string[] ValidAttributeTargets {
5952 return attribute_targets;
5957 public class SetMethod: PropertyMethod {
5959 static string[] attribute_targets = new string [] { "method", "param", "return" };
5960 ImplicitParameter param_attr;
5962 public SetMethod (MethodCore method):
5963 base (method, "set_")
5967 public SetMethod (MethodCore method, Accessor accessor):
5968 base (method, accessor, "set_")
5972 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5974 if (a.Target == AttributeTargets.Parameter) {
5975 if (param_attr == null)
5976 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
5978 param_attr.ApplyAttributeBuilder (a, cb);
5982 base.ApplyAttributeBuilder (a, cb);
5985 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5987 Parameter [] parms = new Parameter [1];
5988 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
5989 Parameters parameters = new Parameters (parms, null);
5991 bool old_unsafe = ec.InUnsafe;
5992 ec.InUnsafe = InUnsafe;
5993 Type [] types = parameters.GetParameterInfo (ec);
5994 ec.InUnsafe = old_unsafe;
5996 return new InternalParameters (types, parameters);
5999 public override MethodBuilder Define (TypeContainer container)
6001 if (container.EmitContext == null)
6002 throw new InternalErrorException ("SetMethod.Define called too early");
6004 base.Define (container);
6006 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6008 if (!method_data.Define (container))
6011 return method_data.MethodBuilder;
6014 public override Type[] ParameterTypes {
6016 return new Type[] { method.MemberType };
6020 public override Type ReturnType {
6022 return TypeManager.void_type;
6026 public override string[] ValidAttributeTargets {
6028 return attribute_targets;
6033 static string[] attribute_targets = new string [] { "property" };
6035 public abstract class PropertyMethod: AbstractPropertyEventMethod
6037 protected readonly MethodCore method;
6038 protected MethodAttributes flags;
6041 public PropertyMethod (MethodCore method, string prefix)
6042 : base (method, prefix)
6044 this.method = method;
6047 public PropertyMethod (MethodCore method, Accessor accessor,
6049 : base (method, accessor, prefix)
6051 this.method = method;
6052 this.ModFlags = accessor.ModFlags;
6053 yields = accessor.Yields;
6055 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6056 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6060 public override AttributeTargets AttributeTargets {
6062 return AttributeTargets.Method;
6066 public override bool IsClsCompliaceRequired(DeclSpace ds)
6068 return method.IsClsCompliaceRequired (ds);
6071 public InternalParameters ParameterInfo
6074 return method_data.ParameterInfo;
6078 public virtual MethodBuilder Define (TypeContainer container)
6080 if (!method.CheckAbstractAndExtern (block != null))
6084 // Check for custom access modifier
6086 if (ModFlags == 0) {
6087 ModFlags = method.ModFlags;
6088 flags = method.flags;
6090 if (container.Kind == Kind.Interface)
6091 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6092 GetSignatureForError ());
6094 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6095 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6098 CheckModifiers (container, ModFlags);
6099 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6100 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6101 flags = Modifiers.MethodAttr (ModFlags);
6102 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6106 // Setup iterator if we are one
6109 Iterator iterator = new Iterator (this,
6110 Parent, method.ParameterInfo, ModFlags);
6112 if (!iterator.DefineIterator ())
6119 public bool HasCustomAccessModifier
6122 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6126 public override Type[] ParameterTypes {
6128 return TypeManager.NoTypes;
6132 public override EmitContext CreateEmitContext (TypeContainer tc,
6135 return new EmitContext (
6136 tc, method.Parent, method.Location, ig, ReturnType,
6137 method.ModFlags, false);
6140 public override ObsoleteAttribute GetObsoleteAttribute ()
6142 return method.GetObsoleteAttribute ();
6145 public override string GetSignatureForError()
6147 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6150 void CheckModifiers (TypeContainer container, int modflags)
6153 int mflags = method.ModFlags & Modifiers.Accessibility;
6155 if ((mflags & Modifiers.PUBLIC) != 0) {
6156 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6158 else if ((mflags & Modifiers.PROTECTED) != 0) {
6159 if ((mflags & Modifiers.INTERNAL) != 0)
6160 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6162 flags |= Modifiers.PRIVATE;
6164 else if ((mflags & Modifiers.INTERNAL) != 0)
6165 flags |= Modifiers.PRIVATE;
6167 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6168 Report.Error (273, Location,
6169 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6170 GetSignatureForError (), method.GetSignatureForError ());
6174 public override bool MarkForDuplicationCheck ()
6176 caching_flags |= Flags.TestMethodDuplication;
6182 public PropertyMethod Get, Set;
6183 public PropertyBuilder PropertyBuilder;
6184 public MethodBuilder GetBuilder, SetBuilder;
6186 protected EmitContext ec;
6188 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6189 int allowed_mod, bool is_iface, MemberName name,
6190 Parameters parameters, Attributes attrs)
6191 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6196 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6198 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6199 a.Error_InvalidSecurityParent ();
6203 PropertyBuilder.SetCustomAttribute (cb);
6206 public override AttributeTargets AttributeTargets {
6208 return AttributeTargets.Property;
6212 public override bool Define ()
6217 if (!IsTypePermitted ())
6223 protected override bool DoDefine ()
6225 if (!base.DoDefine ())
6229 // Accessors modifiers check
6231 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6232 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6233 GetSignatureForError ());
6237 if ((Get.IsDummy || Set.IsDummy)
6238 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6239 Report.Error (276, Location,
6240 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6241 GetSignatureForError ());
6245 if (MemberType.IsAbstract && MemberType.IsSealed) {
6246 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6250 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6254 protected override bool CheckForDuplications ()
6256 ArrayList ar = Parent.Indexers;
6258 int arLen = ar.Count;
6260 for (int i = 0; i < arLen; i++) {
6261 Indexer m = (Indexer) ar [i];
6262 if (IsDuplicateImplementation (m))
6267 ar = Parent.Properties;
6269 int arLen = ar.Count;
6271 for (int i = 0; i < arLen; i++) {
6272 Property m = (Property) ar [i];
6273 if (IsDuplicateImplementation (m))
6281 // TODO: rename to Resolve......
6282 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6284 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6285 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6287 if (base_property == null)
6290 base_ret_type = base_property.PropertyType;
6291 MethodInfo get_accessor = base_property.GetGetMethod (true);
6292 MethodInfo set_accessor = base_property.GetSetMethod (true);
6293 MethodAttributes get_accessor_access, set_accessor_access;
6295 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6296 if (Get != null && !Get.IsDummy && get_accessor == null) {
6297 Report.SymbolRelatedToPreviousError (base_property);
6298 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6301 if (Set != null && !Set.IsDummy && set_accessor == null) {
6302 Report.SymbolRelatedToPreviousError (base_property);
6303 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6308 // Check base class accessors access
6311 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6312 get_accessor_access = set_accessor_access = 0;
6313 if ((ModFlags & Modifiers.NEW) == 0) {
6314 if (get_accessor != null) {
6315 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6316 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6318 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6319 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6322 if (set_accessor != null) {
6323 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6324 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6326 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6327 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6332 // Get the less restrictive access
6334 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6337 public override void Emit ()
6340 // The PropertyBuilder can be null for explicit implementations, in that
6341 // case, we do not actually emit the ".property", so there is nowhere to
6342 // put the attribute
6344 if (PropertyBuilder != null && OptAttributes != null)
6345 OptAttributes.Emit (ec, this);
6357 /// Tests whether accessors are not in collision with some method (CS0111)
6359 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6361 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6364 public override bool IsUsed
6370 return Get.IsUsed | Set.IsUsed;
6374 protected override void SetMemberName (MemberName new_name)
6376 base.SetMemberName (new_name);
6378 Get.UpdateName (this);
6379 Set.UpdateName (this);
6382 public override string[] ValidAttributeTargets {
6384 return attribute_targets;
6389 // Represents header string for documentation comment.
6391 public override string DocCommentHeader {
6392 get { return "P:"; }
6396 public class Property : PropertyBase {
6397 const int AllowedModifiers =
6400 Modifiers.PROTECTED |
6401 Modifiers.INTERNAL |
6405 Modifiers.OVERRIDE |
6406 Modifiers.ABSTRACT |
6409 Modifiers.METHOD_YIELDS |
6412 const int AllowedInterfaceModifiers =
6415 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6416 MemberName name, Attributes attrs, Accessor get_block,
6418 : base (ds, type, mod,
6419 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6420 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6422 if (get_block == null)
6423 Get = new GetMethod (this);
6425 Get = new GetMethod (this, get_block);
6427 if (set_block == null)
6428 Set = new SetMethod (this);
6430 Set = new SetMethod (this, set_block);
6433 public override bool Define ()
6435 if (!base.Define ())
6441 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6444 GetBuilder = Get.Define (Parent);
6445 if (GetBuilder == null)
6450 SetBuilder = Set.Define (Parent);
6451 if (SetBuilder == null)
6454 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6457 // FIXME - PropertyAttributes.HasDefault ?
6459 PropertyAttributes prop_attr = PropertyAttributes.None;
6461 prop_attr |= PropertyAttributes.RTSpecialName |
6462 PropertyAttributes.SpecialName;
6464 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6465 Name, prop_attr, MemberType, null);
6468 PropertyBuilder.SetGetMethod (GetBuilder);
6471 PropertyBuilder.SetSetMethod (SetBuilder);
6478 /// Gigantic workaround for lameness in SRE follows :
6479 /// This class derives from EventInfo and attempts to basically
6480 /// wrap around the EventBuilder so that FindMembers can quickly
6481 /// return this in it search for members
6483 public class MyEventBuilder : EventInfo {
6486 // We use this to "point" to our Builder which is
6487 // not really a MemberInfo
6489 EventBuilder MyBuilder;
6492 // We "catch" and wrap these methods
6494 MethodInfo raise, remove, add;
6496 EventAttributes attributes;
6497 Type declaring_type, reflected_type, event_type;
6502 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6504 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6506 // And now store the values in our own fields.
6508 declaring_type = type_builder;
6510 reflected_type = type_builder;
6512 attributes = event_attr;
6515 this.event_type = event_type;
6519 // Methods that you have to override. Note that you only need
6520 // to "implement" the variants that take the argument (those are
6521 // the "abstract" methods, the others (GetAddMethod()) are
6524 public override MethodInfo GetAddMethod (bool nonPublic)
6529 public override MethodInfo GetRemoveMethod (bool nonPublic)
6534 public override MethodInfo GetRaiseMethod (bool nonPublic)
6540 // These methods make "MyEventInfo" look like a Builder
6542 public void SetRaiseMethod (MethodBuilder raiseMethod)
6544 raise = raiseMethod;
6545 MyBuilder.SetRaiseMethod (raiseMethod);
6548 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6550 remove = removeMethod;
6551 MyBuilder.SetRemoveOnMethod (removeMethod);
6554 public void SetAddOnMethod (MethodBuilder addMethod)
6557 MyBuilder.SetAddOnMethod (addMethod);
6560 public void SetCustomAttribute (CustomAttributeBuilder cb)
6562 MyBuilder.SetCustomAttribute (cb);
6565 public override object [] GetCustomAttributes (bool inherit)
6567 // FIXME : There's nothing which can be seemingly done here because
6568 // we have no way of getting at the custom attribute objects of the
6573 public override object [] GetCustomAttributes (Type t, bool inherit)
6575 // FIXME : Same here !
6579 public override bool IsDefined (Type t, bool b)
6584 public override EventAttributes Attributes {
6590 public override string Name {
6596 public override Type DeclaringType {
6598 return declaring_type;
6602 public override Type ReflectedType {
6604 return reflected_type;
6608 public Type EventType {
6614 public void SetUsed ()
6616 if (my_event != null) {
6617 my_event.SetAssigned ();
6618 my_event.SetMemberIsUsed ();
6624 /// For case when event is declared like property (with add and remove accessors).
6626 public class EventProperty: Event {
6628 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6630 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6631 bool is_iface, MemberName name, Object init,
6632 Attributes attrs, Accessor add, Accessor remove)
6633 : base (parent, type, mod_flags, is_iface, name, init, attrs)
6635 Add = new AddDelegateMethod (this, add);
6636 Remove = new RemoveDelegateMethod (this, remove);
6638 // For this event syntax we don't report error CS0067
6639 // because it is hard to do it.
6643 public override string[] ValidAttributeTargets {
6645 return attribute_targets;
6651 /// Event is declared like field.
6653 public class EventField: Event {
6655 static string[] attribute_targets = new string [] { "event", "field", "method" };
6656 static string[] attribute_targets_interface = new string[] { "event", "method" };
6658 public EventField (TypeContainer parent, Expression type, int mod_flags,
6659 bool is_iface, MemberName name, Object init,
6661 : base (parent, type, mod_flags, is_iface, name, init, attrs)
6663 Add = new AddDelegateMethod (this);
6664 Remove = new RemoveDelegateMethod (this);
6667 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6669 if (a.Target == AttributeTargets.Field) {
6670 FieldBuilder.SetCustomAttribute (cb);
6674 if (a.Target == AttributeTargets.Method) {
6675 Add.ApplyAttributeBuilder (a, cb);
6676 Remove.ApplyAttributeBuilder (a, cb);
6680 base.ApplyAttributeBuilder (a, cb);
6683 public override string[] ValidAttributeTargets {
6685 return IsInterface ? attribute_targets_interface : attribute_targets;
6690 public abstract class Event : FieldBase {
6692 protected sealed class AddDelegateMethod: DelegateMethod
6695 public AddDelegateMethod (Event method):
6696 base (method, "add_")
6700 public AddDelegateMethod (Event method, Accessor accessor):
6701 base (method, accessor, "add_")
6705 protected override MethodInfo DelegateMethodInfo {
6707 return TypeManager.delegate_combine_delegate_delegate;
6713 protected sealed class RemoveDelegateMethod: DelegateMethod
6715 public RemoveDelegateMethod (Event method):
6716 base (method, "remove_")
6720 public RemoveDelegateMethod (Event method, Accessor accessor):
6721 base (method, accessor, "remove_")
6725 protected override MethodInfo DelegateMethodInfo {
6727 return TypeManager.delegate_remove_delegate_delegate;
6733 public abstract class DelegateMethod: AbstractPropertyEventMethod
6735 protected readonly Event method;
6736 ImplicitParameter param_attr;
6738 static string[] attribute_targets = new string [] { "method", "param", "return" };
6740 public DelegateMethod (Event method, string prefix)
6741 : base (method, prefix)
6743 this.method = method;
6746 public DelegateMethod (Event method, Accessor accessor, string prefix)
6747 : base (method, accessor, prefix)
6749 this.method = method;
6752 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6754 if (a.Target == AttributeTargets.Parameter) {
6755 if (param_attr == null)
6756 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6758 param_attr.ApplyAttributeBuilder (a, cb);
6762 base.ApplyAttributeBuilder (a, cb);
6765 public override AttributeTargets AttributeTargets {
6767 return AttributeTargets.Method;
6771 public override bool IsClsCompliaceRequired(DeclSpace ds)
6773 return method.IsClsCompliaceRequired (ds);
6776 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6778 method_data = new MethodData (method, ip, method.ModFlags,
6779 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6781 if (!method_data.Define (container))
6784 MethodBuilder mb = method_data.MethodBuilder;
6785 mb.DefineParameter (1, ParameterAttributes.None, "value");
6790 protected override void EmitMethod (TypeContainer tc)
6792 if (block != null) {
6793 base.EmitMethod (tc);
6797 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6800 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6801 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6803 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6804 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6805 ig.Emit (OpCodes.Ldsfld, field_info);
6806 ig.Emit (OpCodes.Ldarg_0);
6807 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6808 ig.Emit (OpCodes.Castclass, method.MemberType);
6809 ig.Emit (OpCodes.Stsfld, field_info);
6811 ig.Emit (OpCodes.Ldarg_0);
6812 ig.Emit (OpCodes.Ldarg_0);
6813 ig.Emit (OpCodes.Ldfld, field_info);
6814 ig.Emit (OpCodes.Ldarg_1);
6815 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6816 ig.Emit (OpCodes.Castclass, method.MemberType);
6817 ig.Emit (OpCodes.Stfld, field_info);
6819 ig.Emit (OpCodes.Ret);
6822 protected abstract MethodInfo DelegateMethodInfo { get; }
6824 public override Type[] ParameterTypes {
6826 return new Type[] { method.MemberType };
6830 public override Type ReturnType {
6832 return TypeManager.void_type;
6836 public override EmitContext CreateEmitContext (TypeContainer tc,
6839 return new EmitContext (
6840 tc, method.Parent, Location, ig, ReturnType,
6841 method.ModFlags, false);
6844 public override ObsoleteAttribute GetObsoleteAttribute ()
6846 return method.GetObsoleteAttribute ();
6849 public override string[] ValidAttributeTargets {
6851 return attribute_targets;
6857 const int AllowedModifiers =
6860 Modifiers.PROTECTED |
6861 Modifiers.INTERNAL |
6866 Modifiers.OVERRIDE |
6870 const int AllowedInterfaceModifiers =
6873 public DelegateMethod Add, Remove;
6874 public MyEventBuilder EventBuilder;
6875 public MethodBuilder AddBuilder, RemoveBuilder;
6877 public Event (TypeContainer parent, Expression type, int mod_flags,
6878 bool is_iface, MemberName name, Object init, Attributes attrs)
6879 : base (parent, type, mod_flags,
6880 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6883 IsInterface = is_iface;
6886 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6888 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6889 a.Error_InvalidSecurityParent ();
6893 EventBuilder.SetCustomAttribute (cb);
6896 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6898 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6901 public override AttributeTargets AttributeTargets {
6903 return AttributeTargets.Event;
6907 public override bool Define ()
6909 EventAttributes e_attr;
6910 e_attr = EventAttributes.None;
6915 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6916 Report.Error (74, Location, "`" + GetSignatureForError () +
6917 "': abstract event cannot have an initializer");
6921 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6922 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
6926 EmitContext ec = Parent.EmitContext;
6928 throw new InternalErrorException ("Event.Define called too early?");
6929 bool old_unsafe = ec.InUnsafe;
6930 ec.InUnsafe = InUnsafe;
6932 Parameter [] parms = new Parameter [1];
6933 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
6934 Parameters parameters = new Parameters (parms, null);
6935 Type [] types = parameters.GetParameterInfo (ec);
6936 InternalParameters ip = new InternalParameters (types, parameters);
6938 ec.InUnsafe = old_unsafe;
6944 // Now define the accessors
6947 AddBuilder = Add.Define (Parent, ip);
6948 if (AddBuilder == null)
6951 RemoveBuilder = Remove.Define (Parent, ip);
6952 if (RemoveBuilder == null)
6955 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6957 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6958 FieldBuilder = Parent.TypeBuilder.DefineField (
6960 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6961 TypeManager.RegisterPrivateFieldOfEvent (
6962 (EventInfo) EventBuilder, FieldBuilder);
6963 TypeManager.RegisterFieldBase (FieldBuilder, this);
6966 EventBuilder.SetAddOnMethod (AddBuilder);
6967 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6969 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6973 protected override bool CheckBase ()
6975 if (!base.CheckBase ())
6978 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6979 if (!(conflict_symbol is EventInfo)) {
6980 Report.SymbolRelatedToPreviousError (conflict_symbol);
6981 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
6989 public override void Emit ()
6991 if (OptAttributes != null) {
6992 EmitContext ec = new EmitContext (
6993 Parent, Location, null, MemberType, ModFlags);
6994 OptAttributes.Emit (ec, this);
6998 Remove.Emit (Parent);
7003 public override string GetSignatureForError ()
7005 return base.GetSignatureForError ();
7009 // Represents header string for documentation comment.
7011 public override string DocCommentHeader {
7012 get { return "E:"; }
7017 public class Indexer : PropertyBase {
7019 class GetIndexerMethod: GetMethod
7021 public GetIndexerMethod (MethodCore method):
7026 public GetIndexerMethod (MethodCore method, Accessor accessor):
7027 base (method, accessor)
7031 public override Type[] ParameterTypes {
7033 return method.ParameterTypes;
7038 class SetIndexerMethod: SetMethod
7040 readonly Parameters parameters;
7042 public SetIndexerMethod (MethodCore method):
7047 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7048 base (method, accessor)
7050 this.parameters = parameters;
7053 public override Type[] ParameterTypes {
7055 int top = method.ParameterTypes.Length;
7056 Type [] set_pars = new Type [top + 1];
7057 method.ParameterTypes.CopyTo (set_pars, 0);
7058 set_pars [top] = method.MemberType;
7063 protected override InternalParameters GetParameterInfo (EmitContext ec)
7065 Parameter [] fixed_parms = parameters.FixedParameters;
7067 if (fixed_parms == null){
7068 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7069 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7070 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7072 // Here is the problem: the `value' parameter has
7073 // to come *after* the array parameter in the declaration
7075 // X (object [] x, Type value)
7078 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7079 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7083 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7085 fixed_parms.CopyTo (tmp, 0);
7086 tmp [fixed_parms.Length] = new Parameter (
7087 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7089 Parameters set_formal_params = new Parameters (tmp, null);
7090 Type [] types = set_formal_params.GetParameterInfo (ec);
7092 return new InternalParameters (types, set_formal_params);
7097 const int AllowedModifiers =
7100 Modifiers.PROTECTED |
7101 Modifiers.INTERNAL |
7105 Modifiers.OVERRIDE |
7110 const int AllowedInterfaceModifiers =
7114 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7115 bool is_iface, Parameters parameters, Attributes attrs,
7116 Accessor get_block, Accessor set_block)
7117 : base (ds, type, mod,
7118 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7119 is_iface, name, parameters, attrs)
7121 if (get_block == null)
7122 Get = new GetIndexerMethod (this);
7124 Get = new GetIndexerMethod (this, get_block);
7126 if (set_block == null)
7127 Set = new SetIndexerMethod (this);
7129 Set = new SetIndexerMethod (this, parameters, set_block);
7132 public override bool Define ()
7134 PropertyAttributes prop_attr =
7135 PropertyAttributes.RTSpecialName |
7136 PropertyAttributes.SpecialName;
7138 if (!base.Define ())
7141 if (MemberType == TypeManager.void_type) {
7142 Report.Error (620, Location, "Indexers cannot have void type");
7146 if (OptAttributes != null) {
7147 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7148 if (indexer_attr != null) {
7149 // Remove the attribute from the list because it is not emitted
7150 OptAttributes.Attrs.Remove (indexer_attr);
7152 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7154 if (IsExplicitImpl) {
7155 Report.Error (415, indexer_attr.Location,
7156 "The `IndexerName' attribute is valid only on an " +
7157 "indexer that is not an explicit interface member declaration");
7161 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7162 Report.Error (609, indexer_attr.Location,
7163 "Cannot set the `IndexerName' attribute on an indexer marked override");
7167 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7168 Report.Error (633, indexer_attr.Location,
7169 "The argument to the `IndexerName' attribute must be a valid identifier");
7175 if (InterfaceType != null) {
7176 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7177 if (base_IndexerName != Name)
7178 ShortName = base_IndexerName;
7181 if (!Parent.AddToMemberContainer (this) ||
7182 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7188 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7190 GetBuilder = Get.Define (Parent);
7191 if (GetBuilder == null)
7196 SetBuilder = Set.Define (Parent);
7197 if (SetBuilder == null)
7202 // Now name the parameters
7204 Parameter [] p = Parameters.FixedParameters;
7206 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7207 Report.Error (631, Location, "ref and out are not valid in this context");
7213 for (i = 0; i < p.Length; ++i) {
7215 GetBuilder.DefineParameter (
7216 i + 1, p [i].Attributes, p [i].Name);
7219 SetBuilder.DefineParameter (
7220 i + 1, p [i].Attributes, p [i].Name);
7224 SetBuilder.DefineParameter (
7225 i + 1, ParameterAttributes.None, "value");
7227 if (i != ParameterTypes.Length) {
7228 Parameter array_param = Parameters.ArrayParameter;
7230 SetBuilder.DefineParameter (
7231 i + 1, array_param.Attributes, array_param.Name);
7235 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7236 Name, prop_attr, MemberType, ParameterTypes);
7239 PropertyBuilder.SetGetMethod (GetBuilder);
7242 PropertyBuilder.SetSetMethod (SetBuilder);
7244 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7249 public override string GetSignatureForError ()
7251 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7252 if (MemberName.Left != null) {
7254 sb.Append (MemberName.Left);
7257 sb.Append (".this");
7258 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7259 return sb.ToString ();
7262 public override bool MarkForDuplicationCheck ()
7264 caching_flags |= Flags.TestMethodDuplication;
7270 public class Operator : MethodCore, IIteratorContainer {
7272 const int AllowedModifiers =
7278 public enum OpType : byte {
7288 // Unary and Binary operators
7311 // Implicit and Explicit
7315 // Just because of enum
7319 public readonly OpType OperatorType;
7320 public MethodBuilder OperatorMethodBuilder;
7322 public Method OperatorMethod;
7324 static string[] attribute_targets = new string [] { "method", "return" };
7326 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7327 int mod_flags, Parameters parameters,
7328 ToplevelBlock block, Attributes attrs, Location loc)
7329 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7330 new MemberName ("op_" + type, loc), attrs, parameters)
7332 OperatorType = type;
7336 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7338 OperatorMethod.ApplyAttributeBuilder (a, cb);
7341 public override AttributeTargets AttributeTargets {
7343 return AttributeTargets.Method;
7347 protected override bool CheckForDuplications()
7349 ArrayList ar = Parent.Operators;
7351 int arLen = ar.Count;
7353 for (int i = 0; i < arLen; i++) {
7354 Operator o = (Operator) ar [i];
7355 if (IsDuplicateImplementation (o))
7360 ar = Parent.Methods;
7362 int arLen = ar.Count;
7364 for (int i = 0; i < arLen; i++) {
7365 Method m = (Method) ar [i];
7366 if (IsDuplicateImplementation (m))
7374 public override bool Define ()
7376 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7377 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7378 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7385 if (MemberType == TypeManager.void_type) {
7386 Report.Error (590, Location, "User-defined operators cannot return void");
7390 OperatorMethod = new Method (
7391 Parent, Type, ModFlags, false, MemberName,
7392 Parameters, OptAttributes);
7394 OperatorMethod.Block = Block;
7395 OperatorMethod.IsOperator = this;
7396 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7397 OperatorMethod.Define ();
7399 if (OperatorMethod.MethodBuilder == null)
7402 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7404 parameter_types = OperatorMethod.ParameterTypes;
7405 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7406 Type return_type = OperatorMethod.ReturnType;
7407 Type first_arg_type = parameter_types [0];
7412 // Rules for conversion operators
7414 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7415 if (first_arg_type == return_type && first_arg_type == declaring_type){
7416 Report.Error (555, Location,
7417 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7421 if (first_arg_type != declaring_type && return_type != declaring_type){
7424 "User-defined conversion must convert to or from the " +
7429 if (first_arg_type == TypeManager.object_type ||
7430 return_type == TypeManager.object_type){
7433 "User-defined conversion cannot convert to or from " +
7438 if (first_arg_type.IsInterface || return_type.IsInterface){
7439 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7440 GetSignatureForError ());
7444 if (first_arg_type.IsSubclassOf (return_type)
7445 || return_type.IsSubclassOf (first_arg_type)){
7446 if (declaring_type.IsSubclassOf (return_type)) {
7447 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7448 GetSignatureForError ());
7451 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7452 GetSignatureForError ());
7455 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7456 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7457 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");
7460 } else if (Parameters.FixedParameters.Length == 1) {
7461 // Checks for Unary operators
7463 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7464 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7465 Report.Error (448, Location,
7466 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7469 if (first_arg_type != declaring_type) {
7471 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7476 if (first_arg_type != declaring_type){
7479 "The parameter of a unary operator must be the " +
7484 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7485 if (return_type != TypeManager.bool_type){
7488 "The return type of operator True or False " +
7495 // Checks for Binary operators
7497 if (first_arg_type != declaring_type &&
7498 parameter_types [1] != declaring_type){
7501 "One of the parameters of a binary operator must " +
7502 "be the containing type");
7510 public override void Emit ()
7513 // abstract or extern methods have no bodies
7515 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7518 OperatorMethod.Emit ();
7522 // Operator cannot be override
7523 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7528 public static string GetName (OpType ot)
7531 case OpType.LogicalNot:
7533 case OpType.OnesComplement:
7535 case OpType.Increment:
7537 case OpType.Decrement:
7543 case OpType.Addition:
7545 case OpType.Subtraction:
7547 case OpType.UnaryPlus:
7549 case OpType.UnaryNegation:
7551 case OpType.Multiply:
7553 case OpType.Division:
7555 case OpType.Modulus:
7557 case OpType.BitwiseAnd:
7559 case OpType.BitwiseOr:
7561 case OpType.ExclusiveOr:
7563 case OpType.LeftShift:
7565 case OpType.RightShift:
7567 case OpType.Equality:
7569 case OpType.Inequality:
7571 case OpType.GreaterThan:
7573 case OpType.LessThan:
7575 case OpType.GreaterThanOrEqual:
7577 case OpType.LessThanOrEqual:
7579 case OpType.Implicit:
7581 case OpType.Explicit:
7587 public static OpType GetOperatorType (string name)
7589 if (name.StartsWith ("op_")){
7590 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7591 if (Unary.oper_names [i] == name)
7595 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7596 if (Binary.oper_names [i] == name)
7603 public override string GetSignatureForError ()
7605 StringBuilder sb = new StringBuilder ();
7606 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7607 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7610 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7613 sb.Append (Parameters.GetSignatureForError ());
7614 return sb.ToString ();
7617 public override bool MarkForDuplicationCheck ()
7619 caching_flags |= Flags.TestMethodDuplication;
7623 public override string[] ValidAttributeTargets {
7625 return attribute_targets;
7631 // This is used to compare method signatures
7633 struct MethodSignature {
7635 public Type RetType;
7636 public Type [] Parameters;
7639 /// This delegate is used to extract methods which have the
7640 /// same signature as the argument
7642 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7644 public MethodSignature (string name, Type ret_type, Type [] parameters)
7649 if (parameters == null)
7650 Parameters = TypeManager.NoTypes;
7652 Parameters = parameters;
7655 public override string ToString ()
7658 if (Parameters.Length != 0){
7659 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7660 for (int i = 0; i < Parameters.Length; i++){
7661 sb.Append (Parameters [i]);
7662 if (i+1 < Parameters.Length)
7665 pars = sb.ToString ();
7668 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7671 public override int GetHashCode ()
7673 return Name.GetHashCode ();
7676 public override bool Equals (Object o)
7678 MethodSignature other = (MethodSignature) o;
7680 if (other.Name != Name)
7683 if (other.RetType != RetType)
7686 if (Parameters == null){
7687 if (other.Parameters == null)
7692 if (other.Parameters == null)
7695 int c = Parameters.Length;
7696 if (other.Parameters.Length != c)
7699 for (int i = 0; i < c; i++)
7700 if (other.Parameters [i] != Parameters [i])
7706 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7708 MethodSignature sig = (MethodSignature) filter_criteria;
7710 if (m.Name != sig.Name)
7714 MethodInfo mi = m as MethodInfo;
7715 PropertyInfo pi = m as PropertyInfo;
7718 ReturnType = mi.ReturnType;
7719 else if (pi != null)
7720 ReturnType = pi.PropertyType;
7725 // we use sig.RetType == null to mean `do not check the
7726 // method return value.
7728 if (sig.RetType != null)
7729 if (ReturnType != sig.RetType)
7734 args = TypeManager.GetArgumentTypes (mi);
7736 args = TypeManager.GetArgumentTypes (pi);
7737 Type [] sigp = sig.Parameters;
7739 if (args.Length != sigp.Length)
7742 for (int i = args.Length; i > 0; ){
7744 if (args [i] != sigp [i])