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.
36 using System.Collections;
37 using System.Collections.Specialized;
38 using System.Reflection;
39 using System.Reflection.Emit;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42 using System.Security;
43 using System.Security.Permissions;
46 using Mono.CompilerServices.SymbolWriter;
48 namespace Mono.CSharp {
58 /// This is the base class for structs and classes.
60 public abstract class TypeContainer : DeclSpace, IMemberContainer {
62 public class MemberCoreArrayList: ArrayList
65 /// Defines the MemberCore objects that are in this array
67 public virtual void DefineContainerMembers ()
69 foreach (MemberCore mc in this) {
74 public virtual void Emit ()
76 foreach (MemberCore mc in this)
81 public class MethodArrayList : MemberCoreArrayList
89 CachedMethods cached_method;
90 TypeContainer container;
92 public MethodArrayList (TypeContainer container)
94 this.container = container;
98 /// Method container contains Equals method
100 public bool HasEquals {
102 cached_method |= CachedMethods.Equals;
106 return (cached_method & CachedMethods.Equals) != 0;
111 /// Method container contains GetHashCode method
113 public bool HasGetHashCode {
115 cached_method |= CachedMethods.GetHashCode;
119 return (cached_method & CachedMethods.GetHashCode) != 0;
123 public override void DefineContainerMembers ()
125 base.DefineContainerMembers ();
127 if (HasEquals && !HasGetHashCode) {
128 Report.Warning (659, 3, container.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
134 public sealed class IndexerArrayList : MemberCoreArrayList
137 /// The indexer name for this container
139 public string IndexerName = DefaultIndexerName;
141 bool seen_normal_indexers = false;
143 TypeContainer container;
145 public IndexerArrayList (TypeContainer container)
147 this.container = container;
151 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
152 /// class is consistent. Either it is `Item' or it is the name defined by all the
153 /// indexers with the `IndexerName' attribute.
155 /// Turns out that the IndexerNameAttribute is applied to each indexer,
156 /// but it is never emitted, instead a DefaultMember attribute is attached
159 public override void DefineContainerMembers()
161 base.DefineContainerMembers ();
163 string class_indexer_name = null;
166 // If there's both an explicit and an implicit interface implementation, the
167 // explicit one actually implements the interface while the other one is just
168 // a normal indexer. See bug #37714.
171 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
172 foreach (Indexer i in this) {
173 if (i.InterfaceType != null) {
174 if (seen_normal_indexers)
175 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
179 seen_normal_indexers = true;
181 if (class_indexer_name == null) {
182 class_indexer_name = i.ShortName;
186 if (i.ShortName != class_indexer_name)
187 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");
190 if (class_indexer_name != null)
191 IndexerName = class_indexer_name;
194 public override void Emit ()
198 if (!seen_normal_indexers)
201 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
202 container.TypeBuilder.SetCustomAttribute (cb);
206 public class OperatorArrayList: MemberCoreArrayList
208 TypeContainer container;
210 public OperatorArrayList (TypeContainer container)
212 this.container = container;
216 // Operator pair checking
221 public Type ret_type;
222 public Type type1, type2;
224 public Operator.OpType ot;
226 public OperatorEntry (int f, Operator o)
230 ret_type = o.OperatorMethod.ReturnType;
231 Type [] pt = o.OperatorMethod.ParameterTypes;
238 public override int GetHashCode ()
240 return ret_type.GetHashCode ();
243 public override bool Equals (object o)
245 OperatorEntry other = (OperatorEntry) o;
247 if (other.ret_type != ret_type)
249 if (other.type1 != type1)
251 if (other.type2 != type2)
258 // Checks that some operators come in pairs:
264 // They are matched based on the return type and the argument types
266 void CheckPairedOperators ()
268 IDictionary pairs = new HybridDictionary ();
269 Operator true_op = null;
270 Operator false_op = null;
271 bool has_equality_or_inequality = false;
273 // Register all the operators we care about.
274 foreach (Operator op in this){
277 // Skip erroneous code.
278 if (op.OperatorMethod == null)
281 switch (op.OperatorType){
282 case Operator.OpType.Equality:
284 has_equality_or_inequality = true;
286 case Operator.OpType.Inequality:
288 has_equality_or_inequality = true;
291 case Operator.OpType.True:
294 case Operator.OpType.False:
298 case Operator.OpType.GreaterThan:
300 case Operator.OpType.LessThan:
303 case Operator.OpType.GreaterThanOrEqual:
305 case Operator.OpType.LessThanOrEqual:
311 OperatorEntry oe = new OperatorEntry (reg, op);
313 object o = pairs [oe];
317 oe = (OperatorEntry) o;
322 if (true_op != null){
323 if (false_op == null)
324 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
325 true_op.GetSignatureForError ());
326 } else if (false_op != null)
327 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
328 false_op.GetSignatureForError ());
331 // Look for the mistakes.
333 foreach (DictionaryEntry de in pairs){
334 OperatorEntry oe = (OperatorEntry) de.Key;
341 case Operator.OpType.Equality:
344 case Operator.OpType.Inequality:
347 case Operator.OpType.GreaterThan:
350 case Operator.OpType.LessThan:
353 case Operator.OpType.GreaterThanOrEqual:
356 case Operator.OpType.LessThanOrEqual:
360 Report.Error (216, oe.op.Location,
361 "The operator `{0}' requires a matching operator `{1}' to also be defined",
362 oe.op.GetSignatureForError (), s);
365 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
366 if (container.Methods == null || !container.Methods.HasEquals)
367 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
369 if (container.Methods == null || !container.Methods.HasGetHashCode)
370 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
374 public override void DefineContainerMembers ()
376 base.DefineContainerMembers ();
377 CheckPairedOperators ();
382 // Whether this is a struct, class or interface
383 public readonly Kind Kind;
385 // Holds a list of classes and structures
388 // Holds the list of properties
389 MemberCoreArrayList properties;
391 // Holds the list of enumerations
392 MemberCoreArrayList enums;
394 // Holds the list of delegates
395 MemberCoreArrayList delegates;
397 // Holds the list of constructors
398 protected MemberCoreArrayList instance_constructors;
400 // Holds the list of fields
401 MemberCoreArrayList fields;
403 // Holds a list of fields that have initializers
404 protected ArrayList initialized_fields;
406 // Holds a list of static fields that have initializers
407 protected ArrayList initialized_static_fields;
409 // Holds the list of constants
410 MemberCoreArrayList constants;
413 MemberCoreArrayList interfaces;
415 // Holds the methods.
416 MethodArrayList methods;
419 protected MemberCoreArrayList events;
421 // Holds the indexers
422 IndexerArrayList indexers;
424 // Holds the operators
425 MemberCoreArrayList operators;
427 // Holds the iterators
430 // Holds the parts of a partial class;
434 // Pointers to the default constructor and the default static constructor
436 protected Constructor default_constructor;
437 protected Constructor default_static_constructor;
440 // Points to the first non-static field added to the container.
442 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
443 // and the first one's as good as any.
445 FieldBase first_nonstatic_field = null;
448 // This one is computed after we can distinguish interfaces
449 // from classes from the arraylist `type_bases'
451 string base_class_name;
453 TypeExpr[] iface_exprs;
455 ArrayList type_bases;
457 bool members_defined;
458 bool members_defined_ok;
460 // The interfaces we implement.
461 protected Type[] ifaces;
462 protected Type ptype;
464 // The base member cache and our member cache
465 MemberCache base_cache;
466 MemberCache member_cache;
468 public const string DefaultIndexerName = "Item";
471 GenericTypeParameterBuilder[] gen_params;
473 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
474 Attributes attrs, Kind kind)
475 : base (ns, parent, name, attrs)
477 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
478 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
482 types = new ArrayList ();
484 base_class_name = null;
487 public bool AddToMemberContainer (MemberCore symbol)
489 return AddToContainer (symbol, symbol.MemberName.MethodName);
492 protected virtual bool AddToTypeContainer (DeclSpace ds)
494 return AddToContainer (ds, ds.Basename);
497 public void AddConstant (Const constant)
499 if (!AddToMemberContainer (constant))
502 if (constants == null)
503 constants = new MemberCoreArrayList ();
505 constants.Add (constant);
508 public void AddEnum (Mono.CSharp.Enum e)
510 if (!AddToTypeContainer (e))
514 enums = new MemberCoreArrayList ();
519 public bool AddClassOrStruct (TypeContainer c)
521 if (!AddToTypeContainer (c))
528 public void AddDelegate (Delegate d)
530 if (!AddToTypeContainer (d))
533 if (delegates == null)
534 delegates = new MemberCoreArrayList ();
539 public void AddMethod (Method method)
541 if (!AddToMemberContainer (method))
545 methods = new MethodArrayList (this);
547 if (method.MemberName.Left != null)
548 methods.Insert (0, method);
550 methods.Add (method);
554 // Do not use this method: use AddMethod.
556 // This is only used by iterators.
558 public void AppendMethod (Method method)
560 if (!AddToMemberContainer (method))
564 methods = new MethodArrayList (this);
566 methods.Add (method);
569 public void AddConstructor (Constructor c)
571 if (c.Name != MemberName.Name) {
572 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
575 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
578 if (default_static_constructor != null) {
579 Report.SymbolRelatedToPreviousError (default_static_constructor);
580 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
584 default_static_constructor = c;
587 if (default_constructor != null) {
588 Report.SymbolRelatedToPreviousError (default_constructor);
589 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
592 default_constructor = c;
595 if (instance_constructors == null)
596 instance_constructors = new MemberCoreArrayList ();
598 instance_constructors.Add (c);
602 internal static string Error111 {
604 return "`{0}' is already defined. Rename this member or use different parameter types";
608 public bool AddInterface (TypeContainer iface)
610 if (!AddToTypeContainer (iface))
613 if (interfaces == null) {
614 interfaces = new MemberCoreArrayList ();
617 interfaces.Add (iface);
621 public void AddField (FieldMember field)
623 if (!AddToMemberContainer (field))
627 fields = new MemberCoreArrayList ();
631 if ((field.ModFlags & Modifiers.STATIC) != 0)
634 if (first_nonstatic_field == null) {
635 first_nonstatic_field = field;
639 if (Kind == Kind.Struct &&
640 first_nonstatic_field.Parent != field.Parent &&
641 RootContext.WarningLevel >= 3) {
642 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
643 Report.Warning (282, 3, field.Location,
644 "struct instance field `{0}' found in different declaration from instance field `{1}'",
645 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
649 public void AddProperty (Property prop)
651 if (!AddToMemberContainer (prop) ||
652 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
655 if (properties == null)
656 properties = new MemberCoreArrayList ();
658 if (prop.MemberName.Left != null)
659 properties.Insert (0, prop);
661 properties.Add (prop);
664 public void AddEvent (Event e)
666 if (!AddToMemberContainer (e))
669 if (e is EventProperty) {
670 if (!AddToMemberContainer (e.Add))
673 if (!AddToMemberContainer (e.Remove))
678 events = new MemberCoreArrayList ();
684 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
686 public void AddIndexer (Indexer i)
688 if (indexers == null)
689 indexers = new IndexerArrayList (this);
691 if (i.IsExplicitImpl)
692 indexers.Insert (0, i);
697 public void AddOperator (Operator op)
699 if (!AddToMemberContainer (op))
702 if (operators == null)
703 operators = new OperatorArrayList (this);
708 public void AddIterator (Iterator i)
710 if (iterators == null)
711 iterators = new ArrayList ();
716 public void AddType (TypeContainer tc)
721 public void AddPart (ClassPart part)
724 parts = new ArrayList ();
729 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
731 if (a.Type == TypeManager.default_member_type) {
732 if (Indexers != null) {
733 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
738 base.ApplyAttributeBuilder (a, cb);
741 public override AttributeTargets AttributeTargets {
745 return AttributeTargets.Class;
747 return AttributeTargets.Struct;
749 return AttributeTargets.Interface;
751 throw new NotSupportedException ();
756 public ArrayList Types {
762 public MethodArrayList Methods {
768 public ArrayList Constants {
774 public ArrayList Interfaces {
780 public ArrayList Iterators {
788 return base_class_name;
792 public ArrayList Bases {
802 public ArrayList Fields {
808 public ArrayList InstanceConstructors {
810 return instance_constructors;
814 public ArrayList Properties {
820 public ArrayList Events {
826 public ArrayList Enums {
832 public ArrayList Indexers {
838 public ArrayList Operators {
844 public ArrayList Delegates {
850 public ArrayList Parts {
856 protected override TypeAttributes TypeAttr {
858 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
862 public string IndexerName {
864 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
868 public bool IsComImport {
870 if (OptAttributes == null)
873 return OptAttributes.Contains (TypeManager.comimport_attr_type, EmitContext);
877 public virtual void RegisterFieldForInitialization (FieldBase field)
879 if ((field.ModFlags & Modifiers.STATIC) != 0){
880 if (initialized_static_fields == null)
881 initialized_static_fields = new ArrayList (4);
883 initialized_static_fields.Add (field);
885 if (initialized_fields == null)
886 initialized_fields = new ArrayList (4);
888 initialized_fields.Add (field);
893 // Emits the instance field initializers
895 public virtual bool EmitFieldInitializers (EmitContext ec)
900 fields = initialized_static_fields;
902 fields = initialized_fields;
908 foreach (FieldBase f in fields) {
909 f.EmitInitializer (ec);
915 // Defines the default constructors
917 protected void DefineDefaultConstructor (bool is_static)
921 // The default constructor is public
922 // If the class is abstract, the default constructor is protected
923 // The default static constructor is private
925 int mods = Modifiers.PUBLIC;
927 mods = Modifiers.STATIC | Modifiers.PRIVATE;
928 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
929 mods = Modifiers.PROTECTED;
931 TypeContainer constructor_parent = this;
933 constructor_parent = (TypeContainer) Parts [0];
935 c = new Constructor (constructor_parent, MemberName.Name, mods,
936 Parameters.EmptyReadOnlyParameters,
937 new GeneratedBaseInitializer (Location),
942 c.Block = new ToplevelBlock (null, Location);
947 /// The pending methods that need to be implemented
948 // (interfaces or abstract methods)
950 public PendingImplementation Pending;
952 public abstract PendingImplementation GetPendingImplementations ();
954 TypeExpr[] GetPartialBases (out TypeExpr base_class)
956 ArrayList ifaces = new ArrayList ();
960 foreach (ClassPart part in parts) {
961 TypeExpr new_base_class;
962 TypeExpr[] new_ifaces;
964 new_ifaces = part.GetClassBases (out new_base_class);
965 if (new_ifaces == null && new_base_class != null)
968 if ((base_class != null) && (new_base_class != null) &&
969 !base_class.Equals (new_base_class)) {
970 Report.SymbolRelatedToPreviousError (base_class.Location, "");
971 Report.Error (263, part.Location,
972 "Partial declarations of `{0}' must " +
973 "not specify different base classes",
979 if ((base_class == null) && (new_base_class != null)) {
980 base_class = new_base_class;
983 if (new_ifaces == null)
986 foreach (TypeExpr iface in new_ifaces) {
988 foreach (TypeExpr old_iface in ifaces) {
989 if (old_iface.Equals (iface)) {
1000 TypeExpr[] retval = new TypeExpr [ifaces.Count];
1001 ifaces.CopyTo (retval, 0);
1005 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1009 int count = Bases.Count;
1010 int start = 0, i, j;
1012 if (Kind == Kind.Class){
1013 TypeExpr name = ResolveBaseTypeExpr (
1014 (Expression) Bases [0], false, Location);
1020 if (!name.IsInterface) {
1021 // base_class could be a class, struct, enum, delegate.
1022 // This is validated in GetClassBases.
1028 TypeExpr [] ifaces = new TypeExpr [count-start];
1030 for (i = start, j = 0; i < count; i++, j++){
1031 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1032 if (resolved == null) {
1036 ifaces [j] = resolved;
1043 /// This function computes the Base class and also the
1044 /// list of interfaces that the class or struct @c implements.
1046 /// The return value is an array (might be null) of
1047 /// interfaces implemented (as Types).
1049 /// The @base_class argument is set to the base object or null
1050 /// if this is `System.Object'.
1052 protected virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1059 ifaces = GetPartialBases (out base_class);
1060 else if (Bases == null){
1064 ifaces = GetNormalBases (out base_class);
1069 if ((base_class != null) && (Kind == Kind.Class)){
1070 if (base_class is TypeParameterExpr){
1072 689, base_class.Location,
1073 "Cannot derive from `{0}' because it is a type parameter",
1074 base_class.GetSignatureForError ());
1079 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1080 Report.Error (1521, base_class.Location, "Invalid base type");
1084 if (base_class.IsSealed){
1085 Report.SymbolRelatedToPreviousError (base_class.Type);
1086 if (base_class.Type.IsAbstract) {
1087 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
1088 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1090 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
1091 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1096 if (!base_class.CanInheritFrom ()){
1097 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
1098 GetSignatureForError (), base_class.GetSignatureForError ());
1102 if (!base_class.AsAccessible (this, ModFlags)) {
1103 Report.SymbolRelatedToPreviousError (base_class.Type);
1104 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
1105 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1109 if (base_class != null)
1110 base_class_name = base_class.Name;
1115 int count = ifaces != null ? ifaces.Length : 0;
1117 for (i = 0; i < count; i++) {
1118 TypeExpr iface = (TypeExpr) ifaces [i];
1120 if (!iface.IsInterface) {
1121 if (Kind != Kind.Class) {
1122 // TODO: location of symbol related ....
1123 Error_TypeInListIsNotInterface (Location, iface.FullName);
1125 else if (base_class != null)
1126 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1127 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1129 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1130 GetSignatureForError (), iface.GetSignatureForError ());
1135 for (int x = 0; x < i; x++) {
1136 if (iface.Equals (ifaces [x])) {
1137 Report.Error (528, Location,
1138 "`{0}' is already listed in " +
1139 "interface list", iface.Name);
1144 if ((Kind == Kind.Interface) &&
1145 !iface.AsAccessible (Parent, ModFlags)) {
1146 Report.Error (61, Location,
1147 "Inconsistent accessibility: base " +
1148 "interface `{0}' is less accessible " +
1149 "than interface `{1}'", iface.Name,
1157 bool CheckGenericInterfaces (Type[] ifaces)
1159 ArrayList already_checked = new ArrayList ();
1161 for (int i = 0; i < ifaces.Length; i++) {
1162 Type iface = ifaces [i];
1163 foreach (Type t in already_checked) {
1167 Type[] infered = new Type [CountTypeParameters];
1168 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1171 Report.Error (695, Location,
1172 "`{0}' cannot implement both `{1}' and `{2}' " +
1173 "because they may unify for some type parameter substitutions",
1174 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1175 TypeManager.CSharpName (t));
1179 already_checked.Add (iface);
1187 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1189 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1193 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1195 public override TypeBuilder DefineType ()
1200 if (TypeBuilder != null)
1203 TypeAttributes type_attributes = TypeAttr;
1207 if (TypeManager.NamespaceClash (Name, Location)) {
1212 ModuleBuilder builder = CodeGen.Module.Builder;
1213 TypeBuilder = builder.DefineType (
1214 Name, type_attributes, null, null);
1216 TypeBuilder builder = Parent.TypeBuilder;
1217 if (builder == null) {
1222 TypeBuilder = builder.DefineNestedType (
1223 Basename, type_attributes, ptype, null);
1225 } catch (ArgumentException) {
1226 Report.RuntimeMissingSupport (Location, "static classes");
1231 TypeManager.AddUserType (this);
1233 if (Parts != null) {
1235 foreach (ClassPart part in Parts) {
1236 part.TypeBuilder = TypeBuilder;
1237 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1238 part.ec.ContainerType = TypeBuilder;
1242 // Normally, we create the EmitContext here.
1243 // The only exception is if we're an Iterator - in this case,
1244 // we already have the `ec', so we don't want to create a new one.
1247 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1248 ec.ContainerType = TypeBuilder;
1252 string[] param_names = new string [TypeParameters.Length];
1253 for (int i = 0; i < TypeParameters.Length; i++)
1254 param_names [i] = TypeParameters [i].Name;
1256 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1258 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1259 for (int i = offset; i < gen_params.Length; i++)
1260 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1263 iface_exprs = GetClassBases (out base_type);
1264 if (iface_exprs == null && base_type != null) {
1270 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1271 // which in turn should have called DefineType()s on base types if necessary.
1273 // None of the code below should trigger DefineType()s on classes that we depend on.
1274 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1276 // Let's do it as soon as possible, since code below can call DefineType() on classes
1277 // that depend on us to be populated before they are.
1279 if (!(this is Iterator))
1280 RootContext.RegisterOrder (this);
1282 if (base_type == null) {
1283 if (Kind == Kind.Class){
1284 if (RootContext.StdLib)
1285 base_type = TypeManager.system_object_expr;
1286 else if (Name != "System.Object")
1287 base_type = TypeManager.system_object_expr;
1288 } else if (Kind == Kind.Struct){
1290 // If we are compiling our runtime,
1291 // and we are defining ValueType, then our
1292 // base is `System.Object'.
1294 if (!RootContext.StdLib && Name == "System.ValueType")
1295 base_type = TypeManager.system_object_expr;
1296 else if (Kind == Kind.Struct)
1297 base_type = TypeManager.system_valuetype_expr;
1301 // Avoid attributes check when parent is not set
1302 TypeResolveEmitContext.TestObsoleteMethodUsage = false;
1304 if (base_type != null) {
1305 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1306 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1307 FullNamedExpression fne = base_type.ResolveAsTypeStep (TypeResolveEmitContext);
1308 if ((fne == null) || (fne.Type == null)) {
1315 if (IsGeneric && TypeManager.IsAttributeType (ptype)) {
1316 Report.Error (698, base_type.Location,
1317 "A generic type cannot derive from `{0}' " +
1318 "because it is an attribute class",
1325 if (!CheckRecursiveDefinition (this)) {
1330 if (ptype != null) {
1331 TypeBuilder.SetParent (ptype);
1334 // Attribute is undefined at the begining of corlib compilation
1335 if (TypeManager.obsolete_attribute_type != null) {
1336 TypeResolveEmitContext.TestObsoleteMethodUsage = GetObsoleteAttribute () == null;
1337 if (ptype != null && TypeResolveEmitContext.TestObsoleteMethodUsage) {
1338 CheckObsoleteType (base_type);
1342 // add interfaces that were not added at type creation
1343 if (iface_exprs != null) {
1344 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1345 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1346 TypeResolveEmitContext.ContainerType = TypeBuilder;
1347 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1348 if (ifaces == null) {
1353 foreach (Type itype in ifaces)
1354 TypeBuilder.AddInterfaceImplementation (itype);
1356 if (!CheckGenericInterfaces (ifaces)) {
1361 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1364 if (this is Iterator && !ResolveType ()) {
1369 if (!DefineNestedTypes ()) {
1377 public bool ResolveType ()
1379 if ((base_type != null) &&
1380 (base_type.ResolveType (TypeResolveEmitContext) == null)) {
1388 TypeExpr current_type = null;
1389 if (Parts != null) {
1390 foreach (ClassPart part in Parts) {
1391 if (!part.DefineTypeParameters ()) {
1397 foreach (TypeParameter type_param in CurrentTypeParameters) {
1398 if (!type_param.Resolve (this)) {
1404 foreach (TypeParameter type_param in TypeParameters) {
1405 if (!type_param.DefineType (ec)) {
1411 current_type = new ConstructedType (
1412 TypeBuilder, TypeParameters, Location);
1415 foreach (TypeParameter type_param in TypeParameters)
1416 if (!type_param.CheckDependencies (ec)) {
1421 if (current_type != null) {
1422 current_type = current_type.ResolveAsTypeTerminal (ec);
1423 if (current_type == null) {
1428 CurrentType = current_type.ResolveType (ec);
1434 protected virtual bool DefineNestedTypes ()
1436 if (Interfaces != null) {
1437 foreach (TypeContainer iface in Interfaces)
1438 if (iface.DefineType () == null)
1442 if (Types != null) {
1443 foreach (TypeContainer tc in Types)
1444 if (tc.DefineType () == null)
1448 if (Delegates != null) {
1449 foreach (Delegate d in Delegates)
1450 if (d.DefineType () == null)
1454 if (Enums != null) {
1455 foreach (Enum en in Enums)
1456 if (en.DefineType () == null)
1463 TypeContainer InTransit;
1465 protected bool CheckRecursiveDefinition (TypeContainer tc)
1467 if (InTransit != null) {
1468 Report.SymbolRelatedToPreviousError (this);
1469 if (this is Interface)
1471 529, tc.Location, "Inherited interface `{0}' causes a " +
1472 "cycle in the interface hierarchy of `{1}'",
1473 GetSignatureForError (), tc.GetSignatureForError ());
1476 146, tc.Location, "Circular base class dependency " +
1477 "involving `{0}' and `{1}'",
1478 tc.GetSignatureForError (), GetSignatureForError ());
1484 Type parent = ptype;
1485 if (parent != null) {
1486 parent = TypeManager.DropGenericTypeArguments (parent);
1487 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1488 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1492 if (iface_exprs != null) {
1493 foreach (TypeExpr iface in iface_exprs) {
1494 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1495 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1496 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1505 public static void Error_KeywordNotAllowed (Location loc)
1507 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1511 /// Populates our TypeBuilder with fields and methods
1513 public override bool DefineMembers ()
1515 if (members_defined)
1516 return members_defined_ok;
1518 if (!base.DefineMembers ())
1521 members_defined_ok = DoDefineMembers ();
1522 members_defined = true;
1524 return members_defined_ok;
1527 protected virtual bool DoDefineMembers ()
1529 if (iface_exprs != null) {
1530 foreach (TypeExpr iface in iface_exprs) {
1531 ConstructedType ct = iface as ConstructedType;
1532 if ((ct != null) && !ct.CheckConstraints (ec))
1537 if (base_type != null) {
1538 ConstructedType ct = base_type as ConstructedType;
1539 if ((ct != null) && !ct.CheckConstraints (ec))
1544 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1545 if (conflict_symbol == null) {
1546 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1547 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1549 if ((ModFlags & Modifiers.NEW) == 0) {
1550 Report.SymbolRelatedToPreviousError (conflict_symbol);
1551 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1552 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1557 DefineContainerMembers (constants);
1558 DefineContainerMembers (fields);
1560 if ((Kind == Kind.Class) && !(this is ClassPart)){
1561 if ((instance_constructors == null) &&
1562 !(this is StaticClass)) {
1563 if (default_constructor == null)
1564 DefineDefaultConstructor (false);
1567 if (initialized_static_fields != null &&
1568 default_static_constructor == null)
1569 DefineDefaultConstructor (true);
1572 if (Kind == Kind.Struct){
1574 // Structs can not have initialized instance
1577 if (initialized_static_fields != null &&
1578 default_static_constructor == null)
1579 DefineDefaultConstructor (true);
1581 if (initialized_fields != null)
1582 ReportStructInitializedInstanceError ();
1585 Pending = GetPendingImplementations ();
1587 if (parts != null) {
1588 foreach (ClassPart part in parts) {
1589 if (!part.DefineMembers ())
1595 // Constructors are not in the defined_names array
1597 DefineContainerMembers (instance_constructors);
1599 if (default_static_constructor != null)
1600 default_static_constructor.Define ();
1602 DefineContainerMembers (properties);
1603 DefineContainerMembers (events);
1604 DefineContainerMembers (indexers);
1605 DefineContainerMembers (methods);
1606 DefineContainerMembers (operators);
1607 DefineContainerMembers (enums);
1608 DefineContainerMembers (delegates);
1610 if (CurrentType != null) {
1611 GenericType = CurrentType;
1613 ec.ContainerType = GenericType;
1618 if (!(this is ClassPart))
1619 member_cache = new MemberCache (this);
1622 if (parts != null) {
1623 foreach (ClassPart part in parts)
1624 part.member_cache = member_cache;
1627 if (iterators != null) {
1628 foreach (Iterator iterator in iterators) {
1629 if (iterator.DefineType () == null)
1633 foreach (Iterator iterator in iterators) {
1634 if (!iterator.DefineMembers ())
1642 void ReportStructInitializedInstanceError ()
1644 foreach (Field f in initialized_fields){
1645 Report.Error (573, Location,
1646 "`{0}': Structs cannot have instance field initializers",
1647 f.GetSignatureForError ());
1651 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1654 mcal.DefineContainerMembers ();
1657 public override bool Define ()
1659 if (parts != null) {
1660 foreach (ClassPart part in parts) {
1661 if (!part.Define ())
1666 if (iterators != null) {
1667 foreach (Iterator iterator in iterators) {
1668 if (!iterator.Define ())
1676 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1678 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1682 /// This function is based by a delegate to the FindMembers routine
1684 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1690 /// This filter is used by FindMembers, and we just keep
1691 /// a global for the filter to `AlwaysAccept'
1693 static MemberFilter accepting_filter;
1696 static TypeContainer ()
1698 accepting_filter = new MemberFilter (AlwaysAccept);
1701 public MethodInfo[] GetMethods ()
1703 ArrayList members = new ArrayList ();
1707 if (methods != null) {
1708 int len = methods.Count;
1709 for (int i = 0; i < len; i++) {
1710 Method m = (Method) methods [i];
1712 members.Add (m.MethodBuilder);
1716 if (operators != null) {
1717 int len = operators.Count;
1718 for (int i = 0; i < len; i++) {
1719 Operator o = (Operator) operators [i];
1721 members.Add (o.OperatorMethodBuilder);
1725 if (properties != null) {
1726 int len = properties.Count;
1727 for (int i = 0; i < len; i++) {
1728 Property p = (Property) properties [i];
1730 if (p.GetBuilder != null)
1731 members.Add (p.GetBuilder);
1732 if (p.SetBuilder != null)
1733 members.Add (p.SetBuilder);
1737 if (indexers != null) {
1738 int len = indexers.Count;
1739 for (int i = 0; i < len; i++) {
1740 Indexer ix = (Indexer) indexers [i];
1742 if (ix.GetBuilder != null)
1743 members.Add (ix.GetBuilder);
1744 if (ix.SetBuilder != null)
1745 members.Add (ix.SetBuilder);
1749 if (events != null) {
1750 int len = events.Count;
1751 for (int i = 0; i < len; i++) {
1752 Event e = (Event) events [i];
1754 if (e.AddBuilder != null)
1755 members.Add (e.AddBuilder);
1756 if (e.RemoveBuilder != null)
1757 members.Add (e.RemoveBuilder);
1761 MethodInfo[] retMethods = new MethodInfo [members.Count];
1762 members.CopyTo (retMethods, 0);
1766 // Indicated whether container has StructLayout attribute set Explicit
1767 public virtual bool HasExplicitLayout {
1773 public override Type FindNestedType (string name)
1775 ArrayList [] lists = { types, enums, delegates, interfaces };
1777 for (int j = 0; j < lists.Length; ++j) {
1778 ArrayList list = lists [j];
1782 int len = list.Count;
1783 for (int i = 0; i < len; ++i) {
1784 DeclSpace ds = (DeclSpace) list [i];
1785 if (ds.Basename == name) {
1787 return ds.TypeBuilder;
1795 private void FindMembers_NestedTypes (int modflags,
1796 BindingFlags bf, MemberFilter filter, object criteria,
1797 ref ArrayList members)
1799 ArrayList [] lists = { types, enums, delegates, interfaces };
1801 for (int j = 0; j < lists.Length; ++j) {
1802 ArrayList list = lists [j];
1806 int len = list.Count;
1807 for (int i = 0; i < len; i++) {
1808 DeclSpace ds = (DeclSpace) list [i];
1810 if ((ds.ModFlags & modflags) == 0)
1813 TypeBuilder tb = ds.TypeBuilder;
1815 if (!(criteria is string) || ds.Basename.Equals (criteria))
1816 tb = ds.DefineType ();
1819 if (tb != null && (filter (tb, criteria) == true)) {
1820 if (members == null)
1821 members = new ArrayList ();
1830 /// This method returns the members of this type just like Type.FindMembers would
1831 /// Only, we need to use this for types which are _being_ defined because MS'
1832 /// implementation can't take care of that.
1835 // FIXME: return an empty static array instead of null, that cleans up
1836 // some code and is consistent with some coding conventions I just found
1840 // Notice that in various cases we check if our field is non-null,
1841 // something that would normally mean that there was a bug elsewhere.
1843 // The problem happens while we are defining p-invoke methods, as those
1844 // will trigger a FindMembers, but this happens before things are defined
1846 // Since the whole process is a no-op, it is fine to check for null here.
1848 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1849 MemberFilter filter, object criteria)
1851 ArrayList members = null;
1854 if ((bf & BindingFlags.Public) != 0)
1855 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1857 if ((bf & BindingFlags.NonPublic) != 0)
1858 modflags |= Modifiers.PRIVATE;
1860 int static_mask = 0, static_flags = 0;
1861 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1862 case BindingFlags.Static:
1863 static_mask = static_flags = Modifiers.STATIC;
1866 case BindingFlags.Instance:
1867 static_mask = Modifiers.STATIC;
1872 static_mask = static_flags = 0;
1876 Timer.StartTimer (TimerType.TcFindMembers);
1879 filter = accepting_filter;
1881 if ((mt & MemberTypes.Field) != 0) {
1882 if (fields != null) {
1883 int len = fields.Count;
1884 for (int i = 0; i < len; i++) {
1885 FieldMember f = (FieldMember) fields [i];
1887 if ((f.ModFlags & modflags) == 0)
1889 if ((f.ModFlags & static_mask) != static_flags)
1892 FieldBuilder fb = f.FieldBuilder;
1893 if (fb != null && filter (fb, criteria) == true) {
1894 if (members == null)
1895 members = new ArrayList ();
1902 if (constants != null) {
1903 int len = constants.Count;
1904 for (int i = 0; i < len; i++) {
1905 Const con = (Const) constants [i];
1907 if ((con.ModFlags & modflags) == 0)
1909 if ((con.ModFlags & static_mask) != static_flags)
1912 FieldBuilder fb = con.FieldBuilder;
1915 fb = con.FieldBuilder;
1917 if (fb != null && filter (fb, criteria) == true) {
1918 if (members == null)
1919 members = new ArrayList ();
1927 if ((mt & MemberTypes.Method) != 0) {
1928 if (methods != null) {
1929 int len = methods.Count;
1930 for (int i = 0; i < len; i++) {
1931 Method m = (Method) methods [i];
1933 if ((m.ModFlags & modflags) == 0)
1935 if ((m.ModFlags & static_mask) != static_flags)
1938 MethodBuilder mb = m.MethodBuilder;
1940 if (mb != null && filter (mb, criteria) == true) {
1941 if (members == null)
1942 members = new ArrayList ();
1949 if (operators != null) {
1950 int len = operators.Count;
1951 for (int i = 0; i < len; i++) {
1952 Operator o = (Operator) operators [i];
1954 if ((o.ModFlags & modflags) == 0)
1956 if ((o.ModFlags & static_mask) != static_flags)
1959 MethodBuilder ob = o.OperatorMethodBuilder;
1960 if (ob != null && filter (ob, criteria) == true) {
1961 if (members == null)
1962 members = new ArrayList ();
1969 if (properties != null) {
1970 int len = properties.Count;
1971 for (int i = 0; i < len; i++) {
1972 Property p = (Property) properties [i];
1974 if ((p.ModFlags & modflags) == 0)
1976 if ((p.ModFlags & static_mask) != static_flags)
1982 if (b != null && filter (b, criteria) == true) {
1983 if (members == null)
1984 members = new ArrayList ();
1990 if (b != null && filter (b, criteria) == true) {
1991 if (members == null)
1992 members = new ArrayList ();
1999 if (indexers != null) {
2000 int len = indexers.Count;
2001 for (int i = 0; i < len; i++) {
2002 Indexer ix = (Indexer) indexers [i];
2004 if ((ix.ModFlags & modflags) == 0)
2006 if ((ix.ModFlags & static_mask) != static_flags)
2012 if (b != null && filter (b, criteria) == true) {
2013 if (members == null)
2014 members = new ArrayList ();
2020 if (b != null && filter (b, criteria) == true) {
2021 if (members == null)
2022 members = new ArrayList ();
2030 if ((mt & MemberTypes.Event) != 0) {
2031 if (events != null) {
2032 int len = events.Count;
2033 for (int i = 0; i < len; i++) {
2034 Event e = (Event) events [i];
2036 if ((e.ModFlags & modflags) == 0)
2038 if ((e.ModFlags & static_mask) != static_flags)
2041 MemberInfo eb = e.EventBuilder;
2042 if (eb != null && filter (eb, criteria) == true) {
2043 if (members == null)
2044 members = new ArrayList ();
2046 members.Add (e.EventBuilder);
2052 if ((mt & MemberTypes.Property) != 0){
2053 if (properties != null) {
2054 int len = properties.Count;
2055 for (int i = 0; i < len; i++) {
2056 Property p = (Property) properties [i];
2058 if ((p.ModFlags & modflags) == 0)
2060 if ((p.ModFlags & static_mask) != static_flags)
2063 MemberInfo pb = p.PropertyBuilder;
2064 if (pb != null && filter (pb, criteria) == true) {
2065 if (members == null)
2066 members = new ArrayList ();
2068 members.Add (p.PropertyBuilder);
2073 if (indexers != null) {
2074 int len = indexers.Count;
2075 for (int i = 0; i < len; i++) {
2076 Indexer ix = (Indexer) indexers [i];
2078 if ((ix.ModFlags & modflags) == 0)
2080 if ((ix.ModFlags & static_mask) != static_flags)
2083 MemberInfo ib = ix.PropertyBuilder;
2084 if (ib != null && filter (ib, criteria) == true) {
2085 if (members == null)
2086 members = new ArrayList ();
2088 members.Add (ix.PropertyBuilder);
2094 if ((mt & MemberTypes.NestedType) != 0)
2095 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2097 if ((mt & MemberTypes.Constructor) != 0){
2098 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2099 int len = instance_constructors.Count;
2100 for (int i = 0; i < len; i++) {
2101 Constructor c = (Constructor) instance_constructors [i];
2103 ConstructorBuilder cb = c.ConstructorBuilder;
2104 if (cb != null && filter (cb, criteria) == true) {
2105 if (members == null)
2106 members = new ArrayList ();
2113 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2114 ConstructorBuilder cb =
2115 default_static_constructor.ConstructorBuilder;
2117 if (cb != null && filter (cb, criteria) == true) {
2118 if (members == null)
2119 members = new ArrayList ();
2127 // Lookup members in base if requested.
2129 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2130 if (TypeBuilder.BaseType != null) {
2131 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2132 if (list.Count > 0) {
2133 if (members == null)
2134 members = new ArrayList ();
2136 members.AddRange (list);
2142 Timer.StopTimer (TimerType.TcFindMembers);
2144 if (members == null)
2145 return MemberList.Empty;
2147 return new MemberList (members);
2150 public override MemberCache MemberCache {
2152 return member_cache;
2156 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2157 MemberFilter filter, object criteria)
2159 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2162 return ds.FindMembers (mt, bf, filter, criteria);
2164 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2168 // FindMethods will look for methods not only in the type `t', but in
2169 // any interfaces implemented by the type.
2171 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2172 MemberFilter filter, object criteria)
2178 /// Emits the values for the constants
2180 public void EmitConstants ()
2182 if (constants != null)
2183 foreach (Const con in constants)
2188 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2193 foreach (MemberCore mc in al) {
2194 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2198 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2203 public virtual void VerifyMembers ()
2206 // Check for internal or private fields that were never assigned
2208 if (RootContext.WarningLevel >= 3) {
2209 CheckMemberUsage (properties, "property");
2210 CheckMemberUsage (methods, "method");
2211 CheckMemberUsage (constants, "constant");
2213 if (fields != null){
2214 foreach (FieldMember f in fields) {
2215 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2219 if ((f.caching_flags & Flags.IsAssigned) == 0)
2220 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2223 const int error_code = 414;
2225 const int error_code = 169;
2227 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2228 f.GetSignatureForError ());
2234 // Only report 649 on level 4
2236 if (RootContext.WarningLevel < 4)
2239 if ((f.caching_flags & Flags.IsAssigned) != 0)
2242 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2243 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2250 /// Emits the code, this step is performed after all
2251 /// the types, enumerations, constructors
2253 public virtual void EmitType ()
2255 if (OptAttributes != null)
2256 OptAttributes.Emit (ec, this);
2258 if (IsGeneric && !(this is ClassPart)) {
2259 int offset = CountTypeParameters - CurrentTypeParameters.Length;
2260 for (int i = offset; i < gen_params.Length; i++)
2261 CurrentTypeParameters [i - offset].EmitAttributes (ec);
2265 // Structs with no fields need to have at least one byte.
2266 // The right thing would be to set the PackingSize in a DefineType
2267 // but there are no functions that allow interfaces *and* the size to
2271 if (Kind == Kind.Struct && first_nonstatic_field == null){
2272 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2273 FieldAttributes.Private);
2275 if (HasExplicitLayout){
2276 object [] ctor_args = new object [1];
2279 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2280 TypeManager.field_offset_attribute_ctor, ctor_args);
2281 fb.SetCustomAttribute (cba);
2287 if (instance_constructors != null) {
2288 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired (this)) {
2289 bool has_compliant_args = false;
2291 foreach (Constructor c in instance_constructors) {
2294 if (has_compliant_args)
2297 has_compliant_args = c.HasCompliantArgs;
2299 if (!has_compliant_args)
2300 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2302 foreach (Constructor c in instance_constructors)
2307 // Can not continue if constants are broken
2309 if (Report.Errors > 0)
2312 if (default_static_constructor != null)
2313 default_static_constructor.Emit ();
2315 if (methods != null){
2316 foreach (Method m in methods)
2320 if (operators != null)
2321 foreach (Operator o in operators)
2324 if (properties != null)
2325 foreach (Property p in properties)
2328 if (indexers != null){
2333 foreach (FieldMember f in fields)
2336 if (events != null){
2337 foreach (Event e in Events)
2341 if (delegates != null) {
2342 foreach (Delegate d in Delegates) {
2347 if (enums != null) {
2348 foreach (Enum e in enums) {
2353 if (parts != null) {
2354 foreach (ClassPart part in parts)
2358 if ((Pending != null) && !(this is ClassPart))
2359 if (Pending.VerifyPendingMethods ())
2362 if (iterators != null)
2363 foreach (Iterator iterator in iterators)
2364 iterator.EmitType ();
2366 // if (types != null)
2367 // foreach (TypeContainer tc in types)
2371 public override void CloseType ()
2373 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2377 caching_flags |= Flags.CloseTypeCreated;
2378 TypeBuilder.CreateType ();
2379 } catch (TypeLoadException){
2381 // This is fine, the code still created the type
2383 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2384 // Console.WriteLine (e.Message);
2386 Console.WriteLine ("In type: " + Name);
2391 foreach (Enum en in Enums)
2395 foreach (TypeContainer tc in Types)
2396 if (tc.Kind == Kind.Struct)
2399 foreach (TypeContainer tc in Types)
2400 if (tc.Kind != Kind.Struct)
2404 if (Delegates != null)
2405 foreach (Delegate d in Delegates)
2408 if (Iterators != null)
2409 foreach (Iterator i in Iterators)
2417 initialized_fields = null;
2418 initialized_static_fields = null;
2427 default_constructor = null;
2428 default_static_constructor = null;
2430 OptAttributes = null;
2433 member_cache = null;
2437 // Performs the validation on a Method's modifiers (properties have
2438 // the same properties).
2440 public bool MethodModifiersValid (MemberCore mc)
2442 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2443 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2444 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2446 int flags = mc.ModFlags;
2449 // At most one of static, virtual or override
2451 if ((flags & Modifiers.STATIC) != 0){
2452 if ((flags & vao) != 0){
2453 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2454 mc.GetSignatureForError ());
2459 if (Kind == Kind.Struct){
2460 if ((flags & va) != 0){
2461 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2466 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2467 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2468 mc.GetSignatureForError ());
2473 // If the declaration includes the abstract modifier, then the
2474 // declaration does not include static, virtual or extern
2476 if ((flags & Modifiers.ABSTRACT) != 0){
2477 if ((flags & Modifiers.EXTERN) != 0){
2479 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2483 if ((flags & Modifiers.SEALED) != 0) {
2484 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2488 if ((flags & Modifiers.VIRTUAL) != 0){
2489 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2493 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2494 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2499 if ((flags & Modifiers.PRIVATE) != 0){
2500 if ((flags & vao) != 0){
2501 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2506 if ((flags & Modifiers.SEALED) != 0){
2507 if ((flags & Modifiers.OVERRIDE) == 0){
2508 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2516 public bool UserDefinedStaticConstructor {
2518 return default_static_constructor != null;
2522 public Constructor DefaultStaticConstructor {
2523 get { return default_static_constructor; }
2526 protected override bool VerifyClsCompliance (DeclSpace ds)
2528 if (!base.VerifyClsCompliance (ds))
2533 Type base_type = TypeBuilder.BaseType;
2534 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2535 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2538 if (!Parent.IsClsComplianceRequired (ds)) {
2539 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
2540 GetSignatureForError (), Parent.GetSignatureForError ());
2547 /// Checks whether container name is CLS Compliant
2549 void VerifyClsName ()
2551 Hashtable base_members = base_cache == null ?
2553 base_cache.GetPublicMembers ();
2554 Hashtable this_members = new Hashtable ();
2556 foreach (DictionaryEntry entry in defined_names) {
2557 MemberCore mc = (MemberCore)entry.Value;
2558 if (!mc.IsClsComplianceRequired (mc.Parent))
2561 string name = (string) entry.Key;
2562 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2564 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2565 object found = base_members [lcase];
2566 if (found == null) {
2567 found = this_members [lcase];
2568 if (found == null) {
2569 this_members.Add (lcase, mc);
2574 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2577 if (found is MemberInfo) {
2578 if (basename == ((MemberInfo) found).Name)
2580 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2582 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2584 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2590 /// Performs checks for an explicit interface implementation. First it
2591 /// checks whether the `interface_type' is a base inteface implementation.
2592 /// Then it checks whether `name' exists in the interface type.
2594 public virtual bool VerifyImplements (MemberBase mb)
2596 if (ifaces != null) {
2597 foreach (Type t in ifaces){
2598 if (t == mb.InterfaceType)
2603 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2604 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2608 public virtual void Mark_HasEquals ()
2610 Methods.HasEquals = true;
2613 public virtual void Mark_HasGetHashCode ()
2615 Methods.HasGetHashCode = true;
2622 string IMemberContainer.Name {
2628 Type IMemberContainer.Type {
2634 MemberCache IMemberContainer.MemberCache {
2636 return member_cache;
2640 bool IMemberContainer.IsInterface {
2642 return Kind == Kind.Interface;
2646 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2648 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2650 if (GenericType != null)
2651 return TypeManager.FindMembers (GenericType, mt, new_bf,
2654 return FindMembers (mt, new_bf, null, null);
2658 // Generates xml doc comments (if any), and if required,
2659 // handle warning report.
2661 internal override void GenerateDocComment (DeclSpace ds)
2663 DocUtil.GenerateTypeDocComment (this, ds);
2666 public override string DocCommentHeader {
2667 get { return "T:"; }
2670 public virtual MemberCache BaseCache {
2672 if (base_cache != null)
2674 if (TypeBuilder.BaseType != null)
2675 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2676 if (TypeBuilder.IsInterface)
2677 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2684 public class PartialContainer : TypeContainer {
2686 public readonly Namespace Namespace;
2687 public readonly int OriginalModFlags;
2688 public readonly int AllowedModifiers;
2689 public readonly TypeAttributes DefaultTypeAttributes;
2690 public ListDictionary DeclarativeSecurity;
2692 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2693 MemberName member_name, int mod_flags, Kind kind)
2696 if (!CheckModFlags (0, mod_flags, member_name))
2699 PartialContainer pc = RootContext.Tree.GetDecl (member_name) as PartialContainer;
2701 if (pc.Kind != kind) {
2703 261, member_name.Location,
2704 "Partial declarations of `{0}' must be all classes, " +
2705 "all structs or all interfaces",
2706 member_name.GetTypeName ());
2710 if (!CheckModFlags (pc.OriginalModFlags, mod_flags, member_name))
2712 pc.ModFlags |= (mod_flags & pc.AllowedModifiers);
2715 if (pc.CountTypeParameters != member_name.CountTypeArguments) {
2717 264, member_name.Location,
2718 "Partial declarations of `{0}' must have the " +
2719 "same type parameter names in the same order",
2720 member_name.GetTypeName ());
2724 TypeParameterName[] pc_names = pc.MemberName.TypeArguments.GetDeclarations ();
2725 TypeParameterName[] names = member_name.TypeArguments.GetDeclarations ();
2727 for (int i = 0; i < pc.CountTypeParameters; i++) {
2728 if (pc_names [i].Name == names [i].Name)
2732 264, member_name.Location,
2733 "Partial declarations of `{0}' must have the " +
2734 "same type parameter names in the same order",
2735 member_name.GetTypeName ());
2743 if (parent is ClassPart)
2744 parent = ((ClassPart) parent).PartialContainer;
2746 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind);
2748 if (kind == Kind.Interface) {
2749 if (!parent.AddInterface (pc))
2751 } else if (kind == Kind.Class || kind == Kind.Struct) {
2752 if (!parent.AddClassOrStruct (pc))
2755 throw new InvalidOperationException ();
2757 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2758 // This is needed to define our type parameters; we define the constraints later.
2759 pc.SetParameterInfo (null);
2763 static bool CheckModFlags (int flags_org, int flags, MemberName member_name)
2765 // Check (abstract|static|sealed) sanity.
2766 int tmp = (flags_org | flags) & (Modifiers.ABSTRACT | Modifiers.SEALED | Modifiers.STATIC);
2767 if ((tmp & Modifiers.ABSTRACT) != 0) {
2768 if ((tmp & (Modifiers.STATIC | Modifiers.SEALED)) != 0) {
2770 418, member_name.Location,
2771 "`{0}': an abstract class cannot be sealed or static", member_name.ToString ());
2774 } else if (tmp == (Modifiers.SEALED | Modifiers.STATIC)) {
2775 Report.Error (441, member_name.Location, "`{0}': a class cannot be both static and sealed", member_name.ToString ());
2783 if (0 != ((flags_org ^ flags) & (0xFFFFFFFF ^ (Modifiers.SEALED | Modifiers.ABSTRACT)))) {
2785 262, member_name.Location, "Partial declarations of `{0}' " +
2786 "have conflicting accessibility modifiers",
2787 member_name.GetName ());
2793 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2794 MemberName name, int mod, Attributes attrs,
2795 Kind kind, Location loc)
2797 PartialContainer pc = Create (ns, parent, name, mod, kind);
2799 // An error occured; create a dummy container, but don't
2801 pc = new PartialContainer (ns.NS, parent, name, mod, kind);
2804 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind);
2809 protected PartialContainer (Namespace ns, TypeContainer parent,
2810 MemberName name, int mod, Kind kind)
2811 : base (null, parent, name, null, kind)
2813 this.Namespace = ns;
2817 AllowedModifiers = Class.AllowedModifiers;
2818 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2822 AllowedModifiers = Struct.AllowedModifiers;
2823 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2826 case Kind.Interface:
2827 AllowedModifiers = Interface.AllowedModifiers;
2828 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2832 throw new InvalidOperationException ();
2836 if (parent.Parent == null)
2837 accmods = Modifiers.INTERNAL;
2839 accmods = Modifiers.PRIVATE;
2841 // FIXME: remove this nasty fix for bug #77370 when
2842 // we get good AllowModifiersProp implementation.
2843 if ((mod & Modifiers.STATIC) != 0) {
2844 AllowedModifiers |= Modifiers.STATIC;
2845 AllowedModifiers &= ~ (Modifiers.ABSTRACT | Modifiers.SEALED);
2848 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2849 this.OriginalModFlags = mod;
2852 public override void EmitType ()
2856 if (DeclarativeSecurity != null) {
2857 foreach (DictionaryEntry de in DeclarativeSecurity) {
2858 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2863 public override PendingImplementation GetPendingImplementations ()
2865 return PendingImplementation.GetPendingImplementations (this);
2868 public override bool MarkForDuplicationCheck ()
2873 protected override TypeAttributes TypeAttr {
2875 return base.TypeAttr | DefaultTypeAttributes;
2880 public class ClassPart : TypeContainer, IMemberContainer {
2881 public readonly PartialContainer PartialContainer;
2882 public readonly bool IsPartial;
2884 Constraints[] constraints;
2886 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2887 int mod, Attributes attrs, Kind kind)
2888 : base (ns, parent, pc.MemberName, attrs, kind)
2890 this.PartialContainer = pc;
2891 this.IsPartial = true;
2894 if (parent == null || parent == RootContext.Tree.Types)
2895 accmods = Modifiers.INTERNAL;
2897 accmods = Modifiers.PRIVATE;
2899 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, pc.MemberName.Location);
2902 constraints = new Constraints [pc.CountCurrentTypeParameters];
2905 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2907 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2908 if (PartialContainer.DeclarativeSecurity == null)
2909 PartialContainer.DeclarativeSecurity = new ListDictionary ();
2911 a.ExtractSecurityPermissionSet (PartialContainer.DeclarativeSecurity);
2915 base.ApplyAttributeBuilder (a, cb);
2918 public override PendingImplementation GetPendingImplementations ()
2920 return PartialContainer.Pending;
2923 public override bool VerifyImplements (MemberBase mb)
2925 return PartialContainer.VerifyImplements (mb);
2928 public override void SetParameterInfo (ArrayList constraints_list)
2930 if (constraints_list == null)
2933 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2934 for (int i = 0; i < constraints.Length; i++) {
2935 foreach (Constraints constraint in constraints_list) {
2936 if (constraint.TypeParameter == current_params [i].Name) {
2937 constraints [i] = constraint;
2944 public bool DefineTypeParameters ()
2946 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2948 for (int i = 0; i < current_params.Length; i++) {
2949 Constraints new_constraints = constraints [i];
2950 if (new_constraints == null)
2953 if (!current_params [i].UpdateConstraints (ec, new_constraints)) {
2954 Report.Error (265, Location, "Partial declarations of `{0}' have " +
2955 "inconsistent constraints for type parameter `{1}'.",
2956 MemberName.GetTypeName (), current_params [i].Name);
2961 for (int i = 0; i < current_params.Length; i++) {
2962 if (!current_params [i].Resolve (this))
2966 foreach (TypeParameter type_param in PartialContainer.TypeParameters) {
2967 if (!type_param.DefineType (ec))
2974 public override void RegisterFieldForInitialization (FieldBase field)
2976 PartialContainer.RegisterFieldForInitialization (field);
2979 public override bool EmitFieldInitializers (EmitContext ec)
2981 return PartialContainer.EmitFieldInitializers (ec);
2984 public override Type FindNestedType (string name)
2986 return PartialContainer.FindNestedType (name);
2989 public override MemberCache BaseCache {
2991 return PartialContainer.BaseCache;
2995 public override TypeBuilder DefineType ()
2997 throw new InternalErrorException ("Should not get here");
3000 public override void Mark_HasEquals ()
3002 PartialContainer.Mark_HasEquals ();
3005 public override void Mark_HasGetHashCode ()
3007 PartialContainer.Mark_HasGetHashCode ();
3011 public abstract class ClassOrStruct : TypeContainer {
3012 bool has_explicit_layout = false;
3013 ListDictionary declarative_security;
3015 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
3016 MemberName name, Attributes attrs, Kind kind)
3017 : base (ns, parent, name, attrs, kind)
3021 public override PendingImplementation GetPendingImplementations ()
3023 return PendingImplementation.GetPendingImplementations (this);
3026 public override bool HasExplicitLayout {
3028 return has_explicit_layout;
3032 public override void VerifyMembers ()
3034 base.VerifyMembers ();
3036 if ((events != null) && (RootContext.WarningLevel >= 3)) {
3037 foreach (Event e in events){
3038 if ((e.caching_flags & Flags.IsAssigned) == 0)
3039 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
3044 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3046 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3047 if (declarative_security == null)
3048 declarative_security = new ListDictionary ();
3050 a.ExtractSecurityPermissionSet (declarative_security);
3054 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
3055 has_explicit_layout = true;
3057 base.ApplyAttributeBuilder (a, cb);
3060 public override void Emit()
3064 if (declarative_security != null) {
3065 foreach (DictionaryEntry de in declarative_security) {
3066 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3073 /// Class handles static classes declaration
3075 public sealed class StaticClass: Class {
3076 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3078 : base (ns, parent, name, mod, attrs)
3080 if (RootContext.Version == LanguageVersion.ISO_1) {
3081 Report.FeatureIsNotStandardized (Location, "static classes");
3085 protected override int AllowedModifiersProp {
3087 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
3088 Modifiers.STATIC | Modifiers.UNSAFE;
3092 protected override void DefineContainerMembers (MemberCoreArrayList list)
3097 foreach (MemberCore m in list) {
3098 if (m is Operator) {
3099 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
3103 if (m is Destructor) {
3104 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
3108 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
3109 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
3114 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
3118 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
3121 if (m is Constructor) {
3122 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
3126 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
3129 base.DefineContainerMembers (list);
3132 public override TypeBuilder DefineType()
3134 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
3135 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
3139 TypeBuilder tb = base.DefineType ();
3143 if (ptype != TypeManager.object_type) {
3144 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
3148 if (ifaces != null) {
3149 foreach (Type t in ifaces)
3150 Report.SymbolRelatedToPreviousError (t);
3151 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
3156 protected override TypeAttributes TypeAttr {
3158 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
3163 public class Class : ClassOrStruct {
3164 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
3165 public const int AllowedModifiers =
3168 Modifiers.PROTECTED |
3169 Modifiers.INTERNAL |
3171 Modifiers.ABSTRACT |
3175 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3177 : base (ns, parent, name, attrs, Kind.Class)
3179 this.ModFlags = mod;
3182 virtual protected int AllowedModifiersProp {
3184 return AllowedModifiers;
3188 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
3190 if (a.Type == TypeManager.attribute_usage_type) {
3191 if (ptype != TypeManager.attribute_type &&
3192 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
3193 TypeBuilder.FullName != "System.Attribute") {
3194 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
3198 if (a.Type == TypeManager.conditional_attribute_type &&
3199 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
3200 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
3204 if (AttributeTester.IsAttributeExcluded (a.Type))
3207 base.ApplyAttributeBuilder (a, cb);
3210 public const TypeAttributes DefaultTypeAttributes =
3211 TypeAttributes.AutoLayout | TypeAttributes.Class;
3213 public override TypeBuilder DefineType()
3215 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
3216 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
3220 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
3221 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
3223 return base.DefineType ();
3226 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3227 /// Valid only for attribute classes.
3228 public bool IsExcluded ()
3230 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3231 return (caching_flags & Flags.Excluded) != 0;
3233 caching_flags &= ~Flags.Excluded_Undetected;
3235 if (OptAttributes == null)
3238 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3243 foreach (Attribute a in attrs) {
3244 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3245 if (RootContext.AllDefines.Contains (condition))
3249 caching_flags |= Flags.Excluded;
3254 // FIXME: How do we deal with the user specifying a different
3257 protected override TypeAttributes TypeAttr {
3259 return base.TypeAttr | DefaultTypeAttributes;
3264 public class Struct : ClassOrStruct {
3266 // Modifiers allowed in a struct declaration
3268 public const int AllowedModifiers =
3271 Modifiers.PROTECTED |
3272 Modifiers.INTERNAL |
3276 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
3277 int mod, Attributes attrs)
3278 : base (ns, parent, name, attrs, Kind.Struct)
3282 if (parent.Parent == null)
3283 accmods = Modifiers.INTERNAL;
3285 accmods = Modifiers.PRIVATE;
3287 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3289 this.ModFlags |= Modifiers.SEALED;
3292 public const TypeAttributes DefaultTypeAttributes =
3293 TypeAttributes.SequentialLayout |
3294 TypeAttributes.Sealed |
3295 TypeAttributes.BeforeFieldInit;
3298 // FIXME: Allow the user to specify a different set of attributes
3299 // in some cases (Sealed for example is mandatory for a class,
3300 // but what SequentialLayout can be changed
3302 protected override TypeAttributes TypeAttr {
3304 return base.TypeAttr | DefaultTypeAttributes;
3312 public class Interface : TypeContainer, IMemberContainer {
3315 /// Modifiers allowed in a class declaration
3317 public const int AllowedModifiers =
3320 Modifiers.PROTECTED |
3321 Modifiers.INTERNAL |
3325 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3327 : base (ns, parent, name, attrs, Kind.Interface)
3331 if (parent.Parent == null)
3332 accmods = Modifiers.INTERNAL;
3334 accmods = Modifiers.PRIVATE;
3336 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3339 public override PendingImplementation GetPendingImplementations ()
3344 public const TypeAttributes DefaultTypeAttributes =
3345 TypeAttributes.AutoLayout |
3346 TypeAttributes.Abstract |
3347 TypeAttributes.Interface;
3349 protected override TypeAttributes TypeAttr {
3351 return base.TypeAttr | DefaultTypeAttributes;
3355 protected override bool VerifyClsCompliance (DeclSpace ds)
3357 if (!base.VerifyClsCompliance (ds))
3360 if (ifaces != null) {
3361 foreach (Type t in ifaces) {
3362 if (AttributeTester.IsClsCompliant (t))
3365 Report.SymbolRelatedToPreviousError (t);
3366 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3367 GetSignatureForError (), TypeManager.CSharpName (t));
3375 public abstract class MethodCore : MemberBase {
3376 public readonly Parameters Parameters;
3377 protected ToplevelBlock block;
3379 // Whether this is an operator method.
3380 public Operator IsOperator;
3383 // The method we're overriding if this is an override method.
3385 protected MethodInfo base_method = null;
3387 static string[] attribute_targets = new string [] { "method", "return" };
3389 public MethodCore (TypeContainer parent, GenericMethod generic,
3390 Expression type, int mod, int allowed_mod, bool is_iface,
3391 MemberName name, Attributes attrs, Parameters parameters)
3392 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3395 Parameters = parameters;
3396 IsInterface = is_iface;
3400 // Returns the System.Type array for the parameters of this method
3402 public Type [] ParameterTypes {
3404 return Parameters.Types;
3408 public Parameters ParameterInfo
3415 public override EmitContext EmitContext {
3416 get { return ds.EmitContext; }
3419 public ToplevelBlock Block {
3429 public void SetYields ()
3431 ModFlags |= Modifiers.METHOD_YIELDS;
3434 protected override bool CheckBase ()
3436 if (!base.CheckBase ())
3439 // Check whether arguments were correct.
3440 if (!DoDefineParameters ())
3443 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3449 // Is null for System.Object while compiling corlib and base interfaces
3450 if (Parent.BaseCache == null) {
3451 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3452 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3457 Type base_ret_type = null;
3458 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3460 // method is override
3461 if (base_method != null) {
3463 if (!CheckMethodAgainstBase ())
3466 if ((ModFlags & Modifiers.NEW) == 0) {
3467 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_ret_type))) {
3468 Report.SymbolRelatedToPreviousError (base_method);
3469 if (this is PropertyBase) {
3470 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3471 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3474 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3475 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3480 if (base_method.IsAbstract && !IsInterface) {
3481 Report.SymbolRelatedToPreviousError (base_method);
3482 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3483 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3488 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3489 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3493 if (Name == "Equals" && Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type)
3494 Parent.Mark_HasEquals ();
3495 else if (Name == "GetHashCode" && Parameters.Empty)
3496 Parent.Mark_HasGetHashCode ();
3498 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3499 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3501 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3502 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3503 Report.SymbolRelatedToPreviousError (base_method);
3504 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3505 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3512 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3513 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3514 if (conflict_symbol != null) {
3515 Report.SymbolRelatedToPreviousError (conflict_symbol);
3516 if (this is PropertyBase)
3517 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3519 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3521 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3525 if (conflict_symbol == null) {
3526 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3527 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3532 if ((ModFlags & Modifiers.NEW) == 0) {
3533 if (this is Method && conflict_symbol is MethodBase)
3536 Report.SymbolRelatedToPreviousError (conflict_symbol);
3537 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3538 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3545 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3546 // that have been defined.
3548 // `name' is the user visible name for reporting errors (this is used to
3549 // provide the right name regarding method names and properties)
3551 bool CheckMethodAgainstBase ()
3555 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3556 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3557 Report.Error (506, Location,
3558 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3559 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3563 // Now we check that the overriden method is not final
3565 if (base_method.IsFinal) {
3566 Report.SymbolRelatedToPreviousError (base_method);
3567 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3568 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3572 // Check that the permissions are not being changed
3574 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3575 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3577 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3578 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3583 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3584 ModFlags |= Modifiers.NEW;
3585 Report.SymbolRelatedToPreviousError (base_method);
3586 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3587 Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
3588 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3590 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3591 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3598 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3600 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3602 // when overriding protected internal, the method can be declared
3603 // protected internal only within the same assembly
3606 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3607 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3609 // assemblies differ - report an error
3613 } else if (thisp != base_classp) {
3615 // same assembly, but other attributes differ - report an error
3620 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3622 // if it's not "protected internal", it must be "protected"
3626 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3628 // protected within the same assembly - an error
3631 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3632 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3634 // protected ok, but other attributes differ - report an error
3640 return (thisp == base_classp);
3644 public bool CheckAbstractAndExtern (bool has_block)
3646 if (Parent.Kind == Kind.Interface)
3650 if ((ModFlags & Modifiers.EXTERN) != 0) {
3651 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3652 GetSignatureForError ());
3656 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3657 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3658 GetSignatureForError ());
3662 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3663 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3664 GetSignatureForError ());
3672 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3674 Report.SymbolRelatedToPreviousError (base_method);
3675 string base_name = TypeManager.GetFullNameSignature (base_method);
3676 string this_name = GetSignatureForError ();
3677 if (suffix != null) {
3678 base_name += suffix;
3679 this_name += suffix;
3682 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3683 this_name, Modifiers.GetDescription (ma), base_name);
3686 protected static string Error722 {
3688 return "`{0}': static types cannot be used as return types";
3693 /// For custom member duplication search in a container
3695 protected abstract bool CheckForDuplications ();
3698 /// Gets base method and its return type
3700 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3702 protected bool DoDefineParameters ()
3704 EmitContext ec = ds.EmitContext;
3706 throw new InternalErrorException ("DoDefineParameters invoked too early");
3708 bool old_unsafe = ec.InUnsafe;
3709 ec.InUnsafe = InUnsafe;
3710 ec.ResolvingGenericMethod = GenericMethod != null;
3712 bool old_obsolete = ec.TestObsoleteMethodUsage;
3713 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute () != null)
3714 ec.TestObsoleteMethodUsage = false;
3716 // Check if arguments were correct
3717 if (!Parameters.Resolve (ec))
3720 ec.ResolvingGenericMethod = false;
3721 ec.InUnsafe = old_unsafe;
3722 ec.TestObsoleteMethodUsage = old_obsolete;
3724 return CheckParameters (ParameterTypes);
3727 bool CheckParameters (Type [] parameters)
3731 foreach (Type partype in parameters){
3732 if (partype == TypeManager.void_type) {
3734 1547, Location, "Keyword 'void' cannot " +
3735 "be used in this context");
3739 if (partype.IsPointer){
3742 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3746 if (ds.AsAccessible (partype, ModFlags))
3749 if (this is Indexer)
3750 Report.Error (55, Location,
3751 "Inconsistent accessibility: parameter type `" +
3752 TypeManager.CSharpName (partype) + "' is less " +
3753 "accessible than indexer `" + GetSignatureForError () + "'");
3754 else if ((this is Method) && ((Method) this).IsOperator != null)
3755 Report.Error (57, Location,
3756 "Inconsistent accessibility: parameter type `" +
3757 TypeManager.CSharpName (partype) + "' is less " +
3758 "accessible than operator `" + GetSignatureForError () + "'");
3760 Report.Error (51, Location,
3761 "Inconsistent accessibility: parameter type `" +
3762 TypeManager.CSharpName (partype) + "' is less " +
3763 "accessible than method `" + GetSignatureForError () + "'");
3770 public override string[] ValidAttributeTargets {
3772 return attribute_targets;
3776 protected override bool VerifyClsCompliance (DeclSpace ds)
3778 if (!base.VerifyClsCompliance (ds)) {
3779 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsComplianceRequired (ds)) {
3780 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3785 if (Parameters.HasArglist) {
3786 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3789 if (!AttributeTester.IsClsCompliant (MemberType)) {
3790 if (this is PropertyBase)
3791 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3792 GetSignatureForError ());
3794 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3795 GetSignatureForError ());
3798 Parameters.VerifyClsCompliance ();
3803 protected bool IsDuplicateImplementation (MethodCore method)
3805 if (method == this || !(method.MemberName.Equals (MemberName)))
3808 Type[] param_types = method.ParameterTypes;
3809 // This never happen. Rewrite this as Equal
3810 if (param_types == null && ParameterTypes == null)
3812 if (param_types == null || ParameterTypes == null)
3815 if (param_types.Length != ParameterTypes.Length)
3818 if (method.Parameters.HasArglist != Parameters.HasArglist)
3823 for (int i = 0; i < param_types.Length; i++) {
3824 if (param_types [i] != ParameterTypes [i])
3828 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3831 // TODO: make operator compatible with MethodCore to avoid this
3832 if (this is Operator && method is Operator) {
3833 if (MemberType != method.MemberType)
3839 // Try to report 663: method only differs on out/ref
3841 Parameters info = ParameterInfo;
3842 Parameters other_info = method.ParameterInfo;
3843 for (int i = 0; i < info.Count; i++){
3845 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3846 Report.SymbolRelatedToPreviousError (method);
3847 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3848 GetSignatureForError ());
3851 Console.WriteLine ("Method is: {0} {1}", method.Location, method);
3852 Console.WriteLine ("this is: {0} {1}", Location, this);
3856 Report.SymbolRelatedToPreviousError (method);
3857 if (this is Operator && method is Operator)
3858 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3860 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3868 public override bool IsUsed {
3869 get { return IsExplicitImpl || base.IsUsed; }
3873 // Returns a string that represents the signature for this
3874 // member which should be used in XML documentation.
3876 public override string GetDocCommentName (DeclSpace ds)
3878 return DocUtil.GetMethodDocCommentName (this, ds);
3882 // Raised (and passed an XmlElement that contains the comment)
3883 // when GenerateDocComment is writing documentation expectedly.
3885 // FIXME: with a few effort, it could be done with XmlReader,
3886 // that means removal of DOM use.
3888 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3890 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3894 // Represents header string for documentation comment.
3896 public override string DocCommentHeader {
3897 get { return "M:"; }
3902 public class SourceMethod : ISourceMethod
3904 TypeContainer container;
3907 protected SourceMethod (TypeContainer container, MethodBase builder,
3908 ISourceFile file, Location start, Location end)
3910 this.container = container;
3911 this.builder = builder;
3913 CodeGen.SymbolWriter.OpenMethod (
3914 file, this, start.Row, start.Column, end.Row, start.Column);
3917 public string Name {
3918 get { return builder.Name; }
3921 public int NamespaceID {
3922 get { return container.NamespaceEntry.SymbolFileID; }
3927 if (builder is MethodBuilder)
3928 return ((MethodBuilder) builder).GetToken ().Token;
3929 else if (builder is ConstructorBuilder)
3930 return ((ConstructorBuilder) builder).GetToken ().Token;
3932 throw new NotSupportedException ();
3936 public void CloseMethod ()
3938 if (CodeGen.SymbolWriter != null)
3939 CodeGen.SymbolWriter.CloseMethod ();
3942 public static SourceMethod Create (TypeContainer parent,
3943 MethodBase builder, Block block)
3945 if (CodeGen.SymbolWriter == null)
3950 Location start_loc = block.StartLocation;
3951 if (start_loc.IsNull)
3954 Location end_loc = block.EndLocation;
3958 ISourceFile file = start_loc.SourceFile;
3962 return new SourceMethod (
3963 parent, builder, file, start_loc, end_loc);
3967 public class Method : MethodCore, IIteratorContainer, IMethodData {
3968 public MethodBuilder MethodBuilder;
3969 public MethodData MethodData;
3970 ReturnParameter return_attributes;
3971 ListDictionary declarative_security;
3974 /// Modifiers allowed in a class declaration
3976 const int AllowedModifiers =
3979 Modifiers.PROTECTED |
3980 Modifiers.INTERNAL |
3985 Modifiers.OVERRIDE |
3986 Modifiers.ABSTRACT |
3988 Modifiers.METHOD_YIELDS |
3991 const int AllowedInterfaceModifiers =
3992 Modifiers.NEW | Modifiers.UNSAFE;
3995 // return_type can be "null" for VOID values.
3997 public Method (TypeContainer parent, GenericMethod generic,
3998 Expression return_type, int mod, bool is_iface,
3999 MemberName name, Parameters parameters, Attributes attrs)
4000 : base (parent, generic, return_type, mod,
4001 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4002 is_iface, name, attrs, parameters)
4006 public override AttributeTargets AttributeTargets {
4008 return AttributeTargets.Method;
4012 public override string GetSignatureForError()
4014 if (IsOperator != null)
4015 return IsOperator.GetSignatureForError ();
4017 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4020 void DuplicateEntryPoint (MethodInfo b, Location location)
4024 "Program `" + CodeGen.FileName +
4025 "' has more than one entry point defined: `" +
4026 TypeManager.CSharpSignature(b) + "'");
4029 bool IsEntryPoint (MethodBuilder b, Parameters pinfo)
4031 if (b.ReturnType != TypeManager.void_type &&
4032 b.ReturnType != TypeManager.int32_type)
4035 if (pinfo.Count == 0)
4038 if (pinfo.Count > 1)
4041 Type t = pinfo.ParameterType(0);
4043 (t.GetArrayRank() == 1) &&
4044 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
4045 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
4051 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4053 if (a.Target == AttributeTargets.ReturnValue) {
4054 if (return_attributes == null)
4055 return_attributes = new ReturnParameter (MethodBuilder, Location);
4057 return_attributes.ApplyAttributeBuilder (a, cb);
4061 if (a.Type == TypeManager.methodimpl_attr_type &&
4062 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4063 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4066 if (a.Type == TypeManager.dllimport_type) {
4067 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4068 if ((ModFlags & extern_static) != extern_static) {
4069 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
4075 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4076 if (declarative_security == null)
4077 declarative_security = new ListDictionary ();
4078 a.ExtractSecurityPermissionSet (declarative_security);
4082 if (a.Type == TypeManager.conditional_attribute_type) {
4083 if (IsOperator != null || IsExplicitImpl) {
4084 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4085 GetSignatureForError ());
4089 if (ReturnType != TypeManager.void_type) {
4090 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4094 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4095 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4100 Report.Error (582, Location, "Conditional not valid on interface members");
4104 if (MethodData.implementing != null) {
4105 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4106 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4110 for (int i = 0; i < ParameterInfo.Count; ++i) {
4111 if ((ParameterInfo.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4112 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4118 MethodBuilder.SetCustomAttribute (cb);
4121 protected override bool CheckForDuplications ()
4123 ArrayList ar = Parent.Methods;
4125 int arLen = ar.Count;
4127 for (int i = 0; i < arLen; i++) {
4128 Method m = (Method) ar [i];
4129 if (IsDuplicateImplementation (m))
4134 ar = Parent.Properties;
4136 for (int i = 0; i < ar.Count; ++i) {
4137 PropertyBase pb = (PropertyBase) ar [i];
4138 if (pb.AreAccessorsDuplicateImplementation (this))
4143 ar = Parent.Indexers;
4145 for (int i = 0; i < ar.Count; ++i) {
4146 PropertyBase pb = (PropertyBase) ar [i];
4147 if (pb.AreAccessorsDuplicateImplementation (this))
4154 for (int i = 0; i < ar.Count; ++i) {
4155 Event ev = (Event) ar [i];
4156 if (ev.AreAccessorsDuplicateImplementation (this))
4167 public override bool Define ()
4169 if (!DoDefineBase ())
4172 MethodBuilder mb = null;
4173 if (GenericMethod != null) {
4174 string method_name = MemberName.Name;
4176 if (IsExplicitImpl) {
4177 method_name = TypeManager.CSharpName (InterfaceType) +
4181 mb = Parent.TypeBuilder.DefineGenericMethod (method_name, flags);
4182 if (!GenericMethod.Define (mb))
4189 if (!CheckAbstractAndExtern (block != null))
4192 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4193 Error1599 (Location, ReturnType);
4200 if (IsOperator != null)
4201 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
4203 MethodData = new MethodData (this, ModFlags, flags, this, mb, GenericMethod, base_method);
4205 if (!MethodData.Define (Parent))
4208 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4209 Name == "Finalize" && !(this is Destructor)) {
4210 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4214 // Setup iterator if we are one
4216 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4217 Iterator iterator = new Iterator (
4218 this, Parent, GenericMethod, ModFlags);
4220 if (!iterator.DefineIterator ())
4224 MethodBuilder = MethodData.MethodBuilder;
4227 // This is used to track the Entry Point,
4229 if (Name == "Main" &&
4230 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
4231 (RootContext.MainClass == null ||
4232 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4233 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
4234 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4235 md.SetMemberIsUsed ();
4237 if (RootContext.EntryPoint == null) {
4238 if (Parent.IsGeneric){
4239 Report.Error (-201, Location,
4240 "Entry point can not be defined in a generic class");
4243 RootContext.EntryPoint = MethodBuilder;
4244 RootContext.EntryPointLocation = Location;
4246 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4247 DuplicateEntryPoint (MethodBuilder, Location);
4250 if (RootContext.WarningLevel >= 4)
4251 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
4255 if (MemberType.IsAbstract && MemberType.IsSealed) {
4256 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4266 public override void Emit ()
4268 MethodData.Emit (Parent, this);
4271 if (declarative_security != null) {
4272 foreach (DictionaryEntry de in declarative_security) {
4273 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4281 public static void Error1599 (Location loc, Type t)
4283 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4286 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4288 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
4289 container.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4294 base_ret_type = mi.ReturnType;
4298 public override bool MarkForDuplicationCheck ()
4300 caching_flags |= Flags.TestMethodDuplication;
4304 protected override bool VerifyClsCompliance(DeclSpace ds)
4306 if (!base.VerifyClsCompliance (ds))
4309 if (ParameterInfo.Count > 0) {
4310 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
4312 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4318 #region IMethodData Members
4320 public CallingConventions CallingConventions {
4322 CallingConventions cc = Parameters.CallingConvention;
4323 if (Parameters.HasArglist)
4324 block.HasVarargs = true;
4327 if ((ModFlags & Modifiers.STATIC) == 0)
4328 cc |= CallingConventions.HasThis;
4330 // FIXME: How is `ExplicitThis' used in C#?
4336 public Type ReturnType {
4342 public MemberName MethodName {
4348 public new Location Location {
4350 return base.Location;
4354 protected override bool CheckBase() {
4355 if (!base.CheckBase ())
4358 // TODO: Destructor should derive from MethodCore
4359 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4360 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4361 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4368 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4370 EmitContext ec = new EmitContext (
4371 tc, ds, Location, ig, ReturnType, ModFlags, false);
4373 Iterator iterator = tc as Iterator;
4374 if (iterator != null)
4375 ec.CurrentAnonymousMethod = iterator.Host;
4381 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4383 public bool IsExcluded (EmitContext ec)
4385 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4386 return (caching_flags & Flags.Excluded) != 0;
4388 caching_flags &= ~Flags.Excluded_Undetected;
4390 if (base_method == null) {
4391 if (OptAttributes == null)
4394 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4399 foreach (Attribute a in attrs) {
4400 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4401 if (RootContext.AllDefines.Contains (condition))
4405 caching_flags |= Flags.Excluded;
4409 IMethodData md = TypeManager.GetMethod (base_method);
4411 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4412 caching_flags |= Flags.Excluded;
4418 if (md.IsExcluded (ec)) {
4419 caching_flags |= Flags.Excluded;
4425 GenericMethod IMethodData.GenericMethod {
4427 return GenericMethod;
4434 public abstract class ConstructorInitializer {
4435 ArrayList argument_list;
4436 protected ConstructorInfo base_constructor;
4439 public ConstructorInitializer (ArrayList argument_list, Location loc)
4441 this.argument_list = argument_list;
4445 public ArrayList Arguments {
4447 return argument_list;
4451 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4453 Expression base_constructor_group;
4457 ec.CurrentBlock = block;
4459 if (argument_list != null){
4460 foreach (Argument a in argument_list){
4461 if (!a.Resolve (ec, loc))
4465 ec.CurrentBlock = null;
4467 if (this is ConstructorBaseInitializer) {
4468 if (ec.ContainerType.BaseType == null)
4471 t = ec.ContainerType.BaseType;
4472 if (ec.ContainerType.IsValueType) {
4473 Report.Error (522, loc,
4474 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4478 t = ec.ContainerType;
4480 base_constructor_group = Expression.MemberLookup (
4481 ec, t, ".ctor", MemberTypes.Constructor,
4482 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4485 if (base_constructor_group == null){
4487 base_constructor_group = Expression.MemberLookup (
4488 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4489 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4493 int errors = Report.Errors;
4494 if (base_constructor_group != null)
4495 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4496 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4499 if (base_constructor == null) {
4500 if (errors == Report.Errors)
4501 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4502 argument_list.Count);
4507 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4508 base_constructor = null;
4512 if (base_constructor == caller_builder){
4513 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4520 public virtual void Emit (EmitContext ec)
4522 if (base_constructor != null){
4523 ec.Mark (loc, false);
4525 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4527 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4532 public class ConstructorBaseInitializer : ConstructorInitializer {
4533 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4534 base (argument_list, l)
4539 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4540 public GeneratedBaseInitializer (Location loc):
4545 public override void Emit(EmitContext ec)
4547 bool old = ec.TestObsoleteMethodUsage;
4548 ec.TestObsoleteMethodUsage = false;
4550 ec.TestObsoleteMethodUsage = old;
4554 public class ConstructorThisInitializer : ConstructorInitializer {
4555 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4556 base (argument_list, l)
4561 public class Constructor : MethodCore, IMethodData {
4562 public ConstructorBuilder ConstructorBuilder;
4563 public ConstructorInitializer Initializer;
4564 ListDictionary declarative_security;
4567 // Modifiers allowed for a constructor.
4569 public const int AllowedModifiers =
4571 Modifiers.PROTECTED |
4572 Modifiers.INTERNAL |
4578 bool has_compliant_args = false;
4580 // The spec claims that static is not permitted, but
4581 // my very own code has static constructors.
4583 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4584 ConstructorInitializer init, Location loc)
4585 : base (ds, null, null, mod, AllowedModifiers, false,
4586 new MemberName (name, loc), null, args)
4591 public bool HasCompliantArgs {
4593 return has_compliant_args;
4597 public override AttributeTargets AttributeTargets {
4599 return AttributeTargets.Constructor;
4605 // Returns true if this is a default constructor
4607 public bool IsDefault ()
4609 if ((ModFlags & Modifiers.STATIC) != 0)
4610 return Parameters.Empty;
4612 return Parameters.Empty &&
4613 (Initializer is ConstructorBaseInitializer) &&
4614 (Initializer.Arguments == null);
4617 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4619 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4620 if (declarative_security == null) {
4621 declarative_security = new ListDictionary ();
4623 a.ExtractSecurityPermissionSet (declarative_security);
4627 ConstructorBuilder.SetCustomAttribute (cb);
4630 protected override bool CheckForDuplications ()
4632 ArrayList ar = Parent.InstanceConstructors;
4634 int arLen = ar.Count;
4636 for (int i = 0; i < arLen; i++) {
4637 Constructor m = (Constructor) ar [i];
4638 if (IsDuplicateImplementation (m))
4645 protected override bool CheckBase ()
4647 // Check whether arguments were correct.
4648 if (!DoDefineParameters ())
4651 // TODO: skip the rest for generated ctor
4652 if ((ModFlags & Modifiers.STATIC) != 0)
4655 if (!CheckForDuplications ())
4658 if (Parent.Kind == Kind.Struct) {
4659 if (ParameterTypes.Length == 0) {
4660 Report.Error (568, Location,
4661 "Structs cannot contain explicit parameterless constructors");
4665 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4666 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4671 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4672 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4679 // Creates the ConstructorBuilder
4681 public override bool Define ()
4683 if (ConstructorBuilder != null)
4686 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4687 MethodAttributes.SpecialName);
4689 if ((ModFlags & Modifiers.STATIC) != 0){
4690 ca |= MethodAttributes.Static | MethodAttributes.Private;
4692 ca |= MethodAttributes.HideBySig;
4694 if ((ModFlags & Modifiers.PUBLIC) != 0)
4695 ca |= MethodAttributes.Public;
4696 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4697 if ((ModFlags & Modifiers.INTERNAL) != 0)
4698 ca |= MethodAttributes.FamORAssem;
4700 ca |= MethodAttributes.Family;
4701 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4702 ca |= MethodAttributes.Assembly;
4703 else if (IsDefault ())
4704 ca |= MethodAttributes.Public;
4706 ca |= MethodAttributes.Private;
4709 if (!CheckAbstractAndExtern (block != null))
4712 // Check if arguments were correct.
4716 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4717 ca, CallingConventions,
4720 if ((ModFlags & Modifiers.UNSAFE) != 0)
4721 ConstructorBuilder.InitLocals = false;
4723 if (Parent.IsComImport) {
4724 if (!IsDefault ()) {
4725 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4726 Parent.GetSignatureForError ());
4729 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4732 TypeManager.AddMethod (ConstructorBuilder, this);
4740 public override void Emit ()
4742 EmitContext ec = CreateEmitContext (null, null);
4743 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute () != null)
4744 ec.TestObsoleteMethodUsage = false;
4746 // If this is a non-static `struct' constructor and doesn't have any
4747 // initializer, it must initialize all of the struct's fields.
4748 if ((Parent.Kind == Kind.Struct) &&
4749 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4750 Block.AddThisVariable (Parent, Location);
4752 if (block != null) {
4753 if (!block.ResolveMeta (ec, ParameterInfo))
4757 if ((ModFlags & Modifiers.STATIC) == 0){
4758 if (Parent.Kind == Kind.Class && Initializer == null)
4759 Initializer = new GeneratedBaseInitializer (Location);
4763 // Spec mandates that Initializers will not have
4767 if ((Initializer != null) &&
4768 !Initializer.Resolve (ConstructorBuilder, block, ec))
4770 ec.IsStatic = false;
4773 Parameters.ApplyAttributes (ec, ConstructorBuilder);
4775 SourceMethod source = SourceMethod.Create (
4776 Parent, ConstructorBuilder, block);
4779 // Classes can have base initializers and instance field initializers.
4781 if (Parent.Kind == Kind.Class){
4782 if ((ModFlags & Modifiers.STATIC) == 0){
4785 // If we use a "this (...)" constructor initializer, then
4786 // do not emit field initializers, they are initialized in the other constructor
4788 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4789 Parent.EmitFieldInitializers (ec);
4792 if (Initializer != null) {
4793 Initializer.Emit (ec);
4796 if ((ModFlags & Modifiers.STATIC) != 0)
4797 Parent.EmitFieldInitializers (ec);
4799 if (OptAttributes != null)
4800 OptAttributes.Emit (ec, this);
4802 ec.EmitTopBlock (this, block);
4805 source.CloseMethod ();
4809 if (declarative_security != null) {
4810 foreach (DictionaryEntry de in declarative_security) {
4811 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4818 // Is never override
4819 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4824 public override string GetSignatureForError()
4826 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4829 protected override bool VerifyClsCompliance (DeclSpace ds)
4831 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4835 if (ParameterInfo.Count > 0) {
4836 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4838 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4840 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4841 foreach (Type param in ParameterTypes) {
4842 if (param.IsArray) {
4848 has_compliant_args = true;
4852 #region IMethodData Members
4854 public System.Reflection.CallingConventions CallingConventions {
4856 CallingConventions cc = Parameters.CallingConvention;
4858 if (Parent.Kind == Kind.Class)
4859 if ((ModFlags & Modifiers.STATIC) == 0)
4860 cc |= CallingConventions.HasThis;
4862 // FIXME: How is `ExplicitThis' used in C#?
4868 public new Location Location {
4870 return base.Location;
4874 public MemberName MethodName {
4880 public Type ReturnType {
4886 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4888 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4889 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4892 public bool IsExcluded(EmitContext ec)
4897 GenericMethod IMethodData.GenericMethod {
4907 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4909 public interface IMethodData
4911 CallingConventions CallingConventions { get; }
4912 Location Location { get; }
4913 MemberName MethodName { get; }
4914 Type ReturnType { get; }
4915 GenericMethod GenericMethod { get; }
4916 Parameters ParameterInfo { get; }
4918 Attributes OptAttributes { get; }
4919 ToplevelBlock Block { get; set; }
4921 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4922 ObsoleteAttribute GetObsoleteAttribute ();
4923 string GetSignatureForError ();
4924 bool IsExcluded (EmitContext ec);
4925 bool IsClsComplianceRequired (DeclSpace ds);
4926 void SetMemberIsUsed ();
4930 // Encapsulates most of the Method's state
4932 public class MethodData {
4934 readonly IMethodData method;
4936 public readonly GenericMethod GenericMethod;
4939 // Are we implementing an interface ?
4941 public MethodInfo implementing;
4946 protected MemberBase member;
4947 protected int modifiers;
4948 protected MethodAttributes flags;
4949 protected Type declaring_type;
4950 protected MethodInfo parent_method;
4952 MethodBuilder builder = null;
4953 public MethodBuilder MethodBuilder {
4959 public Type DeclaringType {
4961 return declaring_type;
4965 public MethodData (MemberBase member,
4966 int modifiers, MethodAttributes flags, IMethodData method)
4968 this.member = member;
4969 this.modifiers = modifiers;
4972 this.method = method;
4975 public MethodData (MemberBase member,
4976 int modifiers, MethodAttributes flags,
4977 IMethodData method, MethodBuilder builder,
4978 GenericMethod generic, MethodInfo parent_method)
4979 : this (member, modifiers, flags, method)
4981 this.builder = builder;
4982 this.GenericMethod = generic;
4983 this.parent_method = parent_method;
4986 public bool Define (TypeContainer container)
4988 string name = method.MethodName.Basename;
4989 string method_name = method.MethodName.FullName;
4991 if (container.Pending != null){
4992 if (member is Indexer) // TODO: test it, but it should work without this IF
4993 implementing = container.Pending.IsInterfaceIndexer (
4994 member.InterfaceType, method.ReturnType, method.ParameterInfo);
4996 implementing = container.Pending.IsInterfaceMethod (
4997 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
4999 if (member.InterfaceType != null){
5000 if (implementing == null){
5001 if (member is PropertyBase) {
5002 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5003 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5004 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5007 Report.Error (539, method.Location,
5008 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5009 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5013 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5014 Report.SymbolRelatedToPreviousError (implementing);
5015 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5016 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5020 method_name = TypeManager.GetFullName (member.InterfaceType) +
5023 if (implementing != null) {
5024 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5025 if (prop_method != null) {
5026 if (!implementing.IsSpecialName) {
5027 Report.SymbolRelatedToPreviousError (implementing);
5028 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5029 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5032 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5033 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5034 Report.SymbolRelatedToPreviousError (implementing);
5035 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5036 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5045 // For implicit implementations, make sure we are public, for
5046 // explicit implementations, make sure we are private.
5048 if (implementing != null){
5050 // Setting null inside this block will trigger a more
5051 // verbose error reporting for missing interface implementations
5053 // The "candidate" function has been flagged already
5054 // but it wont get cleared
5056 if (member.IsExplicitImpl){
5057 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
5058 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
5059 implementing = null;
5061 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
5062 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
5064 // If this is an interface method implementation,
5065 // check for public accessibility
5067 implementing = null;
5068 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5069 // We may never be private.
5070 implementing = null;
5071 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5073 // We may be protected if we're overriding something.
5075 implementing = null;
5080 // Static is not allowed
5082 if ((modifiers & Modifiers.STATIC) != 0){
5083 implementing = null;
5088 // If implementing is still valid, set flags
5090 if (implementing != null){
5092 // When implementing interface methods, set NewSlot
5093 // unless, we are overwriting a method.
5095 if (implementing.DeclaringType.IsInterface){
5096 if ((modifiers & Modifiers.OVERRIDE) == 0)
5097 flags |= MethodAttributes.NewSlot;
5100 MethodAttributes.Virtual |
5101 MethodAttributes.HideBySig;
5103 // Set Final unless we're virtual, abstract or already overriding a method.
5104 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5105 flags |= MethodAttributes.Final;
5108 EmitContext ec = method.CreateEmitContext (container, null);
5109 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute () != null)
5110 ec.TestObsoleteMethodUsage = false;
5112 DefineMethodBuilder (ec, container, method_name, method.ParameterInfo.Types);
5114 if (builder == null)
5117 if (container.CurrentType != null)
5118 declaring_type = container.CurrentType;
5120 declaring_type = container.TypeBuilder;
5122 if ((modifiers & Modifiers.UNSAFE) != 0)
5123 builder.InitLocals = false;
5125 if (implementing != null){
5127 // clear the pending implemntation flag
5129 if (member is Indexer) {
5130 container.Pending.ImplementIndexer (
5131 member.InterfaceType, builder, method.ReturnType,
5132 method.ParameterInfo, member.IsExplicitImpl);
5134 container.Pending.ImplementMethod (
5135 member.InterfaceType, name, method.ReturnType,
5136 method.ParameterInfo, member.IsExplicitImpl);
5138 if (member.IsExplicitImpl)
5139 container.TypeBuilder.DefineMethodOverride (
5140 builder, implementing);
5143 TypeManager.AddMethod (builder, method);
5145 if (GenericMethod != null) {
5146 bool is_override = member.IsExplicitImpl |
5147 ((modifiers & Modifiers.OVERRIDE) != 0);
5149 if (implementing != null)
5150 parent_method = implementing;
5152 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5160 /// Create the MethodBuilder for the method
5162 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
5164 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
5166 if ((modifiers & extern_static) == extern_static) {
5168 if (method.OptAttributes != null) {
5169 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
5170 if (dllimport_attribute != null) {
5171 flags |= MethodAttributes.PinvokeImpl;
5172 builder = dllimport_attribute.DefinePInvokeMethod (
5173 ec, container.TypeBuilder, method_name, flags,
5174 method.ReturnType, ParameterTypes);
5180 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5181 // We are more strict than Microsoft and report CS0626 like error
5182 if (method.OptAttributes == null ||
5183 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
5184 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",
5185 method.GetSignatureForError ());
5190 if (builder == null)
5191 builder = container.TypeBuilder.DefineMethod (
5192 method_name, flags, method.CallingConventions,
5193 method.ReturnType, ParameterTypes);
5195 builder.SetGenericMethodSignature (
5196 flags, method.CallingConventions,
5197 method.ReturnType, ParameterTypes);
5203 public void Emit (TypeContainer container, Attributable kind)
5206 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5207 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
5209 ec = method.CreateEmitContext (container, null);
5211 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute () != null)
5212 ec.TestObsoleteMethodUsage = false;
5214 method.ParameterInfo.ApplyAttributes (ec, MethodBuilder);
5216 Attributes OptAttributes = method.OptAttributes;
5218 if (OptAttributes != null)
5219 OptAttributes.Emit (ec, kind);
5221 if (GenericMethod != null)
5222 GenericMethod.EmitAttributes (ec);
5224 ToplevelBlock block = method.Block;
5226 SourceMethod source = SourceMethod.Create (
5227 container, MethodBuilder, method.Block);
5230 // Handle destructors specially
5232 // FIXME: This code generates buggy code
5234 if (member is Destructor)
5235 EmitDestructor (ec, block);
5237 ec.EmitTopBlock (method, block);
5240 source.CloseMethod ();
5243 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5245 ILGenerator ig = ec.ig;
5247 Label finish = ig.DefineLabel ();
5249 block.SetDestructor ();
5251 ig.BeginExceptionBlock ();
5252 ec.ReturnLabel = finish;
5253 ec.HasReturnLabel = true;
5254 ec.EmitTopBlock (method, block);
5256 // ig.MarkLabel (finish);
5257 ig.BeginFinallyBlock ();
5259 if (ec.ContainerType.BaseType != null) {
5260 Expression member_lookup = Expression.MemberLookup (
5261 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5262 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5264 if (member_lookup != null){
5265 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5267 ig.Emit (OpCodes.Ldarg_0);
5268 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5272 ig.EndExceptionBlock ();
5273 //ig.MarkLabel (ec.ReturnLabel);
5274 ig.Emit (OpCodes.Ret);
5278 // TODO: Should derive from MethodCore
5279 public class Destructor : Method {
5281 public Destructor (TypeContainer ds, Expression return_type, int mod,
5282 string name, Parameters parameters, Attributes attrs,
5284 : base (ds, null, return_type, mod, false, new MemberName (name, l),
5288 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5290 if (a.Type == TypeManager.conditional_attribute_type) {
5291 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
5292 GetSignatureForError ());
5296 base.ApplyAttributeBuilder (a, cb);
5299 public override string GetSignatureForError ()
5301 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5306 abstract public class MemberBase : MemberCore {
5307 public Expression Type;
5309 public MethodAttributes flags;
5310 public readonly DeclSpace ds;
5311 public readonly GenericMethod GenericMethod;
5313 protected readonly int explicit_mod_flags;
5316 // The "short" name of this property / indexer / event. This is the
5317 // name without the explicit interface.
5319 public string ShortName {
5320 get { return MemberName.Name; }
5321 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
5324 public new TypeContainer Parent {
5325 get { return (TypeContainer) base.Parent; }
5329 // The type of this property / indexer / event
5331 protected Type member_type;
5332 public Type MemberType {
5334 if (member_type == null && Type != null) {
5335 EmitContext ec = ds.EmitContext;
5336 bool old_unsafe = ec.InUnsafe;
5337 ec.InUnsafe = InUnsafe;
5338 ec.ResolvingGenericMethod = GenericMethod != null;
5339 Type = Type.ResolveAsTypeTerminal (ec);
5340 ec.ResolvingGenericMethod = false;
5341 ec.InUnsafe = old_unsafe;
5343 member_type = Type.Type;
5351 // Whether this is an interface member.
5353 public bool IsInterface;
5356 // If true, this is an explicit interface implementation
5358 public bool IsExplicitImpl;
5361 // The interface type we are explicitly implementing
5363 public Type InterfaceType = null;
5366 // The constructor is only exposed to our children
5368 protected MemberBase (TypeContainer parent, GenericMethod generic,
5369 Expression type, int mod, int allowed_mod, int def_mod,
5370 MemberName name, Attributes attrs)
5371 : base (parent, name, attrs)
5373 this.ds = generic != null ? generic : (DeclSpace) parent;
5374 explicit_mod_flags = mod;
5376 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5377 IsExplicitImpl = (MemberName.Left != null);
5378 GenericMethod = generic;
5381 protected virtual bool CheckBase ()
5383 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5384 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5388 if ((RootContext.WarningLevel >= 4) &&
5389 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5390 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5391 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5392 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5397 protected virtual bool DoDefineBase ()
5399 EmitContext ec = Parent.EmitContext;
5401 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5404 throw new InternalErrorException ();
5407 ModFlags = Modifiers.PUBLIC |
5408 Modifiers.ABSTRACT |
5409 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5411 flags = MethodAttributes.Public |
5412 MethodAttributes.Abstract |
5413 MethodAttributes.HideBySig |
5414 MethodAttributes.NewSlot |
5415 MethodAttributes.Virtual;
5417 if (!Parent.MethodModifiersValid (this))
5420 flags = Modifiers.MethodAttr (ModFlags);
5423 if (IsExplicitImpl) {
5424 Expression expr = MemberName.Left.GetTypeExpression ();
5425 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5426 if (iface_texpr == null)
5429 InterfaceType = iface_texpr.ResolveType (ec);
5431 if (!InterfaceType.IsInterface) {
5432 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5436 if (!Parent.VerifyImplements (this))
5439 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5445 protected virtual bool DoDefine ()
5447 EmitContext ec = ds.EmitContext;
5449 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5451 ec.InUnsafe = InUnsafe;
5453 if (MemberType == null)
5456 CheckObsoleteType (Type);
5458 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5459 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5460 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5461 GetSignatureForError (), Parent.GetSignatureForError ());
5465 // verify accessibility
5466 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5467 Report.SymbolRelatedToPreviousError (MemberType);
5468 if (this is Property)
5469 Report.Error (53, Location,
5470 "Inconsistent accessibility: property type `" +
5471 TypeManager.CSharpName (MemberType) + "' is less " +
5472 "accessible than property `" + GetSignatureForError () + "'");
5473 else if (this is Indexer)
5474 Report.Error (54, Location,
5475 "Inconsistent accessibility: indexer return type `" +
5476 TypeManager.CSharpName (MemberType) + "' is less " +
5477 "accessible than indexer `" + GetSignatureForError () + "'");
5478 else if (this is MethodCore) {
5479 if (this is Operator)
5480 Report.Error (56, Location,
5481 "Inconsistent accessibility: return type `" +
5482 TypeManager.CSharpName (MemberType) + "' is less " +
5483 "accessible than operator `" + GetSignatureForError () + "'");
5485 Report.Error (50, Location,
5486 "Inconsistent accessibility: return type `" +
5487 TypeManager.CSharpName (MemberType) + "' is less " +
5488 "accessible than method `" + GetSignatureForError () + "'");
5490 Report.Error (52, Location,
5491 "Inconsistent accessibility: field type `" +
5492 TypeManager.CSharpName (MemberType) + "' is less " +
5493 "accessible than field `" + GetSignatureForError () + "'");
5498 if (MemberType.IsPointer && !UnsafeOK (Parent))
5501 if (IsExplicitImpl) {
5502 Expression expr = MemberName.Left.GetTypeExpression ();
5503 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
5507 InterfaceType = texpr.ResolveType (ec);
5509 if (!InterfaceType.IsInterface) {
5510 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5514 if (!Parent.VerifyImplements (this))
5517 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5523 protected bool IsTypePermitted ()
5525 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5526 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5532 protected override bool VerifyClsCompliance(DeclSpace ds)
5534 if (base.VerifyClsCompliance (ds)) {
5538 if (IsInterface && HasClsCompliantAttribute && ds.IsClsComplianceRequired (ds)) {
5539 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5547 // Fields and Events both generate FieldBuilders, we use this to share
5548 // their common bits. This is also used to flag usage of the field
5550 abstract public class FieldBase : MemberBase {
5551 public FieldBuilder FieldBuilder;
5552 public Status status;
5553 protected Expression initializer;
5556 public enum Status : byte {
5557 HAS_OFFSET = 4 // Used by FieldMember.
5560 static string[] attribute_targets = new string [] { "field" };
5563 /// Symbol with same name in base class/struct
5565 public MemberInfo conflict_symbol;
5567 protected FieldBase (TypeContainer parent, Expression type, int mod,
5568 int allowed_mod, MemberName name, Attributes attrs)
5569 : base (parent, null, type, mod, allowed_mod, Modifiers.PRIVATE,
5574 public override AttributeTargets AttributeTargets {
5576 return AttributeTargets.Field;
5580 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5582 if (a.Type == TypeManager.marshal_as_attr_type) {
5583 UnmanagedMarshal marshal = a.GetMarshal (this);
5584 if (marshal != null) {
5585 FieldBuilder.SetMarshal (marshal);
5590 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5591 a.Error_InvalidSecurityParent ();
5595 FieldBuilder.SetCustomAttribute (cb);
5598 public void EmitInitializer (EmitContext ec)
5600 // Replace DeclSpace because of partial classes
5601 ec.DeclSpace = EmitContext.DeclSpace;
5603 ec.IsFieldInitializer = true;
5604 initializer = initializer.Resolve (ec);
5605 ec.IsFieldInitializer = false;
5606 if (initializer == null)
5608 FieldExpr fe = new FieldExpr (FieldBuilder, Location, true);
5609 if ((ModFlags & Modifiers.STATIC) == 0)
5610 fe.InstanceExpression = new This (Location).Resolve (ec);
5612 ExpressionStatement a = new Assign (fe, initializer, Location);
5614 a = a.ResolveStatement (ec);
5618 Constant c = initializer as Constant;
5619 if (c != null && CanElideInitializer (c))
5622 a.EmitStatement (ec);
5625 bool CanElideInitializer (Constant c)
5627 if (MemberType == c.Type)
5628 return c.IsDefaultValue;
5630 if (c.Type == TypeManager.null_type)
5636 protected override bool CheckBase ()
5638 if (!base.CheckBase ())
5645 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5646 if (conflict_symbol == null) {
5647 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5648 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5653 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5654 Report.SymbolRelatedToPreviousError (conflict_symbol);
5655 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5656 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5662 public Expression Initializer {
5664 if (value != null) {
5665 this.initializer = value;
5666 Parent.RegisterFieldForInitialization (this);
5671 protected virtual bool IsFieldClsCompliant {
5673 if (FieldBuilder == null)
5676 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5680 public override string[] ValidAttributeTargets {
5682 return attribute_targets;
5686 protected override bool VerifyClsCompliance (DeclSpace ds)
5688 if (!base.VerifyClsCompliance (ds))
5691 if (!IsFieldClsCompliant) {
5692 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5698 public void SetAssigned ()
5700 caching_flags |= Flags.IsAssigned;
5704 public abstract class FieldMember : FieldBase
5706 protected FieldMember (TypeContainer parent, Expression type, int mod,
5707 int allowed_mod, MemberName name, Attributes attrs)
5708 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, attrs)
5710 if ((mod & Modifiers.ABSTRACT) != 0)
5711 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5714 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5716 if (a.Type == TypeManager.field_offset_attribute_type)
5718 status |= Status.HAS_OFFSET;
5720 if (!Parent.HasExplicitLayout) {
5721 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5725 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5726 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5731 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5732 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5736 base.ApplyAttributeBuilder (a, cb);
5740 public override bool Define()
5742 EmitContext ec = Parent.EmitContext;
5744 throw new InternalErrorException ("FieldMember.Define called too early");
5746 if (MemberType == null || Type == null)
5749 CheckObsoleteType (Type);
5751 if (MemberType == TypeManager.void_type) {
5752 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5759 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5760 Report.Error (52, Location,
5761 "Inconsistent accessibility: field type `" +
5762 TypeManager.CSharpName (MemberType) + "' is less " +
5763 "accessible than field `" + GetSignatureForError () + "'");
5767 if (!IsTypePermitted ())
5770 if (MemberType.IsPointer && !UnsafeOK (Parent))
5776 public override void Emit ()
5778 if (OptAttributes != null) {
5779 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5780 OptAttributes.Emit (ec, this);
5783 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5784 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5791 // Represents header string for documentation comment.
5793 public override string DocCommentHeader {
5794 get { return "F:"; }
5798 interface IFixedBuffer
5800 FieldInfo Element { get; }
5801 Type ElementType { get; }
5804 public class FixedFieldExternal: IFixedBuffer
5806 FieldInfo element_field;
5808 public FixedFieldExternal (FieldInfo fi)
5810 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5813 #region IFixedField Members
5815 public FieldInfo Element {
5817 return element_field;
5821 public Type ElementType {
5823 return element_field.FieldType;
5831 /// Fixed buffer implementation
5833 public class FixedField : FieldMember, IFixedBuffer
5835 public const string FixedElementName = "FixedElementField";
5836 static int GlobalCounter = 0;
5837 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5838 static FieldInfo[] fi;
5840 TypeBuilder fixed_buffer_type;
5841 FieldBuilder element;
5842 Expression size_expr;
5845 const int AllowedModifiers =
5848 Modifiers.PROTECTED |
5849 Modifiers.INTERNAL |
5852 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5853 Expression size_expr, Attributes attrs, Location loc):
5854 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5856 if (RootContext.Version == LanguageVersion.ISO_1)
5857 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5859 this.size_expr = size_expr;
5862 public override bool Define()
5865 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5866 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5869 if (Parent.Kind != Kind.Struct) {
5870 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5871 GetSignatureForError ());
5875 if (!base.Define ())
5878 if (!TypeManager.IsPrimitiveType (MemberType)) {
5879 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",
5880 GetSignatureForError ());
5884 Constant c = size_expr.ResolveAsConstant (Parent.EmitContext, this);
5888 IntConstant buffer_size_const = c.ToInt (Location);
5889 if (buffer_size_const == null)
5892 buffer_size = buffer_size_const.Value;
5894 if (buffer_size <= 0) {
5895 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5899 int type_size = Expression.GetTypeSize (MemberType);
5901 if (buffer_size > int.MaxValue / type_size) {
5902 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5903 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5907 buffer_size *= type_size;
5910 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5912 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5913 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5914 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5915 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5917 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5918 TypeManager.RegisterFieldBase (FieldBuilder, this);
5923 public override void Emit()
5926 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5928 object[] fi_val = new object[1];
5929 fi_val [0] = buffer_size;
5931 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5932 ctor_args, fi, fi_val);
5933 fixed_buffer_type.SetCustomAttribute (cab);
5935 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5936 FieldBuilder.SetCustomAttribute (cab);
5940 protected override bool IsFieldClsCompliant {
5946 #region IFixedField Members
5948 public FieldInfo Element {
5954 public Type ElementType {
5964 // The Field class is used to represents class/struct fields during parsing.
5966 public class Field : FieldMember {
5968 // Modifiers allowed in a class declaration
5970 const int AllowedModifiers =
5973 Modifiers.PROTECTED |
5974 Modifiers.INTERNAL |
5977 Modifiers.VOLATILE |
5981 public Field (TypeContainer parent, Expression type, int mod, string name,
5982 Attributes attrs, Location loc)
5983 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5988 public override bool Define ()
5990 if (!base.Define ())
5993 if (RootContext.WarningLevel > 1){
5994 Type ptype = Parent.TypeBuilder.BaseType;
5996 // ptype is only null for System.Object while compiling corlib.
5998 TypeContainer.FindMembers (
5999 ptype, MemberTypes.Method,
6000 BindingFlags.Public |
6001 BindingFlags.Static | BindingFlags.Instance,
6002 System.Type.FilterName, Name);
6006 if ((ModFlags & Modifiers.VOLATILE) != 0){
6007 if (!MemberType.IsClass){
6008 Type vt = MemberType;
6010 if (TypeManager.IsEnumType (vt))
6011 vt = TypeManager.EnumToUnderlying (MemberType);
6013 if (!((vt == TypeManager.bool_type) ||
6014 (vt == TypeManager.sbyte_type) ||
6015 (vt == TypeManager.byte_type) ||
6016 (vt == TypeManager.short_type) ||
6017 (vt == TypeManager.ushort_type) ||
6018 (vt == TypeManager.int32_type) ||
6019 (vt == TypeManager.uint32_type) ||
6020 (vt == TypeManager.char_type) ||
6021 (vt == TypeManager.float_type) ||
6022 (!vt.IsValueType))){
6023 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
6024 GetSignatureForError (), TypeManager.CSharpName (vt));
6029 if ((ModFlags & Modifiers.READONLY) != 0){
6030 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
6031 GetSignatureForError ());
6036 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6038 if (Parent.Kind == Kind.Struct &&
6039 ((fa & FieldAttributes.Static) == 0) &&
6040 MemberType == Parent.TypeBuilder &&
6041 !TypeManager.IsBuiltinType (MemberType)){
6042 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6043 "' causes a cycle in the structure layout");
6048 FieldBuilder = Parent.TypeBuilder.DefineField (
6049 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6051 TypeManager.RegisterFieldBase (FieldBuilder, this);
6053 catch (ArgumentException) {
6054 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6061 protected override bool VerifyClsCompliance (DeclSpace ds)
6063 if (!base.VerifyClsCompliance (ds))
6066 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6067 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6075 // `set' and `get' accessors are represented with an Accessor.
6077 public class Accessor : IIteratorContainer {
6079 // Null if the accessor is empty, or a Block if not
6081 public const int AllowedModifiers =
6083 Modifiers.PROTECTED |
6084 Modifiers.INTERNAL |
6087 public ToplevelBlock Block;
6088 public Attributes Attributes;
6089 public Location Location;
6090 public int ModFlags;
6093 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6098 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6101 public void SetYields ()
6107 // Ooouh Martin, templates are missing here.
6108 // When it will be possible move here a lot of child code and template method type.
6109 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6110 protected MethodData method_data;
6111 protected ToplevelBlock block;
6112 protected ListDictionary declarative_security;
6114 // The accessor are created event if they are not wanted.
6115 // But we need them because their names are reserved.
6116 // Field says whether accessor will be emited or not
6117 public readonly bool IsDummy;
6119 protected readonly string prefix;
6121 ReturnParameter return_attributes;
6123 public AbstractPropertyEventMethod (MemberBase member, string prefix)
6124 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6126 this.prefix = prefix;
6130 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
6132 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6133 accessor.Attributes)
6135 this.prefix = prefix;
6136 this.block = accessor.Block;
6139 static MemberName SetupName (string prefix, MemberBase member, Location loc)
6141 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6144 public void UpdateName (MemberBase member)
6146 SetMemberName (SetupName (prefix, member, Location));
6149 #region IMethodData Members
6151 public ToplevelBlock Block {
6161 public CallingConventions CallingConventions {
6163 return CallingConventions.Standard;
6167 public bool IsExcluded (EmitContext ec)
6172 GenericMethod IMethodData.GenericMethod {
6178 public MemberName MethodName {
6184 public Type[] ParameterTypes {
6186 return ParameterInfo.Types;
6190 public abstract Parameters ParameterInfo { get ; }
6191 public abstract Type ReturnType { get; }
6192 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
6196 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6198 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6199 a.Type == TypeManager.conditional_attribute_type) {
6200 Report.Error (1667, a.Location,
6201 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6202 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6206 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6207 if (declarative_security == null)
6208 declarative_security = new ListDictionary ();
6209 a.ExtractSecurityPermissionSet (declarative_security);
6213 if (a.Target == AttributeTargets.Method) {
6214 method_data.MethodBuilder.SetCustomAttribute (cb);
6218 if (a.Target == AttributeTargets.ReturnValue) {
6219 if (return_attributes == null)
6220 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6222 return_attributes.ApplyAttributeBuilder (a, cb);
6226 ApplyToExtraTarget (a, cb);
6229 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6231 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6234 public override bool Define()
6236 throw new NotSupportedException ();
6239 public virtual void Emit (TypeContainer container)
6241 EmitMethod (container);
6243 if (declarative_security != null) {
6244 foreach (DictionaryEntry de in declarative_security) {
6245 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6252 protected virtual void EmitMethod (TypeContainer container)
6254 method_data.Emit (container, this);
6257 public override bool IsClsComplianceRequired(DeclSpace ds)
6262 public bool IsDuplicateImplementation (MethodCore method)
6264 if (!MemberName.Equals (method.MemberName))
6267 Type[] param_types = method.ParameterTypes;
6269 if (param_types.Length != ParameterTypes.Length)
6272 for (int i = 0; i < param_types.Length; i++)
6273 if (param_types [i] != ParameterTypes [i])
6276 Report.SymbolRelatedToPreviousError (method);
6277 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
6281 public override bool IsUsed
6291 public new Location Location {
6293 return base.Location;
6298 // Represents header string for documentation comment.
6300 public override string DocCommentHeader {
6301 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6307 // Properties and Indexers both generate PropertyBuilders, we use this to share
6308 // their common bits.
6310 abstract public class PropertyBase : MethodCore {
6312 public class GetMethod : PropertyMethod
6314 static string[] attribute_targets = new string [] { "method", "return" };
6316 public GetMethod (MethodCore method):
6317 base (method, "get_")
6321 public GetMethod (MethodCore method, Accessor accessor):
6322 base (method, accessor, "get_")
6326 public override MethodBuilder Define(TypeContainer container)
6328 base.Define (container);
6330 method_data = new MethodData (method, ModFlags, flags, this);
6332 if (!method_data.Define (container))
6335 return method_data.MethodBuilder;
6338 public override Type ReturnType {
6340 return method.MemberType;
6344 public override Parameters ParameterInfo {
6346 return Parameters.EmptyReadOnlyParameters;
6350 public override string[] ValidAttributeTargets {
6352 return attribute_targets;
6357 public class SetMethod : PropertyMethod {
6359 static string[] attribute_targets = new string [] { "method", "param", "return" };
6360 ImplicitParameter param_attr;
6361 protected Parameters parameters;
6363 public SetMethod (MethodCore method):
6364 base (method, "set_")
6368 public SetMethod (MethodCore method, Accessor accessor):
6369 base (method, accessor, "set_")
6373 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6375 if (a.Target == AttributeTargets.Parameter) {
6376 if (param_attr == null)
6377 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6379 param_attr.ApplyAttributeBuilder (a, cb);
6383 base.ApplyAttributeBuilder (a, cb);
6386 public override Parameters ParameterInfo {
6392 protected virtual void DefineParameters ()
6394 Parameter [] parms = new Parameter [1];
6395 parms [0] = new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location);
6396 parameters = new Parameters (parms);
6397 parameters.Resolve (null);
6400 public override MethodBuilder Define (TypeContainer container)
6402 if (container.EmitContext == null)
6403 throw new InternalErrorException ("SetMethod.Define called too early");
6405 DefineParameters ();
6409 base.Define (container);
6411 method_data = new MethodData (method, ModFlags, flags, this);
6413 if (!method_data.Define (container))
6416 return method_data.MethodBuilder;
6419 public override Type ReturnType {
6421 return TypeManager.void_type;
6425 public override string[] ValidAttributeTargets {
6427 return attribute_targets;
6432 static string[] attribute_targets = new string [] { "property" };
6434 public abstract class PropertyMethod : AbstractPropertyEventMethod {
6435 protected readonly MethodCore method;
6436 protected MethodAttributes flags;
6439 public PropertyMethod (MethodCore method, string prefix)
6440 : base (method, prefix)
6442 this.method = method;
6445 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6446 : base (method, accessor, prefix)
6448 this.method = method;
6449 this.ModFlags = accessor.ModFlags;
6450 yields = accessor.Yields;
6452 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6453 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6457 public override AttributeTargets AttributeTargets {
6459 return AttributeTargets.Method;
6463 public override bool IsClsComplianceRequired(DeclSpace ds)
6465 return method.IsClsComplianceRequired (ds);
6468 public virtual MethodBuilder Define (TypeContainer container)
6470 if (!method.CheckAbstractAndExtern (block != null))
6474 // Check for custom access modifier
6476 if (ModFlags == 0) {
6477 ModFlags = method.ModFlags;
6478 flags = method.flags;
6480 if (container.Kind == Kind.Interface)
6481 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6482 GetSignatureForError ());
6484 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6485 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6488 CheckModifiers (container, ModFlags);
6489 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6490 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6491 flags = Modifiers.MethodAttr (ModFlags);
6492 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6496 // Setup iterator if we are one
6499 Iterator iterator = new Iterator (this, Parent as TypeContainer, null, ModFlags);
6501 if (!iterator.DefineIterator ())
6508 public bool HasCustomAccessModifier
6511 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6515 public override EmitContext CreateEmitContext (TypeContainer tc,
6518 return new EmitContext (
6519 tc, method.ds, method.Location, ig, ReturnType,
6520 method.ModFlags, false);
6523 public override ObsoleteAttribute GetObsoleteAttribute ()
6525 return method.GetObsoleteAttribute ();
6528 public override string GetSignatureForError()
6530 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6533 void CheckModifiers (TypeContainer container, int modflags)
6536 int mflags = method.ModFlags & Modifiers.Accessibility;
6538 if ((mflags & Modifiers.PUBLIC) != 0) {
6539 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6541 else if ((mflags & Modifiers.PROTECTED) != 0) {
6542 if ((mflags & Modifiers.INTERNAL) != 0)
6543 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6545 flags |= Modifiers.PRIVATE;
6547 else if ((mflags & Modifiers.INTERNAL) != 0)
6548 flags |= Modifiers.PRIVATE;
6550 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6551 Report.Error (273, Location,
6552 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6553 GetSignatureForError (), method.GetSignatureForError ());
6557 public override bool MarkForDuplicationCheck ()
6559 caching_flags |= Flags.TestMethodDuplication;
6564 public PropertyMethod Get, Set;
6565 public PropertyBuilder PropertyBuilder;
6566 public MethodBuilder GetBuilder, SetBuilder;
6568 protected EmitContext ec;
6570 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6571 int allowed_mod, bool is_iface, MemberName name,
6572 Parameters parameters, Attributes attrs)
6573 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6578 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6580 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6581 a.Error_InvalidSecurityParent ();
6585 PropertyBuilder.SetCustomAttribute (cb);
6588 public override AttributeTargets AttributeTargets {
6590 return AttributeTargets.Property;
6594 public override bool Define ()
6599 if (!IsTypePermitted ())
6605 protected override bool DoDefine ()
6607 if (!base.DoDefine ())
6611 // Accessors modifiers check
6613 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6614 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6615 GetSignatureForError ());
6619 if ((Get.IsDummy || Set.IsDummy)
6620 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6621 Report.Error (276, Location,
6622 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6623 GetSignatureForError ());
6627 if (MemberType.IsAbstract && MemberType.IsSealed) {
6628 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6632 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6636 protected override bool CheckForDuplications ()
6638 ArrayList ar = Parent.Indexers;
6640 int arLen = ar.Count;
6642 for (int i = 0; i < arLen; i++) {
6643 Indexer m = (Indexer) ar [i];
6644 if (IsDuplicateImplementation (m))
6649 ar = Parent.Properties;
6651 int arLen = ar.Count;
6653 for (int i = 0; i < arLen; i++) {
6654 Property m = (Property) ar [i];
6655 if (IsDuplicateImplementation (m))
6663 // TODO: rename to Resolve......
6664 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6666 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6667 container.TypeBuilder, Name, ParameterTypes, null, true) as PropertyInfo;
6669 if (base_property == null)
6672 base_ret_type = base_property.PropertyType;
6673 MethodInfo get_accessor = base_property.GetGetMethod (true);
6674 MethodInfo set_accessor = base_property.GetSetMethod (true);
6675 MethodAttributes get_accessor_access, set_accessor_access;
6677 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6678 if (Get != null && !Get.IsDummy && get_accessor == null) {
6679 Report.SymbolRelatedToPreviousError (base_property);
6680 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6683 if (Set != null && !Set.IsDummy && set_accessor == null) {
6684 Report.SymbolRelatedToPreviousError (base_property);
6685 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6690 // Check base class accessors access
6693 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6694 get_accessor_access = set_accessor_access = 0;
6695 if ((ModFlags & Modifiers.NEW) == 0) {
6696 if (get_accessor != null) {
6697 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6698 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6700 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6701 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6704 if (set_accessor != null) {
6705 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6706 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6708 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6709 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6714 // Get the less restrictive access
6716 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6719 public override void Emit ()
6722 // The PropertyBuilder can be null for explicit implementations, in that
6723 // case, we do not actually emit the ".property", so there is nowhere to
6724 // put the attribute
6726 if (PropertyBuilder != null && OptAttributes != null)
6727 OptAttributes.Emit (ec, this);
6739 /// Tests whether accessors are not in collision with some method (CS0111)
6741 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6743 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6746 public override bool IsUsed
6752 return Get.IsUsed | Set.IsUsed;
6756 protected override void SetMemberName (MemberName new_name)
6758 base.SetMemberName (new_name);
6760 Get.UpdateName (this);
6761 Set.UpdateName (this);
6764 public override string[] ValidAttributeTargets {
6766 return attribute_targets;
6771 // Represents header string for documentation comment.
6773 public override string DocCommentHeader {
6774 get { return "P:"; }
6778 public class Property : PropertyBase {
6779 const int AllowedModifiers =
6782 Modifiers.PROTECTED |
6783 Modifiers.INTERNAL |
6787 Modifiers.OVERRIDE |
6788 Modifiers.ABSTRACT |
6791 Modifiers.METHOD_YIELDS |
6794 const int AllowedInterfaceModifiers =
6797 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6798 MemberName name, Attributes attrs, Accessor get_block,
6800 : base (ds, type, mod,
6801 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6802 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6804 if (get_block == null)
6805 Get = new GetMethod (this);
6807 Get = new GetMethod (this, get_block);
6809 if (set_block == null)
6810 Set = new SetMethod (this);
6812 Set = new SetMethod (this, set_block);
6815 public override bool Define ()
6817 if (!DoDefineBase ())
6820 if (!base.Define ())
6826 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6829 GetBuilder = Get.Define (Parent);
6830 if (GetBuilder == null)
6834 SetBuilder = Set.Define (Parent);
6836 if (SetBuilder == null)
6840 // FIXME - PropertyAttributes.HasDefault ?
6842 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6843 MemberName.ToString (), PropertyAttributes.None, MemberType, null);
6846 PropertyBuilder.SetGetMethod (GetBuilder);
6849 PropertyBuilder.SetSetMethod (SetBuilder);
6856 /// Gigantic workaround for lameness in SRE follows :
6857 /// This class derives from EventInfo and attempts to basically
6858 /// wrap around the EventBuilder so that FindMembers can quickly
6859 /// return this in it search for members
6861 public class MyEventBuilder : EventInfo {
6864 // We use this to "point" to our Builder which is
6865 // not really a MemberInfo
6867 EventBuilder MyBuilder;
6870 // We "catch" and wrap these methods
6872 MethodInfo raise, remove, add;
6874 EventAttributes attributes;
6875 Type declaring_type, reflected_type, event_type;
6880 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6882 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6884 // And now store the values in our own fields.
6886 declaring_type = type_builder;
6888 reflected_type = type_builder;
6890 attributes = event_attr;
6893 this.event_type = event_type;
6897 // Methods that you have to override. Note that you only need
6898 // to "implement" the variants that take the argument (those are
6899 // the "abstract" methods, the others (GetAddMethod()) are
6902 public override MethodInfo GetAddMethod (bool nonPublic)
6907 public override MethodInfo GetRemoveMethod (bool nonPublic)
6912 public override MethodInfo GetRaiseMethod (bool nonPublic)
6918 // These methods make "MyEventInfo" look like a Builder
6920 public void SetRaiseMethod (MethodBuilder raiseMethod)
6922 raise = raiseMethod;
6923 MyBuilder.SetRaiseMethod (raiseMethod);
6926 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6928 remove = removeMethod;
6929 MyBuilder.SetRemoveOnMethod (removeMethod);
6932 public void SetAddOnMethod (MethodBuilder addMethod)
6935 MyBuilder.SetAddOnMethod (addMethod);
6938 public void SetCustomAttribute (CustomAttributeBuilder cb)
6940 MyBuilder.SetCustomAttribute (cb);
6943 public override object [] GetCustomAttributes (bool inherit)
6945 // FIXME : There's nothing which can be seemingly done here because
6946 // we have no way of getting at the custom attribute objects of the
6951 public override object [] GetCustomAttributes (Type t, bool inherit)
6953 // FIXME : Same here !
6957 public override bool IsDefined (Type t, bool b)
6962 public override EventAttributes Attributes {
6968 public override string Name {
6974 public override Type DeclaringType {
6976 return declaring_type;
6980 public override Type ReflectedType {
6982 return reflected_type;
6986 public Type EventType {
6992 public void SetUsed ()
6994 if (my_event != null) {
6995 my_event.SetAssigned ();
6996 my_event.SetMemberIsUsed ();
7002 /// For case when event is declared like property (with add and remove accessors).
7004 public class EventProperty: Event {
7006 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7008 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
7009 bool is_iface, MemberName name,
7010 Attributes attrs, Accessor add, Accessor remove)
7011 : base (parent, type, mod_flags, is_iface, name, attrs)
7013 Add = new AddDelegateMethod (this, add);
7014 Remove = new RemoveDelegateMethod (this, remove);
7016 // For this event syntax we don't report error CS0067
7017 // because it is hard to do it.
7021 public override string[] ValidAttributeTargets {
7023 return attribute_targets;
7029 /// Event is declared like field.
7031 public class EventField : Event {
7033 static string[] attribute_targets = new string [] { "event", "field", "method" };
7034 static string[] attribute_targets_interface = new string[] { "event", "method" };
7036 public EventField (TypeContainer parent, Expression type, int mod_flags,
7037 bool is_iface, MemberName name,
7039 : base (parent, type, mod_flags, is_iface, name, attrs)
7041 Add = new AddDelegateMethod (this);
7042 Remove = new RemoveDelegateMethod (this);
7045 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7047 if (a.Target == AttributeTargets.Field) {
7048 FieldBuilder.SetCustomAttribute (cb);
7052 if (a.Target == AttributeTargets.Method) {
7053 Add.ApplyAttributeBuilder (a, cb);
7054 Remove.ApplyAttributeBuilder (a, cb);
7058 base.ApplyAttributeBuilder (a, cb);
7061 public override bool Define()
7063 if (!base.Define ())
7066 if (initializer != null) {
7067 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7068 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7069 GetSignatureForError ());
7077 public override string[] ValidAttributeTargets {
7079 return IsInterface ? attribute_targets_interface : attribute_targets;
7084 public abstract class Event : FieldBase {
7086 protected sealed class AddDelegateMethod: DelegateMethod
7089 public AddDelegateMethod (Event method):
7090 base (method, "add_")
7094 public AddDelegateMethod (Event method, Accessor accessor):
7095 base (method, accessor, "add_")
7099 protected override MethodInfo DelegateMethodInfo {
7101 return TypeManager.delegate_combine_delegate_delegate;
7107 protected sealed class RemoveDelegateMethod: DelegateMethod
7109 public RemoveDelegateMethod (Event method):
7110 base (method, "remove_")
7114 public RemoveDelegateMethod (Event method, Accessor accessor):
7115 base (method, accessor, "remove_")
7119 protected override MethodInfo DelegateMethodInfo {
7121 return TypeManager.delegate_remove_delegate_delegate;
7127 public abstract class DelegateMethod: AbstractPropertyEventMethod
7129 protected readonly Event method;
7130 ImplicitParameter param_attr;
7132 static string[] attribute_targets = new string [] { "method", "param", "return" };
7134 public DelegateMethod (Event method, string prefix)
7135 : base (method, prefix)
7137 this.method = method;
7140 public DelegateMethod (Event method, Accessor accessor, string prefix)
7141 : base (method, accessor, prefix)
7143 this.method = method;
7146 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7148 if (a.Target == AttributeTargets.Parameter) {
7149 if (param_attr == null)
7150 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
7152 param_attr.ApplyAttributeBuilder (a, cb);
7156 base.ApplyAttributeBuilder (a, cb);
7159 public override AttributeTargets AttributeTargets {
7161 return AttributeTargets.Method;
7165 public override bool IsClsComplianceRequired(DeclSpace ds)
7167 return method.IsClsComplianceRequired (ds);
7170 public MethodBuilder Define (TypeContainer container)
7172 method_data = new MethodData (method, method.ModFlags,
7173 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7175 if (!method_data.Define (container))
7178 MethodBuilder mb = method_data.MethodBuilder;
7179 ParameterInfo.ApplyAttributes (Parent.EmitContext, mb);
7184 protected override void EmitMethod (TypeContainer tc)
7186 if (block != null) {
7187 base.EmitMethod (tc);
7191 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7194 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
7195 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
7197 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
7198 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7199 ig.Emit (OpCodes.Ldsfld, field_info);
7200 ig.Emit (OpCodes.Ldarg_0);
7201 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7202 ig.Emit (OpCodes.Castclass, method.MemberType);
7203 ig.Emit (OpCodes.Stsfld, field_info);
7205 ig.Emit (OpCodes.Ldarg_0);
7206 ig.Emit (OpCodes.Ldarg_0);
7207 ig.Emit (OpCodes.Ldfld, field_info);
7208 ig.Emit (OpCodes.Ldarg_1);
7209 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7210 ig.Emit (OpCodes.Castclass, method.MemberType);
7211 ig.Emit (OpCodes.Stfld, field_info);
7213 ig.Emit (OpCodes.Ret);
7216 protected abstract MethodInfo DelegateMethodInfo { get; }
7218 public override Type ReturnType {
7220 return TypeManager.void_type;
7224 public override EmitContext CreateEmitContext (TypeContainer tc,
7227 return new EmitContext (
7228 tc, method.Parent, Location, ig, ReturnType,
7229 method.ModFlags, false);
7232 public override ObsoleteAttribute GetObsoleteAttribute ()
7234 return method.GetObsoleteAttribute ();
7237 public override string[] ValidAttributeTargets {
7239 return attribute_targets;
7243 public override Parameters ParameterInfo {
7245 return method.parameters;
7252 const int AllowedModifiers =
7255 Modifiers.PROTECTED |
7256 Modifiers.INTERNAL |
7261 Modifiers.OVERRIDE |
7265 const int AllowedInterfaceModifiers =
7268 public DelegateMethod Add, Remove;
7269 public MyEventBuilder EventBuilder;
7270 public MethodBuilder AddBuilder, RemoveBuilder;
7271 Parameters parameters;
7273 protected Event (TypeContainer parent, Expression type, int mod_flags,
7274 bool is_iface, MemberName name, Attributes attrs)
7275 : base (parent, type, mod_flags,
7276 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7279 IsInterface = is_iface;
7282 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7284 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7285 a.Error_InvalidSecurityParent ();
7289 EventBuilder.SetCustomAttribute (cb);
7292 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7294 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7297 public override AttributeTargets AttributeTargets {
7299 return AttributeTargets.Event;
7303 public override bool Define ()
7305 EventAttributes e_attr;
7306 e_attr = EventAttributes.None;
7308 if (!DoDefineBase ())
7314 if (!TypeManager.IsDelegateType (MemberType)) {
7315 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7319 EmitContext ec = Parent.EmitContext;
7321 throw new InternalErrorException ("Event.Define called too early?");
7322 bool old_unsafe = ec.InUnsafe;
7323 ec.InUnsafe = InUnsafe;
7325 Parameter [] parms = new Parameter [1];
7326 parms [0] = new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location);
7327 parameters = new Parameters (parms);
7328 parameters.Resolve (null);
7330 ec.InUnsafe = old_unsafe;
7336 // Now define the accessors
7339 AddBuilder = Add.Define (Parent);
7340 if (AddBuilder == null)
7343 RemoveBuilder = Remove.Define (Parent);
7344 if (RemoveBuilder == null)
7347 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7349 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7350 FieldBuilder = Parent.TypeBuilder.DefineField (
7352 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7353 TypeManager.RegisterPrivateFieldOfEvent (
7354 (EventInfo) EventBuilder, FieldBuilder);
7355 TypeManager.RegisterFieldBase (FieldBuilder, this);
7358 EventBuilder.SetAddOnMethod (AddBuilder);
7359 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7361 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7365 protected override bool CheckBase ()
7367 if (!base.CheckBase ())
7370 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7371 if (!(conflict_symbol is EventInfo)) {
7372 Report.SymbolRelatedToPreviousError (conflict_symbol);
7373 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
7381 public override void Emit ()
7383 if (OptAttributes != null) {
7384 EmitContext ec = new EmitContext (
7385 Parent, Location, null, MemberType, ModFlags);
7386 OptAttributes.Emit (ec, this);
7390 Remove.Emit (Parent);
7395 public override string GetSignatureForError ()
7397 return base.GetSignatureForError ();
7401 // Represents header string for documentation comment.
7403 public override string DocCommentHeader {
7404 get { return "E:"; }
7409 public class Indexer : PropertyBase, IIteratorContainer {
7411 class GetIndexerMethod : GetMethod
7413 public GetIndexerMethod (MethodCore method):
7418 public GetIndexerMethod (MethodCore method, Accessor accessor):
7419 base (method, accessor)
7423 public override Parameters ParameterInfo {
7425 return method.ParameterInfo;
7430 class SetIndexerMethod: SetMethod
7432 public SetIndexerMethod (MethodCore method):
7437 public SetIndexerMethod (MethodCore method, Accessor accessor):
7438 base (method, accessor)
7442 protected override void DefineParameters ()
7444 Parameter [] fixed_parms = method.Parameters.FixedParameters;
7445 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7447 fixed_parms.CopyTo (tmp, 0);
7448 tmp [fixed_parms.Length] = new Parameter (
7449 method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location);
7451 parameters = new Parameters (tmp);
7452 parameters.Resolve (null);
7456 const int AllowedModifiers =
7459 Modifiers.PROTECTED |
7460 Modifiers.INTERNAL |
7464 Modifiers.OVERRIDE |
7469 const int AllowedInterfaceModifiers =
7473 // Are we implementing an interface ?
7475 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7476 bool is_iface, Parameters parameters, Attributes attrs,
7477 Accessor get_block, Accessor set_block)
7478 : base (parent, type, mod,
7479 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7480 is_iface, name, parameters, attrs)
7482 if (get_block == null)
7483 Get = new GetIndexerMethod (this);
7485 Get = new GetIndexerMethod (this, get_block);
7487 if (set_block == null)
7488 Set = new SetIndexerMethod (this);
7490 Set = new SetIndexerMethod (this, set_block);
7493 public override bool Define ()
7495 if (!DoDefineBase ())
7498 if (!base.Define ())
7501 if (MemberType == TypeManager.void_type) {
7502 Report.Error (620, Location, "Indexers cannot have void type");
7506 if (OptAttributes != null) {
7507 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7508 if (indexer_attr != null) {
7509 // Remove the attribute from the list because it is not emitted
7510 OptAttributes.Attrs.Remove (indexer_attr);
7512 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7514 if (IsExplicitImpl) {
7515 Report.Error (415, indexer_attr.Location,
7516 "The `IndexerName' attribute is valid only on an " +
7517 "indexer that is not an explicit interface member declaration");
7521 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7522 Report.Error (609, indexer_attr.Location,
7523 "Cannot set the `IndexerName' attribute on an indexer marked override");
7527 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7528 Report.Error (633, indexer_attr.Location,
7529 "The argument to the `IndexerName' attribute must be a valid identifier");
7535 if (InterfaceType != null) {
7536 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7537 if (base_IndexerName != Name)
7538 ShortName = base_IndexerName;
7541 if (!Parent.AddToMemberContainer (this) ||
7542 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7548 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7550 GetBuilder = Get.Define (Parent);
7551 if (GetBuilder == null)
7555 // Setup iterator if we are one
7557 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7558 Iterator iterator = new Iterator (
7559 Get, Parent, null, ModFlags);
7561 if (!iterator.DefineIterator ())
7566 SetBuilder = Set.Define (Parent);
7568 if (SetBuilder == null)
7573 // Now name the parameters
7575 Parameter [] p = Parameters.FixedParameters;
7577 // TODO: should be done in parser and it needs to do cycle
7578 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7579 Report.Error (631, Location, "ref and out are not valid in this context");
7584 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7585 Name, PropertyAttributes.None, MemberType, ParameterTypes);
7588 PropertyBuilder.SetGetMethod (GetBuilder);
7591 PropertyBuilder.SetSetMethod (SetBuilder);
7593 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7598 public override string GetSignatureForError ()
7600 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7601 if (MemberName.Left != null) {
7603 sb.Append (MemberName.Left);
7606 sb.Append (".this");
7607 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7608 return sb.ToString ();
7611 public override bool MarkForDuplicationCheck ()
7613 caching_flags |= Flags.TestMethodDuplication;
7618 public class Operator : MethodCore, IIteratorContainer {
7620 const int AllowedModifiers =
7626 public enum OpType : byte {
7636 // Unary and Binary operators
7659 // Implicit and Explicit
7663 // Just because of enum
7667 public readonly OpType OperatorType;
7668 public MethodBuilder OperatorMethodBuilder;
7670 public Method OperatorMethod;
7672 static string[] attribute_targets = new string [] { "method", "return" };
7674 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7675 int mod_flags, Parameters parameters,
7676 ToplevelBlock block, Attributes attrs, Location loc)
7677 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7678 new MemberName ("op_" + type, loc), attrs, parameters)
7680 OperatorType = type;
7684 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7686 OperatorMethod.ApplyAttributeBuilder (a, cb);
7689 public override AttributeTargets AttributeTargets {
7691 return AttributeTargets.Method;
7695 protected override bool CheckForDuplications()
7697 ArrayList ar = Parent.Operators;
7699 int arLen = ar.Count;
7701 for (int i = 0; i < arLen; i++) {
7702 Operator o = (Operator) ar [i];
7703 if (IsDuplicateImplementation (o))
7708 ar = Parent.Methods;
7710 int arLen = ar.Count;
7712 for (int i = 0; i < arLen; i++) {
7713 Method m = (Method) ar [i];
7714 if (IsDuplicateImplementation (m))
7722 public override bool Define ()
7724 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7725 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7726 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7733 if (MemberType == TypeManager.void_type) {
7734 Report.Error (590, Location, "User-defined operators cannot return void");
7738 OperatorMethod = new Method (
7739 Parent, null, Type, ModFlags, false, MemberName,
7740 Parameters, OptAttributes);
7742 OperatorMethod.Block = Block;
7743 OperatorMethod.IsOperator = this;
7744 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7745 OperatorMethod.Define ();
7747 if (OperatorMethod.MethodBuilder == null)
7750 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7752 Type[] parameter_types = OperatorMethod.ParameterTypes;
7753 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7754 Type return_type = OperatorMethod.ReturnType;
7755 Type first_arg_type = parameter_types [0];
7760 // Rules for conversion operators
7762 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7763 if (first_arg_type == return_type && first_arg_type == declaring_type){
7764 Report.Error (555, Location,
7765 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7769 if (first_arg_type != declaring_type && return_type != declaring_type){
7772 "User-defined conversion must convert to or from the " +
7777 if (first_arg_type == TypeManager.object_type ||
7778 return_type == TypeManager.object_type){
7781 "User-defined conversion cannot convert to or from " +
7786 if (first_arg_type.IsInterface || return_type.IsInterface){
7787 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7788 GetSignatureForError ());
7792 if (first_arg_type.IsSubclassOf (return_type)
7793 || return_type.IsSubclassOf (first_arg_type)){
7794 if (declaring_type.IsSubclassOf (return_type)) {
7795 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7796 GetSignatureForError ());
7799 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7800 GetSignatureForError ());
7803 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7804 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7805 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");
7808 } else if (Parameters.Count == 1) {
7809 // Checks for Unary operators
7811 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7812 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7813 Report.Error (448, Location,
7814 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7817 if (first_arg_type != declaring_type){
7819 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7824 if (first_arg_type != declaring_type){
7827 "The parameter of a unary operator must be the " +
7832 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7833 if (return_type != TypeManager.bool_type){
7836 "The return type of operator True or False " +
7843 // Checks for Binary operators
7845 if (first_arg_type != declaring_type &&
7846 parameter_types [1] != declaring_type){
7849 "One of the parameters of a binary operator must " +
7850 "be the containing type");
7858 public override void Emit ()
7861 // abstract or extern methods have no bodies
7863 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7866 OperatorMethod.Emit ();
7870 // Operator cannot be override
7871 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7876 public static string GetName (OpType ot)
7879 case OpType.LogicalNot:
7881 case OpType.OnesComplement:
7883 case OpType.Increment:
7885 case OpType.Decrement:
7891 case OpType.Addition:
7893 case OpType.Subtraction:
7895 case OpType.UnaryPlus:
7897 case OpType.UnaryNegation:
7899 case OpType.Multiply:
7901 case OpType.Division:
7903 case OpType.Modulus:
7905 case OpType.BitwiseAnd:
7907 case OpType.BitwiseOr:
7909 case OpType.ExclusiveOr:
7911 case OpType.LeftShift:
7913 case OpType.RightShift:
7915 case OpType.Equality:
7917 case OpType.Inequality:
7919 case OpType.GreaterThan:
7921 case OpType.LessThan:
7923 case OpType.GreaterThanOrEqual:
7925 case OpType.LessThanOrEqual:
7927 case OpType.Implicit:
7929 case OpType.Explicit:
7935 public static OpType GetOperatorType (string name)
7937 if (name.StartsWith ("op_")){
7938 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7939 if (Unary.oper_names [i] == name)
7943 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7944 if (Binary.oper_names [i] == name)
7951 public override string GetSignatureForError ()
7953 StringBuilder sb = new StringBuilder ();
7954 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7955 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7958 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7961 sb.Append (Parameters.GetSignatureForError ());
7962 return sb.ToString ();
7965 public override bool MarkForDuplicationCheck ()
7967 caching_flags |= Flags.TestMethodDuplication;
7971 public override string[] ValidAttributeTargets {
7973 return attribute_targets;
7979 // This is used to compare method signatures
7981 struct MethodSignature {
7983 public Type RetType;
7984 public Type [] Parameters;
7987 /// This delegate is used to extract methods which have the
7988 /// same signature as the argument
7990 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7992 public MethodSignature (string name, Type ret_type, Type [] parameters)
7997 if (parameters == null)
7998 Parameters = TypeManager.NoTypes;
8000 Parameters = parameters;
8003 public override string ToString ()
8006 if (Parameters.Length != 0){
8007 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8008 for (int i = 0; i < Parameters.Length; i++){
8009 sb.Append (Parameters [i]);
8010 if (i+1 < Parameters.Length)
8013 pars = sb.ToString ();
8016 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8019 public override int GetHashCode ()
8021 return Name.GetHashCode ();
8024 public override bool Equals (Object o)
8026 MethodSignature other = (MethodSignature) o;
8028 if (other.Name != Name)
8031 if (other.RetType != RetType)
8034 if (Parameters == null){
8035 if (other.Parameters == null)
8040 if (other.Parameters == null)
8043 int c = Parameters.Length;
8044 if (other.Parameters.Length != c)
8047 for (int i = 0; i < c; i++)
8048 if (other.Parameters [i] != Parameters [i])
8054 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8056 MethodSignature sig = (MethodSignature) filter_criteria;
8058 if (m.Name != sig.Name)
8062 MethodInfo mi = m as MethodInfo;
8063 PropertyInfo pi = m as PropertyInfo;
8066 ReturnType = mi.ReturnType;
8067 else if (pi != null)
8068 ReturnType = pi.PropertyType;
8073 // we use sig.RetType == null to mean `do not check the
8074 // method return value.
8076 if (sig.RetType != null)
8077 if (ReturnType != sig.RetType)
8082 args = TypeManager.GetParameterData (mi).Types;
8084 args = TypeManager.GetArgumentTypes (pi);
8085 Type [] sigp = sig.Parameters;
8087 if (args.Length != sigp.Length)
8090 for (int i = args.Length; i > 0; ){
8092 if (args [i] != sigp [i])