2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@gnome.org)
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)
13 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
15 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
16 // have fixed a remaining problem: not every AddXXXX was adding a
17 // fully qualified name.
19 // Now everyone registers a fully qualified name in the DeclSpace as
20 // being defined instead of the partial name.
22 // Downsides: we are slower than we need to be due to the excess
23 // copies and the names being registered this way.
25 // The reason for this is that we currently depend (on the corlib
26 // bootstrap for instance) that types are fully qualified, because
27 // we dump all the types in the namespace, and we should really have
28 // types inserted into the proper namespace, so we can only store the
29 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
44 using Mono.CompilerServices.SymbolWriter;
46 namespace Mono.CSharp {
56 /// This is the base class for structs and classes.
58 public abstract class TypeContainer : DeclSpace, IMemberContainer {
60 public class MemberCoreArrayList: ArrayList
63 /// Defines the MemberCore objects that are in this array
65 public virtual void DefineContainerMembers ()
67 foreach (MemberCore mc in this) {
72 public virtual void Emit ()
74 foreach (MemberCore mc in this)
79 public class MethodArrayList: MemberCoreArrayList
87 CachedMethods cached_method;
88 TypeContainer container;
90 public MethodArrayList (TypeContainer container)
92 this.container = container;
96 /// Method container contains Equals method
98 public bool HasEquals {
100 cached_method |= CachedMethods.Equals;
104 return (cached_method & CachedMethods.Equals) != 0;
109 /// Method container contains GetHashCode method
111 public bool HasGetHashCode {
113 cached_method |= CachedMethods.GetHashCode;
117 return (cached_method & CachedMethods.GetHashCode) != 0;
121 public override void DefineContainerMembers ()
123 base.DefineContainerMembers ();
125 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
126 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
132 public sealed class IndexerArrayList: MemberCoreArrayList
135 /// The indexer name for this container
137 public string IndexerName = DefaultIndexerName;
139 bool seen_normal_indexers = false;
141 TypeContainer container;
143 public IndexerArrayList (TypeContainer container)
145 this.container = container;
149 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
150 /// class is consistent. Either it is `Item' or it is the name defined by all the
151 /// indexers with the `IndexerName' attribute.
153 /// Turns out that the IndexerNameAttribute is applied to each indexer,
154 /// but it is never emitted, instead a DefaultMember attribute is attached
157 public override void DefineContainerMembers()
159 base.DefineContainerMembers ();
161 string class_indexer_name = null;
164 // If there's both an explicit and an implicit interface implementation, the
165 // explicit one actually implements the interface while the other one is just
166 // a normal indexer. See bug #37714.
169 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
170 foreach (Indexer i in this) {
171 if (i.InterfaceType != null) {
172 if (seen_normal_indexers)
173 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
177 seen_normal_indexers = true;
179 if (class_indexer_name == null) {
180 class_indexer_name = i.ShortName;
184 if (i.ShortName != class_indexer_name)
185 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");
188 if (class_indexer_name != null)
189 IndexerName = class_indexer_name;
192 public override void Emit ()
196 if (!seen_normal_indexers)
199 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
200 container.TypeBuilder.SetCustomAttribute (cb);
204 public class OperatorArrayList: MemberCoreArrayList
206 TypeContainer container;
208 public OperatorArrayList (TypeContainer container)
210 this.container = container;
214 // Operator pair checking
219 public Type ret_type;
220 public Type type1, type2;
222 public Operator.OpType ot;
224 public OperatorEntry (int f, Operator o)
228 ret_type = o.OperatorMethod.ReturnType;
229 Type [] pt = o.OperatorMethod.ParameterTypes;
236 public override int GetHashCode ()
238 return ret_type.GetHashCode ();
241 public override bool Equals (object o)
243 OperatorEntry other = (OperatorEntry) o;
245 if (other.ret_type != ret_type)
247 if (other.type1 != type1)
249 if (other.type2 != type2)
256 // Checks that some operators come in pairs:
262 // They are matched based on the return type and the argument types
264 void CheckPairedOperators ()
266 Hashtable pairs = new Hashtable (null, null);
267 Operator true_op = null;
268 Operator false_op = null;
269 bool has_equality_or_inequality = false;
271 // Register all the operators we care about.
272 foreach (Operator op in this){
275 switch (op.OperatorType){
276 case Operator.OpType.Equality:
278 has_equality_or_inequality = true;
280 case Operator.OpType.Inequality:
282 has_equality_or_inequality = true;
285 case Operator.OpType.True:
288 case Operator.OpType.False:
292 case Operator.OpType.GreaterThan:
294 case Operator.OpType.LessThan:
297 case Operator.OpType.GreaterThanOrEqual:
299 case Operator.OpType.LessThanOrEqual:
305 OperatorEntry oe = new OperatorEntry (reg, op);
307 object o = pairs [oe];
311 oe = (OperatorEntry) o;
316 if (true_op != null){
317 if (false_op == null)
318 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
319 } else if (false_op != null)
320 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
323 // Look for the mistakes.
325 foreach (DictionaryEntry de in pairs){
326 OperatorEntry oe = (OperatorEntry) de.Key;
333 case Operator.OpType.Equality:
336 case Operator.OpType.Inequality:
339 case Operator.OpType.GreaterThan:
342 case Operator.OpType.LessThan:
345 case Operator.OpType.GreaterThanOrEqual:
348 case Operator.OpType.LessThanOrEqual:
352 Report.Error (216, oe.op.Location,
353 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
356 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
357 if (container.Methods == null || !container.Methods.HasEquals)
358 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
360 if (container.Methods == null || !container.Methods.HasGetHashCode)
361 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
365 public override void DefineContainerMembers ()
367 base.DefineContainerMembers ();
368 CheckPairedOperators ();
373 // Whether this is a struct, class or interface
374 public readonly Kind Kind;
376 // Holds a list of classes and structures
379 // Holds the list of properties
380 MemberCoreArrayList properties;
382 // Holds the list of enumerations
383 MemberCoreArrayList enums;
385 // Holds the list of delegates
386 MemberCoreArrayList delegates;
388 // Holds the list of constructors
389 protected MemberCoreArrayList instance_constructors;
391 // Holds the list of fields
392 MemberCoreArrayList fields;
394 // Holds a list of fields that have initializers
395 protected ArrayList initialized_fields;
397 // Holds a list of static fields that have initializers
398 protected ArrayList initialized_static_fields;
400 // Holds the list of constants
401 MemberCoreArrayList constants;
404 MemberCoreArrayList interfaces;
406 // Holds the methods.
407 MethodArrayList methods;
410 protected MemberCoreArrayList events;
412 // Holds the indexers
413 IndexerArrayList indexers;
415 // Holds the operators
416 MemberCoreArrayList operators;
418 // Holds the iterators
421 // Holds the parts of a partial class;
425 // Pointers to the default constructor and the default static constructor
427 protected Constructor default_constructor;
428 protected Constructor default_static_constructor;
431 // Whether we have at least one non-static field
433 bool have_nonstatic_fields = false;
436 // This one is computed after we can distinguish interfaces
437 // from classes from the arraylist `type_bases'
439 string base_class_name;
440 TypeExpr parent_type;
442 ArrayList type_bases;
444 bool members_defined;
445 bool members_defined_ok;
447 // The interfaces we implement.
448 protected Type[] ifaces;
449 protected Type ptype;
451 // The parent member container and our member cache
452 IMemberContainer parent_container;
453 MemberCache parent_cache;
454 MemberCache member_cache;
456 public const string DefaultIndexerName = "Item";
460 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
461 Attributes attrs, Kind kind, Location l)
462 : base (ns, parent, name, attrs, l)
466 types = new ArrayList ();
468 base_class_name = null;
471 public bool AddToMemberContainer (MemberCore symbol, bool is_method)
473 return AddToContainer (symbol, is_method, String.Concat (Name, '.', symbol.Name), symbol.Name);
476 bool AddToTypeContainer (DeclSpace ds)
478 return AddToContainer (ds, false, ds.Name, ds.Basename);
481 public void AddConstant (Const constant)
483 if (!AddToMemberContainer (constant, false))
486 if (constants == null)
487 constants = new MemberCoreArrayList ();
489 constants.Add (constant);
492 public void AddEnum (Mono.CSharp.Enum e)
494 if (!AddToTypeContainer (e))
498 enums = new MemberCoreArrayList ();
503 public void AddClassOrStruct (TypeContainer c)
505 if (!AddToTypeContainer (c))
511 public void AddDelegate (Delegate d)
513 if (!AddToTypeContainer (d))
516 if (delegates == null)
517 delegates = new MemberCoreArrayList ();
522 public void AddMethod (Method method)
524 if (!AddToMemberContainer (method, true))
528 methods = new MethodArrayList (this);
530 if (method.Name.IndexOf ('.') != -1)
531 methods.Insert (0, method);
533 methods.Add (method);
536 public void AddConstructor (Constructor c)
538 if (c.Name != Basename) {
539 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
542 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
545 if (default_static_constructor != null) {
546 Report.SymbolRelatedToPreviousError (default_static_constructor);
547 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
548 "called '{1}' with the same parameter types", Name, c.Name);
552 default_static_constructor = c;
555 if (default_constructor != null) {
556 Report.SymbolRelatedToPreviousError (default_constructor);
557 Report.Error (111, c.Location, "Type '{0}' already defines a member " +
558 "called '{1}' with the same parameter types", Name, c.Name);
561 default_constructor = c;
564 if (instance_constructors == null)
565 instance_constructors = new MemberCoreArrayList ();
567 instance_constructors.Add (c);
571 public void AddInterface (TypeContainer iface)
573 if (!AddToTypeContainer (iface))
576 if (interfaces == null) {
577 interfaces = new MemberCoreArrayList ();
580 interfaces.Add (iface);
583 public void AddField (Field field)
585 if (!AddToMemberContainer (field, false))
589 fields = new MemberCoreArrayList ();
593 if (field.HasInitializer){
594 if ((field.ModFlags & Modifiers.STATIC) != 0){
595 if (initialized_static_fields == null)
596 initialized_static_fields = new ArrayList ();
598 initialized_static_fields.Add (field);
601 if (initialized_fields == null)
602 initialized_fields = new ArrayList ();
604 initialized_fields.Add (field);
608 if ((field.ModFlags & Modifiers.STATIC) == 0)
609 have_nonstatic_fields = true;
612 public void AddProperty (Property prop)
614 if (!AddToMemberContainer (prop, false) ||
615 !AddToMemberContainer (prop.Get, true) || !AddToMemberContainer (prop.Set, true))
618 if (properties == null)
619 properties = new MemberCoreArrayList ();
621 if (prop.Name.IndexOf ('.') != -1)
622 properties.Insert (0, prop);
624 properties.Add (prop);
627 public void AddEvent (Event e)
629 if (!AddToMemberContainer (e, false))
632 if (e is EventProperty) {
633 if (!AddToMemberContainer (e.Add, true))
636 if (!AddToMemberContainer (e.Remove, true))
641 events = new MemberCoreArrayList ();
647 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
649 public void AddIndexer (Indexer i)
651 if (indexers == null)
652 indexers = new IndexerArrayList (this);
654 if (i.IsExplicitImpl)
655 indexers.Insert (0, i);
660 public void AddOperator (Operator op)
662 if (!AddToMemberContainer (op, true))
665 if (operators == null)
666 operators = new OperatorArrayList (this);
671 public void AddIterator (Iterator i)
673 if (iterators == null)
674 iterators = new ArrayList ();
679 public void AddType (TypeContainer tc)
684 public void AddPart (ClassPart part)
687 parts = new ArrayList ();
692 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
694 if (a.Type == TypeManager.default_member_type) {
695 if (Indexers != null) {
696 Report.Error (646, a.Location,
697 "Cannot specify the DefaultMember attribute on" +
698 " a type containing an indexer");
703 base.ApplyAttributeBuilder (a, cb);
706 public override AttributeTargets AttributeTargets {
708 throw new NotSupportedException ();
712 public ArrayList Types {
718 public MethodArrayList Methods {
724 public ArrayList Constants {
730 public ArrayList Interfaces {
736 public ArrayList Iterators {
744 return base_class_name;
748 public ArrayList Bases {
758 public ArrayList Fields {
764 public ArrayList InstanceConstructors {
766 return instance_constructors;
770 public ArrayList Properties {
776 public ArrayList Events {
782 public ArrayList Enums {
788 public ArrayList Indexers {
794 public ArrayList Operators {
800 public ArrayList Delegates {
806 public ArrayList Parts {
812 public virtual TypeAttributes TypeAttr {
814 return Modifiers.TypeAttr (ModFlags, this);
818 public string IndexerName {
820 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
825 // Emits the instance field initializers
827 public bool EmitFieldInitializers (EmitContext ec)
830 Expression instance_expr;
833 fields = initialized_static_fields;
834 instance_expr = null;
836 fields = initialized_fields;
837 instance_expr = new This (Location.Null).Resolve (ec);
843 foreach (Field f in fields){
844 Expression e = f.GetInitializerExpression (ec);
848 Location l = f.Location;
849 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
850 fe.InstanceExpression = instance_expr;
851 fe.IsFieldInitializer = true;
853 ExpressionStatement a = new Assign (fe, e, l);
855 a = a.ResolveStatement (ec);
859 a.EmitStatement (ec);
866 // Defines the default constructors
868 protected void DefineDefaultConstructor (bool is_static)
872 // The default constructor is public
873 // If the class is abstract, the default constructor is protected
874 // The default static constructor is private
876 int mods = Modifiers.PUBLIC;
878 mods = Modifiers.STATIC | Modifiers.PRIVATE;
879 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
880 mods = Modifiers.PROTECTED;
882 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
883 new ConstructorBaseInitializer (
884 null, Parameters.EmptyReadOnlyParameters,
890 c.Block = new ToplevelBlock (null, Location);
895 /// The pending methods that need to be implemented
896 // (interfaces or abstract methods)
898 public PendingImplementation Pending;
900 public abstract void Register ();
902 public abstract PendingImplementation GetPendingImplementations ();
904 TypeExpr[] GetPartialBases (out TypeExpr parent, out bool error)
906 ArrayList ifaces = new ArrayList ();
909 Location parent_loc = Location.Null;
911 foreach (ClassPart part in parts) {
913 TypeExpr[] new_ifaces;
915 new_ifaces = part.GetClassBases (out new_parent, out error);
919 if ((parent != null) && (new_parent != null) &&
920 !parent.Equals (new_parent)) {
921 Report.Error (263, part.Location,
922 "Partial declarations of `{0}' must " +
923 "not specify different base classes",
926 if (!Location.IsNull (parent_loc))
927 Report.LocationOfPreviousError (parent_loc);
933 if ((parent == null) && (new_parent != null)) {
935 parent_loc = part.Location;
938 if (new_ifaces == null)
941 foreach (TypeExpr iface in new_ifaces) {
943 foreach (TypeExpr old_iface in ifaces) {
944 if (old_iface.Equals (iface)) {
957 TypeExpr[] retval = new TypeExpr [ifaces.Count];
958 ifaces.CopyTo (retval, 0);
962 TypeExpr[] GetNormalBases (out TypeExpr parent, out bool error)
966 int count = Bases.Count;
969 if (Kind == Kind.Class){
970 TypeExpr name = ResolveTypeExpr ((Expression) Bases [0], Location);
987 TypeExpr [] ifaces = new TypeExpr [count-start];
989 for (i = start, j = 0; i < count; i++, j++){
990 Expression name = (Expression) Bases [i];
991 TypeExpr resolved = ResolveTypeExpr (name, Location);
992 if (resolved == null) {
997 ifaces [j] = resolved;
1005 /// This function computes the Base class and also the
1006 /// list of interfaces that the class or struct @c implements.
1008 /// The return value is an array (might be null) of
1009 /// interfaces implemented (as Types).
1011 /// The @parent argument is set to the parent object or null
1012 /// if this is `System.Object'.
1014 TypeExpr [] GetClassBases (out TypeExpr parent, out bool error)
1023 ifaces = GetPartialBases (out parent, out error);
1024 else if (Bases == null){
1028 ifaces = GetNormalBases (out parent, out error);
1033 if ((parent != null) && (Kind == Kind.Class)){
1034 if (parent is TypeParameterExpr){
1036 689, parent.Location,
1037 "Type parameter `{0}' can not be used as a " +
1038 "base class or interface", parent.Name);
1043 if (IsGeneric && parent.IsAttribute){
1045 698, parent.Location,
1046 "A generic type cannot derive from `{0}' " +
1047 "because it is an attribute class",
1053 if (parent.IsSealed){
1055 Report.SymbolRelatedToPreviousError (parent.Type);
1056 if (parent.Type.IsAbstract) {
1057 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1059 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1064 if (!parent.CanInheritFrom ()){
1065 Report.Error (644, Location,
1066 "`{0}' cannot inherit from special class `{1}'",
1067 Name, parent_type.Name);
1072 if (!parent.AsAccessible (this, ModFlags))
1073 Report.Error (60, Location,
1074 "Inconsistent accessibility: base class `" +
1075 parent.Name + "' is less accessible than class `" +
1080 base_class_name = parent.Name;
1085 int count = ifaces != null ? ifaces.Length : 0;
1087 for (i = 0; i < count; i++) {
1088 TypeExpr iface = (TypeExpr) ifaces [i];
1090 if ((Kind != Kind.Class) && !iface.IsInterface){
1091 string what = Kind == Kind.Struct ?
1092 "Struct" : "Interface";
1094 Report.Error (527, Location,
1095 "In {0} `{1}', type `{2}' is not "+
1096 "an interface", what, Name, iface.Name);
1101 if (iface.IsClass) {
1102 if (parent != null){
1103 Report.Error (527, Location,
1104 "In Class `{0}', `{1}' is not " +
1105 "an interface", Name, iface.Name);
1111 for (int x = 0; x < i; x++) {
1112 if (iface.Equals (ifaces [x])) {
1113 Report.Error (528, Location,
1114 "`{0}' is already listed in " +
1115 "interface list", iface.Name);
1121 if ((Kind == Kind.Interface) &&
1122 !iface.AsAccessible (Parent, ModFlags))
1123 Report.Error (61, Location,
1124 "Inconsistent accessibility: base " +
1125 "interface `{0}' is less accessible " +
1126 "than interface `{1}'", iface.Name,
1133 bool CheckGenericInterfaces (Type[] ifaces)
1135 ArrayList already_checked = new ArrayList ();
1137 for (int i = 0; i < ifaces.Length; i++) {
1138 Type iface = ifaces [i];
1139 foreach (Type t in already_checked) {
1143 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t))
1148 "`{0}' cannot implement both `{1}' and `{2}' " +
1149 "because they may unify for some type " +
1150 "parameter substitutions",
1151 TypeManager.GetFullName (TypeBuilder),
1156 already_checked.Add (iface);
1165 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1167 public override TypeBuilder DefineType ()
1174 if (TypeBuilder != null)
1177 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1179 TypeAttributes type_attributes = TypeAttr;
1183 if (TypeManager.NamespaceClash (Name, Location)) {
1188 ModuleBuilder builder = CodeGen.Module.Builder;
1189 TypeBuilder = builder.DefineType (
1190 Name, type_attributes, null, null);
1192 TypeBuilder builder;
1193 if (Parent.TypeBuilder != null)
1194 builder = Parent.TypeBuilder;
1196 builder = Parent.DefineType ();
1198 if (builder == null) {
1203 TypeBuilder = builder.DefineNestedType (
1204 MemberName.Basename, type_attributes,
1208 catch (ArgumentException) {
1209 Report.RuntimeMissingSupport (Location, "static classes");
1213 TypeManager.AddUserType (Name, TypeBuilder, this);
1215 TypeExpr current_type = null;
1218 string[] param_names = new string [TypeParameters.Length];
1219 for (int i = 0; i < TypeParameters.Length; i++)
1220 param_names [i] = TypeParameters [i].Name;
1222 GenericTypeParameterBuilder[] gen_params;
1223 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1225 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1226 for (int i = offset; i < gen_params.Length; i++)
1227 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1229 foreach (TypeParameter type_param in CurrentTypeParameters) {
1230 if (!type_param.Resolve (this)) {
1236 for (int i = offset; i < gen_params.Length; i++)
1237 CurrentTypeParameters [i - offset].DefineConstraints ();
1239 current_type = new ConstructedType (Name, TypeParameters, Location);
1243 foreach (TypeParameter type_param in TypeParameters)
1244 if (!type_param.DefineType (ec)) {
1250 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1251 throw new Exception ();
1253 TypeExpr[] iface_exprs = GetClassBases (out parent_type, out error);
1257 if (parent_type == null) {
1258 if (Kind == Kind.Class){
1259 if (RootContext.StdLib)
1260 parent_type = TypeManager.system_object_expr;
1261 else if (Name != "System.Object")
1262 parent_type = TypeManager.system_object_expr;
1263 } else if (Kind == Kind.Struct){
1265 // If we are compiling our runtime,
1266 // and we are defining ValueType, then our
1267 // parent is `System.Object'.
1269 if (!RootContext.StdLib && Name == "System.ValueType")
1270 parent_type = TypeManager.system_object_expr;
1271 else if (Kind == Kind.Struct)
1272 parent_type = TypeManager.system_valuetype_expr;
1276 if (parent_type != null) {
1277 parent_type = parent_type.ResolveAsTypeTerminal (ec);
1278 if (parent_type == null) {
1283 ptype = parent_type.Type;
1286 if (!CheckRecursiveDefinition ()) {
1292 TypeBuilder.SetParent (ptype);
1295 // Structs with no fields need to have at least one byte.
1296 // The right thing would be to set the PackingSize in a DefineType
1297 // but there are no functions that allow interfaces *and* the size to
1301 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1302 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1303 FieldAttributes.Private);
1306 // add interfaces that were not added at type creation
1307 if (iface_exprs != null) {
1308 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1309 if (ifaces == null) {
1314 foreach (Type itype in ifaces)
1315 TypeBuilder.AddInterfaceImplementation (itype);
1317 if (!CheckGenericInterfaces (ifaces)) {
1322 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1326 foreach (TypeParameter type_param in TypeParameters)
1327 if (!type_param.CheckDependencies (ec)) {
1333 if (current_type != null) {
1334 current_type = current_type.ResolveAsTypeTerminal (ec);
1335 if (current_type == null) {
1340 CurrentType = current_type.Type;
1344 // Finish the setup for the EmitContext
1346 ec.ContainerType = TypeBuilder;
1348 if ((parent_type != null) && parent_type.IsAttribute) {
1349 RootContext.RegisterAttribute (this);
1350 } else if (!(this is Iterator))
1351 RootContext.RegisterOrder (this);
1353 if (!DefineNestedTypes ()) {
1361 protected virtual bool DefineNestedTypes ()
1363 if (Interfaces != null) {
1364 foreach (TypeContainer iface in Interfaces)
1365 if (iface.DefineType () == null)
1369 if (Types != null) {
1370 foreach (TypeContainer tc in Types)
1371 if (tc.DefineType () == null)
1375 if (Delegates != null) {
1376 foreach (Delegate d in Delegates)
1377 if (d.DefineType () == null)
1381 if (Enums != null) {
1382 foreach (Enum en in Enums)
1383 if (en.DefineType () == null)
1387 if (Parts != null) {
1388 foreach (ClassPart part in Parts) {
1389 part.TypeBuilder = TypeBuilder;
1390 part.parent_type = parent_type;
1391 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1398 protected bool CheckRecursiveDefinition ()
1401 Report.Error (146, Location,
1402 "Class definition is circular: `{0}'",
1403 GetSignatureForError ());
1410 Type parent = ptype;
1411 if (parent != null) {
1412 if (parent.IsGenericInstance)
1413 parent = parent.GetGenericTypeDefinition ();
1415 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1416 if ((ptc != null) && !ptc.CheckRecursiveDefinition ())
1424 static void Error_KeywordNotAllowed (Location loc)
1426 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1430 /// Populates our TypeBuilder with fields and methods
1432 public override bool DefineMembers (TypeContainer container)
1434 if (members_defined)
1435 return members_defined_ok;
1437 members_defined_ok = DoDefineMembers ();
1438 members_defined = true;
1440 return members_defined_ok;
1443 bool DoDefineMembers ()
1446 // We need to be able to use the member cache while we are checking/defining
1448 if (TypeBuilder.BaseType != null) {
1449 parent_container = TypeManager.LookupMemberContainer (TypeBuilder.BaseType);
1450 parent_cache = parent_container.MemberCache;
1453 if (TypeBuilder.IsInterface)
1454 parent_cache = TypeManager.LookupInterfaceCache (this, TypeBuilder);
1457 if ((ModFlags & Modifiers.NEW) != 0)
1458 Error_KeywordNotAllowed (Location);
1460 // HACK: missing implemenation
1461 // This is not fully functional. Better way how to handle this is to have recursive definition of containers
1462 // instead of flat as we have now.
1463 // Now we are not able to check inner attribute class because its parent had not been defined.
1465 // TODO: remove this if
1466 if (Parent.MemberCache != null) {
1467 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1468 if (conflict_symbol == null) {
1469 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1470 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1472 if ((ModFlags & Modifiers.NEW) == 0) {
1473 Report.SymbolRelatedToPreviousError (conflict_symbol);
1474 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1480 DefineContainerMembers (constants);
1481 DefineContainerMembers (fields);
1483 if ((Kind == Kind.Class) && !(this is ClassPart) && !(this is StaticClass)){
1484 if ((instance_constructors == null) &&
1485 !(this is StaticClass)) {
1486 if (default_constructor == null)
1487 DefineDefaultConstructor (false);
1490 if (initialized_static_fields != null &&
1491 default_static_constructor == null)
1492 DefineDefaultConstructor (true);
1495 if (Kind == Kind.Struct){
1497 // Structs can not have initialized instance
1500 if (initialized_static_fields != null &&
1501 default_static_constructor == null)
1502 DefineDefaultConstructor (true);
1504 if (initialized_fields != null)
1505 ReportStructInitializedInstanceError ();
1508 Pending = GetPendingImplementations ();
1510 if (parts != null) {
1511 foreach (ClassPart part in parts) {
1512 if (!part.DefineMembers (this))
1518 // Constructors are not in the defined_names array
1520 DefineContainerMembers (instance_constructors);
1522 if (default_static_constructor != null)
1523 default_static_constructor.Define ();
1525 DefineContainerMembers (properties);
1526 DefineContainerMembers (events);
1527 DefineContainerMembers (indexers);
1528 DefineContainerMembers (methods);
1529 DefineContainerMembers (operators);
1530 DefineContainerMembers (enums);
1531 DefineContainerMembers (delegates);
1533 if (CurrentType != null) {
1534 GenericType = CurrentType;
1536 ec.ContainerType = GenericType;
1541 if (!(this is ClassPart))
1542 member_cache = new MemberCache (this);
1545 if (parts != null) {
1546 foreach (ClassPart part in parts)
1547 part.member_cache = member_cache;
1550 if (iterators != null) {
1551 foreach (Iterator iterator in iterators) {
1552 if (iterator.DefineType () == null)
1556 foreach (Iterator iterator in iterators) {
1557 if (!iterator.DefineMembers (this))
1565 void ReportStructInitializedInstanceError ()
1567 string n = TypeBuilder.FullName;
1569 foreach (Field f in initialized_fields){
1572 "`" + n + "." + f.Name + "': can not have " +
1573 "instance field initializers in structs");
1577 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1580 mcal.DefineContainerMembers ();
1583 public override bool Define ()
1585 if (parts != null) {
1586 foreach (ClassPart part in parts) {
1587 if (!part.Define ())
1595 public MemberInfo FindMemberWithSameName (string name, bool ignore_methods)
1597 return ParentCache.FindMemberWithSameName (name, ignore_methods, null);
1601 /// This function is based by a delegate to the FindMembers routine
1603 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1609 /// This filter is used by FindMembers, and we just keep
1610 /// a global for the filter to `AlwaysAccept'
1612 static MemberFilter accepting_filter;
1615 static TypeContainer ()
1617 accepting_filter = new MemberFilter (AlwaysAccept);
1620 public MethodInfo[] GetMethods ()
1622 ArrayList members = new ArrayList ();
1624 DefineMembers (null);
1626 if (methods != null) {
1627 int len = methods.Count;
1628 for (int i = 0; i < len; i++) {
1629 Method m = (Method) methods [i];
1631 members.Add (m.MethodBuilder);
1635 if (operators != null) {
1636 int len = operators.Count;
1637 for (int i = 0; i < len; i++) {
1638 Operator o = (Operator) operators [i];
1640 members.Add (o.OperatorMethodBuilder);
1644 if (properties != null) {
1645 int len = properties.Count;
1646 for (int i = 0; i < len; i++) {
1647 Property p = (Property) properties [i];
1649 if (p.GetBuilder != null)
1650 members.Add (p.GetBuilder);
1651 if (p.SetBuilder != null)
1652 members.Add (p.SetBuilder);
1656 if (indexers != null) {
1657 int len = indexers.Count;
1658 for (int i = 0; i < len; i++) {
1659 Indexer ix = (Indexer) indexers [i];
1661 if (ix.GetBuilder != null)
1662 members.Add (ix.GetBuilder);
1663 if (ix.SetBuilder != null)
1664 members.Add (ix.SetBuilder);
1668 if (events != null) {
1669 int len = events.Count;
1670 for (int i = 0; i < len; i++) {
1671 Event e = (Event) events [i];
1673 if (e.AddBuilder != null)
1674 members.Add (e.AddBuilder);
1675 if (e.RemoveBuilder != null)
1676 members.Add (e.RemoveBuilder);
1680 MethodInfo[] retMethods = new MethodInfo [members.Count];
1681 members.CopyTo (retMethods, 0);
1685 // Indicated whether container has StructLayout attribute set Explicit
1686 public virtual bool HasExplicitLayout {
1693 /// This method returns the members of this type just like Type.FindMembers would
1694 /// Only, we need to use this for types which are _being_ defined because MS'
1695 /// implementation can't take care of that.
1698 // FIXME: return an empty static array instead of null, that cleans up
1699 // some code and is consistent with some coding conventions I just found
1703 // Notice that in various cases we check if our field is non-null,
1704 // something that would normally mean that there was a bug elsewhere.
1706 // The problem happens while we are defining p-invoke methods, as those
1707 // will trigger a FindMembers, but this happens before things are defined
1709 // Since the whole process is a no-op, it is fine to check for null here.
1711 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1712 MemberFilter filter, object criteria)
1714 ArrayList members = null;
1717 if ((bf & BindingFlags.Public) != 0)
1718 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1720 if ((bf & BindingFlags.NonPublic) != 0)
1721 modflags |= Modifiers.PRIVATE;
1723 int static_mask = 0, static_flags = 0;
1724 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1725 case BindingFlags.Static:
1726 static_mask = static_flags = Modifiers.STATIC;
1729 case BindingFlags.Instance:
1730 static_mask = Modifiers.STATIC;
1735 static_mask = static_flags = 0;
1739 Timer.StartTimer (TimerType.TcFindMembers);
1742 filter = accepting_filter;
1744 if ((mt & MemberTypes.Field) != 0) {
1745 if (fields != null) {
1746 int len = fields.Count;
1747 for (int i = 0; i < len; i++) {
1748 Field f = (Field) fields [i];
1750 if ((f.ModFlags & modflags) == 0)
1752 if ((f.ModFlags & static_mask) != static_flags)
1755 FieldBuilder fb = f.FieldBuilder;
1756 if (fb != null && filter (fb, criteria) == true) {
1757 if (members == null)
1758 members = new ArrayList ();
1765 if (constants != null) {
1766 int len = constants.Count;
1767 for (int i = 0; i < len; i++) {
1768 Const con = (Const) constants [i];
1770 if ((con.ModFlags & modflags) == 0)
1772 if ((con.ModFlags & static_mask) != static_flags)
1775 FieldBuilder fb = con.FieldBuilder;
1776 if (fb != null && filter (fb, criteria) == true) {
1777 if (members == null)
1778 members = new ArrayList ();
1786 if ((mt & MemberTypes.Method) != 0) {
1787 if (methods != null) {
1788 int len = methods.Count;
1789 for (int i = 0; i < len; i++) {
1790 Method m = (Method) methods [i];
1792 if ((m.ModFlags & modflags) == 0)
1794 if ((m.ModFlags & static_mask) != static_flags)
1797 MethodBuilder mb = m.MethodBuilder;
1799 if (mb != null && filter (mb, criteria) == true) {
1800 if (members == null)
1801 members = new ArrayList ();
1808 if (operators != null) {
1809 int len = operators.Count;
1810 for (int i = 0; i < len; i++) {
1811 Operator o = (Operator) operators [i];
1813 if ((o.ModFlags & modflags) == 0)
1815 if ((o.ModFlags & static_mask) != static_flags)
1818 MethodBuilder ob = o.OperatorMethodBuilder;
1819 if (ob != null && filter (ob, criteria) == true) {
1820 if (members == null)
1821 members = new ArrayList ();
1828 if (properties != null) {
1829 int len = properties.Count;
1830 for (int i = 0; i < len; i++) {
1831 Property p = (Property) properties [i];
1833 if ((p.ModFlags & modflags) == 0)
1835 if ((p.ModFlags & static_mask) != static_flags)
1841 if (b != null && filter (b, criteria) == true) {
1842 if (members == null)
1843 members = new ArrayList ();
1849 if (b != null && filter (b, criteria) == true) {
1850 if (members == null)
1851 members = new ArrayList ();
1858 if (indexers != null) {
1859 int len = indexers.Count;
1860 for (int i = 0; i < len; i++) {
1861 Indexer ix = (Indexer) indexers [i];
1863 if ((ix.ModFlags & modflags) == 0)
1865 if ((ix.ModFlags & static_mask) != static_flags)
1871 if (b != null && filter (b, criteria) == true) {
1872 if (members == null)
1873 members = new ArrayList ();
1879 if (b != null && filter (b, criteria) == true) {
1880 if (members == null)
1881 members = new ArrayList ();
1889 if ((mt & MemberTypes.Event) != 0) {
1890 if (events != null) {
1891 int len = events.Count;
1892 for (int i = 0; i < len; i++) {
1893 Event e = (Event) events [i];
1895 if ((e.ModFlags & modflags) == 0)
1897 if ((e.ModFlags & static_mask) != static_flags)
1900 MemberInfo eb = e.EventBuilder;
1901 if (eb != null && filter (eb, criteria) == true) {
1902 if (members == null)
1903 members = new ArrayList ();
1905 members.Add (e.EventBuilder);
1911 if ((mt & MemberTypes.Property) != 0){
1912 if (properties != null) {
1913 int len = properties.Count;
1914 for (int i = 0; i < len; i++) {
1915 Property p = (Property) properties [i];
1917 if ((p.ModFlags & modflags) == 0)
1919 if ((p.ModFlags & static_mask) != static_flags)
1922 MemberInfo pb = p.PropertyBuilder;
1923 if (pb != null && filter (pb, criteria) == true) {
1924 if (members == null)
1925 members = new ArrayList ();
1927 members.Add (p.PropertyBuilder);
1932 if (indexers != null) {
1933 int len = indexers.Count;
1934 for (int i = 0; i < len; i++) {
1935 Indexer ix = (Indexer) indexers [i];
1937 if ((ix.ModFlags & modflags) == 0)
1939 if ((ix.ModFlags & static_mask) != static_flags)
1942 MemberInfo ib = ix.PropertyBuilder;
1943 if (ib != null && filter (ib, criteria) == true) {
1944 if (members == null)
1945 members = new ArrayList ();
1947 members.Add (ix.PropertyBuilder);
1953 if ((mt & MemberTypes.NestedType) != 0) {
1954 if (types != null) {
1955 int len = types.Count;
1956 for (int i = 0; i < len; i++) {
1957 TypeContainer t = (TypeContainer) types [i];
1959 if ((t.ModFlags & modflags) == 0)
1962 TypeBuilder tb = t.TypeBuilder;
1963 if (tb != null && (filter (tb, criteria) == true)) {
1964 if (members == null)
1965 members = new ArrayList ();
1972 if (enums != null) {
1973 int len = enums.Count;
1974 for (int i = 0; i < len; i++) {
1975 Enum en = (Enum) enums [i];
1977 if ((en.ModFlags & modflags) == 0)
1980 TypeBuilder tb = en.TypeBuilder;
1981 if (tb != null && (filter (tb, criteria) == true)) {
1982 if (members == null)
1983 members = new ArrayList ();
1990 if (delegates != null) {
1991 int len = delegates.Count;
1992 for (int i = 0; i < len; i++) {
1993 Delegate d = (Delegate) delegates [i];
1995 if ((d.ModFlags & modflags) == 0)
1998 TypeBuilder tb = d.TypeBuilder;
1999 if (tb != null && (filter (tb, criteria) == true)) {
2000 if (members == null)
2001 members = new ArrayList ();
2008 if (interfaces != null) {
2009 int len = interfaces.Count;
2010 for (int i = 0; i < len; i++) {
2011 TypeContainer iface = (TypeContainer) interfaces [i];
2013 if ((iface.ModFlags & modflags) == 0)
2016 TypeBuilder tb = iface.TypeBuilder;
2017 if (tb != null && (filter (tb, criteria) == true)) {
2018 if (members == null)
2019 members = new ArrayList ();
2027 if ((mt & MemberTypes.Constructor) != 0){
2028 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2029 int len = instance_constructors.Count;
2030 for (int i = 0; i < len; i++) {
2031 Constructor c = (Constructor) instance_constructors [i];
2033 ConstructorBuilder cb = c.ConstructorBuilder;
2034 if (cb != null && filter (cb, criteria) == true) {
2035 if (members == null)
2036 members = new ArrayList ();
2043 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2044 ConstructorBuilder cb =
2045 default_static_constructor.ConstructorBuilder;
2047 if (cb != null && filter (cb, criteria) == true) {
2048 if (members == null)
2049 members = new ArrayList ();
2057 // Lookup members in parent if requested.
2059 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2060 if (TypeBuilder.BaseType != null) {
2061 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2062 if (list.Count > 0) {
2063 if (members == null)
2064 members = new ArrayList ();
2066 members.AddRange (list);
2072 Timer.StopTimer (TimerType.TcFindMembers);
2074 if (members == null)
2075 return MemberList.Empty;
2077 return new MemberList (members);
2080 public override MemberCache MemberCache {
2082 return member_cache;
2086 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2087 MemberFilter filter, object criteria)
2089 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2092 return ds.FindMembers (mt, bf, filter, criteria);
2094 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2098 // FindMethods will look for methods not only in the type `t', but in
2099 // any interfaces implemented by the type.
2101 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
2102 MemberFilter filter, object criteria)
2108 /// Emits the values for the constants
2110 public void EmitConstants ()
2112 if (constants != null)
2113 foreach (Const con in constants)
2118 protected virtual void VerifyMembers (EmitContext ec)
2121 // Check for internal or private fields that were never assigned
2123 if (RootContext.WarningLevel >= 3) {
2124 if (fields != null){
2125 foreach (Field f in fields) {
2126 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2129 if ((f.status & Field.Status.USED) == 0){
2130 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2135 // Only report 649 on level 4
2137 if (RootContext.WarningLevel < 4)
2140 if ((f.status & Field.Status.ASSIGNED) != 0)
2143 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2150 /// Emits the code, this step is performed after all
2151 /// the types, enumerations, constructors
2153 public void EmitType ()
2155 if (OptAttributes != null)
2156 OptAttributes.Emit (ec, this);
2160 if (instance_constructors != null) {
2161 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2162 bool has_compliant_args = false;
2164 foreach (Constructor c in instance_constructors) {
2167 if (has_compliant_args)
2170 has_compliant_args = c.HasCompliantArgs;
2172 if (!has_compliant_args)
2173 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2175 foreach (Constructor c in instance_constructors)
2182 if (default_static_constructor != null)
2183 default_static_constructor.Emit ();
2185 if (methods != null)
2186 foreach (Method m in methods)
2189 if (operators != null)
2190 foreach (Operator o in operators)
2193 if (properties != null)
2194 foreach (Property p in properties)
2197 if (indexers != null){
2202 foreach (Field f in fields)
2205 if (events != null){
2206 foreach (Event e in Events)
2210 if (delegates != null) {
2211 foreach (Delegate d in Delegates) {
2216 if (enums != null) {
2217 foreach (Enum e in enums) {
2222 if (parts != null) {
2223 foreach (ClassPart part in parts)
2227 if ((Pending != null) && !(this is ClassPart))
2228 if (Pending.VerifyPendingMethods ())
2233 if (iterators != null)
2234 foreach (Iterator iterator in iterators)
2235 iterator.EmitType ();
2237 // if (types != null)
2238 // foreach (TypeContainer tc in types)
2242 public override void CloseType ()
2244 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2248 caching_flags |= Flags.CloseTypeCreated;
2249 TypeBuilder.CreateType ();
2250 } catch (TypeLoadException){
2252 // This is fine, the code still created the type
2254 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2255 // Console.WriteLine (e.Message);
2257 Console.WriteLine ("In type: " + Name);
2262 foreach (Enum en in Enums)
2266 foreach (TypeContainer tc in Types)
2267 if (tc.Kind == Kind.Struct)
2270 foreach (TypeContainer tc in Types)
2271 if (tc.Kind != Kind.Struct)
2275 if (Delegates != null)
2276 foreach (Delegate d in Delegates)
2279 if (Iterators != null)
2280 foreach (Iterator i in Iterators)
2288 initialized_fields = null;
2289 initialized_static_fields = null;
2298 default_constructor = null;
2299 default_static_constructor = null;
2301 OptAttributes = null;
2303 parent_cache = null;
2304 member_cache = null;
2307 // TODO: make it obsolete and use GetSignatureForError
2308 public string MakeName (string n)
2310 return "`" + Name + "." + n + "'";
2314 // Performs the validation on a Method's modifiers (properties have
2315 // the same properties).
2317 public bool MethodModifiersValid (int flags, string n, Location loc)
2319 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2320 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2321 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2325 // At most one of static, virtual or override
2327 if ((flags & Modifiers.STATIC) != 0){
2328 if ((flags & vao) != 0){
2330 112, loc, "static method " + MakeName (n) + "can not be marked " +
2331 "as virtual, abstract or override");
2336 if (Kind == Kind.Struct){
2337 if ((flags & va) != 0){
2338 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
2343 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2345 113, loc, MakeName (n) +
2346 " marked as override cannot be marked as new or virtual");
2351 // If the declaration includes the abstract modifier, then the
2352 // declaration does not include static, virtual or extern
2354 if ((flags & Modifiers.ABSTRACT) != 0){
2355 if ((flags & Modifiers.EXTERN) != 0){
2357 180, loc, MakeName (n) + " can not be both abstract and extern");
2361 if ((flags & Modifiers.VIRTUAL) != 0){
2363 503, loc, MakeName (n) + " can not be both abstract and virtual");
2367 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2369 513, loc, MakeName (n) +
2370 " is abstract but its container class is not");
2376 if ((flags & Modifiers.PRIVATE) != 0){
2377 if ((flags & vao) != 0){
2379 621, loc, MakeName (n) +
2380 " virtual or abstract members can not be private");
2385 if ((flags & Modifiers.SEALED) != 0){
2386 if ((flags & Modifiers.OVERRIDE) == 0){
2388 238, loc, MakeName (n) +
2389 " cannot be sealed because it is not an override");
2397 public bool UserDefinedStaticConstructor {
2399 return default_static_constructor != null;
2403 protected override bool VerifyClsCompliance (DeclSpace ds)
2405 if (!base.VerifyClsCompliance (ds))
2410 // parent_container is null for System.Object
2411 if (parent_container != null && !AttributeTester.IsClsCompliant (parent_container.Type)) {
2412 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (parent_container.Type));
2419 /// Checks whether container name is CLS Compliant
2421 void VerifyClsName ()
2423 Hashtable parent_members = parent_cache == null ?
2425 parent_cache.GetPublicMembers ();
2426 Hashtable this_members = new Hashtable ();
2428 foreach (DictionaryEntry entry in defined_names) {
2429 MemberCore mc = (MemberCore)entry.Value;
2430 if (!mc.IsClsCompliaceRequired (this))
2433 string name = (string)entry.Key;
2434 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2436 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2437 object found = parent_members [lcase];
2438 if (found == null) {
2439 found = this_members [lcase];
2440 if (found == null) {
2441 this_members.Add (lcase, mc);
2446 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2449 if (found is MemberInfo) {
2450 if (basename == ((MemberInfo)found).Name)
2452 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2454 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2456 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2462 /// Performs checks for an explicit interface implementation. First it
2463 /// checks whether the `interface_type' is a base inteface implementation.
2464 /// Then it checks whether `name' exists in the interface type.
2466 public virtual bool VerifyImplements (Type interface_type, string full,
2467 string name, Location loc)
2471 if (ifaces != null){
2472 foreach (Type t in ifaces){
2473 if (t == interface_type){
2481 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
2488 protected override void VerifyObsoleteAttribute()
2490 CheckUsageOfObsoleteAttribute (TypeBuilder.BaseType);
2495 foreach (Type iface in ifaces) {
2496 CheckUsageOfObsoleteAttribute (iface);
2504 string IMemberContainer.Name {
2510 Type IMemberContainer.Type {
2516 MemberCache IMemberContainer.MemberCache {
2518 return member_cache;
2522 bool IMemberContainer.IsInterface {
2524 return Kind == Kind.Interface;
2528 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2530 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2532 if (GenericType != null)
2533 return TypeManager.FindMembers (GenericType, mt, new_bf,
2536 return FindMembers (mt, new_bf, null, null);
2539 public virtual MemberCache ParentCache {
2541 return parent_cache;
2547 public class PartialContainer : TypeContainer {
2549 public readonly Namespace Namespace;
2550 public readonly int OriginalModFlags;
2551 public readonly int AllowedModifiers;
2552 public readonly TypeAttributes DefaultTypeAttributes;
2554 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2555 MemberName name, int mod_flags, Kind kind,
2558 PartialContainer pc;
2559 string full_name = name.GetName (true);
2560 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2562 pc = ds as PartialContainer;
2566 260, ds.Location, "Missing partial modifier " +
2567 "on declaration of type `{0}'; another " +
2568 "partial implementation of this type exists",
2571 Report.LocationOfPreviousError (loc);
2575 if (pc.Kind != kind) {
2577 261, loc, "Partial declarations of `{0}' " +
2578 "must be all classes, all structs or " +
2579 "all interfaces", name);
2583 if (pc.OriginalModFlags != mod_flags) {
2585 262, loc, "Partial declarations of `{0}' " +
2586 "have conflicting accessibility modifiers",
2594 pc = new PartialContainer (ns, parent, name, mod_flags, kind, loc);
2595 RootContext.Tree.RecordDecl (full_name, pc);
2596 parent.AddType (pc);
2601 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2602 MemberName name, int mod, Attributes attrs,
2603 Kind kind, Location loc)
2605 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2607 // An error occured; create a dummy container, but don't
2609 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2612 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2617 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2618 MemberName name, int mod, Kind kind, Location l)
2619 : base (ns, parent, name, null, kind, l)
2621 this.Namespace = ns.NS;
2625 AllowedModifiers = Class.AllowedModifiers;
2626 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2630 AllowedModifiers = Struct.AllowedModifiers;
2631 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2634 case Kind.Interface:
2635 AllowedModifiers = Interface.AllowedModifiers;
2636 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2640 throw new InvalidOperationException ();
2644 if (parent.Parent == null)
2645 accmods = Modifiers.INTERNAL;
2647 accmods = Modifiers.PRIVATE;
2649 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2650 this.OriginalModFlags = mod;
2653 public override void Register ()
2655 if (Kind == Kind.Interface)
2656 Parent.AddInterface (this);
2657 else if (Kind == Kind.Class || Kind == Kind.Struct)
2658 Parent.AddClassOrStruct (this);
2660 throw new InvalidOperationException ();
2663 public override PendingImplementation GetPendingImplementations ()
2665 return PendingImplementation.GetPendingImplementations (this);
2668 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2671 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2676 public override TypeAttributes TypeAttr {
2678 return base.TypeAttr | DefaultTypeAttributes;
2683 public class ClassPart : TypeContainer, IMemberContainer {
2684 public readonly PartialContainer PartialContainer;
2685 public readonly bool IsPartial;
2687 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2688 int mod, Attributes attrs, Kind kind, Location l)
2689 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2691 this.PartialContainer = parent;
2692 this.IsPartial = true;
2695 if (parent.Parent == null)
2696 accmods = Modifiers.INTERNAL;
2698 accmods = Modifiers.PRIVATE;
2700 this.ModFlags = Modifiers.Check (
2701 parent.AllowedModifiers, mod, accmods, l);
2704 public override void Register ()
2708 public override PendingImplementation GetPendingImplementations ()
2710 return PartialContainer.Pending;
2713 public override bool VerifyImplements (Type interface_type, string full,
2714 string name, Location loc)
2716 return PartialContainer.VerifyImplements (
2717 interface_type, full, name, loc);
2720 public override MemberCache ParentCache {
2722 return PartialContainer.ParentCache;
2727 public abstract class ClassOrStruct : TypeContainer {
2728 bool hasExplicitLayout = false;
2729 ListDictionary declarative_security;
2731 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2732 MemberName name, Attributes attrs, Kind kind,
2734 : base (ns, parent, name, attrs, kind, l)
2738 public override PendingImplementation GetPendingImplementations ()
2740 return PendingImplementation.GetPendingImplementations (this);
2743 public override bool HasExplicitLayout {
2745 return hasExplicitLayout;
2749 protected override void VerifyMembers (EmitContext ec)
2751 base.VerifyMembers (ec);
2753 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2754 foreach (Event e in events){
2756 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2761 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2763 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2764 if (declarative_security == null)
2765 declarative_security = new ListDictionary ();
2767 a.ExtractSecurityPermissionSet (declarative_security);
2771 if (a.Type == TypeManager.struct_layout_attribute_type
2772 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2773 hasExplicitLayout = true;
2775 base.ApplyAttributeBuilder (a, cb);
2778 public override void Emit()
2782 if (declarative_security != null) {
2783 foreach (DictionaryEntry de in declarative_security) {
2784 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2789 public override void Register ()
2791 Parent.AddClassOrStruct (this);
2796 /// Class handles static classes declaration
2798 public sealed class StaticClass: Class {
2799 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2800 Attributes attrs, Location l)
2801 : base (ns, parent, name, mod & ~Modifiers.STATIC, attrs, l)
2803 if (RootContext.Version == LanguageVersion.ISO_1) {
2804 Report.FeatureIsNotStandardized (l, "static classes");
2805 Environment.Exit (1);
2809 protected override void DefineContainerMembers (MemberCoreArrayList list)
2814 foreach (MemberCore m in list) {
2815 if (m is Operator) {
2816 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2820 if ((m.ModFlags & Modifiers.STATIC) != 0)
2823 if (m is Constructor) {
2824 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2828 if (m is Destructor) {
2829 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2832 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2835 base.DefineContainerMembers (list);
2838 public override TypeBuilder DefineType()
2840 TypeBuilder tb = base.DefineType ();
2844 if ((ptype != null) && (ptype != TypeManager.object_type)) {
2847 "Static class '{0}' cannot derive from type '{1}'. " +
2848 "Static classes must derive from object",
2849 GetSignatureForError (), ptype);
2853 if (ifaces != null) {
2854 foreach (Type t in ifaces)
2855 Report.SymbolRelatedToPreviousError (t);
2858 "'{0}': static classes cannot implement interfaces",
2859 GetSignatureForError ());
2864 public override TypeAttributes TypeAttr {
2866 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2871 public class Class : ClassOrStruct {
2873 // Modifiers allowed in a class declaration
2875 public const int AllowedModifiers =
2878 Modifiers.PROTECTED |
2879 Modifiers.INTERNAL |
2881 Modifiers.ABSTRACT |
2885 // Information in the case we are an attribute type
2886 AttributeUsageAttribute attribute_usage;
2888 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2889 Attributes attrs, Location l)
2890 : base (ns, parent, name, attrs, Kind.Class, l)
2894 if (parent.Parent == null)
2895 accmods = Modifiers.INTERNAL;
2897 accmods = Modifiers.PRIVATE;
2899 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2900 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.SEALED)) == (Modifiers.ABSTRACT | Modifiers.SEALED)) {
2901 Report.Error (502, Location, "'{0}' cannot be both abstract and sealed", GetSignatureForError ());
2904 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2907 public override AttributeTargets AttributeTargets {
2909 return AttributeTargets.Class;
2913 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2915 if (a.UsageAttribute != null) {
2916 if (ptype != TypeManager.attribute_type &&
2917 !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2918 TypeBuilder.FullName != "System.Attribute") {
2919 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2921 attribute_usage = a.UsageAttribute;
2924 base.ApplyAttributeBuilder (a, cb);
2927 public AttributeUsageAttribute AttributeUsage {
2929 return attribute_usage;
2933 public const TypeAttributes DefaultTypeAttributes =
2934 TypeAttributes.AutoLayout | TypeAttributes.Class;
2937 // FIXME: How do we deal with the user specifying a different
2940 public override TypeAttributes TypeAttr {
2942 return base.TypeAttr | DefaultTypeAttributes;
2947 public class Struct : ClassOrStruct {
2949 // Modifiers allowed in a struct declaration
2951 public const int AllowedModifiers =
2954 Modifiers.PROTECTED |
2955 Modifiers.INTERNAL |
2959 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2960 int mod, Attributes attrs, Location l)
2961 : base (ns, parent, name, attrs, Kind.Struct, l)
2965 if (parent.Parent == null)
2966 accmods = Modifiers.INTERNAL;
2968 accmods = Modifiers.PRIVATE;
2970 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2972 this.ModFlags |= Modifiers.SEALED;
2975 public override AttributeTargets AttributeTargets {
2977 return AttributeTargets.Struct;
2981 public const TypeAttributes DefaultTypeAttributes =
2982 TypeAttributes.SequentialLayout |
2983 TypeAttributes.Sealed |
2984 TypeAttributes.BeforeFieldInit;
2987 // FIXME: Allow the user to specify a different set of attributes
2988 // in some cases (Sealed for example is mandatory for a class,
2989 // but what SequentialLayout can be changed
2991 public override TypeAttributes TypeAttr {
2993 return base.TypeAttr | DefaultTypeAttributes;
3001 public class Interface : TypeContainer, IMemberContainer {
3003 /// Modifiers allowed in a class declaration
3005 public const int AllowedModifiers =
3008 Modifiers.PROTECTED |
3009 Modifiers.INTERNAL |
3013 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name,
3014 int mod, Attributes attrs, Location l)
3015 : base (ns, parent, name, attrs, Kind.Interface, l)
3019 if (parent.Parent == null)
3020 accmods = Modifiers.INTERNAL;
3022 accmods = Modifiers.PRIVATE;
3024 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3027 public override void Register ()
3029 Parent.AddInterface (this);
3032 public override PendingImplementation GetPendingImplementations ()
3037 public override AttributeTargets AttributeTargets {
3039 return AttributeTargets.Interface;
3043 public const TypeAttributes DefaultTypeAttributes =
3044 TypeAttributes.AutoLayout |
3045 TypeAttributes.Abstract |
3046 TypeAttributes.Interface;
3048 public override TypeAttributes TypeAttr {
3050 return base.TypeAttr | DefaultTypeAttributes;
3055 public abstract class MethodCore : MemberBase {
3056 public readonly Parameters Parameters;
3057 public readonly GenericMethod GenericMethod;
3058 public readonly DeclSpace ds;
3059 protected ToplevelBlock block;
3062 // Parameters, cached for semantic analysis.
3064 protected InternalParameters parameter_info;
3065 protected Type [] parameter_types;
3067 // Whether this is an operator method.
3068 public bool IsOperator;
3071 // The method we're overriding if this is an override method.
3073 protected MethodInfo parent_method = null;
3075 static string[] attribute_targets = new string [] { "method", "return" };
3077 public MethodCore (TypeContainer parent, GenericMethod generic,
3078 Expression type, int mod, int allowed_mod, bool is_iface,
3079 MemberName name, Attributes attrs, Parameters parameters,
3081 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3084 Parameters = parameters;
3085 IsInterface = is_iface;
3086 this.GenericMethod = generic;
3088 if (generic != null)
3095 // Returns the System.Type array for the parameters of this method
3097 public Type [] ParameterTypes {
3099 return parameter_types;
3103 public InternalParameters ParameterInfo
3106 return parameter_info;
3110 public ToplevelBlock Block {
3120 protected override bool CheckBase ()
3122 if (!base.CheckBase ())
3125 // Check whether arguments were correct.
3126 if (!DoDefineParameters ())
3129 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3135 // Is null for System.Object while compiling corlib and base interfaces
3136 if (Parent.ParentCache == null) {
3137 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3138 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3143 Type parent_ret_type = null;
3144 parent_method = FindOutParentMethod (Parent, ref parent_ret_type);
3146 // method is override
3147 if (parent_method != null) {
3149 if (!CheckMethodAgainstBase ())
3152 if ((ModFlags & Modifiers.NEW) == 0) {
3153 if (!MemberType.Equals (TypeManager.TypeToCoreType (parent_ret_type))) {
3154 Report.SymbolRelatedToPreviousError (parent_method);
3155 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3156 "change return type when overriding inherited member");
3160 if (parent_method.IsAbstract && !IsInterface) {
3161 Report.SymbolRelatedToPreviousError (parent_method);
3162 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3167 if (parent_method.IsSpecialName && !(this is PropertyBase)) {
3168 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (parent_method));
3172 if (RootContext.WarningLevel > 2) {
3173 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3174 Parent.Methods.HasEquals = true;
3175 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3176 Parent.Methods.HasGetHashCode = true;
3179 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (parent_method);
3181 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3182 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3183 Report.SymbolRelatedToPreviousError (parent_method);
3184 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3190 MemberInfo conflict_symbol = Parent.FindMemberWithSameName (Name, !(this is Property));
3191 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3192 if (conflict_symbol != null) {
3193 Report.SymbolRelatedToPreviousError (conflict_symbol);
3194 if (this is PropertyBase)
3195 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3197 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3199 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3203 if (conflict_symbol == null) {
3204 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3205 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3210 if ((ModFlags & Modifiers.NEW) == 0) {
3211 if (this is Method && conflict_symbol is MethodBase)
3214 Report.SymbolRelatedToPreviousError (conflict_symbol);
3215 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3223 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3224 // that have been defined.
3226 // `name' is the user visible name for reporting errors (this is used to
3227 // provide the right name regarding method names and properties)
3229 bool CheckMethodAgainstBase ()
3233 // TODO: replace with GetSignatureForError
3234 string name = parent_method.DeclaringType.Name + "." + parent_method.Name;
3236 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3237 if (!(parent_method.IsAbstract || parent_method.IsVirtual)){
3239 506, Location, Parent.MakeName (Name) +
3240 ": cannot override inherited member `" +
3241 name + "' because it is not " +
3242 "virtual, abstract or override");
3246 // Now we check that the overriden method is not final
3248 if (parent_method.IsFinal) {
3249 // This happens when implementing interface methods.
3250 if (parent_method.IsHideBySig && parent_method.IsVirtual) {
3252 506, Location, Parent.MakeName (Name) +
3253 ": cannot override inherited member `" +
3254 name + "' because it is not " +
3255 "virtual, abstract or override");
3257 Report.Error (239, Location, Parent.MakeName (Name) + " : cannot " +
3258 "override inherited member `" + name +
3259 "' because it is sealed.");
3263 // Check that the permissions are not being changed
3265 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3266 MethodAttributes parentp = parent_method.Attributes & MethodAttributes.MemberAccessMask;
3269 // special case for "protected internal"
3272 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3274 // when overriding protected internal, the method can be declared
3275 // protected internal only within the same assembly
3278 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3279 if (Parent.TypeBuilder.Assembly != parent_method.DeclaringType.Assembly){
3281 // assemblies differ - report an error
3284 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3286 } else if (thisp != parentp) {
3288 // same assembly, but other attributes differ - report an error
3291 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3294 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3296 // if it's not "protected internal", it must be "protected"
3299 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3301 } else if (Parent.TypeBuilder.Assembly == parent_method.DeclaringType.Assembly) {
3303 // protected within the same assembly - an error
3305 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3307 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3308 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3310 // protected ok, but other attributes differ - report an error
3312 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3316 if (thisp != parentp){
3317 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3323 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3324 ModFlags |= Modifiers.NEW;
3325 Report.SymbolRelatedToPreviousError (parent_method);
3326 if (!IsInterface && (parent_method.IsVirtual || parent_method.IsAbstract)) {
3327 if (RootContext.WarningLevel >= 2)
3328 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 (Parent), TypeManager.CSharpSignature (parent_method));
3330 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3336 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method, string name)
3339 // FIXME: report the old/new permissions?
3342 507, Location, parent.MakeName (Name) +
3343 ": can't change the access modifiers when overriding inherited " +
3344 "member `" + name + "'");
3347 protected static string Error722 {
3349 return "'{0}': static types cannot be used as return types";
3354 /// For custom member duplication search in a container
3356 protected abstract bool CheckForDuplications ();
3359 /// Gets parent method and its return type
3361 protected abstract MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type);
3363 protected virtual bool DoDefineParameters ()
3365 EmitContext ec = ds.EmitContext;
3367 throw new InternalErrorException ("DoDefineParameters invoked too early");
3369 bool old_unsafe = ec.InUnsafe;
3370 ec.InUnsafe = InUnsafe;
3371 // Check if arguments were correct
3372 parameter_types = Parameters.GetParameterInfo (ec);
3373 ec.InUnsafe = old_unsafe;
3375 if ((parameter_types == null) ||
3376 !CheckParameters (ds, parameter_types))
3379 TypeParameter[] tparam = ds.IsGeneric ? ds.TypeParameters : null;
3380 parameter_info = new InternalParameters (parameter_types, Parameters, tparam);
3382 Parameter array_param = Parameters.ArrayParameter;
3383 if ((array_param != null) &&
3384 (!array_param.ParameterType.IsArray ||
3385 (array_param.ParameterType.GetArrayRank () != 1))) {
3386 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3393 void error_425 (Type old, Type t, string name)
3395 Report.Error (425, Location,
3396 "The constraints of type parameter `{0}' " +
3397 "of method `{1}' must match the constraints for " +
3398 "type parameter `{2}' of method `{3}'",
3399 TypeManager.CSharpName (old), Name,
3400 TypeManager.CSharpName (t), name);
3403 protected override bool CheckGenericOverride (MethodInfo method, string name)
3405 ParameterData pd = Invocation.GetParameterData (method);
3407 for (int i = 0; i < ParameterTypes.Length; i++) {
3408 GenericConstraints ogc = pd.GenericConstraints (i);
3409 GenericConstraints gc = ParameterInfo.GenericConstraints (i);
3411 if ((gc == null) && (ogc == null))
3414 Type ot = pd.ParameterType (i);
3415 Type t = ParameterTypes [i];
3417 if (!((gc != null) && (ogc != null))) {
3418 error_425 (ot, t, name);
3422 if ((gc.Attributes != ogc.Attributes) ||
3423 (gc.HasClassConstraint != ogc.HasClassConstraint)) {
3424 error_425 (ot, t, name);
3428 if (ogc.HasClassConstraint &&
3429 !ogc.ClassConstraint.Equals (gc.ClassConstraint)) {
3430 error_425 (ot, t, name);
3434 Type[] oct = ogc.InterfaceConstraints;
3435 Type[] ct = gc.InterfaceConstraints;
3437 if (oct.Length != ct.Length) {
3438 error_425 (ot, t, name);
3442 for (int j = 0; j < oct.Length; j++)
3443 if (!oct [j].Equals (ct [j])) {
3444 error_425 (ot, t, name);
3452 public override string[] ValidAttributeTargets {
3454 return attribute_targets;
3458 protected override bool VerifyClsCompliance (DeclSpace ds)
3460 if (!base.VerifyClsCompliance (ds)) {
3461 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3462 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3467 if (Parameters.HasArglist) {
3468 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3471 if (!AttributeTester.IsClsCompliant (MemberType)) {
3472 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant", GetSignatureForError ());
3475 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3480 protected bool IsDuplicateImplementation (MethodCore method)
3482 if ((method == this) ||
3483 (method.MemberName.GetTypeName () != MemberName.GetTypeName ()))
3486 Type[] param_types = method.ParameterTypes;
3487 if (param_types == null)
3490 if (param_types.Length != ParameterTypes.Length)
3493 int type_params = 0;
3494 if (GenericMethod != null)
3495 type_params = GenericMethod.CountTypeParameters;
3497 int m_type_params = 0;
3498 if (method.GenericMethod != null)
3499 m_type_params = method.GenericMethod.CountTypeParameters;
3501 if (type_params != m_type_params)
3507 Type[] infered_types;
3508 if (type_params > 0)
3509 infered_types = new Type [type_params];
3511 infered_types = null;
3513 may_unify = Invocation.InferTypeArguments (
3514 param_types, ParameterTypes, ref infered_types);
3517 if (type_params > 0)
3518 infered_types = new Type [type_params];
3520 infered_types = null;
3522 may_unify = Invocation.InferTypeArguments (
3523 ParameterTypes, param_types, ref infered_types);
3526 for (int i = 0; i < param_types.Length; i++) {
3527 if (param_types [i] != ParameterTypes [i])
3531 // TODO: make operator compatible with MethodCore to avoid this
3532 if (this is Operator && method is Operator) {
3533 if (MemberType != method.MemberType)
3539 // Try to report 663: method only differs on out/ref
3541 ParameterData info = ParameterInfo;
3542 ParameterData other_info = method.ParameterInfo;
3543 for (int i = 0; i < info.Count; i++){
3544 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3545 Report.Error (663, Location,
3546 "Overload method only differs " +
3547 "in parameter modifier");
3552 Report.SymbolRelatedToPreviousError (method);
3553 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with the same parameter types", Parent.Name, Name);
3555 } else if (may_unify) {
3556 Report.Error (408, Location,
3557 "`{0}' cannot define overload members that " +
3558 "may unify for some type parameter substitutions",
3566 protected override void VerifyObsoleteAttribute()
3568 base.VerifyObsoleteAttribute ();
3570 if (parameter_types == null)
3573 foreach (Type type in parameter_types) {
3574 CheckUsageOfObsoleteAttribute (type);
3579 public class SourceMethod : ISourceMethod
3581 TypeContainer container;
3584 protected SourceMethod (TypeContainer container, MethodBase builder,
3585 ISourceFile file, Location start, Location end)
3587 this.container = container;
3588 this.builder = builder;
3590 CodeGen.SymbolWriter.OpenMethod (
3591 file, this, start.Row, 0, end.Row, 0);
3594 public string Name {
3595 get { return builder.Name; }
3598 public int NamespaceID {
3599 get { return container.NamespaceEntry.SymbolFileID; }
3604 if (builder is MethodBuilder)
3605 return ((MethodBuilder) builder).GetToken ().Token;
3606 else if (builder is ConstructorBuilder)
3607 return ((ConstructorBuilder) builder).GetToken ().Token;
3609 throw new NotSupportedException ();
3613 public void CloseMethod ()
3615 if (CodeGen.SymbolWriter != null)
3616 CodeGen.SymbolWriter.CloseMethod ();
3619 public static SourceMethod Create (TypeContainer parent,
3620 MethodBase builder, Block block)
3622 if (CodeGen.SymbolWriter == null)
3627 Location start_loc = block.StartLocation;
3628 if (Location.IsNull (start_loc))
3631 Location end_loc = block.EndLocation;
3632 if (Location.IsNull (end_loc))
3635 ISourceFile file = start_loc.SourceFile;
3639 return new SourceMethod (
3640 parent, builder, file, start_loc, end_loc);
3644 public class Method : MethodCore, IIteratorContainer, IMethodData {
3645 public MethodBuilder MethodBuilder;
3646 public MethodData MethodData;
3647 ReturnParameter return_attributes;
3648 ListDictionary declarative_security;
3651 /// Modifiers allowed in a class declaration
3653 const int AllowedModifiers =
3656 Modifiers.PROTECTED |
3657 Modifiers.INTERNAL |
3662 Modifiers.OVERRIDE |
3663 Modifiers.ABSTRACT |
3665 Modifiers.METHOD_YIELDS |
3668 const int AllowedInterfaceModifiers =
3669 Modifiers.NEW | Modifiers.UNSAFE;
3672 // return_type can be "null" for VOID values.
3674 public Method (TypeContainer parent, GenericMethod generic,
3675 Expression return_type, int mod, bool is_iface,
3676 MemberName name, Parameters parameters, Attributes attrs,
3678 : base (parent, generic, return_type, mod,
3679 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3680 is_iface, name, attrs, parameters, l)
3684 public override AttributeTargets AttributeTargets {
3686 return AttributeTargets.Method;
3690 public override string GetSignatureForError()
3692 if (MethodBuilder == null) {
3693 return GetSignatureForError (Parent);
3695 return TypeManager.CSharpSignature (MethodBuilder);
3699 /// Use this method when MethodBuilder is null
3701 public override string GetSignatureForError (TypeContainer tc)
3703 // TODO: get params from somewhere
3704 if (parameter_info == null)
3705 return base.GetSignatureForError (tc);
3707 // TODO: move to parameters
3708 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3709 if (parameter_info.Parameters.FixedParameters != null) {
3710 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3711 Parameter p = parameter_info.Parameters.FixedParameters [i];
3712 args.Append (p.GetSignatureForError ());
3714 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3719 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3722 void DuplicateEntryPoint (MethodInfo b, Location location)
3726 "Program `" + CodeGen.FileName +
3727 "' has more than one entry point defined: `" +
3728 TypeManager.CSharpSignature(b) + "'");
3731 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3733 if (b.ReturnType != TypeManager.void_type &&
3734 b.ReturnType != TypeManager.int32_type)
3737 if (pinfo.Count == 0)
3740 if (pinfo.Count > 1)
3743 Type t = pinfo.ParameterType(0);
3745 (t.GetArrayRank() == 1) &&
3746 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3747 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3753 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3755 if (a.Target == AttributeTargets.ReturnValue) {
3756 if (return_attributes == null)
3757 return_attributes = new ReturnParameter (MethodBuilder, Location);
3759 return_attributes.ApplyAttributeBuilder (a, cb);
3763 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
3764 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3767 if (a.Type == TypeManager.dllimport_type) {
3768 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3769 if ((ModFlags & extern_static) != extern_static) {
3770 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3776 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3777 if (declarative_security == null)
3778 declarative_security = new ListDictionary ();
3779 a.ExtractSecurityPermissionSet (declarative_security);
3783 if (a.Type == TypeManager.conditional_attribute_type) {
3784 if (IsOperator || IsExplicitImpl) {
3785 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3789 if (ReturnType != TypeManager.void_type) {
3790 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3794 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3795 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3800 Report.Error (582, Location, "Conditional not valid on interface members");
3804 if (MethodData.IsImplementing) {
3805 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3809 for (int i = 0; i < parameter_info.Count; ++i) {
3810 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3811 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3817 MethodBuilder.SetCustomAttribute (cb);
3820 protected override bool CheckForDuplications ()
3822 ArrayList ar = Parent.Methods;
3824 int arLen = ar.Count;
3826 for (int i = 0; i < arLen; i++) {
3827 Method m = (Method) ar [i];
3828 if (IsDuplicateImplementation (m))
3833 ar = Parent.Properties;
3835 for (int i = 0; i < ar.Count; ++i) {
3836 PropertyBase pb = (PropertyBase) ar [i];
3837 if (pb.AreAccessorsDuplicateImplementation (this))
3842 ar = Parent.Indexers;
3844 for (int i = 0; i < ar.Count; ++i) {
3845 PropertyBase pb = (PropertyBase) ar [i];
3846 if (pb.AreAccessorsDuplicateImplementation (this))
3853 for (int i = 0; i < ar.Count; ++i) {
3854 Event ev = (Event) ar [i];
3855 if (ev.AreAccessorsDuplicateImplementation (this))
3866 public override bool Define ()
3868 if (!DoDefineBase ())
3871 MethodBuilder mb = null;
3872 if (GenericMethod != null) {
3873 string mname = MemberName.GetMethodName ();
3874 mb = Parent.TypeBuilder.DefineGenericMethod (mname, flags);
3875 if (!GenericMethod.Define (mb, ReturnType))
3886 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3888 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags,
3889 this, mb, GenericMethod, parent_method);
3891 if (!MethodData.Define (Parent))
3895 // Setup iterator if we are one
3897 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3898 Iterator iterator = new Iterator (
3899 Parent, Name, MemberType, ParameterTypes,
3900 ParameterInfo, ModFlags, block, Location);
3902 if (!iterator.DefineIterator ())
3905 block = iterator.Block;
3908 MethodBuilder = MethodData.MethodBuilder;
3911 // This is used to track the Entry Point,
3913 if (Name == "Main" &&
3914 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3915 (RootContext.MainClass == null ||
3916 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3917 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3918 if (RootContext.EntryPoint == null) {
3919 if (Parent.IsGeneric){
3920 Report.Error (-201, Location,
3921 "Entry point can not be defined in a generic class");
3924 RootContext.EntryPoint = MethodBuilder;
3925 RootContext.EntryPointLocation = Location;
3927 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3928 DuplicateEntryPoint (MethodBuilder, Location);
3931 if (RootContext.WarningLevel >= 4)
3932 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder) );
3936 if (MemberType.IsAbstract && MemberType.IsSealed) {
3937 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3947 public override void Emit ()
3949 MethodData.Emit (Parent, this);
3952 if (declarative_security != null) {
3953 foreach (DictionaryEntry de in declarative_security) {
3954 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3962 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
3964 MethodInfo mi = (MethodInfo) container.ParentCache.FindMemberToOverride (
3965 container.TypeBuilder, Name, ParameterTypes, false);
3970 parent_ret_type = mi.ReturnType;
3974 protected override bool VerifyClsCompliance(DeclSpace ds)
3976 if (!base.VerifyClsCompliance (ds))
3979 if (parameter_types.Length > 0) {
3980 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3982 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3989 void IIteratorContainer.SetYields ()
3991 ModFlags |= Modifiers.METHOD_YIELDS;
3994 #region IMethodData Members
3996 public CallingConventions CallingConventions {
3998 CallingConventions cc = Parameters.GetCallingConvention ();
3999 if (Parameters.HasArglist)
4000 block.HasVarargs = true;
4003 if ((ModFlags & Modifiers.STATIC) == 0)
4004 cc |= CallingConventions.HasThis;
4006 // FIXME: How is `ExplicitThis' used in C#?
4012 public Type ReturnType {
4018 public MemberName MethodName {
4024 public new Location Location {
4026 return base.Location;
4030 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4032 return new EmitContext (
4033 tc, ds, Location, ig, ReturnType, ModFlags, false);
4036 public ObsoleteAttribute GetObsoleteAttribute ()
4038 return GetObsoleteAttribute (ds);
4042 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4044 public bool IsExcluded (EmitContext ec)
4046 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4047 return (caching_flags & Flags.Excluded) != 0;
4049 caching_flags &= ~Flags.Excluded_Undetected;
4051 if (parent_method == null) {
4052 if (OptAttributes == null)
4055 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4060 foreach (Attribute a in attrs) {
4061 string condition = a.GetConditionalAttributeValue (ds);
4062 if (RootContext.AllDefines.Contains (condition))
4066 caching_flags |= Flags.Excluded;
4070 IMethodData md = TypeManager.GetMethod (parent_method);
4072 if (AttributeTester.IsConditionalMethodExcluded (parent_method)) {
4073 caching_flags |= Flags.Excluded;
4079 if (md.IsExcluded (ec)) {
4080 caching_flags |= Flags.Excluded;
4086 GenericMethod IMethodData.GenericMethod {
4088 return GenericMethod;
4095 public abstract class ConstructorInitializer {
4096 ArrayList argument_list;
4097 protected ConstructorInfo parent_constructor;
4098 Parameters parameters;
4101 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4104 this.argument_list = argument_list;
4105 this.parameters = parameters;
4109 public ArrayList Arguments {
4111 return argument_list;
4115 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4117 Expression parent_constructor_group;
4120 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
4122 if (argument_list != null){
4123 foreach (Argument a in argument_list){
4124 if (!a.Resolve (ec, loc))
4128 ec.CurrentBlock = null;
4130 if (this is ConstructorBaseInitializer) {
4131 if (ec.ContainerType.BaseType == null)
4134 t = ec.ContainerType.BaseType;
4135 if (ec.ContainerType.IsValueType) {
4136 Report.Error (522, loc,
4137 "structs cannot call base class constructors");
4141 t = ec.ContainerType;
4143 parent_constructor_group = Expression.MemberLookup (
4144 ec, t, ".ctor", MemberTypes.Constructor,
4145 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4148 if (parent_constructor_group == null){
4149 parent_constructor_group = Expression.MemberLookup (
4150 ec, t, ".ctor", MemberTypes.Constructor,
4151 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4154 if (parent_constructor_group != null)
4156 112, loc, "`{0}.{1}' is inaccessible due to " +
4157 "its protection level", t.FullName, t.Name);
4160 1501, loc, "Can not find a constructor for " +
4161 "this argument list");
4165 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4166 ec, (MethodGroupExpr) parent_constructor_group, argument_list,
4169 if (parent_constructor == null){
4170 Report.Error (1501, loc,
4171 "Can not find a constructor for this argument list");
4175 if (parent_constructor == caller_builder){
4176 Report.Error (516, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
4183 public void Emit (EmitContext ec)
4185 if (parent_constructor != null){
4186 ec.Mark (loc, false);
4188 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
4190 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
4195 /// Method search for base ctor. (We do not cache it).
4197 Constructor GetOverloadedConstructor (TypeContainer tc)
4199 if (tc.InstanceConstructors == null)
4202 foreach (Constructor c in tc.InstanceConstructors) {
4203 if (Arguments == null) {
4204 if (c.ParameterTypes.Length == 0)
4212 int count = c.ParameterInfo.Count;
4214 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
4215 for (int i = 0; i < count-1; i++)
4216 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4221 if (c.ParameterTypes.Length != Arguments.Count)
4224 for (int i = 0; i < Arguments.Count; ++i)
4225 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
4240 //TODO: implement caching when it will be necessary
4241 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
4243 Constructor ctor = GetOverloadedConstructor (tc);
4247 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
4251 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
4255 public class ConstructorBaseInitializer : ConstructorInitializer {
4256 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4257 base (argument_list, pars, l)
4261 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
4262 if (parent_constructor == null)
4265 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
4266 if (type_ds == null) {
4267 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (parent_constructor);
4270 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (parent_constructor), loc);
4275 base.CheckObsoleteAttribute (type_ds, loc);
4280 public class ConstructorThisInitializer : ConstructorInitializer {
4281 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4282 base (argument_list, pars, l)
4287 public class Constructor : MethodCore, IMethodData {
4288 public ConstructorBuilder ConstructorBuilder;
4289 public ConstructorInitializer Initializer;
4290 ListDictionary declarative_security;
4293 // Modifiers allowed for a constructor.
4295 public const int AllowedModifiers =
4297 Modifiers.PROTECTED |
4298 Modifiers.INTERNAL |
4304 bool has_compliant_args = false;
4306 // The spec claims that static is not permitted, but
4307 // my very own code has static constructors.
4309 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4310 ConstructorInitializer init, Location l)
4311 : base (ds, null, null, mod, AllowedModifiers, false,
4312 new MemberName (name), null, args, l)
4317 public override string GetSignatureForError()
4319 if (ConstructorBuilder == null)
4320 return GetSignatureForError (Parent);
4322 return TypeManager.CSharpSignature (ConstructorBuilder);
4325 public bool HasCompliantArgs {
4327 return has_compliant_args;
4331 public override AttributeTargets AttributeTargets {
4333 return AttributeTargets.Constructor;
4339 // Returns true if this is a default constructor
4341 public bool IsDefault ()
4343 if ((ModFlags & Modifiers.STATIC) != 0)
4344 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4345 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4348 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4349 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4350 (Initializer is ConstructorBaseInitializer) &&
4351 (Initializer.Arguments == null);
4354 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4356 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4357 if (declarative_security == null) {
4358 declarative_security = new ListDictionary ();
4360 a.ExtractSecurityPermissionSet (declarative_security);
4364 ConstructorBuilder.SetCustomAttribute (cb);
4367 protected override bool CheckForDuplications ()
4369 ArrayList ar = Parent.InstanceConstructors;
4371 int arLen = ar.Count;
4373 for (int i = 0; i < arLen; i++) {
4374 Constructor m = (Constructor) ar [i];
4375 if (IsDuplicateImplementation (m))
4382 protected override bool CheckBase ()
4384 // Check whether arguments were correct.
4385 if (!DoDefineParameters ())
4388 // TODO: skip the rest for generated ctor
4389 if ((ModFlags & Modifiers.STATIC) != 0)
4392 if (!CheckForDuplications ())
4395 if (Parent.Kind == Kind.Struct) {
4396 if (ParameterTypes.Length == 0) {
4397 Report.Error (568, Location,
4398 "Structs can not contain explicit parameterless " +
4403 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4404 Report.Error (666, Location, "Protected member in struct declaration");
4409 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4410 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4417 // Creates the ConstructorBuilder
4419 public override bool Define ()
4421 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4422 MethodAttributes.SpecialName);
4424 if ((ModFlags & Modifiers.STATIC) != 0){
4425 ca |= MethodAttributes.Static | MethodAttributes.Private;
4427 ca |= MethodAttributes.HideBySig;
4429 if ((ModFlags & Modifiers.PUBLIC) != 0)
4430 ca |= MethodAttributes.Public;
4431 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4432 if ((ModFlags & Modifiers.INTERNAL) != 0)
4433 ca |= MethodAttributes.FamORAssem;
4435 ca |= MethodAttributes.Family;
4436 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4437 ca |= MethodAttributes.Assembly;
4438 else if (IsDefault ())
4439 ca |= MethodAttributes.Public;
4441 ca |= MethodAttributes.Private;
4444 // Check if arguments were correct.
4448 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4449 ca, CallingConventions,
4452 if ((ModFlags & Modifiers.UNSAFE) != 0)
4453 ConstructorBuilder.InitLocals = false;
4455 TypeManager.AddMethod (ConstructorBuilder, this);
4458 // HACK because System.Reflection.Emit is lame
4460 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4468 public override void Emit ()
4470 EmitContext ec = CreateEmitContext (null, null);
4473 // extern methods have no bodies
4475 if ((ModFlags & Modifiers.EXTERN) != 0) {
4476 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4478 179, Location, "External constructor `" +
4479 TypeManager.CSharpSignature (ConstructorBuilder) +
4480 "' can not have a body");
4483 } else if (block == null) {
4485 501, Location, "Constructor `" +
4486 TypeManager.CSharpSignature (ConstructorBuilder) +
4487 "' must declare a body since it is not marked extern");
4491 if ((ModFlags & Modifiers.STATIC) == 0){
4492 if (Parent.Kind == Kind.Class && Initializer == null)
4493 Initializer = new ConstructorBaseInitializer (
4494 null, Parameters.EmptyReadOnlyParameters, Location);
4498 // Spec mandates that Initializers will not have
4502 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4504 ec.IsStatic = false;
4507 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4509 SourceMethod source = SourceMethod.Create (
4510 Parent, ConstructorBuilder, block);
4513 // Classes can have base initializers and instance field initializers.
4515 if (Parent.Kind == Kind.Class){
4516 if ((ModFlags & Modifiers.STATIC) == 0){
4519 // If we use a "this (...)" constructor initializer, then
4520 // do not emit field initializers, they are initialized in the other constructor
4522 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4523 Parent.EmitFieldInitializers (ec);
4526 if (Initializer != null) {
4527 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4528 Initializer.CheckObsoleteAttribute (Parent, Location);
4530 ec.TestObsoleteMethodUsage = false;
4531 Initializer.Emit (ec);
4534 if ((ModFlags & Modifiers.STATIC) != 0)
4535 Parent.EmitFieldInitializers (ec);
4537 if (OptAttributes != null)
4538 OptAttributes.Emit (ec, this);
4540 // If this is a non-static `struct' constructor and doesn't have any
4541 // initializer, it must initialize all of the struct's fields.
4542 if ((Parent.Kind == Kind.Struct) &&
4543 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4544 Block.AddThisVariable (Parent, Location);
4546 ec.EmitTopBlock (block, ParameterInfo, Location);
4549 source.CloseMethod ();
4553 if (declarative_security != null) {
4554 foreach (DictionaryEntry de in declarative_security) {
4555 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4562 // Is never override
4563 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
4568 protected override bool VerifyClsCompliance (DeclSpace ds)
4570 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4574 if (parameter_types.Length > 0) {
4575 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4577 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4579 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4580 foreach (Type param in parameter_types) {
4581 if (param.IsArray) {
4587 has_compliant_args = true;
4591 #region IMethodData Members
4593 public System.Reflection.CallingConventions CallingConventions {
4595 CallingConventions cc = Parameters.GetCallingConvention ();
4597 if (Parent.Kind == Kind.Class)
4598 if ((ModFlags & Modifiers.STATIC) == 0)
4599 cc |= CallingConventions.HasThis;
4601 // FIXME: How is `ExplicitThis' used in C#?
4607 public new Location Location {
4609 return base.Location;
4613 public MemberName MethodName {
4619 public Type ReturnType {
4625 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4627 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4628 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4631 public ObsoleteAttribute GetObsoleteAttribute ()
4636 public bool IsExcluded(EmitContext ec)
4641 GenericMethod IMethodData.GenericMethod {
4651 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4653 public interface IMethodData
4655 CallingConventions CallingConventions { get; }
4656 Location Location { get; }
4657 MemberName MethodName { get; }
4658 Type[] ParameterTypes { get; }
4659 Type ReturnType { get; }
4660 GenericMethod GenericMethod { get; }
4662 Attributes OptAttributes { get; }
4663 ToplevelBlock Block { get; }
4665 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4666 ObsoleteAttribute GetObsoleteAttribute ();
4667 string GetSignatureForError (TypeContainer tc);
4668 bool IsExcluded (EmitContext ec);
4669 bool IsClsCompliaceRequired (DeclSpace ds);
4673 // Encapsulates most of the Method's state
4675 public class MethodData {
4677 readonly IMethodData method;
4680 // The return type of this method
4682 public readonly GenericMethod GenericMethod;
4683 public readonly InternalParameters ParameterInfo;
4686 // Are we implementing an interface ?
4688 public bool IsImplementing = false;
4693 protected MemberBase member;
4694 protected int modifiers;
4695 protected MethodAttributes flags;
4696 protected Type declaring_type;
4697 protected MethodInfo parent_method;
4701 MethodBuilder builder = null;
4702 public MethodBuilder MethodBuilder {
4708 public Type DeclaringType {
4710 return declaring_type;
4714 public MethodData (MemberBase member, InternalParameters parameters,
4715 int modifiers, MethodAttributes flags, IMethodData method)
4717 this.member = member;
4718 this.ParameterInfo = parameters;
4719 this.modifiers = modifiers;
4722 this.method = method;
4725 public MethodData (MemberBase member, InternalParameters parameters,
4726 int modifiers, MethodAttributes flags,
4727 IMethodData method, MethodBuilder builder,
4728 GenericMethod generic, MethodInfo parent_method)
4729 : this (member, parameters, modifiers, flags, method)
4731 this.builder = builder;
4732 this.GenericMethod = generic;
4733 this.parent_method = parent_method;
4736 static string RemoveArity (string name)
4739 StringBuilder sb = new StringBuilder ();
4740 while (start < name.Length) {
4741 int pos = name.IndexOf ('`', start);
4743 sb.Append (name.Substring (start));
4747 sb.Append (name.Substring (start, pos-start));
4750 while ((pos < name.Length) && Char.IsNumber (name [pos]))
4756 return sb.ToString ();
4759 public bool Define (TypeContainer container)
4761 MethodInfo implementing = null;
4764 if (member.IsExplicitImpl)
4765 prefix = member.InterfaceType.FullName + ".";
4769 string name = method.MethodName.Basename;
4770 string method_name = prefix + name;
4772 Type[] ParameterTypes = method.ParameterTypes;
4774 if (container.Pending != null){
4775 if (member is Indexer)
4776 implementing = container.Pending.IsInterfaceIndexer (
4777 member.InterfaceType, method.ReturnType, ParameterTypes);
4779 implementing = container.Pending.IsInterfaceMethod (
4780 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4782 if (member.InterfaceType != null){
4783 if (implementing == null){
4784 Report.Error (539, method.Location,
4785 "'{0}' in explicit interface declaration is not an interface", method_name);
4792 // For implicit implementations, make sure we are public, for
4793 // explicit implementations, make sure we are private.
4795 if (implementing != null){
4797 // Setting null inside this block will trigger a more
4798 // verbose error reporting for missing interface implementations
4800 // The "candidate" function has been flagged already
4801 // but it wont get cleared
4803 if (member.IsExplicitImpl){
4804 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4805 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4806 implementing = null;
4808 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4809 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4811 // If this is an interface method implementation,
4812 // check for public accessibility
4814 implementing = null;
4815 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4816 // We may never be private.
4817 implementing = null;
4818 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4820 // We may be protected if we're overriding something.
4822 implementing = null;
4827 // Static is not allowed
4829 if ((modifiers & Modifiers.STATIC) != 0){
4830 implementing = null;
4831 Modifiers.Error_InvalidModifier (method.Location, "static");
4836 // If implementing is still valid, set flags
4838 if (implementing != null){
4840 // When implementing interface methods, set NewSlot
4841 // unless, we are overwriting a method.
4843 if (implementing.DeclaringType.IsInterface){
4844 if ((modifiers & Modifiers.OVERRIDE) == 0)
4845 flags |= MethodAttributes.NewSlot;
4848 MethodAttributes.Virtual |
4849 MethodAttributes.HideBySig;
4851 // Set Final unless we're virtual, abstract or already overriding a method.
4852 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4853 flags |= MethodAttributes.Final;
4855 IsImplementing = true;
4858 EmitContext ec = method.CreateEmitContext (container, null);
4860 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4862 if (builder == null)
4865 if (container.CurrentType != null)
4866 declaring_type = container.CurrentType;
4868 declaring_type = container.TypeBuilder;
4870 if ((modifiers & Modifiers.UNSAFE) != 0)
4871 builder.InitLocals = false;
4873 if (IsImplementing){
4875 // clear the pending implemntation flag
4877 if (member is Indexer) {
4878 container.Pending.ImplementIndexer (
4879 member.InterfaceType, builder, method.ReturnType,
4880 ParameterTypes, member.IsExplicitImpl);
4882 container.Pending.ImplementMethod (
4883 member.InterfaceType, name, method.ReturnType,
4884 ParameterTypes, member.IsExplicitImpl);
4886 if (member.IsExplicitImpl)
4887 container.TypeBuilder.DefineMethodOverride (
4888 builder, implementing);
4892 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4893 TypeManager.AddMethod (builder, method);
4895 if (GenericMethod != null) {
4896 bool is_override = member.IsExplicitImpl |
4897 ((modifiers & Modifiers.OVERRIDE) != 0);
4899 if (implementing != null)
4900 parent_method = implementing;
4902 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
4910 /// Create the MethodBuilder for the method
4912 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4914 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4916 if ((modifiers & extern_static) == extern_static) {
4918 if (method.OptAttributes != null) {
4919 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4920 if (dllimport_attribute != null) {
4921 flags |= MethodAttributes.PinvokeImpl;
4922 builder = dllimport_attribute.DefinePInvokeMethod (
4923 ec, container.TypeBuilder, method_name, flags,
4924 method.ReturnType, ParameterTypes);
4930 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4931 // We are more strict than Microsoft and report CS0626 like error
4932 if (method.OptAttributes == null ||
4933 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4934 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", method.GetSignatureForError (container));
4939 if (builder == null)
4940 builder = container.TypeBuilder.DefineMethod (
4941 method_name, flags, method.CallingConventions,
4942 method.ReturnType, ParameterTypes);
4944 builder.SetGenericMethodSignature (
4945 flags, method.CallingConventions,
4946 method.ReturnType, ParameterTypes);
4952 public void Emit (TypeContainer container, Attributable kind)
4955 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4956 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4958 ec = method.CreateEmitContext (container, null);
4960 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container.Parent) != null)
4961 ec.TestObsoleteMethodUsage = false;
4963 Location loc = method.Location;
4964 Attributes OptAttributes = method.OptAttributes;
4966 if (OptAttributes != null)
4967 OptAttributes.Emit (ec, kind);
4969 if (member is MethodCore)
4970 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4972 SymbolWriter sw = CodeGen.SymbolWriter;
4973 ToplevelBlock block = method.Block;
4976 // abstract or extern methods have no bodies
4978 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4983 // abstract or extern methods have no bodies.
4985 if ((modifiers & Modifiers.ABSTRACT) != 0)
4987 500, method.Location, "Abstract method `" +
4988 TypeManager.CSharpSignature (builder) +
4989 "' can not have a body");
4991 if ((modifiers & Modifiers.EXTERN) != 0)
4993 179, method.Location, "External method `" +
4994 TypeManager.CSharpSignature (builder) +
4995 "' can not have a body");
5001 // Methods must have a body unless they're extern or abstract
5003 if (block == null) {
5005 501, method.Location, "Method `" +
5006 TypeManager.CSharpSignature (builder) +
5007 "' must declare a body since it is not marked " +
5008 "abstract or extern");
5012 SourceMethod source = SourceMethod.Create (
5013 container, MethodBuilder, method.Block);
5016 // Handle destructors specially
5018 // FIXME: This code generates buggy code
5020 if (member is Destructor)
5021 EmitDestructor (ec, block);
5023 ec.EmitTopBlock (block, ParameterInfo, loc);
5026 source.CloseMethod ();
5029 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5031 ILGenerator ig = ec.ig;
5033 Label finish = ig.DefineLabel ();
5035 block.SetDestructor ();
5037 ig.BeginExceptionBlock ();
5038 ec.ReturnLabel = finish;
5039 ec.HasReturnLabel = true;
5040 ec.EmitTopBlock (block, null, method.Location);
5042 // ig.MarkLabel (finish);
5043 ig.BeginFinallyBlock ();
5045 if (ec.ContainerType.BaseType != null) {
5046 Expression member_lookup = Expression.MemberLookup (
5047 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5048 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5050 if (member_lookup != null){
5051 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
5053 ig.Emit (OpCodes.Ldarg_0);
5054 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
5058 ig.EndExceptionBlock ();
5059 //ig.MarkLabel (ec.ReturnLabel);
5060 ig.Emit (OpCodes.Ret);
5064 public class Destructor : Method {
5066 public Destructor (TypeContainer ds, Expression return_type, int mod, string name,
5067 Parameters parameters, Attributes attrs, Location l)
5068 : base (ds, null, return_type, mod, false, new MemberName (name),
5069 parameters, attrs, l)
5072 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5074 if (a.Type == TypeManager.conditional_attribute_type) {
5075 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
5079 base.ApplyAttributeBuilder (a, cb);
5083 abstract public class MemberBase : MemberCore {
5084 public Expression Type;
5086 public MethodAttributes flags;
5088 protected readonly int explicit_mod_flags;
5091 // The "short" name of this property / indexer / event. This is the
5092 // name without the explicit interface.
5094 public string ShortName;
5097 // The type of this property / indexer / event
5099 public Type MemberType;
5102 // If true, this is an explicit interface implementation
5104 public bool IsExplicitImpl = false;
5107 // The name of the interface we are explicitly implementing
5109 public MemberName ExplicitInterfaceName = null;
5112 // Whether this is an interface member.
5114 public bool IsInterface;
5117 // If true, the interface type we are explicitly implementing
5119 public Type InterfaceType = null;
5122 // The constructor is only exposed to our children
5124 protected MemberBase (TypeContainer parent, Expression type, int mod,
5125 int allowed_mod, int def_mod, MemberName name,
5126 Attributes attrs, Location loc)
5127 : base (parent, name, attrs, loc)
5129 explicit_mod_flags = mod;
5131 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
5133 // Check for explicit interface implementation
5134 if (MemberName.Left != null) {
5135 ExplicitInterfaceName = MemberName.Left;
5136 ShortName = MemberName.Name;
5137 IsExplicitImpl = true;
5142 protected virtual bool CheckBase ()
5144 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
5145 Report.Error (666, Location, "Protected member in struct declaration");
5149 if ((RootContext.WarningLevel >= 4) &&
5150 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5151 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5152 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5153 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
5159 protected abstract bool CheckGenericOverride (MethodInfo method, string name);
5161 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
5165 foreach (Type partype in parameters){
5166 if (partype == TypeManager.void_type) {
5168 1547, Location, "Keyword 'void' cannot " +
5169 "be used in this context");
5173 if (partype.IsPointer){
5176 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5180 if (ds.AsAccessible (partype, ModFlags))
5183 if (this is Indexer)
5184 Report.Error (55, Location,
5185 "Inconsistent accessibility: parameter type `" +
5186 TypeManager.CSharpName (partype) + "' is less " +
5187 "accessible than indexer `" + Name + "'");
5188 else if ((this is Method) && ((Method) this).IsOperator)
5189 Report.Error (57, Location,
5190 "Inconsistent accessibility: parameter type `" +
5191 TypeManager.CSharpName (partype) + "' is less " +
5192 "accessible than operator `" + Name + "'");
5194 Report.Error (51, Location,
5195 "Inconsistent accessibility: parameter type `" +
5196 TypeManager.CSharpName (partype) + "' is less " +
5197 "accessible than method `" + Name + "'");
5204 protected virtual bool DoDefineBase ()
5206 EmitContext ec = Parent.EmitContext;
5208 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5211 throw new InternalErrorException ();
5214 ModFlags = Modifiers.PUBLIC |
5215 Modifiers.ABSTRACT |
5216 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5218 flags = MethodAttributes.Public |
5219 MethodAttributes.Abstract |
5220 MethodAttributes.HideBySig |
5221 MethodAttributes.NewSlot |
5222 MethodAttributes.Virtual;
5224 if (!Parent.MethodModifiersValid (ModFlags, Name, Location))
5227 flags = Modifiers.MethodAttr (ModFlags);
5233 protected virtual bool DoDefine (DeclSpace decl)
5235 EmitContext ec = decl.EmitContext;
5237 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5239 ec.InUnsafe = InUnsafe;
5241 // Lookup Type, verify validity
5242 bool old_unsafe = ec.InUnsafe;
5243 ec.InUnsafe = InUnsafe;
5244 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
5245 ec.InUnsafe = old_unsafe;
5250 MemberType = texpr.Type;
5252 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5253 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5254 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5259 // verify accessibility
5260 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5261 if (this is Property)
5262 Report.Error (53, Location,
5263 "Inconsistent accessibility: property type `" +
5264 TypeManager.CSharpName (MemberType) + "' is less " +
5265 "accessible than property `" + Name + "'");
5266 else if (this is Indexer)
5267 Report.Error (54, Location,
5268 "Inconsistent accessibility: indexer return type `" +
5269 TypeManager.CSharpName (MemberType) + "' is less " +
5270 "accessible than indexer `" + Name + "'");
5271 else if (this is Method) {
5272 if (((Method) this).IsOperator)
5273 Report.Error (56, Location,
5274 "Inconsistent accessibility: return type `" +
5275 TypeManager.CSharpName (MemberType) + "' is less " +
5276 "accessible than operator `" + Name + "'");
5278 Report.Error (50, Location,
5279 "Inconsistent accessibility: return type `" +
5280 TypeManager.CSharpName (MemberType) + "' is less " +
5281 "accessible than method `" + Name + "'");
5283 Report.Error (52, Location,
5284 "Inconsistent accessibility: field type `" +
5285 TypeManager.CSharpName (MemberType) + "' is less " +
5286 "accessible than field `" + Name + "'");
5290 if (MemberType.IsPointer && !UnsafeOK (Parent))
5293 if (IsExplicitImpl) {
5294 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
5295 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (ec);
5296 if (iface_texpr == null)
5299 InterfaceType = iface_texpr.Type;
5301 if (InterfaceType.IsClass) {
5302 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", ExplicitInterfaceName);
5306 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5309 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5316 /// The name of the member can be changed during definition (see IndexerName attribute)
5318 protected virtual void UpdateMemberName ()
5320 MemberName.Name = ShortName;
5323 public override string GetSignatureForError (TypeContainer tc)
5325 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5328 protected bool IsTypePermitted ()
5330 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5331 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5337 protected override bool VerifyClsCompliance(DeclSpace ds)
5339 if (base.VerifyClsCompliance (ds)) {
5343 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5344 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5349 protected override void VerifyObsoleteAttribute()
5351 CheckUsageOfObsoleteAttribute (MemberType);
5356 // Fields and Events both generate FieldBuilders, we use this to share
5357 // their common bits. This is also used to flag usage of the field
5359 abstract public class FieldBase : MemberBase {
5360 public FieldBuilder FieldBuilder;
5361 public Status status;
5364 public enum Status : byte {
5369 static string[] attribute_targets = new string [] { "field" };
5372 /// Symbol with same name in parent class/struct
5374 public MemberInfo conflict_symbol;
5377 // The constructor is only exposed to our children
5379 protected FieldBase (TypeContainer parent, Expression type, int mod,
5380 int allowed_mod, MemberName name, object init,
5381 Attributes attrs, Location loc)
5382 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5388 public override AttributeTargets AttributeTargets {
5390 return AttributeTargets.Field;
5394 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5396 if (a.Type == TypeManager.marshal_as_attr_type) {
5397 UnmanagedMarshal marshal = a.GetMarshal (this);
5398 if (marshal != null) {
5399 FieldBuilder.SetMarshal (marshal);
5404 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5405 a.Error_InvalidSecurityParent ();
5409 FieldBuilder.SetCustomAttribute (cb);
5413 // Whether this field has an initializer.
5415 public bool HasInitializer {
5417 return init != null;
5421 protected readonly Object init;
5423 Expression init_expr;
5424 bool init_expr_initialized = false;
5426 protected override bool CheckGenericOverride (MethodInfo method, string name)
5432 // Resolves and returns the field initializer.
5434 public Expression GetInitializerExpression (EmitContext ec)
5436 if (init_expr_initialized)
5440 if (init is Expression)
5441 e = (Expression) init;
5443 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5445 ec.IsFieldInitializer = true;
5446 e = e.DoResolve (ec);
5447 ec.IsFieldInitializer = false;
5450 init_expr_initialized = true;
5455 protected override bool CheckBase ()
5457 if (!base.CheckBase ())
5464 conflict_symbol = Parent.FindMemberWithSameName (Name, false);
5465 if (conflict_symbol == null) {
5466 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5467 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5472 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5473 Report.SymbolRelatedToPreviousError (conflict_symbol);
5474 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5480 protected override bool DoDefine (DeclSpace ds)
5482 if (!base.DoDefine (ds))
5485 if (MemberType == TypeManager.void_type) {
5486 Report.Error (1547, Location,
5487 "Keyword 'void' cannot be used in this context");
5493 public override string GetSignatureForError ()
5495 if (FieldBuilder == null) {
5496 return base.GetSignatureForError (Parent);
5498 return TypeManager.GetFullNameSignature (FieldBuilder);
5501 public override string[] ValidAttributeTargets {
5503 return attribute_targets;
5507 protected override bool VerifyClsCompliance (DeclSpace ds)
5509 if (!base.VerifyClsCompliance (ds))
5512 if (FieldBuilder == null) {
5516 if (!AttributeTester.IsClsCompliant (FieldBuilder.FieldType)) {
5517 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5523 public void SetAssigned ()
5525 status |= Status.ASSIGNED;
5529 public abstract class FieldMember: FieldBase
5531 bool has_field_offset = false;
5533 protected FieldMember (TypeContainer parent, Expression type, int mod,
5534 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5535 : base (parent, type, mod, allowed_mod, name, init, attrs, loc)
5539 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5541 if (a.Type == TypeManager.field_offset_attribute_type)
5543 has_field_offset = true;
5545 if (!Parent.HasExplicitLayout) {
5546 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5550 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5551 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5555 base.ApplyAttributeBuilder (a, cb);
5559 public override bool Define()
5561 EmitContext ec = Parent.EmitContext;
5563 throw new InternalErrorException ("FieldMember.Define called too early");
5565 bool old_unsafe = ec.InUnsafe;
5566 ec.InUnsafe = InUnsafe;
5567 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
5568 ec.InUnsafe = old_unsafe;
5572 MemberType = texpr.Type;
5577 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5578 Report.Error (52, Location,
5579 "Inconsistent accessibility: field type `" +
5580 TypeManager.CSharpName (MemberType) + "' is less " +
5581 "accessible than field `" + Name + "'");
5585 if (!IsTypePermitted ())
5588 if (MemberType.IsPointer && !UnsafeOK (Parent))
5594 public override void Emit ()
5596 if (Parent.HasExplicitLayout && !has_field_offset && (ModFlags & Modifiers.STATIC) == 0) {
5597 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5605 // The Field class is used to represents class/struct fields during parsing.
5607 public class Field : FieldMember {
5609 // Modifiers allowed in a class declaration
5611 const int AllowedModifiers =
5614 Modifiers.PROTECTED |
5615 Modifiers.INTERNAL |
5618 Modifiers.VOLATILE |
5622 public Field (TypeContainer parent, Expression type, int mod, string name,
5623 Object expr_or_array_init, Attributes attrs, Location loc)
5624 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5625 expr_or_array_init, attrs, loc)
5629 public override bool Define ()
5631 if (!base.Define ())
5634 if (RootContext.WarningLevel > 1){
5635 Type ptype = Parent.TypeBuilder.BaseType;
5637 // ptype is only null for System.Object while compiling corlib.
5639 TypeContainer.FindMembers (
5640 ptype, MemberTypes.Method,
5641 BindingFlags.Public |
5642 BindingFlags.Static | BindingFlags.Instance,
5643 System.Type.FilterName, Name);
5647 if ((ModFlags & Modifiers.VOLATILE) != 0){
5648 if (!MemberType.IsClass){
5649 Type vt = MemberType;
5651 if (TypeManager.IsEnumType (vt))
5652 vt = TypeManager.EnumToUnderlying (MemberType);
5654 if (!((vt == TypeManager.bool_type) ||
5655 (vt == TypeManager.sbyte_type) ||
5656 (vt == TypeManager.byte_type) ||
5657 (vt == TypeManager.short_type) ||
5658 (vt == TypeManager.ushort_type) ||
5659 (vt == TypeManager.int32_type) ||
5660 (vt == TypeManager.uint32_type) ||
5661 (vt == TypeManager.char_type) ||
5662 (vt == TypeManager.float_type) ||
5663 (!vt.IsValueType))){
5665 677, Location, Parent.MakeName (Name) +
5666 " A volatile field can not be of type `" +
5667 TypeManager.CSharpName (vt) + "'");
5672 if ((ModFlags & Modifiers.READONLY) != 0){
5675 "A field can not be both volatile and readonly");
5680 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5682 if (Parent.Kind == Kind.Struct &&
5683 ((fa & FieldAttributes.Static) == 0) &&
5684 MemberType == Parent.TypeBuilder &&
5685 !TypeManager.IsBuiltinType (MemberType)){
5686 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5687 "' causes a cycle in the structure layout");
5692 FieldBuilder = Parent.TypeBuilder.DefineField (
5693 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5695 TypeManager.RegisterFieldBase (FieldBuilder, this);
5697 catch (ArgumentException) {
5698 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5705 public override void Emit ()
5707 if (OptAttributes != null) {
5708 EmitContext ec = new EmitContext (
5709 Parent, Location, null, FieldBuilder.FieldType,
5711 OptAttributes.Emit (ec, this);
5719 // `set' and `get' accessors are represented with an Accessor.
5721 public class Accessor {
5723 // Null if the accessor is empty, or a Block if not
5725 public const int AllowedModifiers =
5727 Modifiers.PROTECTED |
5728 Modifiers.INTERNAL |
5731 public ToplevelBlock Block;
5732 public Attributes Attributes;
5733 public Location Location;
5734 public int ModFlags;
5736 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5741 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5746 // Ooouh Martin, templates are missing here.
5747 // When it will be possible move here a lot of child code and template method type.
5748 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5749 protected MethodData method_data;
5750 protected ToplevelBlock block;
5751 protected ListDictionary declarative_security;
5753 // The accessor are created event if they are not wanted.
5754 // But we need them because their names are reserved.
5755 // Field says whether accessor will be emited or not
5756 public readonly bool IsDummy;
5758 protected readonly string prefix;
5760 ReturnParameter return_attributes;
5762 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5763 : base (null, SetupName (prefix, member), null, member.Location)
5765 this.prefix = prefix;
5769 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5771 : base (null, SetupName (prefix, member),
5772 accessor.Attributes, accessor.Location)
5774 this.prefix = prefix;
5775 this.block = accessor.Block;
5778 static MemberName SetupName (string prefix, MemberBase member)
5780 MemberName name = member.MemberName.Clone ();
5781 name.Name = prefix + member.ShortName;
5785 public void UpdateName (MemberBase member)
5787 MemberName.Name = prefix + member.ShortName;
5790 #region IMethodData Members
5792 public ToplevelBlock Block {
5802 public CallingConventions CallingConventions {
5804 return CallingConventions.Standard;
5808 public bool IsExcluded (EmitContext ec)
5813 GenericMethod IMethodData.GenericMethod {
5819 public MemberName MethodName {
5825 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5826 public abstract Type[] ParameterTypes { get; }
5827 public abstract Type ReturnType { get; }
5828 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5832 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5834 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5835 a.Type == TypeManager.conditional_attribute_type) {
5836 Report.Error (1667, a.Location, "'{0}' is not valid on property or event accessors. It is valid on '{1}' declarations only", TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5840 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5841 if (declarative_security == null)
5842 declarative_security = new ListDictionary ();
5843 a.ExtractSecurityPermissionSet (declarative_security);
5847 if (a.Target == AttributeTargets.Method) {
5848 method_data.MethodBuilder.SetCustomAttribute (cb);
5852 if (a.Target == AttributeTargets.ReturnValue) {
5853 if (return_attributes == null)
5854 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5856 return_attributes.ApplyAttributeBuilder (a, cb);
5860 ApplyToExtraTarget (a, cb);
5863 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5865 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5868 public override bool Define()
5873 public virtual void Emit (TypeContainer container)
5875 method_data.Emit (container, this);
5877 if (declarative_security != null) {
5878 foreach (DictionaryEntry de in declarative_security) {
5879 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5886 public override bool IsClsCompliaceRequired(DeclSpace ds)
5891 public bool IsDuplicateImplementation (MethodCore method)
5893 if (Name != method.Name)
5896 Type[] param_types = method.ParameterTypes;
5898 if (param_types.Length != ParameterTypes.Length)
5901 for (int i = 0; i < param_types.Length; i++)
5902 if (param_types [i] != ParameterTypes [i])
5905 Report.SymbolRelatedToPreviousError (method);
5906 Report.Error (111, Location, "Type '{0}' already defines a member called '{1}' with " +
5907 "the same parameter types", Parent.Name, Name);
5911 public new Location Location {
5913 return base.Location;
5917 protected override void VerifyObsoleteAttribute()
5924 // Properties and Indexers both generate PropertyBuilders, we use this to share
5925 // their common bits.
5927 abstract public class PropertyBase : MethodCore {
5929 public class GetMethod: PropertyMethod
5931 static string[] attribute_targets = new string [] { "method", "return" };
5933 public GetMethod (MethodCore method):
5934 base (method, "get_")
5938 public GetMethod (MethodCore method, Accessor accessor):
5939 base (method, accessor, "get_")
5943 public override MethodBuilder Define(TypeContainer container)
5945 base.Define (container);
5947 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5949 if (!method_data.Define (container))
5952 return method_data.MethodBuilder;
5955 public override string GetSignatureForError (TypeContainer tc)
5957 return String.Concat (base.GetSignatureForError (tc), ".get");
5960 public override Type ReturnType {
5962 return method.MemberType;
5966 public override string[] ValidAttributeTargets {
5968 return attribute_targets;
5973 public class SetMethod: PropertyMethod {
5975 static string[] attribute_targets = new string [] { "method", "param", "return" };
5976 ImplicitParameter param_attr;
5978 public SetMethod (MethodCore method):
5979 base (method, "set_")
5983 public SetMethod (MethodCore method, Accessor accessor):
5984 base (method, accessor, "set_")
5988 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5990 if (a.Target == AttributeTargets.Parameter) {
5991 if (param_attr == null)
5992 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5994 param_attr.ApplyAttributeBuilder (a, cb);
5998 base.ApplyAttributeBuilder (a, cb);
6001 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
6003 Parameter [] parms = new Parameter [1];
6004 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
6005 Parameters parameters = new Parameters (parms, null, method.Location);
6006 Type [] types = parameters.GetParameterInfo (ec);
6007 return new InternalParameters (types, parameters);
6010 public override MethodBuilder Define(TypeContainer container)
6012 if (container.EmitContext == null)
6013 throw new InternalErrorException ("SetMethod.Define called too early");
6015 base.Define (container);
6017 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6019 if (!method_data.Define (container))
6022 return method_data.MethodBuilder;
6025 public override string GetSignatureForError (TypeContainer tc)
6027 return String.Concat (base.GetSignatureForError (tc), ".set");
6030 public override Type[] ParameterTypes {
6032 return new Type[] { method.MemberType };
6036 public override Type ReturnType {
6038 return TypeManager.void_type;
6042 public override string[] ValidAttributeTargets {
6044 return attribute_targets;
6049 static string[] attribute_targets = new string [] { "property" };
6051 public abstract class PropertyMethod: AbstractPropertyEventMethod {
6052 protected readonly MethodCore method;
6053 protected MethodAttributes flags;
6055 public PropertyMethod (MethodCore method, string prefix)
6056 : base (method, prefix)
6058 this.method = method;
6061 public PropertyMethod (MethodCore method, Accessor accessor, string prefix)
6062 : base (method, accessor, prefix)
6064 this.method = method;
6065 this.ModFlags = accessor.ModFlags;
6067 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6068 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
6069 Environment.Exit (1);
6073 public override AttributeTargets AttributeTargets {
6075 return AttributeTargets.Method;
6079 public override bool IsClsCompliaceRequired(DeclSpace ds)
6081 return method.IsClsCompliaceRequired (ds);
6084 public InternalParameters ParameterInfo
6087 return method_data.ParameterInfo;
6091 public virtual MethodBuilder Define (TypeContainer container)
6094 // Check for custom access modifier
6096 if (ModFlags == 0) {
6097 ModFlags = method.ModFlags;
6098 flags = method.flags;
6100 CheckModifiers (container, ModFlags);
6101 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6102 flags = Modifiers.MethodAttr (ModFlags);
6103 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6110 public override Type[] ParameterTypes {
6112 return TypeManager.NoTypes;
6116 public override EmitContext CreateEmitContext (TypeContainer tc,
6119 return new EmitContext (
6120 tc, method.ds, method.Location, ig, ReturnType,
6121 method.ModFlags, false);
6124 public override ObsoleteAttribute GetObsoleteAttribute ()
6126 return method.GetObsoleteAttribute (method.ds);
6129 public override string GetSignatureForError (TypeContainer tc)
6131 return String.Concat (tc.Name, '.', method.Name);
6134 void CheckModifiers (TypeContainer container, int modflags)
6137 int mflags = method.ModFlags & Modifiers.Accessibility;
6139 if ((mflags & Modifiers.PUBLIC) != 0) {
6140 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6142 else if ((mflags & Modifiers.PROTECTED) != 0) {
6143 if ((mflags & Modifiers.INTERNAL) != 0)
6144 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6146 flags |= Modifiers.PRIVATE;
6148 else if ((mflags & Modifiers.INTERNAL) != 0)
6149 flags |= Modifiers.PRIVATE;
6151 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6152 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6153 GetSignatureForError (container));
6157 public PropertyMethod Get, Set;
6158 public PropertyBuilder PropertyBuilder;
6159 public MethodBuilder GetBuilder, SetBuilder;
6161 protected EmitContext ec;
6163 public PropertyBase (TypeContainer parent, Expression type, int mod_flags,
6164 int allowed_mod, bool is_iface, MemberName name,
6165 Parameters parameters, Attributes attrs,
6167 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6168 attrs, parameters, loc)
6172 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6174 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6175 a.Error_InvalidSecurityParent ();
6179 PropertyBuilder.SetCustomAttribute (cb);
6182 public override AttributeTargets AttributeTargets {
6184 return AttributeTargets.Property;
6188 public override bool Define ()
6190 if (!DoDefine (Parent))
6193 if (!IsTypePermitted ())
6199 protected override bool DoDefine (DeclSpace ds)
6201 if (!base.DoDefine (ds))
6205 // Accessors modifiers check
6207 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6208 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6209 GetSignatureForError ());
6213 if ((Get.IsDummy || Set.IsDummy)
6214 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6215 Report.Error (276, Location,
6216 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6217 GetSignatureForError ());
6221 if (MemberType.IsAbstract && MemberType.IsSealed) {
6222 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6226 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6230 public override string GetSignatureForError()
6232 if (PropertyBuilder == null)
6233 return GetSignatureForError (Parent);
6235 return TypeManager.CSharpSignature (PropertyBuilder, false);
6239 protected override bool CheckForDuplications ()
6241 ArrayList ar = Parent.Indexers;
6243 int arLen = ar.Count;
6245 for (int i = 0; i < arLen; i++) {
6246 Indexer m = (Indexer) ar [i];
6247 if (IsDuplicateImplementation (m))
6252 ar = Parent.Properties;
6254 int arLen = ar.Count;
6256 for (int i = 0; i < arLen; i++) {
6257 Property m = (Property) ar [i];
6258 if (IsDuplicateImplementation (m))
6266 // TODO: rename to Resolve......
6267 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
6269 PropertyInfo parent_property = container.ParentCache.FindMemberToOverride (
6270 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6272 if (parent_property == null)
6275 parent_ret_type = parent_property.PropertyType;
6276 MethodInfo get_accessor = parent_property.GetGetMethod (true);
6277 MethodInfo set_accessor = parent_property.GetSetMethod (true);
6278 MethodAttributes get_accessor_access, set_accessor_access;
6280 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6281 if (Get != null && !Get.IsDummy && get_accessor == null) {
6282 Report.SymbolRelatedToPreviousError (parent_property);
6283 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
6286 if (Set != null && !Set.IsDummy && set_accessor == null) {
6287 Report.SymbolRelatedToPreviousError (parent_property);
6288 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
6293 // Check parent accessors access
6295 get_accessor_access = set_accessor_access = 0;
6296 if ((ModFlags & Modifiers.NEW) == 0) {
6297 if (get_accessor != null) {
6298 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6299 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6301 if (!Get.IsDummy && (get_accessor_access) !=
6302 (get_flags & MethodAttributes.MemberAccessMask))
6303 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6304 GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
6307 if (set_accessor != null) {
6308 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6309 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6311 if (!Set.IsDummy & (set_accessor_access) !=
6312 (set_flags & MethodAttributes.MemberAccessMask))
6313 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6314 GetSignatureForError (container), TypeManager.GetFullNameSignature (parent_property));
6319 // Get the less restrictive access
6321 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6324 public override void Emit ()
6327 // The PropertyBuilder can be null for explicit implementations, in that
6328 // case, we do not actually emit the ".property", so there is nowhere to
6329 // put the attribute
6331 if (PropertyBuilder != null && OptAttributes != null)
6332 OptAttributes.Emit (ec, this);
6344 /// Tests whether accessors are not in collision with some method (CS0111)
6346 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6348 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6351 protected override void UpdateMemberName ()
6353 base.UpdateMemberName ();
6355 Get.UpdateName (this);
6356 Set.UpdateName (this);
6360 public override string[] ValidAttributeTargets {
6362 return attribute_targets;
6367 public class Property : PropertyBase, IIteratorContainer {
6368 const int AllowedModifiers =
6371 Modifiers.PROTECTED |
6372 Modifiers.INTERNAL |
6376 Modifiers.OVERRIDE |
6377 Modifiers.ABSTRACT |
6380 Modifiers.METHOD_YIELDS |
6383 const int AllowedInterfaceModifiers =
6386 public Property (TypeContainer parent, Expression type, int mod_flags,
6387 bool is_iface, MemberName name, Attributes attrs,
6388 Accessor get_block, Accessor set_block, Location loc)
6389 : base (parent, type, mod_flags,
6390 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6391 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6394 if (get_block == null)
6395 Get = new GetMethod (this);
6397 Get = new GetMethod (this, get_block);
6399 if (set_block == null)
6400 Set = new SetMethod (this);
6402 Set = new SetMethod (this, set_block);
6405 public override bool Define ()
6407 if (!DoDefineBase ())
6410 if (!base.Define ())
6416 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6420 GetBuilder = Get.Define (Parent);
6421 if (GetBuilder == null)
6425 // Setup iterator if we are one
6427 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6428 Iterator iterator = new Iterator (
6429 Parent, "get", MemberType,
6430 TypeManager.NoTypes, Get.ParameterInfo,
6431 ModFlags, Get.Block, Location);
6433 if (!iterator.DefineIterator ())
6435 Get.Block = iterator.Block;
6440 SetBuilder = Set.Define (Parent);
6441 if (SetBuilder == null)
6444 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6447 // FIXME - PropertyAttributes.HasDefault ?
6449 PropertyAttributes prop_attr = PropertyAttributes.None;
6451 prop_attr |= PropertyAttributes.RTSpecialName |
6452 PropertyAttributes.SpecialName;
6454 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6455 Name, prop_attr, MemberType, null);
6458 PropertyBuilder.SetGetMethod (GetBuilder);
6461 PropertyBuilder.SetSetMethod (SetBuilder);
6463 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6467 public void SetYields ()
6469 ModFlags |= Modifiers.METHOD_YIELDS;
6474 /// Gigantic workaround for lameness in SRE follows :
6475 /// This class derives from EventInfo and attempts to basically
6476 /// wrap around the EventBuilder so that FindMembers can quickly
6477 /// return this in it search for members
6479 public class MyEventBuilder : EventInfo {
6482 // We use this to "point" to our Builder which is
6483 // not really a MemberInfo
6485 EventBuilder MyBuilder;
6488 // We "catch" and wrap these methods
6490 MethodInfo raise, remove, add;
6492 EventAttributes attributes;
6493 Type declaring_type, reflected_type, event_type;
6498 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6500 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6502 // And now store the values in our own fields.
6504 declaring_type = type_builder;
6506 reflected_type = type_builder;
6508 attributes = event_attr;
6511 this.event_type = event_type;
6515 // Methods that you have to override. Note that you only need
6516 // to "implement" the variants that take the argument (those are
6517 // the "abstract" methods, the others (GetAddMethod()) are
6520 public override MethodInfo GetAddMethod (bool nonPublic)
6525 public override MethodInfo GetRemoveMethod (bool nonPublic)
6530 public override MethodInfo GetRaiseMethod (bool nonPublic)
6536 // These methods make "MyEventInfo" look like a Builder
6538 public void SetRaiseMethod (MethodBuilder raiseMethod)
6540 raise = raiseMethod;
6541 MyBuilder.SetRaiseMethod (raiseMethod);
6544 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6546 remove = removeMethod;
6547 MyBuilder.SetRemoveOnMethod (removeMethod);
6550 public void SetAddOnMethod (MethodBuilder addMethod)
6553 MyBuilder.SetAddOnMethod (addMethod);
6556 public void SetCustomAttribute (CustomAttributeBuilder cb)
6558 MyBuilder.SetCustomAttribute (cb);
6561 public override object [] GetCustomAttributes (bool inherit)
6563 // FIXME : There's nothing which can be seemingly done here because
6564 // we have no way of getting at the custom attribute objects of the
6569 public override object [] GetCustomAttributes (Type t, bool inherit)
6571 // FIXME : Same here !
6575 public override bool IsDefined (Type t, bool b)
6580 public override EventAttributes Attributes {
6586 public override string Name {
6592 public override Type DeclaringType {
6594 return declaring_type;
6598 public override Type ReflectedType {
6600 return reflected_type;
6604 public Type EventType {
6610 public void SetUsed ()
6612 if (my_event != null)
6613 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6618 /// For case when event is declared like property (with add and remove accessors).
6620 public class EventProperty: Event {
6622 static string[] attribute_targets = new string [] { "event", "property" };
6624 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6625 bool is_iface, MemberName name, Object init,
6626 Attributes attrs, Accessor add, Accessor remove,
6628 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6630 Add = new AddDelegateMethod (this, add);
6631 Remove = new RemoveDelegateMethod (this, remove);
6634 public override string[] ValidAttributeTargets {
6636 return attribute_targets;
6642 /// Event is declared like field.
6644 public class EventField: Event {
6646 static string[] attribute_targets = new string [] { "event", "field", "method" };
6648 public EventField (TypeContainer parent, Expression type, int mod_flags,
6649 bool is_iface, MemberName name, Object init,
6650 Attributes attrs, Location loc)
6651 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6653 Add = new AddDelegateMethod (this);
6654 Remove = new RemoveDelegateMethod (this);
6657 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6659 if (a.Target == AttributeTargets.Field) {
6660 FieldBuilder.SetCustomAttribute (cb);
6664 if (a.Target == AttributeTargets.Method) {
6665 AddBuilder.SetCustomAttribute (cb);
6666 RemoveBuilder.SetCustomAttribute (cb);
6670 base.ApplyAttributeBuilder (a, cb);
6673 public override string[] ValidAttributeTargets {
6675 return attribute_targets;
6680 public abstract class Event : FieldBase {
6682 protected sealed class AddDelegateMethod: DelegateMethod
6685 public AddDelegateMethod (Event method):
6686 base (method, "add_")
6690 public AddDelegateMethod (Event method, Accessor accessor):
6691 base (method, accessor, "add_")
6695 protected override MethodInfo DelegateMethodInfo {
6697 return TypeManager.delegate_combine_delegate_delegate;
6703 protected sealed class RemoveDelegateMethod: DelegateMethod
6705 public RemoveDelegateMethod (Event method):
6706 base (method, "remove_")
6710 public RemoveDelegateMethod (Event method, Accessor accessor):
6711 base (method, accessor, "remove_")
6715 protected override MethodInfo DelegateMethodInfo {
6717 return TypeManager.delegate_remove_delegate_delegate;
6723 public abstract class DelegateMethod: AbstractPropertyEventMethod
6725 protected readonly Event method;
6726 ImplicitParameter param_attr;
6728 static string[] attribute_targets = new string [] { "method", "param", "return" };
6730 public DelegateMethod (Event method, string prefix)
6731 : base (method, prefix)
6733 this.method = method;
6736 public DelegateMethod (Event method, Accessor accessor, string prefix)
6737 : base (method, accessor, prefix)
6739 this.method = method;
6742 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6744 if (a.Target == AttributeTargets.Parameter) {
6745 if (param_attr == null)
6746 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6748 param_attr.ApplyAttributeBuilder (a, cb);
6752 base.ApplyAttributeBuilder (a, cb);
6755 public override AttributeTargets AttributeTargets {
6757 return AttributeTargets.Method;
6761 public override bool IsClsCompliaceRequired(DeclSpace ds)
6763 return method.IsClsCompliaceRequired (ds);
6766 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6768 method_data = new MethodData (method, ip, method.ModFlags,
6769 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6771 if (!method_data.Define (container))
6774 MethodBuilder mb = method_data.MethodBuilder;
6775 mb.DefineParameter (1, ParameterAttributes.None, "value");
6780 public override void Emit (TypeContainer tc)
6782 if (block != null) {
6787 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6788 EmitContext ec = CreateEmitContext (tc, ig);
6789 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6791 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6792 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6793 ig.Emit (OpCodes.Ldsfld, field_info);
6794 ig.Emit (OpCodes.Ldarg_0);
6795 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6796 ig.Emit (OpCodes.Castclass, method.MemberType);
6797 ig.Emit (OpCodes.Stsfld, field_info);
6799 ig.Emit (OpCodes.Ldarg_0);
6800 ig.Emit (OpCodes.Ldarg_0);
6801 ig.Emit (OpCodes.Ldfld, field_info);
6802 ig.Emit (OpCodes.Ldarg_1);
6803 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6804 ig.Emit (OpCodes.Castclass, method.MemberType);
6805 ig.Emit (OpCodes.Stfld, field_info);
6807 ig.Emit (OpCodes.Ret);
6810 protected abstract MethodInfo DelegateMethodInfo { get; }
6812 public override Type[] ParameterTypes {
6814 return new Type[] { method.MemberType };
6818 public override Type ReturnType {
6820 return TypeManager.void_type;
6824 public override EmitContext CreateEmitContext (TypeContainer tc,
6827 return new EmitContext (
6828 tc, method.Parent, Location, ig, ReturnType,
6829 method.ModFlags, false);
6832 public override string GetSignatureForError (TypeContainer tc)
6834 return String.Concat (tc.Name, '.', method.Name);
6837 public override ObsoleteAttribute GetObsoleteAttribute ()
6839 return method.GetObsoleteAttribute (method.Parent);
6842 public override string[] ValidAttributeTargets {
6844 return attribute_targets;
6850 const int AllowedModifiers =
6853 Modifiers.PROTECTED |
6854 Modifiers.INTERNAL |
6859 Modifiers.OVERRIDE |
6863 const int AllowedInterfaceModifiers =
6866 public DelegateMethod Add, Remove;
6867 public MyEventBuilder EventBuilder;
6868 public MethodBuilder AddBuilder, RemoveBuilder;
6870 MethodData AddData, RemoveData;
6872 public Event (TypeContainer parent, Expression type, int mod_flags,
6873 bool is_iface, MemberName name, Object init, Attributes attrs,
6875 : base (parent, type, mod_flags,
6876 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6877 name, init, attrs, loc)
6879 IsInterface = is_iface;
6882 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6884 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6885 a.Error_InvalidSecurityParent ();
6889 EventBuilder.SetCustomAttribute (cb);
6892 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6894 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6897 public override AttributeTargets AttributeTargets {
6899 return AttributeTargets.Event;
6903 public override bool Define ()
6905 EventAttributes e_attr;
6906 e_attr = EventAttributes.None;
6908 if (!DoDefineBase ())
6911 if (!DoDefine (Parent))
6914 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6915 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6916 "': abstract event can not have an initializer");
6920 if (!TypeManager.IsDelegateType (MemberType)) {
6921 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6922 "' : event must be of a delegate type");
6926 EmitContext ec = Parent.EmitContext;
6928 throw new InternalErrorException ("Event.Define called too early?");
6929 bool old_unsafe = ec.InUnsafe;
6930 ec.InUnsafe = InUnsafe;
6932 Parameter [] parms = new Parameter [1];
6933 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6934 Parameters parameters = new Parameters (parms, null, Location);
6935 Type [] types = parameters.GetParameterInfo (ec);
6936 InternalParameters ip = new InternalParameters (types, parameters);
6938 ec.InUnsafe = old_unsafe;
6944 // Now define the accessors
6947 AddBuilder = Add.Define (Parent, ip);
6948 if (AddBuilder == null)
6951 RemoveBuilder = Remove.Define (Parent, ip);
6952 if (RemoveBuilder == null)
6955 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6957 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6958 FieldBuilder = Parent.TypeBuilder.DefineField (
6960 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6961 TypeManager.RegisterPrivateFieldOfEvent (
6962 (EventInfo) EventBuilder, FieldBuilder);
6963 TypeManager.RegisterFieldBase (FieldBuilder, this);
6966 EventBuilder.SetAddOnMethod (AddBuilder);
6967 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6969 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6973 protected override bool CheckBase ()
6975 if (!base.CheckBase ())
6978 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6979 if (!(conflict_symbol is EventInfo)) {
6980 Report.SymbolRelatedToPreviousError (conflict_symbol);
6981 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6989 public override void Emit ()
6991 if (OptAttributes != null) {
6992 EmitContext ec = new EmitContext (
6993 Parent, Location, null, MemberType, ModFlags);
6994 OptAttributes.Emit (ec, this);
6999 Remove.Emit (Parent);
7005 public override string GetSignatureForError ()
7007 if (EventBuilder == null)
7008 return base.GetSignatureForError (Parent);
7010 return TypeManager.GetFullNameSignature (EventBuilder);
7015 public class Indexer : PropertyBase {
7017 class GetIndexerMethod: GetMethod
7019 public GetIndexerMethod (MethodCore method):
7024 public GetIndexerMethod (MethodCore method, Accessor accessor):
7025 base (method, accessor)
7029 public override Type[] ParameterTypes {
7031 return method.ParameterTypes;
7036 class SetIndexerMethod: SetMethod
7038 readonly Parameters parameters;
7040 public SetIndexerMethod (MethodCore method):
7045 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7046 base (method, accessor)
7048 this.parameters = parameters;
7051 public override Type[] ParameterTypes {
7053 int top = method.ParameterTypes.Length;
7054 Type [] set_pars = new Type [top + 1];
7055 method.ParameterTypes.CopyTo (set_pars, 0);
7056 set_pars [top] = method.MemberType;
7061 protected override InternalParameters GetParameterInfo (EmitContext ec)
7063 Parameter [] fixed_parms = parameters.FixedParameters;
7065 if (fixed_parms == null){
7066 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7067 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7068 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7070 // Here is the problem: the `value' parameter has
7071 // to come *after* the array parameter in the declaration
7073 // X (object [] x, Type value)
7076 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7077 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7081 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7083 fixed_parms.CopyTo (tmp, 0);
7084 tmp [fixed_parms.Length] = new Parameter (
7085 method.Type, "value", Parameter.Modifier.NONE, null);
7087 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
7088 Type [] types = set_formal_params.GetParameterInfo (ec);
7090 return new InternalParameters (types, set_formal_params);
7094 const int AllowedModifiers =
7097 Modifiers.PROTECTED |
7098 Modifiers.INTERNAL |
7102 Modifiers.OVERRIDE |
7107 const int AllowedInterfaceModifiers =
7111 // Are we implementing an interface ?
7113 public Indexer (TypeContainer parent, Expression type, MemberName name, int mod,
7114 bool is_iface, Parameters parameters, Attributes attrs,
7115 Accessor get_block, Accessor set_block, Location loc)
7116 : base (parent, type, mod,
7117 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7118 is_iface, name, parameters, attrs, loc)
7120 if (get_block == null)
7121 Get = new GetIndexerMethod (this);
7123 Get = new GetIndexerMethod (this, get_block);
7125 if (set_block == null)
7126 Set = new SetIndexerMethod (this);
7128 Set = new SetIndexerMethod (this, parameters, set_block);
7131 public override bool Define ()
7133 PropertyAttributes prop_attr =
7134 PropertyAttributes.RTSpecialName |
7135 PropertyAttributes.SpecialName;
7137 if (!DoDefineBase ())
7140 if (!base.Define ())
7143 if (OptAttributes != null) {
7144 Attribute indexer_attr = OptAttributes.GetIndexerNameAttribute (ec);
7145 if (indexer_attr != null) {
7146 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7148 if (IsExplicitImpl) {
7149 Report.Error (415, indexer_attr.Location,
7150 "The 'IndexerName' attribute is valid only on an" +
7151 "indexer that is not an explicit interface member declaration");
7155 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7156 Report.Error (609, indexer_attr.Location,
7157 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7161 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7162 Report.Error (633, indexer_attr.Location,
7163 "The argument to the 'IndexerName' attribute must be a valid identifier");
7167 UpdateMemberName ();
7171 if (InterfaceType != null) {
7172 string parent_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7173 if (parent_IndexerName != Name)
7174 ShortName = parent_IndexerName;
7175 UpdateMemberName ();
7178 if (!Parent.AddToMemberContainer (this, true) ||
7179 !Parent.AddToMemberContainer (Get, true) || !Parent.AddToMemberContainer (Set, true))
7185 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7187 GetBuilder = Get.Define (Parent);
7188 if (GetBuilder == null)
7193 SetBuilder = Set.Define (Parent);
7194 if (SetBuilder == null)
7199 // Now name the parameters
7201 Parameter [] p = Parameters.FixedParameters;
7203 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7204 Report.Error (631, Location, "ref and out are not valid in this context");
7210 for (i = 0; i < p.Length; ++i) {
7212 GetBuilder.DefineParameter (
7213 i + 1, p [i].Attributes, p [i].Name);
7216 SetBuilder.DefineParameter (
7217 i + 1, p [i].Attributes, p [i].Name);
7221 SetBuilder.DefineParameter (
7222 i + 1, ParameterAttributes.None, "value");
7224 if (i != ParameterTypes.Length) {
7225 Parameter array_param = Parameters.ArrayParameter;
7227 SetBuilder.DefineParameter (
7228 i + 1, array_param.Attributes, array_param.Name);
7232 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7233 Name, prop_attr, MemberType, ParameterTypes);
7236 PropertyBuilder.SetGetMethod (GetBuilder);
7239 PropertyBuilder.SetSetMethod (SetBuilder);
7241 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7246 public override string GetSignatureForError ()
7248 if (PropertyBuilder == null)
7249 return GetSignatureForError (Parent);
7251 return TypeManager.CSharpSignature (PropertyBuilder, true);
7254 public override string GetSignatureForError(TypeContainer tc)
7256 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7260 public class Operator : MethodCore, IIteratorContainer {
7262 const int AllowedModifiers =
7268 public enum OpType : byte {
7278 // Unary and Binary operators
7301 // Implicit and Explicit
7306 public readonly OpType OperatorType;
7307 public MethodBuilder OperatorMethodBuilder;
7309 public Method OperatorMethod;
7311 static string[] attribute_targets = new string [] { "method", "return" };
7313 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7314 int mod_flags, Parameters parameters,
7315 ToplevelBlock block, Attributes attrs, Location loc)
7316 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7317 new MemberName ("op_" + type), attrs, parameters, loc)
7319 OperatorType = type;
7323 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7325 OperatorMethod.ApplyAttributeBuilder (a, cb);
7328 public override AttributeTargets AttributeTargets {
7330 return AttributeTargets.Method;
7334 protected override bool CheckGenericOverride (MethodInfo method, string name)
7339 protected override bool CheckForDuplications()
7341 ArrayList ar = Parent.Operators;
7343 int arLen = ar.Count;
7345 for (int i = 0; i < arLen; i++) {
7346 Operator o = (Operator) ar [i];
7347 if (IsDuplicateImplementation (o))
7352 ar = Parent.Methods;
7354 int arLen = ar.Count;
7356 for (int i = 0; i < arLen; i++) {
7357 Method m = (Method) ar [i];
7358 if (IsDuplicateImplementation (m))
7366 public override bool Define ()
7368 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7369 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7370 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7377 OperatorMethod = new Method (
7378 Parent, null, Type, ModFlags, false, MemberName,
7379 Parameters, OptAttributes, Location);
7381 OperatorMethod.Block = Block;
7382 OperatorMethod.IsOperator = true;
7383 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7384 OperatorMethod.Define ();
7386 if (OperatorMethod.MethodBuilder == null)
7389 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7391 parameter_types = OperatorMethod.ParameterTypes;
7392 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7393 Type return_type = OperatorMethod.ReturnType;
7394 Type first_arg_type = parameter_types [0];
7399 // Rules for conversion operators
7401 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7402 if (first_arg_type == return_type && first_arg_type == declaring_type){
7405 "User-defined conversion cannot take an object of the " +
7406 "enclosing type and convert to an object of the enclosing" +
7411 if (first_arg_type != declaring_type && return_type != declaring_type){
7414 "User-defined conversion must convert to or from the " +
7419 if (first_arg_type == TypeManager.object_type ||
7420 return_type == TypeManager.object_type){
7423 "User-defined conversion cannot convert to or from " +
7428 if (first_arg_type.IsInterface || return_type.IsInterface){
7431 "User-defined conversion cannot convert to or from an " +
7436 if (first_arg_type.IsSubclassOf (return_type)
7437 || return_type.IsSubclassOf (first_arg_type)){
7438 if (declaring_type.IsSubclassOf (return_type)) {
7439 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7442 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7445 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7446 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7447 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");
7450 } else if (Parameters.FixedParameters.Length == 1) {
7451 // Checks for Unary operators
7453 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7454 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7455 Report.Error (448, Location,
7456 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7459 if (first_arg_type != declaring_type){
7461 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7466 if (first_arg_type != declaring_type){
7469 "The parameter of a unary operator must be the " +
7474 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7475 if (return_type != TypeManager.bool_type){
7478 "The return type of operator True or False " +
7485 // Checks for Binary operators
7487 if (first_arg_type != declaring_type &&
7488 parameter_types [1] != declaring_type){
7491 "One of the parameters of a binary operator must " +
7492 "be the containing type");
7500 public override void Emit ()
7503 // abstract or extern methods have no bodies
7505 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7508 OperatorMethod.Emit ();
7512 // Operator cannot be override
7513 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
7518 public static string GetName (OpType ot)
7521 case OpType.LogicalNot:
7523 case OpType.OnesComplement:
7525 case OpType.Increment:
7527 case OpType.Decrement:
7533 case OpType.Addition:
7535 case OpType.Subtraction:
7537 case OpType.UnaryPlus:
7539 case OpType.UnaryNegation:
7541 case OpType.Multiply:
7543 case OpType.Division:
7545 case OpType.Modulus:
7547 case OpType.BitwiseAnd:
7549 case OpType.BitwiseOr:
7551 case OpType.ExclusiveOr:
7553 case OpType.LeftShift:
7555 case OpType.RightShift:
7557 case OpType.Equality:
7559 case OpType.Inequality:
7561 case OpType.GreaterThan:
7563 case OpType.LessThan:
7565 case OpType.GreaterThanOrEqual:
7567 case OpType.LessThanOrEqual:
7569 case OpType.Implicit:
7571 case OpType.Explicit:
7577 public override string GetSignatureForError (TypeContainer tc)
7579 StringBuilder sb = new StringBuilder ();
7580 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7581 Parameters.FixedParameters [0].GetSignatureForError ());
7583 if (Parameters.FixedParameters.Length > 1) {
7585 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7588 return sb.ToString ();
7591 public override string GetSignatureForError ()
7596 public override string ToString ()
7598 if (OperatorMethod == null)
7601 Type return_type = OperatorMethod.ReturnType;
7602 Type [] param_types = OperatorMethod.ParameterTypes;
7604 if (Parameters.FixedParameters.Length == 1)
7605 return String.Format (
7606 "{0} operator {1}({2})",
7607 TypeManager.CSharpName (return_type),
7608 GetName (OperatorType),
7611 return String.Format (
7612 "{0} operator {1}({2}, {3})",
7613 TypeManager.CSharpName (return_type),
7614 GetName (OperatorType),
7615 param_types [0], param_types [1]);
7618 public override string[] ValidAttributeTargets {
7620 return attribute_targets;
7624 public void SetYields ()
7626 ModFlags |= Modifiers.METHOD_YIELDS;
7631 // This is used to compare method signatures
7633 struct MethodSignature {
7635 public Type RetType;
7636 public Type [] Parameters;
7639 /// This delegate is used to extract methods which have the
7640 /// same signature as the argument
7642 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7644 public MethodSignature (string name, Type ret_type, Type [] parameters)
7649 if (parameters == null)
7650 Parameters = TypeManager.NoTypes;
7652 Parameters = parameters;
7655 public override string ToString ()
7658 if (Parameters.Length != 0){
7659 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7660 for (int i = 0; i < Parameters.Length; i++){
7661 sb.Append (Parameters [i]);
7662 if (i+1 < Parameters.Length)
7665 pars = sb.ToString ();
7668 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7671 public override int GetHashCode ()
7673 return Name.GetHashCode ();
7676 public override bool Equals (Object o)
7678 MethodSignature other = (MethodSignature) o;
7680 if (other.Name != Name)
7683 if (other.RetType != RetType)
7686 if (Parameters == null){
7687 if (other.Parameters == null)
7692 if (other.Parameters == null)
7695 int c = Parameters.Length;
7696 if (other.Parameters.Length != c)
7699 for (int i = 0; i < c; i++)
7700 if (other.Parameters [i] != Parameters [i])
7706 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7708 MethodSignature sig = (MethodSignature) filter_criteria;
7710 if (m.Name != sig.Name)
7714 MethodInfo mi = m as MethodInfo;
7715 PropertyInfo pi = m as PropertyInfo;
7718 ReturnType = mi.ReturnType;
7719 else if (pi != null)
7720 ReturnType = pi.PropertyType;
7725 // we use sig.RetType == null to mean `do not check the
7726 // method return value.
7728 if (sig.RetType != null)
7729 if (ReturnType != sig.RetType)
7734 args = TypeManager.GetArgumentTypes (mi);
7736 args = TypeManager.GetArgumentTypes (pi);
7737 Type [] sigp = sig.Parameters;
7739 if (args.Length != sigp.Length)
7742 for (int i = args.Length; i > 0; ){
7744 if (args [i] != sigp [i])