2 // class.cs: Class and Struct handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 // 2002-10-11 Miguel de Icaza <miguel@ximian.com>
16 // * class.cs: Following the comment from 2002-09-26 to AddMethod, I
17 // have fixed a remaining problem: not every AddXXXX was adding a
18 // fully qualified name.
20 // Now everyone registers a fully qualified name in the DeclSpace as
21 // being defined instead of the partial name.
23 // Downsides: we are slower than we need to be due to the excess
24 // copies and the names being registered this way.
26 // The reason for this is that we currently depend (on the corlib
27 // bootstrap for instance) that types are fully qualified, because
28 // we dump all the types in the namespace, and we should really have
29 // types inserted into the proper namespace, so we can only store the
30 // basenames in the defined_names array.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Reflection;
38 using System.Reflection.Emit;
39 using System.Runtime.CompilerServices;
40 using System.Runtime.InteropServices;
41 using System.Security;
42 using System.Security.Permissions;
45 #if BOOTSTRAP_WITH_OLDLIB
46 using XmlElement = System.Object;
51 using Mono.CompilerServices.SymbolWriter;
53 namespace Mono.CSharp {
63 /// This is the base class for structs and classes.
65 public abstract class TypeContainer : DeclSpace, IMemberContainer {
67 public class MemberCoreArrayList: ArrayList
70 /// Defines the MemberCore objects that are in this array
72 public virtual void DefineContainerMembers ()
74 foreach (MemberCore mc in this) {
79 public virtual void Emit ()
81 foreach (MemberCore mc in this)
86 public class MethodArrayList: MemberCoreArrayList
94 CachedMethods cached_method;
95 TypeContainer container;
97 public MethodArrayList (TypeContainer container)
99 this.container = container;
103 /// Method container contains Equals method
105 public bool HasEquals {
107 cached_method |= CachedMethods.Equals;
111 return (cached_method & CachedMethods.Equals) != 0;
116 /// Method container contains GetHashCode method
118 public bool HasGetHashCode {
120 cached_method |= CachedMethods.GetHashCode;
124 return (cached_method & CachedMethods.GetHashCode) != 0;
128 public override void DefineContainerMembers ()
130 base.DefineContainerMembers ();
132 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
133 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
139 public sealed class IndexerArrayList: MemberCoreArrayList
142 /// The indexer name for this container
144 public string IndexerName = DefaultIndexerName;
146 bool seen_normal_indexers = false;
148 TypeContainer container;
150 public IndexerArrayList (TypeContainer container)
152 this.container = container;
156 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
157 /// class is consistent. Either it is `Item' or it is the name defined by all the
158 /// indexers with the `IndexerName' attribute.
160 /// Turns out that the IndexerNameAttribute is applied to each indexer,
161 /// but it is never emitted, instead a DefaultMember attribute is attached
164 public override void DefineContainerMembers()
166 base.DefineContainerMembers ();
168 string class_indexer_name = null;
171 // If there's both an explicit and an implicit interface implementation, the
172 // explicit one actually implements the interface while the other one is just
173 // a normal indexer. See bug #37714.
176 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
177 foreach (Indexer i in this) {
178 if (i.InterfaceType != null) {
179 if (seen_normal_indexers)
180 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
184 seen_normal_indexers = true;
186 if (class_indexer_name == null) {
187 class_indexer_name = i.ShortName;
191 if (i.ShortName != class_indexer_name)
192 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");
195 if (class_indexer_name != null)
196 IndexerName = class_indexer_name;
199 public override void Emit ()
203 if (!seen_normal_indexers)
206 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
207 container.TypeBuilder.SetCustomAttribute (cb);
211 public class OperatorArrayList: MemberCoreArrayList
213 TypeContainer container;
215 public OperatorArrayList (TypeContainer container)
217 this.container = container;
221 // Operator pair checking
226 public Type ret_type;
227 public Type type1, type2;
229 public Operator.OpType ot;
231 public OperatorEntry (int f, Operator o)
235 ret_type = o.OperatorMethod.ReturnType;
236 Type [] pt = o.OperatorMethod.ParameterTypes;
243 public override int GetHashCode ()
245 return ret_type.GetHashCode ();
248 public override bool Equals (object o)
250 OperatorEntry other = (OperatorEntry) o;
252 if (other.ret_type != ret_type)
254 if (other.type1 != type1)
256 if (other.type2 != type2)
263 // Checks that some operators come in pairs:
269 // They are matched based on the return type and the argument types
271 void CheckPairedOperators ()
273 Hashtable pairs = new Hashtable (null, null);
274 Operator true_op = null;
275 Operator false_op = null;
276 bool has_equality_or_inequality = false;
278 // Register all the operators we care about.
279 foreach (Operator op in this){
282 // Skip erroneous code.
283 if (op.OperatorMethod == null)
286 switch (op.OperatorType){
287 case Operator.OpType.Equality:
289 has_equality_or_inequality = true;
291 case Operator.OpType.Inequality:
293 has_equality_or_inequality = true;
296 case Operator.OpType.True:
299 case Operator.OpType.False:
303 case Operator.OpType.GreaterThan:
305 case Operator.OpType.LessThan:
308 case Operator.OpType.GreaterThanOrEqual:
310 case Operator.OpType.LessThanOrEqual:
316 OperatorEntry oe = new OperatorEntry (reg, op);
318 object o = pairs [oe];
322 oe = (OperatorEntry) o;
327 if (true_op != null){
328 if (false_op == null)
329 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
330 } else if (false_op != null)
331 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
334 // Look for the mistakes.
336 foreach (DictionaryEntry de in pairs){
337 OperatorEntry oe = (OperatorEntry) de.Key;
344 case Operator.OpType.Equality:
347 case Operator.OpType.Inequality:
350 case Operator.OpType.GreaterThan:
353 case Operator.OpType.LessThan:
356 case Operator.OpType.GreaterThanOrEqual:
359 case Operator.OpType.LessThanOrEqual:
363 Report.Error (216, oe.op.Location,
364 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
367 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
368 if (container.Methods == null || !container.Methods.HasEquals)
369 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
371 if (container.Methods == null || !container.Methods.HasGetHashCode)
372 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
376 public override void DefineContainerMembers ()
378 base.DefineContainerMembers ();
379 CheckPairedOperators ();
384 // Whether this is a struct, class or interface
385 public readonly Kind Kind;
387 // Holds a list of classes and structures
390 // Holds the list of properties
391 MemberCoreArrayList properties;
393 // Holds the list of enumerations
394 MemberCoreArrayList enums;
396 // Holds the list of delegates
397 MemberCoreArrayList delegates;
399 // Holds the list of constructors
400 protected MemberCoreArrayList instance_constructors;
402 // Holds the list of fields
403 MemberCoreArrayList fields;
405 // Holds a list of fields that have initializers
406 protected ArrayList initialized_fields;
408 // Holds a list of static fields that have initializers
409 protected ArrayList initialized_static_fields;
411 // Holds the list of constants
412 MemberCoreArrayList constants;
415 MemberCoreArrayList interfaces;
417 // Holds the methods.
418 MethodArrayList methods;
421 protected MemberCoreArrayList events;
423 // Holds the indexers
424 IndexerArrayList indexers;
426 // Holds the operators
427 MemberCoreArrayList operators;
429 // Holds the iterators
432 // Holds the parts of a partial class;
436 // Pointers to the default constructor and the default static constructor
438 protected Constructor default_constructor;
439 protected Constructor default_static_constructor;
442 // Whether we have at least one non-static field
444 bool have_nonstatic_fields = false;
447 // This one is computed after we can distinguish interfaces
448 // from classes from the arraylist `type_bases'
450 string base_class_name;
452 TypeExpr[] iface_exprs;
454 ArrayList type_bases;
456 bool members_defined;
457 bool members_defined_ok;
459 // The interfaces we implement.
460 protected Type[] ifaces;
461 protected Type ptype;
463 // The base member cache and our member cache
464 MemberCache base_cache;
465 MemberCache member_cache;
467 public const string DefaultIndexerName = "Item";
469 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
470 Attributes attrs, Kind kind, Location l)
471 : base (ns, parent, name, attrs, l)
473 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
474 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
478 types = new ArrayList ();
480 base_class_name = null;
483 public bool AddToMemberContainer (MemberCore symbol)
485 return AddToContainer (symbol, symbol.Name);
488 bool AddToTypeContainer (DeclSpace ds)
490 // Parent == null ==> this == RootContext.Tree.Types
491 return AddToContainer (ds, (Parent == null) ? ds.Name : ds.Basename);
494 public void AddConstant (Const constant)
496 if (!AddToMemberContainer (constant))
499 if (constants == null)
500 constants = new MemberCoreArrayList ();
502 constants.Add (constant);
505 public void AddEnum (Mono.CSharp.Enum e)
507 if (!AddToTypeContainer (e))
511 enums = new MemberCoreArrayList ();
516 public void AddClassOrStruct (TypeContainer c)
518 if (!AddToTypeContainer (c))
524 public void AddDelegate (Delegate d)
526 if (!AddToTypeContainer (d))
529 if (delegates == null)
530 delegates = new MemberCoreArrayList ();
535 public void AddMethod (Method method)
537 if (!AddToMemberContainer (method))
541 methods = new MethodArrayList (this);
543 if (method.MemberName.Left != null)
544 methods.Insert (0, method);
546 methods.Add (method);
549 public void AddConstructor (Constructor c)
551 if (c.Name != Basename) {
552 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
555 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
558 if (default_static_constructor != null) {
559 Report.SymbolRelatedToPreviousError (default_static_constructor);
560 Report.Error (111, c.Location, Error111, Name, c.Name);
564 default_static_constructor = c;
567 if (default_constructor != null) {
568 Report.SymbolRelatedToPreviousError (default_constructor);
569 Report.Error (111, c.Location, Error111, c.Location, Name, c.Name);
572 default_constructor = c;
575 if (instance_constructors == null)
576 instance_constructors = new MemberCoreArrayList ();
578 instance_constructors.Add (c);
582 internal static string Error111 {
584 return "Type '{0}' already defines a member called '{1}' with the same parameter types";
588 public void AddInterface (TypeContainer iface)
590 if (!AddToTypeContainer (iface))
593 if (interfaces == null) {
594 interfaces = new MemberCoreArrayList ();
597 interfaces.Add (iface);
600 public void AddField (FieldMember field)
602 if (!AddToMemberContainer (field))
606 fields = new MemberCoreArrayList ();
610 if (field.HasInitializer)
611 RegisterFieldForInitialization (field);
613 if ((field.ModFlags & Modifiers.STATIC) == 0)
614 have_nonstatic_fields = true;
617 public void AddProperty (Property prop)
619 if (!AddToMemberContainer (prop) ||
620 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
623 if (properties == null)
624 properties = new MemberCoreArrayList ();
626 if (prop.MemberName.Left != null)
627 properties.Insert (0, prop);
629 properties.Add (prop);
632 public void AddEvent (Event e)
634 if (!AddToMemberContainer (e))
637 if (e is EventProperty) {
638 if (!AddToMemberContainer (e.Add))
641 if (!AddToMemberContainer (e.Remove))
646 events = new MemberCoreArrayList ();
653 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
655 public void AddIndexer (Indexer i)
657 if (indexers == null)
658 indexers = new IndexerArrayList (this);
660 if (i.IsExplicitImpl)
661 indexers.Insert (0, i);
666 public void AddOperator (Operator op)
668 if (!AddToMemberContainer (op))
671 if (operators == null)
672 operators = new OperatorArrayList (this);
677 public void AddIterator (Iterator i)
679 if (iterators == null)
680 iterators = new ArrayList ();
685 public void AddType (TypeContainer tc)
690 public void AddPart (ClassPart part)
693 parts = new ArrayList ();
698 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
700 if (a.Type == TypeManager.default_member_type) {
701 if (Indexers != null) {
702 Report.Error (646, a.Location,
703 "Cannot specify the DefaultMember attribute on" +
704 " a type containing an indexer");
709 base.ApplyAttributeBuilder (a, cb);
712 public override AttributeTargets AttributeTargets {
716 return AttributeTargets.Class;
718 return AttributeTargets.Struct;
720 return AttributeTargets.Interface;
722 throw new NotSupportedException ();
727 public ArrayList Types {
733 public MethodArrayList Methods {
739 public ArrayList Constants {
745 public ArrayList Interfaces {
751 public ArrayList Iterators {
759 return base_class_name;
763 public ArrayList Bases {
773 public ArrayList Fields {
779 public ArrayList InstanceConstructors {
781 return instance_constructors;
785 public ArrayList Properties {
791 public ArrayList Events {
797 public ArrayList Enums {
803 public ArrayList Indexers {
809 public ArrayList Operators {
815 public ArrayList Delegates {
821 public ArrayList Parts {
827 protected override TypeAttributes TypeAttr {
829 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
833 public string IndexerName {
835 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
839 public virtual void RegisterFieldForInitialization (FieldMember field)
841 if ((field.ModFlags & Modifiers.STATIC) != 0){
842 if (initialized_static_fields == null)
843 initialized_static_fields = new ArrayList ();
845 initialized_static_fields.Add (field);
847 if (initialized_fields == null)
848 initialized_fields = new ArrayList ();
850 initialized_fields.Add (field);
855 // Emits the instance field initializers
857 public virtual bool EmitFieldInitializers (EmitContext ec)
860 Expression instance_expr;
863 fields = initialized_static_fields;
864 instance_expr = null;
866 fields = initialized_fields;
867 instance_expr = new This (Location.Null).Resolve (ec);
873 foreach (FieldMember f in fields){
874 Expression e = f.GetInitializerExpression (ec);
878 Location l = f.Location;
879 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
880 fe.InstanceExpression = instance_expr;
881 ExpressionStatement a = new Assign (fe, e, l);
883 a = a.ResolveStatement (ec);
887 Constant c = e as Constant;
889 if (c.IsDefaultValue)
893 a.EmitStatement (ec);
900 // Defines the default constructors
902 protected void DefineDefaultConstructor (bool is_static)
906 // The default constructor is public
907 // If the class is abstract, the default constructor is protected
908 // The default static constructor is private
910 int mods = Modifiers.PUBLIC;
912 mods = Modifiers.STATIC | Modifiers.PRIVATE;
913 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
914 mods = Modifiers.PROTECTED;
916 TypeContainer constructor_parent = this;
918 constructor_parent = (TypeContainer) Parts [0];
920 c = new Constructor (constructor_parent, Basename, mods,
921 Parameters.EmptyReadOnlyParameters,
922 new ConstructorBaseInitializer (
923 null, Parameters.EmptyReadOnlyParameters,
929 c.Block = new ToplevelBlock (null, Location);
934 /// The pending methods that need to be implemented
935 // (interfaces or abstract methods)
937 public PendingImplementation Pending;
939 public abstract PendingImplementation GetPendingImplementations ();
941 TypeExpr[] GetPartialBases (out TypeExpr base_class)
943 ArrayList ifaces = new ArrayList ();
946 Location base_loc = Location.Null;
948 foreach (ClassPart part in parts) {
949 TypeExpr new_base_class;
950 TypeExpr[] new_ifaces;
952 new_ifaces = part.GetClassBases (out new_base_class);
953 if (new_ifaces == null && new_base_class != null)
956 if ((base_class != null) && (new_base_class != null) &&
957 !base_class.Equals (new_base_class)) {
958 Report.Error (263, part.Location,
959 "Partial declarations of `{0}' must " +
960 "not specify different base classes",
963 if (!Location.IsNull (base_loc))
964 Report.LocationOfPreviousError (base_loc);
969 if ((base_class == null) && (new_base_class != null)) {
970 base_class = new_base_class;
971 base_loc = part.Location;
974 if (new_ifaces == null)
977 foreach (TypeExpr iface in new_ifaces) {
979 foreach (TypeExpr old_iface in ifaces) {
980 if (old_iface.Equals (iface)) {
991 TypeExpr[] retval = new TypeExpr [ifaces.Count];
992 ifaces.CopyTo (retval, 0);
996 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1000 int count = Bases.Count;
1001 int start = 0, i, j;
1003 if (Kind == Kind.Class){
1004 TypeExpr name = ResolveBaseTypeExpr (
1005 (Expression) Bases [0], false, Location);
1011 if (!name.IsInterface) {
1012 // base_class could be a class, struct, enum, delegate.
1013 // This is validated in GetClassBases.
1019 TypeExpr [] ifaces = new TypeExpr [count-start];
1021 for (i = start, j = 0; i < count; i++, j++){
1022 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1023 if (resolved == null) {
1027 ifaces [j] = resolved;
1034 /// This function computes the Base class and also the
1035 /// list of interfaces that the class or struct @c implements.
1037 /// The return value is an array (might be null) of
1038 /// interfaces implemented (as Types).
1040 /// The @base_class argument is set to the base object or null
1041 /// if this is `System.Object'.
1043 TypeExpr [] GetClassBases (out TypeExpr base_class)
1050 ifaces = GetPartialBases (out base_class);
1051 else if (Bases == null){
1055 ifaces = GetNormalBases (out base_class);
1060 if ((base_class != null) && (Kind == Kind.Class)){
1062 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1063 Report.Error (1521, base_class.Location, "Invalid base type");
1067 if (base_class.IsSealed){
1068 Report.SymbolRelatedToPreviousError (base_class.Type);
1069 if (base_class.Type.IsAbstract) {
1070 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1072 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1077 if (!base_class.CanInheritFrom ()){
1078 Report.Error (644, Location,
1079 "`{0}' cannot inherit from special class `{1}'",
1080 Name, base_class.Name);
1084 if (!base_class.AsAccessible (this, ModFlags)) {
1085 Report.SymbolRelatedToPreviousError (base_class.Type);
1086 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1087 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1091 if (base_class != null)
1092 base_class_name = base_class.Name;
1097 int count = ifaces != null ? ifaces.Length : 0;
1099 for (i = 0; i < count; i++) {
1100 TypeExpr iface = (TypeExpr) ifaces [i];
1102 if (!iface.IsInterface) {
1103 if (Kind != Kind.Class) {
1104 // TODO: location of symbol related ....
1105 Error_TypeInListIsNotInterface (Location, iface.FullName);
1107 else if (base_class != null)
1108 Report.Error (1721, Location,
1109 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1112 Report.Error (1722, Location,
1113 "In Class `{0}', `{1}' is not " +
1114 "an interface, a base class must be listed first", Name, iface.Name);
1119 for (int x = 0; x < i; x++) {
1120 if (iface.Equals (ifaces [x])) {
1121 Report.Error (528, Location,
1122 "`{0}' is already listed in " +
1123 "interface list", iface.Name);
1128 if ((Kind == Kind.Interface) &&
1129 !iface.AsAccessible (Parent, ModFlags)) {
1130 Report.Error (61, Location,
1131 "Inconsistent accessibility: base " +
1132 "interface `{0}' is less accessible " +
1133 "than interface `{1}'", iface.Name,
1143 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1145 Report.Error (527, loc, "'{0}': type in interface list is not an interface", type);
1149 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1151 public override TypeBuilder DefineType ()
1156 if (TypeBuilder != null)
1159 TypeAttributes type_attributes = TypeAttr;
1163 if (TypeManager.NamespaceClash (Name, Location)) {
1168 ModuleBuilder builder = CodeGen.Module.Builder;
1169 TypeBuilder = builder.DefineType (
1170 Name, type_attributes, null, null);
1172 TypeBuilder builder = Parent.TypeBuilder;
1173 if (builder == null) {
1178 TypeBuilder = builder.DefineNestedType (
1179 Basename, type_attributes, ptype, null);
1181 } catch (ArgumentException) {
1182 Report.RuntimeMissingSupport (Location, "static classes");
1187 TypeManager.AddUserType (Name, TypeBuilder, this);
1189 if (Parts != null) {
1191 foreach (ClassPart part in Parts) {
1192 part.TypeBuilder = TypeBuilder;
1194 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1195 part.ec.ContainerType = TypeBuilder;
1198 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1199 ec.ContainerType = TypeBuilder;
1202 iface_exprs = GetClassBases (out base_type);
1203 if (iface_exprs == null && base_type != null) {
1208 if (base_type == null) {
1209 if (Kind == Kind.Class){
1210 if (RootContext.StdLib)
1211 base_type = TypeManager.system_object_expr;
1212 else if (Name != "System.Object")
1213 base_type = TypeManager.system_object_expr;
1214 } else if (Kind == Kind.Struct) {
1216 // If we are compiling our runtime,
1217 // and we are defining ValueType, then our
1218 // base is `System.Object'.
1220 if (!RootContext.StdLib && Name == "System.ValueType")
1221 base_type = TypeManager.system_object_expr;
1223 base_type = TypeManager.system_valuetype_expr;
1227 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1228 throw new Exception ();
1230 if (base_type != null) {
1231 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1232 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1233 ptype = base_type.ResolveType (TypeResolveEmitContext);
1234 if (ptype == null) {
1240 if (!CheckRecursiveDefinition (this)) {
1246 TypeBuilder.SetParent (ptype);
1248 // add interfaces that were not added at type creation
1249 if (iface_exprs != null) {
1250 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1251 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1252 TypeResolveEmitContext.ContainerType = TypeBuilder;
1253 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1254 if (ifaces == null) {
1259 foreach (Type itype in ifaces)
1260 TypeBuilder.AddInterfaceImplementation (itype);
1262 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1265 if (!(this is Iterator))
1266 RootContext.RegisterOrder (this);
1268 if (!DefineNestedTypes ()) {
1276 protected virtual bool DefineNestedTypes ()
1278 if (Interfaces != null) {
1279 foreach (TypeContainer iface in Interfaces)
1280 if (iface.DefineType () == null)
1284 if (Types != null) {
1285 foreach (TypeContainer tc in Types)
1286 if (tc.DefineType () == null)
1290 if (Delegates != null) {
1291 foreach (Delegate d in Delegates)
1292 if (d.DefineType () == null)
1296 if (Enums != null) {
1297 foreach (Enum en in Enums)
1298 if (en.DefineType () == null)
1305 TypeContainer InTransit;
1307 protected bool CheckRecursiveDefinition (TypeContainer tc)
1309 if (InTransit != null) {
1310 Report.SymbolRelatedToPreviousError (this);
1311 if (this is Interface)
1313 529, tc.Location, "Inherited interface '{0}' causes a " +
1314 "cycle in the interface hierarchy of '{1}'",
1315 GetSignatureForError (), tc.GetSignatureForError ());
1318 146, tc.Location, "Circular base class dependency " +
1319 "involving '{0}' and '{1}'",
1320 tc.GetSignatureForError (), GetSignatureForError ());
1326 Type parent = ptype;
1327 if (parent != null) {
1328 TypeContainer ptc = TypeManager.LookupTypeContainer (parent);
1329 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1333 if (iface_exprs != null) {
1334 foreach (TypeExpr iface in iface_exprs) {
1335 Type itype = iface.Type;
1337 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1338 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1347 static void Error_KeywordNotAllowed (Location loc)
1349 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1353 /// Populates our TypeBuilder with fields and methods
1355 public override bool DefineMembers (TypeContainer container)
1357 if (members_defined)
1358 return members_defined_ok;
1360 members_defined_ok = DoDefineMembers ();
1361 members_defined = true;
1363 return members_defined_ok;
1366 bool DoDefineMembers ()
1369 if ((ModFlags & Modifiers.NEW) != 0)
1370 Error_KeywordNotAllowed (Location);
1372 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1373 if (conflict_symbol == null) {
1374 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1375 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1377 if ((ModFlags & Modifiers.NEW) == 0) {
1378 Report.SymbolRelatedToPreviousError (conflict_symbol);
1379 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1384 DefineContainerMembers (constants);
1385 DefineContainerMembers (fields);
1387 if ((Kind == Kind.Class) && !(this is ClassPart)){
1388 if ((instance_constructors == null) &&
1389 !(this is StaticClass)) {
1390 if (default_constructor == null)
1391 DefineDefaultConstructor (false);
1394 if (initialized_static_fields != null &&
1395 default_static_constructor == null)
1396 DefineDefaultConstructor (true);
1399 if (Kind == Kind.Struct){
1401 // Structs can not have initialized instance
1404 if (initialized_static_fields != null &&
1405 default_static_constructor == null)
1406 DefineDefaultConstructor (true);
1408 if (initialized_fields != null)
1409 ReportStructInitializedInstanceError ();
1412 Pending = GetPendingImplementations ();
1414 if (parts != null) {
1415 foreach (ClassPart part in parts) {
1416 if (!part.DefineMembers (this))
1422 // Constructors are not in the defined_names array
1424 DefineContainerMembers (instance_constructors);
1426 if (default_static_constructor != null)
1427 default_static_constructor.Define ();
1429 DefineContainerMembers (properties);
1430 DefineContainerMembers (events);
1431 DefineContainerMembers (indexers);
1432 DefineContainerMembers (methods);
1433 DefineContainerMembers (operators);
1434 DefineContainerMembers (enums);
1435 DefineContainerMembers (delegates);
1438 if (!(this is ClassPart))
1439 member_cache = new MemberCache (this);
1442 if (parts != null) {
1443 foreach (ClassPart part in parts)
1444 part.member_cache = member_cache;
1447 if (iterators != null) {
1448 foreach (Iterator iterator in iterators) {
1449 if (iterator.DefineType () == null)
1453 foreach (Iterator iterator in iterators) {
1454 if (!iterator.DefineMembers (this))
1462 void ReportStructInitializedInstanceError ()
1464 string n = TypeBuilder.FullName;
1466 foreach (Field f in initialized_fields){
1469 "`" + n + "." + f.Name + "': can not have " +
1470 "instance field initializers in structs");
1474 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1477 mcal.DefineContainerMembers ();
1480 public override bool Define ()
1482 if (parts != null) {
1483 foreach (ClassPart part in parts) {
1484 if (!part.Define ())
1492 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1494 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1498 /// This function is based by a delegate to the FindMembers routine
1500 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1506 /// This filter is used by FindMembers, and we just keep
1507 /// a global for the filter to `AlwaysAccept'
1509 static MemberFilter accepting_filter;
1512 static TypeContainer ()
1514 accepting_filter = new MemberFilter (AlwaysAccept);
1517 public MethodInfo[] GetMethods ()
1519 ArrayList members = new ArrayList ();
1521 DefineMembers (null);
1523 if (methods != null) {
1524 int len = methods.Count;
1525 for (int i = 0; i < len; i++) {
1526 Method m = (Method) methods [i];
1528 members.Add (m.MethodBuilder);
1532 if (operators != null) {
1533 int len = operators.Count;
1534 for (int i = 0; i < len; i++) {
1535 Operator o = (Operator) operators [i];
1537 members.Add (o.OperatorMethodBuilder);
1541 if (properties != null) {
1542 int len = properties.Count;
1543 for (int i = 0; i < len; i++) {
1544 Property p = (Property) properties [i];
1546 if (p.GetBuilder != null)
1547 members.Add (p.GetBuilder);
1548 if (p.SetBuilder != null)
1549 members.Add (p.SetBuilder);
1553 if (indexers != null) {
1554 int len = indexers.Count;
1555 for (int i = 0; i < len; i++) {
1556 Indexer ix = (Indexer) indexers [i];
1558 if (ix.GetBuilder != null)
1559 members.Add (ix.GetBuilder);
1560 if (ix.SetBuilder != null)
1561 members.Add (ix.SetBuilder);
1565 if (events != null) {
1566 int len = events.Count;
1567 for (int i = 0; i < len; i++) {
1568 Event e = (Event) events [i];
1570 if (e.AddBuilder != null)
1571 members.Add (e.AddBuilder);
1572 if (e.RemoveBuilder != null)
1573 members.Add (e.RemoveBuilder);
1577 MethodInfo[] retMethods = new MethodInfo [members.Count];
1578 members.CopyTo (retMethods, 0);
1582 // Indicated whether container has StructLayout attribute set Explicit
1583 public virtual bool HasExplicitLayout {
1589 public override Type FindNestedType (string name)
1591 ArrayList [] lists = { types, enums, delegates, interfaces };
1593 for (int j = 0; j < lists.Length; ++j) {
1594 ArrayList list = lists [j];
1598 int len = list.Count;
1599 for (int i = 0; i < len; ++i) {
1600 DeclSpace ds = (DeclSpace) list [i];
1601 if (ds.Basename == name) {
1603 return ds.TypeBuilder;
1611 private void FindMembers_NestedTypes (int modflags,
1612 BindingFlags bf, MemberFilter filter, object criteria,
1613 ref ArrayList members)
1615 ArrayList [] lists = { types, enums, delegates, interfaces };
1617 for (int j = 0; j < lists.Length; ++j) {
1618 ArrayList list = lists [j];
1622 int len = list.Count;
1623 for (int i = 0; i < len; i++) {
1624 DeclSpace ds = (DeclSpace) list [i];
1626 if ((ds.ModFlags & modflags) == 0)
1629 TypeBuilder tb = ds.TypeBuilder;
1631 if (!(criteria is string) || ds.Basename.Equals (criteria))
1632 tb = ds.DefineType ();
1635 if (tb != null && (filter (tb, criteria) == true)) {
1636 if (members == null)
1637 members = new ArrayList ();
1646 /// This method returns the members of this type just like Type.FindMembers would
1647 /// Only, we need to use this for types which are _being_ defined because MS'
1648 /// implementation can't take care of that.
1651 // FIXME: return an empty static array instead of null, that cleans up
1652 // some code and is consistent with some coding conventions I just found
1656 // Notice that in various cases we check if our field is non-null,
1657 // something that would normally mean that there was a bug elsewhere.
1659 // The problem happens while we are defining p-invoke methods, as those
1660 // will trigger a FindMembers, but this happens before things are defined
1662 // Since the whole process is a no-op, it is fine to check for null here.
1664 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1665 MemberFilter filter, object criteria)
1667 ArrayList members = null;
1670 if ((bf & BindingFlags.Public) != 0)
1671 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1673 if ((bf & BindingFlags.NonPublic) != 0)
1674 modflags |= Modifiers.PRIVATE;
1676 int static_mask = 0, static_flags = 0;
1677 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1678 case BindingFlags.Static:
1679 static_mask = static_flags = Modifiers.STATIC;
1682 case BindingFlags.Instance:
1683 static_mask = Modifiers.STATIC;
1688 static_mask = static_flags = 0;
1692 Timer.StartTimer (TimerType.TcFindMembers);
1695 filter = accepting_filter;
1697 if ((mt & MemberTypes.Field) != 0) {
1698 if (fields != null) {
1699 int len = fields.Count;
1700 for (int i = 0; i < len; i++) {
1701 FieldMember f = (FieldMember) fields [i];
1703 if ((f.ModFlags & modflags) == 0)
1705 if ((f.ModFlags & static_mask) != static_flags)
1708 FieldBuilder fb = f.FieldBuilder;
1709 if (fb != null && filter (fb, criteria) == true) {
1710 if (members == null)
1711 members = new ArrayList ();
1718 if (constants != null) {
1719 int len = constants.Count;
1720 for (int i = 0; i < len; i++) {
1721 Const con = (Const) constants [i];
1723 if ((con.ModFlags & modflags) == 0)
1725 if ((con.ModFlags & static_mask) != static_flags)
1728 FieldBuilder fb = con.FieldBuilder;
1731 fb = con.FieldBuilder;
1733 if (fb != null && filter (fb, criteria) == true) {
1734 if (members == null)
1735 members = new ArrayList ();
1743 if ((mt & MemberTypes.Method) != 0) {
1744 if (methods != null) {
1745 int len = methods.Count;
1746 for (int i = 0; i < len; i++) {
1747 Method m = (Method) methods [i];
1749 if ((m.ModFlags & modflags) == 0)
1751 if ((m.ModFlags & static_mask) != static_flags)
1754 MethodBuilder mb = m.MethodBuilder;
1756 if (mb != null && filter (mb, criteria) == true) {
1757 if (members == null)
1758 members = new ArrayList ();
1765 if (operators != null) {
1766 int len = operators.Count;
1767 for (int i = 0; i < len; i++) {
1768 Operator o = (Operator) operators [i];
1770 if ((o.ModFlags & modflags) == 0)
1772 if ((o.ModFlags & static_mask) != static_flags)
1775 MethodBuilder ob = o.OperatorMethodBuilder;
1776 if (ob != null && filter (ob, criteria) == true) {
1777 if (members == null)
1778 members = new ArrayList ();
1785 if (properties != null) {
1786 int len = properties.Count;
1787 for (int i = 0; i < len; i++) {
1788 Property p = (Property) properties [i];
1790 if ((p.ModFlags & modflags) == 0)
1792 if ((p.ModFlags & static_mask) != static_flags)
1798 if (b != null && filter (b, criteria) == true) {
1799 if (members == null)
1800 members = new ArrayList ();
1806 if (b != null && filter (b, criteria) == true) {
1807 if (members == null)
1808 members = new ArrayList ();
1815 if (indexers != null) {
1816 int len = indexers.Count;
1817 for (int i = 0; i < len; i++) {
1818 Indexer ix = (Indexer) indexers [i];
1820 if ((ix.ModFlags & modflags) == 0)
1822 if ((ix.ModFlags & static_mask) != static_flags)
1828 if (b != null && filter (b, criteria) == true) {
1829 if (members == null)
1830 members = new ArrayList ();
1836 if (b != null && filter (b, criteria) == true) {
1837 if (members == null)
1838 members = new ArrayList ();
1846 if ((mt & MemberTypes.Event) != 0) {
1847 if (events != null) {
1848 int len = events.Count;
1849 for (int i = 0; i < len; i++) {
1850 Event e = (Event) events [i];
1852 if ((e.ModFlags & modflags) == 0)
1854 if ((e.ModFlags & static_mask) != static_flags)
1857 MemberInfo eb = e.EventBuilder;
1858 if (eb != null && filter (eb, criteria) == true) {
1859 if (members == null)
1860 members = new ArrayList ();
1862 members.Add (e.EventBuilder);
1868 if ((mt & MemberTypes.Property) != 0){
1869 if (properties != null) {
1870 int len = properties.Count;
1871 for (int i = 0; i < len; i++) {
1872 Property p = (Property) properties [i];
1874 if ((p.ModFlags & modflags) == 0)
1876 if ((p.ModFlags & static_mask) != static_flags)
1879 MemberInfo pb = p.PropertyBuilder;
1880 if (pb != null && filter (pb, criteria) == true) {
1881 if (members == null)
1882 members = new ArrayList ();
1884 members.Add (p.PropertyBuilder);
1889 if (indexers != null) {
1890 int len = indexers.Count;
1891 for (int i = 0; i < len; i++) {
1892 Indexer ix = (Indexer) indexers [i];
1894 if ((ix.ModFlags & modflags) == 0)
1896 if ((ix.ModFlags & static_mask) != static_flags)
1899 MemberInfo ib = ix.PropertyBuilder;
1900 if (ib != null && filter (ib, criteria) == true) {
1901 if (members == null)
1902 members = new ArrayList ();
1904 members.Add (ix.PropertyBuilder);
1910 if ((mt & MemberTypes.NestedType) != 0)
1911 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1913 if ((mt & MemberTypes.Constructor) != 0){
1914 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1915 int len = instance_constructors.Count;
1916 for (int i = 0; i < len; i++) {
1917 Constructor c = (Constructor) instance_constructors [i];
1919 ConstructorBuilder cb = c.ConstructorBuilder;
1920 if (cb != null && filter (cb, criteria) == true) {
1921 if (members == null)
1922 members = new ArrayList ();
1929 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1930 ConstructorBuilder cb =
1931 default_static_constructor.ConstructorBuilder;
1933 if (cb != null && filter (cb, criteria) == true) {
1934 if (members == null)
1935 members = new ArrayList ();
1943 // Lookup members in base if requested.
1945 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1946 if (TypeBuilder.BaseType != null) {
1947 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1948 if (list.Count > 0) {
1949 if (members == null)
1950 members = new ArrayList ();
1952 members.AddRange (list);
1955 if (ifaces != null) {
1956 foreach (Type base_type in ifaces) {
1957 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1959 if (list.Count > 0) {
1960 if (members == null)
1961 members = new ArrayList ();
1962 members.AddRange (list);
1968 Timer.StopTimer (TimerType.TcFindMembers);
1970 if (members == null)
1971 return MemberList.Empty;
1973 return new MemberList (members);
1976 public override MemberCache MemberCache {
1978 return member_cache;
1982 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1983 MemberFilter filter, object criteria)
1985 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1988 return ds.FindMembers (mt, bf, filter, criteria);
1990 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1995 // FindMethods will look for methods not only in the type `t', but in
1996 // any interfaces implemented by the type.
1998 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1999 MemberFilter filter, object criteria)
2005 /// Emits the values for the constants
2007 public void EmitConstants ()
2009 if (constants != null)
2010 foreach (Const con in constants)
2015 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2020 foreach (MemberCore mc in al) {
2021 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2025 Report.Warning (169, mc.Location, "The private {0} '{1}' is never used", member_type, mc.GetSignatureForError ());
2030 public virtual void VerifyMembers ()
2033 // Check for internal or private fields that were never assigned
2035 if (RootContext.WarningLevel >= 3) {
2036 CheckMemberUsage (properties, "property");
2037 CheckMemberUsage (methods, "method");
2038 CheckMemberUsage (constants, "constant");
2040 if (fields != null){
2041 foreach (FieldMember f in fields) {
2042 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2046 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2051 // Only report 649 on level 4
2053 if (RootContext.WarningLevel < 4)
2056 if ((f.status & Field.Status.ASSIGNED) != 0)
2059 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2066 /// Emits the code, this step is performed after all
2067 /// the types, enumerations, constructors
2069 public void EmitType ()
2071 if (OptAttributes != null)
2072 OptAttributes.Emit (ec, this);
2075 // Structs with no fields need to have at least one byte.
2076 // The right thing would be to set the PackingSize in a DefineType
2077 // but there are no functions that allow interfaces *and* the size to
2081 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
2082 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2083 FieldAttributes.Private);
2085 if (HasExplicitLayout){
2086 object [] ctor_args = new object [1];
2089 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2090 TypeManager.field_offset_attribute_ctor, ctor_args);
2091 fb.SetCustomAttribute (cba);
2097 if (instance_constructors != null) {
2098 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2099 bool has_compliant_args = false;
2101 foreach (Constructor c in instance_constructors) {
2104 if (has_compliant_args)
2107 has_compliant_args = c.HasCompliantArgs;
2109 if (!has_compliant_args)
2110 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2112 foreach (Constructor c in instance_constructors)
2117 // Can not continue if constants are broken
2119 if (Report.Errors > 0)
2122 if (default_static_constructor != null)
2123 default_static_constructor.Emit ();
2125 if (methods != null)
2126 foreach (Method m in methods)
2129 if (operators != null)
2130 foreach (Operator o in operators)
2133 if (properties != null)
2134 foreach (Property p in properties)
2137 if (indexers != null){
2142 foreach (FieldMember f in fields)
2145 if (events != null){
2146 foreach (Event e in Events)
2150 if (delegates != null) {
2151 foreach (Delegate d in Delegates) {
2156 if (enums != null) {
2157 foreach (Enum e in enums) {
2162 if (parts != null) {
2163 foreach (ClassPart part in parts)
2167 if ((Pending != null) && !(this is ClassPart))
2168 if (Pending.VerifyPendingMethods ())
2171 if (iterators != null)
2172 foreach (Iterator iterator in iterators)
2173 iterator.EmitType ();
2175 // if (types != null)
2176 // foreach (TypeContainer tc in types)
2180 public override void CloseType ()
2182 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2186 caching_flags |= Flags.CloseTypeCreated;
2187 TypeBuilder.CreateType ();
2188 } catch (TypeLoadException){
2190 // This is fine, the code still created the type
2192 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2193 // Console.WriteLine (e.Message);
2195 Console.WriteLine ("In type: " + Name);
2200 foreach (Enum en in Enums)
2204 foreach (TypeContainer tc in Types)
2205 if (tc.Kind == Kind.Struct)
2208 foreach (TypeContainer tc in Types)
2209 if (tc.Kind != Kind.Struct)
2213 if (Delegates != null)
2214 foreach (Delegate d in Delegates)
2217 if (Iterators != null)
2218 foreach (Iterator i in Iterators)
2226 initialized_fields = null;
2227 initialized_static_fields = null;
2236 default_constructor = null;
2237 default_static_constructor = null;
2239 OptAttributes = null;
2242 member_cache = null;
2245 // TODO: make it obsolete and use GetSignatureForError
2246 public string MakeName (string n)
2248 return "`" + Name + "." + n + "'";
2252 // Performs the validation on a Method's modifiers (properties have
2253 // the same properties).
2255 public bool MethodModifiersValid (MemberCore mc)
2257 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2258 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2259 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2261 int flags = mc.ModFlags;
2264 // At most one of static, virtual or override
2266 if ((flags & Modifiers.STATIC) != 0){
2267 if ((flags & vao) != 0){
2268 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2269 GetSignatureForError ());
2274 if (Kind == Kind.Struct){
2275 if ((flags & va) != 0){
2276 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2281 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2282 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2287 // If the declaration includes the abstract modifier, then the
2288 // declaration does not include static, virtual or extern
2290 if ((flags & Modifiers.ABSTRACT) != 0){
2291 if ((flags & Modifiers.EXTERN) != 0){
2293 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2297 if ((flags & Modifiers.SEALED) != 0) {
2298 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2302 if ((flags & Modifiers.VIRTUAL) != 0){
2303 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2307 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2308 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2313 if ((flags & Modifiers.PRIVATE) != 0){
2314 if ((flags & vao) != 0){
2315 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2320 if ((flags & Modifiers.SEALED) != 0){
2321 if ((flags & Modifiers.OVERRIDE) == 0){
2322 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2330 public bool UserDefinedStaticConstructor {
2332 return default_static_constructor != null;
2336 public Constructor DefaultStaticConstructor {
2337 get { return default_static_constructor; }
2340 protected override bool VerifyClsCompliance (DeclSpace ds)
2342 if (!base.VerifyClsCompliance (ds))
2347 Type base_type = TypeBuilder.BaseType;
2348 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2349 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2352 if (!Parent.IsClsCompliaceRequired (ds)) {
2353 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2354 GetSignatureForError (), Parent.GetSignatureForError ());
2361 /// Checks whether container name is CLS Compliant
2363 void VerifyClsName ()
2365 Hashtable base_members = base_cache == null ?
2367 base_cache.GetPublicMembers ();
2368 Hashtable this_members = new Hashtable ();
2370 foreach (DictionaryEntry entry in defined_names) {
2371 MemberCore mc = (MemberCore)entry.Value;
2372 if (!mc.IsClsCompliaceRequired (this))
2375 string name = (string)entry.Key;
2376 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2378 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2379 object found = base_members [lcase];
2380 if (found == null) {
2381 found = this_members [lcase];
2382 if (found == null) {
2383 this_members.Add (lcase, mc);
2388 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2391 if (found is MemberInfo) {
2392 if (basename == ((MemberInfo)found).Name)
2394 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2396 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2398 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2404 /// Performs checks for an explicit interface implementation. First it
2405 /// checks whether the `interface_type' is a base inteface implementation.
2406 /// Then it checks whether `name' exists in the interface type.
2408 public virtual bool VerifyImplements (Type interface_type, string full,
2409 string name, Location loc)
2413 if (ifaces != null){
2414 foreach (Type t in ifaces){
2415 if (t == interface_type){
2423 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2424 full, interface_type.FullName);
2431 protected override void VerifyObsoleteAttribute()
2433 CheckUsageOfObsoleteAttribute (ptype);
2438 foreach (Type iface in ifaces) {
2439 CheckUsageOfObsoleteAttribute (iface);
2448 string IMemberContainer.Name {
2454 Type IMemberContainer.Type {
2460 MemberCache IMemberContainer.MemberCache {
2462 return member_cache;
2466 bool IMemberContainer.IsInterface {
2468 return Kind == Kind.Interface;
2472 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2474 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2478 // Generates xml doc comments (if any), and if required,
2479 // handle warning report.
2481 internal override void GenerateDocComment (DeclSpace ds)
2483 DocUtil.GenerateTypeDocComment (this, ds);
2486 public override string DocCommentHeader {
2487 get { return "T:"; }
2490 public virtual MemberCache BaseCache {
2492 if (base_cache != null)
2494 if (TypeBuilder.BaseType != null)
2495 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2496 if (TypeBuilder.IsInterface)
2497 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2503 public class PartialContainer : TypeContainer {
2505 public readonly Namespace Namespace;
2506 public readonly int OriginalModFlags;
2507 public readonly int AllowedModifiers;
2508 public readonly TypeAttributes DefaultTypeAttributes;
2510 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2511 MemberName member_name, int mod_flags, Kind kind,
2514 PartialContainer pc;
2515 DeclSpace ds = RootContext.Tree.GetDecl (member_name);
2517 pc = ds as PartialContainer;
2521 260, ds.Location, "Missing partial modifier " +
2522 "on declaration of type `{0}'; another " +
2523 "partial implementation of this type exists",
2524 member_name.GetPartialName());
2526 Report.LocationOfPreviousError (loc);
2530 if (pc.Kind != kind) {
2532 261, loc, "Partial declarations of `{0}' " +
2533 "must be all classes, all structs or " +
2534 "all interfaces", member_name.GetPartialName ());
2538 if (pc.OriginalModFlags != mod_flags) {
2540 262, loc, "Partial declarations of `{0}' " +
2541 "have conflicting accessibility modifiers",
2542 member_name.GetPartialName ());
2549 if (parent is ClassPart)
2550 parent = ((ClassPart) parent).PartialContainer;
2552 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2553 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2555 if (kind == Kind.Interface)
2556 parent.AddInterface (pc);
2557 else if (kind == Kind.Class || kind == Kind.Struct)
2558 parent.AddClassOrStruct (pc);
2560 throw new InvalidOperationException ();
2565 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2566 MemberName name, int mod, Attributes attrs,
2567 Kind kind, Location loc)
2569 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2571 // An error occured; create a dummy container, but don't
2573 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2576 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2581 protected PartialContainer (Namespace ns, TypeContainer parent,
2582 MemberName name, int mod, Kind kind, Location l)
2583 : base (null, parent, name, null, kind, l)
2585 this.Namespace = ns;
2589 AllowedModifiers = Class.AllowedModifiers;
2590 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2594 AllowedModifiers = Struct.AllowedModifiers;
2595 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2598 case Kind.Interface:
2599 AllowedModifiers = Interface.AllowedModifiers;
2600 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2604 throw new InvalidOperationException ();
2608 if (parent.Parent == null)
2609 accmods = Modifiers.INTERNAL;
2611 accmods = Modifiers.PRIVATE;
2613 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2614 this.OriginalModFlags = mod;
2617 public override PendingImplementation GetPendingImplementations ()
2619 return PendingImplementation.GetPendingImplementations (this);
2622 protected override TypeAttributes TypeAttr {
2624 return base.TypeAttr | DefaultTypeAttributes;
2629 public class ClassPart : TypeContainer, IMemberContainer {
2630 public readonly PartialContainer PartialContainer;
2631 public readonly bool IsPartial;
2633 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2634 int mod, Attributes attrs, Kind kind, Location l)
2635 : base (ns, parent, pc.MemberName, attrs, kind, l)
2637 this.PartialContainer = pc;
2638 this.IsPartial = true;
2641 if (parent == null || parent == RootContext.Tree.Types)
2642 accmods = Modifiers.INTERNAL;
2644 accmods = Modifiers.PRIVATE;
2646 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2649 public override PendingImplementation GetPendingImplementations ()
2651 return PartialContainer.Pending;
2654 public override bool VerifyImplements (Type interface_type, string full,
2655 string name, Location loc)
2657 return PartialContainer.VerifyImplements (
2658 interface_type, full, name, loc);
2662 public override void RegisterFieldForInitialization (FieldMember field)
2664 PartialContainer.RegisterFieldForInitialization (field);
2667 public override bool EmitFieldInitializers (EmitContext ec)
2669 return PartialContainer.EmitFieldInitializers (ec);
2672 public override Type FindNestedType (string name)
2674 return PartialContainer.FindNestedType (name);
2677 public override MemberCache BaseCache {
2679 return PartialContainer.BaseCache;
2683 public override TypeBuilder DefineType ()
2685 throw new InternalErrorException ("Should not get here");
2690 public abstract class ClassOrStruct : TypeContainer {
2691 bool has_explicit_layout = false;
2692 ListDictionary declarative_security;
2694 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2695 MemberName name, Attributes attrs, Kind kind,
2697 : base (ns, parent, name, attrs, kind, l)
2701 public override PendingImplementation GetPendingImplementations ()
2703 return PendingImplementation.GetPendingImplementations (this);
2706 public override bool HasExplicitLayout {
2708 return has_explicit_layout;
2712 public override void VerifyMembers ()
2714 base.VerifyMembers ();
2716 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2717 foreach (Event e in events){
2719 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2724 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2726 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2727 if (declarative_security == null)
2728 declarative_security = new ListDictionary ();
2730 a.ExtractSecurityPermissionSet (declarative_security);
2734 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2735 has_explicit_layout = true;
2737 base.ApplyAttributeBuilder (a, cb);
2740 public override void Emit()
2744 if (declarative_security != null) {
2745 foreach (DictionaryEntry de in declarative_security) {
2746 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2753 /// Class handles static classes declaration
2755 public sealed class StaticClass: Class {
2756 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2757 Attributes attrs, Location l)
2758 : base (ns, parent, name, mod, attrs, l)
2760 if (RootContext.Version == LanguageVersion.ISO_1) {
2761 Report.FeatureIsNotStandardized (l, "static classes");
2765 protected override int AllowedModifiersProp {
2767 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2768 Modifiers.STATIC | Modifiers.UNSAFE;
2772 protected override void DefineContainerMembers (MemberCoreArrayList list)
2777 foreach (MemberCore m in list) {
2778 if (m is Operator) {
2779 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2783 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2784 Report.Warning (628, 4, m.Location, "'{0}': new protected member declared in static class", m.GetSignatureForError (this));
2787 Report.Error (720, m.Location, "'{0}': cannot declare indexers in a static class", m.GetSignatureForError (this));
2791 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2794 if (m is Constructor) {
2795 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2799 if (m is Destructor) {
2800 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2804 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2807 base.DefineContainerMembers (list);
2810 public override TypeBuilder DefineType()
2812 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2813 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2817 TypeBuilder tb = base.DefineType ();
2821 if (ptype != TypeManager.object_type) {
2822 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2826 if (ifaces != null) {
2827 foreach (Type t in ifaces)
2828 Report.SymbolRelatedToPreviousError (t);
2829 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2834 protected override TypeAttributes TypeAttr {
2836 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2841 public class Class : ClassOrStruct {
2842 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2843 public const int AllowedModifiers =
2846 Modifiers.PROTECTED |
2847 Modifiers.INTERNAL |
2849 Modifiers.ABSTRACT |
2853 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2854 Attributes attrs, Location l)
2855 : base (ns, parent, name, attrs, Kind.Class, l)
2857 this.ModFlags = mod;
2860 virtual protected int AllowedModifiersProp {
2862 return AllowedModifiers;
2866 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2868 if (a.Type == TypeManager.attribute_usage_type) {
2869 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2870 TypeBuilder.FullName != "System.Attribute") {
2871 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2875 if (a.Type == TypeManager.conditional_attribute_type &&
2876 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
2877 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2881 if (AttributeTester.IsAttributeExcluded (a.Type))
2884 base.ApplyAttributeBuilder (a, cb);
2887 public const TypeAttributes DefaultTypeAttributes =
2888 TypeAttributes.AutoLayout | TypeAttributes.Class;
2890 public override TypeBuilder DefineType()
2892 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2893 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2897 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2898 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2900 return base.DefineType ();
2903 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2904 /// Valid only for attribute classes.
2905 public bool IsExcluded ()
2907 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2908 return (caching_flags & Flags.Excluded) != 0;
2910 caching_flags &= ~Flags.Excluded_Undetected;
2912 if (OptAttributes == null)
2915 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
2920 foreach (Attribute a in attrs) {
2921 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
2922 if (RootContext.AllDefines.Contains (condition))
2926 caching_flags |= Flags.Excluded;
2931 // FIXME: How do we deal with the user specifying a different
2934 protected override TypeAttributes TypeAttr {
2936 return base.TypeAttr | DefaultTypeAttributes;
2941 public class Struct : ClassOrStruct {
2943 // Modifiers allowed in a struct declaration
2945 public const int AllowedModifiers =
2948 Modifiers.PROTECTED |
2949 Modifiers.INTERNAL |
2953 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2954 int mod, Attributes attrs, Location l)
2955 : base (ns, parent, name, attrs, Kind.Struct, l)
2959 if (parent.Parent == null)
2960 accmods = Modifiers.INTERNAL;
2962 accmods = Modifiers.PRIVATE;
2964 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2966 this.ModFlags |= Modifiers.SEALED;
2969 public const TypeAttributes DefaultTypeAttributes =
2970 TypeAttributes.SequentialLayout |
2971 TypeAttributes.Sealed |
2972 TypeAttributes.BeforeFieldInit;
2975 // FIXME: Allow the user to specify a different set of attributes
2976 // in some cases (Sealed for example is mandatory for a class,
2977 // but what SequentialLayout can be changed
2979 protected override TypeAttributes TypeAttr {
2981 return base.TypeAttr | DefaultTypeAttributes;
2989 public class Interface : TypeContainer, IMemberContainer {
2992 /// Modifiers allowed in a class declaration
2994 public const int AllowedModifiers =
2997 Modifiers.PROTECTED |
2998 Modifiers.INTERNAL |
3002 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3003 Attributes attrs, Location l)
3004 : base (ns, parent, name, attrs, Kind.Interface, l)
3008 if (parent.Parent == null)
3009 accmods = Modifiers.INTERNAL;
3011 accmods = Modifiers.PRIVATE;
3013 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3016 public override PendingImplementation GetPendingImplementations ()
3021 public const TypeAttributes DefaultTypeAttributes =
3022 TypeAttributes.AutoLayout |
3023 TypeAttributes.Abstract |
3024 TypeAttributes.Interface;
3026 protected override TypeAttributes TypeAttr {
3028 return base.TypeAttr | DefaultTypeAttributes;
3032 protected override bool VerifyClsCompliance (DeclSpace ds)
3034 if (!base.VerifyClsCompliance (ds))
3037 if (ifaces != null) {
3038 foreach (Type t in ifaces) {
3039 if (AttributeTester.IsClsCompliant (t))
3042 Report.SymbolRelatedToPreviousError (t);
3043 Report.Warning (3027, 1, Location, "'{0}' is not CLS-compliant because base interface '{1}' is not CLS-compliant",
3044 GetSignatureForError (), TypeManager.CSharpName (t));
3052 public abstract class MethodCore : MemberBase {
3053 public readonly Parameters Parameters;
3054 protected ToplevelBlock block;
3057 // Parameters, cached for semantic analysis.
3059 protected InternalParameters parameter_info;
3060 protected Type [] parameter_types;
3062 // Whether this is an operator method.
3063 public bool IsOperator;
3066 // The method we're overriding if this is an override method.
3068 protected MethodInfo base_method = null;
3070 static string[] attribute_targets = new string [] { "method", "return" };
3072 public MethodCore (TypeContainer parent, Expression type, int mod,
3073 int allowed_mod, bool is_interface, MemberName name,
3074 Attributes attrs, Parameters parameters, Location loc)
3075 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3078 Parameters = parameters;
3079 IsInterface = is_interface;
3083 // Returns the System.Type array for the parameters of this method
3085 public Type [] ParameterTypes {
3087 return parameter_types;
3091 public InternalParameters ParameterInfo
3094 return parameter_info;
3098 public ToplevelBlock Block {
3108 protected override bool CheckBase ()
3110 if (!base.CheckBase ())
3113 // Check whether arguments were correct.
3114 if (!DoDefineParameters ())
3117 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3123 // Is null for System.Object while compiling corlib and base interfaces
3124 if (Parent.BaseCache == null) {
3125 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3126 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3131 Type base_ret_type = null;
3132 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3134 // method is override
3135 if (base_method != null) {
3137 if (!CheckMethodAgainstBase ())
3140 if ((ModFlags & Modifiers.NEW) == 0) {
3141 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3142 Report.SymbolRelatedToPreviousError (base_method);
3143 if (this is PropertyBase) {
3144 Report.Error (1715, Location, "'{0}': type must be '{1}' to match overridden member '{2}'",
3145 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3148 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3149 "change return type when overriding inherited member");
3154 if (base_method.IsAbstract && !IsInterface) {
3155 Report.SymbolRelatedToPreviousError (base_method);
3156 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3161 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3162 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3166 if (RootContext.WarningLevel > 2) {
3167 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3168 Parent.Methods.HasEquals = true;
3169 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3170 Parent.Methods.HasGetHashCode = true;
3173 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3174 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3176 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3177 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3178 Report.SymbolRelatedToPreviousError (base_method);
3179 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3186 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3187 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3188 if (conflict_symbol != null) {
3189 Report.SymbolRelatedToPreviousError (conflict_symbol);
3190 if (this is PropertyBase)
3191 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3193 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3195 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3199 if (conflict_symbol == null) {
3200 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3201 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3206 if ((ModFlags & Modifiers.NEW) == 0) {
3207 if (this is Method && conflict_symbol is MethodBase)
3210 Report.SymbolRelatedToPreviousError (conflict_symbol);
3211 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3219 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3220 // that have been defined.
3222 // `name' is the user visible name for reporting errors (this is used to
3223 // provide the right name regarding method names and properties)
3225 bool CheckMethodAgainstBase ()
3229 // TODO: replace with GetSignatureForError
3230 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3232 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3233 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3235 506, Location, Parent.MakeName (Name) +
3236 ": cannot override inherited member `" +
3237 name + "' because it is not " +
3238 "virtual, abstract or override");
3242 // Now we check that the overriden method is not final
3244 if (base_method.IsFinal) {
3245 Report.SymbolRelatedToPreviousError (base_method);
3246 Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
3247 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3251 // Check that the permissions are not being changed
3253 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3254 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3256 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3257 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3262 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3263 ModFlags |= Modifiers.NEW;
3264 Report.SymbolRelatedToPreviousError (base_method);
3265 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3266 if (RootContext.WarningLevel >= 2)
3267 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 (base_method));
3269 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3275 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3277 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3279 // when overriding protected internal, the method can be declared
3280 // protected internal only within the same assembly
3283 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3284 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3286 // assemblies differ - report an error
3290 } else if (thisp != base_classp) {
3292 // same assembly, but other attributes differ - report an error
3297 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3299 // if it's not "protected internal", it must be "protected"
3303 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3305 // protected within the same assembly - an error
3308 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3309 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3311 // protected ok, but other attributes differ - report an error
3317 return (thisp == base_classp);
3321 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3324 // FIXME: report the old/new permissions?
3327 507, Location, parent.MakeName (Name) +
3328 ": can't change the access modifiers when overriding inherited " +
3329 "member `" + name + "'");
3332 protected static string Error722 {
3334 return "'{0}': static types cannot be used as return types";
3339 /// For custom member duplication search in a container
3341 protected abstract bool CheckForDuplications ();
3344 /// Gets base method and its return type
3346 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3348 protected virtual bool DoDefineParameters ()
3350 EmitContext ec = Parent.EmitContext;
3352 throw new InternalErrorException ("DoDefineParameters invoked too early");
3354 bool old_unsafe = ec.InUnsafe;
3355 ec.InUnsafe = InUnsafe;
3356 // Check if arguments were correct
3357 parameter_types = Parameters.GetParameterInfo (ec);
3358 ec.InUnsafe = old_unsafe;
3360 if ((parameter_types == null) ||
3361 !CheckParameters (Parent, parameter_types))
3364 parameter_info = new InternalParameters (parameter_types, Parameters);
3366 Parameter array_param = Parameters.ArrayParameter;
3367 if ((array_param != null) &&
3368 (!array_param.ParameterType.IsArray ||
3369 (array_param.ParameterType.GetArrayRank () != 1))) {
3370 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3377 public override string[] ValidAttributeTargets {
3379 return attribute_targets;
3383 protected override bool VerifyClsCompliance (DeclSpace ds)
3385 if (!base.VerifyClsCompliance (ds)) {
3386 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3387 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3392 if (Parameters.HasArglist) {
3393 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3396 if (!AttributeTester.IsClsCompliant (MemberType)) {
3397 if (this is PropertyBase)
3398 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3399 GetSignatureForError ());
3401 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3402 GetSignatureForError ());
3405 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3410 protected bool IsDuplicateImplementation (MethodCore method)
3412 if ((method == this) || (method.Name != Name))
3415 Type[] param_types = method.ParameterTypes;
3416 if (param_types == null)
3419 if (param_types.Length != ParameterTypes.Length)
3422 for (int i = 0; i < param_types.Length; i++)
3423 if (param_types [i] != ParameterTypes [i])
3426 // TODO: make operator compatible with MethodCore to avoid this
3427 if (this is Operator && method is Operator) {
3428 if (MemberType != method.MemberType)
3433 // Try to report 663: method only differs on out/ref
3435 ParameterData info = ParameterInfo;
3436 ParameterData other_info = method.ParameterInfo;
3437 for (int i = 0; i < info.Count; i++){
3438 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3439 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3444 Report.SymbolRelatedToPreviousError (method);
3445 if (this is Operator && method is Operator)
3446 Report.Error (557, Location, "Duplicate user-defined conversion in type '{0}'", Parent.Name);
3448 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3452 public override bool IsUsed
3463 // Returns a string that represents the signature for this
3464 // member which should be used in XML documentation.
3466 public override string GetDocCommentName (DeclSpace ds)
3468 return DocUtil.GetMethodDocCommentName (this, ds);
3472 // Raised (and passed an XmlElement that contains the comment)
3473 // when GenerateDocComment is writing documentation expectedly.
3475 // FIXME: with a few effort, it could be done with XmlReader,
3476 // that means removal of DOM use.
3478 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3480 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3484 // Represents header string for documentation comment.
3486 public override string DocCommentHeader {
3487 get { return "M:"; }
3490 protected override void VerifyObsoleteAttribute()
3492 base.VerifyObsoleteAttribute ();
3494 if (parameter_types == null)
3497 foreach (Type type in parameter_types) {
3498 CheckUsageOfObsoleteAttribute (type);
3503 public class SourceMethod : ISourceMethod
3505 TypeContainer container;
3508 protected SourceMethod (TypeContainer container, MethodBase builder,
3509 ISourceFile file, Location start, Location end)
3511 this.container = container;
3512 this.builder = builder;
3514 CodeGen.SymbolWriter.OpenMethod (
3515 file, this, start.Row, 0, end.Row, 0);
3518 public string Name {
3519 get { return builder.Name; }
3522 public int NamespaceID {
3523 get { return container.NamespaceEntry.SymbolFileID; }
3528 if (builder is MethodBuilder)
3529 return ((MethodBuilder) builder).GetToken ().Token;
3530 else if (builder is ConstructorBuilder)
3531 return ((ConstructorBuilder) builder).GetToken ().Token;
3533 throw new NotSupportedException ();
3537 public void CloseMethod ()
3539 if (CodeGen.SymbolWriter != null)
3540 CodeGen.SymbolWriter.CloseMethod ();
3543 public static SourceMethod Create (TypeContainer parent,
3544 MethodBase builder, Block block)
3546 if (CodeGen.SymbolWriter == null)
3551 Location start_loc = block.StartLocation;
3552 if (Location.IsNull (start_loc))
3555 Location end_loc = block.EndLocation;
3556 if (Location.IsNull (end_loc))
3559 ISourceFile file = start_loc.SourceFile;
3563 return new SourceMethod (
3564 parent, builder, file, start_loc, end_loc);
3568 public class Method : MethodCore, IIteratorContainer, IMethodData {
3569 public MethodBuilder MethodBuilder;
3570 public MethodData MethodData;
3571 ReturnParameter return_attributes;
3572 ListDictionary declarative_security;
3575 /// Modifiers allowed in a class declaration
3577 const int AllowedModifiers =
3580 Modifiers.PROTECTED |
3581 Modifiers.INTERNAL |
3586 Modifiers.OVERRIDE |
3587 Modifiers.ABSTRACT |
3589 Modifiers.METHOD_YIELDS |
3592 const int AllowedInterfaceModifiers =
3593 Modifiers.NEW | Modifiers.UNSAFE;
3596 // return_type can be "null" for VOID values.
3598 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3599 MemberName name, Parameters parameters, Attributes attrs,
3601 : base (ds, return_type, mod,
3602 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3603 is_iface, name, attrs, parameters, l)
3607 public override AttributeTargets AttributeTargets {
3609 return AttributeTargets.Method;
3613 public override string GetSignatureForError()
3615 if (MethodBuilder == null) {
3616 return GetSignatureForError (Parent);
3618 return TypeManager.CSharpSignature (MethodBuilder);
3622 /// Use this method when MethodBuilder is null
3624 public override string GetSignatureForError (TypeContainer tc)
3626 // TODO: get params from somewhere
3627 if (parameter_info == null)
3628 return base.GetSignatureForError (tc);
3630 // TODO: move to parameters
3631 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3632 if (parameter_info.Parameters.FixedParameters != null) {
3633 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3634 Parameter p = parameter_info.Parameters.FixedParameters [i];
3635 args.Append (p.GetSignatureForError ());
3637 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3642 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3645 void DuplicateEntryPoint (MethodInfo b, Location location)
3649 "Program `" + CodeGen.FileName +
3650 "' has more than one entry point defined: `" +
3651 TypeManager.CSharpSignature(b) + "'");
3654 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3656 if (b.ReturnType != TypeManager.void_type &&
3657 b.ReturnType != TypeManager.int32_type)
3660 if (pinfo.Count == 0)
3663 if (pinfo.Count > 1)
3666 Type t = pinfo.ParameterType(0);
3668 (t.GetArrayRank() == 1) &&
3669 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3670 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3676 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3678 if (a.Target == AttributeTargets.ReturnValue) {
3679 if (return_attributes == null)
3680 return_attributes = new ReturnParameter (MethodBuilder, Location);
3682 return_attributes.ApplyAttributeBuilder (a, cb);
3686 if (a.Type == TypeManager.methodimpl_attr_type &&
3687 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3688 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3691 if (a.Type == TypeManager.dllimport_type) {
3692 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3693 if ((ModFlags & extern_static) != extern_static) {
3694 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3700 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3701 if (declarative_security == null)
3702 declarative_security = new ListDictionary ();
3703 a.ExtractSecurityPermissionSet (declarative_security);
3707 if (a.Type == TypeManager.conditional_attribute_type) {
3708 if (IsOperator || IsExplicitImpl) {
3709 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3713 if (ReturnType != TypeManager.void_type) {
3714 Report.Error (578, Location, "Conditional not valid on '{0}' because its return type is not void", GetSignatureForError ());
3718 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3719 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3724 Report.Error (582, Location, "Conditional not valid on interface members");
3728 if (MethodData.IsImplementing) {
3729 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3733 for (int i = 0; i < parameter_info.Count; ++i) {
3734 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3735 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3741 MethodBuilder.SetCustomAttribute (cb);
3744 protected override bool CheckForDuplications ()
3746 ArrayList ar = Parent.Methods;
3748 int arLen = ar.Count;
3750 for (int i = 0; i < arLen; i++) {
3751 Method m = (Method) ar [i];
3752 if (IsDuplicateImplementation (m))
3757 ar = Parent.Properties;
3759 for (int i = 0; i < ar.Count; ++i) {
3760 PropertyBase pb = (PropertyBase) ar [i];
3761 if (pb.AreAccessorsDuplicateImplementation (this))
3766 ar = Parent.Indexers;
3768 for (int i = 0; i < ar.Count; ++i) {
3769 PropertyBase pb = (PropertyBase) ar [i];
3770 if (pb.AreAccessorsDuplicateImplementation (this))
3777 for (int i = 0; i < ar.Count; ++i) {
3778 Event ev = (Event) ar [i];
3779 if (ev.AreAccessorsDuplicateImplementation (this))
3790 public override bool Define ()
3795 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3796 Error1599 (Location, ReturnType);
3804 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3806 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3808 if (!MethodData.Define (Parent))
3811 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3812 Name == "Finalize" && !(this is Destructor)) {
3813 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3817 // Setup iterator if we are one
3819 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3820 Iterator iterator = new Iterator (
3821 Parent, Name, MemberType,
3822 ParameterInfo, ModFlags, block, Location);
3824 if (!iterator.DefineIterator ())
3827 block = iterator.Block;
3830 MethodBuilder = MethodData.MethodBuilder;
3833 // This is used to track the Entry Point,
3835 if (Name == "Main" &&
3836 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3837 (RootContext.MainClass == null ||
3838 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3839 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3840 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3841 md.SetMemberIsUsed ();
3843 if (RootContext.EntryPoint == null) {
3844 RootContext.EntryPoint = MethodBuilder;
3845 RootContext.EntryPointLocation = Location;
3847 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3848 DuplicateEntryPoint (MethodBuilder, Location);
3851 if (RootContext.WarningLevel >= 4)
3852 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3856 if (MemberType.IsAbstract && MemberType.IsSealed) {
3857 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3867 public override void Emit ()
3869 MethodData.Emit (Parent, this);
3872 if (declarative_security != null) {
3873 foreach (DictionaryEntry de in declarative_security) {
3874 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3882 public static void Error1599 (Location loc, Type t)
3884 Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
3887 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3889 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3890 container.TypeBuilder, Name, ParameterTypes, false);
3895 base_ret_type = mi.ReturnType;
3899 public override bool MarkForDuplicationCheck ()
3901 caching_flags |= Flags.TestMethodDuplication;
3905 protected override bool VerifyClsCompliance(DeclSpace ds)
3907 if (!base.VerifyClsCompliance (ds))
3910 if (parameter_types.Length > 0) {
3911 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3913 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3920 void IIteratorContainer.SetYields ()
3922 ModFlags |= Modifiers.METHOD_YIELDS;
3925 #region IMethodData Members
3927 public CallingConventions CallingConventions {
3929 CallingConventions cc = Parameters.GetCallingConvention ();
3930 if (Parameters.HasArglist)
3931 block.HasVarargs = true;
3934 if ((ModFlags & Modifiers.STATIC) == 0)
3935 cc |= CallingConventions.HasThis;
3937 // FIXME: How is `ExplicitThis' used in C#?
3943 public Type ReturnType {
3949 public MemberName MethodName {
3955 public new Location Location {
3957 return base.Location;
3961 protected override bool CheckBase() {
3962 if (!base.CheckBase ())
3965 // TODO: Destructor should derive from MethodCore
3966 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3967 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3968 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3975 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3977 return new EmitContext (
3978 tc, Parent, Location, ig, ReturnType, ModFlags, false);
3981 public ObsoleteAttribute GetObsoleteAttribute ()
3983 return GetObsoleteAttribute (Parent);
3987 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3989 public bool IsExcluded (EmitContext ec)
3991 if ((caching_flags & Flags.Excluded_Undetected) == 0)
3992 return (caching_flags & Flags.Excluded) != 0;
3994 caching_flags &= ~Flags.Excluded_Undetected;
3996 if (base_method == null) {
3997 if (OptAttributes == null)
4000 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4005 foreach (Attribute a in attrs) {
4006 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4007 if (RootContext.AllDefines.Contains (condition))
4011 caching_flags |= Flags.Excluded;
4015 IMethodData md = TypeManager.GetMethod (base_method);
4017 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4018 caching_flags |= Flags.Excluded;
4024 if (md.IsExcluded (ec)) {
4025 caching_flags |= Flags.Excluded;
4034 public abstract class ConstructorInitializer {
4035 ArrayList argument_list;
4036 protected ConstructorInfo base_constructor;
4037 Parameters parameters;
4040 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4043 this.argument_list = argument_list;
4044 this.parameters = parameters;
4048 public ArrayList Arguments {
4050 return argument_list;
4054 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4056 Expression base_constructor_group;
4060 ec.CurrentBlock = block;
4062 if (argument_list != null){
4063 foreach (Argument a in argument_list){
4064 if (!a.Resolve (ec, loc))
4068 ec.CurrentBlock = null;
4070 if (this is ConstructorBaseInitializer) {
4071 if (ec.ContainerType.BaseType == null)
4074 t = ec.ContainerType.BaseType;
4075 if (ec.ContainerType.IsValueType) {
4076 Report.Error (522, loc,
4077 "structs cannot call base class constructors");
4081 t = ec.ContainerType;
4083 base_constructor_group = Expression.MemberLookup (
4084 ec, t, ".ctor", MemberTypes.Constructor,
4085 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4088 if (base_constructor_group == null){
4090 base_constructor_group = Expression.MemberLookup (
4091 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4092 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4096 int errors = Report.Errors;
4097 if (base_constructor_group != null)
4098 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4099 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4102 if (base_constructor == null) {
4103 if (errors == Report.Errors)
4104 Report.Error (1501, loc, "Can not find a constructor for this argument list");
4109 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
4110 TypeManager.CSharpSignature (base_constructor));
4111 base_constructor = null;
4115 if (base_constructor == caller_builder){
4116 Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
4123 public void Emit (EmitContext ec)
4125 if (base_constructor != null){
4126 ec.Mark (loc, false);
4128 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4130 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4135 public class ConstructorBaseInitializer : ConstructorInitializer {
4136 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4137 base (argument_list, pars, l)
4142 public class ConstructorThisInitializer : ConstructorInitializer {
4143 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4144 base (argument_list, pars, l)
4149 public class Constructor : MethodCore, IMethodData {
4150 public ConstructorBuilder ConstructorBuilder;
4151 public ConstructorInitializer Initializer;
4152 ListDictionary declarative_security;
4155 // Modifiers allowed for a constructor.
4157 public const int AllowedModifiers =
4159 Modifiers.PROTECTED |
4160 Modifiers.INTERNAL |
4166 bool has_compliant_args = false;
4168 // The spec claims that static is not permitted, but
4169 // my very own code has static constructors.
4171 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4172 ConstructorInitializer init, Location l)
4173 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4179 public override string GetSignatureForError()
4181 if (ConstructorBuilder == null)
4182 return GetSignatureForError (Parent);
4184 return TypeManager.CSharpSignature (ConstructorBuilder);
4187 public bool HasCompliantArgs {
4189 return has_compliant_args;
4193 public override AttributeTargets AttributeTargets {
4195 return AttributeTargets.Constructor;
4201 // Returns true if this is a default constructor
4203 public bool IsDefault ()
4205 if ((ModFlags & Modifiers.STATIC) != 0)
4206 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4207 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4210 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4211 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4212 (Initializer is ConstructorBaseInitializer) &&
4213 (Initializer.Arguments == null);
4216 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4218 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4219 if (declarative_security == null) {
4220 declarative_security = new ListDictionary ();
4222 a.ExtractSecurityPermissionSet (declarative_security);
4226 ConstructorBuilder.SetCustomAttribute (cb);
4229 protected override bool CheckForDuplications ()
4231 ArrayList ar = Parent.InstanceConstructors;
4233 int arLen = ar.Count;
4235 for (int i = 0; i < arLen; i++) {
4236 Constructor m = (Constructor) ar [i];
4237 if (IsDuplicateImplementation (m))
4244 protected override bool CheckBase ()
4246 // Check whether arguments were correct.
4247 if (!DoDefineParameters ())
4250 // TODO: skip the rest for generated ctor
4251 if ((ModFlags & Modifiers.STATIC) != 0)
4254 if (!CheckForDuplications ())
4257 if (Parent.Kind == Kind.Struct) {
4258 if (ParameterTypes.Length == 0) {
4259 Report.Error (568, Location,
4260 "Structs can not contain explicit parameterless " +
4265 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4266 Report.Error (666, Location, "Protected member in struct declaration");
4271 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4272 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4279 // Creates the ConstructorBuilder
4281 public override bool Define ()
4283 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4284 MethodAttributes.SpecialName);
4286 if ((ModFlags & Modifiers.STATIC) != 0) {
4287 ca |= MethodAttributes.Static | MethodAttributes.Private;
4289 ca |= MethodAttributes.HideBySig;
4291 if ((ModFlags & Modifiers.PUBLIC) != 0)
4292 ca |= MethodAttributes.Public;
4293 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4294 if ((ModFlags & Modifiers.INTERNAL) != 0)
4295 ca |= MethodAttributes.FamORAssem;
4297 ca |= MethodAttributes.Family;
4298 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4299 ca |= MethodAttributes.Assembly;
4300 else if (IsDefault ())
4301 ca |= MethodAttributes.Public;
4303 ca |= MethodAttributes.Private;
4306 // Check if arguments were correct.
4310 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4311 ca, CallingConventions,
4314 if ((ModFlags & Modifiers.UNSAFE) != 0)
4315 ConstructorBuilder.InitLocals = false;
4317 TypeManager.AddMethod (ConstructorBuilder, this);
4320 // HACK because System.Reflection.Emit is lame
4322 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4330 public override void Emit ()
4332 EmitContext ec = CreateEmitContext (null, null);
4335 // extern methods have no bodies
4337 if ((ModFlags & Modifiers.EXTERN) != 0) {
4338 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4340 179, Location, "External constructor `" +
4341 TypeManager.CSharpSignature (ConstructorBuilder) +
4342 "' can not have a body");
4345 } else if (block == null) {
4347 501, Location, "Constructor `" +
4348 TypeManager.CSharpSignature (ConstructorBuilder) +
4349 "' must declare a body since it is not marked extern");
4353 // If this is a non-static `struct' constructor and doesn't have any
4354 // initializer, it must initialize all of the struct's fields.
4355 if ((Parent.Kind == Kind.Struct) &&
4356 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4357 Block.AddThisVariable (Parent, Location);
4360 block.ResolveMeta (ec, ParameterInfo);
4362 if ((ModFlags & Modifiers.STATIC) == 0){
4363 if (Parent.Kind == Kind.Class && Initializer == null)
4364 Initializer = new ConstructorBaseInitializer (
4365 null, Parameters.EmptyReadOnlyParameters, Location);
4369 // Spec mandates that Initializers will not have
4373 if ((Initializer != null) &&
4374 !Initializer.Resolve (ConstructorBuilder, block, ec))
4376 ec.IsStatic = false;
4379 Parameters.LabelParameters (ec, ConstructorBuilder);
4381 SourceMethod source = SourceMethod.Create (
4382 Parent, ConstructorBuilder, block);
4385 // Classes can have base initializers and instance field initializers.
4387 if (Parent.Kind == Kind.Class){
4388 if ((ModFlags & Modifiers.STATIC) == 0){
4391 // If we use a "this (...)" constructor initializer, then
4392 // do not emit field initializers, they are initialized in the other constructor
4394 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4395 Parent.EmitFieldInitializers (ec);
4398 if (Initializer != null) {
4399 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4400 ec.TestObsoleteMethodUsage = false;
4402 Initializer.Emit (ec);
4405 if ((ModFlags & Modifiers.STATIC) != 0)
4406 Parent.EmitFieldInitializers (ec);
4408 if (OptAttributes != null)
4409 OptAttributes.Emit (ec, this);
4411 ec.EmitTopBlock (block, ParameterInfo, Location);
4414 source.CloseMethod ();
4418 if (declarative_security != null) {
4419 foreach (DictionaryEntry de in declarative_security) {
4420 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4427 // Is never override
4428 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4433 protected override bool VerifyClsCompliance (DeclSpace ds)
4435 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4439 if (parameter_types.Length > 0) {
4440 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4442 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4444 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4445 foreach (Type param in parameter_types) {
4446 if (param.IsArray) {
4452 has_compliant_args = true;
4456 #region IMethodData Members
4458 public System.Reflection.CallingConventions CallingConventions {
4460 CallingConventions cc = Parameters.GetCallingConvention ();
4462 if (Parent.Kind == Kind.Class)
4463 if ((ModFlags & Modifiers.STATIC) == 0)
4464 cc |= CallingConventions.HasThis;
4466 // FIXME: How is `ExplicitThis' used in C#?
4472 public new Location Location {
4474 return base.Location;
4478 public MemberName MethodName {
4484 public Type ReturnType {
4490 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4492 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4493 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4496 public ObsoleteAttribute GetObsoleteAttribute ()
4498 return GetObsoleteAttribute (Parent);
4501 public bool IsExcluded(EmitContext ec)
4510 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4512 public interface IMethodData
4514 CallingConventions CallingConventions { get; }
4515 Location Location { get; }
4516 MemberName MethodName { get; }
4517 Type[] ParameterTypes { get; }
4518 Type ReturnType { get; }
4520 Attributes OptAttributes { get; }
4521 ToplevelBlock Block { get; }
4523 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4524 ObsoleteAttribute GetObsoleteAttribute ();
4525 string GetSignatureForError (TypeContainer tc);
4526 bool IsExcluded (EmitContext ec);
4527 bool IsClsCompliaceRequired (DeclSpace ds);
4528 void SetMemberIsUsed ();
4532 // Encapsulates most of the Method's state
4534 public class MethodData {
4536 readonly IMethodData method;
4539 // The return type of this method
4541 public readonly InternalParameters ParameterInfo;
4544 // Are we implementing an interface ?
4546 public bool IsImplementing = false;
4551 protected MemberBase member;
4552 protected int modifiers;
4553 protected MethodAttributes flags;
4555 MethodBuilder builder = null;
4556 public MethodBuilder MethodBuilder {
4562 public MethodData (MemberBase member, InternalParameters parameters,
4563 int modifiers, MethodAttributes flags, IMethodData method)
4565 this.member = member;
4566 this.ParameterInfo = parameters;
4567 this.modifiers = modifiers;
4570 this.method = method;
4573 public bool Define (TypeContainer container)
4575 MethodInfo implementing = null;
4577 string name = method.MethodName.Name;
4578 string method_name = name;
4580 Type[] ParameterTypes = method.ParameterTypes;
4582 if (container.Pending != null){
4583 if (member is Indexer) // TODO: test it, but it should work without this IF
4584 implementing = container.Pending.IsInterfaceIndexer (
4585 member.InterfaceType, method.ReturnType, ParameterInfo);
4587 implementing = container.Pending.IsInterfaceMethod (
4588 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4590 if (member.InterfaceType != null){
4591 if (implementing == null){
4592 if (member is PropertyBase) {
4593 Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
4594 method.GetSignatureForError (container), member.Name);
4597 Report.Error (539, method.Location,
4598 "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
4602 if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
4603 Report.SymbolRelatedToPreviousError (implementing);
4604 Report.Error (683, method.Location, "'{0}' explicit method implementation cannot implement '{1}' because it is an accessor",
4605 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4608 method_name = member.InterfaceType.FullName + "." + name;
4610 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
4611 Report.SymbolRelatedToPreviousError (implementing);
4612 Report.Error (686, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
4613 method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4620 // For implicit implementations, make sure we are public, for
4621 // explicit implementations, make sure we are private.
4623 if (implementing != null){
4625 // Setting null inside this block will trigger a more
4626 // verbose error reporting for missing interface implementations
4628 // The "candidate" function has been flagged already
4629 // but it wont get cleared
4631 if (member.IsExplicitImpl){
4632 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4633 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4634 implementing = null;
4636 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4637 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4639 // If this is an interface method implementation,
4640 // check for public accessibility
4642 implementing = null;
4643 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4644 // We may never be private.
4645 implementing = null;
4646 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4648 // We may be protected if we're overriding something.
4650 implementing = null;
4655 // Static is not allowed
4657 if ((modifiers & Modifiers.STATIC) != 0){
4658 implementing = null;
4659 Modifiers.Error_InvalidModifier (method.Location, "static");
4664 // If implementing is still valid, set flags
4666 if (implementing != null){
4668 // When implementing interface methods, set NewSlot
4669 // unless, we are overwriting a method.
4671 if (implementing.DeclaringType.IsInterface){
4672 if ((modifiers & Modifiers.OVERRIDE) == 0)
4673 flags |= MethodAttributes.NewSlot;
4676 MethodAttributes.Virtual |
4677 MethodAttributes.HideBySig;
4679 // Set Final unless we're virtual, abstract or already overriding a method.
4680 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4681 flags |= MethodAttributes.Final;
4683 IsImplementing = true;
4686 EmitContext ec = method.CreateEmitContext (container, null);
4688 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4690 if (builder == null)
4693 if ((modifiers & Modifiers.UNSAFE) != 0)
4694 builder.InitLocals = false;
4696 if (IsImplementing){
4698 // clear the pending implemntation flag
4700 if (member is Indexer) {
4701 container.Pending.ImplementIndexer (
4702 member.InterfaceType, builder, method.ReturnType,
4703 ParameterInfo, member.IsExplicitImpl);
4705 container.Pending.ImplementMethod (
4706 member.InterfaceType, name, method.ReturnType,
4707 ParameterInfo, member.IsExplicitImpl);
4709 if (member.IsExplicitImpl)
4710 container.TypeBuilder.DefineMethodOverride (
4711 builder, implementing);
4715 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4716 TypeManager.AddMethod (builder, method);
4723 /// Create the MethodBuilder for the method
4725 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4727 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4729 if ((modifiers & extern_static) == extern_static) {
4731 if (method.OptAttributes != null) {
4732 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4733 if (dllimport_attribute != null) {
4734 flags |= MethodAttributes.PinvokeImpl;
4735 builder = dllimport_attribute.DefinePInvokeMethod (
4736 ec, container.TypeBuilder, method_name, flags,
4737 method.ReturnType, ParameterTypes);
4743 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4744 // We are more strict than Microsoft and report CS0626 like error
4745 if (method.OptAttributes == null ||
4746 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4747 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));
4752 builder = container.TypeBuilder.DefineMethod (
4753 method_name, flags, method.CallingConventions,
4754 method.ReturnType, ParameterTypes);
4760 public void Emit (TypeContainer container, Attributable kind)
4763 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4764 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4766 ec = method.CreateEmitContext (container, null);
4768 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
4769 ec.TestObsoleteMethodUsage = false;
4771 Location loc = method.Location;
4772 Attributes OptAttributes = method.OptAttributes;
4774 if (OptAttributes != null)
4775 OptAttributes.Emit (ec, kind);
4777 if (member is MethodCore)
4778 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
4780 ToplevelBlock block = method.Block;
4783 // abstract or extern methods have no bodies
4785 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4790 // abstract or extern methods have no bodies.
4792 if ((modifiers & Modifiers.ABSTRACT) != 0)
4794 500, method.Location, "Abstract method `" +
4795 TypeManager.CSharpSignature (builder) +
4796 "' can not have a body");
4798 if ((modifiers & Modifiers.EXTERN) != 0)
4800 179, method.Location, "External method `" +
4801 TypeManager.CSharpSignature (builder) +
4802 "' can not have a body");
4808 // Methods must have a body unless they're extern or abstract
4810 if (block == null) {
4812 501, method.Location, "Method `" +
4813 TypeManager.CSharpSignature (builder) +
4814 "' must declare a body since it is not marked " +
4815 "abstract or extern");
4819 SourceMethod source = SourceMethod.Create (
4820 container, MethodBuilder, method.Block);
4823 // Handle destructors specially
4825 // FIXME: This code generates buggy code
4827 if (member is Destructor)
4828 EmitDestructor (ec, block);
4830 ec.EmitTopBlock (block, ParameterInfo, loc);
4833 source.CloseMethod ();
4836 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4838 ILGenerator ig = ec.ig;
4840 Label finish = ig.DefineLabel ();
4842 block.SetDestructor ();
4844 ig.BeginExceptionBlock ();
4845 ec.ReturnLabel = finish;
4846 ec.HasReturnLabel = true;
4847 ec.EmitTopBlock (block, null, method.Location);
4849 // ig.MarkLabel (finish);
4850 ig.BeginFinallyBlock ();
4852 if (ec.ContainerType.BaseType != null) {
4853 Expression member_lookup = Expression.MemberLookup (
4854 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4855 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4857 if (member_lookup != null){
4858 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4860 ig.Emit (OpCodes.Ldarg_0);
4861 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4865 ig.EndExceptionBlock ();
4866 //ig.MarkLabel (ec.ReturnLabel);
4867 ig.Emit (OpCodes.Ret);
4871 // Should derive from MethodCore
4872 public class Destructor : Method {
4874 public Destructor (TypeContainer ds, Expression return_type, int mod,
4875 string name, Parameters parameters, Attributes attrs,
4877 : base (ds, return_type, mod, false, new MemberName (name),
4878 parameters, attrs, l)
4881 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4883 if (a.Type == TypeManager.conditional_attribute_type) {
4884 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4888 base.ApplyAttributeBuilder (a, cb);
4892 abstract public class MemberBase : MemberCore {
4893 public Expression Type;
4895 public MethodAttributes flags;
4897 protected readonly int explicit_mod_flags;
4900 // The "short" name of this property / indexer / event. This is the
4901 // name without the explicit interface.
4903 public string ShortName {
4904 get { return MemberName.Name; }
4906 SetMemberName (new MemberName (MemberName.Left, value));
4911 // The type of this property / indexer / event
4914 public Type MemberType {
4916 if (member_type == null && Type != null) {
4917 EmitContext ec = Parent.EmitContext;
4918 bool old_unsafe = ec.InUnsafe;
4919 ec.InUnsafe = InUnsafe;
4920 Type = Type.ResolveAsTypeTerminal (ec, false);
4921 ec.InUnsafe = old_unsafe;
4923 member_type = Type == null ? null : Type.Type;
4930 // Whether this is an interface member.
4932 public bool IsInterface;
4935 // If true, this is an explicit interface implementation
4937 public bool IsExplicitImpl;
4940 // The interface type we are explicitly implementing
4942 public Type InterfaceType = null;
4945 // The constructor is only exposed to our children
4947 protected MemberBase (TypeContainer parent, Expression type, int mod,
4948 int allowed_mod, int def_mod, MemberName name,
4949 Attributes attrs, Location loc)
4950 : base (parent, name, attrs, loc)
4952 explicit_mod_flags = mod;
4954 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4955 IsExplicitImpl = (MemberName.Left != null);
4958 protected virtual bool CheckBase ()
4960 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4961 Report.Error (666, Location, "Protected member in struct declaration");
4965 if ((RootContext.WarningLevel >= 4) &&
4966 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4967 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4968 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4969 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4974 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4978 foreach (Type partype in parameters){
4979 if (partype == TypeManager.void_type) {
4981 1547, Location, "Keyword 'void' cannot " +
4982 "be used in this context");
4986 if (partype.IsPointer){
4989 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
4993 if (ds.AsAccessible (partype, ModFlags))
4996 if (this is Indexer)
4997 Report.Error (55, Location,
4998 "Inconsistent accessibility: parameter type `" +
4999 TypeManager.CSharpName (partype) + "' is less " +
5000 "accessible than indexer `" + Name + "'");
5001 else if ((this is Method) && ((Method) this).IsOperator)
5002 Report.Error (57, Location,
5003 "Inconsistent accessibility: parameter type `" +
5004 TypeManager.CSharpName (partype) + "' is less " +
5005 "accessible than operator `" + Name + "'");
5007 Report.Error (51, Location,
5008 "Inconsistent accessibility: parameter type `" +
5009 TypeManager.CSharpName (partype) + "' is less " +
5010 "accessible than method `" + Name + "'");
5017 protected virtual bool DoDefine ()
5019 EmitContext ec = Parent.EmitContext;
5021 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5024 throw new InternalErrorException ();
5027 ModFlags = Modifiers.PUBLIC |
5028 Modifiers.ABSTRACT |
5029 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5031 flags = MethodAttributes.Public |
5032 MethodAttributes.Abstract |
5033 MethodAttributes.HideBySig |
5034 MethodAttributes.NewSlot |
5035 MethodAttributes.Virtual;
5037 if (!Parent.MethodModifiersValid (this))
5040 flags = Modifiers.MethodAttr (ModFlags);
5043 if (MemberType == null)
5046 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5047 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5048 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5053 // verify accessibility
5054 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5055 Report.SymbolRelatedToPreviousError (MemberType);
5056 if (this is Property)
5057 Report.Error (53, Location,
5058 "Inconsistent accessibility: property type `" +
5059 TypeManager.CSharpName (MemberType) + "' is less " +
5060 "accessible than property `" + GetSignatureForError () + "'");
5061 else if (this is Indexer)
5062 Report.Error (54, Location,
5063 "Inconsistent accessibility: indexer return type `" +
5064 TypeManager.CSharpName (MemberType) + "' is less " +
5065 "accessible than indexer `" + Name + "'");
5066 else if (this is MethodCore) {
5067 if (this is Operator)
5068 Report.Error (56, Location,
5069 "Inconsistent accessibility: return type `" +
5070 TypeManager.CSharpName (MemberType) + "' is less " +
5071 "accessible than operator `" + Name + "'");
5073 Report.Error (50, Location,
5074 "Inconsistent accessibility: return type `" +
5075 TypeManager.CSharpName (MemberType) + "' is less " +
5076 "accessible than method `" + Name + "'");
5078 Report.Error (52, Location,
5079 "Inconsistent accessibility: field type `" +
5080 TypeManager.CSharpName (MemberType) + "' is less " +
5081 "accessible than field `" + Name + "'");
5086 if (MemberType.IsPointer && !UnsafeOK (Parent))
5089 if (IsExplicitImpl) {
5090 Expression expr = MemberName.Left.GetTypeExpression (Location);
5091 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5095 InterfaceType = texpr.ResolveType (ec);
5097 if (!InterfaceType.IsInterface) {
5098 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5102 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5105 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5111 public override string GetSignatureForError (TypeContainer tc)
5113 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5116 protected bool IsTypePermitted ()
5118 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5119 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5125 protected override bool VerifyClsCompliance(DeclSpace ds)
5127 if (base.VerifyClsCompliance (ds)) {
5131 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5132 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5137 protected override void VerifyObsoleteAttribute()
5139 CheckUsageOfObsoleteAttribute (MemberType);
5144 // Fields and Events both generate FieldBuilders, we use this to share
5145 // their common bits. This is also used to flag usage of the field
5147 abstract public class FieldBase : MemberBase {
5148 public FieldBuilder FieldBuilder;
5149 public Status status;
5152 public enum Status : byte {
5154 HAS_OFFSET = 4 // Used by FieldMember.
5157 static string[] attribute_targets = new string [] { "field" };
5160 /// Symbol with same name in base class/struct
5162 public MemberInfo conflict_symbol;
5165 // The constructor is only exposed to our children
5167 protected FieldBase (TypeContainer parent, Expression type, int mod,
5168 int allowed_mod, MemberName name, object init,
5169 Attributes attrs, Location loc)
5170 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5176 public override AttributeTargets AttributeTargets {
5178 return AttributeTargets.Field;
5182 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5184 if (a.Type == TypeManager.marshal_as_attr_type) {
5185 UnmanagedMarshal marshal = a.GetMarshal (this);
5186 if (marshal != null) {
5187 FieldBuilder.SetMarshal (marshal);
5192 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5193 a.Error_InvalidSecurityParent ();
5197 FieldBuilder.SetCustomAttribute (cb);
5201 // Whether this field has an initializer.
5203 public bool HasInitializer {
5205 return init != null;
5209 protected readonly Object init;
5212 Expression init_expr;
5213 bool init_expr_initialized = false;
5216 // Resolves and returns the field initializer.
5218 public Expression GetInitializerExpression (EmitContext ec)
5220 if (init_expr_initialized)
5224 if (init is Expression)
5225 e = (Expression) init;
5227 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5229 EmitContext parent_ec = Parent.EmitContext;
5231 bool old_is_static = parent_ec.IsStatic;
5232 parent_ec.IsStatic = ec.IsStatic;
5233 parent_ec.IsFieldInitializer = true;
5234 e = e.DoResolve (parent_ec);
5235 parent_ec.IsFieldInitializer = false;
5236 parent_ec.IsStatic = old_is_static;
5239 init_expr_initialized = true;
5244 protected override bool CheckBase ()
5246 if (!base.CheckBase ())
5253 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5254 if (conflict_symbol == null) {
5255 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5256 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5261 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5262 Report.SymbolRelatedToPreviousError (conflict_symbol);
5263 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5269 public override string GetSignatureForError ()
5271 if (FieldBuilder == null) {
5272 return base.GetSignatureForError (Parent);
5274 return TypeManager.GetFullNameSignature (FieldBuilder);
5277 protected virtual bool IsFieldClsCompliant {
5279 if (FieldBuilder == null)
5282 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5286 public override string[] ValidAttributeTargets {
5288 return attribute_targets;
5292 protected override bool VerifyClsCompliance (DeclSpace ds)
5294 if (!base.VerifyClsCompliance (ds))
5297 if (!IsFieldClsCompliant) {
5298 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5304 public void SetAssigned ()
5306 status |= Status.ASSIGNED;
5310 public abstract class FieldMember: FieldBase
5312 protected FieldMember (TypeContainer parent, Expression type, int mod,
5313 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5314 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5316 if ((mod & Modifiers.ABSTRACT) != 0)
5317 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5320 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5322 if (a.Type == TypeManager.field_offset_attribute_type)
5324 status |= Status.HAS_OFFSET;
5326 if (!Parent.HasExplicitLayout) {
5327 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5331 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5332 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5338 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5339 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5344 base.ApplyAttributeBuilder (a, cb);
5348 public override bool Define()
5350 EmitContext ec = Parent.EmitContext;
5352 throw new InternalErrorException ("FieldMember.Define called too early");
5354 if (MemberType == null)
5357 if (MemberType == TypeManager.void_type) {
5358 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5365 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5366 Report.Error (52, Location,
5367 "Inconsistent accessibility: field type `" +
5368 TypeManager.CSharpName (MemberType) + "' is less " +
5369 "accessible than field `" + Name + "'");
5373 if (!IsTypePermitted ())
5376 if (MemberType.IsPointer && !UnsafeOK (Parent))
5382 public override void Emit ()
5384 if (OptAttributes != null) {
5385 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5386 OptAttributes.Emit (ec, this);
5389 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5390 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5397 // Represents header string for documentation comment.
5399 public override string DocCommentHeader {
5400 get { return "F:"; }
5404 interface IFixedBuffer
5406 FieldInfo Element { get; }
5407 Type ElementType { get; }
5410 public class FixedFieldExternal: IFixedBuffer
5412 FieldInfo element_field;
5414 public FixedFieldExternal (FieldInfo fi)
5416 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5419 #region IFixedField Members
5421 public FieldInfo Element {
5423 return element_field;
5427 public Type ElementType {
5429 return element_field.FieldType;
5437 /// Fixed buffer implementation
5439 public class FixedField: FieldMember, IFixedBuffer
5441 public const string FixedElementName = "FixedElementField";
5442 static int GlobalCounter = 0;
5443 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5444 static FieldInfo[] fi;
5446 TypeBuilder fixed_buffer_type;
5447 FieldBuilder element;
5448 Expression size_expr;
5451 const int AllowedModifiers =
5454 Modifiers.PROTECTED |
5455 Modifiers.INTERNAL |
5458 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5459 Expression size_expr, Attributes attrs, Location loc):
5460 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5462 if (RootContext.Version == LanguageVersion.ISO_1)
5463 Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
5465 this.size_expr = size_expr;
5468 public override bool Define()
5471 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5472 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5475 if (Parent.Kind != Kind.Struct) {
5476 Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
5480 if (!base.Define ())
5483 if (!TypeManager.IsPrimitiveType (MemberType)) {
5484 Report.Error (1663, Location, "Fixed sized buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double");
5488 Expression e = size_expr.Resolve (Parent.EmitContext);
5492 Constant c = e as Constant;
5494 Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
5498 IntConstant buffer_size_const = c.ToInt (Location);
5499 if (buffer_size_const == null)
5502 buffer_size = buffer_size_const.Value;
5504 if (buffer_size <= 0) {
5505 Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
5509 int type_size = Expression.GetTypeSize (MemberType);
5511 if (buffer_size > int.MaxValue / type_size) {
5512 Report.Error (1664, Location, "Fixed sized buffer of length '{0}' and type '{1}' exceeded 2^31 limit",
5513 buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5517 buffer_size *= type_size;
5520 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5522 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5523 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5524 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5525 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5527 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5528 TypeManager.RegisterFieldBase (FieldBuilder, this);
5533 public override void Emit()
5536 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5538 object[] fi_val = new object[1];
5539 fi_val [0] = buffer_size;
5541 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5542 ctor_args, fi, fi_val);
5543 fixed_buffer_type.SetCustomAttribute (cab);
5546 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5547 FieldBuilder.SetCustomAttribute (cab);
5552 protected override bool IsFieldClsCompliant {
5558 #region IFixedField Members
5560 public FieldInfo Element {
5566 public Type ElementType {
5576 // The Field class is used to represents class/struct fields during parsing.
5578 public class Field : FieldMember {
5580 // Modifiers allowed in a class declaration
5582 const int AllowedModifiers =
5585 Modifiers.PROTECTED |
5586 Modifiers.INTERNAL |
5589 Modifiers.VOLATILE |
5593 public Field (TypeContainer parent, Expression type, int mod, string name,
5594 Object expr_or_array_init, Attributes attrs, Location loc)
5595 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5596 expr_or_array_init, attrs, loc)
5600 public override bool Define ()
5602 if (!base.Define ())
5605 if (RootContext.WarningLevel > 1){
5606 Type ptype = Parent.TypeBuilder.BaseType;
5608 // ptype is only null for System.Object while compiling corlib.
5610 TypeContainer.FindMembers (
5611 ptype, MemberTypes.Method,
5612 BindingFlags.Public |
5613 BindingFlags.Static | BindingFlags.Instance,
5614 System.Type.FilterName, Name);
5618 if ((ModFlags & Modifiers.VOLATILE) != 0){
5619 if (!MemberType.IsClass){
5620 Type vt = MemberType;
5622 if (TypeManager.IsEnumType (vt))
5623 vt = TypeManager.EnumToUnderlying (MemberType);
5625 if (!((vt == TypeManager.bool_type) ||
5626 (vt == TypeManager.sbyte_type) ||
5627 (vt == TypeManager.byte_type) ||
5628 (vt == TypeManager.short_type) ||
5629 (vt == TypeManager.ushort_type) ||
5630 (vt == TypeManager.int32_type) ||
5631 (vt == TypeManager.uint32_type) ||
5632 (vt == TypeManager.char_type) ||
5633 (vt == TypeManager.float_type) ||
5634 (!vt.IsValueType))){
5636 677, Location, Parent.MakeName (Name) +
5637 " A volatile field can not be of type `" +
5638 TypeManager.CSharpName (vt) + "'");
5643 if ((ModFlags & Modifiers.READONLY) != 0){
5646 "A field can not be both volatile and readonly");
5651 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5653 if (Parent.Kind == Kind.Struct &&
5654 ((fa & FieldAttributes.Static) == 0) &&
5655 MemberType == Parent.TypeBuilder &&
5656 !TypeManager.IsBuiltinType (MemberType)){
5657 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5658 "' causes a cycle in the structure layout");
5663 FieldBuilder = Parent.TypeBuilder.DefineField (
5664 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5666 TypeManager.RegisterFieldBase (FieldBuilder, this);
5668 catch (ArgumentException) {
5669 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5676 protected override bool VerifyClsCompliance (DeclSpace ds)
5678 if (!base.VerifyClsCompliance (ds))
5681 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5682 Report.Warning (3026, 1, Location, "CLS-compliant field '{0}' cannot be volatile", GetSignatureForError ());
5690 // `set' and `get' accessors are represented with an Accessor.
5692 public class Accessor {
5694 // Null if the accessor is empty, or a Block if not
5696 public const int AllowedModifiers =
5698 Modifiers.PROTECTED |
5699 Modifiers.INTERNAL |
5702 public ToplevelBlock Block;
5703 public Attributes Attributes;
5704 public Location Location;
5705 public int ModFlags;
5707 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5712 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5717 // Ooouh Martin, templates are missing here.
5718 // When it will be possible move here a lot of child code and template method type.
5719 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5720 protected MethodData method_data;
5721 protected ToplevelBlock block;
5722 protected ListDictionary declarative_security;
5724 // The accessor are created event if they are not wanted.
5725 // But we need them because their names are reserved.
5726 // Field says whether accessor will be emited or not
5727 public readonly bool IsDummy;
5729 protected readonly string prefix;
5731 ReturnParameter return_attributes;
5733 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5734 : base (null, SetupName (prefix, member), null, member.Location)
5736 this.prefix = prefix;
5740 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5742 : base (null, SetupName (prefix, member),
5743 accessor.Attributes, accessor.Location)
5745 this.prefix = prefix;
5746 this.block = accessor.Block;
5749 static MemberName SetupName (string prefix, MemberBase member)
5751 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
5754 public void UpdateName (MemberBase member)
5756 SetMemberName (SetupName (prefix, member));
5759 #region IMethodData Members
5761 public ToplevelBlock Block {
5771 public CallingConventions CallingConventions {
5773 return CallingConventions.Standard;
5777 public bool IsExcluded (EmitContext ec)
5782 public MemberName MethodName {
5788 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5789 public abstract Type[] ParameterTypes { get; }
5790 public abstract Type ReturnType { get; }
5791 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5795 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5797 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5798 a.Type == TypeManager.conditional_attribute_type) {
5799 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 ());
5803 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5804 if (declarative_security == null)
5805 declarative_security = new ListDictionary ();
5806 a.ExtractSecurityPermissionSet (declarative_security);
5810 if (a.Target == AttributeTargets.Method) {
5811 method_data.MethodBuilder.SetCustomAttribute (cb);
5815 if (a.Target == AttributeTargets.ReturnValue) {
5816 if (return_attributes == null)
5817 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5819 return_attributes.ApplyAttributeBuilder (a, cb);
5823 ApplyToExtraTarget (a, cb);
5826 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5828 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5831 public override bool Define()
5833 throw new NotSupportedException ();
5836 public virtual void Emit (TypeContainer container)
5838 EmitMethod (container);
5840 if (declarative_security != null) {
5841 foreach (DictionaryEntry de in declarative_security) {
5842 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5849 protected virtual void EmitMethod (TypeContainer container)
5851 method_data.Emit (container, this);
5854 public override bool IsClsCompliaceRequired(DeclSpace ds)
5859 public bool IsDuplicateImplementation (MethodCore method)
5861 if (Name != method.Name)
5864 Type[] param_types = method.ParameterTypes;
5866 if (param_types.Length != ParameterTypes.Length)
5869 for (int i = 0; i < param_types.Length; i++)
5870 if (param_types [i] != ParameterTypes [i])
5873 Report.SymbolRelatedToPreviousError (method);
5874 Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
5878 public override bool IsUsed
5888 public new Location Location {
5890 return base.Location;
5895 // Represents header string for documentation comment.
5897 public override string DocCommentHeader {
5898 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5901 protected override void VerifyObsoleteAttribute()
5908 // Properties and Indexers both generate PropertyBuilders, we use this to share
5909 // their common bits.
5911 abstract public class PropertyBase : MethodCore {
5913 public class GetMethod: PropertyMethod
5915 static string[] attribute_targets = new string [] { "method", "return" };
5917 public GetMethod (MethodCore method):
5918 base (method, "get_")
5922 public GetMethod (MethodCore method, Accessor accessor):
5923 base (method, accessor, "get_")
5927 public override MethodBuilder Define(TypeContainer container)
5929 base.Define (container);
5931 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5933 if (!method_data.Define (container))
5936 return method_data.MethodBuilder;
5939 public override string GetSignatureForError (TypeContainer tc)
5941 return String.Concat (base.GetSignatureForError (tc), ".get");
5944 public override Type ReturnType {
5946 return method.MemberType;
5950 public override string[] ValidAttributeTargets {
5952 return attribute_targets;
5957 public class SetMethod: PropertyMethod {
5959 static string[] attribute_targets = new string [] { "method", "param", "return" };
5960 ImplicitParameter param_attr;
5962 public SetMethod (MethodCore method):
5963 base (method, "set_")
5967 public SetMethod (MethodCore method, Accessor accessor):
5968 base (method, accessor, "set_")
5972 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5974 if (a.Target == AttributeTargets.Parameter) {
5975 if (param_attr == null)
5976 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
5978 param_attr.ApplyAttributeBuilder (a, cb);
5982 base.ApplyAttributeBuilder (a, cb);
5985 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
5987 Parameter [] parms = new Parameter [1];
5988 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
5989 Parameters parameters = new Parameters (parms, null);
5991 bool old_unsafe = ec.InUnsafe;
5992 ec.InUnsafe = InUnsafe;
5993 Type [] types = parameters.GetParameterInfo (ec);
5994 ec.InUnsafe = old_unsafe;
5996 return new InternalParameters (types, parameters);
5999 public override MethodBuilder Define (TypeContainer container)
6001 if (container.EmitContext == null)
6002 throw new InternalErrorException ("SetMethod.Define called too early");
6004 base.Define (container);
6006 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6008 if (!method_data.Define (container))
6011 return method_data.MethodBuilder;
6014 public override string GetSignatureForError (TypeContainer tc)
6016 return String.Concat (base.GetSignatureForError (tc), ".set");
6019 public override Type[] ParameterTypes {
6021 return new Type[] { method.MemberType };
6025 public override Type ReturnType {
6027 return TypeManager.void_type;
6031 public override string[] ValidAttributeTargets {
6033 return attribute_targets;
6038 static string[] attribute_targets = new string [] { "property" };
6040 public abstract class PropertyMethod: AbstractPropertyEventMethod
6042 protected readonly MethodCore method;
6043 protected MethodAttributes flags;
6045 public PropertyMethod (MethodCore method, string prefix)
6046 : base (method, prefix)
6048 this.method = method;
6049 Parent = method.Parent;
6052 public PropertyMethod (MethodCore method, Accessor accessor,
6054 : base (method, accessor, prefix)
6056 this.method = method;
6057 Parent = method.Parent;
6058 this.ModFlags = accessor.ModFlags;
6060 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6061 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
6065 public override AttributeTargets AttributeTargets {
6067 return AttributeTargets.Method;
6071 public override bool IsClsCompliaceRequired(DeclSpace ds)
6073 return method.IsClsCompliaceRequired (ds);
6076 public InternalParameters ParameterInfo
6079 return method_data.ParameterInfo;
6083 public virtual MethodBuilder Define (TypeContainer container)
6086 // Check for custom access modifier
6088 if (ModFlags == 0) {
6089 ModFlags = method.ModFlags;
6090 flags = method.flags;
6092 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6093 Report.Error (442, Location, "{0}': abstract properties cannot have private accessors", GetSignatureForError (container));
6096 CheckModifiers (container, ModFlags);
6097 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6098 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6099 flags = Modifiers.MethodAttr (ModFlags);
6100 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6107 public bool HasCustomAccessModifier
6110 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6114 public override Type[] ParameterTypes {
6116 return TypeManager.NoTypes;
6120 public override EmitContext CreateEmitContext (TypeContainer tc,
6123 return new EmitContext (
6124 tc, method.Parent, method.Location, ig, ReturnType,
6125 method.ModFlags, false);
6128 public override ObsoleteAttribute GetObsoleteAttribute ()
6130 return method.GetObsoleteAttribute (method.Parent);
6133 public override string GetSignatureForError (TypeContainer tc)
6135 return String.Concat (tc.Name, '.', method.Name);
6138 void CheckModifiers (TypeContainer container, int modflags)
6141 int mflags = method.ModFlags & Modifiers.Accessibility;
6143 if ((mflags & Modifiers.PUBLIC) != 0) {
6144 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6146 else if ((mflags & Modifiers.PROTECTED) != 0) {
6147 if ((mflags & Modifiers.INTERNAL) != 0)
6148 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6150 flags |= Modifiers.PRIVATE;
6152 else if ((mflags & Modifiers.INTERNAL) != 0)
6153 flags |= Modifiers.PRIVATE;
6155 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6156 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6157 GetSignatureForError (container));
6160 public override bool MarkForDuplicationCheck ()
6162 caching_flags |= Flags.TestMethodDuplication;
6168 public PropertyMethod Get, Set;
6169 public PropertyBuilder PropertyBuilder;
6170 public MethodBuilder GetBuilder, SetBuilder;
6172 protected EmitContext ec;
6174 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6175 int allowed_mod, bool is_iface, MemberName name,
6176 Parameters parameters, Attributes attrs,
6178 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6179 attrs, parameters, loc)
6183 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6185 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6186 a.Error_InvalidSecurityParent ();
6190 PropertyBuilder.SetCustomAttribute (cb);
6193 public override AttributeTargets AttributeTargets {
6195 return AttributeTargets.Property;
6199 public override bool Define ()
6204 if (!IsTypePermitted ())
6210 protected override bool DoDefine ()
6212 if (!base.DoDefine ())
6216 // Accessors modifiers check
6218 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6219 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6220 GetSignatureForError ());
6224 if ((Get.IsDummy || Set.IsDummy)
6225 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6226 Report.Error (276, Location,
6227 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6228 GetSignatureForError ());
6232 if (MemberType.IsAbstract && MemberType.IsSealed) {
6233 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6237 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6241 public override string GetSignatureForError()
6243 if (PropertyBuilder == null)
6244 return GetSignatureForError (Parent);
6246 return TypeManager.CSharpSignature (PropertyBuilder, false);
6249 protected override bool CheckForDuplications ()
6251 ArrayList ar = Parent.Indexers;
6253 int arLen = ar.Count;
6255 for (int i = 0; i < arLen; i++) {
6256 Indexer m = (Indexer) ar [i];
6257 if (IsDuplicateImplementation (m))
6262 ar = Parent.Properties;
6264 int arLen = ar.Count;
6266 for (int i = 0; i < arLen; i++) {
6267 Property m = (Property) ar [i];
6268 if (IsDuplicateImplementation (m))
6276 // TODO: rename to Resolve......
6277 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6279 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6280 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6282 if (base_property == null)
6285 base_ret_type = base_property.PropertyType;
6286 MethodInfo get_accessor = base_property.GetGetMethod (true);
6287 MethodInfo set_accessor = base_property.GetSetMethod (true);
6288 MethodAttributes get_accessor_access, set_accessor_access;
6290 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6291 if (Get != null && !Get.IsDummy && get_accessor == null) {
6292 Report.SymbolRelatedToPreviousError (base_property);
6293 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6296 if (Set != null && !Set.IsDummy && set_accessor == null) {
6297 Report.SymbolRelatedToPreviousError (base_property);
6298 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6303 // Check base class accessors access
6305 get_accessor_access = set_accessor_access = 0;
6306 if ((ModFlags & Modifiers.NEW) == 0) {
6307 if (get_accessor != null) {
6308 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6309 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6311 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6312 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6313 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6316 if (set_accessor != null) {
6317 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6318 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6320 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6321 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6322 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6327 // Get the less restrictive access
6329 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6332 public override void Emit ()
6335 // The PropertyBuilder can be null for explicit implementations, in that
6336 // case, we do not actually emit the ".property", so there is nowhere to
6337 // put the attribute
6339 if (PropertyBuilder != null && OptAttributes != null)
6340 OptAttributes.Emit (ec, this);
6352 /// Tests whether accessors are not in collision with some method (CS0111)
6354 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6356 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6359 public override bool IsUsed
6365 return Get.IsUsed | Set.IsUsed;
6369 protected override void SetMemberName (MemberName new_name)
6371 base.SetMemberName (new_name);
6373 Get.UpdateName (this);
6374 Set.UpdateName (this);
6377 public override string[] ValidAttributeTargets {
6379 return attribute_targets;
6384 // Represents header string for documentation comment.
6386 public override string DocCommentHeader {
6387 get { return "P:"; }
6391 public class Property : PropertyBase, IIteratorContainer {
6392 const int AllowedModifiers =
6395 Modifiers.PROTECTED |
6396 Modifiers.INTERNAL |
6400 Modifiers.OVERRIDE |
6401 Modifiers.ABSTRACT |
6404 Modifiers.METHOD_YIELDS |
6407 const int AllowedInterfaceModifiers =
6410 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6411 MemberName name, Attributes attrs, Accessor get_block,
6412 Accessor set_block, Location loc)
6413 : base (ds, type, mod,
6414 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6415 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6418 if (get_block == null)
6419 Get = new GetMethod (this);
6421 Get = new GetMethod (this, get_block);
6423 if (set_block == null)
6424 Set = new SetMethod (this);
6426 Set = new SetMethod (this, set_block);
6429 public override bool Define ()
6431 if (!base.Define ())
6437 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6441 GetBuilder = Get.Define (Parent);
6442 if (GetBuilder == null)
6446 // Setup iterator if we are one
6448 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6449 Iterator iterator = new Iterator (
6450 Parent, "get", MemberType,
6452 ModFlags, Get.Block, Location);
6454 if (!iterator.DefineIterator ())
6456 Get.Block = iterator.Block;
6461 SetBuilder = Set.Define (Parent);
6462 if (SetBuilder == null)
6465 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6468 // FIXME - PropertyAttributes.HasDefault ?
6470 PropertyAttributes prop_attr = PropertyAttributes.None;
6472 prop_attr |= PropertyAttributes.RTSpecialName |
6473 PropertyAttributes.SpecialName;
6475 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6476 Name, prop_attr, MemberType, null);
6479 PropertyBuilder.SetGetMethod (GetBuilder);
6482 PropertyBuilder.SetSetMethod (SetBuilder);
6484 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6488 public void SetYields ()
6490 ModFlags |= Modifiers.METHOD_YIELDS;
6495 /// Gigantic workaround for lameness in SRE follows :
6496 /// This class derives from EventInfo and attempts to basically
6497 /// wrap around the EventBuilder so that FindMembers can quickly
6498 /// return this in it search for members
6500 public class MyEventBuilder : EventInfo {
6503 // We use this to "point" to our Builder which is
6504 // not really a MemberInfo
6506 EventBuilder MyBuilder;
6509 // We "catch" and wrap these methods
6511 MethodInfo raise, remove, add;
6513 EventAttributes attributes;
6514 Type declaring_type, reflected_type, event_type;
6519 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6521 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6523 // And now store the values in our own fields.
6525 declaring_type = type_builder;
6527 reflected_type = type_builder;
6529 attributes = event_attr;
6532 this.event_type = event_type;
6536 // Methods that you have to override. Note that you only need
6537 // to "implement" the variants that take the argument (those are
6538 // the "abstract" methods, the others (GetAddMethod()) are
6541 public override MethodInfo GetAddMethod (bool nonPublic)
6546 public override MethodInfo GetRemoveMethod (bool nonPublic)
6551 public override MethodInfo GetRaiseMethod (bool nonPublic)
6557 // These methods make "MyEventInfo" look like a Builder
6559 public void SetRaiseMethod (MethodBuilder raiseMethod)
6561 raise = raiseMethod;
6562 MyBuilder.SetRaiseMethod (raiseMethod);
6565 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6567 remove = removeMethod;
6568 MyBuilder.SetRemoveOnMethod (removeMethod);
6571 public void SetAddOnMethod (MethodBuilder addMethod)
6574 MyBuilder.SetAddOnMethod (addMethod);
6577 public void SetCustomAttribute (CustomAttributeBuilder cb)
6579 MyBuilder.SetCustomAttribute (cb);
6582 public override object [] GetCustomAttributes (bool inherit)
6584 // FIXME : There's nothing which can be seemingly done here because
6585 // we have no way of getting at the custom attribute objects of the
6590 public override object [] GetCustomAttributes (Type t, bool inherit)
6592 // FIXME : Same here !
6596 public override bool IsDefined (Type t, bool b)
6601 public override EventAttributes Attributes {
6607 public override string Name {
6613 public override Type DeclaringType {
6615 return declaring_type;
6619 public override Type ReflectedType {
6621 return reflected_type;
6625 public Type EventType {
6631 public void SetUsed ()
6633 if (my_event != null) {
6634 my_event.status = FieldBase.Status.ASSIGNED;
6635 my_event.SetMemberIsUsed ();
6641 /// For case when event is declared like property (with add and remove accessors).
6643 public class EventProperty: Event {
6645 static string[] attribute_targets = new string [] { "event", "property" };
6647 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6648 bool is_iface, MemberName name, Object init,
6649 Attributes attrs, Accessor add, Accessor remove,
6651 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6653 Add = new AddDelegateMethod (this, add);
6654 Remove = new RemoveDelegateMethod (this, remove);
6656 // For this event syntax we don't report error CS0067
6657 // because it is hard to do it.
6661 public override string[] ValidAttributeTargets {
6663 return attribute_targets;
6669 /// Event is declared like field.
6671 public class EventField: Event {
6673 static string[] attribute_targets = new string [] { "event", "field", "method" };
6674 static string[] attribute_targets_interface = new string[] { "event", "method" };
6676 public EventField (TypeContainer parent, Expression type, int mod_flags,
6677 bool is_iface, MemberName name, Object init,
6678 Attributes attrs, Location loc)
6679 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6681 Add = new AddDelegateMethod (this);
6682 Remove = new RemoveDelegateMethod (this);
6685 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6687 if (a.Target == AttributeTargets.Field) {
6688 FieldBuilder.SetCustomAttribute (cb);
6692 if (a.Target == AttributeTargets.Method) {
6693 Add.ApplyAttributeBuilder (a, cb);
6694 Remove.ApplyAttributeBuilder (a, cb);
6698 base.ApplyAttributeBuilder (a, cb);
6701 public override string[] ValidAttributeTargets {
6703 return IsInterface ? attribute_targets_interface : attribute_targets;
6708 public abstract class Event : FieldBase {
6710 protected sealed class AddDelegateMethod: DelegateMethod
6713 public AddDelegateMethod (Event method):
6714 base (method, "add_")
6718 public AddDelegateMethod (Event method, Accessor accessor):
6719 base (method, accessor, "add_")
6723 protected override MethodInfo DelegateMethodInfo {
6725 return TypeManager.delegate_combine_delegate_delegate;
6731 protected sealed class RemoveDelegateMethod: DelegateMethod
6733 public RemoveDelegateMethod (Event method):
6734 base (method, "remove_")
6738 public RemoveDelegateMethod (Event method, Accessor accessor):
6739 base (method, accessor, "remove_")
6743 protected override MethodInfo DelegateMethodInfo {
6745 return TypeManager.delegate_remove_delegate_delegate;
6751 public abstract class DelegateMethod: AbstractPropertyEventMethod
6753 protected readonly Event method;
6754 ImplicitParameter param_attr;
6756 static string[] attribute_targets = new string [] { "method", "param", "return" };
6758 public DelegateMethod (Event method, string prefix)
6759 : base (method, prefix)
6761 this.method = method;
6764 public DelegateMethod (Event method, Accessor accessor, string prefix)
6765 : base (method, accessor, prefix)
6767 this.method = method;
6770 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6772 if (a.Target == AttributeTargets.Parameter) {
6773 if (param_attr == null)
6774 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6776 param_attr.ApplyAttributeBuilder (a, cb);
6780 base.ApplyAttributeBuilder (a, cb);
6783 public override AttributeTargets AttributeTargets {
6785 return AttributeTargets.Method;
6789 public override bool IsClsCompliaceRequired(DeclSpace ds)
6791 return method.IsClsCompliaceRequired (ds);
6794 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6796 method_data = new MethodData (method, ip, method.ModFlags,
6797 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6799 if (!method_data.Define (container))
6802 MethodBuilder mb = method_data.MethodBuilder;
6803 mb.DefineParameter (1, ParameterAttributes.None, "value");
6808 protected override void EmitMethod (TypeContainer tc)
6810 if (block != null) {
6811 base.EmitMethod (tc);
6815 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6818 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6819 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6821 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6822 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6823 ig.Emit (OpCodes.Ldsfld, field_info);
6824 ig.Emit (OpCodes.Ldarg_0);
6825 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6826 ig.Emit (OpCodes.Castclass, method.MemberType);
6827 ig.Emit (OpCodes.Stsfld, field_info);
6829 ig.Emit (OpCodes.Ldarg_0);
6830 ig.Emit (OpCodes.Ldarg_0);
6831 ig.Emit (OpCodes.Ldfld, field_info);
6832 ig.Emit (OpCodes.Ldarg_1);
6833 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6834 ig.Emit (OpCodes.Castclass, method.MemberType);
6835 ig.Emit (OpCodes.Stfld, field_info);
6837 ig.Emit (OpCodes.Ret);
6840 protected abstract MethodInfo DelegateMethodInfo { get; }
6842 public override Type[] ParameterTypes {
6844 return new Type[] { method.MemberType };
6848 public override Type ReturnType {
6850 return TypeManager.void_type;
6854 public override EmitContext CreateEmitContext (TypeContainer tc,
6857 return new EmitContext (
6858 tc, method.Parent, Location, ig, ReturnType,
6859 method.ModFlags, false);
6862 public override string GetSignatureForError (TypeContainer tc)
6864 return String.Concat (tc.Name, '.', method.Name);
6867 public override ObsoleteAttribute GetObsoleteAttribute ()
6869 return method.GetObsoleteAttribute (method.Parent);
6872 public override string[] ValidAttributeTargets {
6874 return attribute_targets;
6880 const int AllowedModifiers =
6883 Modifiers.PROTECTED |
6884 Modifiers.INTERNAL |
6889 Modifiers.OVERRIDE |
6893 const int AllowedInterfaceModifiers =
6896 public DelegateMethod Add, Remove;
6897 public MyEventBuilder EventBuilder;
6898 public MethodBuilder AddBuilder, RemoveBuilder;
6900 public Event (TypeContainer parent, Expression type, int mod_flags,
6901 bool is_iface, MemberName name, Object init, Attributes attrs,
6903 : base (parent, type, mod_flags,
6904 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6905 name, init, attrs, loc)
6907 IsInterface = is_iface;
6910 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6912 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6913 a.Error_InvalidSecurityParent ();
6917 EventBuilder.SetCustomAttribute (cb);
6920 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6922 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6925 public override AttributeTargets AttributeTargets {
6927 return AttributeTargets.Event;
6931 public override bool Define ()
6933 EventAttributes e_attr;
6934 e_attr = EventAttributes.None;
6939 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6940 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6941 "': abstract event can not have an initializer");
6945 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6946 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6947 "' : event must be of a delegate type");
6951 EmitContext ec = Parent.EmitContext;
6953 throw new InternalErrorException ("Event.Define called too early?");
6954 bool old_unsafe = ec.InUnsafe;
6955 ec.InUnsafe = InUnsafe;
6957 Parameter [] parms = new Parameter [1];
6958 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
6959 Parameters parameters = new Parameters (parms, null);
6960 Type [] types = parameters.GetParameterInfo (ec);
6961 InternalParameters ip = new InternalParameters (types, parameters);
6963 ec.InUnsafe = old_unsafe;
6969 // Now define the accessors
6972 AddBuilder = Add.Define (Parent, ip);
6973 if (AddBuilder == null)
6976 RemoveBuilder = Remove.Define (Parent, ip);
6977 if (RemoveBuilder == null)
6980 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6982 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6983 FieldBuilder = Parent.TypeBuilder.DefineField (
6985 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6986 TypeManager.RegisterPrivateFieldOfEvent (
6987 (EventInfo) EventBuilder, FieldBuilder);
6988 TypeManager.RegisterFieldBase (FieldBuilder, this);
6991 EventBuilder.SetAddOnMethod (AddBuilder);
6992 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6994 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6998 protected override bool CheckBase ()
7000 if (!base.CheckBase ())
7003 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7004 if (!(conflict_symbol is EventInfo)) {
7005 Report.SymbolRelatedToPreviousError (conflict_symbol);
7006 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
7014 public override void Emit ()
7016 if (OptAttributes != null) {
7017 EmitContext ec = new EmitContext (
7018 Parent, Location, null, MemberType, ModFlags);
7019 OptAttributes.Emit (ec, this);
7023 Remove.Emit (Parent);
7028 public override string GetSignatureForError ()
7030 if (EventBuilder == null)
7031 return base.GetSignatureForError (Parent);
7033 return TypeManager.GetFullNameSignature (EventBuilder);
7037 // Represents header string for documentation comment.
7039 public override string DocCommentHeader {
7040 get { return "E:"; }
7045 public class Indexer : PropertyBase {
7047 class GetIndexerMethod: GetMethod
7049 public GetIndexerMethod (MethodCore method):
7054 public GetIndexerMethod (MethodCore method, Accessor accessor):
7055 base (method, accessor)
7059 // TODO: one GetSignatureForError is enough (reuse Parent member)
7060 public override string GetSignatureForError (TypeContainer tc)
7062 string core = base.GetSignatureForError (tc);
7063 return core.Replace (TypeContainer.DefaultIndexerName,
7064 String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
7067 public override Type[] ParameterTypes {
7069 return method.ParameterTypes;
7074 class SetIndexerMethod: SetMethod
7076 readonly Parameters parameters;
7078 public SetIndexerMethod (MethodCore method):
7083 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7084 base (method, accessor)
7086 this.parameters = parameters;
7089 public override Type[] ParameterTypes {
7091 int top = method.ParameterTypes.Length;
7092 Type [] set_pars = new Type [top + 1];
7093 method.ParameterTypes.CopyTo (set_pars, 0);
7094 set_pars [top] = method.MemberType;
7099 protected override InternalParameters GetParameterInfo (EmitContext ec)
7101 Parameter [] fixed_parms = parameters.FixedParameters;
7103 if (fixed_parms == null){
7104 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7105 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7106 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7108 // Here is the problem: the `value' parameter has
7109 // to come *after* the array parameter in the declaration
7111 // X (object [] x, Type value)
7114 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7115 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7119 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7121 fixed_parms.CopyTo (tmp, 0);
7122 tmp [fixed_parms.Length] = new Parameter (
7123 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7125 Parameters set_formal_params = new Parameters (tmp, null);
7126 Type [] types = set_formal_params.GetParameterInfo (ec);
7128 return new InternalParameters (types, set_formal_params);
7133 const int AllowedModifiers =
7136 Modifiers.PROTECTED |
7137 Modifiers.INTERNAL |
7141 Modifiers.OVERRIDE |
7146 const int AllowedInterfaceModifiers =
7150 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7151 bool is_iface, Parameters parameters, Attributes attrs,
7152 Accessor get_block, Accessor set_block, Location loc)
7153 : base (ds, type, mod,
7154 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7155 is_iface, name, parameters, attrs, loc)
7157 if (get_block == null)
7158 Get = new GetIndexerMethod (this);
7160 Get = new GetIndexerMethod (this, get_block);
7162 if (set_block == null)
7163 Set = new SetIndexerMethod (this);
7165 Set = new SetIndexerMethod (this, parameters, set_block);
7168 public override bool Define ()
7170 PropertyAttributes prop_attr =
7171 PropertyAttributes.RTSpecialName |
7172 PropertyAttributes.SpecialName;
7174 if (!base.Define ())
7177 if (MemberType == TypeManager.void_type) {
7178 Report.Error (620, Location, "Indexers cannot have void type");
7182 if (OptAttributes != null) {
7183 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7184 if (indexer_attr != null) {
7185 // Remove the attribute from the list because it is not emitted
7186 OptAttributes.Attrs.Remove (indexer_attr);
7188 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7190 if (IsExplicitImpl) {
7191 Report.Error (415, indexer_attr.Location,
7192 "The 'IndexerName' attribute is valid only on an " +
7193 "indexer that is not an explicit interface member declaration");
7197 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7198 Report.Error (609, indexer_attr.Location,
7199 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7203 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7204 Report.Error (633, indexer_attr.Location,
7205 "The argument to the 'IndexerName' attribute must be a valid identifier");
7211 if (InterfaceType != null) {
7212 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7213 if (base_IndexerName != Name)
7214 ShortName = base_IndexerName;
7217 if (!Parent.AddToMemberContainer (this) ||
7218 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7224 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7226 GetBuilder = Get.Define (Parent);
7227 if (GetBuilder == null)
7232 SetBuilder = Set.Define (Parent);
7233 if (SetBuilder == null)
7238 // Now name the parameters
7240 Parameter [] p = Parameters.FixedParameters;
7242 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7243 Report.Error (631, Location, "ref and out are not valid in this context");
7249 for (i = 0; i < p.Length; ++i) {
7251 GetBuilder.DefineParameter (
7252 i + 1, p [i].Attributes, p [i].Name);
7255 SetBuilder.DefineParameter (
7256 i + 1, p [i].Attributes, p [i].Name);
7260 SetBuilder.DefineParameter (
7261 i + 1, ParameterAttributes.None, "value");
7263 if (i != ParameterTypes.Length) {
7264 Parameter array_param = Parameters.ArrayParameter;
7266 SetBuilder.DefineParameter (
7267 i + 1, array_param.Attributes, array_param.Name);
7271 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7272 Name, prop_attr, MemberType, ParameterTypes);
7275 PropertyBuilder.SetGetMethod (GetBuilder);
7278 PropertyBuilder.SetSetMethod (SetBuilder);
7280 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7285 public override string GetSignatureForError ()
7287 if (PropertyBuilder == null)
7288 return GetSignatureForError (Parent);
7290 return TypeManager.CSharpSignature (PropertyBuilder, true);
7293 public override string GetSignatureForError(TypeContainer tc)
7295 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7298 public override bool MarkForDuplicationCheck ()
7300 caching_flags |= Flags.TestMethodDuplication;
7306 public class Operator : MethodCore, IIteratorContainer {
7308 const int AllowedModifiers =
7314 public enum OpType : byte {
7324 // Unary and Binary operators
7347 // Implicit and Explicit
7352 public readonly OpType OperatorType;
7353 public MethodBuilder OperatorMethodBuilder;
7355 public Method OperatorMethod;
7357 static string[] attribute_targets = new string [] { "method", "return" };
7359 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7360 int mod_flags, Parameters parameters,
7361 ToplevelBlock block, Attributes attrs, Location loc)
7362 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7363 new MemberName ("op_" + type), attrs, parameters, loc)
7365 OperatorType = type;
7369 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7371 OperatorMethod.ApplyAttributeBuilder (a, cb);
7374 public override AttributeTargets AttributeTargets {
7376 return AttributeTargets.Method;
7380 protected override bool CheckForDuplications()
7382 ArrayList ar = Parent.Operators;
7384 int arLen = ar.Count;
7386 for (int i = 0; i < arLen; i++) {
7387 Operator o = (Operator) ar [i];
7388 if (IsDuplicateImplementation (o))
7393 ar = Parent.Methods;
7395 int arLen = ar.Count;
7397 for (int i = 0; i < arLen; i++) {
7398 Method m = (Method) ar [i];
7399 if (IsDuplicateImplementation (m))
7407 public override bool Define ()
7410 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7411 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7412 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7419 if (MemberType == TypeManager.void_type) {
7420 Report.Error (590, Location, "User-defined operators cannot return void");
7424 OperatorMethod = new Method (
7425 Parent, Type, ModFlags, false, MemberName,
7426 Parameters, OptAttributes, Location);
7428 OperatorMethod.Block = Block;
7429 OperatorMethod.IsOperator = true;
7430 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7431 OperatorMethod.Define ();
7433 if (OperatorMethod.MethodBuilder == null)
7436 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7438 parameter_types = OperatorMethod.ParameterTypes;
7439 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7440 Type return_type = OperatorMethod.ReturnType;
7441 Type first_arg_type = parameter_types [0];
7446 // Rules for conversion operators
7448 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7449 if (first_arg_type == return_type && first_arg_type == declaring_type){
7452 "User-defined conversion cannot take an object of the " +
7453 "enclosing type and convert to an object of the enclosing" +
7458 if (first_arg_type != declaring_type && return_type != declaring_type){
7461 "User-defined conversion must convert to or from the " +
7466 if (first_arg_type == TypeManager.object_type ||
7467 return_type == TypeManager.object_type){
7470 "User-defined conversion cannot convert to or from " +
7475 if (first_arg_type.IsInterface || return_type.IsInterface){
7478 "User-defined conversion cannot convert to or from an " +
7483 if (first_arg_type.IsSubclassOf (return_type)
7484 || return_type.IsSubclassOf (first_arg_type)){
7485 if (declaring_type.IsSubclassOf (return_type)) {
7486 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7489 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7492 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7493 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7494 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");
7497 } else if (Parameters.FixedParameters.Length == 1) {
7498 // Checks for Unary operators
7500 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7501 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7502 Report.Error (448, Location,
7503 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7506 if (first_arg_type != declaring_type) {
7508 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7513 if (first_arg_type != declaring_type){
7516 "The parameter of a unary operator must be the " +
7521 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7522 if (return_type != TypeManager.bool_type){
7525 "The return type of operator True or False " +
7532 // Checks for Binary operators
7534 if (first_arg_type != declaring_type &&
7535 parameter_types [1] != declaring_type){
7538 "One of the parameters of a binary operator must " +
7539 "be the containing type");
7547 public override void Emit ()
7550 // abstract or extern methods have no bodies
7552 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7555 OperatorMethod.Emit ();
7559 // Operator cannot be override
7560 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7565 public static string GetName (OpType ot)
7568 case OpType.LogicalNot:
7570 case OpType.OnesComplement:
7572 case OpType.Increment:
7574 case OpType.Decrement:
7580 case OpType.Addition:
7582 case OpType.Subtraction:
7584 case OpType.UnaryPlus:
7586 case OpType.UnaryNegation:
7588 case OpType.Multiply:
7590 case OpType.Division:
7592 case OpType.Modulus:
7594 case OpType.BitwiseAnd:
7596 case OpType.BitwiseOr:
7598 case OpType.ExclusiveOr:
7600 case OpType.LeftShift:
7602 case OpType.RightShift:
7604 case OpType.Equality:
7606 case OpType.Inequality:
7608 case OpType.GreaterThan:
7610 case OpType.LessThan:
7612 case OpType.GreaterThanOrEqual:
7614 case OpType.LessThanOrEqual:
7616 case OpType.Implicit:
7618 case OpType.Explicit:
7624 public override string GetSignatureForError (TypeContainer tc)
7626 StringBuilder sb = new StringBuilder ();
7627 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7628 Parameters.FixedParameters [0].GetSignatureForError ());
7630 if (Parameters.FixedParameters.Length > 1) {
7632 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7635 return sb.ToString ();
7638 public override string GetSignatureForError ()
7643 public override bool MarkForDuplicationCheck ()
7645 caching_flags |= Flags.TestMethodDuplication;
7649 public override string ToString ()
7651 if (OperatorMethod == null)
7654 Type return_type = OperatorMethod.ReturnType;
7655 Type [] param_types = OperatorMethod.ParameterTypes;
7657 if (Parameters.FixedParameters.Length == 1)
7658 return String.Format (
7659 "{0} operator {1}({2})",
7660 TypeManager.CSharpName (return_type),
7661 GetName (OperatorType),
7664 return String.Format (
7665 "{0} operator {1}({2}, {3})",
7666 TypeManager.CSharpName (return_type),
7667 GetName (OperatorType),
7668 param_types [0], param_types [1]);
7671 public override string[] ValidAttributeTargets {
7673 return attribute_targets;
7677 public void SetYields ()
7679 ModFlags |= Modifiers.METHOD_YIELDS;
7684 // This is used to compare method signatures
7686 struct MethodSignature {
7688 public Type RetType;
7689 public Type [] Parameters;
7692 /// This delegate is used to extract methods which have the
7693 /// same signature as the argument
7695 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7697 public MethodSignature (string name, Type ret_type, Type [] parameters)
7702 if (parameters == null)
7703 Parameters = TypeManager.NoTypes;
7705 Parameters = parameters;
7708 public override string ToString ()
7711 if (Parameters.Length != 0){
7712 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7713 for (int i = 0; i < Parameters.Length; i++){
7714 sb.Append (Parameters [i]);
7715 if (i+1 < Parameters.Length)
7718 pars = sb.ToString ();
7721 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7724 public override int GetHashCode ()
7726 return Name.GetHashCode ();
7729 public override bool Equals (Object o)
7731 MethodSignature other = (MethodSignature) o;
7733 if (other.Name != Name)
7736 if (other.RetType != RetType)
7739 if (Parameters == null){
7740 if (other.Parameters == null)
7745 if (other.Parameters == null)
7748 int c = Parameters.Length;
7749 if (other.Parameters.Length != c)
7752 for (int i = 0; i < c; i++)
7753 if (other.Parameters [i] != Parameters [i])
7759 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7761 MethodSignature sig = (MethodSignature) filter_criteria;
7763 if (m.Name != sig.Name)
7767 MethodInfo mi = m as MethodInfo;
7768 PropertyInfo pi = m as PropertyInfo;
7771 ReturnType = mi.ReturnType;
7772 else if (pi != null)
7773 ReturnType = pi.PropertyType;
7778 // we use sig.RetType == null to mean `do not check the
7779 // method return value.
7781 if (sig.RetType != null)
7782 if (ReturnType != sig.RetType)
7787 args = TypeManager.GetArgumentTypes (mi);
7789 args = TypeManager.GetArgumentTypes (pi);
7790 Type [] sigp = sig.Parameters;
7792 if (args.Length != sigp.Length)
7795 for (int i = args.Length; i > 0; ){
7797 if (args [i] != sigp [i])