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.
34 using System.Collections;
35 using System.Collections.Specialized;
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Security;
41 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;
424 // The emit context for toplevel objects.
427 public EmitContext EmitContext {
432 // Pointers to the default constructor and the default static constructor
434 protected Constructor default_constructor;
435 protected Constructor default_static_constructor;
438 // Whether we have at least one non-static field
440 bool have_nonstatic_fields = false;
443 // This one is computed after we can distinguish interfaces
444 // from classes from the arraylist `type_bases'
446 string base_class_name;
447 TypeExpr parent_type;
449 ArrayList type_bases;
451 bool members_defined;
452 bool members_defined_ok;
454 // The interfaces we implement.
455 protected Type [] ifaces;
456 protected Type ptype;
458 // The parent member container and our member cache
459 IMemberContainer parent_container;
460 MemberCache parent_cache;
461 MemberCache member_cache;
463 public const string DefaultIndexerName = "Item";
465 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
466 Attributes attrs, Kind kind, Location l)
467 : base (ns, parent, name, attrs, l)
471 types = new ArrayList ();
473 base_class_name = null;
476 public bool AddToMemberContainer (MemberCore symbol, bool is_method)
478 return AddToContainer (symbol, is_method, String.Concat (Name, '.', symbol.Name), symbol.Name);
481 bool AddToTypeContainer (DeclSpace ds)
483 return AddToContainer (ds, false, ds.Name, ds.Basename);
486 public void AddConstant (Const constant)
488 if (!AddToMemberContainer (constant, false))
491 if (constants == null)
492 constants = new MemberCoreArrayList ();
494 constants.Add (constant);
497 public void AddEnum (Mono.CSharp.Enum e)
499 if (!AddToTypeContainer (e))
503 enums = new MemberCoreArrayList ();
508 public void AddClassOrStruct (TypeContainer c)
510 if (!AddToTypeContainer (c))
516 public void AddDelegate (Delegate d)
518 if (!AddToTypeContainer (d))
521 if (delegates == null)
522 delegates = new MemberCoreArrayList ();
527 public void AddMethod (Method method)
529 if (!AddToMemberContainer (method, true))
533 methods = new MethodArrayList (this);
535 if (method.Name.IndexOf ('.') != -1)
536 methods.Insert (0, method);
538 methods.Add (method);
541 public void AddConstructor (Constructor c)
543 if (c.Name != Basename) {
544 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
547 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
550 if (default_static_constructor != null) {
551 Report.SymbolRelatedToPreviousError (default_static_constructor);
552 Report.Error (111, c.Location, Error111, Name, c.Name);
556 default_static_constructor = c;
559 if (default_constructor != null) {
560 Report.SymbolRelatedToPreviousError (default_constructor);
561 Report.Error (111, c.Location, Error111, c.Location, Name, c.Name);
564 default_constructor = c;
567 if (instance_constructors == null)
568 instance_constructors = new MemberCoreArrayList ();
570 instance_constructors.Add (c);
574 internal static string Error111 {
576 return "Type '{0}' already defines a member called '{1}' with the same parameter types";
580 public void AddInterface (TypeContainer iface)
582 if (!AddToTypeContainer (iface))
585 if (interfaces == null) {
586 interfaces = new MemberCoreArrayList ();
589 interfaces.Add (iface);
592 public void AddField (Field field)
594 if (!AddToMemberContainer (field, false))
598 fields = new MemberCoreArrayList ();
602 if (field.HasInitializer){
603 if ((field.ModFlags & Modifiers.STATIC) != 0){
604 if (initialized_static_fields == null)
605 initialized_static_fields = new ArrayList ();
607 initialized_static_fields.Add (field);
609 if (initialized_fields == null)
610 initialized_fields = new ArrayList ();
612 initialized_fields.Add (field);
616 if ((field.ModFlags & Modifiers.STATIC) == 0)
617 have_nonstatic_fields = true;
620 public void AddProperty (Property prop)
622 if (!AddToMemberContainer (prop, false) ||
623 !AddToMemberContainer (prop.Get, true) || !AddToMemberContainer (prop.Set, true))
626 if (properties == null)
627 properties = new MemberCoreArrayList ();
629 if (prop.Name.IndexOf ('.') != -1)
630 properties.Insert (0, prop);
632 properties.Add (prop);
635 public void AddEvent (Event e)
637 if (!AddToMemberContainer (e, false))
640 if (e is EventProperty) {
641 if (!AddToMemberContainer (e.Add, true))
644 if (!AddToMemberContainer (e.Remove, true))
649 events = new MemberCoreArrayList ();
656 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
658 public void AddIndexer (Indexer i)
660 if (indexers == null)
661 indexers = new IndexerArrayList (this);
663 if (i.IsExplicitImpl)
664 indexers.Insert (0, i);
669 public void AddOperator (Operator op)
671 if (!AddToMemberContainer (op, true))
674 if (operators == null)
675 operators = new OperatorArrayList (this);
680 public void AddIterator (Iterator i)
682 if (iterators == null)
683 iterators = new ArrayList ();
688 public void AddType (TypeContainer tc)
693 public void AddPart (ClassPart part)
696 parts = new ArrayList ();
701 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
703 if (a.Type == TypeManager.default_member_type) {
704 if (Indexers != null) {
705 Report.Error (646, a.Location,
706 "Cannot specify the DefaultMember attribute on" +
707 " a type containing an indexer");
712 base.ApplyAttributeBuilder (a, cb);
715 public override AttributeTargets AttributeTargets {
717 throw new NotSupportedException ();
721 public ArrayList Types {
727 public MethodArrayList Methods {
733 public ArrayList Constants {
739 public ArrayList Interfaces {
745 public ArrayList Iterators {
753 return base_class_name;
757 public ArrayList Bases {
767 public ArrayList Fields {
773 public ArrayList InstanceConstructors {
775 return instance_constructors;
779 public ArrayList Properties {
785 public ArrayList Events {
791 public ArrayList Enums {
797 public ArrayList Indexers {
803 public ArrayList Operators {
809 public ArrayList Delegates {
815 public ArrayList Parts {
821 public virtual TypeAttributes TypeAttr {
823 return Modifiers.TypeAttr (ModFlags, this);
827 public string IndexerName {
829 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
834 // Emits the instance field initializers
836 public bool EmitFieldInitializers (EmitContext ec)
839 Expression instance_expr;
842 fields = initialized_static_fields;
843 instance_expr = null;
845 fields = initialized_fields;
846 instance_expr = new This (Location.Null).Resolve (ec);
852 foreach (Field f in fields){
853 Expression e = f.GetInitializerExpression (ec);
857 Location l = f.Location;
858 FieldExpr fe = new FieldExpr (f.FieldBuilder, l);
859 fe.InstanceExpression = instance_expr;
860 ExpressionStatement a = new Assign (fe, e, l);
862 a = a.ResolveStatement (ec);
866 a.EmitStatement (ec);
873 // Defines the default constructors
875 protected void DefineDefaultConstructor (bool is_static)
879 // The default constructor is public
880 // If the class is abstract, the default constructor is protected
881 // The default static constructor is private
883 int mods = Modifiers.PUBLIC;
885 mods = Modifiers.STATIC | Modifiers.PRIVATE;
886 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
887 mods = Modifiers.PROTECTED;
889 c = new Constructor (this, Basename, mods, Parameters.EmptyReadOnlyParameters,
890 new ConstructorBaseInitializer (
891 null, Parameters.EmptyReadOnlyParameters,
897 c.Block = new ToplevelBlock (null, Location);
902 /// The pending methods that need to be implemented
903 // (interfaces or abstract methods)
905 public PendingImplementation Pending;
907 public abstract void Register ();
909 public abstract PendingImplementation GetPendingImplementations ();
911 TypeExpr[] GetPartialBases (out TypeExpr parent, out bool error)
913 ArrayList ifaces = new ArrayList ();
916 Location parent_loc = Location.Null;
918 foreach (ClassPart part in parts) {
920 TypeExpr[] new_ifaces;
922 new_ifaces = part.GetClassBases (out new_parent, out error);
926 if ((parent != null) && (new_parent != null) &&
927 !parent.Equals (new_parent)) {
928 Report.Error (263, part.Location,
929 "Partial declarations of `{0}' must " +
930 "not specify different base classes",
933 if (!Location.IsNull (parent_loc))
934 Report.LocationOfPreviousError (parent_loc);
940 if ((parent == null) && (new_parent != null)) {
942 parent_loc = part.Location;
945 if (new_ifaces == null)
948 foreach (TypeExpr iface in new_ifaces) {
950 foreach (TypeExpr old_iface in ifaces) {
951 if (old_iface.Equals (iface)) {
964 TypeExpr[] retval = new TypeExpr [ifaces.Count];
965 ifaces.CopyTo (retval, 0);
969 TypeExpr[] GetNormalBases (out TypeExpr parent, out bool error)
973 int count = Bases.Count;
976 if (Kind == Kind.Class){
977 TypeExpr name = ResolveTypeExpr (
978 (Expression) Bases [0], false, Location);
995 TypeExpr [] ifaces = new TypeExpr [count-start];
997 for (i = start, j = 0; i < count; i++, j++){
998 Expression name = (Expression) Bases [i];
999 TypeExpr resolved = ResolveTypeExpr (name, false, Location);
1000 if (resolved == null) {
1005 ifaces [j] = resolved;
1013 /// This function computes the Base class and also the
1014 /// list of interfaces that the class or struct @c implements.
1016 /// The return value is an array (might be null) of
1017 /// interfaces implemented (as Types).
1019 /// The @parent argument is set to the parent object or null
1020 /// if this is `System.Object'.
1022 TypeExpr [] GetClassBases (out TypeExpr parent, out bool error)
1031 ifaces = GetPartialBases (out parent, out error);
1032 else if (Bases == null){
1036 ifaces = GetNormalBases (out parent, out error);
1041 if ((parent != null) && (Kind == Kind.Class)){
1042 if (parent.IsSealed){
1044 Report.SymbolRelatedToPreviousError (parent.Type);
1045 if (parent.Type.IsAbstract) {
1046 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1048 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1053 if (!parent.CanInheritFrom ()){
1054 Report.Error (644, Location,
1055 "`{0}' cannot inherit from special class `{1}'",
1061 if (!parent.AsAccessible (this, ModFlags))
1062 Report.Error (60, Location,
1063 "Inconsistent accessibility: base class `" +
1064 parent.Name + "' is less accessible than class `" +
1069 base_class_name = parent.Name;
1074 int count = ifaces != null ? ifaces.Length : 0;
1076 for (i = 0; i < count; i++) {
1077 TypeExpr iface = (TypeExpr) ifaces [i];
1079 if ((Kind != Kind.Class) && !iface.IsInterface){
1080 string what = Kind == Kind.Struct ?
1081 "Struct" : "Interface";
1083 Report.Error (527, Location,
1084 "In {0} `{1}', type `{2}' is not "+
1085 "an interface", what, Name, iface.Name);
1090 if (iface.IsClass) {
1091 if (parent != null){
1092 Report.Error (527, Location,
1093 "In Class `{0}', `{1}' is not " +
1094 "an interface", Name, iface.Name);
1100 for (int x = 0; x < i; x++) {
1101 if (iface.Equals (ifaces [x])) {
1102 Report.Error (528, Location,
1103 "`{0}' is already listed in " +
1104 "interface list", iface.Name);
1110 if ((Kind == Kind.Interface) &&
1111 !iface.AsAccessible (Parent, ModFlags))
1112 Report.Error (61, Location,
1113 "Inconsistent accessibility: base " +
1114 "interface `{0}' is less accessible " +
1115 "than interface `{1}'", iface.Name,
1125 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1127 public override TypeBuilder DefineType ()
1129 if (TypeBuilder != null)
1136 Report.Error (146, Location, "Class definition is circular: `{0}'", Name);
1143 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1145 TypeExpr[] iface_exprs = GetClassBases (out parent_type, out error);
1149 if (parent_type == null) {
1150 if (Kind == Kind.Class){
1151 if (RootContext.StdLib)
1152 parent_type = TypeManager.system_object_expr;
1153 else if (Name != "System.Object")
1154 parent_type = TypeManager.system_object_expr;
1155 } else if (Kind == Kind.Struct) {
1157 // If we are compiling our runtime,
1158 // and we are defining ValueType, then our
1159 // parent is `System.Object'.
1161 if (!RootContext.StdLib && Name == "System.ValueType")
1162 parent_type = TypeManager.system_object_expr;
1164 parent_type = TypeManager.system_valuetype_expr;
1168 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1169 throw new Exception ();
1171 TypeAttributes type_attributes = TypeAttr;
1173 if (parent_type != null) {
1174 ptype = parent_type.ResolveType (ec);
1175 if (ptype == null) {
1183 if (TypeManager.NamespaceClash (Name, Location)) {
1188 ModuleBuilder builder = CodeGen.Module.Builder;
1189 TypeBuilder = builder.DefineType (
1190 Name, type_attributes, ptype, null);
1193 TypeBuilder builder = Parent.DefineType ();
1194 if (builder == null)
1197 TypeBuilder = builder.DefineNestedType (
1198 Basename, type_attributes, ptype, null);
1201 catch (ArgumentException) {
1202 Report.RuntimeMissingSupport (Location, "static classes");
1207 // Structs with no fields need to have at least one byte.
1208 // The right thing would be to set the PackingSize in a DefineType
1209 // but there are no functions that allow interfaces *and* the size to
1213 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
1214 TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
1215 FieldAttributes.Private);
1218 // add interfaces that were not added at type creation
1219 if (iface_exprs != null) {
1220 ifaces = TypeManager.ExpandInterfaces (ec, iface_exprs);
1221 if (ifaces == null) {
1226 foreach (Type itype in ifaces)
1227 TypeBuilder.AddInterfaceImplementation (itype);
1229 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1233 // Finish the setup for the EmitContext
1235 ec.ContainerType = TypeBuilder;
1237 TypeManager.AddUserType (Name, TypeBuilder, this);
1239 if ((parent_type != null) && parent_type.IsAttribute) {
1240 RootContext.RegisterAttribute (this);
1241 } else if (!(this is Iterator))
1242 RootContext.RegisterOrder (this);
1244 if (!DefineNestedTypes ()) {
1253 protected virtual bool DefineNestedTypes ()
1255 if (Interfaces != null) {
1256 foreach (TypeContainer iface in Interfaces)
1257 if (iface.DefineType () == null)
1261 if (Types != null) {
1262 foreach (TypeContainer tc in Types)
1263 if (tc.DefineType () == null)
1267 if (Delegates != null) {
1268 foreach (Delegate d in Delegates)
1269 if (d.DefineType () == null)
1273 if (Enums != null) {
1274 foreach (Enum en in Enums)
1275 if (en.DefineType () == null)
1279 if (Parts != null) {
1280 foreach (ClassPart part in Parts) {
1281 part.TypeBuilder = TypeBuilder;
1283 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1290 static void Error_KeywordNotAllowed (Location loc)
1292 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1296 /// Populates our TypeBuilder with fields and methods
1298 public override bool DefineMembers (TypeContainer container)
1300 if (members_defined)
1301 return members_defined_ok;
1303 members_defined_ok = DoDefineMembers ();
1304 members_defined = true;
1306 return members_defined_ok;
1309 bool DoDefineMembers ()
1312 // We need to be able to use the member cache while we are checking/defining
1314 if (TypeBuilder.BaseType != null) {
1315 parent_container = TypeManager.LookupMemberContainer (TypeBuilder.BaseType);
1316 parent_cache = parent_container.MemberCache;
1319 if (TypeBuilder.IsInterface)
1320 parent_cache = TypeManager.LookupInterfaceCache (this, TypeBuilder);
1323 if ((ModFlags & Modifiers.NEW) != 0)
1324 Error_KeywordNotAllowed (Location);
1326 // HACK: missing implemenation
1327 // This is not fully functional. Better way how to handle this is to have recursive definition of containers
1328 // instead of flat as we have now.
1329 // Now we are not able to check inner attribute class because its parent had not been defined.
1331 // TODO: remove this if
1332 if (Parent.MemberCache != null) {
1333 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1334 if (conflict_symbol == null) {
1335 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1336 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1338 if ((ModFlags & Modifiers.NEW) == 0) {
1339 Report.SymbolRelatedToPreviousError (conflict_symbol);
1340 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1346 DefineContainerMembers (constants);
1347 DefineContainerMembers (fields);
1349 if ((Kind == Kind.Class) && !(this is ClassPart) && !(this is StaticClass)){
1350 if ((instance_constructors == null) &&
1351 !(this is StaticClass)) {
1352 if (default_constructor == null)
1353 DefineDefaultConstructor (false);
1356 if (initialized_static_fields != null &&
1357 default_static_constructor == null)
1358 DefineDefaultConstructor (true);
1361 if (Kind == Kind.Struct){
1363 // Structs can not have initialized instance
1366 if (initialized_static_fields != null &&
1367 default_static_constructor == null)
1368 DefineDefaultConstructor (true);
1370 if (initialized_fields != null)
1371 ReportStructInitializedInstanceError ();
1374 Pending = GetPendingImplementations ();
1376 if (parts != null) {
1377 foreach (ClassPart part in parts) {
1378 if (!part.DefineMembers (this))
1384 // Constructors are not in the defined_names array
1386 DefineContainerMembers (instance_constructors);
1388 if (default_static_constructor != null)
1389 default_static_constructor.Define ();
1391 DefineContainerMembers (properties);
1392 DefineContainerMembers (events);
1393 DefineContainerMembers (indexers);
1394 DefineContainerMembers (methods);
1395 DefineContainerMembers (operators);
1396 DefineContainerMembers (enums);
1397 DefineContainerMembers (delegates);
1400 if (!(this is ClassPart))
1401 member_cache = new MemberCache (this);
1404 if (parts != null) {
1405 foreach (ClassPart part in parts)
1406 part.member_cache = member_cache;
1409 if (iterators != null) {
1410 foreach (Iterator iterator in iterators) {
1411 if (iterator.DefineType () == null)
1415 foreach (Iterator iterator in iterators) {
1416 if (!iterator.DefineMembers (this))
1424 void ReportStructInitializedInstanceError ()
1426 string n = TypeBuilder.FullName;
1428 foreach (Field f in initialized_fields){
1431 "`" + n + "." + f.Name + "': can not have " +
1432 "instance field initializers in structs");
1436 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1439 mcal.DefineContainerMembers ();
1442 public override bool Define ()
1444 if (parts != null) {
1445 foreach (ClassPart part in parts) {
1446 if (!part.Define ())
1454 public MemberInfo FindMemberWithSameName (string name, bool ignore_methods)
1456 return ParentCache.FindMemberWithSameName (name, ignore_methods, null);
1460 /// This function is based by a delegate to the FindMembers routine
1462 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1468 /// This filter is used by FindMembers, and we just keep
1469 /// a global for the filter to `AlwaysAccept'
1471 static MemberFilter accepting_filter;
1474 static TypeContainer ()
1476 accepting_filter = new MemberFilter (AlwaysAccept);
1479 public MethodInfo[] GetMethods ()
1481 ArrayList members = new ArrayList ();
1483 DefineMembers (null);
1485 if (methods != null) {
1486 int len = methods.Count;
1487 for (int i = 0; i < len; i++) {
1488 Method m = (Method) methods [i];
1490 members.Add (m.MethodBuilder);
1494 if (operators != null) {
1495 int len = operators.Count;
1496 for (int i = 0; i < len; i++) {
1497 Operator o = (Operator) operators [i];
1499 members.Add (o.OperatorMethodBuilder);
1503 if (properties != null) {
1504 int len = properties.Count;
1505 for (int i = 0; i < len; i++) {
1506 Property p = (Property) properties [i];
1508 if (p.GetBuilder != null)
1509 members.Add (p.GetBuilder);
1510 if (p.SetBuilder != null)
1511 members.Add (p.SetBuilder);
1515 if (indexers != null) {
1516 int len = indexers.Count;
1517 for (int i = 0; i < len; i++) {
1518 Indexer ix = (Indexer) indexers [i];
1520 if (ix.GetBuilder != null)
1521 members.Add (ix.GetBuilder);
1522 if (ix.SetBuilder != null)
1523 members.Add (ix.SetBuilder);
1527 if (events != null) {
1528 int len = events.Count;
1529 for (int i = 0; i < len; i++) {
1530 Event e = (Event) events [i];
1532 if (e.AddBuilder != null)
1533 members.Add (e.AddBuilder);
1534 if (e.RemoveBuilder != null)
1535 members.Add (e.RemoveBuilder);
1539 MethodInfo[] retMethods = new MethodInfo [members.Count];
1540 members.CopyTo (retMethods, 0);
1544 // Indicated whether container has StructLayout attribute set Explicit
1545 public virtual bool HasExplicitLayout {
1552 /// This method returns the members of this type just like Type.FindMembers would
1553 /// Only, we need to use this for types which are _being_ defined because MS'
1554 /// implementation can't take care of that.
1557 // FIXME: return an empty static array instead of null, that cleans up
1558 // some code and is consistent with some coding conventions I just found
1562 // Notice that in various cases we check if our field is non-null,
1563 // something that would normally mean that there was a bug elsewhere.
1565 // The problem happens while we are defining p-invoke methods, as those
1566 // will trigger a FindMembers, but this happens before things are defined
1568 // Since the whole process is a no-op, it is fine to check for null here.
1570 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1571 MemberFilter filter, object criteria)
1573 ArrayList members = null;
1576 if ((bf & BindingFlags.Public) != 0)
1577 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1579 if ((bf & BindingFlags.NonPublic) != 0)
1580 modflags |= Modifiers.PRIVATE;
1582 int static_mask = 0, static_flags = 0;
1583 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1584 case BindingFlags.Static:
1585 static_mask = static_flags = Modifiers.STATIC;
1588 case BindingFlags.Instance:
1589 static_mask = Modifiers.STATIC;
1594 static_mask = static_flags = 0;
1598 Timer.StartTimer (TimerType.TcFindMembers);
1601 filter = accepting_filter;
1603 if ((mt & MemberTypes.Field) != 0) {
1604 if (fields != null) {
1605 int len = fields.Count;
1606 for (int i = 0; i < len; i++) {
1607 Field f = (Field) fields [i];
1609 if ((f.ModFlags & modflags) == 0)
1611 if ((f.ModFlags & static_mask) != static_flags)
1614 FieldBuilder fb = f.FieldBuilder;
1615 if (fb != null && filter (fb, criteria) == true) {
1616 if (members == null)
1617 members = new ArrayList ();
1624 if (constants != null) {
1625 int len = constants.Count;
1626 for (int i = 0; i < len; i++) {
1627 Const con = (Const) constants [i];
1629 if ((con.ModFlags & modflags) == 0)
1631 if ((con.ModFlags & static_mask) != static_flags)
1634 FieldBuilder fb = con.FieldBuilder;
1635 if (fb != null && filter (fb, criteria) == true) {
1636 if (members == null)
1637 members = new ArrayList ();
1645 if ((mt & MemberTypes.Method) != 0) {
1646 if (methods != null) {
1647 int len = methods.Count;
1648 for (int i = 0; i < len; i++) {
1649 Method m = (Method) methods [i];
1651 if ((m.ModFlags & modflags) == 0)
1653 if ((m.ModFlags & static_mask) != static_flags)
1656 MethodBuilder mb = m.MethodBuilder;
1658 if (mb != null && filter (mb, criteria) == true) {
1659 if (members == null)
1660 members = new ArrayList ();
1667 if (operators != null) {
1668 int len = operators.Count;
1669 for (int i = 0; i < len; i++) {
1670 Operator o = (Operator) operators [i];
1672 if ((o.ModFlags & modflags) == 0)
1674 if ((o.ModFlags & static_mask) != static_flags)
1677 MethodBuilder ob = o.OperatorMethodBuilder;
1678 if (ob != null && filter (ob, criteria) == true) {
1679 if (members == null)
1680 members = new ArrayList ();
1687 if (properties != null) {
1688 int len = properties.Count;
1689 for (int i = 0; i < len; i++) {
1690 Property p = (Property) properties [i];
1692 if ((p.ModFlags & modflags) == 0)
1694 if ((p.ModFlags & static_mask) != static_flags)
1700 if (b != null && filter (b, criteria) == true) {
1701 if (members == null)
1702 members = new ArrayList ();
1708 if (b != null && filter (b, criteria) == true) {
1709 if (members == null)
1710 members = new ArrayList ();
1717 if (indexers != null) {
1718 int len = indexers.Count;
1719 for (int i = 0; i < len; i++) {
1720 Indexer ix = (Indexer) indexers [i];
1722 if ((ix.ModFlags & modflags) == 0)
1724 if ((ix.ModFlags & static_mask) != static_flags)
1730 if (b != null && filter (b, criteria) == true) {
1731 if (members == null)
1732 members = new ArrayList ();
1738 if (b != null && filter (b, criteria) == true) {
1739 if (members == null)
1740 members = new ArrayList ();
1748 if ((mt & MemberTypes.Event) != 0) {
1749 if (events != null) {
1750 int len = events.Count;
1751 for (int i = 0; i < len; i++) {
1752 Event e = (Event) events [i];
1754 if ((e.ModFlags & modflags) == 0)
1756 if ((e.ModFlags & static_mask) != static_flags)
1759 MemberInfo eb = e.EventBuilder;
1760 if (eb != null && filter (eb, criteria) == true) {
1761 if (members == null)
1762 members = new ArrayList ();
1764 members.Add (e.EventBuilder);
1770 if ((mt & MemberTypes.Property) != 0){
1771 if (properties != null) {
1772 int len = properties.Count;
1773 for (int i = 0; i < len; i++) {
1774 Property p = (Property) properties [i];
1776 if ((p.ModFlags & modflags) == 0)
1778 if ((p.ModFlags & static_mask) != static_flags)
1781 MemberInfo pb = p.PropertyBuilder;
1782 if (pb != null && filter (pb, criteria) == true) {
1783 if (members == null)
1784 members = new ArrayList ();
1786 members.Add (p.PropertyBuilder);
1791 if (indexers != null) {
1792 int len = indexers.Count;
1793 for (int i = 0; i < len; i++) {
1794 Indexer ix = (Indexer) indexers [i];
1796 if ((ix.ModFlags & modflags) == 0)
1798 if ((ix.ModFlags & static_mask) != static_flags)
1801 MemberInfo ib = ix.PropertyBuilder;
1802 if (ib != null && filter (ib, criteria) == true) {
1803 if (members == null)
1804 members = new ArrayList ();
1806 members.Add (ix.PropertyBuilder);
1812 if ((mt & MemberTypes.NestedType) != 0) {
1813 if (types != null) {
1814 int len = types.Count;
1815 for (int i = 0; i < len; i++) {
1816 TypeContainer t = (TypeContainer) types [i];
1818 if ((t.ModFlags & modflags) == 0)
1821 TypeBuilder tb = t.TypeBuilder;
1822 if (tb != null && (filter (tb, criteria) == true)) {
1823 if (members == null)
1824 members = new ArrayList ();
1831 if (enums != null) {
1832 int len = enums.Count;
1833 for (int i = 0; i < len; i++) {
1834 Enum en = (Enum) enums [i];
1836 if ((en.ModFlags & modflags) == 0)
1839 TypeBuilder tb = en.TypeBuilder;
1840 if (tb != null && (filter (tb, criteria) == true)) {
1841 if (members == null)
1842 members = new ArrayList ();
1849 if (delegates != null) {
1850 int len = delegates.Count;
1851 for (int i = 0; i < len; i++) {
1852 Delegate d = (Delegate) delegates [i];
1854 if ((d.ModFlags & modflags) == 0)
1857 TypeBuilder tb = d.TypeBuilder;
1858 if (tb != null && (filter (tb, criteria) == true)) {
1859 if (members == null)
1860 members = new ArrayList ();
1867 if (interfaces != null) {
1868 int len = interfaces.Count;
1869 for (int i = 0; i < len; i++) {
1870 TypeContainer iface = (TypeContainer) interfaces [i];
1872 if ((iface.ModFlags & modflags) == 0)
1875 TypeBuilder tb = iface.TypeBuilder;
1876 if (tb != null && (filter (tb, criteria) == true)) {
1877 if (members == null)
1878 members = new ArrayList ();
1886 if ((mt & MemberTypes.Constructor) != 0){
1887 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1888 int len = instance_constructors.Count;
1889 for (int i = 0; i < len; i++) {
1890 Constructor c = (Constructor) instance_constructors [i];
1892 ConstructorBuilder cb = c.ConstructorBuilder;
1893 if (cb != null && filter (cb, criteria) == true) {
1894 if (members == null)
1895 members = new ArrayList ();
1902 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1903 ConstructorBuilder cb =
1904 default_static_constructor.ConstructorBuilder;
1906 if (cb != null && filter (cb, criteria) == true) {
1907 if (members == null)
1908 members = new ArrayList ();
1916 // Lookup members in parent if requested.
1918 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1919 if (TypeBuilder.BaseType != null) {
1920 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1921 if (list.Count > 0) {
1922 if (members == null)
1923 members = new ArrayList ();
1925 members.AddRange (list);
1928 if (ifaces != null) {
1929 foreach (Type base_type in ifaces) {
1930 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1932 if (list.Count > 0) {
1933 if (members == null)
1934 members = new ArrayList ();
1935 members.AddRange (list);
1941 Timer.StopTimer (TimerType.TcFindMembers);
1943 if (members == null)
1944 return MemberList.Empty;
1946 return new MemberList (members);
1949 public override MemberCache MemberCache {
1951 return member_cache;
1955 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1956 MemberFilter filter, object criteria)
1958 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1961 return ds.FindMembers (mt, bf, filter, criteria);
1963 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1968 // FindMethods will look for methods not only in the type `t', but in
1969 // any interfaces implemented by the type.
1971 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1972 MemberFilter filter, object criteria)
1978 /// Emits the values for the constants
1980 public void EmitConstants ()
1982 if (constants != null)
1983 foreach (Const con in constants)
1988 protected virtual void VerifyMembers (EmitContext ec)
1991 // Check for internal or private fields that were never assigned
1993 if (RootContext.WarningLevel >= 3) {
1994 if (fields != null){
1995 foreach (Field f in fields) {
1996 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1999 if ((f.status & Field.Status.USED) == 0){
2000 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2005 // Only report 649 on level 4
2007 if (RootContext.WarningLevel < 4)
2010 if ((f.status & Field.Status.ASSIGNED) != 0)
2013 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2020 /// Emits the code, this step is performed after all
2021 /// the types, enumerations, constructors
2023 public void EmitType ()
2025 if (OptAttributes != null)
2026 OptAttributes.Emit (ec, this);
2030 if (instance_constructors != null) {
2031 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2032 bool has_compliant_args = false;
2034 foreach (Constructor c in instance_constructors) {
2037 if (has_compliant_args)
2040 has_compliant_args = c.HasCompliantArgs;
2042 if (!has_compliant_args)
2043 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2045 foreach (Constructor c in instance_constructors)
2052 if (default_static_constructor != null)
2053 default_static_constructor.Emit ();
2055 if (methods != null)
2056 foreach (Method m in methods)
2059 if (operators != null)
2060 foreach (Operator o in operators)
2063 if (properties != null)
2064 foreach (Property p in properties)
2067 if (indexers != null){
2072 foreach (Field f in fields)
2075 if (events != null){
2076 foreach (Event e in Events)
2080 if (delegates != null) {
2081 foreach (Delegate d in Delegates) {
2086 if (enums != null) {
2087 foreach (Enum e in enums) {
2092 if (parts != null) {
2093 foreach (ClassPart part in parts)
2097 if ((Pending != null) && !(this is ClassPart))
2098 if (Pending.VerifyPendingMethods ())
2103 if (iterators != null)
2104 foreach (Iterator iterator in iterators)
2105 iterator.EmitType ();
2107 // if (types != null)
2108 // foreach (TypeContainer tc in types)
2112 public override void CloseType ()
2114 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2118 caching_flags |= Flags.CloseTypeCreated;
2119 TypeBuilder.CreateType ();
2120 } catch (TypeLoadException){
2122 // This is fine, the code still created the type
2124 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2125 // Console.WriteLine (e.Message);
2127 Console.WriteLine ("In type: " + Name);
2132 foreach (Enum en in Enums)
2136 foreach (TypeContainer tc in Types)
2137 if (tc.Kind == Kind.Struct)
2140 foreach (TypeContainer tc in Types)
2141 if (tc.Kind != Kind.Struct)
2145 if (Delegates != null)
2146 foreach (Delegate d in Delegates)
2149 if (Iterators != null)
2150 foreach (Iterator i in Iterators)
2158 initialized_fields = null;
2159 initialized_static_fields = null;
2168 default_constructor = null;
2169 default_static_constructor = null;
2171 OptAttributes = null;
2173 parent_cache = null;
2174 member_cache = null;
2177 // TODO: make it obsolete and use GetSignatureForError
2178 public string MakeName (string n)
2180 return "`" + Name + "." + n + "'";
2184 // Performs the validation on a Method's modifiers (properties have
2185 // the same properties).
2187 public bool MethodModifiersValid (int flags, string n, Location loc)
2189 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2190 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2191 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2195 // At most one of static, virtual or override
2197 if ((flags & Modifiers.STATIC) != 0){
2198 if ((flags & vao) != 0){
2200 112, loc, "static method " + MakeName (n) + "can not be marked " +
2201 "as virtual, abstract or override");
2206 if (Kind == Kind.Struct){
2207 if ((flags & va) != 0){
2208 Modifiers.Error_InvalidModifier (loc, "virtual or abstract");
2213 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2215 113, loc, MakeName (n) +
2216 " marked as override cannot be marked as new or virtual");
2221 // If the declaration includes the abstract modifier, then the
2222 // declaration does not include static, virtual or extern
2224 if ((flags & Modifiers.ABSTRACT) != 0){
2225 if ((flags & Modifiers.EXTERN) != 0){
2227 180, loc, MakeName (n) + " can not be both abstract and extern");
2231 if ((flags & Modifiers.VIRTUAL) != 0){
2233 503, loc, MakeName (n) + " can not be both abstract and virtual");
2237 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2239 513, loc, MakeName (n) +
2240 " is abstract but its container class is not");
2246 if ((flags & Modifiers.PRIVATE) != 0){
2247 if ((flags & vao) != 0){
2249 621, loc, MakeName (n) +
2250 " virtual or abstract members can not be private");
2255 if ((flags & Modifiers.SEALED) != 0){
2256 if ((flags & Modifiers.OVERRIDE) == 0){
2258 238, loc, MakeName (n) +
2259 " cannot be sealed because it is not an override");
2267 public bool UserDefinedStaticConstructor {
2269 return default_static_constructor != null;
2273 protected override bool VerifyClsCompliance (DeclSpace ds)
2275 if (!base.VerifyClsCompliance (ds))
2280 // parent_container is null for System.Object
2281 if (parent_container != null && !AttributeTester.IsClsCompliant (parent_container.Type)) {
2282 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (parent_container.Type));
2289 /// Checks whether container name is CLS Compliant
2291 void VerifyClsName ()
2293 Hashtable parent_members = parent_cache == null ?
2295 parent_cache.GetPublicMembers ();
2296 Hashtable this_members = new Hashtable ();
2298 foreach (DictionaryEntry entry in defined_names) {
2299 MemberCore mc = (MemberCore)entry.Value;
2300 if (!mc.IsClsCompliaceRequired (this))
2303 string name = (string)entry.Key;
2304 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2306 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2307 object found = parent_members [lcase];
2308 if (found == null) {
2309 found = this_members [lcase];
2310 if (found == null) {
2311 this_members.Add (lcase, mc);
2316 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2319 if (found is MemberInfo) {
2320 if (basename == ((MemberInfo)found).Name)
2322 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2324 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2326 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2332 /// Performs checks for an explicit interface implementation. First it
2333 /// checks whether the `interface_type' is a base inteface implementation.
2334 /// Then it checks whether `name' exists in the interface type.
2336 public virtual bool VerifyImplements (Type interface_type, string full,
2337 string name, Location loc)
2341 if (ifaces != null){
2342 foreach (Type t in ifaces){
2343 if (t == interface_type){
2351 Report.Error (540, "`" + full + "': containing class does not implement interface `" + interface_type.FullName + "'");
2358 protected override void VerifyObsoleteAttribute()
2360 CheckUsageOfObsoleteAttribute (ptype);
2365 foreach (Type iface in ifaces) {
2366 CheckUsageOfObsoleteAttribute (iface);
2375 string IMemberContainer.Name {
2381 Type IMemberContainer.Type {
2387 MemberCache IMemberContainer.MemberCache {
2389 return member_cache;
2393 bool IMemberContainer.IsInterface {
2395 return Kind == Kind.Interface;
2399 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2401 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2404 public virtual MemberCache ParentCache {
2406 return parent_cache;
2411 public class PartialContainer : TypeContainer {
2413 public readonly Namespace Namespace;
2414 public readonly int OriginalModFlags;
2415 public readonly int AllowedModifiers;
2416 public readonly TypeAttributes DefaultTypeAttributes;
2418 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2419 MemberName name, int mod_flags, Kind kind,
2422 PartialContainer pc;
2423 string full_name = name.GetName (true);
2424 DeclSpace ds = (DeclSpace) RootContext.Tree.Decls [full_name];
2426 pc = ds as PartialContainer;
2430 260, ds.Location, "Missing partial modifier " +
2431 "on declaration of type `{0}'; another " +
2432 "partial implementation of this type exists",
2435 Report.LocationOfPreviousError (loc);
2439 if (pc.Kind != kind) {
2441 261, loc, "Partial declarations of `{0}' " +
2442 "must be all classes, all structs or " +
2443 "all interfaces", name);
2447 if (pc.OriginalModFlags != mod_flags) {
2449 262, loc, "Partial declarations of `{0}' " +
2450 "have conflicting accessibility modifiers",
2458 pc = new PartialContainer (ns, parent, name, mod_flags, kind, loc);
2459 RootContext.Tree.RecordDecl (full_name, pc);
2460 parent.AddType (pc);
2465 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2466 MemberName name, int mod, Attributes attrs,
2467 Kind kind, Location loc)
2469 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2471 // An error occured; create a dummy container, but don't
2473 pc = new PartialContainer (ns, parent, name, mod, kind, loc);
2476 ClassPart part = new ClassPart (ns, pc, mod, attrs, kind, loc);
2481 protected PartialContainer (NamespaceEntry ns, TypeContainer parent,
2482 MemberName name, int mod, Kind kind, Location l)
2483 : base (ns, parent, name, null, kind, l)
2485 this.Namespace = ns.NS;
2489 AllowedModifiers = Class.AllowedModifiers;
2490 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2494 AllowedModifiers = Struct.AllowedModifiers;
2495 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2498 case Kind.Interface:
2499 AllowedModifiers = Interface.AllowedModifiers;
2500 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2504 throw new InvalidOperationException ();
2508 if (parent.Parent == null)
2509 accmods = Modifiers.INTERNAL;
2511 accmods = Modifiers.PRIVATE;
2513 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2514 this.OriginalModFlags = mod;
2517 public override void Register ()
2519 if (Kind == Kind.Interface)
2520 Parent.AddInterface (this);
2521 else if (Kind == Kind.Class || Kind == Kind.Struct)
2522 Parent.AddClassOrStruct (this);
2524 throw new InvalidOperationException ();
2527 public override PendingImplementation GetPendingImplementations ()
2529 return PendingImplementation.GetPendingImplementations (this);
2532 public ClassPart AddPart (NamespaceEntry ns, int mod, Attributes attrs,
2535 ClassPart part = new ClassPart (ns, this, mod, attrs, Kind, l);
2540 public override TypeAttributes TypeAttr {
2542 return base.TypeAttr | DefaultTypeAttributes;
2547 public class ClassPart : TypeContainer, IMemberContainer {
2548 public readonly PartialContainer PartialContainer;
2549 public readonly bool IsPartial;
2551 public ClassPart (NamespaceEntry ns, PartialContainer parent,
2552 int mod, Attributes attrs, Kind kind, Location l)
2553 : base (ns, parent.Parent, parent.MemberName, attrs, kind, l)
2555 this.PartialContainer = parent;
2556 this.IsPartial = true;
2559 if (parent.Parent == null)
2560 accmods = Modifiers.INTERNAL;
2562 accmods = Modifiers.PRIVATE;
2564 this.ModFlags = Modifiers.Check (
2565 parent.AllowedModifiers, mod, accmods, l);
2568 public override void Register ()
2572 public override PendingImplementation GetPendingImplementations ()
2574 return PartialContainer.Pending;
2577 public override bool VerifyImplements (Type interface_type, string full,
2578 string name, Location loc)
2580 return PartialContainer.VerifyImplements (
2581 interface_type, full, name, loc);
2584 public override MemberCache ParentCache {
2586 return PartialContainer.ParentCache;
2591 public abstract class ClassOrStruct : TypeContainer {
2592 bool hasExplicitLayout = false;
2593 ListDictionary declarative_security;
2595 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2596 MemberName name, Attributes attrs, Kind kind,
2598 : base (ns, parent, name, attrs, kind, l)
2602 public override PendingImplementation GetPendingImplementations ()
2604 return PendingImplementation.GetPendingImplementations (this);
2607 public override bool HasExplicitLayout {
2609 return hasExplicitLayout;
2613 protected override void VerifyMembers (EmitContext ec)
2615 base.VerifyMembers (ec);
2617 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2618 foreach (Event e in events){
2620 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2625 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2627 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2628 if (declarative_security == null)
2629 declarative_security = new ListDictionary ();
2631 a.ExtractSecurityPermissionSet (declarative_security);
2635 if (a.Type == TypeManager.struct_layout_attribute_type
2636 && (LayoutKind) a.GetPositionalValue (0) == LayoutKind.Explicit)
2637 hasExplicitLayout = true;
2639 base.ApplyAttributeBuilder (a, cb);
2642 public override void Emit()
2646 if (declarative_security != null) {
2647 foreach (DictionaryEntry de in declarative_security) {
2648 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2653 public override void Register ()
2655 Parent.AddClassOrStruct (this);
2660 /// Class handles static classes declaration
2662 public sealed class StaticClass: Class {
2663 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2664 Attributes attrs, Location l)
2665 : base (ns, parent, name, mod & ~Modifiers.STATIC, attrs, l)
2667 if (RootContext.Version == LanguageVersion.ISO_1) {
2668 Report.FeatureIsNotStandardized (l, "static classes");
2669 Environment.Exit (1);
2673 protected override void DefineContainerMembers (MemberCoreArrayList list)
2678 foreach (MemberCore m in list) {
2679 if (m is Operator) {
2680 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2684 if ((m.ModFlags & Modifiers.STATIC) != 0)
2687 if (m is Constructor) {
2688 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2692 if (m is Destructor) {
2693 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2697 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2700 base.DefineContainerMembers (list);
2703 public override TypeBuilder DefineType()
2705 TypeBuilder tb = base.DefineType ();
2709 if (ptype != TypeManager.object_type) {
2710 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2714 if (ifaces != null) {
2715 foreach (Type t in ifaces)
2716 Report.SymbolRelatedToPreviousError (t);
2717 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2722 public override TypeAttributes TypeAttr {
2724 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2729 public class Class : ClassOrStruct {
2731 // Modifiers allowed in a class declaration
2733 public const int AllowedModifiers =
2736 Modifiers.PROTECTED |
2737 Modifiers.INTERNAL |
2739 Modifiers.ABSTRACT |
2743 // Information in the case we are an attribute type
2744 AttributeUsageAttribute attribute_usage;
2746 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2747 Attributes attrs, Location l)
2748 : base (ns, parent, name, attrs, Kind.Class, l)
2752 if (parent.Parent == null)
2753 accmods = Modifiers.INTERNAL;
2755 accmods = Modifiers.PRIVATE;
2757 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2758 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.SEALED)) == (Modifiers.ABSTRACT | Modifiers.SEALED)) {
2759 Report.Error (502, Location, "'{0}' cannot be both abstract and sealed", GetSignatureForError ());
2762 attribute_usage = new AttributeUsageAttribute (AttributeTargets.All);
2765 public override AttributeTargets AttributeTargets {
2767 return AttributeTargets.Class;
2771 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2773 if (a.UsageAttribute != null) {
2774 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2775 TypeBuilder.FullName != "System.Attribute") {
2776 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2778 attribute_usage = a.UsageAttribute;
2781 base.ApplyAttributeBuilder (a, cb);
2784 public AttributeUsageAttribute AttributeUsage {
2786 return attribute_usage;
2790 public const TypeAttributes DefaultTypeAttributes =
2791 TypeAttributes.AutoLayout | TypeAttributes.Class;
2794 // FIXME: How do we deal with the user specifying a different
2797 public override TypeAttributes TypeAttr {
2799 return base.TypeAttr | DefaultTypeAttributes;
2804 public class Struct : ClassOrStruct {
2806 // Modifiers allowed in a struct declaration
2808 public const int AllowedModifiers =
2811 Modifiers.PROTECTED |
2812 Modifiers.INTERNAL |
2816 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2817 int mod, Attributes attrs, Location l)
2818 : base (ns, parent, name, attrs, Kind.Struct, l)
2822 if (parent.Parent == null)
2823 accmods = Modifiers.INTERNAL;
2825 accmods = Modifiers.PRIVATE;
2827 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2829 this.ModFlags |= Modifiers.SEALED;
2832 public override AttributeTargets AttributeTargets {
2834 return AttributeTargets.Struct;
2838 public const TypeAttributes DefaultTypeAttributes =
2839 TypeAttributes.SequentialLayout |
2840 TypeAttributes.Sealed |
2841 TypeAttributes.BeforeFieldInit;
2844 // FIXME: Allow the user to specify a different set of attributes
2845 // in some cases (Sealed for example is mandatory for a class,
2846 // but what SequentialLayout can be changed
2848 public override TypeAttributes TypeAttr {
2850 return base.TypeAttr | DefaultTypeAttributes;
2858 public class Interface : TypeContainer, IMemberContainer {
2860 /// Modifiers allowed in a class declaration
2862 public const int AllowedModifiers =
2865 Modifiers.PROTECTED |
2866 Modifiers.INTERNAL |
2870 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2871 Attributes attrs, Location l)
2872 : base (ns, parent, name, attrs, Kind.Interface, l)
2876 if (parent.Parent == null)
2877 accmods = Modifiers.INTERNAL;
2879 accmods = Modifiers.PRIVATE;
2881 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2884 public override void Register ()
2886 Parent.AddInterface (this);
2889 public override PendingImplementation GetPendingImplementations ()
2894 public override AttributeTargets AttributeTargets {
2896 return AttributeTargets.Interface;
2900 public const TypeAttributes DefaultTypeAttributes =
2901 TypeAttributes.AutoLayout |
2902 TypeAttributes.Abstract |
2903 TypeAttributes.Interface;
2905 public override TypeAttributes TypeAttr {
2907 return base.TypeAttr | DefaultTypeAttributes;
2912 public abstract class MethodCore : MemberBase {
2913 public readonly Parameters Parameters;
2914 protected ToplevelBlock block;
2917 // Parameters, cached for semantic analysis.
2919 protected InternalParameters parameter_info;
2920 protected Type [] parameter_types;
2922 // Whether this is an operator method.
2923 public bool IsOperator;
2926 // The method we're overriding if this is an override method.
2928 protected MethodInfo parent_method = null;
2930 static string[] attribute_targets = new string [] { "method", "return" };
2932 public MethodCore (TypeContainer parent, Expression type, int mod,
2933 int allowed_mod, bool is_interface, MemberName name,
2934 Attributes attrs, Parameters parameters, Location loc)
2935 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
2938 Parameters = parameters;
2939 IsInterface = is_interface;
2943 // Returns the System.Type array for the parameters of this method
2945 public Type [] ParameterTypes {
2947 return parameter_types;
2951 public InternalParameters ParameterInfo
2954 return parameter_info;
2958 public ToplevelBlock Block {
2968 protected override bool CheckBase ()
2970 if (!base.CheckBase ())
2973 // Check whether arguments were correct.
2974 if (!DoDefineParameters ())
2977 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
2983 // Is null for System.Object while compiling corlib and base interfaces
2984 if (Parent.ParentCache == null) {
2985 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
2986 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
2991 Type parent_ret_type = null;
2992 parent_method = FindOutParentMethod (Parent, ref parent_ret_type);
2994 // method is override
2995 if (parent_method != null) {
2997 if (!CheckMethodAgainstBase ())
3000 if ((ModFlags & Modifiers.NEW) == 0) {
3001 if (MemberType != TypeManager.TypeToCoreType (parent_ret_type)) {
3002 Report.SymbolRelatedToPreviousError (parent_method);
3003 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3004 "change return type when overriding inherited member");
3008 if (parent_method.IsAbstract && !IsInterface) {
3009 Report.SymbolRelatedToPreviousError (parent_method);
3010 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3015 if (parent_method.IsSpecialName && !(this is PropertyBase)) {
3016 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (parent_method));
3020 if (RootContext.WarningLevel > 2) {
3021 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3022 Parent.Methods.HasEquals = true;
3023 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3024 Parent.Methods.HasGetHashCode = true;
3027 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (parent_method);
3029 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3030 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3031 Report.SymbolRelatedToPreviousError (parent_method);
3032 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3038 MemberInfo conflict_symbol = Parent.FindMemberWithSameName (Name, !(this is Property));
3039 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3040 if (conflict_symbol != null) {
3041 Report.SymbolRelatedToPreviousError (conflict_symbol);
3042 if (this is PropertyBase)
3043 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3045 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3047 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3051 if (conflict_symbol == null) {
3052 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3053 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3058 if ((ModFlags & Modifiers.NEW) == 0) {
3059 if (this is Method && conflict_symbol is MethodBase)
3062 Report.SymbolRelatedToPreviousError (conflict_symbol);
3063 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3071 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3072 // that have been defined.
3074 // `name' is the user visible name for reporting errors (this is used to
3075 // provide the right name regarding method names and properties)
3077 bool CheckMethodAgainstBase ()
3081 // TODO: replace with GetSignatureForError
3082 string name = parent_method.DeclaringType.Name + "." + parent_method.Name;
3084 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3085 if (!(parent_method.IsAbstract || parent_method.IsVirtual)){
3087 506, Location, Parent.MakeName (Name) +
3088 ": cannot override inherited member `" +
3089 name + "' because it is not " +
3090 "virtual, abstract or override");
3094 // Now we check that the overriden method is not final
3096 if (parent_method.IsFinal) {
3097 // This happens when implementing interface methods.
3098 if (parent_method.IsHideBySig && parent_method.IsVirtual) {
3100 506, Location, Parent.MakeName (Name) +
3101 ": cannot override inherited member `" +
3102 name + "' because it is not " +
3103 "virtual, abstract or override");
3105 Report.Error (239, Location, Parent.MakeName (Name) + " : cannot " +
3106 "override inherited member `" + name +
3107 "' because it is sealed.");
3111 // Check that the permissions are not being changed
3113 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3114 MethodAttributes parentp = parent_method.Attributes & MethodAttributes.MemberAccessMask;
3117 // special case for "protected internal"
3120 if ((parentp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3122 // when overriding protected internal, the method can be declared
3123 // protected internal only within the same assembly
3126 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3127 if (Parent.TypeBuilder.Assembly != parent_method.DeclaringType.Assembly){
3129 // assemblies differ - report an error
3132 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3134 } else if (thisp != parentp) {
3136 // same assembly, but other attributes differ - report an error
3139 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3142 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3144 // if it's not "protected internal", it must be "protected"
3147 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3149 } else if (Parent.TypeBuilder.Assembly == parent_method.DeclaringType.Assembly) {
3151 // protected within the same assembly - an error
3153 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3155 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3156 (parentp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3158 // protected ok, but other attributes differ - report an error
3160 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3164 if (thisp != parentp){
3165 Error_CannotChangeAccessModifiers (Parent, parent_method, name);
3171 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3172 ModFlags |= Modifiers.NEW;
3173 Report.SymbolRelatedToPreviousError (parent_method);
3174 if (!IsInterface && (parent_method.IsVirtual || parent_method.IsAbstract)) {
3175 if (RootContext.WarningLevel >= 2)
3176 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));
3178 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3184 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo parent_method, string name)
3187 // FIXME: report the old/new permissions?
3190 507, Location, parent.MakeName (Name) +
3191 ": can't change the access modifiers when overriding inherited " +
3192 "member `" + name + "'");
3195 protected static string Error722 {
3197 return "'{0}': static types cannot be used as return types";
3202 /// For custom member duplication search in a container
3204 protected abstract bool CheckForDuplications ();
3207 /// Gets parent method and its return type
3209 protected abstract MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type);
3211 protected virtual bool DoDefineParameters ()
3213 EmitContext ec = Parent.EmitContext;
3215 throw new InternalErrorException ("DoDefineParameters invoked too early");
3217 bool old_unsafe = ec.InUnsafe;
3218 ec.InUnsafe = InUnsafe;
3219 // Check if arguments were correct
3220 parameter_types = Parameters.GetParameterInfo (ec);
3221 ec.InUnsafe = old_unsafe;
3223 if ((parameter_types == null) ||
3224 !CheckParameters (Parent, parameter_types))
3227 parameter_info = new InternalParameters (parameter_types, Parameters);
3229 Parameter array_param = Parameters.ArrayParameter;
3230 if ((array_param != null) &&
3231 (!array_param.ParameterType.IsArray ||
3232 (array_param.ParameterType.GetArrayRank () != 1))) {
3233 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3240 public override string[] ValidAttributeTargets {
3242 return attribute_targets;
3246 protected override bool VerifyClsCompliance (DeclSpace ds)
3248 if (!base.VerifyClsCompliance (ds)) {
3249 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3250 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3255 if (Parameters.HasArglist) {
3256 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3259 if (!AttributeTester.IsClsCompliant (MemberType)) {
3260 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant", GetSignatureForError ());
3263 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3268 protected bool IsDuplicateImplementation (MethodCore method)
3270 if ((method == this) || (method.Name != Name))
3273 Type[] param_types = method.ParameterTypes;
3274 if (param_types == null)
3277 if (param_types.Length != ParameterTypes.Length)
3280 for (int i = 0; i < param_types.Length; i++)
3281 if (param_types [i] != ParameterTypes [i])
3284 // TODO: make operator compatible with MethodCore to avoid this
3285 if (this is Operator && method is Operator) {
3286 if (MemberType != method.MemberType)
3291 // Try to report 663: method only differs on out/ref
3293 ParameterData info = ParameterInfo;
3294 ParameterData other_info = method.ParameterInfo;
3295 for (int i = 0; i < info.Count; i++){
3296 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3297 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3302 Report.SymbolRelatedToPreviousError (method);
3303 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3307 protected override void VerifyObsoleteAttribute()
3309 base.VerifyObsoleteAttribute ();
3311 if (parameter_types == null)
3314 foreach (Type type in parameter_types) {
3315 CheckUsageOfObsoleteAttribute (type);
3320 public class SourceMethod : ISourceMethod
3322 TypeContainer container;
3325 protected SourceMethod (TypeContainer container, MethodBase builder,
3326 ISourceFile file, Location start, Location end)
3328 this.container = container;
3329 this.builder = builder;
3331 CodeGen.SymbolWriter.OpenMethod (
3332 file, this, start.Row, 0, end.Row, 0);
3335 public string Name {
3336 get { return builder.Name; }
3339 public int NamespaceID {
3340 get { return container.NamespaceEntry.SymbolFileID; }
3345 if (builder is MethodBuilder)
3346 return ((MethodBuilder) builder).GetToken ().Token;
3347 else if (builder is ConstructorBuilder)
3348 return ((ConstructorBuilder) builder).GetToken ().Token;
3350 throw new NotSupportedException ();
3354 public void CloseMethod ()
3356 if (CodeGen.SymbolWriter != null)
3357 CodeGen.SymbolWriter.CloseMethod ();
3360 public static SourceMethod Create (TypeContainer parent,
3361 MethodBase builder, Block block)
3363 if (CodeGen.SymbolWriter == null)
3368 Location start_loc = block.StartLocation;
3369 if (Location.IsNull (start_loc))
3372 Location end_loc = block.EndLocation;
3373 if (Location.IsNull (end_loc))
3376 ISourceFile file = start_loc.SourceFile;
3380 return new SourceMethod (
3381 parent, builder, file, start_loc, end_loc);
3385 public class Method : MethodCore, IIteratorContainer, IMethodData {
3386 public MethodBuilder MethodBuilder;
3387 public MethodData MethodData;
3388 ReturnParameter return_attributes;
3389 ListDictionary declarative_security;
3392 /// Modifiers allowed in a class declaration
3394 const int AllowedModifiers =
3397 Modifiers.PROTECTED |
3398 Modifiers.INTERNAL |
3403 Modifiers.OVERRIDE |
3404 Modifiers.ABSTRACT |
3406 Modifiers.METHOD_YIELDS |
3409 const int AllowedInterfaceModifiers =
3410 Modifiers.NEW | Modifiers.UNSAFE;
3413 // return_type can be "null" for VOID values.
3415 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3416 MemberName name, Parameters parameters, Attributes attrs,
3418 : base (ds, return_type, mod,
3419 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3420 is_iface, name, attrs, parameters, l)
3424 public override AttributeTargets AttributeTargets {
3426 return AttributeTargets.Method;
3430 public override string GetSignatureForError()
3432 if (MethodBuilder == null) {
3433 return GetSignatureForError (Parent);
3435 return TypeManager.CSharpSignature (MethodBuilder);
3439 /// Use this method when MethodBuilder is null
3441 public override string GetSignatureForError (TypeContainer tc)
3443 // TODO: get params from somewhere
3444 if (parameter_info == null)
3445 return base.GetSignatureForError (tc);
3447 // TODO: move to parameters
3448 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3449 if (parameter_info.Parameters.FixedParameters != null) {
3450 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3451 Parameter p = parameter_info.Parameters.FixedParameters [i];
3452 args.Append (p.GetSignatureForError ());
3454 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3459 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3462 void DuplicateEntryPoint (MethodInfo b, Location location)
3466 "Program `" + CodeGen.FileName +
3467 "' has more than one entry point defined: `" +
3468 TypeManager.CSharpSignature(b) + "'");
3471 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3473 if (b.ReturnType != TypeManager.void_type &&
3474 b.ReturnType != TypeManager.int32_type)
3477 if (pinfo.Count == 0)
3480 if (pinfo.Count > 1)
3483 Type t = pinfo.ParameterType(0);
3485 (t.GetArrayRank() == 1) &&
3486 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3487 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3493 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3495 if (a.Target == AttributeTargets.ReturnValue) {
3496 if (return_attributes == null)
3497 return_attributes = new ReturnParameter (MethodBuilder, Location);
3499 return_attributes.ApplyAttributeBuilder (a, cb);
3503 if (a.Type == TypeManager.methodimpl_attr_type && a.IsInternalCall) {
3504 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3507 if (a.Type == TypeManager.dllimport_type) {
3508 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3509 if ((ModFlags & extern_static) != extern_static) {
3510 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3516 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3517 if (declarative_security == null)
3518 declarative_security = new ListDictionary ();
3519 a.ExtractSecurityPermissionSet (declarative_security);
3523 if (a.Type == TypeManager.conditional_attribute_type) {
3524 if (IsOperator || IsExplicitImpl) {
3525 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3529 if (ReturnType != TypeManager.void_type) {
3530 Report.Error (578, Location, "Conditional not valid on '{0}' because its return new ErrorData ( type is not void", GetSignatureForError ());
3534 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3535 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3540 Report.Error (582, Location, "Conditional not valid on interface members");
3544 if (MethodData.IsImplementing) {
3545 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3549 for (int i = 0; i < parameter_info.Count; ++i) {
3550 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3551 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3557 MethodBuilder.SetCustomAttribute (cb);
3560 protected override bool CheckForDuplications ()
3562 ArrayList ar = Parent.Methods;
3564 int arLen = ar.Count;
3566 for (int i = 0; i < arLen; i++) {
3567 Method m = (Method) ar [i];
3568 if (IsDuplicateImplementation (m))
3573 ar = Parent.Properties;
3575 for (int i = 0; i < ar.Count; ++i) {
3576 PropertyBase pb = (PropertyBase) ar [i];
3577 if (pb.AreAccessorsDuplicateImplementation (this))
3582 ar = Parent.Indexers;
3584 for (int i = 0; i < ar.Count; ++i) {
3585 PropertyBase pb = (PropertyBase) ar [i];
3586 if (pb.AreAccessorsDuplicateImplementation (this))
3593 for (int i = 0; i < ar.Count; ++i) {
3594 Event ev = (Event) ar [i];
3595 if (ev.AreAccessorsDuplicateImplementation (this))
3606 public override bool Define ()
3615 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3617 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3619 if (!MethodData.Define (Parent))
3623 // Setup iterator if we are one
3625 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3626 Iterator iterator = new Iterator (
3627 Parent, Name, MemberType, ParameterTypes,
3628 ParameterInfo, ModFlags, block, Location);
3630 if (!iterator.DefineIterator ())
3633 block = iterator.Block;
3636 MethodBuilder = MethodData.MethodBuilder;
3639 // This is used to track the Entry Point,
3641 if (Name == "Main" &&
3642 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3643 (RootContext.MainClass == null ||
3644 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3645 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3646 if (RootContext.EntryPoint == null) {
3647 RootContext.EntryPoint = MethodBuilder;
3648 RootContext.EntryPointLocation = Location;
3650 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3651 DuplicateEntryPoint (MethodBuilder, Location);
3654 if (RootContext.WarningLevel >= 4)
3655 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3659 if (MemberType.IsAbstract && MemberType.IsSealed) {
3660 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3670 public override void Emit ()
3672 MethodData.Emit (Parent, this);
3675 if (declarative_security != null) {
3676 foreach (DictionaryEntry de in declarative_security) {
3677 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3685 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
3687 MethodInfo mi = (MethodInfo) container.ParentCache.FindMemberToOverride (
3688 container.TypeBuilder, Name, ParameterTypes, false);
3693 parent_ret_type = mi.ReturnType;
3697 protected override bool VerifyClsCompliance(DeclSpace ds)
3699 if (!base.VerifyClsCompliance (ds))
3702 if (parameter_types.Length > 0) {
3703 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3705 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3712 void IIteratorContainer.SetYields ()
3714 ModFlags |= Modifiers.METHOD_YIELDS;
3717 #region IMethodData Members
3719 public CallingConventions CallingConventions {
3721 CallingConventions cc = Parameters.GetCallingConvention ();
3722 if (Parameters.HasArglist)
3723 block.HasVarargs = true;
3726 if ((ModFlags & Modifiers.STATIC) == 0)
3727 cc |= CallingConventions.HasThis;
3729 // FIXME: How is `ExplicitThis' used in C#?
3735 public Type ReturnType {
3741 public MemberName MethodName {
3747 public new Location Location {
3749 return base.Location;
3753 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3755 return new EmitContext (
3756 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3759 public ObsoleteAttribute GetObsoleteAttribute ()
3761 return GetObsoleteAttribute (Parent);
3765 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3767 public bool IsExcluded (EmitContext ec)
3769 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3770 return (caching_flags & Flags.Excluded) != 0;
3772 caching_flags &= ~Flags.Excluded_Undetected;
3774 if (parent_method == null) {
3775 if (OptAttributes == null)
3778 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
3783 foreach (Attribute a in attrs) {
3784 string condition = a.GetConditionalAttributeValue (
3786 if (RootContext.AllDefines.Contains (condition))
3790 caching_flags |= Flags.Excluded;
3794 IMethodData md = TypeManager.GetMethod (parent_method);
3796 if (AttributeTester.IsConditionalMethodExcluded (parent_method)) {
3797 caching_flags |= Flags.Excluded;
3803 if (md.IsExcluded (ec)) {
3804 caching_flags |= Flags.Excluded;
3813 public abstract class ConstructorInitializer {
3814 ArrayList argument_list;
3815 protected ConstructorInfo parent_constructor;
3816 Parameters parameters;
3819 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
3822 this.argument_list = argument_list;
3823 this.parameters = parameters;
3827 public ArrayList Arguments {
3829 return argument_list;
3833 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
3835 Expression parent_constructor_group;
3838 ec.CurrentBlock = new ToplevelBlock (Block.Flags.Implicit, parameters, loc);
3840 if (argument_list != null){
3841 foreach (Argument a in argument_list){
3842 if (!a.Resolve (ec, loc))
3846 ec.CurrentBlock = null;
3848 if (this is ConstructorBaseInitializer) {
3849 if (ec.ContainerType.BaseType == null)
3852 t = ec.ContainerType.BaseType;
3853 if (ec.ContainerType.IsValueType) {
3854 Report.Error (522, loc,
3855 "structs cannot call base class constructors");
3859 t = ec.ContainerType;
3861 parent_constructor_group = Expression.MemberLookup (
3862 ec, t, ".ctor", MemberTypes.Constructor,
3863 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3866 if (parent_constructor_group == null){
3867 parent_constructor_group = Expression.MemberLookup (
3868 ec, t, ".ctor", MemberTypes.Constructor,
3869 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
3872 if (parent_constructor_group != null)
3874 112, loc, "`{0}.{1}' is inaccessible due to " +
3875 "its protection level", t.FullName, t.Name);
3878 1501, loc, "Can not find a constructor for " +
3879 "this argument list");
3883 parent_constructor = (ConstructorInfo) Invocation.OverloadResolve (
3884 ec, (MethodGroupExpr) parent_constructor_group, argument_list,
3887 if (parent_constructor == null){
3888 Report.Error (1501, loc,
3889 "Can not find a constructor for this argument list");
3893 if (parent_constructor == caller_builder){
3894 Report.Error (516, String.Format ("Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder)));
3901 public void Emit (EmitContext ec)
3903 if (parent_constructor != null){
3904 ec.Mark (loc, false);
3906 Invocation.EmitCall (ec, true, true, null, parent_constructor, argument_list, loc);
3908 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), parent_constructor, argument_list, loc);
3913 /// Method search for base ctor. (We do not cache it).
3915 Constructor GetOverloadedConstructor (TypeContainer tc)
3917 if (tc.InstanceConstructors == null)
3920 foreach (Constructor c in tc.InstanceConstructors) {
3921 if (Arguments == null) {
3922 if (c.ParameterTypes.Length == 0)
3930 int count = c.ParameterInfo.Count;
3932 c.ParameterInfo.ParameterModifier (count - 1) == Parameter.Modifier.PARAMS) {
3933 for (int i = 0; i < count-1; i++)
3934 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
3939 if (c.ParameterTypes.Length != Arguments.Count)
3942 for (int i = 0; i < Arguments.Count; ++i)
3943 if (c.ParameterTypes [i] != ((Argument)Arguments [i]).Type) {
3958 //TODO: implement caching when it will be necessary
3959 public virtual void CheckObsoleteAttribute (TypeContainer tc, Location loc)
3961 Constructor ctor = GetOverloadedConstructor (tc);
3965 ObsoleteAttribute oa = ctor.GetObsoleteAttribute (tc);
3969 AttributeTester.Report_ObsoleteMessage (oa, ctor.GetSignatureForError (), loc);
3973 public class ConstructorBaseInitializer : ConstructorInitializer {
3974 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
3975 base (argument_list, pars, l)
3979 public override void CheckObsoleteAttribute(TypeContainer tc, Location loc) {
3980 if (parent_constructor == null)
3983 TypeContainer type_ds = TypeManager.LookupTypeContainer (tc.TypeBuilder.BaseType);
3984 if (type_ds == null) {
3985 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (parent_constructor);
3988 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (parent_constructor), loc);
3993 base.CheckObsoleteAttribute (type_ds, loc);
3998 public class ConstructorThisInitializer : ConstructorInitializer {
3999 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4000 base (argument_list, pars, l)
4005 public class Constructor : MethodCore, IMethodData {
4006 public ConstructorBuilder ConstructorBuilder;
4007 public ConstructorInitializer Initializer;
4008 ListDictionary declarative_security;
4011 // Modifiers allowed for a constructor.
4013 public const int AllowedModifiers =
4015 Modifiers.PROTECTED |
4016 Modifiers.INTERNAL |
4022 bool has_compliant_args = false;
4024 // The spec claims that static is not permitted, but
4025 // my very own code has static constructors.
4027 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4028 ConstructorInitializer init, Location l)
4029 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4035 public override string GetSignatureForError()
4037 if (ConstructorBuilder == null)
4038 return GetSignatureForError (Parent);
4040 return TypeManager.CSharpSignature (ConstructorBuilder);
4043 public bool HasCompliantArgs {
4045 return has_compliant_args;
4049 public override AttributeTargets AttributeTargets {
4051 return AttributeTargets.Constructor;
4057 // Returns true if this is a default constructor
4059 public bool IsDefault ()
4061 if ((ModFlags & Modifiers.STATIC) != 0)
4062 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4063 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4066 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4067 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4068 (Initializer is ConstructorBaseInitializer) &&
4069 (Initializer.Arguments == null);
4072 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4074 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4075 if (declarative_security == null) {
4076 declarative_security = new ListDictionary ();
4078 a.ExtractSecurityPermissionSet (declarative_security);
4082 ConstructorBuilder.SetCustomAttribute (cb);
4085 protected override bool CheckForDuplications ()
4087 ArrayList ar = Parent.InstanceConstructors;
4089 int arLen = ar.Count;
4091 for (int i = 0; i < arLen; i++) {
4092 Constructor m = (Constructor) ar [i];
4093 if (IsDuplicateImplementation (m))
4100 protected override bool CheckBase ()
4102 // Check whether arguments were correct.
4103 if (!DoDefineParameters ())
4106 // TODO: skip the rest for generated ctor
4107 if ((ModFlags & Modifiers.STATIC) != 0)
4110 if (!CheckForDuplications ())
4113 if (Parent.Kind == Kind.Struct) {
4114 if (ParameterTypes.Length == 0) {
4115 Report.Error (568, Location,
4116 "Structs can not contain explicit parameterless " +
4121 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4122 Report.Error (666, Location, "Protected member in struct declaration");
4127 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4128 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4135 // Creates the ConstructorBuilder
4137 public override bool Define ()
4139 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4140 MethodAttributes.SpecialName);
4142 if ((ModFlags & Modifiers.STATIC) != 0) {
4143 ca |= MethodAttributes.Static | MethodAttributes.Private;
4145 ca |= MethodAttributes.HideBySig;
4147 if ((ModFlags & Modifiers.PUBLIC) != 0)
4148 ca |= MethodAttributes.Public;
4149 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4150 if ((ModFlags & Modifiers.INTERNAL) != 0)
4151 ca |= MethodAttributes.FamORAssem;
4153 ca |= MethodAttributes.Family;
4154 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4155 ca |= MethodAttributes.Assembly;
4156 else if (IsDefault ())
4157 ca |= MethodAttributes.Public;
4159 ca |= MethodAttributes.Private;
4162 // Check if arguments were correct.
4166 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4167 ca, CallingConventions,
4170 if ((ModFlags & Modifiers.UNSAFE) != 0)
4171 ConstructorBuilder.InitLocals = false;
4173 TypeManager.AddMethod (ConstructorBuilder, this);
4176 // HACK because System.Reflection.Emit is lame
4178 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4186 public override void Emit ()
4188 EmitContext ec = CreateEmitContext (null, null);
4191 // extern methods have no bodies
4193 if ((ModFlags & Modifiers.EXTERN) != 0) {
4194 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4196 179, Location, "External constructor `" +
4197 TypeManager.CSharpSignature (ConstructorBuilder) +
4198 "' can not have a body");
4201 } else if (block == null) {
4203 501, Location, "Constructor `" +
4204 TypeManager.CSharpSignature (ConstructorBuilder) +
4205 "' must declare a body since it is not marked extern");
4209 if ((ModFlags & Modifiers.STATIC) == 0){
4210 if (Parent.Kind == Kind.Class && Initializer == null)
4211 Initializer = new ConstructorBaseInitializer (
4212 null, Parameters.EmptyReadOnlyParameters, Location);
4216 // Spec mandates that Initializers will not have
4220 if (Initializer != null && !Initializer.Resolve (ConstructorBuilder, ec))
4222 ec.IsStatic = false;
4225 Parameters.LabelParameters (ec, ConstructorBuilder, Location);
4227 SourceMethod source = SourceMethod.Create (
4228 Parent, ConstructorBuilder, block);
4231 // Classes can have base initializers and instance field initializers.
4233 if (Parent.Kind == Kind.Class){
4234 if ((ModFlags & Modifiers.STATIC) == 0){
4237 // If we use a "this (...)" constructor initializer, then
4238 // do not emit field initializers, they are initialized in the other constructor
4240 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4241 Parent.EmitFieldInitializers (ec);
4244 if (Initializer != null) {
4245 if (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null)
4246 Initializer.CheckObsoleteAttribute (Parent, Location);
4248 ec.TestObsoleteMethodUsage = false;
4249 Initializer.Emit (ec);
4252 if ((ModFlags & Modifiers.STATIC) != 0)
4253 Parent.EmitFieldInitializers (ec);
4255 if (OptAttributes != null)
4256 OptAttributes.Emit (ec, this);
4258 // If this is a non-static `struct' constructor and doesn't have any
4259 // initializer, it must initialize all of the struct's fields.
4260 if ((Parent.Kind == Kind.Struct) &&
4261 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4262 Block.AddThisVariable (Parent, Location);
4264 ec.EmitTopBlock (block, ParameterInfo, Location);
4267 source.CloseMethod ();
4271 if (declarative_security != null) {
4272 foreach (DictionaryEntry de in declarative_security) {
4273 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4280 // Is never override
4281 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
4286 protected override bool VerifyClsCompliance (DeclSpace ds)
4288 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4292 if (parameter_types.Length > 0) {
4293 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4295 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4297 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4298 foreach (Type param in parameter_types) {
4299 if (param.IsArray) {
4305 has_compliant_args = true;
4309 #region IMethodData Members
4311 public System.Reflection.CallingConventions CallingConventions {
4313 CallingConventions cc = Parameters.GetCallingConvention ();
4315 if (Parent.Kind == Kind.Class)
4316 if ((ModFlags & Modifiers.STATIC) == 0)
4317 cc |= CallingConventions.HasThis;
4319 // FIXME: How is `ExplicitThis' used in C#?
4325 public new Location Location {
4327 return base.Location;
4331 public MemberName MethodName {
4337 public Type ReturnType {
4343 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4345 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4346 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4349 public ObsoleteAttribute GetObsoleteAttribute ()
4354 public bool IsExcluded(EmitContext ec)
4363 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4365 public interface IMethodData
4367 CallingConventions CallingConventions { get; }
4368 Location Location { get; }
4369 MemberName MethodName { get; }
4370 Type[] ParameterTypes { get; }
4371 Type ReturnType { get; }
4373 Attributes OptAttributes { get; }
4374 ToplevelBlock Block { get; }
4376 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4377 ObsoleteAttribute GetObsoleteAttribute ();
4378 string GetSignatureForError (TypeContainer tc);
4379 bool IsExcluded (EmitContext ec);
4380 bool IsClsCompliaceRequired (DeclSpace ds);
4384 // Encapsulates most of the Method's state
4386 public class MethodData {
4388 readonly IMethodData method;
4391 // The return type of this method
4393 public readonly InternalParameters ParameterInfo;
4396 // Are we implementing an interface ?
4398 public bool IsImplementing = false;
4403 protected MemberBase member;
4404 protected int modifiers;
4405 protected MethodAttributes flags;
4407 MethodBuilder builder = null;
4408 public MethodBuilder MethodBuilder {
4414 public MethodData (MemberBase member, InternalParameters parameters,
4415 int modifiers, MethodAttributes flags, IMethodData method)
4417 this.member = member;
4418 this.ParameterInfo = parameters;
4419 this.modifiers = modifiers;
4422 this.method = method;
4425 public bool Define (TypeContainer container)
4427 MethodInfo implementing = null;
4429 string name = method.MethodName.Name;
4430 string method_name = name;
4432 Type[] ParameterTypes = method.ParameterTypes;
4434 if (container.Pending != null){
4435 if (member is Indexer)
4436 implementing = container.Pending.IsInterfaceIndexer (
4437 member.InterfaceType, method.ReturnType, ParameterTypes);
4439 implementing = container.Pending.IsInterfaceMethod (
4440 member.InterfaceType, name, method.ReturnType, ParameterTypes);
4442 if (member.InterfaceType != null){
4443 if (implementing == null){
4444 Report.Error (539, method.Location,
4445 "'{0}' in explicit interface declaration is not an interface", method_name);
4448 method_name = member.InterfaceType.FullName + "." + name;
4453 // For implicit implementations, make sure we are public, for
4454 // explicit implementations, make sure we are private.
4456 if (implementing != null){
4458 // Setting null inside this block will trigger a more
4459 // verbose error reporting for missing interface implementations
4461 // The "candidate" function has been flagged already
4462 // but it wont get cleared
4464 if (member.IsExplicitImpl){
4465 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4466 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4467 implementing = null;
4469 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4470 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4472 // If this is an interface method implementation,
4473 // check for public accessibility
4475 implementing = null;
4476 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4477 // We may never be private.
4478 implementing = null;
4479 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4481 // We may be protected if we're overriding something.
4483 implementing = null;
4488 // Static is not allowed
4490 if ((modifiers & Modifiers.STATIC) != 0){
4491 implementing = null;
4492 Modifiers.Error_InvalidModifier (method.Location, "static");
4497 // If implementing is still valid, set flags
4499 if (implementing != null){
4501 // When implementing interface methods, set NewSlot
4502 // unless, we are overwriting a method.
4504 if (implementing.DeclaringType.IsInterface){
4505 if ((modifiers & Modifiers.OVERRIDE) == 0)
4506 flags |= MethodAttributes.NewSlot;
4509 MethodAttributes.Virtual |
4510 MethodAttributes.HideBySig;
4512 // Set Final unless we're virtual, abstract or already overriding a method.
4513 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4514 flags |= MethodAttributes.Final;
4516 IsImplementing = true;
4519 EmitContext ec = method.CreateEmitContext (container, null);
4521 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4523 if (builder == null)
4526 if ((modifiers & Modifiers.UNSAFE) != 0)
4527 builder.InitLocals = false;
4529 if (IsImplementing){
4531 // clear the pending implemntation flag
4533 if (member is Indexer) {
4534 container.Pending.ImplementIndexer (
4535 member.InterfaceType, builder, method.ReturnType,
4536 ParameterTypes, member.IsExplicitImpl);
4538 container.Pending.ImplementMethod (
4539 member.InterfaceType, name, method.ReturnType,
4540 ParameterTypes, member.IsExplicitImpl);
4542 if (member.IsExplicitImpl)
4543 container.TypeBuilder.DefineMethodOverride (
4544 builder, implementing);
4548 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4549 TypeManager.AddMethod (builder, method);
4556 /// Create the MethodBuilder for the method
4558 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4560 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4562 if ((modifiers & extern_static) == extern_static) {
4564 if (method.OptAttributes != null) {
4565 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4566 if (dllimport_attribute != null) {
4567 flags |= MethodAttributes.PinvokeImpl;
4568 builder = dllimport_attribute.DefinePInvokeMethod (
4569 ec, container.TypeBuilder, method_name, flags,
4570 method.ReturnType, ParameterTypes);
4576 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4577 // We are more strict than Microsoft and report CS0626 like error
4578 if (method.OptAttributes == null ||
4579 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4580 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));
4585 builder = container.TypeBuilder.DefineMethod (
4586 method_name, flags, method.CallingConventions,
4587 method.ReturnType, ParameterTypes);
4593 public void Emit (TypeContainer container, Attributable kind)
4596 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4597 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4599 ec = method.CreateEmitContext (container, null);
4601 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container.Parent) != null)
4602 ec.TestObsoleteMethodUsage = false;
4604 Location loc = method.Location;
4605 Attributes OptAttributes = method.OptAttributes;
4607 if (OptAttributes != null)
4608 OptAttributes.Emit (ec, kind);
4610 if (member is MethodCore)
4611 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder, loc);
4613 SymbolWriter sw = CodeGen.SymbolWriter;
4614 ToplevelBlock block = method.Block;
4617 // abstract or extern methods have no bodies
4619 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4624 // abstract or extern methods have no bodies.
4626 if ((modifiers & Modifiers.ABSTRACT) != 0)
4628 500, method.Location, "Abstract method `" +
4629 TypeManager.CSharpSignature (builder) +
4630 "' can not have a body");
4632 if ((modifiers & Modifiers.EXTERN) != 0)
4634 179, method.Location, "External method `" +
4635 TypeManager.CSharpSignature (builder) +
4636 "' can not have a body");
4642 // Methods must have a body unless they're extern or abstract
4644 if (block == null) {
4646 501, method.Location, "Method `" +
4647 TypeManager.CSharpSignature (builder) +
4648 "' must declare a body since it is not marked " +
4649 "abstract or extern");
4653 SourceMethod source = SourceMethod.Create (
4654 container, MethodBuilder, method.Block);
4657 // Handle destructors specially
4659 // FIXME: This code generates buggy code
4661 if (member is Destructor)
4662 EmitDestructor (ec, block);
4664 ec.EmitTopBlock (block, ParameterInfo, loc);
4667 source.CloseMethod ();
4670 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4672 ILGenerator ig = ec.ig;
4674 Label finish = ig.DefineLabel ();
4676 block.SetDestructor ();
4678 ig.BeginExceptionBlock ();
4679 ec.ReturnLabel = finish;
4680 ec.HasReturnLabel = true;
4681 ec.EmitTopBlock (block, null, method.Location);
4683 // ig.MarkLabel (finish);
4684 ig.BeginFinallyBlock ();
4686 if (ec.ContainerType.BaseType != null) {
4687 Expression member_lookup = Expression.MemberLookup (
4688 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4689 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4691 if (member_lookup != null){
4692 MethodGroupExpr parent_destructor = ((MethodGroupExpr) member_lookup);
4694 ig.Emit (OpCodes.Ldarg_0);
4695 ig.Emit (OpCodes.Call, (MethodInfo) parent_destructor.Methods [0]);
4699 ig.EndExceptionBlock ();
4700 //ig.MarkLabel (ec.ReturnLabel);
4701 ig.Emit (OpCodes.Ret);
4705 public class Destructor : Method {
4707 public Destructor (TypeContainer ds, Expression return_type, int mod,
4708 string name, Parameters parameters, Attributes attrs,
4710 : base (ds, return_type, mod, false, new MemberName (name),
4711 parameters, attrs, l)
4714 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4716 if (a.Type == TypeManager.conditional_attribute_type) {
4717 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4721 base.ApplyAttributeBuilder (a, cb);
4725 abstract public class MemberBase : MemberCore {
4726 public Expression Type;
4728 public MethodAttributes flags;
4730 protected readonly int explicit_mod_flags;
4733 // The "short" name of this property / indexer / event. This is the
4734 // name without the explicit interface.
4736 public string ShortName;
4739 // The type of this property / indexer / event
4741 public Type MemberType;
4744 // If true, this is an explicit interface implementation
4746 public bool IsExplicitImpl = false;
4749 // The name of the interface we are explicitly implementing
4751 public MemberName ExplicitInterfaceName = null;
4754 // Whether this is an interface member.
4756 public bool IsInterface;
4759 // If true, the interface type we are explicitly implementing
4761 public Type InterfaceType = null;
4764 // The constructor is only exposed to our children
4766 protected MemberBase (TypeContainer parent, Expression type, int mod,
4767 int allowed_mod, int def_mod, MemberName name,
4768 Attributes attrs, Location loc)
4769 : base (parent, name, attrs, loc)
4771 explicit_mod_flags = mod;
4773 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4775 // Check for explicit interface implementation
4776 if (MemberName.Left != null) {
4777 ExplicitInterfaceName = MemberName.Left;
4778 ShortName = MemberName.Name;
4779 IsExplicitImpl = true;
4784 protected virtual bool CheckBase ()
4786 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4787 Report.Error (666, Location, "Protected member in struct declaration");
4791 if ((RootContext.WarningLevel >= 4) &&
4792 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4793 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4794 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4795 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4800 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4804 foreach (Type partype in parameters){
4805 if (partype == TypeManager.void_type) {
4807 1547, Location, "Keyword 'void' cannot " +
4808 "be used in this context");
4812 if (partype.IsPointer){
4815 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4819 if (ds.AsAccessible (partype, ModFlags))
4822 if (this is Indexer)
4823 Report.Error (55, Location,
4824 "Inconsistent accessibility: parameter type `" +
4825 TypeManager.CSharpName (partype) + "' is less " +
4826 "accessible than indexer `" + Name + "'");
4827 else if ((this is Method) && ((Method) this).IsOperator)
4828 Report.Error (57, Location,
4829 "Inconsistent accessibility: parameter type `" +
4830 TypeManager.CSharpName (partype) + "' is less " +
4831 "accessible than operator `" + Name + "'");
4833 Report.Error (51, Location,
4834 "Inconsistent accessibility: parameter type `" +
4835 TypeManager.CSharpName (partype) + "' is less " +
4836 "accessible than method `" + Name + "'");
4843 protected virtual bool DoDefine ()
4845 EmitContext ec = Parent.EmitContext;
4847 throw new InternalErrorException ("MemberBase.DoDefine called too early");
4850 throw new InternalErrorException ();
4853 ModFlags = Modifiers.PUBLIC |
4854 Modifiers.ABSTRACT |
4855 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
4857 flags = MethodAttributes.Public |
4858 MethodAttributes.Abstract |
4859 MethodAttributes.HideBySig |
4860 MethodAttributes.NewSlot |
4861 MethodAttributes.Virtual;
4863 if (!Parent.MethodModifiersValid (ModFlags, Name, Location))
4866 flags = Modifiers.MethodAttr (ModFlags);
4869 // Lookup Type, verify validity
4870 bool old_unsafe = ec.InUnsafe;
4871 ec.InUnsafe = InUnsafe;
4872 Type = Type.ResolveAsTypeTerminal (ec, false);
4873 ec.InUnsafe = old_unsafe;
4878 MemberType = Type.Type;
4880 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
4881 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
4882 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
4887 // verify accessibility
4888 if (!Parent.AsAccessible (MemberType, ModFlags)) {
4889 if (this is Property)
4890 Report.Error (53, Location,
4891 "Inconsistent accessibility: property type `" +
4892 TypeManager.CSharpName (MemberType) + "' is less " +
4893 "accessible than property `" + Name + "'");
4894 else if (this is Indexer)
4895 Report.Error (54, Location,
4896 "Inconsistent accessibility: indexer return type `" +
4897 TypeManager.CSharpName (MemberType) + "' is less " +
4898 "accessible than indexer `" + Name + "'");
4899 else if (this is Method) {
4900 if (((Method) this).IsOperator)
4901 Report.Error (56, Location,
4902 "Inconsistent accessibility: return type `" +
4903 TypeManager.CSharpName (MemberType) + "' is less " +
4904 "accessible than operator `" + Name + "'");
4906 Report.Error (50, Location,
4907 "Inconsistent accessibility: return type `" +
4908 TypeManager.CSharpName (MemberType) + "' is less " +
4909 "accessible than method `" + Name + "'");
4911 Report.Error (52, Location,
4912 "Inconsistent accessibility: field type `" +
4913 TypeManager.CSharpName (MemberType) + "' is less " +
4914 "accessible than field `" + Name + "'");
4918 if (MemberType.IsPointer && !UnsafeOK (Parent))
4921 if (IsExplicitImpl) {
4922 Expression expr = ExplicitInterfaceName.GetTypeExpression (Location);
4923 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
4927 InterfaceType = texpr.ResolveType (ec);
4929 if (InterfaceType.IsClass) {
4930 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", ExplicitInterfaceName);
4935 // Compute the full name that we need to export.
4936 if (InterfaceType.FullName != ExplicitInterfaceName) {
4937 ExplicitInterfaceName = InterfaceType.FullName;
4938 UpdateMemberName ();
4942 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
4945 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
4952 /// The name of the member can be changed during definition (see IndexerName attribute)
4954 protected virtual void UpdateMemberName ()
4956 MemberName.Name = ShortName;
4959 public override string GetSignatureForError (TypeContainer tc)
4961 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
4964 protected bool IsTypePermitted ()
4966 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
4967 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
4973 protected override bool VerifyClsCompliance(DeclSpace ds)
4975 if (base.VerifyClsCompliance (ds)) {
4979 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
4980 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
4985 protected override void VerifyObsoleteAttribute()
4987 CheckUsageOfObsoleteAttribute (MemberType);
4992 // Fields and Events both generate FieldBuilders, we use this to share
4993 // their common bits. This is also used to flag usage of the field
4995 abstract public class FieldBase : MemberBase {
4996 public FieldBuilder FieldBuilder;
4997 public Status status;
5000 public enum Status : byte {
5005 static string[] attribute_targets = new string [] { "field" };
5008 /// Symbol with same name in parent class/struct
5010 public MemberInfo conflict_symbol;
5013 // The constructor is only exposed to our children
5015 protected FieldBase (TypeContainer parent, Expression type, int mod,
5016 int allowed_mod, MemberName name, object init,
5017 Attributes attrs, Location loc)
5018 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5024 public override AttributeTargets AttributeTargets {
5026 return AttributeTargets.Field;
5030 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5032 if (a.Type == TypeManager.marshal_as_attr_type) {
5033 UnmanagedMarshal marshal = a.GetMarshal (this);
5034 if (marshal != null) {
5035 FieldBuilder.SetMarshal (marshal);
5040 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5041 a.Error_InvalidSecurityParent ();
5045 FieldBuilder.SetCustomAttribute (cb);
5049 // Whether this field has an initializer.
5051 public bool HasInitializer {
5053 return init != null;
5057 protected readonly Object init;
5060 Expression init_expr;
5061 bool init_expr_initialized = false;
5064 // Resolves and returns the field initializer.
5066 public Expression GetInitializerExpression (EmitContext ec)
5068 if (init_expr_initialized)
5072 if (init is Expression)
5073 e = (Expression) init;
5075 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5077 ec.IsFieldInitializer = true;
5078 e = e.DoResolve (ec);
5079 ec.IsFieldInitializer = false;
5082 init_expr_initialized = true;
5087 protected override bool CheckBase ()
5089 if (!base.CheckBase ())
5096 conflict_symbol = Parent.FindMemberWithSameName (Name, false);
5097 if (conflict_symbol == null) {
5098 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5099 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5104 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5105 Report.SymbolRelatedToPreviousError (conflict_symbol);
5106 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5112 protected override bool DoDefine ()
5114 if (!base.DoDefine ())
5117 if (MemberType == TypeManager.void_type) {
5118 Report.Error (1547, Location,
5119 "Keyword 'void' cannot be used in this context");
5125 public override string GetSignatureForError ()
5127 if (FieldBuilder == null) {
5128 return base.GetSignatureForError (Parent);
5130 return TypeManager.GetFullNameSignature (FieldBuilder);
5133 public override string[] ValidAttributeTargets {
5135 return attribute_targets;
5139 protected override bool VerifyClsCompliance (DeclSpace ds)
5141 if (!base.VerifyClsCompliance (ds))
5144 if (FieldBuilder == null) {
5148 if (!AttributeTester.IsClsCompliant (FieldBuilder.FieldType)) {
5149 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5155 public void SetAssigned ()
5157 status |= Status.ASSIGNED;
5161 public abstract class FieldMember: FieldBase
5163 bool has_field_offset = false;
5165 protected FieldMember (TypeContainer parent, Expression type, int mod,
5166 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5167 : base (parent, type, mod, allowed_mod, name, init, attrs, loc)
5171 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5173 if (a.Type == TypeManager.field_offset_attribute_type)
5175 has_field_offset = true;
5177 if (!Parent.HasExplicitLayout) {
5178 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5182 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5183 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5187 base.ApplyAttributeBuilder (a, cb);
5191 public override bool Define()
5193 EmitContext ec = Parent.EmitContext;
5195 throw new InternalErrorException ("FieldMember.Define called too early");
5197 bool old_unsafe = ec.InUnsafe;
5198 ec.InUnsafe = InUnsafe;
5199 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
5203 MemberType = texpr.ResolveType (ec);
5204 ec.InUnsafe = old_unsafe;
5209 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5210 Report.Error (52, Location,
5211 "Inconsistent accessibility: field type `" +
5212 TypeManager.CSharpName (MemberType) + "' is less " +
5213 "accessible than field `" + Name + "'");
5217 if (!IsTypePermitted ())
5220 if (MemberType.IsPointer && !UnsafeOK (Parent))
5226 public override void Emit ()
5228 if (Parent.HasExplicitLayout && !has_field_offset && (ModFlags & Modifiers.STATIC) == 0) {
5229 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5237 // The Field class is used to represents class/struct fields during parsing.
5239 public class Field : FieldMember {
5241 // Modifiers allowed in a class declaration
5243 const int AllowedModifiers =
5246 Modifiers.PROTECTED |
5247 Modifiers.INTERNAL |
5250 Modifiers.VOLATILE |
5254 public Field (TypeContainer parent, Expression type, int mod, string name,
5255 Object expr_or_array_init, Attributes attrs, Location loc)
5256 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5257 expr_or_array_init, attrs, loc)
5261 public override bool Define ()
5263 if (!base.Define ())
5266 if (RootContext.WarningLevel > 1){
5267 Type ptype = Parent.TypeBuilder.BaseType;
5269 // ptype is only null for System.Object while compiling corlib.
5271 TypeContainer.FindMembers (
5272 ptype, MemberTypes.Method,
5273 BindingFlags.Public |
5274 BindingFlags.Static | BindingFlags.Instance,
5275 System.Type.FilterName, Name);
5279 if ((ModFlags & Modifiers.VOLATILE) != 0){
5280 if (!MemberType.IsClass){
5281 Type vt = MemberType;
5283 if (TypeManager.IsEnumType (vt))
5284 vt = TypeManager.EnumToUnderlying (MemberType);
5286 if (!((vt == TypeManager.bool_type) ||
5287 (vt == TypeManager.sbyte_type) ||
5288 (vt == TypeManager.byte_type) ||
5289 (vt == TypeManager.short_type) ||
5290 (vt == TypeManager.ushort_type) ||
5291 (vt == TypeManager.int32_type) ||
5292 (vt == TypeManager.uint32_type) ||
5293 (vt == TypeManager.char_type) ||
5294 (vt == TypeManager.float_type) ||
5295 (!vt.IsValueType))){
5297 677, Location, Parent.MakeName (Name) +
5298 " A volatile field can not be of type `" +
5299 TypeManager.CSharpName (vt) + "'");
5304 if ((ModFlags & Modifiers.READONLY) != 0){
5307 "A field can not be both volatile and readonly");
5312 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5314 if (Parent.Kind == Kind.Struct &&
5315 ((fa & FieldAttributes.Static) == 0) &&
5316 MemberType == Parent.TypeBuilder &&
5317 !TypeManager.IsBuiltinType (MemberType)){
5318 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5319 "' causes a cycle in the structure layout");
5324 FieldBuilder = Parent.TypeBuilder.DefineField (
5325 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5327 TypeManager.RegisterFieldBase (FieldBuilder, this);
5329 catch (ArgumentException) {
5330 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5337 public override void Emit ()
5339 if (OptAttributes != null) {
5340 EmitContext ec = new EmitContext (
5341 Parent, Location, null, FieldBuilder.FieldType,
5343 OptAttributes.Emit (ec, this);
5351 // `set' and `get' accessors are represented with an Accessor.
5353 public class Accessor {
5355 // Null if the accessor is empty, or a Block if not
5357 public const int AllowedModifiers =
5359 Modifiers.PROTECTED |
5360 Modifiers.INTERNAL |
5363 public ToplevelBlock Block;
5364 public Attributes Attributes;
5365 public Location Location;
5366 public int ModFlags;
5368 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5373 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5378 // Ooouh Martin, templates are missing here.
5379 // When it will be possible move here a lot of child code and template method type.
5380 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5381 protected MethodData method_data;
5382 protected ToplevelBlock block;
5383 protected ListDictionary declarative_security;
5385 // The accessor are created event if they are not wanted.
5386 // But we need them because their names are reserved.
5387 // Field says whether accessor will be emited or not
5388 public readonly bool IsDummy;
5390 protected readonly string prefix;
5392 ReturnParameter return_attributes;
5394 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5395 : base (null, SetupName (prefix, member), null, member.Location)
5397 this.prefix = prefix;
5401 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5403 : base (null, SetupName (prefix, member),
5404 accessor.Attributes, accessor.Location)
5406 this.prefix = prefix;
5407 this.block = accessor.Block;
5410 static MemberName SetupName (string prefix, MemberBase member)
5412 MemberName name = member.MemberName.Clone ();
5413 name.Name = prefix + member.ShortName;
5417 public void UpdateName (MemberBase member)
5419 MemberName.Name = prefix + member.ShortName;
5422 #region IMethodData Members
5424 public ToplevelBlock Block {
5434 public CallingConventions CallingConventions {
5436 return CallingConventions.Standard;
5440 public bool IsExcluded (EmitContext ec)
5445 public MemberName MethodName {
5451 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5452 public abstract Type[] ParameterTypes { get; }
5453 public abstract Type ReturnType { get; }
5454 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5458 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5460 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5461 a.Type == TypeManager.conditional_attribute_type) {
5462 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 ());
5466 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5467 if (declarative_security == null)
5468 declarative_security = new ListDictionary ();
5469 a.ExtractSecurityPermissionSet (declarative_security);
5473 if (a.Target == AttributeTargets.Method) {
5474 method_data.MethodBuilder.SetCustomAttribute (cb);
5478 if (a.Target == AttributeTargets.ReturnValue) {
5479 if (return_attributes == null)
5480 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5482 return_attributes.ApplyAttributeBuilder (a, cb);
5486 ApplyToExtraTarget (a, cb);
5489 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5491 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5494 public override bool Define()
5499 public virtual void Emit (TypeContainer container)
5501 method_data.Emit (container, this);
5503 if (declarative_security != null) {
5504 foreach (DictionaryEntry de in declarative_security) {
5505 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5512 public override bool IsClsCompliaceRequired(DeclSpace ds)
5517 public bool IsDuplicateImplementation (MethodCore method)
5519 if (Name != method.Name)
5522 Type[] param_types = method.ParameterTypes;
5524 if (param_types.Length != ParameterTypes.Length)
5527 for (int i = 0; i < param_types.Length; i++)
5528 if (param_types [i] != ParameterTypes [i])
5531 Report.SymbolRelatedToPreviousError (method);
5532 Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
5536 public new Location Location {
5538 return base.Location;
5542 protected override void VerifyObsoleteAttribute()
5549 // Properties and Indexers both generate PropertyBuilders, we use this to share
5550 // their common bits.
5552 abstract public class PropertyBase : MethodCore {
5554 public class GetMethod: PropertyMethod
5556 static string[] attribute_targets = new string [] { "method", "return" };
5558 public GetMethod (MethodCore method):
5559 base (method, "get_")
5563 public GetMethod (MethodCore method, Accessor accessor):
5564 base (method, accessor, "get_")
5568 public override MethodBuilder Define(TypeContainer container)
5570 base.Define (container);
5572 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5574 if (!method_data.Define (container))
5577 return method_data.MethodBuilder;
5580 public override string GetSignatureForError (TypeContainer tc)
5582 return String.Concat (base.GetSignatureForError (tc), ".get");
5585 public override Type ReturnType {
5587 return method.MemberType;
5591 public override string[] ValidAttributeTargets {
5593 return attribute_targets;
5598 public class SetMethod: PropertyMethod {
5600 static string[] attribute_targets = new string [] { "method", "param", "return" };
5601 ImplicitParameter param_attr;
5603 public SetMethod (MethodCore method):
5604 base (method, "set_")
5608 public SetMethod (MethodCore method, Accessor accessor):
5609 base (method, accessor, "set_")
5613 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5615 if (a.Target == AttributeTargets.Parameter) {
5616 if (param_attr == null)
5617 param_attr = new ImplicitParameter (method_data.MethodBuilder);
5619 param_attr.ApplyAttributeBuilder (a, cb);
5623 base.ApplyAttributeBuilder (a, cb);
5626 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5628 Parameter [] parms = new Parameter [1];
5629 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null);
5630 Parameters parameters = new Parameters (parms, null, method.Location);
5631 Type [] types = parameters.GetParameterInfo (ec);
5632 return new InternalParameters (types, parameters);
5635 public override MethodBuilder Define(TypeContainer container)
5637 if (container.EmitContext == null)
5638 throw new InternalErrorException ("SetMethod.Define called too early");
5640 base.Define (container);
5642 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
5644 if (!method_data.Define (container))
5647 return method_data.MethodBuilder;
5650 public override string GetSignatureForError (TypeContainer tc)
5652 return String.Concat (base.GetSignatureForError (tc), ".set");
5655 public override Type[] ParameterTypes {
5657 return new Type[] { method.MemberType };
5661 public override Type ReturnType {
5663 return TypeManager.void_type;
5667 public override string[] ValidAttributeTargets {
5669 return attribute_targets;
5674 static string[] attribute_targets = new string [] { "property" };
5676 public abstract class PropertyMethod: AbstractPropertyEventMethod
5678 protected readonly MethodCore method;
5679 protected MethodAttributes flags;
5681 public PropertyMethod (MethodCore method, string prefix)
5682 : base (method, prefix)
5684 this.method = method;
5687 public PropertyMethod (MethodCore method, Accessor accessor,
5689 : base (method, accessor, prefix)
5691 this.method = method;
5692 this.ModFlags = accessor.ModFlags;
5694 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
5695 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
5696 Environment.Exit (1);
5700 public override AttributeTargets AttributeTargets {
5702 return AttributeTargets.Method;
5706 public override bool IsClsCompliaceRequired(DeclSpace ds)
5708 return method.IsClsCompliaceRequired (ds);
5711 public InternalParameters ParameterInfo
5714 return method_data.ParameterInfo;
5718 public virtual MethodBuilder Define (TypeContainer container)
5721 // Check for custom access modifier
5723 if (ModFlags == 0) {
5724 ModFlags = method.ModFlags;
5725 flags = method.flags;
5727 CheckModifiers (container, ModFlags);
5728 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
5729 flags = Modifiers.MethodAttr (ModFlags);
5730 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
5737 public override Type[] ParameterTypes {
5739 return TypeManager.NoTypes;
5743 public override EmitContext CreateEmitContext (TypeContainer tc,
5746 return new EmitContext (
5747 tc, method.Parent, method.Location, ig, ReturnType,
5748 method.ModFlags, false);
5751 public override ObsoleteAttribute GetObsoleteAttribute ()
5753 return method.GetObsoleteAttribute (method.Parent);
5756 public override string GetSignatureForError (TypeContainer tc)
5758 return String.Concat (tc.Name, '.', method.Name);
5761 void CheckModifiers (TypeContainer container, int modflags)
5764 int mflags = method.ModFlags & Modifiers.Accessibility;
5766 if ((mflags & Modifiers.PUBLIC) != 0) {
5767 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
5769 else if ((mflags & Modifiers.PROTECTED) != 0) {
5770 if ((mflags & Modifiers.INTERNAL) != 0)
5771 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
5773 flags |= Modifiers.PRIVATE;
5775 else if ((mflags & Modifiers.INTERNAL) != 0)
5776 flags |= Modifiers.PRIVATE;
5778 if ((mflags == modflags) || (modflags & (~flags)) != 0)
5779 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
5780 GetSignatureForError (container));
5786 public PropertyMethod Get, Set;
5787 public PropertyBuilder PropertyBuilder;
5788 public MethodBuilder GetBuilder, SetBuilder;
5790 protected EmitContext ec;
5792 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
5793 int allowed_mod, bool is_iface, MemberName name,
5794 Parameters parameters, Attributes attrs,
5796 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
5797 attrs, parameters, loc)
5801 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5803 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5804 a.Error_InvalidSecurityParent ();
5808 PropertyBuilder.SetCustomAttribute (cb);
5811 public override AttributeTargets AttributeTargets {
5813 return AttributeTargets.Property;
5817 public override bool Define ()
5822 if (!IsTypePermitted ())
5828 protected override bool DoDefine ()
5830 if (!base.DoDefine ())
5834 // Accessors modifiers check
5836 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
5837 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
5838 GetSignatureForError ());
5842 if ((Get.IsDummy || Set.IsDummy)
5843 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
5844 Report.Error (276, Location,
5845 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
5846 GetSignatureForError ());
5850 if (MemberType.IsAbstract && MemberType.IsSealed) {
5851 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
5855 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
5859 public override string GetSignatureForError()
5861 if (PropertyBuilder == null)
5862 return GetSignatureForError (Parent);
5864 return TypeManager.CSharpSignature (PropertyBuilder, false);
5868 protected override bool CheckForDuplications ()
5870 ArrayList ar = Parent.Indexers;
5872 int arLen = ar.Count;
5874 for (int i = 0; i < arLen; i++) {
5875 Indexer m = (Indexer) ar [i];
5876 if (IsDuplicateImplementation (m))
5881 ar = Parent.Properties;
5883 int arLen = ar.Count;
5885 for (int i = 0; i < arLen; i++) {
5886 Property m = (Property) ar [i];
5887 if (IsDuplicateImplementation (m))
5895 // TODO: rename to Resolve......
5896 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
5898 PropertyInfo parent_property = container.ParentCache.FindMemberToOverride (
5899 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
5901 if (parent_property == null)
5904 parent_ret_type = parent_property.PropertyType;
5905 MethodInfo get_accessor = parent_property.GetGetMethod (true);
5906 MethodInfo set_accessor = parent_property.GetSetMethod (true);
5907 MethodAttributes get_accessor_access, set_accessor_access;
5909 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
5910 if (Get != null && !Get.IsDummy && get_accessor == null) {
5911 Report.SymbolRelatedToPreviousError (parent_property);
5912 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
5915 if (Set != null && !Set.IsDummy && set_accessor == null) {
5916 Report.SymbolRelatedToPreviousError (parent_property);
5917 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
5922 // Check parent accessors access
5924 get_accessor_access = set_accessor_access = 0;
5925 if ((ModFlags & Modifiers.NEW) == 0) {
5926 if (get_accessor != null) {
5927 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
5928 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
5930 if (!Get.IsDummy && (get_accessor_access) !=
5931 (get_flags & MethodAttributes.MemberAccessMask))
5932 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
5933 GetSignatureForError (), TypeManager.GetFullNameSignature (parent_property));
5936 if (set_accessor != null) {
5937 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
5938 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
5940 if (!Set.IsDummy & (set_accessor_access) !=
5941 (set_flags & MethodAttributes.MemberAccessMask))
5942 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
5943 GetSignatureForError (container), TypeManager.GetFullNameSignature (parent_property));
5948 // Get the less restrictive access
5950 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
5953 public override void Emit ()
5956 // The PropertyBuilder can be null for explicit implementations, in that
5957 // case, we do not actually emit the ".property", so there is nowhere to
5958 // put the attribute
5960 if (PropertyBuilder != null && OptAttributes != null)
5961 OptAttributes.Emit (ec, this);
5973 /// Tests whether accessors are not in collision with some method (CS0111)
5975 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
5977 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
5980 protected override void UpdateMemberName ()
5982 base.UpdateMemberName ();
5984 Get.UpdateName (this);
5985 Set.UpdateName (this);
5989 public override string[] ValidAttributeTargets {
5991 return attribute_targets;
5996 public class Property : PropertyBase, IIteratorContainer {
5997 const int AllowedModifiers =
6000 Modifiers.PROTECTED |
6001 Modifiers.INTERNAL |
6005 Modifiers.OVERRIDE |
6006 Modifiers.ABSTRACT |
6009 Modifiers.METHOD_YIELDS |
6012 const int AllowedInterfaceModifiers =
6015 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6016 MemberName name, Attributes attrs, Accessor get_block,
6017 Accessor set_block, Location loc)
6018 : base (ds, type, mod,
6019 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6020 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6023 if (get_block == null)
6024 Get = new GetMethod (this);
6026 Get = new GetMethod (this, get_block);
6028 if (set_block == null)
6029 Set = new SetMethod (this);
6031 Set = new SetMethod (this, set_block);
6034 public override bool Define ()
6036 if (!base.Define ())
6042 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6046 GetBuilder = Get.Define (Parent);
6047 if (GetBuilder == null)
6051 // Setup iterator if we are one
6053 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6054 Iterator iterator = new Iterator (
6055 Parent, "get", MemberType,
6056 TypeManager.NoTypes, Get.ParameterInfo,
6057 ModFlags, Get.Block, Location);
6059 if (!iterator.DefineIterator ())
6061 Get.Block = iterator.Block;
6066 SetBuilder = Set.Define (Parent);
6067 if (SetBuilder == null)
6070 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6073 // FIXME - PropertyAttributes.HasDefault ?
6075 PropertyAttributes prop_attr = PropertyAttributes.None;
6077 prop_attr |= PropertyAttributes.RTSpecialName |
6078 PropertyAttributes.SpecialName;
6080 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6081 Name, prop_attr, MemberType, null);
6084 PropertyBuilder.SetGetMethod (GetBuilder);
6087 PropertyBuilder.SetSetMethod (SetBuilder);
6089 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6093 public void SetYields ()
6095 ModFlags |= Modifiers.METHOD_YIELDS;
6100 /// Gigantic workaround for lameness in SRE follows :
6101 /// This class derives from EventInfo and attempts to basically
6102 /// wrap around the EventBuilder so that FindMembers can quickly
6103 /// return this in it search for members
6105 public class MyEventBuilder : EventInfo {
6108 // We use this to "point" to our Builder which is
6109 // not really a MemberInfo
6111 EventBuilder MyBuilder;
6114 // We "catch" and wrap these methods
6116 MethodInfo raise, remove, add;
6118 EventAttributes attributes;
6119 Type declaring_type, reflected_type, event_type;
6124 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6126 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6128 // And now store the values in our own fields.
6130 declaring_type = type_builder;
6132 reflected_type = type_builder;
6134 attributes = event_attr;
6137 this.event_type = event_type;
6141 // Methods that you have to override. Note that you only need
6142 // to "implement" the variants that take the argument (those are
6143 // the "abstract" methods, the others (GetAddMethod()) are
6146 public override MethodInfo GetAddMethod (bool nonPublic)
6151 public override MethodInfo GetRemoveMethod (bool nonPublic)
6156 public override MethodInfo GetRaiseMethod (bool nonPublic)
6162 // These methods make "MyEventInfo" look like a Builder
6164 public void SetRaiseMethod (MethodBuilder raiseMethod)
6166 raise = raiseMethod;
6167 MyBuilder.SetRaiseMethod (raiseMethod);
6170 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6172 remove = removeMethod;
6173 MyBuilder.SetRemoveOnMethod (removeMethod);
6176 public void SetAddOnMethod (MethodBuilder addMethod)
6179 MyBuilder.SetAddOnMethod (addMethod);
6182 public void SetCustomAttribute (CustomAttributeBuilder cb)
6184 MyBuilder.SetCustomAttribute (cb);
6187 public override object [] GetCustomAttributes (bool inherit)
6189 // FIXME : There's nothing which can be seemingly done here because
6190 // we have no way of getting at the custom attribute objects of the
6195 public override object [] GetCustomAttributes (Type t, bool inherit)
6197 // FIXME : Same here !
6201 public override bool IsDefined (Type t, bool b)
6206 public override EventAttributes Attributes {
6212 public override string Name {
6218 public override Type DeclaringType {
6220 return declaring_type;
6224 public override Type ReflectedType {
6226 return reflected_type;
6230 public Type EventType {
6236 public void SetUsed ()
6238 if (my_event != null)
6239 my_event.status = (FieldBase.Status.ASSIGNED | FieldBase.Status.USED);
6244 /// For case when event is declared like property (with add and remove accessors).
6246 public class EventProperty: Event {
6248 static string[] attribute_targets = new string [] { "event", "property" };
6250 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6251 bool is_iface, MemberName name, Object init,
6252 Attributes attrs, Accessor add, Accessor remove,
6254 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6256 Add = new AddDelegateMethod (this, add);
6257 Remove = new RemoveDelegateMethod (this, remove);
6260 public override string[] ValidAttributeTargets {
6262 return attribute_targets;
6268 /// Event is declared like field.
6270 public class EventField: Event {
6272 static string[] attribute_targets = new string [] { "event", "field", "method" };
6274 public EventField (TypeContainer parent, Expression type, int mod_flags,
6275 bool is_iface, MemberName name, Object init,
6276 Attributes attrs, Location loc)
6277 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6279 Add = new AddDelegateMethod (this);
6280 Remove = new RemoveDelegateMethod (this);
6283 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6285 if (a.Target == AttributeTargets.Field) {
6286 FieldBuilder.SetCustomAttribute (cb);
6290 if (a.Target == AttributeTargets.Method) {
6291 AddBuilder.SetCustomAttribute (cb);
6292 RemoveBuilder.SetCustomAttribute (cb);
6296 base.ApplyAttributeBuilder (a, cb);
6299 public override string[] ValidAttributeTargets {
6301 return attribute_targets;
6306 public abstract class Event : FieldBase {
6308 protected sealed class AddDelegateMethod: DelegateMethod
6311 public AddDelegateMethod (Event method):
6312 base (method, "add_")
6316 public AddDelegateMethod (Event method, Accessor accessor):
6317 base (method, accessor, "add_")
6321 protected override MethodInfo DelegateMethodInfo {
6323 return TypeManager.delegate_combine_delegate_delegate;
6329 protected sealed class RemoveDelegateMethod: DelegateMethod
6331 public RemoveDelegateMethod (Event method):
6332 base (method, "remove_")
6336 public RemoveDelegateMethod (Event method, Accessor accessor):
6337 base (method, accessor, "remove_")
6341 protected override MethodInfo DelegateMethodInfo {
6343 return TypeManager.delegate_remove_delegate_delegate;
6349 public abstract class DelegateMethod: AbstractPropertyEventMethod
6351 protected readonly Event method;
6352 ImplicitParameter param_attr;
6354 static string[] attribute_targets = new string [] { "method", "param", "return" };
6356 public DelegateMethod (Event method, string prefix)
6357 : base (method, prefix)
6359 this.method = method;
6362 public DelegateMethod (Event method, Accessor accessor, string prefix)
6363 : base (method, accessor, prefix)
6365 this.method = method;
6368 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6370 if (a.Target == AttributeTargets.Parameter) {
6371 if (param_attr == null)
6372 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6374 param_attr.ApplyAttributeBuilder (a, cb);
6378 base.ApplyAttributeBuilder (a, cb);
6381 public override AttributeTargets AttributeTargets {
6383 return AttributeTargets.Method;
6387 public override bool IsClsCompliaceRequired(DeclSpace ds)
6389 return method.IsClsCompliaceRequired (ds);
6392 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6394 method_data = new MethodData (method, ip, method.ModFlags,
6395 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6397 if (!method_data.Define (container))
6400 MethodBuilder mb = method_data.MethodBuilder;
6401 mb.DefineParameter (1, ParameterAttributes.None, "value");
6406 public override void Emit (TypeContainer tc)
6408 if (block != null) {
6413 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6414 EmitContext ec = CreateEmitContext (tc, ig);
6415 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6417 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6418 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6419 ig.Emit (OpCodes.Ldsfld, field_info);
6420 ig.Emit (OpCodes.Ldarg_0);
6421 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6422 ig.Emit (OpCodes.Castclass, method.MemberType);
6423 ig.Emit (OpCodes.Stsfld, field_info);
6425 ig.Emit (OpCodes.Ldarg_0);
6426 ig.Emit (OpCodes.Ldarg_0);
6427 ig.Emit (OpCodes.Ldfld, field_info);
6428 ig.Emit (OpCodes.Ldarg_1);
6429 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6430 ig.Emit (OpCodes.Castclass, method.MemberType);
6431 ig.Emit (OpCodes.Stfld, field_info);
6433 ig.Emit (OpCodes.Ret);
6436 protected abstract MethodInfo DelegateMethodInfo { get; }
6438 public override Type[] ParameterTypes {
6440 return new Type[] { method.MemberType };
6444 public override Type ReturnType {
6446 return TypeManager.void_type;
6450 public override EmitContext CreateEmitContext (TypeContainer tc,
6453 return new EmitContext (
6454 tc, method.Parent, Location, ig, ReturnType,
6455 method.ModFlags, false);
6458 public override string GetSignatureForError (TypeContainer tc)
6460 return String.Concat (tc.Name, '.', method.Name);
6463 public override ObsoleteAttribute GetObsoleteAttribute ()
6465 return method.GetObsoleteAttribute (method.Parent);
6468 public override string[] ValidAttributeTargets {
6470 return attribute_targets;
6476 const int AllowedModifiers =
6479 Modifiers.PROTECTED |
6480 Modifiers.INTERNAL |
6485 Modifiers.OVERRIDE |
6489 const int AllowedInterfaceModifiers =
6492 public DelegateMethod Add, Remove;
6493 public MyEventBuilder EventBuilder;
6494 public MethodBuilder AddBuilder, RemoveBuilder;
6496 public Event (TypeContainer parent, Expression type, int mod_flags,
6497 bool is_iface, MemberName name, Object init, Attributes attrs,
6499 : base (parent, type, mod_flags,
6500 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6501 name, init, attrs, loc)
6503 IsInterface = is_iface;
6506 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6508 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6509 a.Error_InvalidSecurityParent ();
6513 EventBuilder.SetCustomAttribute (cb);
6516 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6518 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6521 public override AttributeTargets AttributeTargets {
6523 return AttributeTargets.Event;
6527 public override bool Define ()
6529 EventAttributes e_attr;
6530 e_attr = EventAttributes.None;
6535 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6536 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6537 "': abstract event can not have an initializer");
6541 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6542 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6543 "' : event must be of a delegate type");
6547 EmitContext ec = Parent.EmitContext;
6549 throw new InternalErrorException ("Event.Define called too early?");
6550 bool old_unsafe = ec.InUnsafe;
6551 ec.InUnsafe = InUnsafe;
6553 Parameter [] parms = new Parameter [1];
6554 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null);
6555 Parameters parameters = new Parameters (parms, null, Location);
6556 Type [] types = parameters.GetParameterInfo (ec);
6557 InternalParameters ip = new InternalParameters (types, parameters);
6559 ec.InUnsafe = old_unsafe;
6565 // Now define the accessors
6568 AddBuilder = Add.Define (Parent, ip);
6569 if (AddBuilder == null)
6572 RemoveBuilder = Remove.Define (Parent, ip);
6573 if (RemoveBuilder == null)
6576 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6578 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6579 FieldBuilder = Parent.TypeBuilder.DefineField (
6581 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6582 TypeManager.RegisterPrivateFieldOfEvent (
6583 (EventInfo) EventBuilder, FieldBuilder);
6584 TypeManager.RegisterFieldBase (FieldBuilder, this);
6587 EventBuilder.SetAddOnMethod (AddBuilder);
6588 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6590 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6594 protected override bool CheckBase ()
6596 if (!base.CheckBase ())
6599 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6600 if (!(conflict_symbol is EventInfo)) {
6601 Report.SymbolRelatedToPreviousError (conflict_symbol);
6602 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
6610 public override void Emit ()
6612 if (OptAttributes != null) {
6613 EmitContext ec = new EmitContext (
6614 Parent, Location, null, MemberType, ModFlags);
6615 OptAttributes.Emit (ec, this);
6620 Remove.Emit (Parent);
6626 public override string GetSignatureForError ()
6628 if (EventBuilder == null)
6629 return base.GetSignatureForError (Parent);
6631 return TypeManager.GetFullNameSignature (EventBuilder);
6636 public class Indexer : PropertyBase {
6638 class GetIndexerMethod: GetMethod
6640 public GetIndexerMethod (MethodCore method):
6645 public GetIndexerMethod (MethodCore method, Accessor accessor):
6646 base (method, accessor)
6650 public override Type[] ParameterTypes {
6652 return method.ParameterTypes;
6657 class SetIndexerMethod: SetMethod
6659 readonly Parameters parameters;
6661 public SetIndexerMethod (MethodCore method):
6666 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
6667 base (method, accessor)
6669 this.parameters = parameters;
6672 public override Type[] ParameterTypes {
6674 int top = method.ParameterTypes.Length;
6675 Type [] set_pars = new Type [top + 1];
6676 method.ParameterTypes.CopyTo (set_pars, 0);
6677 set_pars [top] = method.MemberType;
6682 protected override InternalParameters GetParameterInfo (EmitContext ec)
6684 Parameter [] fixed_parms = parameters.FixedParameters;
6686 if (fixed_parms == null){
6687 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
6688 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6689 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6691 // Here is the problem: the `value' parameter has
6692 // to come *after* the array parameter in the declaration
6694 // X (object [] x, Type value)
6697 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6698 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
6702 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
6704 fixed_parms.CopyTo (tmp, 0);
6705 tmp [fixed_parms.Length] = new Parameter (
6706 method.Type, "value", Parameter.Modifier.NONE, null);
6708 Parameters set_formal_params = new Parameters (tmp, null, method.Location);
6709 Type [] types = set_formal_params.GetParameterInfo (ec);
6711 return new InternalParameters (types, set_formal_params);
6716 const int AllowedModifiers =
6719 Modifiers.PROTECTED |
6720 Modifiers.INTERNAL |
6724 Modifiers.OVERRIDE |
6729 const int AllowedInterfaceModifiers =
6733 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
6734 bool is_iface, Parameters parameters, Attributes attrs,
6735 Accessor get_block, Accessor set_block, Location loc)
6736 : base (ds, type, mod,
6737 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6738 is_iface, name, parameters, attrs, loc)
6740 if (get_block == null)
6741 Get = new GetIndexerMethod (this);
6743 Get = new GetIndexerMethod (this, get_block);
6745 if (set_block == null)
6746 Set = new SetIndexerMethod (this);
6748 Set = new SetIndexerMethod (this, parameters, set_block);
6751 public override bool Define ()
6753 PropertyAttributes prop_attr =
6754 PropertyAttributes.RTSpecialName |
6755 PropertyAttributes.SpecialName;
6757 if (!base.Define ())
6760 if (OptAttributes != null) {
6761 Attribute indexer_attr = OptAttributes.GetIndexerNameAttribute (ec);
6762 if (indexer_attr != null) {
6763 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
6765 if (IsExplicitImpl) {
6766 Report.Error (415, indexer_attr.Location,
6767 "The 'IndexerName' attribute is valid only on an" +
6768 "indexer that is not an explicit interface member declaration");
6772 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6773 Report.Error (609, indexer_attr.Location,
6774 "Cannot set the 'IndexerName' attribute on an indexer marked override");
6778 if (!Tokenizer.IsValidIdentifier (ShortName)) {
6779 Report.Error (633, indexer_attr.Location,
6780 "The argument to the 'IndexerName' attribute must be a valid identifier");
6784 UpdateMemberName ();
6788 if (InterfaceType != null) {
6789 string parent_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
6790 if (parent_IndexerName != Name)
6791 ShortName = parent_IndexerName;
6792 UpdateMemberName ();
6795 if (!Parent.AddToMemberContainer (this, true) ||
6796 !Parent.AddToMemberContainer (Get, true) || !Parent.AddToMemberContainer (Set, true))
6802 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6804 GetBuilder = Get.Define (Parent);
6805 if (GetBuilder == null)
6810 SetBuilder = Set.Define (Parent);
6811 if (SetBuilder == null)
6816 // Now name the parameters
6818 Parameter [] p = Parameters.FixedParameters;
6820 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
6821 Report.Error (631, Location, "ref and out are not valid in this context");
6827 for (i = 0; i < p.Length; ++i) {
6829 GetBuilder.DefineParameter (
6830 i + 1, p [i].Attributes, p [i].Name);
6833 SetBuilder.DefineParameter (
6834 i + 1, p [i].Attributes, p [i].Name);
6838 SetBuilder.DefineParameter (
6839 i + 1, ParameterAttributes.None, "value");
6841 if (i != ParameterTypes.Length) {
6842 Parameter array_param = Parameters.ArrayParameter;
6844 SetBuilder.DefineParameter (
6845 i + 1, array_param.Attributes, array_param.Name);
6849 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6850 Name, prop_attr, MemberType, ParameterTypes);
6853 PropertyBuilder.SetGetMethod (GetBuilder);
6856 PropertyBuilder.SetSetMethod (SetBuilder);
6858 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
6863 public override string GetSignatureForError ()
6865 if (PropertyBuilder == null)
6866 return GetSignatureForError (Parent);
6868 return TypeManager.CSharpSignature (PropertyBuilder, true);
6871 public override string GetSignatureForError(TypeContainer tc)
6873 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
6877 public class Operator : MethodCore, IIteratorContainer {
6879 const int AllowedModifiers =
6885 public enum OpType : byte {
6895 // Unary and Binary operators
6918 // Implicit and Explicit
6923 public readonly OpType OperatorType;
6924 public MethodBuilder OperatorMethodBuilder;
6926 public Method OperatorMethod;
6928 static string[] attribute_targets = new string [] { "method", "return" };
6930 public Operator (TypeContainer parent, OpType type, Expression ret_type,
6931 int mod_flags, Parameters parameters,
6932 ToplevelBlock block, Attributes attrs, Location loc)
6933 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
6934 new MemberName ("op_" + type), attrs, parameters, loc)
6936 OperatorType = type;
6940 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6942 OperatorMethod.ApplyAttributeBuilder (a, cb);
6945 public override AttributeTargets AttributeTargets {
6947 return AttributeTargets.Method;
6951 protected override bool CheckForDuplications()
6953 ArrayList ar = Parent.Operators;
6955 int arLen = ar.Count;
6957 for (int i = 0; i < arLen; i++) {
6958 Operator o = (Operator) ar [i];
6959 if (IsDuplicateImplementation (o))
6964 ar = Parent.Methods;
6966 int arLen = ar.Count;
6968 for (int i = 0; i < arLen; i++) {
6969 Method m = (Method) ar [i];
6970 if (IsDuplicateImplementation (m))
6978 public override bool Define ()
6981 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
6982 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
6983 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
6990 OperatorMethod = new Method (
6991 Parent, Type, ModFlags, false, MemberName,
6992 Parameters, OptAttributes, Location);
6994 OperatorMethod.Block = Block;
6995 OperatorMethod.IsOperator = true;
6996 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
6997 OperatorMethod.Define ();
6999 if (OperatorMethod.MethodBuilder == null)
7002 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7004 parameter_types = OperatorMethod.ParameterTypes;
7005 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7006 Type return_type = OperatorMethod.ReturnType;
7007 Type first_arg_type = parameter_types [0];
7012 // Rules for conversion operators
7014 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7015 if (first_arg_type == return_type && first_arg_type == declaring_type){
7018 "User-defined conversion cannot take an object of the " +
7019 "enclosing type and convert to an object of the enclosing" +
7024 if (first_arg_type != declaring_type && return_type != declaring_type){
7027 "User-defined conversion must convert to or from the " +
7032 if (first_arg_type == TypeManager.object_type ||
7033 return_type == TypeManager.object_type){
7036 "User-defined conversion cannot convert to or from " +
7041 if (first_arg_type.IsInterface || return_type.IsInterface){
7044 "User-defined conversion cannot convert to or from an " +
7049 if (first_arg_type.IsSubclassOf (return_type)
7050 || return_type.IsSubclassOf (first_arg_type)){
7051 if (declaring_type.IsSubclassOf (return_type)) {
7052 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7055 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7058 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7059 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7060 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");
7063 } else if (Parameters.FixedParameters.Length == 1) {
7064 // Checks for Unary operators
7066 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7067 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7068 Report.Error (448, Location,
7069 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7072 if (first_arg_type != declaring_type) {
7074 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7079 if (first_arg_type != declaring_type){
7082 "The parameter of a unary operator must be the " +
7087 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7088 if (return_type != TypeManager.bool_type){
7091 "The return type of operator True or False " +
7098 // Checks for Binary operators
7100 if (first_arg_type != declaring_type &&
7101 parameter_types [1] != declaring_type){
7104 "One of the parameters of a binary operator must " +
7105 "be the containing type");
7113 public override void Emit ()
7116 // abstract or extern methods have no bodies
7118 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7121 OperatorMethod.Emit ();
7125 // Operator cannot be override
7126 protected override MethodInfo FindOutParentMethod (TypeContainer container, ref Type parent_ret_type)
7131 public static string GetName (OpType ot)
7134 case OpType.LogicalNot:
7136 case OpType.OnesComplement:
7138 case OpType.Increment:
7140 case OpType.Decrement:
7146 case OpType.Addition:
7148 case OpType.Subtraction:
7150 case OpType.UnaryPlus:
7152 case OpType.UnaryNegation:
7154 case OpType.Multiply:
7156 case OpType.Division:
7158 case OpType.Modulus:
7160 case OpType.BitwiseAnd:
7162 case OpType.BitwiseOr:
7164 case OpType.ExclusiveOr:
7166 case OpType.LeftShift:
7168 case OpType.RightShift:
7170 case OpType.Equality:
7172 case OpType.Inequality:
7174 case OpType.GreaterThan:
7176 case OpType.LessThan:
7178 case OpType.GreaterThanOrEqual:
7180 case OpType.LessThanOrEqual:
7182 case OpType.Implicit:
7184 case OpType.Explicit:
7190 public override string GetSignatureForError (TypeContainer tc)
7192 StringBuilder sb = new StringBuilder ();
7193 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7194 Parameters.FixedParameters [0].GetSignatureForError ());
7196 if (Parameters.FixedParameters.Length > 1) {
7198 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7201 return sb.ToString ();
7204 public override string GetSignatureForError ()
7209 public override string ToString ()
7211 if (OperatorMethod == null)
7214 Type return_type = OperatorMethod.ReturnType;
7215 Type [] param_types = OperatorMethod.ParameterTypes;
7217 if (Parameters.FixedParameters.Length == 1)
7218 return String.Format (
7219 "{0} operator {1}({2})",
7220 TypeManager.CSharpName (return_type),
7221 GetName (OperatorType),
7224 return String.Format (
7225 "{0} operator {1}({2}, {3})",
7226 TypeManager.CSharpName (return_type),
7227 GetName (OperatorType),
7228 param_types [0], param_types [1]);
7231 public override string[] ValidAttributeTargets {
7233 return attribute_targets;
7237 public void SetYields ()
7239 ModFlags |= Modifiers.METHOD_YIELDS;
7244 // This is used to compare method signatures
7246 struct MethodSignature {
7248 public Type RetType;
7249 public Type [] Parameters;
7252 /// This delegate is used to extract methods which have the
7253 /// same signature as the argument
7255 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7257 public MethodSignature (string name, Type ret_type, Type [] parameters)
7262 if (parameters == null)
7263 Parameters = TypeManager.NoTypes;
7265 Parameters = parameters;
7268 public override string ToString ()
7271 if (Parameters.Length != 0){
7272 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7273 for (int i = 0; i < Parameters.Length; i++){
7274 sb.Append (Parameters [i]);
7275 if (i+1 < Parameters.Length)
7278 pars = sb.ToString ();
7281 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7284 public override int GetHashCode ()
7286 return Name.GetHashCode ();
7289 public override bool Equals (Object o)
7291 MethodSignature other = (MethodSignature) o;
7293 if (other.Name != Name)
7296 if (other.RetType != RetType)
7299 if (Parameters == null){
7300 if (other.Parameters == null)
7305 if (other.Parameters == null)
7308 int c = Parameters.Length;
7309 if (other.Parameters.Length != c)
7312 for (int i = 0; i < c; i++)
7313 if (other.Parameters [i] != Parameters [i])
7319 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7321 MethodSignature sig = (MethodSignature) filter_criteria;
7323 if (m.Name != sig.Name)
7327 MethodInfo mi = m as MethodInfo;
7328 PropertyInfo pi = m as PropertyInfo;
7331 ReturnType = mi.ReturnType;
7332 else if (pi != null)
7333 ReturnType = pi.PropertyType;
7338 // we use sig.RetType == null to mean `do not check the
7339 // method return value.
7341 if (sig.RetType != null)
7342 if (ReturnType != sig.RetType)
7347 args = TypeManager.GetArgumentTypes (mi);
7349 args = TypeManager.GetArgumentTypes (pi);
7350 Type [] sigp = sig.Parameters;
7352 if (args.Length != sigp.Length)
7355 for (int i = args.Length; i > 0; ){
7357 if (args [i] != sigp [i])