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.Name);
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);
553 public void AddConstructor (Constructor c)
555 if (c.Name != MemberName.Name) {
556 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
559 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
562 if (default_static_constructor != null) {
563 Report.SymbolRelatedToPreviousError (default_static_constructor);
564 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
568 default_static_constructor = c;
571 if (default_constructor != null) {
572 Report.SymbolRelatedToPreviousError (default_constructor);
573 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
576 default_constructor = c;
579 if (instance_constructors == null)
580 instance_constructors = new MemberCoreArrayList ();
582 instance_constructors.Add (c);
586 internal static string Error111 {
588 return "`{0}' is already defined. Rename this member or use different parameter types";
592 public bool AddInterface (TypeContainer iface)
594 if (!AddToTypeContainer (iface))
597 if (interfaces == null) {
598 interfaces = new MemberCoreArrayList ();
601 interfaces.Add (iface);
605 public void AddField (FieldMember field)
607 if (!AddToMemberContainer (field))
611 fields = new MemberCoreArrayList ();
615 if ((field.ModFlags & Modifiers.STATIC) != 0)
618 if (first_nonstatic_field == null) {
619 first_nonstatic_field = field;
623 if (Kind == Kind.Struct &&
624 first_nonstatic_field.Parent != field.Parent &&
625 RootContext.WarningLevel >= 3) {
626 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
627 Report.Warning (282, 3, field.Location,
628 "struct instance field `{0}' found in different declaration from instance field `{1}'",
629 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
633 public void AddProperty (Property prop)
635 if (!AddToMemberContainer (prop) ||
636 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
639 if (properties == null)
640 properties = new MemberCoreArrayList ();
642 if (prop.MemberName.Left != null)
643 properties.Insert (0, prop);
645 properties.Add (prop);
648 public void AddEvent (Event e)
650 if (!AddToMemberContainer (e))
653 if (e is EventProperty) {
654 if (!AddToMemberContainer (e.Add))
657 if (!AddToMemberContainer (e.Remove))
662 events = new MemberCoreArrayList ();
668 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
670 public void AddIndexer (Indexer i)
672 if (indexers == null)
673 indexers = new IndexerArrayList (this);
675 if (i.IsExplicitImpl)
676 indexers.Insert (0, i);
681 public void AddOperator (Operator op)
683 if (!AddToMemberContainer (op))
686 if (operators == null)
687 operators = new OperatorArrayList (this);
692 public void AddIterator (Iterator i)
694 if (iterators == null)
695 iterators = new ArrayList ();
700 public void AddType (TypeContainer tc)
705 public void AddPart (ClassPart part)
708 parts = new ArrayList ();
713 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
715 if (a.Type == TypeManager.default_member_type) {
716 if (Indexers != null) {
717 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
722 base.ApplyAttributeBuilder (a, cb);
725 public override AttributeTargets AttributeTargets {
729 return AttributeTargets.Class;
731 return AttributeTargets.Struct;
733 return AttributeTargets.Interface;
735 throw new NotSupportedException ();
740 public ArrayList Types {
746 public MethodArrayList Methods {
752 public ArrayList Constants {
758 public ArrayList Interfaces {
764 public ArrayList Iterators {
772 return base_class_name;
776 public ArrayList Bases {
786 public ArrayList Fields {
792 public ArrayList InstanceConstructors {
794 return instance_constructors;
798 public ArrayList Properties {
804 public ArrayList Events {
810 public ArrayList Enums {
816 public ArrayList Indexers {
822 public ArrayList Operators {
828 public ArrayList Delegates {
834 public ArrayList Parts {
840 protected override TypeAttributes TypeAttr {
842 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
846 public string IndexerName {
848 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
852 public bool IsComImport {
854 if (OptAttributes == null)
857 return OptAttributes.Contains (TypeManager.comimport_attr_type, EmitContext);
861 public virtual void RegisterFieldForInitialization (FieldBase field)
863 if ((field.ModFlags & Modifiers.STATIC) != 0){
864 if (initialized_static_fields == null)
865 initialized_static_fields = new ArrayList (4);
867 initialized_static_fields.Add (field);
869 if (initialized_fields == null)
870 initialized_fields = new ArrayList (4);
872 initialized_fields.Add (field);
877 // Emits the instance field initializers
879 public virtual bool EmitFieldInitializers (EmitContext ec)
884 fields = initialized_static_fields;
886 fields = initialized_fields;
892 foreach (FieldBase f in fields) {
893 f.EmitInitializer (ec);
899 // Defines the default constructors
901 protected void DefineDefaultConstructor (bool is_static)
905 // The default constructor is public
906 // If the class is abstract, the default constructor is protected
907 // The default static constructor is private
909 int mods = Modifiers.PUBLIC;
911 mods = Modifiers.STATIC | Modifiers.PRIVATE;
912 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
913 mods = Modifiers.PROTECTED;
915 TypeContainer constructor_parent = this;
917 constructor_parent = (TypeContainer) Parts [0];
919 c = new Constructor (constructor_parent, MemberName.Name, mods,
920 Parameters.EmptyReadOnlyParameters,
921 new GeneratedBaseInitializer (Location),
926 c.Block = new ToplevelBlock (null, Location);
931 /// The pending methods that need to be implemented
932 // (interfaces or abstract methods)
934 public PendingImplementation Pending;
936 public abstract PendingImplementation GetPendingImplementations ();
938 TypeExpr[] GetPartialBases (out TypeExpr base_class)
940 ArrayList ifaces = new ArrayList ();
944 foreach (ClassPart part in parts) {
945 TypeExpr new_base_class;
946 TypeExpr[] new_ifaces;
948 new_ifaces = part.GetClassBases (out new_base_class);
949 if (new_ifaces == null && new_base_class != null)
952 if ((base_class != null) && (new_base_class != null) &&
953 !base_class.Equals (new_base_class)) {
954 Report.SymbolRelatedToPreviousError (base_class.Location, "");
955 Report.Error (263, part.Location,
956 "Partial declarations of `{0}' must " +
957 "not specify different base classes",
963 if ((base_class == null) && (new_base_class != null)) {
964 base_class = new_base_class;
967 if (new_ifaces == null)
970 foreach (TypeExpr iface in new_ifaces) {
972 foreach (TypeExpr old_iface in ifaces) {
973 if (old_iface.Equals (iface)) {
984 TypeExpr[] retval = new TypeExpr [ifaces.Count];
985 ifaces.CopyTo (retval, 0);
989 TypeExpr[] GetNormalBases (out TypeExpr base_class)
993 int count = Bases.Count;
996 if (Kind == Kind.Class){
997 TypeExpr name = ResolveBaseTypeExpr (
998 (Expression) Bases [0], false, Location);
1004 if (!name.IsInterface) {
1005 // base_class could be a class, struct, enum, delegate.
1006 // This is validated in GetClassBases.
1012 TypeExpr [] ifaces = new TypeExpr [count-start];
1014 for (i = start, j = 0; i < count; i++, j++){
1015 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1016 if (resolved == null) {
1020 ifaces [j] = resolved;
1027 /// This function computes the Base class and also the
1028 /// list of interfaces that the class or struct @c implements.
1030 /// The return value is an array (might be null) of
1031 /// interfaces implemented (as Types).
1033 /// The @base_class argument is set to the base object or null
1034 /// if this is `System.Object'.
1036 protected virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1043 ifaces = GetPartialBases (out base_class);
1044 else if (Bases == null){
1048 ifaces = GetNormalBases (out base_class);
1053 if ((base_class != null) && (Kind == Kind.Class)){
1054 if (base_class is TypeParameterExpr){
1056 689, base_class.Location,
1057 "Cannot derive from `{0}' because it is a type parameter",
1058 base_class.GetSignatureForError ());
1063 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1064 Report.Error (1521, base_class.Location, "Invalid base type");
1068 if (base_class.IsSealed){
1069 Report.SymbolRelatedToPreviousError (base_class.Type);
1070 if (base_class.Type.IsAbstract) {
1071 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
1072 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1074 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
1075 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1080 if (!base_class.CanInheritFrom ()){
1081 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
1082 GetSignatureForError (), base_class.GetSignatureForError ());
1086 if (!base_class.AsAccessible (this, ModFlags)) {
1087 Report.SymbolRelatedToPreviousError (base_class.Type);
1088 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
1089 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1093 if (base_class != null)
1094 base_class_name = base_class.Name;
1099 int count = ifaces != null ? ifaces.Length : 0;
1101 for (i = 0; i < count; i++) {
1102 TypeExpr iface = (TypeExpr) ifaces [i];
1104 if (!iface.IsInterface) {
1105 if (Kind != Kind.Class) {
1106 // TODO: location of symbol related ....
1107 Error_TypeInListIsNotInterface (Location, iface.FullName);
1109 else if (base_class != null)
1110 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1111 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1113 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1114 GetSignatureForError (), iface.GetSignatureForError ());
1119 for (int x = 0; x < i; x++) {
1120 if (iface.Equals (ifaces [x])) {
1121 Report.Error (528, Location,
1122 "`{0}' is already listed in " +
1123 "interface list", iface.Name);
1128 if ((Kind == Kind.Interface) &&
1129 !iface.AsAccessible (Parent, ModFlags)) {
1130 Report.Error (61, Location,
1131 "Inconsistent accessibility: base " +
1132 "interface `{0}' is less accessible " +
1133 "than interface `{1}'", iface.Name,
1141 bool CheckGenericInterfaces (Type[] ifaces)
1143 ArrayList already_checked = new ArrayList ();
1145 for (int i = 0; i < ifaces.Length; i++) {
1146 Type iface = ifaces [i];
1147 foreach (Type t in already_checked) {
1151 Type[] infered = new Type [CountTypeParameters];
1152 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1155 Report.Error (695, Location,
1156 "`{0}' cannot implement both `{1}' and `{2}' " +
1157 "because they may unify for some type parameter substitutions",
1158 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1159 TypeManager.CSharpName (t));
1163 already_checked.Add (iface);
1171 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1173 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1177 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1179 public override TypeBuilder DefineType ()
1184 if (TypeBuilder != null)
1187 TypeAttributes type_attributes = TypeAttr;
1191 if (TypeManager.NamespaceClash (Name, Location)) {
1196 ModuleBuilder builder = CodeGen.Module.Builder;
1197 TypeBuilder = builder.DefineType (
1198 Name, type_attributes, null, null);
1200 TypeBuilder builder = Parent.TypeBuilder;
1201 if (builder == null) {
1206 TypeBuilder = builder.DefineNestedType (
1207 Basename, type_attributes, ptype, null);
1209 } catch (ArgumentException) {
1210 Report.RuntimeMissingSupport (Location, "static classes");
1215 TypeManager.AddUserType (this);
1217 if (Parts != null) {
1219 foreach (ClassPart part in Parts) {
1220 part.TypeBuilder = TypeBuilder;
1221 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1222 part.ec.ContainerType = TypeBuilder;
1226 // Normally, we create the EmitContext here.
1227 // The only exception is if we're an Iterator - in this case,
1228 // we already have the `ec', so we don't want to create a new one.
1231 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1232 ec.ContainerType = TypeBuilder;
1236 string[] param_names = new string [TypeParameters.Length];
1237 for (int i = 0; i < TypeParameters.Length; i++)
1238 param_names [i] = TypeParameters [i].Name;
1240 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1242 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1243 for (int i = offset; i < gen_params.Length; i++)
1244 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1247 iface_exprs = GetClassBases (out base_type);
1248 if (iface_exprs == null && base_type != null) {
1254 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1255 // which in turn should have called DefineType()s on base types if necessary.
1257 // None of the code below should trigger DefineType()s on classes that we depend on.
1258 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1260 // Let's do it as soon as possible, since code below can call DefineType() on classes
1261 // that depend on us to be populated before they are.
1263 if (!(this is Iterator))
1264 RootContext.RegisterOrder (this);
1266 if (base_type == null) {
1267 if (Kind == Kind.Class){
1268 if (RootContext.StdLib)
1269 base_type = TypeManager.system_object_expr;
1270 else if (Name != "System.Object")
1271 base_type = TypeManager.system_object_expr;
1272 } else if (Kind == Kind.Struct){
1274 // If we are compiling our runtime,
1275 // and we are defining ValueType, then our
1276 // base is `System.Object'.
1278 if (!RootContext.StdLib && Name == "System.ValueType")
1279 base_type = TypeManager.system_object_expr;
1280 else if (Kind == Kind.Struct)
1281 base_type = TypeManager.system_valuetype_expr;
1285 // Avoid attributes check when parent is not set
1286 TypeResolveEmitContext.TestObsoleteMethodUsage = false;
1288 if (base_type != null) {
1289 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1290 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1291 FullNamedExpression fne = base_type.ResolveAsTypeStep (TypeResolveEmitContext);
1292 if ((fne == null) || (fne.Type == null)) {
1299 if (IsGeneric && TypeManager.IsAttributeType (ptype)) {
1300 Report.Error (698, base_type.Location,
1301 "A generic type cannot derive from `{0}' " +
1302 "because it is an attribute class",
1309 if (!CheckRecursiveDefinition (this)) {
1314 if (ptype != null) {
1315 TypeBuilder.SetParent (ptype);
1318 // Attribute is undefined at the begining of corlib compilation
1319 if (TypeManager.obsolete_attribute_type != null) {
1320 TypeResolveEmitContext.TestObsoleteMethodUsage = GetObsoleteAttribute () == null;
1321 if (ptype != null && TypeResolveEmitContext.TestObsoleteMethodUsage) {
1322 CheckObsoleteType (base_type);
1326 // add interfaces that were not added at type creation
1327 if (iface_exprs != null) {
1328 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1329 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1330 TypeResolveEmitContext.ContainerType = TypeBuilder;
1331 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1332 if (ifaces == null) {
1337 foreach (Type itype in ifaces)
1338 TypeBuilder.AddInterfaceImplementation (itype);
1340 if (!CheckGenericInterfaces (ifaces)) {
1345 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1348 if (this is Iterator && !ResolveType ()) {
1353 if (!DefineNestedTypes ()) {
1361 public bool ResolveType ()
1363 if ((base_type != null) &&
1364 (base_type.ResolveType (TypeResolveEmitContext) == null)) {
1372 TypeExpr current_type = null;
1373 if (Parts != null) {
1374 foreach (ClassPart part in Parts) {
1375 if (!part.DefineTypeParameters ()) {
1381 foreach (TypeParameter type_param in CurrentTypeParameters) {
1382 if (!type_param.Resolve (this)) {
1388 foreach (TypeParameter type_param in TypeParameters) {
1389 if (!type_param.DefineType (ec)) {
1395 current_type = new ConstructedType (
1396 TypeBuilder, TypeParameters, Location);
1399 foreach (TypeParameter type_param in TypeParameters)
1400 if (!type_param.CheckDependencies (ec)) {
1405 if (current_type != null) {
1406 current_type = current_type.ResolveAsTypeTerminal (ec);
1407 if (current_type == null) {
1412 CurrentType = current_type.ResolveType (ec);
1418 protected virtual bool DefineNestedTypes ()
1420 if (Interfaces != null) {
1421 foreach (TypeContainer iface in Interfaces)
1422 if (iface.DefineType () == null)
1426 if (Types != null) {
1427 foreach (TypeContainer tc in Types)
1428 if (tc.DefineType () == null)
1432 if (Delegates != null) {
1433 foreach (Delegate d in Delegates)
1434 if (d.DefineType () == null)
1438 if (Enums != null) {
1439 foreach (Enum en in Enums)
1440 if (en.DefineType () == null)
1447 TypeContainer InTransit;
1449 protected bool CheckRecursiveDefinition (TypeContainer tc)
1451 if (InTransit != null) {
1452 Report.SymbolRelatedToPreviousError (this);
1453 if (this is Interface)
1455 529, tc.Location, "Inherited interface `{0}' causes a " +
1456 "cycle in the interface hierarchy of `{1}'",
1457 GetSignatureForError (), tc.GetSignatureForError ());
1460 146, tc.Location, "Circular base class dependency " +
1461 "involving `{0}' and `{1}'",
1462 tc.GetSignatureForError (), GetSignatureForError ());
1468 Type parent = ptype;
1469 if (parent != null) {
1470 parent = TypeManager.DropGenericTypeArguments (parent);
1471 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1472 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1476 if (iface_exprs != null) {
1477 foreach (TypeExpr iface in iface_exprs) {
1478 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1479 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1480 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1489 public static void Error_KeywordNotAllowed (Location loc)
1491 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1495 /// Populates our TypeBuilder with fields and methods
1497 public override bool DefineMembers ()
1499 if (members_defined)
1500 return members_defined_ok;
1502 if (!base.DefineMembers ())
1505 members_defined_ok = DoDefineMembers ();
1506 members_defined = true;
1508 return members_defined_ok;
1511 protected virtual bool DoDefineMembers ()
1513 if (iface_exprs != null) {
1514 foreach (TypeExpr iface in iface_exprs) {
1515 ConstructedType ct = iface as ConstructedType;
1516 if ((ct != null) && !ct.CheckConstraints (ec))
1521 if (base_type != null) {
1522 ConstructedType ct = base_type as ConstructedType;
1523 if ((ct != null) && !ct.CheckConstraints (ec))
1528 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1529 if (conflict_symbol == null) {
1530 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1531 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1533 if ((ModFlags & Modifiers.NEW) == 0) {
1534 Report.SymbolRelatedToPreviousError (conflict_symbol);
1535 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1536 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1541 DefineContainerMembers (constants);
1542 DefineContainerMembers (fields);
1544 if ((Kind == Kind.Class) && !(this is ClassPart)){
1545 if ((instance_constructors == null) &&
1546 !(this is StaticClass)) {
1547 if (default_constructor == null)
1548 DefineDefaultConstructor (false);
1551 if (initialized_static_fields != null &&
1552 default_static_constructor == null)
1553 DefineDefaultConstructor (true);
1556 if (Kind == Kind.Struct){
1558 // Structs can not have initialized instance
1561 if (initialized_static_fields != null &&
1562 default_static_constructor == null)
1563 DefineDefaultConstructor (true);
1565 if (initialized_fields != null)
1566 ReportStructInitializedInstanceError ();
1569 Pending = GetPendingImplementations ();
1571 if (parts != null) {
1572 foreach (ClassPart part in parts) {
1573 if (!part.DefineMembers ())
1579 // Constructors are not in the defined_names array
1581 DefineContainerMembers (instance_constructors);
1583 if (default_static_constructor != null)
1584 default_static_constructor.Define ();
1586 DefineContainerMembers (properties);
1587 DefineContainerMembers (events);
1588 DefineContainerMembers (indexers);
1589 DefineContainerMembers (methods);
1590 DefineContainerMembers (operators);
1591 DefineContainerMembers (enums);
1592 DefineContainerMembers (delegates);
1594 if (CurrentType != null) {
1595 GenericType = CurrentType;
1597 ec.ContainerType = GenericType;
1602 if (!(this is ClassPart))
1603 member_cache = new MemberCache (this);
1606 if (parts != null) {
1607 foreach (ClassPart part in parts)
1608 part.member_cache = member_cache;
1611 if (iterators != null) {
1612 foreach (Iterator iterator in iterators) {
1613 if (iterator.DefineType () == null)
1617 foreach (Iterator iterator in iterators) {
1618 if (!iterator.DefineMembers ())
1626 void ReportStructInitializedInstanceError ()
1628 foreach (Field f in initialized_fields){
1629 Report.Error (573, Location,
1630 "`{0}': Structs cannot have instance field initializers",
1631 f.GetSignatureForError ());
1635 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1638 mcal.DefineContainerMembers ();
1641 public override bool Define ()
1643 if (parts != null) {
1644 foreach (ClassPart part in parts) {
1645 if (!part.Define ())
1650 if (iterators != null) {
1651 foreach (Iterator iterator in iterators) {
1652 if (!iterator.Define ())
1660 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1662 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1666 /// This function is based by a delegate to the FindMembers routine
1668 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1674 /// This filter is used by FindMembers, and we just keep
1675 /// a global for the filter to `AlwaysAccept'
1677 static MemberFilter accepting_filter;
1680 static TypeContainer ()
1682 accepting_filter = new MemberFilter (AlwaysAccept);
1685 public MethodInfo[] GetMethods ()
1687 ArrayList members = new ArrayList ();
1691 if (methods != null) {
1692 int len = methods.Count;
1693 for (int i = 0; i < len; i++) {
1694 Method m = (Method) methods [i];
1696 members.Add (m.MethodBuilder);
1700 if (operators != null) {
1701 int len = operators.Count;
1702 for (int i = 0; i < len; i++) {
1703 Operator o = (Operator) operators [i];
1705 members.Add (o.OperatorMethodBuilder);
1709 if (properties != null) {
1710 int len = properties.Count;
1711 for (int i = 0; i < len; i++) {
1712 Property p = (Property) properties [i];
1714 if (p.GetBuilder != null)
1715 members.Add (p.GetBuilder);
1716 if (p.SetBuilder != null)
1717 members.Add (p.SetBuilder);
1721 if (indexers != null) {
1722 int len = indexers.Count;
1723 for (int i = 0; i < len; i++) {
1724 Indexer ix = (Indexer) indexers [i];
1726 if (ix.GetBuilder != null)
1727 members.Add (ix.GetBuilder);
1728 if (ix.SetBuilder != null)
1729 members.Add (ix.SetBuilder);
1733 if (events != null) {
1734 int len = events.Count;
1735 for (int i = 0; i < len; i++) {
1736 Event e = (Event) events [i];
1738 if (e.AddBuilder != null)
1739 members.Add (e.AddBuilder);
1740 if (e.RemoveBuilder != null)
1741 members.Add (e.RemoveBuilder);
1745 MethodInfo[] retMethods = new MethodInfo [members.Count];
1746 members.CopyTo (retMethods, 0);
1750 // Indicated whether container has StructLayout attribute set Explicit
1751 public virtual bool HasExplicitLayout {
1757 public override Type FindNestedType (string name)
1759 ArrayList [] lists = { types, enums, delegates, interfaces };
1761 for (int j = 0; j < lists.Length; ++j) {
1762 ArrayList list = lists [j];
1766 int len = list.Count;
1767 for (int i = 0; i < len; ++i) {
1768 DeclSpace ds = (DeclSpace) list [i];
1769 if (ds.Basename == name) {
1771 return ds.TypeBuilder;
1779 private void FindMembers_NestedTypes (int modflags,
1780 BindingFlags bf, MemberFilter filter, object criteria,
1781 ref ArrayList members)
1783 ArrayList [] lists = { types, enums, delegates, interfaces };
1785 for (int j = 0; j < lists.Length; ++j) {
1786 ArrayList list = lists [j];
1790 int len = list.Count;
1791 for (int i = 0; i < len; i++) {
1792 DeclSpace ds = (DeclSpace) list [i];
1794 if ((ds.ModFlags & modflags) == 0)
1797 TypeBuilder tb = ds.TypeBuilder;
1799 if (!(criteria is string) || ds.Basename.Equals (criteria))
1800 tb = ds.DefineType ();
1803 if (tb != null && (filter (tb, criteria) == true)) {
1804 if (members == null)
1805 members = new ArrayList ();
1814 /// This method returns the members of this type just like Type.FindMembers would
1815 /// Only, we need to use this for types which are _being_ defined because MS'
1816 /// implementation can't take care of that.
1819 // FIXME: return an empty static array instead of null, that cleans up
1820 // some code and is consistent with some coding conventions I just found
1824 // Notice that in various cases we check if our field is non-null,
1825 // something that would normally mean that there was a bug elsewhere.
1827 // The problem happens while we are defining p-invoke methods, as those
1828 // will trigger a FindMembers, but this happens before things are defined
1830 // Since the whole process is a no-op, it is fine to check for null here.
1832 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1833 MemberFilter filter, object criteria)
1835 ArrayList members = null;
1838 if ((bf & BindingFlags.Public) != 0)
1839 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1841 if ((bf & BindingFlags.NonPublic) != 0)
1842 modflags |= Modifiers.PRIVATE;
1844 int static_mask = 0, static_flags = 0;
1845 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1846 case BindingFlags.Static:
1847 static_mask = static_flags = Modifiers.STATIC;
1850 case BindingFlags.Instance:
1851 static_mask = Modifiers.STATIC;
1856 static_mask = static_flags = 0;
1860 Timer.StartTimer (TimerType.TcFindMembers);
1863 filter = accepting_filter;
1865 if ((mt & MemberTypes.Field) != 0) {
1866 if (fields != null) {
1867 int len = fields.Count;
1868 for (int i = 0; i < len; i++) {
1869 FieldMember f = (FieldMember) fields [i];
1871 if ((f.ModFlags & modflags) == 0)
1873 if ((f.ModFlags & static_mask) != static_flags)
1876 FieldBuilder fb = f.FieldBuilder;
1877 if (fb != null && filter (fb, criteria) == true) {
1878 if (members == null)
1879 members = new ArrayList ();
1886 if (constants != null) {
1887 int len = constants.Count;
1888 for (int i = 0; i < len; i++) {
1889 Const con = (Const) constants [i];
1891 if ((con.ModFlags & modflags) == 0)
1893 if ((con.ModFlags & static_mask) != static_flags)
1896 FieldBuilder fb = con.FieldBuilder;
1899 fb = con.FieldBuilder;
1901 if (fb != null && filter (fb, criteria) == true) {
1902 if (members == null)
1903 members = new ArrayList ();
1911 if ((mt & MemberTypes.Method) != 0) {
1912 if (methods != null) {
1913 int len = methods.Count;
1914 for (int i = 0; i < len; i++) {
1915 Method m = (Method) methods [i];
1917 if ((m.ModFlags & modflags) == 0)
1919 if ((m.ModFlags & static_mask) != static_flags)
1922 MethodBuilder mb = m.MethodBuilder;
1924 if (mb != null && filter (mb, criteria) == true) {
1925 if (members == null)
1926 members = new ArrayList ();
1933 if (operators != null) {
1934 int len = operators.Count;
1935 for (int i = 0; i < len; i++) {
1936 Operator o = (Operator) operators [i];
1938 if ((o.ModFlags & modflags) == 0)
1940 if ((o.ModFlags & static_mask) != static_flags)
1943 MethodBuilder ob = o.OperatorMethodBuilder;
1944 if (ob != null && filter (ob, criteria) == true) {
1945 if (members == null)
1946 members = new ArrayList ();
1953 if (properties != null) {
1954 int len = properties.Count;
1955 for (int i = 0; i < len; i++) {
1956 Property p = (Property) properties [i];
1958 if ((p.ModFlags & modflags) == 0)
1960 if ((p.ModFlags & static_mask) != static_flags)
1966 if (b != null && filter (b, criteria) == true) {
1967 if (members == null)
1968 members = new ArrayList ();
1974 if (b != null && filter (b, criteria) == true) {
1975 if (members == null)
1976 members = new ArrayList ();
1983 if (indexers != null) {
1984 int len = indexers.Count;
1985 for (int i = 0; i < len; i++) {
1986 Indexer ix = (Indexer) indexers [i];
1988 if ((ix.ModFlags & modflags) == 0)
1990 if ((ix.ModFlags & static_mask) != static_flags)
1996 if (b != null && filter (b, criteria) == true) {
1997 if (members == null)
1998 members = new ArrayList ();
2004 if (b != null && filter (b, criteria) == true) {
2005 if (members == null)
2006 members = new ArrayList ();
2014 if ((mt & MemberTypes.Event) != 0) {
2015 if (events != null) {
2016 int len = events.Count;
2017 for (int i = 0; i < len; i++) {
2018 Event e = (Event) events [i];
2020 if ((e.ModFlags & modflags) == 0)
2022 if ((e.ModFlags & static_mask) != static_flags)
2025 MemberInfo eb = e.EventBuilder;
2026 if (eb != null && filter (eb, criteria) == true) {
2027 if (members == null)
2028 members = new ArrayList ();
2030 members.Add (e.EventBuilder);
2036 if ((mt & MemberTypes.Property) != 0){
2037 if (properties != null) {
2038 int len = properties.Count;
2039 for (int i = 0; i < len; i++) {
2040 Property p = (Property) properties [i];
2042 if ((p.ModFlags & modflags) == 0)
2044 if ((p.ModFlags & static_mask) != static_flags)
2047 MemberInfo pb = p.PropertyBuilder;
2048 if (pb != null && filter (pb, criteria) == true) {
2049 if (members == null)
2050 members = new ArrayList ();
2052 members.Add (p.PropertyBuilder);
2057 if (indexers != null) {
2058 int len = indexers.Count;
2059 for (int i = 0; i < len; i++) {
2060 Indexer ix = (Indexer) indexers [i];
2062 if ((ix.ModFlags & modflags) == 0)
2064 if ((ix.ModFlags & static_mask) != static_flags)
2067 MemberInfo ib = ix.PropertyBuilder;
2068 if (ib != null && filter (ib, criteria) == true) {
2069 if (members == null)
2070 members = new ArrayList ();
2072 members.Add (ix.PropertyBuilder);
2078 if ((mt & MemberTypes.NestedType) != 0)
2079 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2081 if ((mt & MemberTypes.Constructor) != 0){
2082 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2083 int len = instance_constructors.Count;
2084 for (int i = 0; i < len; i++) {
2085 Constructor c = (Constructor) instance_constructors [i];
2087 ConstructorBuilder cb = c.ConstructorBuilder;
2088 if (cb != null && filter (cb, criteria) == true) {
2089 if (members == null)
2090 members = new ArrayList ();
2097 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2098 ConstructorBuilder cb =
2099 default_static_constructor.ConstructorBuilder;
2101 if (cb != null && filter (cb, criteria) == true) {
2102 if (members == null)
2103 members = new ArrayList ();
2111 // Lookup members in base if requested.
2113 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2114 if (TypeBuilder.BaseType != null) {
2115 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2116 if (list.Count > 0) {
2117 if (members == null)
2118 members = new ArrayList ();
2120 members.AddRange (list);
2126 Timer.StopTimer (TimerType.TcFindMembers);
2128 if (members == null)
2129 return MemberList.Empty;
2131 return new MemberList (members);
2134 public override MemberCache MemberCache {
2136 return member_cache;
2140 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2141 MemberFilter filter, object criteria)
2143 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2146 return ds.FindMembers (mt, bf, filter, criteria);
2148 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2152 // FindMethods will look for methods not only in the type `t', but in
2153 // any interfaces implemented by the type.
2155 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2156 MemberFilter filter, object criteria)
2162 /// Emits the values for the constants
2164 public void EmitConstants ()
2166 if (constants != null)
2167 foreach (Const con in constants)
2172 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2177 foreach (MemberCore mc in al) {
2178 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2182 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2187 public virtual void VerifyMembers ()
2190 // Check for internal or private fields that were never assigned
2192 if (RootContext.WarningLevel >= 3) {
2193 CheckMemberUsage (properties, "property");
2194 CheckMemberUsage (methods, "method");
2195 CheckMemberUsage (constants, "constant");
2197 if (fields != null){
2198 foreach (FieldMember f in fields) {
2199 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2203 if ((f.caching_flags & Flags.IsAssigned) == 0)
2204 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2207 const int error_code = 414;
2209 const int error_code = 169;
2211 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2212 f.GetSignatureForError ());
2218 // Only report 649 on level 4
2220 if (RootContext.WarningLevel < 4)
2223 if ((f.caching_flags & Flags.IsAssigned) != 0)
2226 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2227 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2234 /// Emits the code, this step is performed after all
2235 /// the types, enumerations, constructors
2237 public virtual void EmitType ()
2239 if (OptAttributes != null)
2240 OptAttributes.Emit (ec, this);
2242 if (IsGeneric && !(this is ClassPart)) {
2243 int offset = CountTypeParameters - CurrentTypeParameters.Length;
2244 for (int i = offset; i < gen_params.Length; i++)
2245 CurrentTypeParameters [i - offset].EmitAttributes (ec);
2249 // Structs with no fields need to have at least one byte.
2250 // The right thing would be to set the PackingSize in a DefineType
2251 // but there are no functions that allow interfaces *and* the size to
2255 if (Kind == Kind.Struct && first_nonstatic_field == null){
2256 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2257 FieldAttributes.Private);
2259 if (HasExplicitLayout){
2260 object [] ctor_args = new object [1];
2263 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2264 TypeManager.field_offset_attribute_ctor, ctor_args);
2265 fb.SetCustomAttribute (cba);
2271 if (instance_constructors != null) {
2272 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired (this)) {
2273 bool has_compliant_args = false;
2275 foreach (Constructor c in instance_constructors) {
2278 if (has_compliant_args)
2281 has_compliant_args = c.HasCompliantArgs;
2283 if (!has_compliant_args)
2284 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2286 foreach (Constructor c in instance_constructors)
2291 // Can not continue if constants are broken
2293 if (Report.Errors > 0)
2296 if (default_static_constructor != null)
2297 default_static_constructor.Emit ();
2299 if (methods != null)
2300 foreach (Method m in methods)
2303 if (operators != null)
2304 foreach (Operator o in operators)
2307 if (properties != null)
2308 foreach (Property p in properties)
2311 if (indexers != null){
2316 foreach (FieldMember f in fields)
2319 if (events != null){
2320 foreach (Event e in Events)
2324 if (delegates != null) {
2325 foreach (Delegate d in Delegates) {
2330 if (enums != null) {
2331 foreach (Enum e in enums) {
2336 if (parts != null) {
2337 foreach (ClassPart part in parts)
2341 if ((Pending != null) && !(this is ClassPart))
2342 if (Pending.VerifyPendingMethods ())
2345 if (iterators != null)
2346 foreach (Iterator iterator in iterators)
2347 iterator.EmitType ();
2349 // if (types != null)
2350 // foreach (TypeContainer tc in types)
2354 public override void CloseType ()
2356 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2360 caching_flags |= Flags.CloseTypeCreated;
2361 TypeBuilder.CreateType ();
2362 } catch (TypeLoadException){
2364 // This is fine, the code still created the type
2366 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2367 // Console.WriteLine (e.Message);
2369 Console.WriteLine ("In type: " + Name);
2374 foreach (Enum en in Enums)
2378 foreach (TypeContainer tc in Types)
2379 if (tc.Kind == Kind.Struct)
2382 foreach (TypeContainer tc in Types)
2383 if (tc.Kind != Kind.Struct)
2387 if (Delegates != null)
2388 foreach (Delegate d in Delegates)
2391 if (Iterators != null)
2392 foreach (Iterator i in Iterators)
2400 initialized_fields = null;
2401 initialized_static_fields = null;
2410 default_constructor = null;
2411 default_static_constructor = null;
2413 OptAttributes = null;
2416 member_cache = null;
2420 // Performs the validation on a Method's modifiers (properties have
2421 // the same properties).
2423 public bool MethodModifiersValid (MemberCore mc)
2425 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2426 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2427 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2429 int flags = mc.ModFlags;
2432 // At most one of static, virtual or override
2434 if ((flags & Modifiers.STATIC) != 0){
2435 if ((flags & vao) != 0){
2436 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2437 mc.GetSignatureForError ());
2442 if (Kind == Kind.Struct){
2443 if ((flags & va) != 0){
2444 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2449 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2450 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2451 mc.GetSignatureForError ());
2456 // If the declaration includes the abstract modifier, then the
2457 // declaration does not include static, virtual or extern
2459 if ((flags & Modifiers.ABSTRACT) != 0){
2460 if ((flags & Modifiers.EXTERN) != 0){
2462 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2466 if ((flags & Modifiers.SEALED) != 0) {
2467 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2471 if ((flags & Modifiers.VIRTUAL) != 0){
2472 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2476 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2477 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2482 if ((flags & Modifiers.PRIVATE) != 0){
2483 if ((flags & vao) != 0){
2484 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2489 if ((flags & Modifiers.SEALED) != 0){
2490 if ((flags & Modifiers.OVERRIDE) == 0){
2491 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2499 public bool UserDefinedStaticConstructor {
2501 return default_static_constructor != null;
2505 public Constructor DefaultStaticConstructor {
2506 get { return default_static_constructor; }
2509 protected override bool VerifyClsCompliance (DeclSpace ds)
2511 if (!base.VerifyClsCompliance (ds))
2516 Type base_type = TypeBuilder.BaseType;
2517 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2518 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2521 if (!Parent.IsClsComplianceRequired (ds)) {
2522 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
2523 GetSignatureForError (), Parent.GetSignatureForError ());
2530 /// Checks whether container name is CLS Compliant
2532 void VerifyClsName ()
2534 Hashtable base_members = base_cache == null ?
2536 base_cache.GetPublicMembers ();
2537 Hashtable this_members = new Hashtable ();
2539 foreach (DictionaryEntry entry in defined_names) {
2540 MemberCore mc = (MemberCore)entry.Value;
2541 if (!mc.IsClsComplianceRequired (mc.Parent))
2544 string name = (string) entry.Key;
2545 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2547 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2548 object found = base_members [lcase];
2549 if (found == null) {
2550 found = this_members [lcase];
2551 if (found == null) {
2552 this_members.Add (lcase, mc);
2557 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2560 if (found is MemberInfo) {
2561 if (basename == ((MemberInfo) found).Name)
2563 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2565 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2567 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2573 /// Performs checks for an explicit interface implementation. First it
2574 /// checks whether the `interface_type' is a base inteface implementation.
2575 /// Then it checks whether `name' exists in the interface type.
2577 public virtual bool VerifyImplements (MemberBase mb)
2579 if (ifaces != null) {
2580 foreach (Type t in ifaces){
2581 if (t == mb.InterfaceType)
2586 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2587 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2591 public virtual void Mark_HasEquals ()
2593 Methods.HasEquals = true;
2596 public virtual void Mark_HasGetHashCode ()
2598 Methods.HasGetHashCode = true;
2605 string IMemberContainer.Name {
2611 Type IMemberContainer.Type {
2617 MemberCache IMemberContainer.MemberCache {
2619 return member_cache;
2623 bool IMemberContainer.IsInterface {
2625 return Kind == Kind.Interface;
2629 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2631 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2633 if (GenericType != null)
2634 return TypeManager.FindMembers (GenericType, mt, new_bf,
2637 return FindMembers (mt, new_bf, null, null);
2641 // Generates xml doc comments (if any), and if required,
2642 // handle warning report.
2644 internal override void GenerateDocComment (DeclSpace ds)
2646 DocUtil.GenerateTypeDocComment (this, ds);
2649 public override string DocCommentHeader {
2650 get { return "T:"; }
2653 public virtual MemberCache BaseCache {
2655 if (base_cache != null)
2657 if (TypeBuilder.BaseType != null)
2658 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2659 if (TypeBuilder.IsInterface)
2660 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2667 public class PartialContainer : TypeContainer {
2669 public readonly Namespace Namespace;
2670 public readonly int OriginalModFlags;
2671 public readonly int AllowedModifiers;
2672 public readonly TypeAttributes DefaultTypeAttributes;
2673 public ListDictionary DeclarativeSecurity;
2675 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2676 MemberName member_name, int mod_flags, Kind kind)
2679 if (!CheckModFlags (0, mod_flags, member_name))
2682 PartialContainer pc = RootContext.Tree.GetDecl (member_name) as PartialContainer;
2684 if (pc.Kind != kind) {
2686 261, member_name.Location,
2687 "Partial declarations of `{0}' must be all classes, " +
2688 "all structs or all interfaces",
2689 member_name.GetTypeName ());
2693 if (!CheckModFlags (pc.OriginalModFlags, mod_flags, member_name))
2695 pc.ModFlags |= (mod_flags & pc.AllowedModifiers);
2698 if (pc.CountTypeParameters != member_name.CountTypeArguments) {
2700 264, member_name.Location,
2701 "Partial declarations of `{0}' must have the " +
2702 "same type parameter names in the same order",
2703 member_name.GetTypeName ());
2707 TypeParameterName[] pc_names = pc.MemberName.TypeArguments.GetDeclarations ();
2708 TypeParameterName[] names = member_name.TypeArguments.GetDeclarations ();
2710 for (int i = 0; i < pc.CountTypeParameters; i++) {
2711 if (pc_names [i].Name == names [i].Name)
2715 264, member_name.Location,
2716 "Partial declarations of `{0}' must have the " +
2717 "same type parameter names in the same order",
2718 member_name.GetTypeName ());
2726 if (parent is ClassPart)
2727 parent = ((ClassPart) parent).PartialContainer;
2729 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind);
2731 if (kind == Kind.Interface) {
2732 if (!parent.AddInterface (pc))
2734 } else if (kind == Kind.Class || kind == Kind.Struct) {
2735 if (!parent.AddClassOrStruct (pc))
2738 throw new InvalidOperationException ();
2740 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2741 // This is needed to define our type parameters; we define the constraints later.
2742 pc.SetParameterInfo (null);
2746 static bool CheckModFlags (int flags_org, int flags, MemberName member_name)
2748 // Check (abstract|static|sealed) sanity.
2749 int tmp = (flags_org | flags) & (Modifiers.ABSTRACT | Modifiers.SEALED | Modifiers.STATIC);
2750 if ((tmp & Modifiers.ABSTRACT) != 0) {
2751 if ((tmp & (Modifiers.STATIC | Modifiers.SEALED)) != 0) {
2753 418, member_name.Location,
2754 "`{0}': an abstract class cannot be sealed or static", member_name.ToString ());
2757 } else if (tmp == (Modifiers.SEALED | Modifiers.STATIC)) {
2758 Report.Error (441, member_name.Location, "`{0}': a class cannot be both static and sealed", member_name.ToString ());
2766 if (0 != ((flags_org ^ flags) & (0xFFFFFFFF ^ (Modifiers.SEALED | Modifiers.ABSTRACT)))) {
2768 262, member_name.Location, "Partial declarations of `{0}' " +
2769 "have conflicting accessibility modifiers",
2770 member_name.GetName ());
2776 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2777 MemberName name, int mod, Attributes attrs,
2778 Kind kind, Location loc)
2780 PartialContainer pc = Create (ns, parent, name, mod, kind);
2782 // An error occured; create a dummy container, but don't
2784 pc = new PartialContainer (ns.NS, parent, name, mod, kind);
2787 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind);
2792 protected PartialContainer (Namespace ns, TypeContainer parent,
2793 MemberName name, int mod, Kind kind)
2794 : base (null, parent, name, null, kind)
2796 this.Namespace = ns;
2800 AllowedModifiers = Class.AllowedModifiers;
2801 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2805 AllowedModifiers = Struct.AllowedModifiers;
2806 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2809 case Kind.Interface:
2810 AllowedModifiers = Interface.AllowedModifiers;
2811 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2815 throw new InvalidOperationException ();
2819 if (parent.Parent == null)
2820 accmods = Modifiers.INTERNAL;
2822 accmods = Modifiers.PRIVATE;
2824 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2825 this.OriginalModFlags = mod;
2828 public override void EmitType ()
2832 if (DeclarativeSecurity != null) {
2833 foreach (DictionaryEntry de in DeclarativeSecurity) {
2834 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2839 public override PendingImplementation GetPendingImplementations ()
2841 return PendingImplementation.GetPendingImplementations (this);
2844 public override bool MarkForDuplicationCheck ()
2849 protected override TypeAttributes TypeAttr {
2851 return base.TypeAttr | DefaultTypeAttributes;
2856 public class ClassPart : TypeContainer, IMemberContainer {
2857 public readonly PartialContainer PartialContainer;
2858 public readonly bool IsPartial;
2860 Constraints[] constraints;
2862 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2863 int mod, Attributes attrs, Kind kind)
2864 : base (ns, parent, pc.MemberName, attrs, kind)
2866 this.PartialContainer = pc;
2867 this.IsPartial = true;
2870 if (parent == null || parent == RootContext.Tree.Types)
2871 accmods = Modifiers.INTERNAL;
2873 accmods = Modifiers.PRIVATE;
2875 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, pc.MemberName.Location);
2878 constraints = new Constraints [pc.CountCurrentTypeParameters];
2881 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2883 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2884 if (PartialContainer.DeclarativeSecurity == null)
2885 PartialContainer.DeclarativeSecurity = new ListDictionary ();
2887 a.ExtractSecurityPermissionSet (PartialContainer.DeclarativeSecurity);
2891 base.ApplyAttributeBuilder (a, cb);
2894 public override PendingImplementation GetPendingImplementations ()
2896 return PartialContainer.Pending;
2899 public override bool VerifyImplements (MemberBase mb)
2901 return PartialContainer.VerifyImplements (mb);
2904 public override void SetParameterInfo (ArrayList constraints_list)
2906 if (constraints_list == null)
2909 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2910 for (int i = 0; i < constraints.Length; i++) {
2911 foreach (Constraints constraint in constraints_list) {
2912 if (constraint.TypeParameter == current_params [i].Name) {
2913 constraints [i] = constraint;
2920 public bool DefineTypeParameters ()
2922 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2924 for (int i = 0; i < current_params.Length; i++) {
2925 Constraints new_constraints = constraints [i];
2926 if (new_constraints == null)
2929 if (!current_params [i].UpdateConstraints (ec, new_constraints)) {
2930 Report.Error (265, Location, "Partial declarations of `{0}' have " +
2931 "inconsistent constraints for type parameter `{1}'.",
2932 MemberName.GetTypeName (), current_params [i].Name);
2937 for (int i = 0; i < current_params.Length; i++) {
2938 if (!current_params [i].Resolve (this))
2942 foreach (TypeParameter type_param in PartialContainer.TypeParameters) {
2943 if (!type_param.DefineType (ec))
2950 public override void RegisterFieldForInitialization (FieldBase field)
2952 PartialContainer.RegisterFieldForInitialization (field);
2955 public override bool EmitFieldInitializers (EmitContext ec)
2957 return PartialContainer.EmitFieldInitializers (ec);
2960 public override Type FindNestedType (string name)
2962 return PartialContainer.FindNestedType (name);
2965 public override MemberCache BaseCache {
2967 return PartialContainer.BaseCache;
2971 public override TypeBuilder DefineType ()
2973 throw new InternalErrorException ("Should not get here");
2976 public override void Mark_HasEquals ()
2978 PartialContainer.Mark_HasEquals ();
2981 public override void Mark_HasGetHashCode ()
2983 PartialContainer.Mark_HasGetHashCode ();
2987 public abstract class ClassOrStruct : TypeContainer {
2988 bool has_explicit_layout = false;
2989 ListDictionary declarative_security;
2991 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2992 MemberName name, Attributes attrs, Kind kind)
2993 : base (ns, parent, name, attrs, kind)
2997 public override PendingImplementation GetPendingImplementations ()
2999 return PendingImplementation.GetPendingImplementations (this);
3002 public override bool HasExplicitLayout {
3004 return has_explicit_layout;
3008 public override void VerifyMembers ()
3010 base.VerifyMembers ();
3012 if ((events != null) && (RootContext.WarningLevel >= 3)) {
3013 foreach (Event e in events){
3014 if ((e.caching_flags & Flags.IsAssigned) == 0)
3015 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
3020 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3022 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3023 if (declarative_security == null)
3024 declarative_security = new ListDictionary ();
3026 a.ExtractSecurityPermissionSet (declarative_security);
3030 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
3031 has_explicit_layout = true;
3033 base.ApplyAttributeBuilder (a, cb);
3036 public override void Emit()
3040 if (declarative_security != null) {
3041 foreach (DictionaryEntry de in declarative_security) {
3042 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3049 /// Class handles static classes declaration
3051 public sealed class StaticClass: Class {
3052 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3054 : base (ns, parent, name, mod, attrs)
3056 if (RootContext.Version == LanguageVersion.ISO_1) {
3057 Report.FeatureIsNotStandardized (Location, "static classes");
3061 protected override int AllowedModifiersProp {
3063 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
3064 Modifiers.STATIC | Modifiers.UNSAFE;
3068 protected override void DefineContainerMembers (MemberCoreArrayList list)
3073 foreach (MemberCore m in list) {
3074 if (m is Operator) {
3075 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
3079 if (m is Destructor) {
3080 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
3084 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
3085 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
3090 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
3094 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
3097 if (m is Constructor) {
3098 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
3102 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
3105 base.DefineContainerMembers (list);
3108 public override TypeBuilder DefineType()
3110 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
3111 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
3115 TypeBuilder tb = base.DefineType ();
3119 if (ptype != TypeManager.object_type) {
3120 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
3124 if (ifaces != null) {
3125 foreach (Type t in ifaces)
3126 Report.SymbolRelatedToPreviousError (t);
3127 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
3132 protected override TypeAttributes TypeAttr {
3134 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
3139 public class Class : ClassOrStruct {
3140 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
3141 public const int AllowedModifiers =
3144 Modifiers.PROTECTED |
3145 Modifiers.INTERNAL |
3147 Modifiers.ABSTRACT |
3151 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3153 : base (ns, parent, name, attrs, Kind.Class)
3155 this.ModFlags = mod;
3158 virtual protected int AllowedModifiersProp {
3160 return AllowedModifiers;
3164 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
3166 if (a.Type == TypeManager.attribute_usage_type) {
3167 if (ptype != TypeManager.attribute_type &&
3168 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
3169 TypeBuilder.FullName != "System.Attribute") {
3170 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
3174 if (a.Type == TypeManager.conditional_attribute_type &&
3175 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
3176 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
3180 if (AttributeTester.IsAttributeExcluded (a.Type))
3183 base.ApplyAttributeBuilder (a, cb);
3186 public const TypeAttributes DefaultTypeAttributes =
3187 TypeAttributes.AutoLayout | TypeAttributes.Class;
3189 public override TypeBuilder DefineType()
3191 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
3192 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
3196 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
3197 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
3199 return base.DefineType ();
3202 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3203 /// Valid only for attribute classes.
3204 public bool IsExcluded ()
3206 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3207 return (caching_flags & Flags.Excluded) != 0;
3209 caching_flags &= ~Flags.Excluded_Undetected;
3211 if (OptAttributes == null)
3214 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3219 foreach (Attribute a in attrs) {
3220 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3221 if (RootContext.AllDefines.Contains (condition))
3225 caching_flags |= Flags.Excluded;
3230 // FIXME: How do we deal with the user specifying a different
3233 protected override TypeAttributes TypeAttr {
3235 return base.TypeAttr | DefaultTypeAttributes;
3240 public class Struct : ClassOrStruct {
3242 // Modifiers allowed in a struct declaration
3244 public const int AllowedModifiers =
3247 Modifiers.PROTECTED |
3248 Modifiers.INTERNAL |
3252 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
3253 int mod, Attributes attrs)
3254 : base (ns, parent, name, attrs, Kind.Struct)
3258 if (parent.Parent == null)
3259 accmods = Modifiers.INTERNAL;
3261 accmods = Modifiers.PRIVATE;
3263 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3265 this.ModFlags |= Modifiers.SEALED;
3268 public const TypeAttributes DefaultTypeAttributes =
3269 TypeAttributes.SequentialLayout |
3270 TypeAttributes.Sealed |
3271 TypeAttributes.BeforeFieldInit;
3274 // FIXME: Allow the user to specify a different set of attributes
3275 // in some cases (Sealed for example is mandatory for a class,
3276 // but what SequentialLayout can be changed
3278 protected override TypeAttributes TypeAttr {
3280 return base.TypeAttr | DefaultTypeAttributes;
3288 public class Interface : TypeContainer, IMemberContainer {
3291 /// Modifiers allowed in a class declaration
3293 public const int AllowedModifiers =
3296 Modifiers.PROTECTED |
3297 Modifiers.INTERNAL |
3301 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3303 : base (ns, parent, name, attrs, Kind.Interface)
3307 if (parent.Parent == null)
3308 accmods = Modifiers.INTERNAL;
3310 accmods = Modifiers.PRIVATE;
3312 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3315 public override PendingImplementation GetPendingImplementations ()
3320 public const TypeAttributes DefaultTypeAttributes =
3321 TypeAttributes.AutoLayout |
3322 TypeAttributes.Abstract |
3323 TypeAttributes.Interface;
3325 protected override TypeAttributes TypeAttr {
3327 return base.TypeAttr | DefaultTypeAttributes;
3331 protected override bool VerifyClsCompliance (DeclSpace ds)
3333 if (!base.VerifyClsCompliance (ds))
3336 if (ifaces != null) {
3337 foreach (Type t in ifaces) {
3338 if (AttributeTester.IsClsCompliant (t))
3341 Report.SymbolRelatedToPreviousError (t);
3342 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3343 GetSignatureForError (), TypeManager.CSharpName (t));
3351 public abstract class MethodCore : MemberBase {
3352 public readonly Parameters Parameters;
3353 protected ToplevelBlock block;
3355 // Whether this is an operator method.
3356 public Operator IsOperator;
3359 // The method we're overriding if this is an override method.
3361 protected MethodInfo base_method = null;
3363 static string[] attribute_targets = new string [] { "method", "return" };
3365 public MethodCore (TypeContainer parent, GenericMethod generic,
3366 Expression type, int mod, int allowed_mod, bool is_iface,
3367 MemberName name, Attributes attrs, Parameters parameters)
3368 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3371 Parameters = parameters;
3372 IsInterface = is_iface;
3376 // Returns the System.Type array for the parameters of this method
3378 public Type [] ParameterTypes {
3380 return Parameters.Types;
3384 public Parameters ParameterInfo
3391 public override EmitContext EmitContext {
3392 get { return ds.EmitContext; }
3395 public ToplevelBlock Block {
3405 public void SetYields ()
3407 ModFlags |= Modifiers.METHOD_YIELDS;
3410 protected override bool CheckBase ()
3412 if (!base.CheckBase ())
3415 // Check whether arguments were correct.
3416 if (!DoDefineParameters ())
3419 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3425 // Is null for System.Object while compiling corlib and base interfaces
3426 if (Parent.BaseCache == null) {
3427 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3428 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3433 Type base_ret_type = null;
3434 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3436 // method is override
3437 if (base_method != null) {
3439 if (!CheckMethodAgainstBase ())
3442 if ((ModFlags & Modifiers.NEW) == 0) {
3443 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_ret_type))) {
3444 Report.SymbolRelatedToPreviousError (base_method);
3445 if (this is PropertyBase) {
3446 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3447 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3450 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3451 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3456 if (base_method.IsAbstract && !IsInterface) {
3457 Report.SymbolRelatedToPreviousError (base_method);
3458 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3459 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3464 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3465 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3469 if (Name == "Equals" && Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type)
3470 Parent.Mark_HasEquals ();
3471 else if (Name == "GetHashCode" && Parameters.Empty)
3472 Parent.Mark_HasGetHashCode ();
3474 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3475 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3477 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3478 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3479 Report.SymbolRelatedToPreviousError (base_method);
3480 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3481 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3488 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3489 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3490 if (conflict_symbol != null) {
3491 Report.SymbolRelatedToPreviousError (conflict_symbol);
3492 if (this is PropertyBase)
3493 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3495 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3497 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3501 if (conflict_symbol == null) {
3502 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3503 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3508 if ((ModFlags & Modifiers.NEW) == 0) {
3509 if (this is Method && conflict_symbol is MethodBase)
3512 Report.SymbolRelatedToPreviousError (conflict_symbol);
3513 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3514 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3521 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3522 // that have been defined.
3524 // `name' is the user visible name for reporting errors (this is used to
3525 // provide the right name regarding method names and properties)
3527 bool CheckMethodAgainstBase ()
3531 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3532 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3533 Report.Error (506, Location,
3534 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3535 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3539 // Now we check that the overriden method is not final
3541 if (base_method.IsFinal) {
3542 Report.SymbolRelatedToPreviousError (base_method);
3543 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3544 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3548 // Check that the permissions are not being changed
3550 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3551 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3553 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3554 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3559 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3560 ModFlags |= Modifiers.NEW;
3561 Report.SymbolRelatedToPreviousError (base_method);
3562 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3563 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",
3564 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3566 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3567 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3574 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3576 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3578 // when overriding protected internal, the method can be declared
3579 // protected internal only within the same assembly
3582 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3583 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3585 // assemblies differ - report an error
3589 } else if (thisp != base_classp) {
3591 // same assembly, but other attributes differ - report an error
3596 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3598 // if it's not "protected internal", it must be "protected"
3602 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3604 // protected within the same assembly - an error
3607 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3608 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3610 // protected ok, but other attributes differ - report an error
3616 return (thisp == base_classp);
3620 public bool CheckAbstractAndExtern (bool has_block)
3622 if (Parent.Kind == Kind.Interface)
3626 if ((ModFlags & Modifiers.EXTERN) != 0) {
3627 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3628 GetSignatureForError ());
3632 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3633 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3634 GetSignatureForError ());
3638 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3639 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3640 GetSignatureForError ());
3648 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3650 Report.SymbolRelatedToPreviousError (base_method);
3651 string base_name = TypeManager.GetFullNameSignature (base_method);
3652 string this_name = GetSignatureForError ();
3653 if (suffix != null) {
3654 base_name += suffix;
3655 this_name += suffix;
3658 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3659 this_name, Modifiers.GetDescription (ma), base_name);
3662 protected static string Error722 {
3664 return "`{0}': static types cannot be used as return types";
3669 /// For custom member duplication search in a container
3671 protected abstract bool CheckForDuplications ();
3674 /// Gets base method and its return type
3676 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3678 protected bool DoDefineParameters ()
3680 EmitContext ec = ds.EmitContext;
3682 throw new InternalErrorException ("DoDefineParameters invoked too early");
3684 bool old_unsafe = ec.InUnsafe;
3685 ec.InUnsafe = InUnsafe;
3686 ec.ResolvingGenericMethod = GenericMethod != null;
3688 bool old_obsolete = ec.TestObsoleteMethodUsage;
3689 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute () != null)
3690 ec.TestObsoleteMethodUsage = false;
3692 // Check if arguments were correct
3693 if (!Parameters.Resolve (ec))
3696 ec.ResolvingGenericMethod = false;
3697 ec.InUnsafe = old_unsafe;
3698 ec.TestObsoleteMethodUsage = old_obsolete;
3700 return CheckParameters (ParameterTypes);
3703 bool CheckParameters (Type [] parameters)
3707 foreach (Type partype in parameters){
3708 if (partype == TypeManager.void_type) {
3710 1547, Location, "Keyword 'void' cannot " +
3711 "be used in this context");
3715 if (partype.IsPointer){
3718 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3722 if (ds.AsAccessible (partype, ModFlags))
3725 if (this is Indexer)
3726 Report.Error (55, Location,
3727 "Inconsistent accessibility: parameter type `" +
3728 TypeManager.CSharpName (partype) + "' is less " +
3729 "accessible than indexer `" + GetSignatureForError () + "'");
3730 else if ((this is Method) && ((Method) this).IsOperator != null)
3731 Report.Error (57, Location,
3732 "Inconsistent accessibility: parameter type `" +
3733 TypeManager.CSharpName (partype) + "' is less " +
3734 "accessible than operator `" + GetSignatureForError () + "'");
3736 Report.Error (51, Location,
3737 "Inconsistent accessibility: parameter type `" +
3738 TypeManager.CSharpName (partype) + "' is less " +
3739 "accessible than method `" + GetSignatureForError () + "'");
3746 public override string[] ValidAttributeTargets {
3748 return attribute_targets;
3752 protected override bool VerifyClsCompliance (DeclSpace ds)
3754 if (!base.VerifyClsCompliance (ds)) {
3755 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsComplianceRequired (ds)) {
3756 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3761 if (Parameters.HasArglist) {
3762 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3765 if (!AttributeTester.IsClsCompliant (MemberType)) {
3766 if (this is PropertyBase)
3767 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3768 GetSignatureForError ());
3770 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3771 GetSignatureForError ());
3774 Parameters.VerifyClsCompliance ();
3779 protected bool IsDuplicateImplementation (MethodCore method)
3781 if (method == this || !(method.MemberName.Equals (MemberName)))
3784 Type[] param_types = method.ParameterTypes;
3785 // This never happen. Rewrite this as Equal
3786 if (param_types == null && ParameterTypes == null)
3788 if (param_types == null || ParameterTypes == null)
3791 if (param_types.Length != ParameterTypes.Length)
3794 if (method.Parameters.HasArglist != Parameters.HasArglist)
3799 for (int i = 0; i < param_types.Length; i++) {
3800 if (param_types [i] != ParameterTypes [i])
3804 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3807 // TODO: make operator compatible with MethodCore to avoid this
3808 if (this is Operator && method is Operator) {
3809 if (MemberType != method.MemberType)
3815 // Try to report 663: method only differs on out/ref
3817 Parameters info = ParameterInfo;
3818 Parameters other_info = method.ParameterInfo;
3819 for (int i = 0; i < info.Count; i++){
3821 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3822 Report.SymbolRelatedToPreviousError (method);
3823 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3824 GetSignatureForError ());
3827 Console.WriteLine ("Method is: {0} {1}", method.Location, method);
3828 Console.WriteLine ("this is: {0} {1}", Location, this);
3832 Report.SymbolRelatedToPreviousError (method);
3833 if (this is Operator && method is Operator)
3834 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3836 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3844 public override bool IsUsed {
3845 get { return IsExplicitImpl || base.IsUsed; }
3849 // Returns a string that represents the signature for this
3850 // member which should be used in XML documentation.
3852 public override string GetDocCommentName (DeclSpace ds)
3854 return DocUtil.GetMethodDocCommentName (this, ds);
3858 // Raised (and passed an XmlElement that contains the comment)
3859 // when GenerateDocComment is writing documentation expectedly.
3861 // FIXME: with a few effort, it could be done with XmlReader,
3862 // that means removal of DOM use.
3864 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3866 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3870 // Represents header string for documentation comment.
3872 public override string DocCommentHeader {
3873 get { return "M:"; }
3878 public class SourceMethod : ISourceMethod
3880 TypeContainer container;
3883 protected SourceMethod (TypeContainer container, MethodBase builder,
3884 ISourceFile file, Location start, Location end)
3886 this.container = container;
3887 this.builder = builder;
3889 CodeGen.SymbolWriter.OpenMethod (
3890 file, this, start.Row, start.Column, end.Row, start.Column);
3893 public string Name {
3894 get { return builder.Name; }
3897 public int NamespaceID {
3898 get { return container.NamespaceEntry.SymbolFileID; }
3903 if (builder is MethodBuilder)
3904 return ((MethodBuilder) builder).GetToken ().Token;
3905 else if (builder is ConstructorBuilder)
3906 return ((ConstructorBuilder) builder).GetToken ().Token;
3908 throw new NotSupportedException ();
3912 public void CloseMethod ()
3914 if (CodeGen.SymbolWriter != null)
3915 CodeGen.SymbolWriter.CloseMethod ();
3918 public static SourceMethod Create (TypeContainer parent,
3919 MethodBase builder, Block block)
3921 if (CodeGen.SymbolWriter == null)
3926 Location start_loc = block.StartLocation;
3927 if (start_loc.IsNull)
3930 Location end_loc = block.EndLocation;
3934 ISourceFile file = start_loc.SourceFile;
3938 return new SourceMethod (
3939 parent, builder, file, start_loc, end_loc);
3943 public class Method : MethodCore, IIteratorContainer, IMethodData {
3944 public MethodBuilder MethodBuilder;
3945 public MethodData MethodData;
3946 ReturnParameter return_attributes;
3947 ListDictionary declarative_security;
3950 /// Modifiers allowed in a class declaration
3952 const int AllowedModifiers =
3955 Modifiers.PROTECTED |
3956 Modifiers.INTERNAL |
3961 Modifiers.OVERRIDE |
3962 Modifiers.ABSTRACT |
3964 Modifiers.METHOD_YIELDS |
3967 const int AllowedInterfaceModifiers =
3968 Modifiers.NEW | Modifiers.UNSAFE;
3971 // return_type can be "null" for VOID values.
3973 public Method (TypeContainer parent, GenericMethod generic,
3974 Expression return_type, int mod, bool is_iface,
3975 MemberName name, Parameters parameters, Attributes attrs)
3976 : base (parent, generic, return_type, mod,
3977 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3978 is_iface, name, attrs, parameters)
3982 public override AttributeTargets AttributeTargets {
3984 return AttributeTargets.Method;
3988 public override string GetSignatureForError()
3990 if (IsOperator != null)
3991 return IsOperator.GetSignatureForError ();
3993 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3996 void DuplicateEntryPoint (MethodInfo b, Location location)
4000 "Program `" + CodeGen.FileName +
4001 "' has more than one entry point defined: `" +
4002 TypeManager.CSharpSignature(b) + "'");
4005 bool IsEntryPoint (MethodBuilder b, Parameters pinfo)
4007 if (b.ReturnType != TypeManager.void_type &&
4008 b.ReturnType != TypeManager.int32_type)
4011 if (pinfo.Count == 0)
4014 if (pinfo.Count > 1)
4017 Type t = pinfo.ParameterType(0);
4019 (t.GetArrayRank() == 1) &&
4020 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
4021 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
4027 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4029 if (a.Target == AttributeTargets.ReturnValue) {
4030 if (return_attributes == null)
4031 return_attributes = new ReturnParameter (MethodBuilder, Location);
4033 return_attributes.ApplyAttributeBuilder (a, cb);
4037 if (a.Type == TypeManager.methodimpl_attr_type &&
4038 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4039 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4042 if (a.Type == TypeManager.dllimport_type) {
4043 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4044 if ((ModFlags & extern_static) != extern_static) {
4045 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
4051 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4052 if (declarative_security == null)
4053 declarative_security = new ListDictionary ();
4054 a.ExtractSecurityPermissionSet (declarative_security);
4058 if (a.Type == TypeManager.conditional_attribute_type) {
4059 if (IsOperator != null || IsExplicitImpl) {
4060 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4061 GetSignatureForError ());
4065 if (ReturnType != TypeManager.void_type) {
4066 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4070 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4071 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4076 Report.Error (582, Location, "Conditional not valid on interface members");
4080 if (MethodData.implementing != null) {
4081 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4082 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4086 for (int i = 0; i < ParameterInfo.Count; ++i) {
4087 if ((ParameterInfo.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
4088 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4094 MethodBuilder.SetCustomAttribute (cb);
4097 protected override bool CheckForDuplications ()
4099 ArrayList ar = Parent.Methods;
4101 int arLen = ar.Count;
4103 for (int i = 0; i < arLen; i++) {
4104 Method m = (Method) ar [i];
4105 if (IsDuplicateImplementation (m))
4110 ar = Parent.Properties;
4112 for (int i = 0; i < ar.Count; ++i) {
4113 PropertyBase pb = (PropertyBase) ar [i];
4114 if (pb.AreAccessorsDuplicateImplementation (this))
4119 ar = Parent.Indexers;
4121 for (int i = 0; i < ar.Count; ++i) {
4122 PropertyBase pb = (PropertyBase) ar [i];
4123 if (pb.AreAccessorsDuplicateImplementation (this))
4130 for (int i = 0; i < ar.Count; ++i) {
4131 Event ev = (Event) ar [i];
4132 if (ev.AreAccessorsDuplicateImplementation (this))
4143 public override bool Define ()
4145 if (!DoDefineBase ())
4148 MethodBuilder mb = null;
4149 if (GenericMethod != null) {
4150 string method_name = MemberName.Name;
4152 if (IsExplicitImpl) {
4153 method_name = TypeManager.CSharpName (InterfaceType) +
4157 mb = Parent.TypeBuilder.DefineGenericMethod (method_name, flags);
4158 if (!GenericMethod.Define (mb))
4165 if (!CheckAbstractAndExtern (block != null))
4168 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4169 Error1599 (Location, ReturnType);
4176 if (IsOperator != null)
4177 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
4179 MethodData = new MethodData (this, ModFlags, flags, this, mb, GenericMethod, base_method);
4181 if (!MethodData.Define (Parent))
4184 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4185 Name == "Finalize" && !(this is Destructor)) {
4186 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4190 // Setup iterator if we are one
4192 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4193 Iterator iterator = new Iterator (
4194 this, Parent, GenericMethod, ModFlags);
4196 if (!iterator.DefineIterator ())
4200 MethodBuilder = MethodData.MethodBuilder;
4203 // This is used to track the Entry Point,
4205 if (Name == "Main" &&
4206 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
4207 (RootContext.MainClass == null ||
4208 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4209 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
4210 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4211 md.SetMemberIsUsed ();
4213 if (RootContext.EntryPoint == null) {
4214 if (Parent.IsGeneric){
4215 Report.Error (-201, Location,
4216 "Entry point can not be defined in a generic class");
4219 RootContext.EntryPoint = MethodBuilder;
4220 RootContext.EntryPointLocation = Location;
4222 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4223 DuplicateEntryPoint (MethodBuilder, Location);
4226 if (RootContext.WarningLevel >= 4)
4227 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
4231 if (MemberType.IsAbstract && MemberType.IsSealed) {
4232 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4242 public override void Emit ()
4244 MethodData.Emit (Parent, this);
4247 if (declarative_security != null) {
4248 foreach (DictionaryEntry de in declarative_security) {
4249 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4257 public static void Error1599 (Location loc, Type t)
4259 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4262 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4264 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
4265 container.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
4270 base_ret_type = mi.ReturnType;
4274 public override bool MarkForDuplicationCheck ()
4276 caching_flags |= Flags.TestMethodDuplication;
4280 protected override bool VerifyClsCompliance(DeclSpace ds)
4282 if (!base.VerifyClsCompliance (ds))
4285 if (ParameterInfo.Count > 0) {
4286 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
4288 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4294 #region IMethodData Members
4296 public CallingConventions CallingConventions {
4298 CallingConventions cc = Parameters.CallingConvention;
4299 if (Parameters.HasArglist)
4300 block.HasVarargs = true;
4303 if ((ModFlags & Modifiers.STATIC) == 0)
4304 cc |= CallingConventions.HasThis;
4306 // FIXME: How is `ExplicitThis' used in C#?
4312 public Type ReturnType {
4318 public MemberName MethodName {
4324 public new Location Location {
4326 return base.Location;
4330 protected override bool CheckBase() {
4331 if (!base.CheckBase ())
4334 // TODO: Destructor should derive from MethodCore
4335 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4336 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4337 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4344 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4346 EmitContext ec = new EmitContext (
4347 tc, ds, Location, ig, ReturnType, ModFlags, false);
4349 Iterator iterator = tc as Iterator;
4350 if (iterator != null)
4351 ec.CurrentAnonymousMethod = iterator.Host;
4357 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4359 public bool IsExcluded (EmitContext ec)
4361 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4362 return (caching_flags & Flags.Excluded) != 0;
4364 caching_flags &= ~Flags.Excluded_Undetected;
4366 if (base_method == null) {
4367 if (OptAttributes == null)
4370 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4375 foreach (Attribute a in attrs) {
4376 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4377 if (RootContext.AllDefines.Contains (condition))
4381 caching_flags |= Flags.Excluded;
4385 IMethodData md = TypeManager.GetMethod (base_method);
4387 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4388 caching_flags |= Flags.Excluded;
4394 if (md.IsExcluded (ec)) {
4395 caching_flags |= Flags.Excluded;
4401 GenericMethod IMethodData.GenericMethod {
4403 return GenericMethod;
4410 public abstract class ConstructorInitializer {
4411 ArrayList argument_list;
4412 protected ConstructorInfo base_constructor;
4415 public ConstructorInitializer (ArrayList argument_list, Location loc)
4417 this.argument_list = argument_list;
4421 public ArrayList Arguments {
4423 return argument_list;
4427 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4429 Expression base_constructor_group;
4433 ec.CurrentBlock = block;
4435 if (argument_list != null){
4436 foreach (Argument a in argument_list){
4437 if (!a.Resolve (ec, loc))
4441 ec.CurrentBlock = null;
4443 if (this is ConstructorBaseInitializer) {
4444 if (ec.ContainerType.BaseType == null)
4447 t = ec.ContainerType.BaseType;
4448 if (ec.ContainerType.IsValueType) {
4449 Report.Error (522, loc,
4450 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4454 t = ec.ContainerType;
4456 base_constructor_group = Expression.MemberLookup (
4457 ec, t, ".ctor", MemberTypes.Constructor,
4458 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4461 if (base_constructor_group == null){
4463 base_constructor_group = Expression.MemberLookup (
4464 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4465 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4469 int errors = Report.Errors;
4470 if (base_constructor_group != null)
4471 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4472 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4475 if (base_constructor == null) {
4476 if (errors == Report.Errors)
4477 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4478 argument_list.Count);
4483 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4484 base_constructor = null;
4488 if (base_constructor == caller_builder){
4489 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4496 public virtual void Emit (EmitContext ec)
4498 if (base_constructor != null){
4499 ec.Mark (loc, false);
4501 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4503 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4508 public class ConstructorBaseInitializer : ConstructorInitializer {
4509 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4510 base (argument_list, l)
4515 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4516 public GeneratedBaseInitializer (Location loc):
4521 public override void Emit(EmitContext ec)
4523 bool old = ec.TestObsoleteMethodUsage;
4524 ec.TestObsoleteMethodUsage = false;
4526 ec.TestObsoleteMethodUsage = old;
4530 public class ConstructorThisInitializer : ConstructorInitializer {
4531 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4532 base (argument_list, l)
4537 public class Constructor : MethodCore, IMethodData {
4538 public ConstructorBuilder ConstructorBuilder;
4539 public ConstructorInitializer Initializer;
4540 ListDictionary declarative_security;
4543 // Modifiers allowed for a constructor.
4545 public const int AllowedModifiers =
4547 Modifiers.PROTECTED |
4548 Modifiers.INTERNAL |
4554 bool has_compliant_args = false;
4556 // The spec claims that static is not permitted, but
4557 // my very own code has static constructors.
4559 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4560 ConstructorInitializer init, Location loc)
4561 : base (ds, null, null, mod, AllowedModifiers, false,
4562 new MemberName (name, loc), null, args)
4567 public bool HasCompliantArgs {
4569 return has_compliant_args;
4573 public override AttributeTargets AttributeTargets {
4575 return AttributeTargets.Constructor;
4581 // Returns true if this is a default constructor
4583 public bool IsDefault ()
4585 if ((ModFlags & Modifiers.STATIC) != 0)
4586 return Parameters.Empty;
4588 return Parameters.Empty &&
4589 (Initializer is ConstructorBaseInitializer) &&
4590 (Initializer.Arguments == null);
4593 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4595 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4596 if (declarative_security == null) {
4597 declarative_security = new ListDictionary ();
4599 a.ExtractSecurityPermissionSet (declarative_security);
4603 ConstructorBuilder.SetCustomAttribute (cb);
4606 protected override bool CheckForDuplications ()
4608 ArrayList ar = Parent.InstanceConstructors;
4610 int arLen = ar.Count;
4612 for (int i = 0; i < arLen; i++) {
4613 Constructor m = (Constructor) ar [i];
4614 if (IsDuplicateImplementation (m))
4621 protected override bool CheckBase ()
4623 // Check whether arguments were correct.
4624 if (!DoDefineParameters ())
4627 // TODO: skip the rest for generated ctor
4628 if ((ModFlags & Modifiers.STATIC) != 0)
4631 if (!CheckForDuplications ())
4634 if (Parent.Kind == Kind.Struct) {
4635 if (ParameterTypes.Length == 0) {
4636 Report.Error (568, Location,
4637 "Structs cannot contain explicit parameterless constructors");
4641 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4642 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4647 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4648 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4655 // Creates the ConstructorBuilder
4657 public override bool Define ()
4659 if (ConstructorBuilder != null)
4662 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4663 MethodAttributes.SpecialName);
4665 if ((ModFlags & Modifiers.STATIC) != 0){
4666 ca |= MethodAttributes.Static | MethodAttributes.Private;
4668 ca |= MethodAttributes.HideBySig;
4670 if ((ModFlags & Modifiers.PUBLIC) != 0)
4671 ca |= MethodAttributes.Public;
4672 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4673 if ((ModFlags & Modifiers.INTERNAL) != 0)
4674 ca |= MethodAttributes.FamORAssem;
4676 ca |= MethodAttributes.Family;
4677 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4678 ca |= MethodAttributes.Assembly;
4679 else if (IsDefault ())
4680 ca |= MethodAttributes.Public;
4682 ca |= MethodAttributes.Private;
4685 if (!CheckAbstractAndExtern (block != null))
4688 // Check if arguments were correct.
4692 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4693 ca, CallingConventions,
4696 if ((ModFlags & Modifiers.UNSAFE) != 0)
4697 ConstructorBuilder.InitLocals = false;
4699 if (Parent.IsComImport) {
4700 if (!IsDefault ()) {
4701 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4702 Parent.GetSignatureForError ());
4705 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4708 TypeManager.AddMethod (ConstructorBuilder, this);
4716 public override void Emit ()
4718 EmitContext ec = CreateEmitContext (null, null);
4719 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute () != null)
4720 ec.TestObsoleteMethodUsage = false;
4722 // If this is a non-static `struct' constructor and doesn't have any
4723 // initializer, it must initialize all of the struct's fields.
4724 if ((Parent.Kind == Kind.Struct) &&
4725 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4726 Block.AddThisVariable (Parent, Location);
4728 if (block != null) {
4729 if (!block.ResolveMeta (ec, ParameterInfo))
4733 if ((ModFlags & Modifiers.STATIC) == 0){
4734 if (Parent.Kind == Kind.Class && Initializer == null)
4735 Initializer = new GeneratedBaseInitializer (Location);
4739 // Spec mandates that Initializers will not have
4743 if ((Initializer != null) &&
4744 !Initializer.Resolve (ConstructorBuilder, block, ec))
4746 ec.IsStatic = false;
4749 Parameters.ApplyAttributes (ec, ConstructorBuilder);
4751 SourceMethod source = SourceMethod.Create (
4752 Parent, ConstructorBuilder, block);
4755 // Classes can have base initializers and instance field initializers.
4757 if (Parent.Kind == Kind.Class){
4758 if ((ModFlags & Modifiers.STATIC) == 0){
4761 // If we use a "this (...)" constructor initializer, then
4762 // do not emit field initializers, they are initialized in the other constructor
4764 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4765 Parent.EmitFieldInitializers (ec);
4768 if (Initializer != null) {
4769 Initializer.Emit (ec);
4772 if ((ModFlags & Modifiers.STATIC) != 0)
4773 Parent.EmitFieldInitializers (ec);
4775 if (OptAttributes != null)
4776 OptAttributes.Emit (ec, this);
4778 ec.EmitTopBlock (this, block);
4781 source.CloseMethod ();
4785 if (declarative_security != null) {
4786 foreach (DictionaryEntry de in declarative_security) {
4787 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4794 // Is never override
4795 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4800 public override string GetSignatureForError()
4802 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4805 protected override bool VerifyClsCompliance (DeclSpace ds)
4807 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4811 if (ParameterInfo.Count > 0) {
4812 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4814 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4816 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4817 foreach (Type param in ParameterTypes) {
4818 if (param.IsArray) {
4824 has_compliant_args = true;
4828 #region IMethodData Members
4830 public System.Reflection.CallingConventions CallingConventions {
4832 CallingConventions cc = Parameters.CallingConvention;
4834 if (Parent.Kind == Kind.Class)
4835 if ((ModFlags & Modifiers.STATIC) == 0)
4836 cc |= CallingConventions.HasThis;
4838 // FIXME: How is `ExplicitThis' used in C#?
4844 public new Location Location {
4846 return base.Location;
4850 public MemberName MethodName {
4856 public Type ReturnType {
4862 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4864 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4865 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4868 public bool IsExcluded(EmitContext ec)
4873 GenericMethod IMethodData.GenericMethod {
4883 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4885 public interface IMethodData
4887 CallingConventions CallingConventions { get; }
4888 Location Location { get; }
4889 MemberName MethodName { get; }
4890 Type ReturnType { get; }
4891 GenericMethod GenericMethod { get; }
4892 Parameters ParameterInfo { get; }
4894 Attributes OptAttributes { get; }
4895 ToplevelBlock Block { get; set; }
4897 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4898 ObsoleteAttribute GetObsoleteAttribute ();
4899 string GetSignatureForError ();
4900 bool IsExcluded (EmitContext ec);
4901 bool IsClsComplianceRequired (DeclSpace ds);
4902 void SetMemberIsUsed ();
4906 // Encapsulates most of the Method's state
4908 public class MethodData {
4910 readonly IMethodData method;
4912 public readonly GenericMethod GenericMethod;
4915 // Are we implementing an interface ?
4917 public MethodInfo implementing;
4922 protected MemberBase member;
4923 protected int modifiers;
4924 protected MethodAttributes flags;
4925 protected Type declaring_type;
4926 protected MethodInfo parent_method;
4928 MethodBuilder builder = null;
4929 public MethodBuilder MethodBuilder {
4935 public Type DeclaringType {
4937 return declaring_type;
4941 public MethodData (MemberBase member,
4942 int modifiers, MethodAttributes flags, IMethodData method)
4944 this.member = member;
4945 this.modifiers = modifiers;
4948 this.method = method;
4951 public MethodData (MemberBase member,
4952 int modifiers, MethodAttributes flags,
4953 IMethodData method, MethodBuilder builder,
4954 GenericMethod generic, MethodInfo parent_method)
4955 : this (member, modifiers, flags, method)
4957 this.builder = builder;
4958 this.GenericMethod = generic;
4959 this.parent_method = parent_method;
4962 public bool Define (TypeContainer container)
4964 string name = method.MethodName.Basename;
4965 string method_name = method.MethodName.FullName;
4967 if (container.Pending != null){
4968 if (member is Indexer) // TODO: test it, but it should work without this IF
4969 implementing = container.Pending.IsInterfaceIndexer (
4970 member.InterfaceType, method.ReturnType, method.ParameterInfo);
4972 implementing = container.Pending.IsInterfaceMethod (
4973 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
4975 if (member.InterfaceType != null){
4976 if (implementing == null){
4977 if (member is PropertyBase) {
4978 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4979 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4980 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4983 Report.Error (539, method.Location,
4984 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4985 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4989 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4990 Report.SymbolRelatedToPreviousError (implementing);
4991 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4992 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4996 method_name = TypeManager.GetFullName (member.InterfaceType) +
4999 if (implementing != null) {
5000 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5001 if (prop_method != null) {
5002 if (!implementing.IsSpecialName) {
5003 Report.SymbolRelatedToPreviousError (implementing);
5004 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5005 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5008 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5009 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5010 Report.SymbolRelatedToPreviousError (implementing);
5011 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5012 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5021 // For implicit implementations, make sure we are public, for
5022 // explicit implementations, make sure we are private.
5024 if (implementing != null){
5026 // Setting null inside this block will trigger a more
5027 // verbose error reporting for missing interface implementations
5029 // The "candidate" function has been flagged already
5030 // but it wont get cleared
5032 if (member.IsExplicitImpl){
5033 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
5034 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
5035 implementing = null;
5037 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
5038 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
5040 // If this is an interface method implementation,
5041 // check for public accessibility
5043 implementing = null;
5044 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5045 // We may never be private.
5046 implementing = null;
5047 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5049 // We may be protected if we're overriding something.
5051 implementing = null;
5056 // Static is not allowed
5058 if ((modifiers & Modifiers.STATIC) != 0){
5059 implementing = null;
5064 // If implementing is still valid, set flags
5066 if (implementing != null){
5068 // When implementing interface methods, set NewSlot
5069 // unless, we are overwriting a method.
5071 if (implementing.DeclaringType.IsInterface){
5072 if ((modifiers & Modifiers.OVERRIDE) == 0)
5073 flags |= MethodAttributes.NewSlot;
5076 MethodAttributes.Virtual |
5077 MethodAttributes.HideBySig;
5079 // Set Final unless we're virtual, abstract or already overriding a method.
5080 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5081 flags |= MethodAttributes.Final;
5084 EmitContext ec = method.CreateEmitContext (container, null);
5085 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute () != null)
5086 ec.TestObsoleteMethodUsage = false;
5088 DefineMethodBuilder (ec, container, method_name, method.ParameterInfo.Types);
5090 if (builder == null)
5093 if (container.CurrentType != null)
5094 declaring_type = container.CurrentType;
5096 declaring_type = container.TypeBuilder;
5098 if ((modifiers & Modifiers.UNSAFE) != 0)
5099 builder.InitLocals = false;
5101 if (implementing != null){
5103 // clear the pending implemntation flag
5105 if (member is Indexer) {
5106 container.Pending.ImplementIndexer (
5107 member.InterfaceType, builder, method.ReturnType,
5108 method.ParameterInfo, member.IsExplicitImpl);
5110 container.Pending.ImplementMethod (
5111 member.InterfaceType, name, method.ReturnType,
5112 method.ParameterInfo, member.IsExplicitImpl);
5114 if (member.IsExplicitImpl)
5115 container.TypeBuilder.DefineMethodOverride (
5116 builder, implementing);
5119 TypeManager.AddMethod (builder, method);
5121 if (GenericMethod != null) {
5122 bool is_override = member.IsExplicitImpl |
5123 ((modifiers & Modifiers.OVERRIDE) != 0);
5125 if (implementing != null)
5126 parent_method = implementing;
5128 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5136 /// Create the MethodBuilder for the method
5138 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
5140 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
5142 if ((modifiers & extern_static) == extern_static) {
5144 if (method.OptAttributes != null) {
5145 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
5146 if (dllimport_attribute != null) {
5147 flags |= MethodAttributes.PinvokeImpl;
5148 builder = dllimport_attribute.DefinePInvokeMethod (
5149 ec, container.TypeBuilder, method_name, flags,
5150 method.ReturnType, ParameterTypes);
5156 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5157 // We are more strict than Microsoft and report CS0626 like error
5158 if (method.OptAttributes == null ||
5159 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
5160 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",
5161 method.GetSignatureForError ());
5166 if (builder == null)
5167 builder = container.TypeBuilder.DefineMethod (
5168 method_name, flags, method.CallingConventions,
5169 method.ReturnType, ParameterTypes);
5171 builder.SetGenericMethodSignature (
5172 flags, method.CallingConventions,
5173 method.ReturnType, ParameterTypes);
5179 public void Emit (TypeContainer container, Attributable kind)
5182 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5183 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
5185 ec = method.CreateEmitContext (container, null);
5187 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute () != null)
5188 ec.TestObsoleteMethodUsage = false;
5190 method.ParameterInfo.ApplyAttributes (ec, MethodBuilder);
5192 Attributes OptAttributes = method.OptAttributes;
5194 if (OptAttributes != null)
5195 OptAttributes.Emit (ec, kind);
5197 if (GenericMethod != null)
5198 GenericMethod.EmitAttributes (ec);
5200 ToplevelBlock block = method.Block;
5202 SourceMethod source = SourceMethod.Create (
5203 container, MethodBuilder, method.Block);
5206 // Handle destructors specially
5208 // FIXME: This code generates buggy code
5210 if (member is Destructor)
5211 EmitDestructor (ec, block);
5213 ec.EmitTopBlock (method, block);
5216 source.CloseMethod ();
5219 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5221 ILGenerator ig = ec.ig;
5223 Label finish = ig.DefineLabel ();
5225 block.SetDestructor ();
5227 ig.BeginExceptionBlock ();
5228 ec.ReturnLabel = finish;
5229 ec.HasReturnLabel = true;
5230 ec.EmitTopBlock (method, block);
5232 // ig.MarkLabel (finish);
5233 ig.BeginFinallyBlock ();
5235 if (ec.ContainerType.BaseType != null) {
5236 Expression member_lookup = Expression.MemberLookup (
5237 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5238 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5240 if (member_lookup != null){
5241 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5243 ig.Emit (OpCodes.Ldarg_0);
5244 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5248 ig.EndExceptionBlock ();
5249 //ig.MarkLabel (ec.ReturnLabel);
5250 ig.Emit (OpCodes.Ret);
5254 // TODO: Should derive from MethodCore
5255 public class Destructor : Method {
5257 public Destructor (TypeContainer ds, Expression return_type, int mod,
5258 string name, Parameters parameters, Attributes attrs,
5260 : base (ds, null, return_type, mod, false, new MemberName (name, l),
5264 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5266 if (a.Type == TypeManager.conditional_attribute_type) {
5267 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
5268 GetSignatureForError ());
5272 base.ApplyAttributeBuilder (a, cb);
5275 public override string GetSignatureForError ()
5277 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5282 abstract public class MemberBase : MemberCore {
5283 public Expression Type;
5285 public MethodAttributes flags;
5286 public readonly DeclSpace ds;
5287 public readonly GenericMethod GenericMethod;
5289 protected readonly int explicit_mod_flags;
5292 // The "short" name of this property / indexer / event. This is the
5293 // name without the explicit interface.
5295 public string ShortName {
5296 get { return MemberName.Name; }
5297 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
5300 public new TypeContainer Parent {
5301 get { return (TypeContainer) base.Parent; }
5305 // The type of this property / indexer / event
5307 protected Type member_type;
5308 public Type MemberType {
5310 if (member_type == null && Type != null) {
5311 EmitContext ec = ds.EmitContext;
5312 bool old_unsafe = ec.InUnsafe;
5313 ec.InUnsafe = InUnsafe;
5314 ec.ResolvingGenericMethod = GenericMethod != null;
5315 Type = Type.ResolveAsTypeTerminal (ec);
5316 ec.ResolvingGenericMethod = false;
5317 ec.InUnsafe = old_unsafe;
5319 member_type = Type.Type;
5327 // Whether this is an interface member.
5329 public bool IsInterface;
5332 // If true, this is an explicit interface implementation
5334 public bool IsExplicitImpl;
5337 // The interface type we are explicitly implementing
5339 public Type InterfaceType = null;
5342 // The constructor is only exposed to our children
5344 protected MemberBase (TypeContainer parent, GenericMethod generic,
5345 Expression type, int mod, int allowed_mod, int def_mod,
5346 MemberName name, Attributes attrs)
5347 : base (parent, name, attrs)
5349 this.ds = generic != null ? generic : (DeclSpace) parent;
5350 explicit_mod_flags = mod;
5352 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5353 IsExplicitImpl = (MemberName.Left != null);
5354 GenericMethod = generic;
5357 protected virtual bool CheckBase ()
5359 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5360 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5364 if ((RootContext.WarningLevel >= 4) &&
5365 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5366 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5367 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5368 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5373 protected virtual bool DoDefineBase ()
5375 EmitContext ec = Parent.EmitContext;
5377 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5380 throw new InternalErrorException ();
5383 ModFlags = Modifiers.PUBLIC |
5384 Modifiers.ABSTRACT |
5385 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5387 flags = MethodAttributes.Public |
5388 MethodAttributes.Abstract |
5389 MethodAttributes.HideBySig |
5390 MethodAttributes.NewSlot |
5391 MethodAttributes.Virtual;
5393 if (!Parent.MethodModifiersValid (this))
5396 flags = Modifiers.MethodAttr (ModFlags);
5399 if (IsExplicitImpl) {
5400 Expression expr = MemberName.Left.GetTypeExpression ();
5401 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5402 if (iface_texpr == null)
5405 InterfaceType = iface_texpr.ResolveType (ec);
5407 if (!InterfaceType.IsInterface) {
5408 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5412 if (!Parent.VerifyImplements (this))
5415 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5421 protected virtual bool DoDefine ()
5423 EmitContext ec = ds.EmitContext;
5425 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5427 ec.InUnsafe = InUnsafe;
5429 if (MemberType == null)
5432 CheckObsoleteType (Type);
5434 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5435 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5436 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5437 GetSignatureForError (), Parent.GetSignatureForError ());
5441 // verify accessibility
5442 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5443 Report.SymbolRelatedToPreviousError (MemberType);
5444 if (this is Property)
5445 Report.Error (53, Location,
5446 "Inconsistent accessibility: property type `" +
5447 TypeManager.CSharpName (MemberType) + "' is less " +
5448 "accessible than property `" + GetSignatureForError () + "'");
5449 else if (this is Indexer)
5450 Report.Error (54, Location,
5451 "Inconsistent accessibility: indexer return type `" +
5452 TypeManager.CSharpName (MemberType) + "' is less " +
5453 "accessible than indexer `" + GetSignatureForError () + "'");
5454 else if (this is MethodCore) {
5455 if (this is Operator)
5456 Report.Error (56, Location,
5457 "Inconsistent accessibility: return type `" +
5458 TypeManager.CSharpName (MemberType) + "' is less " +
5459 "accessible than operator `" + GetSignatureForError () + "'");
5461 Report.Error (50, Location,
5462 "Inconsistent accessibility: return type `" +
5463 TypeManager.CSharpName (MemberType) + "' is less " +
5464 "accessible than method `" + GetSignatureForError () + "'");
5466 Report.Error (52, Location,
5467 "Inconsistent accessibility: field type `" +
5468 TypeManager.CSharpName (MemberType) + "' is less " +
5469 "accessible than field `" + GetSignatureForError () + "'");
5474 if (MemberType.IsPointer && !UnsafeOK (Parent))
5477 if (IsExplicitImpl) {
5478 Expression expr = MemberName.Left.GetTypeExpression ();
5479 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
5483 InterfaceType = texpr.ResolveType (ec);
5485 if (!InterfaceType.IsInterface) {
5486 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5490 if (!Parent.VerifyImplements (this))
5493 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5499 protected bool IsTypePermitted ()
5501 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5502 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5508 protected override bool VerifyClsCompliance(DeclSpace ds)
5510 if (base.VerifyClsCompliance (ds)) {
5514 if (IsInterface && HasClsCompliantAttribute && ds.IsClsComplianceRequired (ds)) {
5515 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5523 // Fields and Events both generate FieldBuilders, we use this to share
5524 // their common bits. This is also used to flag usage of the field
5526 abstract public class FieldBase : MemberBase {
5527 public FieldBuilder FieldBuilder;
5528 public Status status;
5529 protected Expression initializer;
5532 public enum Status : byte {
5533 HAS_OFFSET = 4 // Used by FieldMember.
5536 static string[] attribute_targets = new string [] { "field" };
5539 /// Symbol with same name in base class/struct
5541 public MemberInfo conflict_symbol;
5543 protected FieldBase (TypeContainer parent, Expression type, int mod,
5544 int allowed_mod, MemberName name, Attributes attrs)
5545 : base (parent, null, type, mod, allowed_mod, Modifiers.PRIVATE,
5550 public override AttributeTargets AttributeTargets {
5552 return AttributeTargets.Field;
5556 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5558 if (a.Type == TypeManager.marshal_as_attr_type) {
5559 UnmanagedMarshal marshal = a.GetMarshal (this);
5560 if (marshal != null) {
5561 FieldBuilder.SetMarshal (marshal);
5566 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5567 a.Error_InvalidSecurityParent ();
5571 FieldBuilder.SetCustomAttribute (cb);
5574 public void EmitInitializer (EmitContext ec)
5576 // Replace DeclSpace because of partial classes
5577 ec.DeclSpace = EmitContext.DeclSpace;
5579 ec.IsFieldInitializer = true;
5580 initializer = initializer.Resolve (ec);
5581 ec.IsFieldInitializer = false;
5582 if (initializer == null)
5584 FieldExpr fe = new FieldExpr (FieldBuilder, Location, true);
5585 if ((ModFlags & Modifiers.STATIC) == 0)
5586 fe.InstanceExpression = new This (Location).Resolve (ec);
5588 ExpressionStatement a = new Assign (fe, initializer, Location);
5590 a = a.ResolveStatement (ec);
5594 Constant c = initializer as Constant;
5595 if (c != null && CanElideInitializer (c))
5598 a.EmitStatement (ec);
5601 bool CanElideInitializer (Constant c)
5603 if (MemberType == c.Type)
5604 return c.IsDefaultValue;
5606 if (c.Type == TypeManager.null_type)
5612 protected override bool CheckBase ()
5614 if (!base.CheckBase ())
5621 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5622 if (conflict_symbol == null) {
5623 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5624 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5629 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5630 Report.SymbolRelatedToPreviousError (conflict_symbol);
5631 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5632 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5638 public Expression Initializer {
5640 if (value != null) {
5641 this.initializer = value;
5642 Parent.RegisterFieldForInitialization (this);
5647 protected virtual bool IsFieldClsCompliant {
5649 if (FieldBuilder == null)
5652 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5656 public override string[] ValidAttributeTargets {
5658 return attribute_targets;
5662 protected override bool VerifyClsCompliance (DeclSpace ds)
5664 if (!base.VerifyClsCompliance (ds))
5667 if (!IsFieldClsCompliant) {
5668 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5674 public void SetAssigned ()
5676 caching_flags |= Flags.IsAssigned;
5680 public abstract class FieldMember : FieldBase
5682 protected FieldMember (TypeContainer parent, Expression type, int mod,
5683 int allowed_mod, MemberName name, Attributes attrs)
5684 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, attrs)
5686 if ((mod & Modifiers.ABSTRACT) != 0)
5687 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5690 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5692 if (a.Type == TypeManager.field_offset_attribute_type)
5694 status |= Status.HAS_OFFSET;
5696 if (!Parent.HasExplicitLayout) {
5697 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5701 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5702 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5707 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5708 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5712 base.ApplyAttributeBuilder (a, cb);
5716 public override bool Define()
5718 EmitContext ec = Parent.EmitContext;
5720 throw new InternalErrorException ("FieldMember.Define called too early");
5722 if (MemberType == null || Type == null)
5725 CheckObsoleteType (Type);
5727 if (MemberType == TypeManager.void_type) {
5728 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5735 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5736 Report.Error (52, Location,
5737 "Inconsistent accessibility: field type `" +
5738 TypeManager.CSharpName (MemberType) + "' is less " +
5739 "accessible than field `" + GetSignatureForError () + "'");
5743 if (!IsTypePermitted ())
5746 if (MemberType.IsPointer && !UnsafeOK (Parent))
5752 public override void Emit ()
5754 if (OptAttributes != null) {
5755 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5756 OptAttributes.Emit (ec, this);
5759 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5760 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5767 // Represents header string for documentation comment.
5769 public override string DocCommentHeader {
5770 get { return "F:"; }
5774 interface IFixedBuffer
5776 FieldInfo Element { get; }
5777 Type ElementType { get; }
5780 public class FixedFieldExternal: IFixedBuffer
5782 FieldInfo element_field;
5784 public FixedFieldExternal (FieldInfo fi)
5786 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5789 #region IFixedField Members
5791 public FieldInfo Element {
5793 return element_field;
5797 public Type ElementType {
5799 return element_field.FieldType;
5807 /// Fixed buffer implementation
5809 public class FixedField : FieldMember, IFixedBuffer
5811 public const string FixedElementName = "FixedElementField";
5812 static int GlobalCounter = 0;
5813 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5814 static FieldInfo[] fi;
5816 TypeBuilder fixed_buffer_type;
5817 FieldBuilder element;
5818 Expression size_expr;
5821 const int AllowedModifiers =
5824 Modifiers.PROTECTED |
5825 Modifiers.INTERNAL |
5828 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5829 Expression size_expr, Attributes attrs, Location loc):
5830 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5832 if (RootContext.Version == LanguageVersion.ISO_1)
5833 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5835 this.size_expr = size_expr;
5838 public override bool Define()
5841 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5842 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5845 if (Parent.Kind != Kind.Struct) {
5846 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5847 GetSignatureForError ());
5851 if (!base.Define ())
5854 if (!TypeManager.IsPrimitiveType (MemberType)) {
5855 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",
5856 GetSignatureForError ());
5860 Constant c = size_expr.ResolveAsConstant (Parent.EmitContext, this);
5864 IntConstant buffer_size_const = c.ToInt (Location);
5865 if (buffer_size_const == null)
5868 buffer_size = buffer_size_const.Value;
5870 if (buffer_size <= 0) {
5871 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5875 int type_size = Expression.GetTypeSize (MemberType);
5877 if (buffer_size > int.MaxValue / type_size) {
5878 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5879 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5883 buffer_size *= type_size;
5886 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5888 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5889 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5890 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5891 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5893 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5894 TypeManager.RegisterFieldBase (FieldBuilder, this);
5899 public override void Emit()
5902 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5904 object[] fi_val = new object[1];
5905 fi_val [0] = buffer_size;
5907 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5908 ctor_args, fi, fi_val);
5909 fixed_buffer_type.SetCustomAttribute (cab);
5911 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5912 FieldBuilder.SetCustomAttribute (cab);
5916 protected override bool IsFieldClsCompliant {
5922 #region IFixedField Members
5924 public FieldInfo Element {
5930 public Type ElementType {
5940 // The Field class is used to represents class/struct fields during parsing.
5942 public class Field : FieldMember {
5944 // Modifiers allowed in a class declaration
5946 const int AllowedModifiers =
5949 Modifiers.PROTECTED |
5950 Modifiers.INTERNAL |
5953 Modifiers.VOLATILE |
5957 public Field (TypeContainer parent, Expression type, int mod, string name,
5958 Attributes attrs, Location loc)
5959 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5964 public override bool Define ()
5966 if (!base.Define ())
5969 if (RootContext.WarningLevel > 1){
5970 Type ptype = Parent.TypeBuilder.BaseType;
5972 // ptype is only null for System.Object while compiling corlib.
5974 TypeContainer.FindMembers (
5975 ptype, MemberTypes.Method,
5976 BindingFlags.Public |
5977 BindingFlags.Static | BindingFlags.Instance,
5978 System.Type.FilterName, Name);
5982 if ((ModFlags & Modifiers.VOLATILE) != 0){
5983 if (!MemberType.IsClass){
5984 Type vt = MemberType;
5986 if (TypeManager.IsEnumType (vt))
5987 vt = TypeManager.EnumToUnderlying (MemberType);
5989 if (!((vt == TypeManager.bool_type) ||
5990 (vt == TypeManager.sbyte_type) ||
5991 (vt == TypeManager.byte_type) ||
5992 (vt == TypeManager.short_type) ||
5993 (vt == TypeManager.ushort_type) ||
5994 (vt == TypeManager.int32_type) ||
5995 (vt == TypeManager.uint32_type) ||
5996 (vt == TypeManager.char_type) ||
5997 (vt == TypeManager.float_type) ||
5998 (!vt.IsValueType))){
5999 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
6000 GetSignatureForError (), TypeManager.CSharpName (vt));
6005 if ((ModFlags & Modifiers.READONLY) != 0){
6006 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
6007 GetSignatureForError ());
6012 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6014 if (Parent.Kind == Kind.Struct &&
6015 ((fa & FieldAttributes.Static) == 0) &&
6016 MemberType == Parent.TypeBuilder &&
6017 !TypeManager.IsBuiltinType (MemberType)){
6018 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6019 "' causes a cycle in the structure layout");
6024 FieldBuilder = Parent.TypeBuilder.DefineField (
6025 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6027 TypeManager.RegisterFieldBase (FieldBuilder, this);
6029 catch (ArgumentException) {
6030 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6037 protected override bool VerifyClsCompliance (DeclSpace ds)
6039 if (!base.VerifyClsCompliance (ds))
6042 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6043 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6051 // `set' and `get' accessors are represented with an Accessor.
6053 public class Accessor : IIteratorContainer {
6055 // Null if the accessor is empty, or a Block if not
6057 public const int AllowedModifiers =
6059 Modifiers.PROTECTED |
6060 Modifiers.INTERNAL |
6063 public ToplevelBlock Block;
6064 public Attributes Attributes;
6065 public Location Location;
6066 public int ModFlags;
6069 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6074 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6077 public void SetYields ()
6083 // Ooouh Martin, templates are missing here.
6084 // When it will be possible move here a lot of child code and template method type.
6085 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
6086 protected MethodData method_data;
6087 protected ToplevelBlock block;
6088 protected ListDictionary declarative_security;
6090 // The accessor are created event if they are not wanted.
6091 // But we need them because their names are reserved.
6092 // Field says whether accessor will be emited or not
6093 public readonly bool IsDummy;
6095 protected readonly string prefix;
6097 ReturnParameter return_attributes;
6099 public AbstractPropertyEventMethod (MemberBase member, string prefix)
6100 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6102 this.prefix = prefix;
6106 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
6108 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6109 accessor.Attributes)
6111 this.prefix = prefix;
6112 this.block = accessor.Block;
6115 static MemberName SetupName (string prefix, MemberBase member, Location loc)
6117 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6120 public void UpdateName (MemberBase member)
6122 SetMemberName (SetupName (prefix, member, Location));
6125 #region IMethodData Members
6127 public ToplevelBlock Block {
6137 public CallingConventions CallingConventions {
6139 return CallingConventions.Standard;
6143 public bool IsExcluded (EmitContext ec)
6148 GenericMethod IMethodData.GenericMethod {
6154 public MemberName MethodName {
6160 public Type[] ParameterTypes {
6162 return ParameterInfo.Types;
6166 public abstract Parameters ParameterInfo { get ; }
6167 public abstract Type ReturnType { get; }
6168 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
6172 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6174 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6175 a.Type == TypeManager.conditional_attribute_type) {
6176 Report.Error (1667, a.Location,
6177 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6178 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6182 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6183 if (declarative_security == null)
6184 declarative_security = new ListDictionary ();
6185 a.ExtractSecurityPermissionSet (declarative_security);
6189 if (a.Target == AttributeTargets.Method) {
6190 method_data.MethodBuilder.SetCustomAttribute (cb);
6194 if (a.Target == AttributeTargets.ReturnValue) {
6195 if (return_attributes == null)
6196 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6198 return_attributes.ApplyAttributeBuilder (a, cb);
6202 ApplyToExtraTarget (a, cb);
6205 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6207 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6210 public override bool Define()
6212 throw new NotSupportedException ();
6215 public virtual void Emit (TypeContainer container)
6217 EmitMethod (container);
6219 if (declarative_security != null) {
6220 foreach (DictionaryEntry de in declarative_security) {
6221 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6228 protected virtual void EmitMethod (TypeContainer container)
6230 method_data.Emit (container, this);
6233 public override bool IsClsComplianceRequired(DeclSpace ds)
6238 public bool IsDuplicateImplementation (MethodCore method)
6240 if (!MemberName.Equals (method.MemberName))
6243 Type[] param_types = method.ParameterTypes;
6245 if (param_types.Length != ParameterTypes.Length)
6248 for (int i = 0; i < param_types.Length; i++)
6249 if (param_types [i] != ParameterTypes [i])
6252 Report.SymbolRelatedToPreviousError (method);
6253 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
6257 public override bool IsUsed
6267 public new Location Location {
6269 return base.Location;
6274 // Represents header string for documentation comment.
6276 public override string DocCommentHeader {
6277 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6283 // Properties and Indexers both generate PropertyBuilders, we use this to share
6284 // their common bits.
6286 abstract public class PropertyBase : MethodCore {
6288 public class GetMethod : PropertyMethod
6290 static string[] attribute_targets = new string [] { "method", "return" };
6292 public GetMethod (MethodCore method):
6293 base (method, "get_")
6297 public GetMethod (MethodCore method, Accessor accessor):
6298 base (method, accessor, "get_")
6302 public override MethodBuilder Define(TypeContainer container)
6304 base.Define (container);
6306 method_data = new MethodData (method, ModFlags, flags, this);
6308 if (!method_data.Define (container))
6311 return method_data.MethodBuilder;
6314 public override Type ReturnType {
6316 return method.MemberType;
6320 public override Parameters ParameterInfo {
6322 return Parameters.EmptyReadOnlyParameters;
6326 public override string[] ValidAttributeTargets {
6328 return attribute_targets;
6333 public class SetMethod : PropertyMethod {
6335 static string[] attribute_targets = new string [] { "method", "param", "return" };
6336 ImplicitParameter param_attr;
6337 protected Parameters parameters;
6339 public SetMethod (MethodCore method):
6340 base (method, "set_")
6344 public SetMethod (MethodCore method, Accessor accessor):
6345 base (method, accessor, "set_")
6349 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6351 if (a.Target == AttributeTargets.Parameter) {
6352 if (param_attr == null)
6353 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6355 param_attr.ApplyAttributeBuilder (a, cb);
6359 base.ApplyAttributeBuilder (a, cb);
6362 public override Parameters ParameterInfo {
6368 protected virtual void DefineParameters ()
6370 Parameter [] parms = new Parameter [1];
6371 parms [0] = new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location);
6372 parameters = new Parameters (parms);
6373 parameters.Resolve (null);
6376 public override MethodBuilder Define (TypeContainer container)
6378 if (container.EmitContext == null)
6379 throw new InternalErrorException ("SetMethod.Define called too early");
6381 DefineParameters ();
6385 base.Define (container);
6387 method_data = new MethodData (method, ModFlags, flags, this);
6389 if (!method_data.Define (container))
6392 return method_data.MethodBuilder;
6395 public override Type ReturnType {
6397 return TypeManager.void_type;
6401 public override string[] ValidAttributeTargets {
6403 return attribute_targets;
6408 static string[] attribute_targets = new string [] { "property" };
6410 public abstract class PropertyMethod : AbstractPropertyEventMethod {
6411 protected readonly MethodCore method;
6412 protected MethodAttributes flags;
6415 public PropertyMethod (MethodCore method, string prefix)
6416 : base (method, prefix)
6418 this.method = method;
6421 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6422 : base (method, accessor, prefix)
6424 this.method = method;
6425 this.ModFlags = accessor.ModFlags;
6426 yields = accessor.Yields;
6428 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6429 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6433 public override AttributeTargets AttributeTargets {
6435 return AttributeTargets.Method;
6439 public override bool IsClsComplianceRequired(DeclSpace ds)
6441 return method.IsClsComplianceRequired (ds);
6444 public virtual MethodBuilder Define (TypeContainer container)
6446 if (!method.CheckAbstractAndExtern (block != null))
6450 // Check for custom access modifier
6452 if (ModFlags == 0) {
6453 ModFlags = method.ModFlags;
6454 flags = method.flags;
6456 if (container.Kind == Kind.Interface)
6457 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6458 GetSignatureForError ());
6460 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6461 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6464 CheckModifiers (container, ModFlags);
6465 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6466 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6467 flags = Modifiers.MethodAttr (ModFlags);
6468 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6472 // Setup iterator if we are one
6475 Iterator iterator = new Iterator (this, Parent as TypeContainer, null, ModFlags);
6477 if (!iterator.DefineIterator ())
6484 public bool HasCustomAccessModifier
6487 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6491 public override EmitContext CreateEmitContext (TypeContainer tc,
6494 return new EmitContext (
6495 tc, method.ds, method.Location, ig, ReturnType,
6496 method.ModFlags, false);
6499 public override ObsoleteAttribute GetObsoleteAttribute ()
6501 return method.GetObsoleteAttribute ();
6504 public override string GetSignatureForError()
6506 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6509 void CheckModifiers (TypeContainer container, int modflags)
6512 int mflags = method.ModFlags & Modifiers.Accessibility;
6514 if ((mflags & Modifiers.PUBLIC) != 0) {
6515 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6517 else if ((mflags & Modifiers.PROTECTED) != 0) {
6518 if ((mflags & Modifiers.INTERNAL) != 0)
6519 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6521 flags |= Modifiers.PRIVATE;
6523 else if ((mflags & Modifiers.INTERNAL) != 0)
6524 flags |= Modifiers.PRIVATE;
6526 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6527 Report.Error (273, Location,
6528 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6529 GetSignatureForError (), method.GetSignatureForError ());
6533 public override bool MarkForDuplicationCheck ()
6535 caching_flags |= Flags.TestMethodDuplication;
6540 public PropertyMethod Get, Set;
6541 public PropertyBuilder PropertyBuilder;
6542 public MethodBuilder GetBuilder, SetBuilder;
6544 protected EmitContext ec;
6546 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6547 int allowed_mod, bool is_iface, MemberName name,
6548 Parameters parameters, Attributes attrs)
6549 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6554 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6556 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6557 a.Error_InvalidSecurityParent ();
6561 PropertyBuilder.SetCustomAttribute (cb);
6564 public override AttributeTargets AttributeTargets {
6566 return AttributeTargets.Property;
6570 public override bool Define ()
6575 if (!IsTypePermitted ())
6581 protected override bool DoDefine ()
6583 if (!base.DoDefine ())
6587 // Accessors modifiers check
6589 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6590 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6591 GetSignatureForError ());
6595 if ((Get.IsDummy || Set.IsDummy)
6596 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6597 Report.Error (276, Location,
6598 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6599 GetSignatureForError ());
6603 if (MemberType.IsAbstract && MemberType.IsSealed) {
6604 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6608 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6612 protected override bool CheckForDuplications ()
6614 ArrayList ar = Parent.Indexers;
6616 int arLen = ar.Count;
6618 for (int i = 0; i < arLen; i++) {
6619 Indexer m = (Indexer) ar [i];
6620 if (IsDuplicateImplementation (m))
6625 ar = Parent.Properties;
6627 int arLen = ar.Count;
6629 for (int i = 0; i < arLen; i++) {
6630 Property m = (Property) ar [i];
6631 if (IsDuplicateImplementation (m))
6639 // TODO: rename to Resolve......
6640 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6642 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6643 container.TypeBuilder, Name, ParameterTypes, null, true) as PropertyInfo;
6645 if (base_property == null)
6648 base_ret_type = base_property.PropertyType;
6649 MethodInfo get_accessor = base_property.GetGetMethod (true);
6650 MethodInfo set_accessor = base_property.GetSetMethod (true);
6651 MethodAttributes get_accessor_access, set_accessor_access;
6653 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6654 if (Get != null && !Get.IsDummy && get_accessor == null) {
6655 Report.SymbolRelatedToPreviousError (base_property);
6656 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6659 if (Set != null && !Set.IsDummy && set_accessor == null) {
6660 Report.SymbolRelatedToPreviousError (base_property);
6661 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6666 // Check base class accessors access
6669 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6670 get_accessor_access = set_accessor_access = 0;
6671 if ((ModFlags & Modifiers.NEW) == 0) {
6672 if (get_accessor != null) {
6673 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6674 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6676 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6677 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6680 if (set_accessor != null) {
6681 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6682 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6684 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6685 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6690 // Get the less restrictive access
6692 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6695 public override void Emit ()
6698 // The PropertyBuilder can be null for explicit implementations, in that
6699 // case, we do not actually emit the ".property", so there is nowhere to
6700 // put the attribute
6702 if (PropertyBuilder != null && OptAttributes != null)
6703 OptAttributes.Emit (ec, this);
6715 /// Tests whether accessors are not in collision with some method (CS0111)
6717 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6719 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6722 public override bool IsUsed
6728 return Get.IsUsed | Set.IsUsed;
6732 protected override void SetMemberName (MemberName new_name)
6734 base.SetMemberName (new_name);
6736 Get.UpdateName (this);
6737 Set.UpdateName (this);
6740 public override string[] ValidAttributeTargets {
6742 return attribute_targets;
6747 // Represents header string for documentation comment.
6749 public override string DocCommentHeader {
6750 get { return "P:"; }
6754 public class Property : PropertyBase {
6755 const int AllowedModifiers =
6758 Modifiers.PROTECTED |
6759 Modifiers.INTERNAL |
6763 Modifiers.OVERRIDE |
6764 Modifiers.ABSTRACT |
6767 Modifiers.METHOD_YIELDS |
6770 const int AllowedInterfaceModifiers =
6773 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6774 MemberName name, Attributes attrs, Accessor get_block,
6776 : base (ds, type, mod,
6777 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6778 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6780 if (get_block == null)
6781 Get = new GetMethod (this);
6783 Get = new GetMethod (this, get_block);
6785 if (set_block == null)
6786 Set = new SetMethod (this);
6788 Set = new SetMethod (this, set_block);
6791 public override bool Define ()
6793 if (!DoDefineBase ())
6796 if (!base.Define ())
6802 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6805 GetBuilder = Get.Define (Parent);
6806 if (GetBuilder == null)
6810 SetBuilder = Set.Define (Parent);
6812 if (SetBuilder == null)
6816 // FIXME - PropertyAttributes.HasDefault ?
6818 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6819 MemberName.ToString (), PropertyAttributes.None, MemberType, null);
6822 PropertyBuilder.SetGetMethod (GetBuilder);
6825 PropertyBuilder.SetSetMethod (SetBuilder);
6832 /// Gigantic workaround for lameness in SRE follows :
6833 /// This class derives from EventInfo and attempts to basically
6834 /// wrap around the EventBuilder so that FindMembers can quickly
6835 /// return this in it search for members
6837 public class MyEventBuilder : EventInfo {
6840 // We use this to "point" to our Builder which is
6841 // not really a MemberInfo
6843 EventBuilder MyBuilder;
6846 // We "catch" and wrap these methods
6848 MethodInfo raise, remove, add;
6850 EventAttributes attributes;
6851 Type declaring_type, reflected_type, event_type;
6856 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6858 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6860 // And now store the values in our own fields.
6862 declaring_type = type_builder;
6864 reflected_type = type_builder;
6866 attributes = event_attr;
6869 this.event_type = event_type;
6873 // Methods that you have to override. Note that you only need
6874 // to "implement" the variants that take the argument (those are
6875 // the "abstract" methods, the others (GetAddMethod()) are
6878 public override MethodInfo GetAddMethod (bool nonPublic)
6883 public override MethodInfo GetRemoveMethod (bool nonPublic)
6888 public override MethodInfo GetRaiseMethod (bool nonPublic)
6894 // These methods make "MyEventInfo" look like a Builder
6896 public void SetRaiseMethod (MethodBuilder raiseMethod)
6898 raise = raiseMethod;
6899 MyBuilder.SetRaiseMethod (raiseMethod);
6902 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6904 remove = removeMethod;
6905 MyBuilder.SetRemoveOnMethod (removeMethod);
6908 public void SetAddOnMethod (MethodBuilder addMethod)
6911 MyBuilder.SetAddOnMethod (addMethod);
6914 public void SetCustomAttribute (CustomAttributeBuilder cb)
6916 MyBuilder.SetCustomAttribute (cb);
6919 public override object [] GetCustomAttributes (bool inherit)
6921 // FIXME : There's nothing which can be seemingly done here because
6922 // we have no way of getting at the custom attribute objects of the
6927 public override object [] GetCustomAttributes (Type t, bool inherit)
6929 // FIXME : Same here !
6933 public override bool IsDefined (Type t, bool b)
6938 public override EventAttributes Attributes {
6944 public override string Name {
6950 public override Type DeclaringType {
6952 return declaring_type;
6956 public override Type ReflectedType {
6958 return reflected_type;
6962 public Type EventType {
6968 public void SetUsed ()
6970 if (my_event != null) {
6971 my_event.SetAssigned ();
6972 my_event.SetMemberIsUsed ();
6978 /// For case when event is declared like property (with add and remove accessors).
6980 public class EventProperty: Event {
6982 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6984 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6985 bool is_iface, MemberName name,
6986 Attributes attrs, Accessor add, Accessor remove)
6987 : base (parent, type, mod_flags, is_iface, name, attrs)
6989 Add = new AddDelegateMethod (this, add);
6990 Remove = new RemoveDelegateMethod (this, remove);
6992 // For this event syntax we don't report error CS0067
6993 // because it is hard to do it.
6997 public override string[] ValidAttributeTargets {
6999 return attribute_targets;
7005 /// Event is declared like field.
7007 public class EventField : Event {
7009 static string[] attribute_targets = new string [] { "event", "field", "method" };
7010 static string[] attribute_targets_interface = new string[] { "event", "method" };
7012 public EventField (TypeContainer parent, Expression type, int mod_flags,
7013 bool is_iface, MemberName name,
7015 : base (parent, type, mod_flags, is_iface, name, attrs)
7017 Add = new AddDelegateMethod (this);
7018 Remove = new RemoveDelegateMethod (this);
7021 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7023 if (a.Target == AttributeTargets.Field) {
7024 FieldBuilder.SetCustomAttribute (cb);
7028 if (a.Target == AttributeTargets.Method) {
7029 Add.ApplyAttributeBuilder (a, cb);
7030 Remove.ApplyAttributeBuilder (a, cb);
7034 base.ApplyAttributeBuilder (a, cb);
7037 public override bool Define()
7039 if (!base.Define ())
7042 if (initializer != null) {
7043 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7044 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7045 GetSignatureForError ());
7053 public override string[] ValidAttributeTargets {
7055 return IsInterface ? attribute_targets_interface : attribute_targets;
7060 public abstract class Event : FieldBase {
7062 protected sealed class AddDelegateMethod: DelegateMethod
7065 public AddDelegateMethod (Event method):
7066 base (method, "add_")
7070 public AddDelegateMethod (Event method, Accessor accessor):
7071 base (method, accessor, "add_")
7075 protected override MethodInfo DelegateMethodInfo {
7077 return TypeManager.delegate_combine_delegate_delegate;
7083 protected sealed class RemoveDelegateMethod: DelegateMethod
7085 public RemoveDelegateMethod (Event method):
7086 base (method, "remove_")
7090 public RemoveDelegateMethod (Event method, Accessor accessor):
7091 base (method, accessor, "remove_")
7095 protected override MethodInfo DelegateMethodInfo {
7097 return TypeManager.delegate_remove_delegate_delegate;
7103 public abstract class DelegateMethod: AbstractPropertyEventMethod
7105 protected readonly Event method;
7106 ImplicitParameter param_attr;
7108 static string[] attribute_targets = new string [] { "method", "param", "return" };
7110 public DelegateMethod (Event method, string prefix)
7111 : base (method, prefix)
7113 this.method = method;
7116 public DelegateMethod (Event method, Accessor accessor, string prefix)
7117 : base (method, accessor, prefix)
7119 this.method = method;
7122 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7124 if (a.Target == AttributeTargets.Parameter) {
7125 if (param_attr == null)
7126 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
7128 param_attr.ApplyAttributeBuilder (a, cb);
7132 base.ApplyAttributeBuilder (a, cb);
7135 public override AttributeTargets AttributeTargets {
7137 return AttributeTargets.Method;
7141 public override bool IsClsComplianceRequired(DeclSpace ds)
7143 return method.IsClsComplianceRequired (ds);
7146 public MethodBuilder Define (TypeContainer container)
7148 method_data = new MethodData (method, method.ModFlags,
7149 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7151 if (!method_data.Define (container))
7154 MethodBuilder mb = method_data.MethodBuilder;
7155 ParameterInfo.ApplyAttributes (Parent.EmitContext, mb);
7160 protected override void EmitMethod (TypeContainer tc)
7162 if (block != null) {
7163 base.EmitMethod (tc);
7167 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7170 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
7171 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
7173 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
7174 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7175 ig.Emit (OpCodes.Ldsfld, field_info);
7176 ig.Emit (OpCodes.Ldarg_0);
7177 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7178 ig.Emit (OpCodes.Castclass, method.MemberType);
7179 ig.Emit (OpCodes.Stsfld, field_info);
7181 ig.Emit (OpCodes.Ldarg_0);
7182 ig.Emit (OpCodes.Ldarg_0);
7183 ig.Emit (OpCodes.Ldfld, field_info);
7184 ig.Emit (OpCodes.Ldarg_1);
7185 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7186 ig.Emit (OpCodes.Castclass, method.MemberType);
7187 ig.Emit (OpCodes.Stfld, field_info);
7189 ig.Emit (OpCodes.Ret);
7192 protected abstract MethodInfo DelegateMethodInfo { get; }
7194 public override Type ReturnType {
7196 return TypeManager.void_type;
7200 public override EmitContext CreateEmitContext (TypeContainer tc,
7203 return new EmitContext (
7204 tc, method.Parent, Location, ig, ReturnType,
7205 method.ModFlags, false);
7208 public override ObsoleteAttribute GetObsoleteAttribute ()
7210 return method.GetObsoleteAttribute ();
7213 public override string[] ValidAttributeTargets {
7215 return attribute_targets;
7219 public override Parameters ParameterInfo {
7221 return method.parameters;
7228 const int AllowedModifiers =
7231 Modifiers.PROTECTED |
7232 Modifiers.INTERNAL |
7237 Modifiers.OVERRIDE |
7241 const int AllowedInterfaceModifiers =
7244 public DelegateMethod Add, Remove;
7245 public MyEventBuilder EventBuilder;
7246 public MethodBuilder AddBuilder, RemoveBuilder;
7247 Parameters parameters;
7249 protected Event (TypeContainer parent, Expression type, int mod_flags,
7250 bool is_iface, MemberName name, Attributes attrs)
7251 : base (parent, type, mod_flags,
7252 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7255 IsInterface = is_iface;
7258 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7260 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7261 a.Error_InvalidSecurityParent ();
7265 EventBuilder.SetCustomAttribute (cb);
7268 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7270 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7273 public override AttributeTargets AttributeTargets {
7275 return AttributeTargets.Event;
7279 public override bool Define ()
7281 EventAttributes e_attr;
7282 e_attr = EventAttributes.None;
7284 if (!DoDefineBase ())
7290 if (!TypeManager.IsDelegateType (MemberType)) {
7291 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7295 EmitContext ec = Parent.EmitContext;
7297 throw new InternalErrorException ("Event.Define called too early?");
7298 bool old_unsafe = ec.InUnsafe;
7299 ec.InUnsafe = InUnsafe;
7301 Parameter [] parms = new Parameter [1];
7302 parms [0] = new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location);
7303 parameters = new Parameters (parms);
7304 parameters.Resolve (null);
7306 ec.InUnsafe = old_unsafe;
7312 // Now define the accessors
7315 AddBuilder = Add.Define (Parent);
7316 if (AddBuilder == null)
7319 RemoveBuilder = Remove.Define (Parent);
7320 if (RemoveBuilder == null)
7323 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7325 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7326 FieldBuilder = Parent.TypeBuilder.DefineField (
7328 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7329 TypeManager.RegisterPrivateFieldOfEvent (
7330 (EventInfo) EventBuilder, FieldBuilder);
7331 TypeManager.RegisterFieldBase (FieldBuilder, this);
7334 EventBuilder.SetAddOnMethod (AddBuilder);
7335 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7337 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7341 protected override bool CheckBase ()
7343 if (!base.CheckBase ())
7346 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7347 if (!(conflict_symbol is EventInfo)) {
7348 Report.SymbolRelatedToPreviousError (conflict_symbol);
7349 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
7357 public override void Emit ()
7359 if (OptAttributes != null) {
7360 EmitContext ec = new EmitContext (
7361 Parent, Location, null, MemberType, ModFlags);
7362 OptAttributes.Emit (ec, this);
7366 Remove.Emit (Parent);
7371 public override string GetSignatureForError ()
7373 return base.GetSignatureForError ();
7377 // Represents header string for documentation comment.
7379 public override string DocCommentHeader {
7380 get { return "E:"; }
7385 public class Indexer : PropertyBase, IIteratorContainer {
7387 class GetIndexerMethod : GetMethod
7389 public GetIndexerMethod (MethodCore method):
7394 public GetIndexerMethod (MethodCore method, Accessor accessor):
7395 base (method, accessor)
7399 public override Parameters ParameterInfo {
7401 return method.ParameterInfo;
7406 class SetIndexerMethod: SetMethod
7408 public SetIndexerMethod (MethodCore method):
7413 public SetIndexerMethod (MethodCore method, Accessor accessor):
7414 base (method, accessor)
7418 protected override void DefineParameters ()
7420 Parameter [] fixed_parms = method.Parameters.FixedParameters;
7421 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7423 fixed_parms.CopyTo (tmp, 0);
7424 tmp [fixed_parms.Length] = new Parameter (
7425 method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location);
7427 parameters = new Parameters (tmp);
7428 parameters.Resolve (null);
7432 const int AllowedModifiers =
7435 Modifiers.PROTECTED |
7436 Modifiers.INTERNAL |
7440 Modifiers.OVERRIDE |
7445 const int AllowedInterfaceModifiers =
7449 // Are we implementing an interface ?
7451 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7452 bool is_iface, Parameters parameters, Attributes attrs,
7453 Accessor get_block, Accessor set_block)
7454 : base (parent, type, mod,
7455 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7456 is_iface, name, parameters, attrs)
7458 if (get_block == null)
7459 Get = new GetIndexerMethod (this);
7461 Get = new GetIndexerMethod (this, get_block);
7463 if (set_block == null)
7464 Set = new SetIndexerMethod (this);
7466 Set = new SetIndexerMethod (this, set_block);
7469 public override bool Define ()
7471 if (!DoDefineBase ())
7474 if (!base.Define ())
7477 if (MemberType == TypeManager.void_type) {
7478 Report.Error (620, Location, "Indexers cannot have void type");
7482 if (OptAttributes != null) {
7483 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7484 if (indexer_attr != null) {
7485 // Remove the attribute from the list because it is not emitted
7486 OptAttributes.Attrs.Remove (indexer_attr);
7488 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7490 if (IsExplicitImpl) {
7491 Report.Error (415, indexer_attr.Location,
7492 "The `IndexerName' attribute is valid only on an " +
7493 "indexer that is not an explicit interface member declaration");
7497 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7498 Report.Error (609, indexer_attr.Location,
7499 "Cannot set the `IndexerName' attribute on an indexer marked override");
7503 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7504 Report.Error (633, indexer_attr.Location,
7505 "The argument to the `IndexerName' attribute must be a valid identifier");
7511 if (InterfaceType != null) {
7512 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7513 if (base_IndexerName != Name)
7514 ShortName = base_IndexerName;
7517 if (!Parent.AddToMemberContainer (this) ||
7518 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7524 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7526 GetBuilder = Get.Define (Parent);
7527 if (GetBuilder == null)
7531 // Setup iterator if we are one
7533 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7534 Iterator iterator = new Iterator (
7535 Get, Parent, null, ModFlags);
7537 if (!iterator.DefineIterator ())
7542 SetBuilder = Set.Define (Parent);
7544 if (SetBuilder == null)
7549 // Now name the parameters
7551 Parameter [] p = Parameters.FixedParameters;
7553 // TODO: should be done in parser and it needs to do cycle
7554 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7555 Report.Error (631, Location, "ref and out are not valid in this context");
7560 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7561 Name, PropertyAttributes.None, MemberType, ParameterTypes);
7564 PropertyBuilder.SetGetMethod (GetBuilder);
7567 PropertyBuilder.SetSetMethod (SetBuilder);
7569 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7574 public override string GetSignatureForError ()
7576 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7577 if (MemberName.Left != null) {
7579 sb.Append (MemberName.Left);
7582 sb.Append (".this");
7583 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7584 return sb.ToString ();
7587 public override bool MarkForDuplicationCheck ()
7589 caching_flags |= Flags.TestMethodDuplication;
7594 public class Operator : MethodCore, IIteratorContainer {
7596 const int AllowedModifiers =
7602 public enum OpType : byte {
7612 // Unary and Binary operators
7635 // Implicit and Explicit
7639 // Just because of enum
7643 public readonly OpType OperatorType;
7644 public MethodBuilder OperatorMethodBuilder;
7646 public Method OperatorMethod;
7648 static string[] attribute_targets = new string [] { "method", "return" };
7650 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7651 int mod_flags, Parameters parameters,
7652 ToplevelBlock block, Attributes attrs, Location loc)
7653 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7654 new MemberName ("op_" + type, loc), attrs, parameters)
7656 OperatorType = type;
7660 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7662 OperatorMethod.ApplyAttributeBuilder (a, cb);
7665 public override AttributeTargets AttributeTargets {
7667 return AttributeTargets.Method;
7671 protected override bool CheckForDuplications()
7673 ArrayList ar = Parent.Operators;
7675 int arLen = ar.Count;
7677 for (int i = 0; i < arLen; i++) {
7678 Operator o = (Operator) ar [i];
7679 if (IsDuplicateImplementation (o))
7684 ar = Parent.Methods;
7686 int arLen = ar.Count;
7688 for (int i = 0; i < arLen; i++) {
7689 Method m = (Method) ar [i];
7690 if (IsDuplicateImplementation (m))
7698 public override bool Define ()
7700 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7701 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7702 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7709 if (MemberType == TypeManager.void_type) {
7710 Report.Error (590, Location, "User-defined operators cannot return void");
7714 OperatorMethod = new Method (
7715 Parent, null, Type, ModFlags, false, MemberName,
7716 Parameters, OptAttributes);
7718 OperatorMethod.Block = Block;
7719 OperatorMethod.IsOperator = this;
7720 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7721 OperatorMethod.Define ();
7723 if (OperatorMethod.MethodBuilder == null)
7726 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7728 Type[] parameter_types = OperatorMethod.ParameterTypes;
7729 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7730 Type return_type = OperatorMethod.ReturnType;
7731 Type first_arg_type = parameter_types [0];
7736 // Rules for conversion operators
7738 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7739 if (first_arg_type == return_type && first_arg_type == declaring_type){
7740 Report.Error (555, Location,
7741 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7745 if (first_arg_type != declaring_type && return_type != declaring_type){
7748 "User-defined conversion must convert to or from the " +
7753 if (first_arg_type == TypeManager.object_type ||
7754 return_type == TypeManager.object_type){
7757 "User-defined conversion cannot convert to or from " +
7762 if (first_arg_type.IsInterface || return_type.IsInterface){
7763 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7764 GetSignatureForError ());
7768 if (first_arg_type.IsSubclassOf (return_type)
7769 || return_type.IsSubclassOf (first_arg_type)){
7770 if (declaring_type.IsSubclassOf (return_type)) {
7771 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7772 GetSignatureForError ());
7775 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7776 GetSignatureForError ());
7779 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7780 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7781 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");
7784 } else if (Parameters.Count == 1) {
7785 // Checks for Unary operators
7787 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7788 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7789 Report.Error (448, Location,
7790 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7793 if (first_arg_type != declaring_type){
7795 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7800 if (first_arg_type != declaring_type){
7803 "The parameter of a unary operator must be the " +
7808 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7809 if (return_type != TypeManager.bool_type){
7812 "The return type of operator True or False " +
7819 // Checks for Binary operators
7821 if (first_arg_type != declaring_type &&
7822 parameter_types [1] != declaring_type){
7825 "One of the parameters of a binary operator must " +
7826 "be the containing type");
7834 public override void Emit ()
7837 // abstract or extern methods have no bodies
7839 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7842 OperatorMethod.Emit ();
7846 // Operator cannot be override
7847 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7852 public static string GetName (OpType ot)
7855 case OpType.LogicalNot:
7857 case OpType.OnesComplement:
7859 case OpType.Increment:
7861 case OpType.Decrement:
7867 case OpType.Addition:
7869 case OpType.Subtraction:
7871 case OpType.UnaryPlus:
7873 case OpType.UnaryNegation:
7875 case OpType.Multiply:
7877 case OpType.Division:
7879 case OpType.Modulus:
7881 case OpType.BitwiseAnd:
7883 case OpType.BitwiseOr:
7885 case OpType.ExclusiveOr:
7887 case OpType.LeftShift:
7889 case OpType.RightShift:
7891 case OpType.Equality:
7893 case OpType.Inequality:
7895 case OpType.GreaterThan:
7897 case OpType.LessThan:
7899 case OpType.GreaterThanOrEqual:
7901 case OpType.LessThanOrEqual:
7903 case OpType.Implicit:
7905 case OpType.Explicit:
7911 public static OpType GetOperatorType (string name)
7913 if (name.StartsWith ("op_")){
7914 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7915 if (Unary.oper_names [i] == name)
7919 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7920 if (Binary.oper_names [i] == name)
7927 public override string GetSignatureForError ()
7929 StringBuilder sb = new StringBuilder ();
7930 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7931 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7934 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7937 sb.Append (Parameters.GetSignatureForError ());
7938 return sb.ToString ();
7941 public override bool MarkForDuplicationCheck ()
7943 caching_flags |= Flags.TestMethodDuplication;
7947 public override string[] ValidAttributeTargets {
7949 return attribute_targets;
7955 // This is used to compare method signatures
7957 struct MethodSignature {
7959 public Type RetType;
7960 public Type [] Parameters;
7963 /// This delegate is used to extract methods which have the
7964 /// same signature as the argument
7966 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7968 public MethodSignature (string name, Type ret_type, Type [] parameters)
7973 if (parameters == null)
7974 Parameters = TypeManager.NoTypes;
7976 Parameters = parameters;
7979 public override string ToString ()
7982 if (Parameters.Length != 0){
7983 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7984 for (int i = 0; i < Parameters.Length; i++){
7985 sb.Append (Parameters [i]);
7986 if (i+1 < Parameters.Length)
7989 pars = sb.ToString ();
7992 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7995 public override int GetHashCode ()
7997 return Name.GetHashCode ();
8000 public override bool Equals (Object o)
8002 MethodSignature other = (MethodSignature) o;
8004 if (other.Name != Name)
8007 if (other.RetType != RetType)
8010 if (Parameters == null){
8011 if (other.Parameters == null)
8016 if (other.Parameters == null)
8019 int c = Parameters.Length;
8020 if (other.Parameters.Length != c)
8023 for (int i = 0; i < c; i++)
8024 if (other.Parameters [i] != Parameters [i])
8030 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8032 MethodSignature sig = (MethodSignature) filter_criteria;
8034 if (m.Name != sig.Name)
8038 MethodInfo mi = m as MethodInfo;
8039 PropertyInfo pi = m as PropertyInfo;
8042 ReturnType = mi.ReturnType;
8043 else if (pi != null)
8044 ReturnType = pi.PropertyType;
8049 // we use sig.RetType == null to mean `do not check the
8050 // method return value.
8052 if (sig.RetType != null)
8053 if (ReturnType != sig.RetType)
8058 args = TypeManager.GetParameterData (mi).Types;
8060 args = TypeManager.GetArgumentTypes (pi);
8061 Type [] sigp = sig.Parameters;
8063 if (args.Length != sigp.Length)
8066 for (int i = args.Length; i > 0; ){
8068 if (args [i] != sigp [i])