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 ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
128 Report.Warning (659, 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 Hashtable pairs = new Hashtable (null, null);
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, 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, 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.Location, 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.HasInitializer)
616 RegisterFieldForInitialization (field);
618 if ((field.ModFlags & Modifiers.STATIC) != 0)
621 if (first_nonstatic_field == null) {
622 first_nonstatic_field = field;
626 if (Kind == Kind.Struct &&
627 first_nonstatic_field.Parent != field.Parent &&
628 RootContext.WarningLevel >= 3) {
629 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
630 Report.Warning (282, field.Location,
631 "struct instance field `{0}' found in different declaration from instance field `{1}'",
632 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
636 public void AddProperty (Property prop)
638 if (!AddToMemberContainer (prop) ||
639 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
642 if (properties == null)
643 properties = new MemberCoreArrayList ();
645 if (prop.MemberName.Left != null)
646 properties.Insert (0, prop);
648 properties.Add (prop);
651 public void AddEvent (Event e)
653 if (!AddToMemberContainer (e))
656 if (e is EventProperty) {
657 if (!AddToMemberContainer (e.Add))
660 if (!AddToMemberContainer (e.Remove))
665 events = new MemberCoreArrayList ();
671 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
673 public void AddIndexer (Indexer i)
675 if (indexers == null)
676 indexers = new IndexerArrayList (this);
678 if (i.IsExplicitImpl)
679 indexers.Insert (0, i);
684 public void AddOperator (Operator op)
686 if (!AddToMemberContainer (op))
689 if (operators == null)
690 operators = new OperatorArrayList (this);
695 public void AddIterator (Iterator i)
697 if (iterators == null)
698 iterators = new ArrayList ();
703 public void AddType (TypeContainer tc)
708 public void AddPart (ClassPart part)
711 parts = new ArrayList ();
716 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
718 if (a.Type == TypeManager.default_member_type) {
719 if (Indexers != null) {
720 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
725 base.ApplyAttributeBuilder (a, cb);
728 public override AttributeTargets AttributeTargets {
732 return AttributeTargets.Class;
734 return AttributeTargets.Struct;
736 return AttributeTargets.Interface;
738 throw new NotSupportedException ();
743 public ArrayList Types {
749 public MethodArrayList Methods {
755 public ArrayList Constants {
761 public ArrayList Interfaces {
767 public ArrayList Iterators {
775 return base_class_name;
779 public ArrayList Bases {
789 public ArrayList Fields {
795 public ArrayList InstanceConstructors {
797 return instance_constructors;
801 public ArrayList Properties {
807 public ArrayList Events {
813 public ArrayList Enums {
819 public ArrayList Indexers {
825 public ArrayList Operators {
831 public ArrayList Delegates {
837 public ArrayList Parts {
843 protected override TypeAttributes TypeAttr {
845 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
849 public string IndexerName {
851 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
855 public virtual void RegisterFieldForInitialization (FieldMember field)
857 if ((field.ModFlags & Modifiers.STATIC) != 0){
858 if (initialized_static_fields == null)
859 initialized_static_fields = new ArrayList ();
861 initialized_static_fields.Add (field);
863 if (initialized_fields == null)
864 initialized_fields = new ArrayList ();
866 initialized_fields.Add (field);
870 bool CanElideInitializer (Type field_type, Constant c)
872 if (field_type == c.Type)
874 if (TypeManager.IsValueType (field_type) || TypeManager.HasElementType (field_type))
876 // Reference type with null initializer.
877 return c.Type == TypeManager.null_type;
881 // Emits the instance field initializers
883 public virtual bool EmitFieldInitializers (EmitContext ec)
886 Expression instance_expr;
889 fields = initialized_static_fields;
890 instance_expr = null;
892 fields = initialized_fields;
893 instance_expr = new This (Location.Null).Resolve (ec);
899 foreach (FieldMember f in fields){
900 Expression e = f.GetInitializerExpression (ec);
904 Location l = f.Location;
905 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
906 fe.InstanceExpression = instance_expr;
908 ExpressionStatement a = new Assign (fe, e, l);
910 a = a.ResolveStatement (ec);
914 Constant c = e as Constant;
915 if (c != null && c.IsDefaultValue && CanElideInitializer (f.MemberType, c))
918 a.EmitStatement (ec);
925 // Defines the default constructors
927 protected void DefineDefaultConstructor (bool is_static)
931 // The default constructor is public
932 // If the class is abstract, the default constructor is protected
933 // The default static constructor is private
935 int mods = Modifiers.PUBLIC;
937 mods = Modifiers.STATIC | Modifiers.PRIVATE;
938 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
939 mods = Modifiers.PROTECTED;
941 TypeContainer constructor_parent = this;
943 constructor_parent = (TypeContainer) Parts [0];
945 c = new Constructor (constructor_parent, MemberName.Name, mods,
946 Parameters.EmptyReadOnlyParameters,
947 new ConstructorBaseInitializer (null, Location),
952 c.Block = new ToplevelBlock (null, Location);
957 /// The pending methods that need to be implemented
958 // (interfaces or abstract methods)
960 public PendingImplementation Pending;
962 public abstract PendingImplementation GetPendingImplementations ();
964 TypeExpr[] GetPartialBases (out TypeExpr base_class)
966 ArrayList ifaces = new ArrayList ();
969 Location base_loc = Location.Null;
971 foreach (ClassPart part in parts) {
972 TypeExpr new_base_class;
973 TypeExpr[] new_ifaces;
975 new_ifaces = part.GetClassBases (out new_base_class);
976 if (new_ifaces == null && new_base_class != null)
979 if ((base_class != null) && (new_base_class != null) &&
980 !base_class.Equals (new_base_class)) {
981 Report.Error (263, part.Location,
982 "Partial declarations of `{0}' must " +
983 "not specify different base classes",
986 if (!base_loc.IsNull)
987 Report.LocationOfPreviousError (base_loc);
992 if ((base_class == null) && (new_base_class != null)) {
993 base_class = new_base_class;
994 base_loc = part.Location;
997 if (new_ifaces == null)
1000 foreach (TypeExpr iface in new_ifaces) {
1002 foreach (TypeExpr old_iface in ifaces) {
1003 if (old_iface.Equals (iface)) {
1014 TypeExpr[] retval = new TypeExpr [ifaces.Count];
1015 ifaces.CopyTo (retval, 0);
1019 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1023 int count = Bases.Count;
1024 int start = 0, i, j;
1026 if (Kind == Kind.Class){
1027 TypeExpr name = ResolveBaseTypeExpr (
1028 (Expression) Bases [0], false, Location);
1034 if (!name.IsInterface) {
1035 // base_class could be a class, struct, enum, delegate.
1036 // This is validated in GetClassBases.
1042 TypeExpr [] ifaces = new TypeExpr [count-start];
1044 for (i = start, j = 0; i < count; i++, j++){
1045 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1046 if (resolved == null) {
1050 ifaces [j] = resolved;
1057 /// This function computes the Base class and also the
1058 /// list of interfaces that the class or struct @c implements.
1060 /// The return value is an array (might be null) of
1061 /// interfaces implemented (as Types).
1063 /// The @base_class argument is set to the base object or null
1064 /// if this is `System.Object'.
1066 protected virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1073 ifaces = GetPartialBases (out base_class);
1074 else if (Bases == null){
1078 ifaces = GetNormalBases (out base_class);
1083 if ((base_class != null) && (Kind == Kind.Class)){
1084 if (base_class is TypeParameterExpr){
1086 689, base_class.Location,
1087 "Type parameter `{0}' can not be used as a " +
1088 "base class or interface", base_class.Name);
1093 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1094 Report.Error (1521, base_class.Location, "Invalid base type");
1098 if (base_class.IsSealed){
1099 Report.SymbolRelatedToPreviousError (base_class.Type);
1100 if (base_class.Type.IsAbstract) {
1101 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
1102 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1104 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
1105 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
1110 if (!base_class.CanInheritFrom ()){
1111 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
1112 GetSignatureForError (), base_class.GetSignatureForError ());
1116 if (!base_class.AsAccessible (this, ModFlags)) {
1117 Report.SymbolRelatedToPreviousError (base_class.Type);
1118 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
1119 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1123 if (base_class != null)
1124 base_class_name = base_class.Name;
1129 int count = ifaces != null ? ifaces.Length : 0;
1131 for (i = 0; i < count; i++) {
1132 TypeExpr iface = (TypeExpr) ifaces [i];
1134 if (!iface.IsInterface) {
1135 if (Kind != Kind.Class) {
1136 // TODO: location of symbol related ....
1137 Error_TypeInListIsNotInterface (Location, iface.FullName);
1139 else if (base_class != null)
1140 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1141 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1143 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1144 GetSignatureForError (), iface.GetSignatureForError ());
1149 for (int x = 0; x < i; x++) {
1150 if (iface.Equals (ifaces [x])) {
1151 Report.Error (528, Location,
1152 "`{0}' is already listed in " +
1153 "interface list", iface.Name);
1158 if ((Kind == Kind.Interface) &&
1159 !iface.AsAccessible (Parent, ModFlags)) {
1160 Report.Error (61, Location,
1161 "Inconsistent accessibility: base " +
1162 "interface `{0}' is less accessible " +
1163 "than interface `{1}'", iface.Name,
1171 bool CheckGenericInterfaces (Type[] ifaces)
1173 ArrayList already_checked = new ArrayList ();
1175 for (int i = 0; i < ifaces.Length; i++) {
1176 Type iface = ifaces [i];
1177 foreach (Type t in already_checked) {
1181 Type[] infered = new Type [CountTypeParameters];
1182 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1187 "`{0}' cannot implement both `{1}' and `{2}' " +
1188 "because they may unify for some type " +
1189 "parameter substitutions",
1190 TypeManager.GetFullName (TypeBuilder),
1195 already_checked.Add (iface);
1203 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1205 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1209 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1211 public override TypeBuilder DefineType ()
1216 if (TypeBuilder != null)
1219 TypeAttributes type_attributes = TypeAttr;
1223 if (TypeManager.NamespaceClash (Name, Location)) {
1228 ModuleBuilder builder = CodeGen.Module.Builder;
1229 TypeBuilder = builder.DefineType (
1230 Name, type_attributes, null, null);
1232 TypeBuilder builder = Parent.TypeBuilder;
1233 if (builder == null) {
1238 TypeBuilder = builder.DefineNestedType (
1239 Basename, type_attributes, ptype, null);
1241 } catch (ArgumentException) {
1242 Report.RuntimeMissingSupport (Location, "static classes");
1247 TypeManager.AddUserType (Name, this);
1249 if (Parts != null) {
1251 foreach (ClassPart part in Parts) {
1252 part.TypeBuilder = TypeBuilder;
1254 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1255 part.ec.ContainerType = TypeBuilder;
1259 // Normally, we create the EmitContext here.
1260 // The only exception is if we're an Iterator - in this case,
1261 // we already have the `ec', so we don't want to create a new one.
1264 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1265 ec.ContainerType = TypeBuilder;
1269 string[] param_names = new string [TypeParameters.Length];
1270 for (int i = 0; i < TypeParameters.Length; i++)
1271 param_names [i] = TypeParameters [i].Name;
1273 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1275 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1276 for (int i = offset; i < gen_params.Length; i++)
1277 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1280 iface_exprs = GetClassBases (out base_type);
1281 if (iface_exprs == null && base_type != null) {
1286 if (base_type == null) {
1287 if (Kind == Kind.Class){
1288 if (RootContext.StdLib)
1289 base_type = TypeManager.system_object_expr;
1290 else if (Name != "System.Object")
1291 base_type = TypeManager.system_object_expr;
1292 } else if (Kind == Kind.Struct){
1294 // If we are compiling our runtime,
1295 // and we are defining ValueType, then our
1296 // base is `System.Object'.
1298 if (!RootContext.StdLib && Name == "System.ValueType")
1299 base_type = TypeManager.system_object_expr;
1300 else if (Kind == Kind.Struct)
1301 base_type = TypeManager.system_valuetype_expr;
1305 if (base_type != null) {
1306 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1307 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1308 ptype = base_type.ResolveType (TypeResolveEmitContext);
1309 if (ptype == null) {
1314 ptype = base_type.Type;
1316 if (IsGeneric && TypeManager.IsAttributeType (ptype)) {
1317 Report.Error (698, base_type.Location,
1318 "A generic type cannot derive from `{0}' " +
1319 "because it is an attribute class",
1326 if (!CheckRecursiveDefinition (this)) {
1332 TypeBuilder.SetParent (ptype);
1334 // add interfaces that were not added at type creation
1335 if (iface_exprs != null) {
1336 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1337 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1338 TypeResolveEmitContext.ContainerType = TypeBuilder;
1339 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1340 if (ifaces == null) {
1345 foreach (Type itype in ifaces)
1346 TypeBuilder.AddInterfaceImplementation (itype);
1348 if (!CheckGenericInterfaces (ifaces)) {
1353 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1356 if (!(this is Iterator))
1357 RootContext.RegisterOrder (this);
1358 else if (!ResolveType ()) {
1363 if (!DefineNestedTypes ()) {
1371 public bool ResolveType ()
1376 TypeExpr current_type = null;
1377 if (Parts != null) {
1378 foreach (ClassPart part in Parts) {
1379 if (!part.DefineTypeParameters ()) {
1385 foreach (TypeParameter type_param in CurrentTypeParameters) {
1386 if (!type_param.Resolve (this)) {
1392 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1393 for (int i = offset; i < gen_params.Length; i++)
1394 CurrentTypeParameters [i - offset].DefineConstraints ();
1396 foreach (TypeParameter type_param in TypeParameters) {
1397 if (!type_param.DefineType (ec)) {
1403 current_type = new ConstructedType (
1404 TypeBuilder, TypeParameters, Location);
1407 foreach (TypeParameter type_param in TypeParameters)
1408 if (!type_param.CheckDependencies (ec)) {
1413 if (current_type != null) {
1414 current_type = current_type.ResolveAsTypeTerminal (ec);
1415 if (current_type == null) {
1420 CurrentType = current_type.Type;
1426 protected virtual bool DefineNestedTypes ()
1428 if (Interfaces != null) {
1429 foreach (TypeContainer iface in Interfaces)
1430 if (iface.DefineType () == null)
1434 if (Types != null) {
1435 foreach (TypeContainer tc in Types)
1436 if (tc.DefineType () == null)
1440 if (Delegates != null) {
1441 foreach (Delegate d in Delegates)
1442 if (d.DefineType () == null)
1446 if (Enums != null) {
1447 foreach (Enum en in Enums)
1448 if (en.DefineType () == null)
1455 TypeContainer InTransit;
1457 protected bool CheckRecursiveDefinition (TypeContainer tc)
1459 if (InTransit != null) {
1460 Report.SymbolRelatedToPreviousError (this);
1461 if (this is Interface)
1463 529, tc.Location, "Inherited interface `{0}' causes a " +
1464 "cycle in the interface hierarchy of `{1}'",
1465 GetSignatureForError (), tc.GetSignatureForError ());
1468 146, tc.Location, "Circular base class dependency " +
1469 "involving `{0}' and `{1}'",
1470 tc.GetSignatureForError (), GetSignatureForError ());
1476 Type parent = ptype;
1477 if (parent != null) {
1478 if (parent.IsGenericInstance)
1479 parent = parent.GetGenericTypeDefinition ();
1481 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1482 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1486 if (iface_exprs != null) {
1487 foreach (TypeExpr iface in iface_exprs) {
1488 Type itype = iface.Type;
1490 if (itype.IsGenericInstance)
1491 itype = itype.GetGenericTypeDefinition ();
1493 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1494 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1503 public static void Error_KeywordNotAllowed (Location loc)
1505 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1509 /// Populates our TypeBuilder with fields and methods
1511 public override bool DefineMembers (TypeContainer container)
1513 if (members_defined)
1514 return members_defined_ok;
1516 if (!base.DefineMembers (container))
1519 members_defined_ok = DoDefineMembers ();
1520 members_defined = true;
1522 return members_defined_ok;
1525 protected virtual bool DoDefineMembers ()
1527 if (iface_exprs != null) {
1528 foreach (TypeExpr iface in iface_exprs) {
1529 ConstructedType ct = iface as ConstructedType;
1530 if ((ct != null) && !ct.CheckConstraints (ec))
1535 if (base_type != null) {
1536 ConstructedType ct = base_type as ConstructedType;
1537 if ((ct != null) && !ct.CheckConstraints (ec))
1542 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1543 if (conflict_symbol == null) {
1544 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1545 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1547 if ((ModFlags & Modifiers.NEW) == 0) {
1548 Report.SymbolRelatedToPreviousError (conflict_symbol);
1549 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1550 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1555 DefineContainerMembers (constants);
1556 DefineContainerMembers (fields);
1558 if ((Kind == Kind.Class) && !(this is ClassPart)){
1559 if ((instance_constructors == null) &&
1560 !(this is StaticClass)) {
1561 if (default_constructor == null)
1562 DefineDefaultConstructor (false);
1565 if (initialized_static_fields != null &&
1566 default_static_constructor == null)
1567 DefineDefaultConstructor (true);
1570 if (Kind == Kind.Struct){
1572 // Structs can not have initialized instance
1575 if (initialized_static_fields != null &&
1576 default_static_constructor == null)
1577 DefineDefaultConstructor (true);
1579 if (initialized_fields != null)
1580 ReportStructInitializedInstanceError ();
1583 Pending = GetPendingImplementations ();
1585 if (parts != null) {
1586 foreach (ClassPart part in parts) {
1587 if (!part.DefineMembers (this))
1593 // Constructors are not in the defined_names array
1595 DefineContainerMembers (instance_constructors);
1597 if (default_static_constructor != null)
1598 default_static_constructor.Define ();
1600 DefineContainerMembers (properties);
1601 DefineContainerMembers (events);
1602 DefineContainerMembers (indexers);
1603 DefineContainerMembers (methods);
1604 DefineContainerMembers (operators);
1605 DefineContainerMembers (enums);
1606 DefineContainerMembers (delegates);
1608 if (CurrentType != null) {
1609 GenericType = CurrentType;
1611 ec.ContainerType = GenericType;
1616 if (!(this is ClassPart))
1617 member_cache = new MemberCache (this);
1620 if (parts != null) {
1621 foreach (ClassPart part in parts)
1622 part.member_cache = member_cache;
1625 if (iterators != null) {
1626 foreach (Iterator iterator in iterators) {
1627 if (iterator.DefineType () == null)
1631 foreach (Iterator iterator in iterators) {
1632 if (!iterator.DefineMembers (this))
1640 void ReportStructInitializedInstanceError ()
1642 foreach (Field f in initialized_fields){
1643 Report.Error (573, Location,
1644 "`{0}': Structs cannot have instance field initializers",
1645 f.GetSignatureForError ());
1649 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1652 mcal.DefineContainerMembers ();
1655 public override bool Define ()
1657 if (parts != null) {
1658 foreach (ClassPart part in parts) {
1659 if (!part.Define ())
1664 if (iterators != null) {
1665 foreach (Iterator iterator in iterators) {
1666 if (!iterator.Define ())
1674 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1676 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1680 /// This function is based by a delegate to the FindMembers routine
1682 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1688 /// This filter is used by FindMembers, and we just keep
1689 /// a global for the filter to `AlwaysAccept'
1691 static MemberFilter accepting_filter;
1694 static TypeContainer ()
1696 accepting_filter = new MemberFilter (AlwaysAccept);
1699 public MethodInfo[] GetMethods ()
1701 ArrayList members = new ArrayList ();
1703 DefineMembers (null);
1705 if (methods != null) {
1706 int len = methods.Count;
1707 for (int i = 0; i < len; i++) {
1708 Method m = (Method) methods [i];
1710 members.Add (m.MethodBuilder);
1714 if (operators != null) {
1715 int len = operators.Count;
1716 for (int i = 0; i < len; i++) {
1717 Operator o = (Operator) operators [i];
1719 members.Add (o.OperatorMethodBuilder);
1723 if (properties != null) {
1724 int len = properties.Count;
1725 for (int i = 0; i < len; i++) {
1726 Property p = (Property) properties [i];
1728 if (p.GetBuilder != null)
1729 members.Add (p.GetBuilder);
1730 if (p.SetBuilder != null)
1731 members.Add (p.SetBuilder);
1735 if (indexers != null) {
1736 int len = indexers.Count;
1737 for (int i = 0; i < len; i++) {
1738 Indexer ix = (Indexer) indexers [i];
1740 if (ix.GetBuilder != null)
1741 members.Add (ix.GetBuilder);
1742 if (ix.SetBuilder != null)
1743 members.Add (ix.SetBuilder);
1747 if (events != null) {
1748 int len = events.Count;
1749 for (int i = 0; i < len; i++) {
1750 Event e = (Event) events [i];
1752 if (e.AddBuilder != null)
1753 members.Add (e.AddBuilder);
1754 if (e.RemoveBuilder != null)
1755 members.Add (e.RemoveBuilder);
1759 MethodInfo[] retMethods = new MethodInfo [members.Count];
1760 members.CopyTo (retMethods, 0);
1764 // Indicated whether container has StructLayout attribute set Explicit
1765 public virtual bool HasExplicitLayout {
1771 public override Type FindNestedType (string name)
1773 ArrayList [] lists = { types, enums, delegates, interfaces };
1775 for (int j = 0; j < lists.Length; ++j) {
1776 ArrayList list = lists [j];
1780 int len = list.Count;
1781 for (int i = 0; i < len; ++i) {
1782 DeclSpace ds = (DeclSpace) list [i];
1783 if (ds.Basename == name) {
1785 return ds.TypeBuilder;
1793 private void FindMembers_NestedTypes (int modflags,
1794 BindingFlags bf, MemberFilter filter, object criteria,
1795 ref ArrayList members)
1797 ArrayList [] lists = { types, enums, delegates, interfaces };
1799 for (int j = 0; j < lists.Length; ++j) {
1800 ArrayList list = lists [j];
1804 int len = list.Count;
1805 for (int i = 0; i < len; i++) {
1806 DeclSpace ds = (DeclSpace) list [i];
1808 if ((ds.ModFlags & modflags) == 0)
1811 TypeBuilder tb = ds.TypeBuilder;
1813 if (!(criteria is string) || ds.Basename.Equals (criteria))
1814 tb = ds.DefineType ();
1817 if (tb != null && (filter (tb, criteria) == true)) {
1818 if (members == null)
1819 members = new ArrayList ();
1828 /// This method returns the members of this type just like Type.FindMembers would
1829 /// Only, we need to use this for types which are _being_ defined because MS'
1830 /// implementation can't take care of that.
1833 // FIXME: return an empty static array instead of null, that cleans up
1834 // some code and is consistent with some coding conventions I just found
1838 // Notice that in various cases we check if our field is non-null,
1839 // something that would normally mean that there was a bug elsewhere.
1841 // The problem happens while we are defining p-invoke methods, as those
1842 // will trigger a FindMembers, but this happens before things are defined
1844 // Since the whole process is a no-op, it is fine to check for null here.
1846 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1847 MemberFilter filter, object criteria)
1849 ArrayList members = null;
1852 if ((bf & BindingFlags.Public) != 0)
1853 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1855 if ((bf & BindingFlags.NonPublic) != 0)
1856 modflags |= Modifiers.PRIVATE;
1858 int static_mask = 0, static_flags = 0;
1859 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1860 case BindingFlags.Static:
1861 static_mask = static_flags = Modifiers.STATIC;
1864 case BindingFlags.Instance:
1865 static_mask = Modifiers.STATIC;
1870 static_mask = static_flags = 0;
1874 Timer.StartTimer (TimerType.TcFindMembers);
1877 filter = accepting_filter;
1879 if ((mt & MemberTypes.Field) != 0) {
1880 if (fields != null) {
1881 int len = fields.Count;
1882 for (int i = 0; i < len; i++) {
1883 FieldMember f = (FieldMember) fields [i];
1885 if ((f.ModFlags & modflags) == 0)
1887 if ((f.ModFlags & static_mask) != static_flags)
1890 FieldBuilder fb = f.FieldBuilder;
1891 if (fb != null && filter (fb, criteria) == true) {
1892 if (members == null)
1893 members = new ArrayList ();
1900 if (constants != null) {
1901 int len = constants.Count;
1902 for (int i = 0; i < len; i++) {
1903 Const con = (Const) constants [i];
1905 if ((con.ModFlags & modflags) == 0)
1907 if ((con.ModFlags & static_mask) != static_flags)
1910 FieldBuilder fb = con.FieldBuilder;
1913 fb = con.FieldBuilder;
1915 if (fb != null && filter (fb, criteria) == true) {
1916 if (members == null)
1917 members = new ArrayList ();
1925 if ((mt & MemberTypes.Method) != 0) {
1926 if (methods != null) {
1927 int len = methods.Count;
1928 for (int i = 0; i < len; i++) {
1929 Method m = (Method) methods [i];
1931 if ((m.ModFlags & modflags) == 0)
1933 if ((m.ModFlags & static_mask) != static_flags)
1936 MethodBuilder mb = m.MethodBuilder;
1938 if (mb != null && filter (mb, criteria) == true) {
1939 if (members == null)
1940 members = new ArrayList ();
1947 if (operators != null) {
1948 int len = operators.Count;
1949 for (int i = 0; i < len; i++) {
1950 Operator o = (Operator) operators [i];
1952 if ((o.ModFlags & modflags) == 0)
1954 if ((o.ModFlags & static_mask) != static_flags)
1957 MethodBuilder ob = o.OperatorMethodBuilder;
1958 if (ob != null && filter (ob, criteria) == true) {
1959 if (members == null)
1960 members = new ArrayList ();
1967 if (properties != null) {
1968 int len = properties.Count;
1969 for (int i = 0; i < len; i++) {
1970 Property p = (Property) properties [i];
1972 if ((p.ModFlags & modflags) == 0)
1974 if ((p.ModFlags & static_mask) != static_flags)
1980 if (b != null && filter (b, criteria) == true) {
1981 if (members == null)
1982 members = new ArrayList ();
1988 if (b != null && filter (b, criteria) == true) {
1989 if (members == null)
1990 members = new ArrayList ();
1997 if (indexers != null) {
1998 int len = indexers.Count;
1999 for (int i = 0; i < len; i++) {
2000 Indexer ix = (Indexer) indexers [i];
2002 if ((ix.ModFlags & modflags) == 0)
2004 if ((ix.ModFlags & static_mask) != static_flags)
2010 if (b != null && filter (b, criteria) == true) {
2011 if (members == null)
2012 members = new ArrayList ();
2018 if (b != null && filter (b, criteria) == true) {
2019 if (members == null)
2020 members = new ArrayList ();
2028 if ((mt & MemberTypes.Event) != 0) {
2029 if (events != null) {
2030 int len = events.Count;
2031 for (int i = 0; i < len; i++) {
2032 Event e = (Event) events [i];
2034 if ((e.ModFlags & modflags) == 0)
2036 if ((e.ModFlags & static_mask) != static_flags)
2039 MemberInfo eb = e.EventBuilder;
2040 if (eb != null && filter (eb, criteria) == true) {
2041 if (members == null)
2042 members = new ArrayList ();
2044 members.Add (e.EventBuilder);
2050 if ((mt & MemberTypes.Property) != 0){
2051 if (properties != null) {
2052 int len = properties.Count;
2053 for (int i = 0; i < len; i++) {
2054 Property p = (Property) properties [i];
2056 if ((p.ModFlags & modflags) == 0)
2058 if ((p.ModFlags & static_mask) != static_flags)
2061 MemberInfo pb = p.PropertyBuilder;
2062 if (pb != null && filter (pb, criteria) == true) {
2063 if (members == null)
2064 members = new ArrayList ();
2066 members.Add (p.PropertyBuilder);
2071 if (indexers != null) {
2072 int len = indexers.Count;
2073 for (int i = 0; i < len; i++) {
2074 Indexer ix = (Indexer) indexers [i];
2076 if ((ix.ModFlags & modflags) == 0)
2078 if ((ix.ModFlags & static_mask) != static_flags)
2081 MemberInfo ib = ix.PropertyBuilder;
2082 if (ib != null && filter (ib, criteria) == true) {
2083 if (members == null)
2084 members = new ArrayList ();
2086 members.Add (ix.PropertyBuilder);
2092 if ((mt & MemberTypes.NestedType) != 0)
2093 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2095 if ((mt & MemberTypes.Constructor) != 0){
2096 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2097 int len = instance_constructors.Count;
2098 for (int i = 0; i < len; i++) {
2099 Constructor c = (Constructor) instance_constructors [i];
2101 ConstructorBuilder cb = c.ConstructorBuilder;
2102 if (cb != null && filter (cb, criteria) == true) {
2103 if (members == null)
2104 members = new ArrayList ();
2111 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2112 ConstructorBuilder cb =
2113 default_static_constructor.ConstructorBuilder;
2115 if (cb != null && filter (cb, criteria) == true) {
2116 if (members == null)
2117 members = new ArrayList ();
2125 // Lookup members in base if requested.
2127 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2128 if (TypeBuilder.BaseType != null) {
2129 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2130 if (list.Count > 0) {
2131 if (members == null)
2132 members = new ArrayList ();
2134 members.AddRange (list);
2140 Timer.StopTimer (TimerType.TcFindMembers);
2142 if (members == null)
2143 return MemberList.Empty;
2145 return new MemberList (members);
2148 public override MemberCache MemberCache {
2150 return member_cache;
2154 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2155 MemberFilter filter, object criteria)
2157 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2160 return ds.FindMembers (mt, bf, filter, criteria);
2162 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2166 // FindMethods will look for methods not only in the type `t', but in
2167 // any interfaces implemented by the type.
2169 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2170 MemberFilter filter, object criteria)
2176 /// Emits the values for the constants
2178 public void EmitConstants ()
2180 if (constants != null)
2181 foreach (Const con in constants)
2186 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2191 foreach (MemberCore mc in al) {
2192 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2196 Report.Warning (169, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2201 public virtual void VerifyMembers ()
2204 // Check for internal or private fields that were never assigned
2206 if (RootContext.WarningLevel >= 3) {
2207 CheckMemberUsage (properties, "property");
2208 CheckMemberUsage (methods, "method");
2209 CheckMemberUsage (constants, "constant");
2211 if (fields != null){
2212 foreach (FieldMember f in fields) {
2213 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2217 if ((f.caching_flags & Flags.IsAssigned) == 0)
2218 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2221 const int error_code = 414;
2223 const int error_code = 169;
2225 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2226 f.GetSignatureForError ());
2232 // Only report 649 on level 4
2234 if (RootContext.WarningLevel < 4)
2237 if ((f.caching_flags & Flags.IsAssigned) != 0)
2240 Report.Warning (649, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2241 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2248 /// Emits the code, this step is performed after all
2249 /// the types, enumerations, constructors
2251 public void EmitType ()
2253 if (OptAttributes != null)
2254 OptAttributes.Emit (ec, this);
2257 // Structs with no fields need to have at least one byte.
2258 // The right thing would be to set the PackingSize in a DefineType
2259 // but there are no functions that allow interfaces *and* the size to
2263 if (Kind == Kind.Struct && first_nonstatic_field == null){
2264 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2265 FieldAttributes.Private);
2267 if (HasExplicitLayout){
2268 object [] ctor_args = new object [1];
2271 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2272 TypeManager.field_offset_attribute_ctor, ctor_args);
2273 fb.SetCustomAttribute (cba);
2279 if (instance_constructors != null) {
2280 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired (this)) {
2281 bool has_compliant_args = false;
2283 foreach (Constructor c in instance_constructors) {
2286 if (has_compliant_args)
2289 has_compliant_args = c.HasCompliantArgs;
2291 if (!has_compliant_args)
2292 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2294 foreach (Constructor c in instance_constructors)
2299 // Can not continue if constants are broken
2301 if (Report.Errors > 0)
2304 if (default_static_constructor != null)
2305 default_static_constructor.Emit ();
2307 if (methods != null)
2308 foreach (Method m in methods)
2311 if (operators != null)
2312 foreach (Operator o in operators)
2315 if (properties != null)
2316 foreach (Property p in properties)
2319 if (indexers != null){
2324 foreach (FieldMember f in fields)
2327 if (events != null){
2328 foreach (Event e in Events)
2332 if (delegates != null) {
2333 foreach (Delegate d in Delegates) {
2338 if (enums != null) {
2339 foreach (Enum e in enums) {
2344 if (parts != null) {
2345 foreach (ClassPart part in parts)
2349 if ((Pending != null) && !(this is ClassPart))
2350 if (Pending.VerifyPendingMethods ())
2353 if (iterators != null)
2354 foreach (Iterator iterator in iterators)
2355 iterator.EmitType ();
2357 // if (types != null)
2358 // foreach (TypeContainer tc in types)
2362 public override void CloseType ()
2364 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2368 caching_flags |= Flags.CloseTypeCreated;
2369 TypeBuilder.CreateType ();
2370 } catch (TypeLoadException){
2372 // This is fine, the code still created the type
2374 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2375 // Console.WriteLine (e.Message);
2377 Console.WriteLine ("In type: " + Name);
2382 foreach (Enum en in Enums)
2386 foreach (TypeContainer tc in Types)
2387 if (tc.Kind == Kind.Struct)
2390 foreach (TypeContainer tc in Types)
2391 if (tc.Kind != Kind.Struct)
2395 if (Delegates != null)
2396 foreach (Delegate d in Delegates)
2399 if (Iterators != null)
2400 foreach (Iterator i in Iterators)
2408 initialized_fields = null;
2409 initialized_static_fields = null;
2418 default_constructor = null;
2419 default_static_constructor = null;
2421 OptAttributes = null;
2424 member_cache = null;
2428 // Performs the validation on a Method's modifiers (properties have
2429 // the same properties).
2431 public bool MethodModifiersValid (MemberCore mc)
2433 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2434 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2435 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2437 int flags = mc.ModFlags;
2440 // At most one of static, virtual or override
2442 if ((flags & Modifiers.STATIC) != 0){
2443 if ((flags & vao) != 0){
2444 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2445 mc.GetSignatureForError ());
2450 if (Kind == Kind.Struct){
2451 if ((flags & va) != 0){
2452 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2457 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2458 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2459 mc.GetSignatureForError ());
2464 // If the declaration includes the abstract modifier, then the
2465 // declaration does not include static, virtual or extern
2467 if ((flags & Modifiers.ABSTRACT) != 0){
2468 if ((flags & Modifiers.EXTERN) != 0){
2470 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2474 if ((flags & Modifiers.SEALED) != 0) {
2475 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2479 if ((flags & Modifiers.VIRTUAL) != 0){
2480 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2484 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2485 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2490 if ((flags & Modifiers.PRIVATE) != 0){
2491 if ((flags & vao) != 0){
2492 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2497 if ((flags & Modifiers.SEALED) != 0){
2498 if ((flags & Modifiers.OVERRIDE) == 0){
2499 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2507 public bool UserDefinedStaticConstructor {
2509 return default_static_constructor != null;
2513 public Constructor DefaultStaticConstructor {
2514 get { return default_static_constructor; }
2517 protected override bool VerifyClsCompliance (DeclSpace ds)
2519 if (!base.VerifyClsCompliance (ds))
2524 Type base_type = TypeBuilder.BaseType;
2525 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2526 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2529 if (!Parent.IsClsComplianceRequired (ds)) {
2530 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type `{1}'",
2531 GetSignatureForError (), Parent.GetSignatureForError ());
2538 /// Checks whether container name is CLS Compliant
2540 void VerifyClsName ()
2542 Hashtable base_members = base_cache == null ?
2544 base_cache.GetPublicMembers ();
2545 Hashtable this_members = new Hashtable ();
2547 foreach (DictionaryEntry entry in defined_names) {
2548 MemberCore mc = (MemberCore)entry.Value;
2549 if (!mc.IsClsComplianceRequired (mc.Parent))
2552 string name = (string) entry.Key;
2553 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2555 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2556 object found = base_members [lcase];
2557 if (found == null) {
2558 found = this_members [lcase];
2559 if (found == null) {
2560 this_members.Add (lcase, mc);
2565 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2568 if (found is MemberInfo) {
2569 if (basename == ((MemberInfo) found).Name)
2571 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2573 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2575 Report.Warning (3005, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2581 /// Performs checks for an explicit interface implementation. First it
2582 /// checks whether the `interface_type' is a base inteface implementation.
2583 /// Then it checks whether `name' exists in the interface type.
2585 public virtual bool VerifyImplements (MemberBase mb)
2587 if (ifaces != null) {
2588 foreach (Type t in ifaces){
2589 if (t == mb.InterfaceType)
2594 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2595 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2599 protected override void VerifyObsoleteAttribute()
2601 CheckUsageOfObsoleteAttribute (TypeBuilder.BaseType);
2606 foreach (Type iface in ifaces) {
2607 CheckUsageOfObsoleteAttribute (iface);
2615 string IMemberContainer.Name {
2621 Type IMemberContainer.Type {
2627 MemberCache IMemberContainer.MemberCache {
2629 return member_cache;
2633 bool IMemberContainer.IsInterface {
2635 return Kind == Kind.Interface;
2639 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2641 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2643 if (GenericType != null)
2644 return TypeManager.FindMembers (GenericType, mt, new_bf,
2647 return FindMembers (mt, new_bf, null, null);
2651 // Generates xml doc comments (if any), and if required,
2652 // handle warning report.
2654 internal override void GenerateDocComment (DeclSpace ds)
2656 DocUtil.GenerateTypeDocComment (this, ds);
2659 public override string DocCommentHeader {
2660 get { return "T:"; }
2663 public virtual MemberCache BaseCache {
2665 if (base_cache != null)
2667 if (TypeBuilder.BaseType != null)
2668 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2669 if (TypeBuilder.IsInterface)
2670 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2677 public class PartialContainer : TypeContainer {
2679 public readonly Namespace Namespace;
2680 public readonly int OriginalModFlags;
2681 public readonly int AllowedModifiers;
2682 public readonly TypeAttributes DefaultTypeAttributes;
2684 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2685 MemberName member_name, int mod_flags, Kind kind)
2688 if (!CheckModFlags (0, mod_flags, member_name))
2691 PartialContainer pc = RootContext.Tree.GetDecl (member_name) as PartialContainer;
2693 if (pc.Kind != kind) {
2695 261, member_name.Location,
2696 "Partial declarations of `{0}' must be all classes, " +
2697 "all structs or all interfaces",
2698 member_name.GetTypeName ());
2702 if (!CheckModFlags (pc.OriginalModFlags, mod_flags, member_name))
2704 pc.ModFlags |= (mod_flags & pc.AllowedModifiers);
2707 if (pc.CountTypeParameters != member_name.CountTypeArguments) {
2709 264, member_name.Location,
2710 "Partial declarations of `{0}' must have the " +
2711 "same type parameter names in the same order",
2712 member_name.GetTypeName ());
2716 string[] pc_names = pc.MemberName.TypeArguments.GetDeclarations ();
2717 string[] names = member_name.TypeArguments.GetDeclarations ();
2719 for (int i = 0; i < pc.CountTypeParameters; i++) {
2720 if (pc_names [i] == names [i])
2724 264, member_name.Location,
2725 "Partial declarations of `{0}' must have the " +
2726 "same type parameter names in the same order",
2727 member_name.GetTypeName ());
2735 if (parent is ClassPart)
2736 parent = ((ClassPart) parent).PartialContainer;
2738 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind);
2740 if (kind == Kind.Interface) {
2741 if (!parent.AddInterface (pc))
2743 } else if (kind == Kind.Class || kind == Kind.Struct) {
2744 if (!parent.AddClassOrStruct (pc))
2747 throw new InvalidOperationException ();
2749 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2750 // This is needed to define our type parameters; we define the constraints later.
2751 pc.SetParameterInfo (null);
2755 static bool CheckModFlags (int flags_org, int flags, MemberName member_name)
2757 // Check (abstract|static|sealed) sanity.
2758 int tmp = (flags_org | flags) & (Modifiers.ABSTRACT | Modifiers.SEALED | Modifiers.STATIC);
2759 if ((tmp & Modifiers.ABSTRACT) != 0) {
2760 if ((tmp & (Modifiers.STATIC | Modifiers.SEALED)) != 0) {
2762 418, member_name.Location,
2763 "`{0}': an abstract class cannot be sealed or static", member_name.ToString ());
2766 } else if (tmp == (Modifiers.SEALED | Modifiers.STATIC)) {
2767 Report.Error (441, member_name.Location, "`{0}': a class cannot be both static and sealed", member_name.ToString ());
2775 if (0 != ((flags_org ^ flags) & (0xFFFFFFFF ^ (Modifiers.SEALED | Modifiers.ABSTRACT)))) {
2777 262, member_name.Location, "Partial declarations of `{0}' " +
2778 "have conflicting accessibility modifiers",
2779 member_name.GetName ());
2785 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2786 MemberName name, int mod, Attributes attrs,
2787 Kind kind, Location loc)
2789 PartialContainer pc = Create (ns, parent, name, mod, kind);
2791 // An error occured; create a dummy container, but don't
2793 pc = new PartialContainer (ns.NS, parent, name, mod, kind);
2796 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind);
2801 protected PartialContainer (Namespace ns, TypeContainer parent,
2802 MemberName name, int mod, Kind kind)
2803 : base (null, parent, name, null, kind)
2805 this.Namespace = ns;
2809 AllowedModifiers = Class.AllowedModifiers;
2810 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2814 AllowedModifiers = Struct.AllowedModifiers;
2815 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2818 case Kind.Interface:
2819 AllowedModifiers = Interface.AllowedModifiers;
2820 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2824 throw new InvalidOperationException ();
2828 if (parent.Parent == null)
2829 accmods = Modifiers.INTERNAL;
2831 accmods = Modifiers.PRIVATE;
2833 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2834 this.OriginalModFlags = mod;
2837 public override PendingImplementation GetPendingImplementations ()
2839 return PendingImplementation.GetPendingImplementations (this);
2842 public override bool MarkForDuplicationCheck ()
2847 protected override TypeAttributes TypeAttr {
2849 return base.TypeAttr | DefaultTypeAttributes;
2854 public class ClassPart : TypeContainer, IMemberContainer {
2855 public readonly PartialContainer PartialContainer;
2856 public readonly bool IsPartial;
2858 Constraints[] constraints;
2860 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2861 int mod, Attributes attrs, Kind kind)
2862 : base (ns, parent, pc.MemberName, attrs, kind)
2864 this.PartialContainer = pc;
2865 this.IsPartial = true;
2868 if (parent == null || parent == RootContext.Tree.Types)
2869 accmods = Modifiers.INTERNAL;
2871 accmods = Modifiers.PRIVATE;
2873 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, pc.MemberName.Location);
2876 constraints = new Constraints [pc.CountCurrentTypeParameters];
2879 public override PendingImplementation GetPendingImplementations ()
2881 return PartialContainer.Pending;
2884 public override bool VerifyImplements (MemberBase mb)
2886 return PartialContainer.VerifyImplements (mb);
2889 public override void SetParameterInfo (ArrayList constraints_list)
2891 if (constraints_list == null)
2894 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2895 for (int i = 0; i < constraints.Length; i++) {
2896 foreach (Constraints constraint in constraints_list) {
2897 if (constraint.TypeParameter == current_params [i].Name) {
2898 constraints [i] = constraint;
2905 public bool DefineTypeParameters ()
2907 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
2909 for (int i = 0; i < current_params.Length; i++) {
2910 Constraints new_constraints = constraints [i];
2911 if (new_constraints == null)
2914 if (!current_params [i].UpdateConstraints (ec, new_constraints)) {
2915 Report.Error (265, Location, "Partial declarations of `{0}' have " +
2916 "inconsistent constraints for type parameter `{1}'.",
2917 MemberName.GetTypeName (), current_params [i].Name);
2922 for (int i = 0; i < current_params.Length; i++) {
2923 if (!current_params [i].Resolve (this))
2927 for (int i = 0; i < current_params.Length; i++)
2928 current_params [i].DefineConstraints ();
2930 foreach (TypeParameter type_param in PartialContainer.TypeParameters) {
2931 if (!type_param.DefineType (ec))
2938 public override void RegisterFieldForInitialization (FieldMember field)
2940 PartialContainer.RegisterFieldForInitialization (field);
2943 public override bool EmitFieldInitializers (EmitContext ec)
2945 return PartialContainer.EmitFieldInitializers (ec);
2948 public override Type FindNestedType (string name)
2950 return PartialContainer.FindNestedType (name);
2953 public override MemberCache BaseCache {
2955 return PartialContainer.BaseCache;
2959 public override TypeBuilder DefineType ()
2961 throw new InternalErrorException ("Should not get here");
2966 public abstract class ClassOrStruct : TypeContainer {
2967 bool has_explicit_layout = false;
2968 ListDictionary declarative_security;
2970 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2971 MemberName name, Attributes attrs, Kind kind)
2972 : base (ns, parent, name, attrs, kind)
2976 public override PendingImplementation GetPendingImplementations ()
2978 return PendingImplementation.GetPendingImplementations (this);
2981 public override bool HasExplicitLayout {
2983 return has_explicit_layout;
2987 public override void VerifyMembers ()
2989 base.VerifyMembers ();
2991 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2992 foreach (Event e in events){
2993 if ((e.caching_flags & Flags.IsAssigned) == 0)
2994 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2999 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3001 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3002 if (declarative_security == null)
3003 declarative_security = new ListDictionary ();
3005 a.ExtractSecurityPermissionSet (declarative_security);
3009 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
3010 has_explicit_layout = true;
3012 base.ApplyAttributeBuilder (a, cb);
3015 public override void Emit()
3019 if (declarative_security != null) {
3020 foreach (DictionaryEntry de in declarative_security) {
3021 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3028 /// Class handles static classes declaration
3030 public sealed class StaticClass: Class {
3031 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3033 : base (ns, parent, name, mod, attrs)
3035 if (RootContext.Version == LanguageVersion.ISO_1) {
3036 Report.FeatureIsNotStandardized (Location, "static classes");
3040 protected override int AllowedModifiersProp {
3042 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
3043 Modifiers.STATIC | Modifiers.UNSAFE;
3047 protected override void DefineContainerMembers (MemberCoreArrayList list)
3052 foreach (MemberCore m in list) {
3053 if (m is Operator) {
3054 Report.Error (715, m.Location, "`{0}': static classes cannot contain user-defined operators", m.GetSignatureForError ());
3058 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
3059 Report.Warning (-628, 4, m.Location, "`{0}': new protected member declared in static class", m.GetSignatureForError ());
3062 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
3066 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
3069 if (m is Constructor) {
3070 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
3074 if (m is Destructor) {
3075 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
3078 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
3081 base.DefineContainerMembers (list);
3084 public override TypeBuilder DefineType()
3086 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
3087 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
3091 TypeBuilder tb = base.DefineType ();
3095 if (ptype != TypeManager.object_type) {
3096 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
3100 if (ifaces != null) {
3101 foreach (Type t in ifaces)
3102 Report.SymbolRelatedToPreviousError (t);
3103 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
3108 protected override TypeAttributes TypeAttr {
3110 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
3115 public class Class : ClassOrStruct {
3116 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
3117 public const int AllowedModifiers =
3120 Modifiers.PROTECTED |
3121 Modifiers.INTERNAL |
3123 Modifiers.ABSTRACT |
3127 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3129 : base (ns, parent, name, attrs, Kind.Class)
3131 this.ModFlags = mod;
3134 virtual protected int AllowedModifiersProp {
3136 return AllowedModifiers;
3140 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
3142 if (a.Type == TypeManager.attribute_usage_type) {
3143 if (ptype != TypeManager.attribute_type &&
3144 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
3145 TypeBuilder.FullName != "System.Attribute") {
3146 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
3150 if (a.Type == TypeManager.conditional_attribute_type &&
3151 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
3152 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
3156 if (AttributeTester.IsAttributeExcluded (a.Type))
3159 base.ApplyAttributeBuilder (a, cb);
3162 public const TypeAttributes DefaultTypeAttributes =
3163 TypeAttributes.AutoLayout | TypeAttributes.Class;
3165 public override TypeBuilder DefineType()
3167 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
3168 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
3172 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
3173 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
3175 return base.DefineType ();
3178 /// Search for at least one defined condition in ConditionalAttribute of attribute class
3179 /// Valid only for attribute classes.
3180 public bool IsExcluded ()
3182 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3183 return (caching_flags & Flags.Excluded) != 0;
3185 caching_flags &= ~Flags.Excluded_Undetected;
3187 if (OptAttributes == null)
3190 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3195 foreach (Attribute a in attrs) {
3196 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
3197 if (RootContext.AllDefines.Contains (condition))
3201 caching_flags |= Flags.Excluded;
3206 // FIXME: How do we deal with the user specifying a different
3209 protected override TypeAttributes TypeAttr {
3211 return base.TypeAttr | DefaultTypeAttributes;
3216 public class Struct : ClassOrStruct {
3218 // Modifiers allowed in a struct declaration
3220 public const int AllowedModifiers =
3223 Modifiers.PROTECTED |
3224 Modifiers.INTERNAL |
3228 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
3229 int mod, Attributes attrs)
3230 : base (ns, parent, name, attrs, Kind.Struct)
3234 if (parent.Parent == null)
3235 accmods = Modifiers.INTERNAL;
3237 accmods = Modifiers.PRIVATE;
3239 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
3241 this.ModFlags |= Modifiers.SEALED;
3244 public const TypeAttributes DefaultTypeAttributes =
3245 TypeAttributes.SequentialLayout |
3246 TypeAttributes.Sealed |
3247 TypeAttributes.BeforeFieldInit;
3250 // FIXME: Allow the user to specify a different set of attributes
3251 // in some cases (Sealed for example is mandatory for a class,
3252 // but what SequentialLayout can be changed
3254 protected override TypeAttributes TypeAttr {
3256 return base.TypeAttr | DefaultTypeAttributes;
3264 public class Interface : TypeContainer, IMemberContainer {
3267 /// Modifiers allowed in a class declaration
3269 public const int AllowedModifiers =
3272 Modifiers.PROTECTED |
3273 Modifiers.INTERNAL |
3277 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3279 : base (ns, parent, name, attrs, Kind.Interface)
3283 if (parent.Parent == null)
3284 accmods = Modifiers.INTERNAL;
3286 accmods = Modifiers.PRIVATE;
3288 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3291 public override PendingImplementation GetPendingImplementations ()
3296 public const TypeAttributes DefaultTypeAttributes =
3297 TypeAttributes.AutoLayout |
3298 TypeAttributes.Abstract |
3299 TypeAttributes.Interface;
3301 protected override TypeAttributes TypeAttr {
3303 return base.TypeAttr | DefaultTypeAttributes;
3307 protected override bool VerifyClsCompliance (DeclSpace ds)
3309 if (!base.VerifyClsCompliance (ds))
3312 if (ifaces != null) {
3313 foreach (Type t in ifaces) {
3314 if (AttributeTester.IsClsCompliant (t))
3317 Report.SymbolRelatedToPreviousError (t);
3318 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3319 GetSignatureForError (), TypeManager.CSharpName (t));
3327 public abstract class MethodCore : MemberBase {
3328 public readonly Parameters Parameters;
3329 public readonly GenericMethod GenericMethod;
3330 protected ToplevelBlock block;
3333 // Parameters, cached for semantic analysis.
3335 protected InternalParameters parameter_info;
3336 protected Type [] parameter_types;
3338 // Whether this is an operator method.
3339 public Operator IsOperator;
3342 // The method we're overriding if this is an override method.
3344 protected MethodInfo base_method = null;
3346 static string[] attribute_targets = new string [] { "method", "return" };
3348 public MethodCore (TypeContainer parent, GenericMethod generic,
3349 Expression type, int mod, int allowed_mod, bool is_iface,
3350 MemberName name, Attributes attrs, Parameters parameters)
3351 : base (parent, generic != null ? generic : (DeclSpace) parent,
3352 type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs)
3354 Parameters = parameters;
3355 IsInterface = is_iface;
3356 this.GenericMethod = generic;
3360 // Returns the System.Type array for the parameters of this method
3362 public Type [] ParameterTypes {
3364 return parameter_types;
3368 public InternalParameters ParameterInfo
3371 return parameter_info;
3375 public ToplevelBlock Block {
3385 public void SetYields ()
3387 ModFlags |= Modifiers.METHOD_YIELDS;
3390 protected override bool CheckBase ()
3392 if (!base.CheckBase ())
3395 // Check whether arguments were correct.
3396 if (!DoDefineParameters ())
3399 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3405 // Is null for System.Object while compiling corlib and base interfaces
3406 if (Parent.BaseCache == null) {
3407 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3408 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3413 Type base_ret_type = null;
3414 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3416 // method is override
3417 if (base_method != null) {
3419 if (!CheckMethodAgainstBase ())
3422 if ((ModFlags & Modifiers.NEW) == 0) {
3423 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_ret_type))) {
3424 Report.SymbolRelatedToPreviousError (base_method);
3425 if (this is PropertyBase) {
3426 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3427 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3430 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3431 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3436 if (base_method.IsAbstract && !IsInterface) {
3437 Report.SymbolRelatedToPreviousError (base_method);
3438 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3439 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3444 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3445 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3449 if (RootContext.WarningLevel > 2) {
3450 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3451 Parent.Methods.HasEquals = true;
3452 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3453 Parent.Methods.HasGetHashCode = true;
3456 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3457 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3459 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3460 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3461 Report.SymbolRelatedToPreviousError (base_method);
3462 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3463 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3470 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3471 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3472 if (conflict_symbol != null) {
3473 Report.SymbolRelatedToPreviousError (conflict_symbol);
3474 if (this is PropertyBase)
3475 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3477 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3479 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3483 if (conflict_symbol == null) {
3484 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3485 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3490 if ((ModFlags & Modifiers.NEW) == 0) {
3491 if (this is Method && conflict_symbol is MethodBase)
3494 Report.SymbolRelatedToPreviousError (conflict_symbol);
3495 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3496 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3503 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3504 // that have been defined.
3506 // `name' is the user visible name for reporting errors (this is used to
3507 // provide the right name regarding method names and properties)
3509 bool CheckMethodAgainstBase ()
3513 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3514 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3515 Report.Error (506, Location,
3516 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3517 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3521 // Now we check that the overriden method is not final
3523 if (base_method.IsFinal) {
3524 Report.SymbolRelatedToPreviousError (base_method);
3525 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3526 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3530 // Check that the permissions are not being changed
3532 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3533 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3535 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3536 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3541 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3542 ModFlags |= Modifiers.NEW;
3543 Report.SymbolRelatedToPreviousError (base_method);
3544 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3545 if (RootContext.WarningLevel >= 2)
3546 Report.Warning (114, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword", GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3548 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3549 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3556 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3558 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3560 // when overriding protected internal, the method can be declared
3561 // protected internal only within the same assembly
3564 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3565 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3567 // assemblies differ - report an error
3571 } else if (thisp != base_classp) {
3573 // same assembly, but other attributes differ - report an error
3578 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3580 // if it's not "protected internal", it must be "protected"
3584 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3586 // protected within the same assembly - an error
3589 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3590 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3592 // protected ok, but other attributes differ - report an error
3598 return (thisp == base_classp);
3602 public bool CheckAbstractAndExtern (bool has_block)
3604 if (Parent.Kind == Kind.Interface)
3608 if ((ModFlags & Modifiers.EXTERN) != 0) {
3609 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3610 GetSignatureForError ());
3614 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3615 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3616 GetSignatureForError ());
3620 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3621 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3622 GetSignatureForError ());
3630 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3632 Report.SymbolRelatedToPreviousError (base_method);
3633 string base_name = TypeManager.GetFullNameSignature (base_method);
3634 string this_name = GetSignatureForError ();
3635 if (suffix != null) {
3636 base_name += suffix;
3637 this_name += suffix;
3640 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3641 this_name, Modifiers.GetDescription (ma), base_name);
3644 protected static string Error722 {
3646 return "`{0}': static types cannot be used as return types";
3651 /// For custom member duplication search in a container
3653 protected abstract bool CheckForDuplications ();
3656 /// Gets base method and its return type
3658 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3660 protected virtual bool DoDefineParameters ()
3662 EmitContext ec = ds.EmitContext;
3664 throw new InternalErrorException ("DoDefineParameters invoked too early");
3666 bool old_unsafe = ec.InUnsafe;
3667 ec.InUnsafe = InUnsafe;
3668 // Check if arguments were correct
3669 parameter_types = Parameters.GetParameterInfo (ec);
3670 ec.InUnsafe = old_unsafe;
3672 if ((parameter_types == null) ||
3673 !CheckParameters (ds, parameter_types))
3676 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3677 parameter_info = new InternalParameters (parameter_types, Parameters, tparam);
3679 Parameter array_param = Parameters.ArrayParameter;
3680 if ((array_param != null) &&
3681 (!array_param.ParameterType.IsArray ||
3682 (array_param.ParameterType.GetArrayRank () != 1))) {
3683 Report.Error (225, Location, "The params parameter must be a single dimensional array");
3690 void error_425 (Type old, Type t, string name)
3692 Report.Error (425, Location,
3693 "The constraints of type parameter `{0}' " +
3694 "of method `{1}' must match the constraints for " +
3695 "type parameter `{2}' of method `{3}'",
3696 TypeManager.CSharpName (old), Name,
3697 TypeManager.CSharpName (t), name);
3700 protected override bool CheckGenericOverride (MethodInfo method, string name)
3702 ParameterData pd = TypeManager.GetParameterData (method);
3704 for (int i = 0; i < ParameterTypes.Length; i++) {
3705 GenericConstraints ogc = pd.GenericConstraints (i);
3706 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3708 if ((gc == null) && (ogc == null))
3711 Type ot = pd.ParameterType (i);
3712 Type t = ParameterTypes [i];
3714 if (!((gc != null) && (ogc != null))) {
3715 error_425 (ot, t, name);
3719 if ((gc.Attributes != ogc.Attributes) ||
3720 (gc.HasClassConstraint != ogc.HasClassConstraint)) {
3721 error_425 (ot, t, name);
3725 if (ogc.HasClassConstraint &&
3726 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3727 error_425 (ot, t, name);
3731 Type[] oct = ogc.InterfaceConstraints;
3732 Type[] ct = gc.InterfaceConstraints;
3734 if (oct.Length != ct.Length) {
3735 error_425 (ot, t, name);
3739 for (int j = 0; j < oct.Length; j++)
3740 if (!oct [j].Equals (ct [j])) {
3741 error_425 (ot, t, name);
3749 public override string[] ValidAttributeTargets {
3751 return attribute_targets;
3755 protected override bool VerifyClsCompliance (DeclSpace ds)
3757 if (!base.VerifyClsCompliance (ds)) {
3758 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsComplianceRequired (ds)) {
3759 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3764 if (Parameters.HasArglist) {
3765 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3768 if (!AttributeTester.IsClsCompliant (MemberType)) {
3769 if (this is PropertyBase)
3770 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3771 GetSignatureForError ());
3773 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3774 GetSignatureForError ());
3777 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3782 bool MayUnify (MethodCore first, MethodCore second)
3784 int a_type_params = 0;
3785 if (first.GenericMethod != null)
3786 a_type_params = first.GenericMethod.CountTypeParameters;
3788 int b_type_params = 0;
3789 if (second.GenericMethod != null)
3790 b_type_params = second.GenericMethod.CountTypeParameters;
3792 if (a_type_params != b_type_params)
3795 Type[] class_infered, method_infered;
3796 if (Parent.CountTypeParameters > 0)
3797 class_infered = new Type [Parent.CountTypeParameters];
3799 class_infered = null;
3801 if (a_type_params > 0)
3802 method_infered = new Type [a_type_params];
3804 method_infered = null;
3806 return TypeManager.MayBecomeEqualGenericInstances (
3807 first.ParameterTypes, second.ParameterTypes, class_infered, method_infered);
3810 protected bool IsDuplicateImplementation (MethodCore method)
3812 if (method == this || !(method.MemberName.Equals (MemberName)))
3815 Type[] param_types = method.ParameterTypes;
3816 if (param_types == null && ParameterTypes == null)
3818 if (param_types == null || ParameterTypes == null)
3821 if (param_types.Length != ParameterTypes.Length)
3825 bool may_unify = MayUnify (this, method);
3827 for (int i = 0; i < param_types.Length; i++) {
3828 if (param_types [i] != ParameterTypes [i])
3832 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3833 equal = may_unify = false;
3835 // TODO: make operator compatible with MethodCore to avoid this
3836 if (this is Operator && method is Operator) {
3837 if (MemberType != method.MemberType)
3838 equal = may_unify = false;
3843 // Try to report 663: method only differs on out/ref
3845 ParameterData info = ParameterInfo;
3846 ParameterData other_info = method.ParameterInfo;
3847 for (int i = 0; i < info.Count; i++){
3848 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3849 Report.SymbolRelatedToPreviousError (method);
3850 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3851 GetSignatureForError ());
3856 Report.SymbolRelatedToPreviousError (method);
3857 if (this is Operator && method is Operator)
3858 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3860 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3863 } else if (may_unify) {
3864 Report.Error (408, Location,
3865 "`{0}' cannot define overload members that " +
3866 "may unify for some type parameter substitutions",
3874 public override bool IsUsed {
3875 get { return IsExplicitImpl || base.IsUsed; }
3879 // Returns a string that represents the signature for this
3880 // member which should be used in XML documentation.
3882 public override string GetDocCommentName (DeclSpace ds)
3884 return DocUtil.GetMethodDocCommentName (this, ds);
3888 // Raised (and passed an XmlElement that contains the comment)
3889 // when GenerateDocComment is writing documentation expectedly.
3891 // FIXME: with a few effort, it could be done with XmlReader,
3892 // that means removal of DOM use.
3894 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3896 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3900 // Represents header string for documentation comment.
3902 public override string DocCommentHeader {
3903 get { return "M:"; }
3906 protected override void VerifyObsoleteAttribute()
3908 base.VerifyObsoleteAttribute ();
3910 if (parameter_types == null)
3913 foreach (Type type in parameter_types) {
3914 CheckUsageOfObsoleteAttribute (type);
3919 public class SourceMethod : ISourceMethod
3921 TypeContainer container;
3924 protected SourceMethod (TypeContainer container, MethodBase builder,
3925 ISourceFile file, Location start, Location end)
3927 this.container = container;
3928 this.builder = builder;
3930 CodeGen.SymbolWriter.OpenMethod (
3931 file, this, start.Row, start.Column, end.Row, start.Column);
3934 public string Name {
3935 get { return builder.Name; }
3938 public int NamespaceID {
3939 get { return container.NamespaceEntry.SymbolFileID; }
3944 if (builder is MethodBuilder)
3945 return ((MethodBuilder) builder).GetToken ().Token;
3946 else if (builder is ConstructorBuilder)
3947 return ((ConstructorBuilder) builder).GetToken ().Token;
3949 throw new NotSupportedException ();
3953 public void CloseMethod ()
3955 if (CodeGen.SymbolWriter != null)
3956 CodeGen.SymbolWriter.CloseMethod ();
3959 public static SourceMethod Create (TypeContainer parent,
3960 MethodBase builder, Block block)
3962 if (CodeGen.SymbolWriter == null)
3967 Location start_loc = block.StartLocation;
3968 if (start_loc.IsNull)
3971 Location end_loc = block.EndLocation;
3975 ISourceFile file = start_loc.SourceFile;
3979 return new SourceMethod (
3980 parent, builder, file, start_loc, end_loc);
3984 public class Method : MethodCore, IIteratorContainer, IMethodData {
3985 public MethodBuilder MethodBuilder;
3986 public MethodData MethodData;
3987 ReturnParameter return_attributes;
3988 ListDictionary declarative_security;
3991 /// Modifiers allowed in a class declaration
3993 const int AllowedModifiers =
3996 Modifiers.PROTECTED |
3997 Modifiers.INTERNAL |
4002 Modifiers.OVERRIDE |
4003 Modifiers.ABSTRACT |
4005 Modifiers.METHOD_YIELDS |
4008 const int AllowedInterfaceModifiers =
4009 Modifiers.NEW | Modifiers.UNSAFE;
4012 // return_type can be "null" for VOID values.
4014 public Method (TypeContainer parent, GenericMethod generic,
4015 Expression return_type, int mod, bool is_iface,
4016 MemberName name, Parameters parameters, Attributes attrs)
4017 : base (parent, generic, return_type, mod,
4018 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
4019 is_iface, name, attrs, parameters)
4023 public override AttributeTargets AttributeTargets {
4025 return AttributeTargets.Method;
4029 public override string GetSignatureForError()
4031 if (IsOperator != null)
4032 return IsOperator.GetSignatureForError ();
4034 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4037 void DuplicateEntryPoint (MethodInfo b, Location location)
4041 "Program `" + CodeGen.FileName +
4042 "' has more than one entry point defined: `" +
4043 TypeManager.CSharpSignature(b) + "'");
4046 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
4048 if (b.ReturnType != TypeManager.void_type &&
4049 b.ReturnType != TypeManager.int32_type)
4052 if (pinfo.Count == 0)
4055 if (pinfo.Count > 1)
4058 Type t = pinfo.ParameterType(0);
4060 (t.GetArrayRank() == 1) &&
4061 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
4062 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
4068 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4070 if (a.Target == AttributeTargets.ReturnValue) {
4071 if (return_attributes == null)
4072 return_attributes = new ReturnParameter (MethodBuilder, Location);
4074 return_attributes.ApplyAttributeBuilder (a, cb);
4078 if (a.Type == TypeManager.methodimpl_attr_type &&
4079 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
4080 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
4083 if (a.Type == TypeManager.dllimport_type) {
4084 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4085 if ((ModFlags & extern_static) != extern_static) {
4086 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
4092 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4093 if (declarative_security == null)
4094 declarative_security = new ListDictionary ();
4095 a.ExtractSecurityPermissionSet (declarative_security);
4099 if (a.Type == TypeManager.conditional_attribute_type) {
4100 if (IsOperator != null || IsExplicitImpl) {
4101 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4102 GetSignatureForError ());
4106 if (ReturnType != TypeManager.void_type) {
4107 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4111 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4112 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4117 Report.Error (582, Location, "Conditional not valid on interface members");
4121 if (MethodData.implementing != null) {
4122 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4123 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4127 for (int i = 0; i < parameter_info.Count; ++i) {
4128 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
4129 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4135 MethodBuilder.SetCustomAttribute (cb);
4138 protected override bool CheckForDuplications ()
4140 ArrayList ar = Parent.Methods;
4142 int arLen = ar.Count;
4144 for (int i = 0; i < arLen; i++) {
4145 Method m = (Method) ar [i];
4146 if (IsDuplicateImplementation (m))
4151 ar = Parent.Properties;
4153 for (int i = 0; i < ar.Count; ++i) {
4154 PropertyBase pb = (PropertyBase) ar [i];
4155 if (pb.AreAccessorsDuplicateImplementation (this))
4160 ar = Parent.Indexers;
4162 for (int i = 0; i < ar.Count; ++i) {
4163 PropertyBase pb = (PropertyBase) ar [i];
4164 if (pb.AreAccessorsDuplicateImplementation (this))
4171 for (int i = 0; i < ar.Count; ++i) {
4172 Event ev = (Event) ar [i];
4173 if (ev.AreAccessorsDuplicateImplementation (this))
4184 public override bool Define ()
4186 if (!DoDefineBase ())
4189 MethodBuilder mb = null;
4190 if (GenericMethod != null) {
4191 string method_name = MemberName.Name;
4194 method_name = TypeManager.GetFullName (InterfaceType) + "." + method_name;
4196 mb = Parent.TypeBuilder.DefineGenericMethod (method_name, flags);
4197 if (!GenericMethod.Define (mb))
4204 if (!CheckAbstractAndExtern (block != null))
4207 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
4208 Error1599 (Location, ReturnType);
4215 if (IsOperator != null)
4216 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
4218 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
4219 this, mb, GenericMethod, base_method);
4221 if (!MethodData.Define (Parent))
4224 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
4225 Name == "Finalize" && !(this is Destructor)) {
4226 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4230 // Setup iterator if we are one
4232 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
4233 Iterator iterator = new Iterator (
4234 this, Parent, GenericMethod, ParameterInfo, ModFlags);
4236 if (!iterator.DefineIterator ())
4240 MethodBuilder = MethodData.MethodBuilder;
4243 // This is used to track the Entry Point,
4245 if (Name == "Main" &&
4246 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
4247 (RootContext.MainClass == null ||
4248 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4249 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
4250 IMethodData md = TypeManager.GetMethod (MethodBuilder);
4251 md.SetMemberIsUsed ();
4253 if (RootContext.EntryPoint == null) {
4254 if (Parent.IsGeneric){
4255 Report.Error (-201, Location,
4256 "Entry point can not be defined in a generic class");
4259 RootContext.EntryPoint = MethodBuilder;
4260 RootContext.EntryPointLocation = Location;
4262 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4263 DuplicateEntryPoint (MethodBuilder, Location);
4266 if (RootContext.WarningLevel >= 4)
4267 Report.Warning (28, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
4271 if (MemberType.IsAbstract && MemberType.IsSealed) {
4272 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
4282 public override void Emit ()
4284 MethodData.Emit (Parent, this);
4287 if (declarative_security != null) {
4288 foreach (DictionaryEntry de in declarative_security) {
4289 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4297 public static void Error1599 (Location loc, Type t)
4299 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4302 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4304 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
4305 container.TypeBuilder, Name, ParameterTypes, false);
4310 base_ret_type = mi.ReturnType;
4314 public override bool MarkForDuplicationCheck ()
4316 caching_flags |= Flags.TestMethodDuplication;
4320 protected override bool VerifyClsCompliance(DeclSpace ds)
4322 if (!base.VerifyClsCompliance (ds))
4325 if (parameter_types.Length > 0) {
4326 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
4328 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4334 #region IMethodData Members
4336 public CallingConventions CallingConventions {
4338 CallingConventions cc = Parameters.GetCallingConvention ();
4339 if (Parameters.HasArglist)
4340 block.HasVarargs = true;
4343 if ((ModFlags & Modifiers.STATIC) == 0)
4344 cc |= CallingConventions.HasThis;
4346 // FIXME: How is `ExplicitThis' used in C#?
4352 public Type ReturnType {
4358 public MemberName MethodName {
4364 public new Location Location {
4366 return base.Location;
4370 protected override bool CheckBase() {
4371 if (!base.CheckBase ())
4374 // TODO: Destructor should derive from MethodCore
4375 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4376 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4377 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4384 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4386 EmitContext ec = new EmitContext (
4387 tc, ds, Location, ig, ReturnType, ModFlags, false);
4389 Iterator iterator = tc as Iterator;
4390 if (iterator != null)
4391 ec.CurrentAnonymousMethod = iterator.Host;
4396 public ObsoleteAttribute GetObsoleteAttribute ()
4398 return GetObsoleteAttribute (ds);
4402 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4404 public bool IsExcluded (EmitContext ec)
4406 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4407 return (caching_flags & Flags.Excluded) != 0;
4409 caching_flags &= ~Flags.Excluded_Undetected;
4411 if (base_method == null) {
4412 if (OptAttributes == null)
4415 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4420 foreach (Attribute a in attrs) {
4421 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4422 if (RootContext.AllDefines.Contains (condition))
4426 caching_flags |= Flags.Excluded;
4430 IMethodData md = TypeManager.GetMethod (base_method);
4432 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4433 caching_flags |= Flags.Excluded;
4439 if (md.IsExcluded (ec)) {
4440 caching_flags |= Flags.Excluded;
4446 GenericMethod IMethodData.GenericMethod {
4448 return GenericMethod;
4455 public abstract class ConstructorInitializer {
4456 ArrayList argument_list;
4457 protected ConstructorInfo base_constructor;
4460 public ConstructorInitializer (ArrayList argument_list, Location loc)
4462 this.argument_list = argument_list;
4466 public ArrayList Arguments {
4468 return argument_list;
4472 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4474 Expression base_constructor_group;
4478 ec.CurrentBlock = block;
4480 if (argument_list != null){
4481 foreach (Argument a in argument_list){
4482 if (!a.Resolve (ec, loc))
4486 ec.CurrentBlock = null;
4488 if (this is ConstructorBaseInitializer) {
4489 if (ec.ContainerType.BaseType == null)
4492 t = ec.ContainerType.BaseType;
4493 if (ec.ContainerType.IsValueType) {
4494 Report.Error (522, loc,
4495 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4499 t = ec.ContainerType;
4501 base_constructor_group = Expression.MemberLookup (
4502 ec, t, ".ctor", MemberTypes.Constructor,
4503 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4506 if (base_constructor_group == null){
4508 base_constructor_group = Expression.MemberLookup (
4509 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4510 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4514 int errors = Report.Errors;
4515 if (base_constructor_group != null)
4516 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4517 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4520 if (base_constructor == null) {
4521 if (errors == Report.Errors)
4522 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4523 argument_list.Count);
4528 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4529 base_constructor = null;
4533 if (base_constructor == caller_builder){
4534 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4541 public void Emit (EmitContext ec)
4543 if (base_constructor != null){
4544 ec.Mark (loc, false);
4546 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4548 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4553 public class ConstructorBaseInitializer : ConstructorInitializer {
4554 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4555 base (argument_list, l)
4560 public class ConstructorThisInitializer : ConstructorInitializer {
4561 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4562 base (argument_list, l)
4567 public class Constructor : MethodCore, IMethodData {
4568 public ConstructorBuilder ConstructorBuilder;
4569 public ConstructorInitializer Initializer;
4570 ListDictionary declarative_security;
4573 // Modifiers allowed for a constructor.
4575 public const int AllowedModifiers =
4577 Modifiers.PROTECTED |
4578 Modifiers.INTERNAL |
4584 bool has_compliant_args = false;
4586 // The spec claims that static is not permitted, but
4587 // my very own code has static constructors.
4589 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4590 ConstructorInitializer init, Location loc)
4591 : base (ds, null, null, mod, AllowedModifiers, false,
4592 new MemberName (name, loc), null, args)
4597 public bool HasCompliantArgs {
4599 return has_compliant_args;
4603 public override AttributeTargets AttributeTargets {
4605 return AttributeTargets.Constructor;
4611 // Returns true if this is a default constructor
4613 public bool IsDefault ()
4615 if ((ModFlags & Modifiers.STATIC) != 0)
4616 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4617 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4620 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4621 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4622 (Initializer is ConstructorBaseInitializer) &&
4623 (Initializer.Arguments == null);
4626 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4628 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4629 if (declarative_security == null) {
4630 declarative_security = new ListDictionary ();
4632 a.ExtractSecurityPermissionSet (declarative_security);
4636 ConstructorBuilder.SetCustomAttribute (cb);
4639 protected override bool CheckForDuplications ()
4641 ArrayList ar = Parent.InstanceConstructors;
4643 int arLen = ar.Count;
4645 for (int i = 0; i < arLen; i++) {
4646 Constructor m = (Constructor) ar [i];
4647 if (IsDuplicateImplementation (m))
4654 protected override bool CheckBase ()
4656 // Check whether arguments were correct.
4657 if (!DoDefineParameters ())
4660 // TODO: skip the rest for generated ctor
4661 if ((ModFlags & Modifiers.STATIC) != 0)
4664 if (!CheckForDuplications ())
4667 if (Parent.Kind == Kind.Struct) {
4668 if (ParameterTypes.Length == 0) {
4669 Report.Error (568, Location,
4670 "Structs cannot contain explicit parameterless constructors");
4674 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4675 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4680 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4681 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4688 // Creates the ConstructorBuilder
4690 public override bool Define ()
4692 if (ConstructorBuilder != null)
4695 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4696 MethodAttributes.SpecialName);
4698 if ((ModFlags & Modifiers.STATIC) != 0){
4699 ca |= MethodAttributes.Static | MethodAttributes.Private;
4701 ca |= MethodAttributes.HideBySig;
4703 if ((ModFlags & Modifiers.PUBLIC) != 0)
4704 ca |= MethodAttributes.Public;
4705 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4706 if ((ModFlags & Modifiers.INTERNAL) != 0)
4707 ca |= MethodAttributes.FamORAssem;
4709 ca |= MethodAttributes.Family;
4710 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4711 ca |= MethodAttributes.Assembly;
4712 else if (IsDefault ())
4713 ca |= MethodAttributes.Public;
4715 ca |= MethodAttributes.Private;
4718 if (!CheckAbstractAndExtern (block != null))
4721 // Check if arguments were correct.
4725 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4726 ca, CallingConventions,
4729 if ((ModFlags & Modifiers.UNSAFE) != 0)
4730 ConstructorBuilder.InitLocals = false;
4732 TypeManager.AddMethod (ConstructorBuilder, this);
4735 // HACK because System.Reflection.Emit is lame
4737 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4745 public override void Emit ()
4747 EmitContext ec = CreateEmitContext (null, null);
4749 // If this is a non-static `struct' constructor and doesn't have any
4750 // initializer, it must initialize all of the struct's fields.
4751 if ((Parent.Kind == Kind.Struct) &&
4752 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4753 Block.AddThisVariable (Parent, Location);
4755 if (block != null) {
4756 if (!block.ResolveMeta (ec, ParameterInfo))
4760 if ((ModFlags & Modifiers.STATIC) == 0){
4761 if (Parent.Kind == Kind.Class && Initializer == null)
4762 Initializer = new ConstructorBaseInitializer (null, Location);
4766 // Spec mandates that Initializers will not have
4770 if ((Initializer != null) &&
4771 !Initializer.Resolve (ConstructorBuilder, block, ec))
4773 ec.IsStatic = false;
4776 Parameters.LabelParameters (ec, ConstructorBuilder);
4778 SourceMethod source = SourceMethod.Create (
4779 Parent, ConstructorBuilder, block);
4782 // Classes can have base initializers and instance field initializers.
4784 if (Parent.Kind == Kind.Class){
4785 if ((ModFlags & Modifiers.STATIC) == 0){
4788 // If we use a "this (...)" constructor initializer, then
4789 // do not emit field initializers, they are initialized in the other constructor
4791 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4792 Parent.EmitFieldInitializers (ec);
4795 if (Initializer != null) {
4796 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4797 ec.TestObsoleteMethodUsage = false;
4799 Initializer.Emit (ec);
4802 if ((ModFlags & Modifiers.STATIC) != 0)
4803 Parent.EmitFieldInitializers (ec);
4805 if (OptAttributes != null)
4806 OptAttributes.Emit (ec, this);
4808 ec.EmitTopBlock (this, block, ParameterInfo);
4811 source.CloseMethod ();
4815 if (declarative_security != null) {
4816 foreach (DictionaryEntry de in declarative_security) {
4817 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4824 // Is never override
4825 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4830 public override string GetSignatureForError()
4832 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4835 protected override bool VerifyClsCompliance (DeclSpace ds)
4837 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4841 if (parameter_types.Length > 0) {
4842 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4844 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4846 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4847 foreach (Type param in parameter_types) {
4848 if (param.IsArray) {
4854 has_compliant_args = true;
4858 #region IMethodData Members
4860 public System.Reflection.CallingConventions CallingConventions {
4862 CallingConventions cc = Parameters.GetCallingConvention ();
4864 if (Parent.Kind == Kind.Class)
4865 if ((ModFlags & Modifiers.STATIC) == 0)
4866 cc |= CallingConventions.HasThis;
4868 // FIXME: How is `ExplicitThis' used in C#?
4874 public new Location Location {
4876 return base.Location;
4880 public MemberName MethodName {
4886 public Type ReturnType {
4892 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4894 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4895 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4898 public ObsoleteAttribute GetObsoleteAttribute ()
4900 return GetObsoleteAttribute (Parent);
4903 public bool IsExcluded(EmitContext ec)
4908 GenericMethod IMethodData.GenericMethod {
4918 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4920 public interface IMethodData
4922 CallingConventions CallingConventions { get; }
4923 Location Location { get; }
4924 MemberName MethodName { get; }
4925 Type[] ParameterTypes { get; }
4926 Type ReturnType { get; }
4927 GenericMethod GenericMethod { get; }
4929 Attributes OptAttributes { get; }
4930 ToplevelBlock Block { get; set; }
4932 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4933 ObsoleteAttribute GetObsoleteAttribute ();
4934 string GetSignatureForError ();
4935 bool IsExcluded (EmitContext ec);
4936 bool IsClsComplianceRequired (DeclSpace ds);
4937 void SetMemberIsUsed ();
4941 // Encapsulates most of the Method's state
4943 public class MethodData {
4945 readonly IMethodData method;
4948 // The return type of this method
4950 public readonly GenericMethod GenericMethod;
4951 public readonly InternalParameters ParameterInfo;
4954 // Are we implementing an interface ?
4956 public MethodInfo implementing;
4961 protected MemberBase member;
4962 protected int modifiers;
4963 protected MethodAttributes flags;
4964 protected Type declaring_type;
4965 protected MethodInfo parent_method;
4967 MethodBuilder builder = null;
4968 public MethodBuilder MethodBuilder {
4974 public Type DeclaringType {
4976 return declaring_type;
4980 public MethodData (MemberBase member, InternalParameters parameters,
4981 int modifiers, MethodAttributes flags, IMethodData method)
4983 this.member = member;
4984 this.ParameterInfo = parameters;
4985 this.modifiers = modifiers;
4988 this.method = method;
4991 public MethodData (MemberBase member, InternalParameters parameters,
4992 int modifiers, MethodAttributes flags,
4993 IMethodData method, MethodBuilder builder,
4994 GenericMethod generic, MethodInfo parent_method)
4995 : this (member, parameters, modifiers, flags, method)
4997 this.builder = builder;
4998 this.GenericMethod = generic;
4999 this.parent_method = parent_method;
5002 public bool Define (TypeContainer container)
5004 string name = method.MethodName.Basename;
5005 string method_name = method.MethodName.FullName;
5007 Type[] ParameterTypes = method.ParameterTypes;
5009 if (container.Pending != null){
5010 if (member is Indexer) // TODO: test it, but it should work without this IF
5011 implementing = container.Pending.IsInterfaceIndexer (
5012 member.InterfaceType, method.ReturnType, ParameterInfo);
5014 implementing = container.Pending.IsInterfaceMethod (
5015 member.InterfaceType, name, method.ReturnType, ParameterInfo);
5017 if (member.InterfaceType != null){
5018 if (implementing == null){
5019 if (member is PropertyBase) {
5020 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
5021 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
5022 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
5025 Report.Error (539, method.Location,
5026 "`{0}.{1}' in explicit interface declaration is not a member of interface",
5027 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
5031 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
5032 Report.SymbolRelatedToPreviousError (implementing);
5033 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
5034 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
5038 method_name = TypeManager.GetFullName (member.InterfaceType) + "." + method_name;
5040 if (implementing != null) {
5041 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
5042 if (prop_method != null) {
5043 if (!implementing.IsSpecialName) {
5044 Report.SymbolRelatedToPreviousError (implementing);
5045 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
5046 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
5049 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
5050 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
5051 Report.SymbolRelatedToPreviousError (implementing);
5052 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
5053 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
5062 // For implicit implementations, make sure we are public, for
5063 // explicit implementations, make sure we are private.
5065 if (implementing != null){
5067 // Setting null inside this block will trigger a more
5068 // verbose error reporting for missing interface implementations
5070 // The "candidate" function has been flagged already
5071 // but it wont get cleared
5073 if (member.IsExplicitImpl){
5074 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
5075 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
5076 implementing = null;
5078 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
5079 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
5081 // If this is an interface method implementation,
5082 // check for public accessibility
5084 implementing = null;
5085 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
5086 // We may never be private.
5087 implementing = null;
5088 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5090 // We may be protected if we're overriding something.
5092 implementing = null;
5097 // Static is not allowed
5099 if ((modifiers & Modifiers.STATIC) != 0){
5100 implementing = null;
5105 // If implementing is still valid, set flags
5107 if (implementing != null){
5109 // When implementing interface methods, set NewSlot
5110 // unless, we are overwriting a method.
5112 if (implementing.DeclaringType.IsInterface){
5113 if ((modifiers & Modifiers.OVERRIDE) == 0)
5114 flags |= MethodAttributes.NewSlot;
5117 MethodAttributes.Virtual |
5118 MethodAttributes.HideBySig;
5120 // Set Final unless we're virtual, abstract or already overriding a method.
5121 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5122 flags |= MethodAttributes.Final;
5125 EmitContext ec = method.CreateEmitContext (container, null);
5127 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
5129 if (builder == null)
5132 if (container.CurrentType != null)
5133 declaring_type = container.CurrentType;
5135 declaring_type = container.TypeBuilder;
5137 if ((modifiers & Modifiers.UNSAFE) != 0)
5138 builder.InitLocals = false;
5140 if (implementing != null){
5142 // clear the pending implemntation flag
5144 if (member is Indexer) {
5145 container.Pending.ImplementIndexer (
5146 member.InterfaceType, builder, method.ReturnType,
5147 ParameterInfo, member.IsExplicitImpl);
5149 container.Pending.ImplementMethod (
5150 member.InterfaceType, name, method.ReturnType,
5151 ParameterInfo, member.IsExplicitImpl);
5153 if (member.IsExplicitImpl)
5154 container.TypeBuilder.DefineMethodOverride (
5155 builder, implementing);
5158 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
5159 TypeManager.AddMethod (builder, method);
5161 if (GenericMethod != null) {
5162 bool is_override = member.IsExplicitImpl |
5163 ((modifiers & Modifiers.OVERRIDE) != 0);
5165 if (implementing != null)
5166 parent_method = implementing;
5168 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5176 /// Create the MethodBuilder for the method
5178 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
5180 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
5182 if ((modifiers & extern_static) == extern_static) {
5184 if (method.OptAttributes != null) {
5185 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
5186 if (dllimport_attribute != null) {
5187 flags |= MethodAttributes.PinvokeImpl;
5188 builder = dllimport_attribute.DefinePInvokeMethod (
5189 ec, container.TypeBuilder, method_name, flags,
5190 method.ReturnType, ParameterTypes);
5196 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
5197 // We are more strict than Microsoft and report CS0626 like error
5198 if (method.OptAttributes == null ||
5199 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
5200 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",
5201 method.GetSignatureForError ());
5206 if (builder == null)
5207 builder = container.TypeBuilder.DefineMethod (
5208 method_name, flags, method.CallingConventions,
5209 method.ReturnType, ParameterTypes);
5211 builder.SetGenericMethodSignature (
5212 flags, method.CallingConventions,
5213 method.ReturnType, ParameterTypes);
5219 public void Emit (TypeContainer container, Attributable kind)
5222 if ((flags & MethodAttributes.PinvokeImpl) == 0)
5223 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
5225 ec = method.CreateEmitContext (container, null);
5227 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
5228 ec.TestObsoleteMethodUsage = false;
5230 Attributes OptAttributes = method.OptAttributes;
5232 if (OptAttributes != null)
5233 OptAttributes.Emit (ec, kind);
5235 if (member is MethodCore)
5236 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
5238 ToplevelBlock block = method.Block;
5240 SourceMethod source = SourceMethod.Create (
5241 container, MethodBuilder, method.Block);
5244 // Handle destructors specially
5246 // FIXME: This code generates buggy code
5248 if (member is Destructor)
5249 EmitDestructor (ec, block);
5251 ec.EmitTopBlock (method, block, ParameterInfo);
5254 source.CloseMethod ();
5257 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5259 ILGenerator ig = ec.ig;
5261 Label finish = ig.DefineLabel ();
5263 block.SetDestructor ();
5265 ig.BeginExceptionBlock ();
5266 ec.ReturnLabel = finish;
5267 ec.HasReturnLabel = true;
5268 ec.EmitTopBlock (method, block, null);
5270 // ig.MarkLabel (finish);
5271 ig.BeginFinallyBlock ();
5273 if (ec.ContainerType.BaseType != null) {
5274 Expression member_lookup = Expression.MemberLookup (
5275 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5276 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5278 if (member_lookup != null){
5279 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5281 ig.Emit (OpCodes.Ldarg_0);
5282 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5286 ig.EndExceptionBlock ();
5287 //ig.MarkLabel (ec.ReturnLabel);
5288 ig.Emit (OpCodes.Ret);
5292 // TODO: Should derive from MethodCore
5293 public class Destructor : Method {
5295 public Destructor (TypeContainer ds, Expression return_type, int mod,
5296 string name, Parameters parameters, Attributes attrs,
5298 : base (ds, null, return_type, mod, false, new MemberName (name, l),
5302 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5304 if (a.Type == TypeManager.conditional_attribute_type) {
5305 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
5306 GetSignatureForError ());
5310 base.ApplyAttributeBuilder (a, cb);
5313 public override string GetSignatureForError ()
5315 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5320 abstract public class MemberBase : MemberCore {
5321 public Expression Type;
5323 public MethodAttributes flags;
5324 public readonly DeclSpace ds;
5326 protected readonly int explicit_mod_flags;
5329 // The "short" name of this property / indexer / event. This is the
5330 // name without the explicit interface.
5332 public string ShortName {
5333 get { return MemberName.Name; }
5335 SetMemberName (new MemberName (MemberName.Left, value, Location));
5340 // The type of this property / indexer / event
5342 protected Type member_type;
5343 public Type MemberType {
5345 if (member_type == null && Type != null) {
5346 EmitContext ec = ds.EmitContext;
5347 bool old_unsafe = ec.InUnsafe;
5348 ec.InUnsafe = InUnsafe;
5349 Type = Type.ResolveAsTypeTerminal (ec);
5350 ec.InUnsafe = old_unsafe;
5352 member_type = Type == null ? null : Type.Type;
5359 // Whether this is an interface member.
5361 public bool IsInterface;
5364 // If true, this is an explicit interface implementation
5366 public bool IsExplicitImpl;
5369 // The interface type we are explicitly implementing
5371 public Type InterfaceType = null;
5374 // The constructor is only exposed to our children
5376 protected MemberBase (TypeContainer parent, DeclSpace ds, Expression type, int mod,
5377 int allowed_mod, int def_mod, MemberName name,
5379 : base (parent, name, attrs)
5382 explicit_mod_flags = mod;
5384 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5385 IsExplicitImpl = (MemberName.Left != null);
5388 protected virtual bool CheckBase ()
5390 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5391 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5395 if ((RootContext.WarningLevel >= 4) &&
5396 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5397 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5398 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5399 Report.Warning (628, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5404 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5406 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5410 foreach (Type partype in parameters){
5411 if (partype == TypeManager.void_type) {
5413 1547, Location, "Keyword 'void' cannot " +
5414 "be used in this context");
5418 if (partype.IsPointer){
5421 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5425 if (ds.AsAccessible (partype, ModFlags))
5428 if (this is Indexer)
5429 Report.Error (55, Location,
5430 "Inconsistent accessibility: parameter type `" +
5431 TypeManager.CSharpName (partype) + "' is less " +
5432 "accessible than indexer `" + GetSignatureForError () + "'");
5433 else if ((this is Method) && ((Method) this).IsOperator != null)
5434 Report.Error (57, Location,
5435 "Inconsistent accessibility: parameter type `" +
5436 TypeManager.CSharpName (partype) + "' is less " +
5437 "accessible than operator `" + GetSignatureForError () + "'");
5439 Report.Error (51, Location,
5440 "Inconsistent accessibility: parameter type `" +
5441 TypeManager.CSharpName (partype) + "' is less " +
5442 "accessible than method `" + GetSignatureForError () + "'");
5449 protected virtual bool DoDefineBase ()
5451 EmitContext ec = Parent.EmitContext;
5453 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5456 throw new InternalErrorException ();
5459 ModFlags = Modifiers.PUBLIC |
5460 Modifiers.ABSTRACT |
5461 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5463 flags = MethodAttributes.Public |
5464 MethodAttributes.Abstract |
5465 MethodAttributes.HideBySig |
5466 MethodAttributes.NewSlot |
5467 MethodAttributes.Virtual;
5469 if (!Parent.MethodModifiersValid (this))
5472 flags = Modifiers.MethodAttr (ModFlags);
5475 if (IsExplicitImpl) {
5476 Expression expr = MemberName.Left.GetTypeExpression ();
5477 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5478 if (iface_texpr == null)
5481 InterfaceType = iface_texpr.Type;
5483 if (!InterfaceType.IsInterface) {
5484 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5488 if (!Parent.VerifyImplements (this))
5491 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5497 protected virtual bool DoDefine ()
5499 EmitContext ec = ds.EmitContext;
5501 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5503 ec.InUnsafe = InUnsafe;
5505 if (MemberType == null)
5508 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5509 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5510 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5511 GetSignatureForError (), Parent.GetSignatureForError ());
5515 // verify accessibility
5516 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5517 Report.SymbolRelatedToPreviousError (MemberType);
5518 if (this is Property)
5519 Report.Error (53, Location,
5520 "Inconsistent accessibility: property type `" +
5521 TypeManager.CSharpName (MemberType) + "' is less " +
5522 "accessible than property `" + GetSignatureForError () + "'");
5523 else if (this is Indexer)
5524 Report.Error (54, Location,
5525 "Inconsistent accessibility: indexer return type `" +
5526 TypeManager.CSharpName (MemberType) + "' is less " +
5527 "accessible than indexer `" + GetSignatureForError () + "'");
5528 else if (this is MethodCore) {
5529 if (this is Operator)
5530 Report.Error (56, Location,
5531 "Inconsistent accessibility: return type `" +
5532 TypeManager.CSharpName (MemberType) + "' is less " +
5533 "accessible than operator `" + GetSignatureForError () + "'");
5535 Report.Error (50, Location,
5536 "Inconsistent accessibility: return type `" +
5537 TypeManager.CSharpName (MemberType) + "' is less " +
5538 "accessible than method `" + GetSignatureForError () + "'");
5540 Report.Error (52, Location,
5541 "Inconsistent accessibility: field type `" +
5542 TypeManager.CSharpName (MemberType) + "' is less " +
5543 "accessible than field `" + GetSignatureForError () + "'");
5548 if (MemberType.IsPointer && !UnsafeOK (Parent))
5551 if (IsExplicitImpl) {
5552 Expression expr = MemberName.Left.GetTypeExpression ();
5553 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
5557 InterfaceType = texpr.ResolveType (ec);
5559 if (!InterfaceType.IsInterface) {
5560 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5564 if (!Parent.VerifyImplements (this))
5567 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5573 protected bool IsTypePermitted ()
5575 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5576 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5582 protected override bool VerifyClsCompliance(DeclSpace ds)
5584 if (base.VerifyClsCompliance (ds)) {
5588 if (IsInterface && HasClsCompliantAttribute && ds.IsClsComplianceRequired (ds)) {
5589 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5594 protected override void VerifyObsoleteAttribute()
5596 CheckUsageOfObsoleteAttribute (MemberType);
5601 // Fields and Events both generate FieldBuilders, we use this to share
5602 // their common bits. This is also used to flag usage of the field
5604 abstract public class FieldBase : MemberBase {
5605 public FieldBuilder FieldBuilder;
5606 public Status status;
5609 public enum Status : byte {
5610 HAS_OFFSET = 4 // Used by FieldMember.
5613 static string[] attribute_targets = new string [] { "field" };
5616 /// Symbol with same name in base class/struct
5618 public MemberInfo conflict_symbol;
5621 // The constructor is only exposed to our children
5623 protected FieldBase (TypeContainer parent, Expression type, int mod,
5624 int allowed_mod, MemberName name, object init,
5626 : base (parent, parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5632 public override AttributeTargets AttributeTargets {
5634 return AttributeTargets.Field;
5638 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5640 if (a.Type == TypeManager.marshal_as_attr_type) {
5641 UnmanagedMarshal marshal = a.GetMarshal (this);
5642 if (marshal != null) {
5643 FieldBuilder.SetMarshal (marshal);
5648 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5649 a.Error_InvalidSecurityParent ();
5653 FieldBuilder.SetCustomAttribute (cb);
5657 // Whether this field has an initializer.
5659 public bool HasInitializer {
5661 return init != null;
5665 protected readonly Object init;
5667 Expression init_expr;
5668 bool init_expr_initialized = false;
5670 protected override bool CheckGenericOverride (MethodInfo method, string name)
5676 // Resolves and returns the field initializer.
5678 public Expression GetInitializerExpression (EmitContext ec)
5680 if (init_expr_initialized)
5684 if (init is Expression)
5685 e = (Expression) init;
5687 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5689 // TODO: Any reason why we are using parent EC ?
5690 EmitContext parent_ec = Parent.EmitContext;
5692 bool old_is_static = parent_ec.IsStatic;
5693 bool old_is_ctor = parent_ec.IsConstructor;
5694 parent_ec.IsStatic = ec.IsStatic;
5695 parent_ec.IsConstructor = ec.IsConstructor;
5696 parent_ec.IsFieldInitializer = true;
5697 e = e.DoResolve (parent_ec);
5698 parent_ec.IsFieldInitializer = false;
5699 parent_ec.IsStatic = old_is_static;
5700 parent_ec.IsConstructor = old_is_ctor;
5703 init_expr_initialized = true;
5708 protected override bool CheckBase ()
5710 if (!base.CheckBase ())
5717 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5718 if (conflict_symbol == null) {
5719 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5720 Report.Warning (109, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5725 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5726 Report.SymbolRelatedToPreviousError (conflict_symbol);
5727 Report.Warning (108, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5728 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5734 protected virtual bool IsFieldClsCompliant {
5736 if (FieldBuilder == null)
5739 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5743 public override string[] ValidAttributeTargets {
5745 return attribute_targets;
5749 protected override bool VerifyClsCompliance (DeclSpace ds)
5751 if (!base.VerifyClsCompliance (ds))
5754 if (!IsFieldClsCompliant) {
5755 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5761 public void SetAssigned ()
5763 caching_flags |= Flags.IsAssigned;
5767 public abstract class FieldMember: FieldBase
5769 protected FieldMember (TypeContainer parent, Expression type, int mod,
5770 int allowed_mod, MemberName name, object init, Attributes attrs)
5771 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs)
5773 if ((mod & Modifiers.ABSTRACT) != 0)
5774 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5777 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5779 if (a.Type == TypeManager.field_offset_attribute_type)
5781 status |= Status.HAS_OFFSET;
5783 if (!Parent.HasExplicitLayout) {
5784 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5788 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5789 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5794 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5795 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5799 base.ApplyAttributeBuilder (a, cb);
5803 public override bool Define()
5805 EmitContext ec = Parent.EmitContext;
5807 throw new InternalErrorException ("FieldMember.Define called too early");
5809 if (MemberType == null)
5812 if (MemberType == TypeManager.void_type) {
5813 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5820 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5821 Report.Error (52, Location,
5822 "Inconsistent accessibility: field type `" +
5823 TypeManager.CSharpName (MemberType) + "' is less " +
5824 "accessible than field `" + GetSignatureForError () + "'");
5828 if (!IsTypePermitted ())
5831 if (MemberType.IsPointer && !UnsafeOK (Parent))
5837 public override void Emit ()
5839 if (OptAttributes != null) {
5840 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5841 OptAttributes.Emit (ec, this);
5844 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5845 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5852 // Represents header string for documentation comment.
5854 public override string DocCommentHeader {
5855 get { return "F:"; }
5859 interface IFixedBuffer
5861 FieldInfo Element { get; }
5862 Type ElementType { get; }
5865 public class FixedFieldExternal: IFixedBuffer
5867 FieldInfo element_field;
5869 public FixedFieldExternal (FieldInfo fi)
5871 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5874 #region IFixedField Members
5876 public FieldInfo Element {
5878 return element_field;
5882 public Type ElementType {
5884 return element_field.FieldType;
5892 /// Fixed buffer implementation
5894 public class FixedField: FieldMember, IFixedBuffer
5896 public const string FixedElementName = "FixedElementField";
5897 static int GlobalCounter = 0;
5898 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5899 static FieldInfo[] fi;
5901 TypeBuilder fixed_buffer_type;
5902 FieldBuilder element;
5903 Expression size_expr;
5906 const int AllowedModifiers =
5909 Modifiers.PROTECTED |
5910 Modifiers.INTERNAL |
5913 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5914 Expression size_expr, Attributes attrs, Location loc):
5915 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), null, attrs)
5917 if (RootContext.Version == LanguageVersion.ISO_1)
5918 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5920 this.size_expr = size_expr;
5923 public override bool Define()
5925 if (Parent.Kind != Kind.Struct) {
5926 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5927 GetSignatureForError ());
5931 if (!base.Define ())
5934 if (!TypeManager.IsPrimitiveType (MemberType)) {
5935 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",
5936 GetSignatureForError ());
5940 Constant c = size_expr.ResolveAsConstant (Parent.EmitContext, this);
5944 IntConstant buffer_size_const = c.ToInt (Location);
5945 if (buffer_size_const == null)
5948 buffer_size = buffer_size_const.Value;
5950 if (buffer_size <= 0) {
5951 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5955 int type_size = Expression.GetTypeSize (MemberType);
5957 if (buffer_size > int.MaxValue / type_size) {
5958 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5959 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5963 buffer_size *= type_size;
5966 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5968 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5969 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5970 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5971 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5973 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5974 TypeManager.RegisterFieldBase (FieldBuilder, this);
5979 public override void Emit()
5982 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5984 object[] fi_val = new object[1];
5985 fi_val [0] = buffer_size;
5987 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5988 ctor_args, fi, fi_val);
5989 fixed_buffer_type.SetCustomAttribute (cab);
5991 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5992 FieldBuilder.SetCustomAttribute (cab);
5996 protected override bool IsFieldClsCompliant {
6002 #region IFixedField Members
6004 public FieldInfo Element {
6010 public Type ElementType {
6020 // The Field class is used to represents class/struct fields during parsing.
6022 public class Field : FieldMember {
6024 // Modifiers allowed in a class declaration
6026 const int AllowedModifiers =
6029 Modifiers.PROTECTED |
6030 Modifiers.INTERNAL |
6033 Modifiers.VOLATILE |
6037 public Field (TypeContainer parent, Expression type, int mod, string name,
6038 Object expr_or_array_init, Attributes attrs, Location loc)
6039 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
6040 expr_or_array_init, attrs)
6044 public override bool Define ()
6046 if (!base.Define ())
6049 if (RootContext.WarningLevel > 1){
6050 Type ptype = Parent.TypeBuilder.BaseType;
6052 // ptype is only null for System.Object while compiling corlib.
6054 TypeContainer.FindMembers (
6055 ptype, MemberTypes.Method,
6056 BindingFlags.Public |
6057 BindingFlags.Static | BindingFlags.Instance,
6058 System.Type.FilterName, Name);
6062 if ((ModFlags & Modifiers.VOLATILE) != 0){
6063 if (!MemberType.IsClass){
6064 Type vt = MemberType;
6066 if (TypeManager.IsEnumType (vt))
6067 vt = TypeManager.EnumToUnderlying (MemberType);
6069 if (!((vt == TypeManager.bool_type) ||
6070 (vt == TypeManager.sbyte_type) ||
6071 (vt == TypeManager.byte_type) ||
6072 (vt == TypeManager.short_type) ||
6073 (vt == TypeManager.ushort_type) ||
6074 (vt == TypeManager.int32_type) ||
6075 (vt == TypeManager.uint32_type) ||
6076 (vt == TypeManager.char_type) ||
6077 (vt == TypeManager.float_type) ||
6078 (!vt.IsValueType))){
6079 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
6080 GetSignatureForError (), TypeManager.CSharpName (vt));
6085 if ((ModFlags & Modifiers.READONLY) != 0){
6086 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
6087 GetSignatureForError ());
6092 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
6094 if (Parent.Kind == Kind.Struct &&
6095 ((fa & FieldAttributes.Static) == 0) &&
6096 MemberType == Parent.TypeBuilder &&
6097 !TypeManager.IsBuiltinType (MemberType)){
6098 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
6099 "' causes a cycle in the structure layout");
6104 FieldBuilder = Parent.TypeBuilder.DefineField (
6105 Name, MemberType, Modifiers.FieldAttr (ModFlags));
6107 TypeManager.RegisterFieldBase (FieldBuilder, this);
6109 catch (ArgumentException) {
6110 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
6117 protected override bool VerifyClsCompliance (DeclSpace ds)
6119 if (!base.VerifyClsCompliance (ds))
6122 if ((ModFlags & Modifiers.VOLATILE) != 0) {
6123 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
6131 // `set' and `get' accessors are represented with an Accessor.
6133 public class Accessor : IIteratorContainer {
6135 // Null if the accessor is empty, or a Block if not
6137 public const int AllowedModifiers =
6139 Modifiers.PROTECTED |
6140 Modifiers.INTERNAL |
6143 public ToplevelBlock Block;
6144 public Attributes Attributes;
6145 public Location Location;
6146 public int ModFlags;
6149 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
6154 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
6157 public void SetYields ()
6163 // Ooouh Martin, templates are missing here.
6164 // When it will be possible move here a lot of child code and template method type.
6165 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
6166 protected MethodData method_data;
6167 protected ToplevelBlock block;
6168 protected ListDictionary declarative_security;
6170 // The accessor are created event if they are not wanted.
6171 // But we need them because their names are reserved.
6172 // Field says whether accessor will be emited or not
6173 public readonly bool IsDummy;
6175 protected readonly string prefix;
6177 ReturnParameter return_attributes;
6179 public AbstractPropertyEventMethod (MemberBase member, string prefix)
6180 : base (member.Parent, SetupName (prefix, member, member.Location), null)
6182 this.prefix = prefix;
6186 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
6188 : base (member.Parent, SetupName (prefix, member, accessor.Location),
6189 accessor.Attributes)
6191 this.prefix = prefix;
6192 this.block = accessor.Block;
6195 static MemberName SetupName (string prefix, MemberBase member, Location loc)
6197 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6200 public void UpdateName (MemberBase member)
6202 SetMemberName (SetupName (prefix, member, Location));
6205 #region IMethodData Members
6207 public ToplevelBlock Block {
6217 public CallingConventions CallingConventions {
6219 return CallingConventions.Standard;
6223 public bool IsExcluded (EmitContext ec)
6228 GenericMethod IMethodData.GenericMethod {
6234 public MemberName MethodName {
6240 public abstract ObsoleteAttribute GetObsoleteAttribute ();
6241 public abstract Type[] ParameterTypes { get; }
6242 public abstract Type ReturnType { get; }
6243 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
6247 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6249 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6250 a.Type == TypeManager.conditional_attribute_type) {
6251 Report.Error (1667, a.Location,
6252 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6253 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6257 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
6258 if (declarative_security == null)
6259 declarative_security = new ListDictionary ();
6260 a.ExtractSecurityPermissionSet (declarative_security);
6264 if (a.Target == AttributeTargets.Method) {
6265 method_data.MethodBuilder.SetCustomAttribute (cb);
6269 if (a.Target == AttributeTargets.ReturnValue) {
6270 if (return_attributes == null)
6271 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6273 return_attributes.ApplyAttributeBuilder (a, cb);
6277 ApplyToExtraTarget (a, cb);
6280 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6282 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
6285 public override bool Define()
6287 throw new NotSupportedException ();
6290 public virtual void Emit (TypeContainer container)
6292 EmitMethod (container);
6294 if (declarative_security != null) {
6295 foreach (DictionaryEntry de in declarative_security) {
6296 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6303 protected virtual void EmitMethod (TypeContainer container)
6305 method_data.Emit (container, this);
6308 public override bool IsClsComplianceRequired(DeclSpace ds)
6313 public bool IsDuplicateImplementation (MethodCore method)
6315 if (!MemberName.Equals (method.MemberName))
6318 Type[] param_types = method.ParameterTypes;
6320 if (param_types.Length != ParameterTypes.Length)
6323 for (int i = 0; i < param_types.Length; i++)
6324 if (param_types [i] != ParameterTypes [i])
6327 Report.SymbolRelatedToPreviousError (method);
6328 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
6332 public override bool IsUsed
6342 public new Location Location {
6344 return base.Location;
6349 // Represents header string for documentation comment.
6351 public override string DocCommentHeader {
6352 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6355 protected override void VerifyObsoleteAttribute()
6362 // Properties and Indexers both generate PropertyBuilders, we use this to share
6363 // their common bits.
6365 abstract public class PropertyBase : MethodCore {
6367 public class GetMethod: PropertyMethod
6369 static string[] attribute_targets = new string [] { "method", "return" };
6371 public GetMethod (MethodCore method):
6372 base (method, "get_")
6376 public GetMethod (MethodCore method, Accessor accessor):
6377 base (method, accessor, "get_")
6381 public override MethodBuilder Define(TypeContainer container)
6383 base.Define (container);
6385 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
6387 if (!method_data.Define (container))
6390 return method_data.MethodBuilder;
6393 public override Type ReturnType {
6395 return method.MemberType;
6399 public override string[] ValidAttributeTargets {
6401 return attribute_targets;
6406 public class SetMethod: PropertyMethod {
6408 static string[] attribute_targets = new string [] { "method", "param", "return" };
6409 ImplicitParameter param_attr;
6411 public SetMethod (MethodCore method):
6412 base (method, "set_")
6416 public SetMethod (MethodCore method, Accessor accessor):
6417 base (method, accessor, "set_")
6421 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6423 if (a.Target == AttributeTargets.Parameter) {
6424 if (param_attr == null)
6425 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6427 param_attr.ApplyAttributeBuilder (a, cb);
6431 base.ApplyAttributeBuilder (a, cb);
6434 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
6436 Parameter [] parms = new Parameter [1];
6437 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
6438 Parameters parameters = new Parameters (parms, null);
6440 bool old_unsafe = ec.InUnsafe;
6441 ec.InUnsafe = InUnsafe;
6442 Type [] types = parameters.GetParameterInfo (ec);
6443 ec.InUnsafe = old_unsafe;
6445 return new InternalParameters (types, parameters);
6448 public override MethodBuilder Define (TypeContainer container)
6450 if (container.EmitContext == null)
6451 throw new InternalErrorException ("SetMethod.Define called too early");
6453 base.Define (container);
6455 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6457 if (!method_data.Define (container))
6460 return method_data.MethodBuilder;
6463 public override Type[] ParameterTypes {
6465 return new Type[] { method.MemberType };
6469 public override Type ReturnType {
6471 return TypeManager.void_type;
6475 public override string[] ValidAttributeTargets {
6477 return attribute_targets;
6482 static string[] attribute_targets = new string [] { "property" };
6484 public abstract class PropertyMethod: AbstractPropertyEventMethod {
6485 protected readonly MethodCore method;
6486 protected MethodAttributes flags;
6489 public PropertyMethod (MethodCore method, string prefix)
6490 : base (method, prefix)
6492 this.method = method;
6495 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6496 : base (method, accessor, prefix)
6498 this.method = method;
6499 this.ModFlags = accessor.ModFlags;
6500 yields = accessor.Yields;
6502 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6503 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6507 public override AttributeTargets AttributeTargets {
6509 return AttributeTargets.Method;
6513 public override bool IsClsComplianceRequired(DeclSpace ds)
6515 return method.IsClsComplianceRequired (ds);
6518 public InternalParameters ParameterInfo
6521 return method_data.ParameterInfo;
6525 public virtual MethodBuilder Define (TypeContainer container)
6527 if (!method.CheckAbstractAndExtern (block != null))
6531 // Check for custom access modifier
6533 if (ModFlags == 0) {
6534 ModFlags = method.ModFlags;
6535 flags = method.flags;
6537 if (container.Kind == Kind.Interface)
6538 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6539 GetSignatureForError ());
6541 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6542 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6545 CheckModifiers (container, ModFlags);
6546 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6547 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6548 flags = Modifiers.MethodAttr (ModFlags);
6549 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6553 // Setup iterator if we are one
6556 Iterator iterator = new Iterator (
6557 this, Parent, null, method.ParameterInfo, ModFlags);
6559 if (!iterator.DefineIterator ())
6566 public bool HasCustomAccessModifier
6569 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6573 public override Type[] ParameterTypes {
6575 return TypeManager.NoTypes;
6579 public override EmitContext CreateEmitContext (TypeContainer tc,
6582 return new EmitContext (
6583 tc, method.ds, method.Location, ig, ReturnType,
6584 method.ModFlags, false);
6587 public override ObsoleteAttribute GetObsoleteAttribute ()
6589 return method.GetObsoleteAttribute (method.ds);
6592 public override string GetSignatureForError()
6594 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6597 void CheckModifiers (TypeContainer container, int modflags)
6600 int mflags = method.ModFlags & Modifiers.Accessibility;
6602 if ((mflags & Modifiers.PUBLIC) != 0) {
6603 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6605 else if ((mflags & Modifiers.PROTECTED) != 0) {
6606 if ((mflags & Modifiers.INTERNAL) != 0)
6607 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6609 flags |= Modifiers.PRIVATE;
6611 else if ((mflags & Modifiers.INTERNAL) != 0)
6612 flags |= Modifiers.PRIVATE;
6614 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6615 Report.Error (273, Location,
6616 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6617 GetSignatureForError (), method.GetSignatureForError ());
6621 public override bool MarkForDuplicationCheck ()
6623 caching_flags |= Flags.TestMethodDuplication;
6628 public PropertyMethod Get, Set;
6629 public PropertyBuilder PropertyBuilder;
6630 public MethodBuilder GetBuilder, SetBuilder;
6632 protected EmitContext ec;
6634 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6635 int allowed_mod, bool is_iface, MemberName name,
6636 Parameters parameters, Attributes attrs)
6637 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6642 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6644 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6645 a.Error_InvalidSecurityParent ();
6649 PropertyBuilder.SetCustomAttribute (cb);
6652 public override AttributeTargets AttributeTargets {
6654 return AttributeTargets.Property;
6658 public override bool Define ()
6663 if (!IsTypePermitted ())
6669 protected override bool DoDefine ()
6671 if (!base.DoDefine ())
6675 // Accessors modifiers check
6677 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6678 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6679 GetSignatureForError ());
6683 if ((Get.IsDummy || Set.IsDummy)
6684 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6685 Report.Error (276, Location,
6686 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6687 GetSignatureForError ());
6691 if (MemberType.IsAbstract && MemberType.IsSealed) {
6692 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6696 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6700 protected override bool CheckForDuplications ()
6702 ArrayList ar = Parent.Indexers;
6704 int arLen = ar.Count;
6706 for (int i = 0; i < arLen; i++) {
6707 Indexer m = (Indexer) ar [i];
6708 if (IsDuplicateImplementation (m))
6713 ar = Parent.Properties;
6715 int arLen = ar.Count;
6717 for (int i = 0; i < arLen; i++) {
6718 Property m = (Property) ar [i];
6719 if (IsDuplicateImplementation (m))
6727 // TODO: rename to Resolve......
6728 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6730 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6731 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6733 if (base_property == null)
6736 base_ret_type = base_property.PropertyType;
6737 MethodInfo get_accessor = base_property.GetGetMethod (true);
6738 MethodInfo set_accessor = base_property.GetSetMethod (true);
6739 MethodAttributes get_accessor_access, set_accessor_access;
6741 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6742 if (Get != null && !Get.IsDummy && get_accessor == null) {
6743 Report.SymbolRelatedToPreviousError (base_property);
6744 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6747 if (Set != null && !Set.IsDummy && set_accessor == null) {
6748 Report.SymbolRelatedToPreviousError (base_property);
6749 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6754 // Check base class accessors access
6757 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6758 get_accessor_access = set_accessor_access = 0;
6759 if ((ModFlags & Modifiers.NEW) == 0) {
6760 if (get_accessor != null) {
6761 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6762 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6764 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6765 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6768 if (set_accessor != null) {
6769 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6770 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6772 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6773 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6778 // Get the less restrictive access
6780 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6783 public override void Emit ()
6786 // The PropertyBuilder can be null for explicit implementations, in that
6787 // case, we do not actually emit the ".property", so there is nowhere to
6788 // put the attribute
6790 if (PropertyBuilder != null && OptAttributes != null)
6791 OptAttributes.Emit (ec, this);
6803 /// Tests whether accessors are not in collision with some method (CS0111)
6805 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6807 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6810 public override bool IsUsed
6816 return Get.IsUsed | Set.IsUsed;
6820 protected override void SetMemberName (MemberName new_name)
6822 base.SetMemberName (new_name);
6824 Get.UpdateName (this);
6825 Set.UpdateName (this);
6828 public override string[] ValidAttributeTargets {
6830 return attribute_targets;
6835 // Represents header string for documentation comment.
6837 public override string DocCommentHeader {
6838 get { return "P:"; }
6842 public class Property : PropertyBase {
6843 const int AllowedModifiers =
6846 Modifiers.PROTECTED |
6847 Modifiers.INTERNAL |
6851 Modifiers.OVERRIDE |
6852 Modifiers.ABSTRACT |
6855 Modifiers.METHOD_YIELDS |
6858 const int AllowedInterfaceModifiers =
6861 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6862 MemberName name, Attributes attrs, Accessor get_block,
6864 : base (ds, type, mod,
6865 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6866 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6868 if (get_block == null)
6869 Get = new GetMethod (this);
6871 Get = new GetMethod (this, get_block);
6873 if (set_block == null)
6874 Set = new SetMethod (this);
6876 Set = new SetMethod (this, set_block);
6879 public override bool Define ()
6881 if (!DoDefineBase ())
6884 if (!base.Define ())
6890 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6893 GetBuilder = Get.Define (Parent);
6894 if (GetBuilder == null)
6899 SetBuilder = Set.Define (Parent);
6900 if (SetBuilder == null)
6903 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6906 // FIXME - PropertyAttributes.HasDefault ?
6908 PropertyAttributes prop_attr = PropertyAttributes.None;
6910 prop_attr |= PropertyAttributes.RTSpecialName |
6911 PropertyAttributes.SpecialName;
6913 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6914 Name, prop_attr, MemberType, null);
6917 PropertyBuilder.SetGetMethod (GetBuilder);
6920 PropertyBuilder.SetSetMethod (SetBuilder);
6927 /// Gigantic workaround for lameness in SRE follows :
6928 /// This class derives from EventInfo and attempts to basically
6929 /// wrap around the EventBuilder so that FindMembers can quickly
6930 /// return this in it search for members
6932 public class MyEventBuilder : EventInfo {
6935 // We use this to "point" to our Builder which is
6936 // not really a MemberInfo
6938 EventBuilder MyBuilder;
6941 // We "catch" and wrap these methods
6943 MethodInfo raise, remove, add;
6945 EventAttributes attributes;
6946 Type declaring_type, reflected_type, event_type;
6951 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6953 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6955 // And now store the values in our own fields.
6957 declaring_type = type_builder;
6959 reflected_type = type_builder;
6961 attributes = event_attr;
6964 this.event_type = event_type;
6968 // Methods that you have to override. Note that you only need
6969 // to "implement" the variants that take the argument (those are
6970 // the "abstract" methods, the others (GetAddMethod()) are
6973 public override MethodInfo GetAddMethod (bool nonPublic)
6978 public override MethodInfo GetRemoveMethod (bool nonPublic)
6983 public override MethodInfo GetRaiseMethod (bool nonPublic)
6989 // These methods make "MyEventInfo" look like a Builder
6991 public void SetRaiseMethod (MethodBuilder raiseMethod)
6993 raise = raiseMethod;
6994 MyBuilder.SetRaiseMethod (raiseMethod);
6997 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6999 remove = removeMethod;
7000 MyBuilder.SetRemoveOnMethod (removeMethod);
7003 public void SetAddOnMethod (MethodBuilder addMethod)
7006 MyBuilder.SetAddOnMethod (addMethod);
7009 public void SetCustomAttribute (CustomAttributeBuilder cb)
7011 MyBuilder.SetCustomAttribute (cb);
7014 public override object [] GetCustomAttributes (bool inherit)
7016 // FIXME : There's nothing which can be seemingly done here because
7017 // we have no way of getting at the custom attribute objects of the
7022 public override object [] GetCustomAttributes (Type t, bool inherit)
7024 // FIXME : Same here !
7028 public override bool IsDefined (Type t, bool b)
7033 public override EventAttributes Attributes {
7039 public override string Name {
7045 public override Type DeclaringType {
7047 return declaring_type;
7051 public override Type ReflectedType {
7053 return reflected_type;
7057 public Type EventType {
7063 public void SetUsed ()
7065 if (my_event != null) {
7066 my_event.SetAssigned ();
7067 my_event.SetMemberIsUsed ();
7073 /// For case when event is declared like property (with add and remove accessors).
7075 public class EventProperty: Event {
7077 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
7079 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
7080 bool is_iface, MemberName name, Object init,
7081 Attributes attrs, Accessor add, Accessor remove)
7082 : base (parent, type, mod_flags, is_iface, name, init, attrs)
7084 Add = new AddDelegateMethod (this, add);
7085 Remove = new RemoveDelegateMethod (this, remove);
7087 // For this event syntax we don't report error CS0067
7088 // because it is hard to do it.
7092 public override string[] ValidAttributeTargets {
7094 return attribute_targets;
7100 /// Event is declared like field.
7102 public class EventField: Event {
7104 static string[] attribute_targets = new string [] { "event", "field", "method" };
7105 static string[] attribute_targets_interface = new string[] { "event", "method" };
7107 public EventField (TypeContainer parent, Expression type, int mod_flags,
7108 bool is_iface, MemberName name, Object init,
7110 : base (parent, type, mod_flags, is_iface, name, init, attrs)
7112 Add = new AddDelegateMethod (this);
7113 Remove = new RemoveDelegateMethod (this);
7116 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7118 if (a.Target == AttributeTargets.Field) {
7119 FieldBuilder.SetCustomAttribute (cb);
7123 if (a.Target == AttributeTargets.Method) {
7124 Add.ApplyAttributeBuilder (a, cb);
7125 Remove.ApplyAttributeBuilder (a, cb);
7129 base.ApplyAttributeBuilder (a, cb);
7132 public override string[] ValidAttributeTargets {
7134 return IsInterface ? attribute_targets_interface : attribute_targets;
7139 public abstract class Event : FieldBase {
7141 protected sealed class AddDelegateMethod: DelegateMethod
7144 public AddDelegateMethod (Event method):
7145 base (method, "add_")
7149 public AddDelegateMethod (Event method, Accessor accessor):
7150 base (method, accessor, "add_")
7154 protected override MethodInfo DelegateMethodInfo {
7156 return TypeManager.delegate_combine_delegate_delegate;
7162 protected sealed class RemoveDelegateMethod: DelegateMethod
7164 public RemoveDelegateMethod (Event method):
7165 base (method, "remove_")
7169 public RemoveDelegateMethod (Event method, Accessor accessor):
7170 base (method, accessor, "remove_")
7174 protected override MethodInfo DelegateMethodInfo {
7176 return TypeManager.delegate_remove_delegate_delegate;
7182 public abstract class DelegateMethod: AbstractPropertyEventMethod
7184 protected readonly Event method;
7185 ImplicitParameter param_attr;
7187 static string[] attribute_targets = new string [] { "method", "param", "return" };
7189 public DelegateMethod (Event method, string prefix)
7190 : base (method, prefix)
7192 this.method = method;
7195 public DelegateMethod (Event method, Accessor accessor, string prefix)
7196 : base (method, accessor, prefix)
7198 this.method = method;
7201 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7203 if (a.Target == AttributeTargets.Parameter) {
7204 if (param_attr == null)
7205 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
7207 param_attr.ApplyAttributeBuilder (a, cb);
7211 base.ApplyAttributeBuilder (a, cb);
7214 public override AttributeTargets AttributeTargets {
7216 return AttributeTargets.Method;
7220 public override bool IsClsComplianceRequired(DeclSpace ds)
7222 return method.IsClsComplianceRequired (ds);
7225 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
7227 method_data = new MethodData (method, ip, method.ModFlags,
7228 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7230 if (!method_data.Define (container))
7233 MethodBuilder mb = method_data.MethodBuilder;
7234 mb.DefineParameter (1, ParameterAttributes.None, "value");
7239 protected override void EmitMethod (TypeContainer tc)
7241 if (block != null) {
7242 base.EmitMethod (tc);
7246 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7249 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
7250 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
7252 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
7253 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7254 ig.Emit (OpCodes.Ldsfld, field_info);
7255 ig.Emit (OpCodes.Ldarg_0);
7256 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7257 ig.Emit (OpCodes.Castclass, method.MemberType);
7258 ig.Emit (OpCodes.Stsfld, field_info);
7260 ig.Emit (OpCodes.Ldarg_0);
7261 ig.Emit (OpCodes.Ldarg_0);
7262 ig.Emit (OpCodes.Ldfld, field_info);
7263 ig.Emit (OpCodes.Ldarg_1);
7264 ig.Emit (OpCodes.Call, DelegateMethodInfo);
7265 ig.Emit (OpCodes.Castclass, method.MemberType);
7266 ig.Emit (OpCodes.Stfld, field_info);
7268 ig.Emit (OpCodes.Ret);
7271 protected abstract MethodInfo DelegateMethodInfo { get; }
7273 public override Type[] ParameterTypes {
7275 return new Type[] { method.MemberType };
7279 public override Type ReturnType {
7281 return TypeManager.void_type;
7285 public override EmitContext CreateEmitContext (TypeContainer tc,
7288 return new EmitContext (
7289 tc, method.Parent, Location, ig, ReturnType,
7290 method.ModFlags, false);
7293 public override ObsoleteAttribute GetObsoleteAttribute ()
7295 return method.GetObsoleteAttribute (method.Parent);
7298 public override string[] ValidAttributeTargets {
7300 return attribute_targets;
7306 const int AllowedModifiers =
7309 Modifiers.PROTECTED |
7310 Modifiers.INTERNAL |
7315 Modifiers.OVERRIDE |
7319 const int AllowedInterfaceModifiers =
7322 public DelegateMethod Add, Remove;
7323 public MyEventBuilder EventBuilder;
7324 public MethodBuilder AddBuilder, RemoveBuilder;
7326 public Event (TypeContainer parent, Expression type, int mod_flags,
7327 bool is_iface, MemberName name, Object init, Attributes attrs)
7328 : base (parent, type, mod_flags,
7329 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7332 IsInterface = is_iface;
7335 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7337 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
7338 a.Error_InvalidSecurityParent ();
7342 EventBuilder.SetCustomAttribute (cb);
7345 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7347 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7350 public override AttributeTargets AttributeTargets {
7352 return AttributeTargets.Event;
7356 public override bool Define ()
7358 EventAttributes e_attr;
7359 e_attr = EventAttributes.None;
7361 if (!DoDefineBase ())
7367 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
7368 Report.Error (74, Location, "`" + GetSignatureForError () +
7369 "': abstract event cannot have an initializer");
7373 if (!TypeManager.IsDelegateType (MemberType)) {
7374 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7378 EmitContext ec = Parent.EmitContext;
7380 throw new InternalErrorException ("Event.Define called too early?");
7381 bool old_unsafe = ec.InUnsafe;
7382 ec.InUnsafe = InUnsafe;
7384 Parameter [] parms = new Parameter [1];
7385 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
7386 Parameters parameters = new Parameters (parms, null);
7387 Type [] types = parameters.GetParameterInfo (ec);
7388 InternalParameters ip = new InternalParameters (types, parameters);
7390 ec.InUnsafe = old_unsafe;
7396 // Now define the accessors
7399 AddBuilder = Add.Define (Parent, ip);
7400 if (AddBuilder == null)
7403 RemoveBuilder = Remove.Define (Parent, ip);
7404 if (RemoveBuilder == null)
7407 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7409 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7410 FieldBuilder = Parent.TypeBuilder.DefineField (
7412 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7413 TypeManager.RegisterPrivateFieldOfEvent (
7414 (EventInfo) EventBuilder, FieldBuilder);
7415 TypeManager.RegisterFieldBase (FieldBuilder, this);
7418 EventBuilder.SetAddOnMethod (AddBuilder);
7419 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7421 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7425 protected override bool CheckBase ()
7427 if (!base.CheckBase ())
7430 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7431 if (!(conflict_symbol is EventInfo)) {
7432 Report.SymbolRelatedToPreviousError (conflict_symbol);
7433 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
7441 public override void Emit ()
7443 if (OptAttributes != null) {
7444 EmitContext ec = new EmitContext (
7445 Parent, Location, null, MemberType, ModFlags);
7446 OptAttributes.Emit (ec, this);
7450 Remove.Emit (Parent);
7455 public override string GetSignatureForError ()
7457 return base.GetSignatureForError ();
7461 // Represents header string for documentation comment.
7463 public override string DocCommentHeader {
7464 get { return "E:"; }
7469 public class Indexer : PropertyBase, IIteratorContainer {
7471 class GetIndexerMethod: GetMethod
7473 public GetIndexerMethod (MethodCore method):
7478 public GetIndexerMethod (MethodCore method, Accessor accessor):
7479 base (method, accessor)
7483 public override Type[] ParameterTypes {
7485 return method.ParameterTypes;
7490 class SetIndexerMethod: SetMethod
7492 readonly Parameters parameters;
7494 public SetIndexerMethod (MethodCore method):
7499 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7500 base (method, accessor)
7502 this.parameters = parameters;
7505 public override Type[] ParameterTypes {
7507 int top = method.ParameterTypes.Length;
7508 Type [] set_pars = new Type [top + 1];
7509 method.ParameterTypes.CopyTo (set_pars, 0);
7510 set_pars [top] = method.MemberType;
7515 protected override InternalParameters GetParameterInfo (EmitContext ec)
7517 Parameter [] fixed_parms = parameters.FixedParameters;
7519 if (fixed_parms == null){
7520 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7521 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7522 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7524 // Here is the problem: the `value' parameter has
7525 // to come *after* the array parameter in the declaration
7527 // X (object [] x, Type value)
7530 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7531 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7535 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7537 fixed_parms.CopyTo (tmp, 0);
7538 tmp [fixed_parms.Length] = new Parameter (
7539 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7541 Parameters set_formal_params = new Parameters (tmp, null);
7542 Type [] types = set_formal_params.GetParameterInfo (ec);
7544 return new InternalParameters (types, set_formal_params);
7548 const int AllowedModifiers =
7551 Modifiers.PROTECTED |
7552 Modifiers.INTERNAL |
7556 Modifiers.OVERRIDE |
7561 const int AllowedInterfaceModifiers =
7565 // Are we implementing an interface ?
7567 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7568 bool is_iface, Parameters parameters, Attributes attrs,
7569 Accessor get_block, Accessor set_block)
7570 : base (parent, type, mod,
7571 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7572 is_iface, name, parameters, attrs)
7574 if (get_block == null)
7575 Get = new GetIndexerMethod (this);
7577 Get = new GetIndexerMethod (this, get_block);
7579 if (set_block == null)
7580 Set = new SetIndexerMethod (this);
7582 Set = new SetIndexerMethod (this, parameters, set_block);
7585 public override bool Define ()
7587 PropertyAttributes prop_attr =
7588 PropertyAttributes.RTSpecialName |
7589 PropertyAttributes.SpecialName;
7591 if (!DoDefineBase ())
7594 if (!base.Define ())
7597 if (MemberType == TypeManager.void_type) {
7598 Report.Error (620, Location, "Indexers cannot have void type");
7602 if (OptAttributes != null) {
7603 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7604 if (indexer_attr != null) {
7605 // Remove the attribute from the list because it is not emitted
7606 OptAttributes.Attrs.Remove (indexer_attr);
7608 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7610 if (IsExplicitImpl) {
7611 Report.Error (415, indexer_attr.Location,
7612 "The `IndexerName' attribute is valid only on an " +
7613 "indexer that is not an explicit interface member declaration");
7617 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7618 Report.Error (609, indexer_attr.Location,
7619 "Cannot set the `IndexerName' attribute on an indexer marked override");
7623 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7624 Report.Error (633, indexer_attr.Location,
7625 "The argument to the `IndexerName' attribute must be a valid identifier");
7631 if (InterfaceType != null) {
7632 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7633 if (base_IndexerName != Name)
7634 ShortName = base_IndexerName;
7637 if (!Parent.AddToMemberContainer (this) ||
7638 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7644 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7646 GetBuilder = Get.Define (Parent);
7647 if (GetBuilder == null)
7651 // Setup iterator if we are one
7653 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7654 Iterator iterator = new Iterator (
7655 Get, Parent, null, Get.ParameterInfo, ModFlags);
7657 if (!iterator.DefineIterator ())
7663 SetBuilder = Set.Define (Parent);
7664 if (SetBuilder == null)
7669 // Now name the parameters
7671 Parameter [] p = Parameters.FixedParameters;
7673 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7674 Report.Error (631, Location, "ref and out are not valid in this context");
7680 for (i = 0; i < p.Length; ++i) {
7682 GetBuilder.DefineParameter (
7683 i + 1, p [i].Attributes, p [i].Name);
7686 SetBuilder.DefineParameter (
7687 i + 1, p [i].Attributes, p [i].Name);
7691 SetBuilder.DefineParameter (
7692 i + 1, ParameterAttributes.None, "value");
7694 if (i != ParameterTypes.Length) {
7695 Parameter array_param = Parameters.ArrayParameter;
7697 SetBuilder.DefineParameter (
7698 i + 1, array_param.Attributes, array_param.Name);
7702 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7703 Name, prop_attr, MemberType, ParameterTypes);
7706 PropertyBuilder.SetGetMethod (GetBuilder);
7709 PropertyBuilder.SetSetMethod (SetBuilder);
7711 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7716 public override string GetSignatureForError ()
7718 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7719 if (MemberName.Left != null) {
7721 sb.Append (MemberName.Left);
7724 sb.Append (".this");
7725 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7726 return sb.ToString ();
7729 public override bool MarkForDuplicationCheck ()
7731 caching_flags |= Flags.TestMethodDuplication;
7736 public class Operator : MethodCore, IIteratorContainer {
7738 const int AllowedModifiers =
7744 public enum OpType : byte {
7754 // Unary and Binary operators
7777 // Implicit and Explicit
7781 // Just because of enum
7785 public readonly OpType OperatorType;
7786 public MethodBuilder OperatorMethodBuilder;
7788 public Method OperatorMethod;
7790 static string[] attribute_targets = new string [] { "method", "return" };
7792 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7793 int mod_flags, Parameters parameters,
7794 ToplevelBlock block, Attributes attrs, Location loc)
7795 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7796 new MemberName ("op_" + type, loc), attrs, parameters)
7798 OperatorType = type;
7802 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7804 OperatorMethod.ApplyAttributeBuilder (a, cb);
7807 public override AttributeTargets AttributeTargets {
7809 return AttributeTargets.Method;
7813 protected override bool CheckGenericOverride (MethodInfo method, string name)
7818 protected override bool CheckForDuplications()
7820 ArrayList ar = Parent.Operators;
7822 int arLen = ar.Count;
7824 for (int i = 0; i < arLen; i++) {
7825 Operator o = (Operator) ar [i];
7826 if (IsDuplicateImplementation (o))
7831 ar = Parent.Methods;
7833 int arLen = ar.Count;
7835 for (int i = 0; i < arLen; i++) {
7836 Method m = (Method) ar [i];
7837 if (IsDuplicateImplementation (m))
7845 public override bool Define ()
7847 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7848 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7849 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7856 if (MemberType == TypeManager.void_type) {
7857 Report.Error (590, Location, "User-defined operators cannot return void");
7861 OperatorMethod = new Method (
7862 Parent, null, Type, ModFlags, false, MemberName,
7863 Parameters, OptAttributes);
7865 OperatorMethod.Block = Block;
7866 OperatorMethod.IsOperator = this;
7867 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7868 OperatorMethod.Define ();
7870 if (OperatorMethod.MethodBuilder == null)
7873 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7875 parameter_types = OperatorMethod.ParameterTypes;
7876 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7877 Type return_type = OperatorMethod.ReturnType;
7878 Type first_arg_type = parameter_types [0];
7883 // Rules for conversion operators
7885 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7886 if (first_arg_type == return_type && first_arg_type == declaring_type){
7887 Report.Error (555, Location,
7888 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7892 if (first_arg_type != declaring_type && return_type != declaring_type){
7895 "User-defined conversion must convert to or from the " +
7900 if (first_arg_type == TypeManager.object_type ||
7901 return_type == TypeManager.object_type){
7904 "User-defined conversion cannot convert to or from " +
7909 if (first_arg_type.IsInterface || return_type.IsInterface){
7910 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7911 GetSignatureForError ());
7915 if (first_arg_type.IsSubclassOf (return_type)
7916 || return_type.IsSubclassOf (first_arg_type)){
7917 if (declaring_type.IsSubclassOf (return_type)) {
7918 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7919 GetSignatureForError ());
7922 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7923 GetSignatureForError ());
7926 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7927 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7928 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");
7931 } else if (Parameters.FixedParameters.Length == 1) {
7932 // Checks for Unary operators
7934 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7935 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7936 Report.Error (448, Location,
7937 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7940 if (first_arg_type != declaring_type){
7942 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7947 if (first_arg_type != declaring_type){
7950 "The parameter of a unary operator must be the " +
7955 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7956 if (return_type != TypeManager.bool_type){
7959 "The return type of operator True or False " +
7966 if (OperatorType == OpType.BitwiseAnd &&
7967 (first_arg_type != return_type || first_arg_type != parameter_types [1])) {
7968 Report.Error (217, Location, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
7969 "must have the same return type as the type of its 2 parameters", GetSignatureForError ());
7973 // Checks for Binary operators
7975 if (first_arg_type != declaring_type &&
7976 parameter_types [1] != declaring_type){
7979 "One of the parameters of a binary operator must " +
7980 "be the containing type");
7988 public override void Emit ()
7991 // abstract or extern methods have no bodies
7993 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7996 OperatorMethod.Emit ();
8000 // Operator cannot be override
8001 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
8006 public static string GetName (OpType ot)
8009 case OpType.LogicalNot:
8011 case OpType.OnesComplement:
8013 case OpType.Increment:
8015 case OpType.Decrement:
8021 case OpType.Addition:
8023 case OpType.Subtraction:
8025 case OpType.UnaryPlus:
8027 case OpType.UnaryNegation:
8029 case OpType.Multiply:
8031 case OpType.Division:
8033 case OpType.Modulus:
8035 case OpType.BitwiseAnd:
8037 case OpType.BitwiseOr:
8039 case OpType.ExclusiveOr:
8041 case OpType.LeftShift:
8043 case OpType.RightShift:
8045 case OpType.Equality:
8047 case OpType.Inequality:
8049 case OpType.GreaterThan:
8051 case OpType.LessThan:
8053 case OpType.GreaterThanOrEqual:
8055 case OpType.LessThanOrEqual:
8057 case OpType.Implicit:
8059 case OpType.Explicit:
8065 public static OpType GetOperatorType (string name)
8067 if (name.StartsWith ("op_")){
8068 for (int i = 0; i < Unary.oper_names.Length; ++i) {
8069 if (Unary.oper_names [i] == name)
8073 for (int i = 0; i < Binary.oper_names.Length; ++i) {
8074 if (Binary.oper_names [i] == name)
8081 public override string GetSignatureForError ()
8083 StringBuilder sb = new StringBuilder ();
8084 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
8085 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
8088 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
8091 sb.Append (Parameters.GetSignatureForError ());
8092 return sb.ToString ();
8095 public override bool MarkForDuplicationCheck ()
8097 caching_flags |= Flags.TestMethodDuplication;
8101 public override string[] ValidAttributeTargets {
8103 return attribute_targets;
8109 // This is used to compare method signatures
8111 struct MethodSignature {
8113 public Type RetType;
8114 public Type [] Parameters;
8117 /// This delegate is used to extract methods which have the
8118 /// same signature as the argument
8120 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
8122 public MethodSignature (string name, Type ret_type, Type [] parameters)
8127 if (parameters == null)
8128 Parameters = TypeManager.NoTypes;
8130 Parameters = parameters;
8133 public override string ToString ()
8136 if (Parameters.Length != 0){
8137 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8138 for (int i = 0; i < Parameters.Length; i++){
8139 sb.Append (Parameters [i]);
8140 if (i+1 < Parameters.Length)
8143 pars = sb.ToString ();
8146 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8149 public override int GetHashCode ()
8151 return Name.GetHashCode ();
8154 public override bool Equals (Object o)
8156 MethodSignature other = (MethodSignature) o;
8158 if (other.Name != Name)
8161 if (other.RetType != RetType)
8164 if (Parameters == null){
8165 if (other.Parameters == null)
8170 if (other.Parameters == null)
8173 int c = Parameters.Length;
8174 if (other.Parameters.Length != c)
8177 for (int i = 0; i < c; i++)
8178 if (other.Parameters [i] != Parameters [i])
8184 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8186 MethodSignature sig = (MethodSignature) filter_criteria;
8188 if (m.Name != sig.Name)
8192 MethodInfo mi = m as MethodInfo;
8193 PropertyInfo pi = m as PropertyInfo;
8196 ReturnType = mi.ReturnType;
8197 else if (pi != null)
8198 ReturnType = pi.PropertyType;
8203 // we use sig.RetType == null to mean `do not check the
8204 // method return value.
8206 if (sig.RetType != null)
8207 if (ReturnType != sig.RetType)
8212 args = TypeManager.GetArgumentTypes (mi);
8214 args = TypeManager.GetArgumentTypes (pi);
8215 Type [] sigp = sig.Parameters;
8217 if (args.Length != sigp.Length)
8220 for (int i = args.Length; i > 0; ){
8222 if (args [i] != sigp [i])