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 protected class CircularDepException: Exception
69 public TypeContainer Container;
70 public CircularDepException (TypeContainer tc)
76 public class MemberCoreArrayList: ArrayList
79 /// Defines the MemberCore objects that are in this array
81 public virtual void DefineContainerMembers ()
83 foreach (MemberCore mc in this) {
88 public virtual void Emit ()
90 foreach (MemberCore mc in this)
95 public class MethodArrayList: MemberCoreArrayList
103 CachedMethods cached_method;
104 TypeContainer container;
106 public MethodArrayList (TypeContainer container)
108 this.container = container;
112 /// Method container contains Equals method
114 public bool HasEquals {
116 cached_method |= CachedMethods.Equals;
120 return (cached_method & CachedMethods.Equals) != 0;
125 /// Method container contains GetHashCode method
127 public bool HasGetHashCode {
129 cached_method |= CachedMethods.GetHashCode;
133 return (cached_method & CachedMethods.GetHashCode) != 0;
137 public override void DefineContainerMembers ()
139 base.DefineContainerMembers ();
141 if ((RootContext.WarningLevel >= 3) && HasEquals && !HasGetHashCode) {
142 Report.Warning (659, container.Location, "'{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
148 public sealed class IndexerArrayList: MemberCoreArrayList
151 /// The indexer name for this container
153 public string IndexerName = DefaultIndexerName;
155 bool seen_normal_indexers = false;
157 TypeContainer container;
159 public IndexerArrayList (TypeContainer container)
161 this.container = container;
165 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
166 /// class is consistent. Either it is `Item' or it is the name defined by all the
167 /// indexers with the `IndexerName' attribute.
169 /// Turns out that the IndexerNameAttribute is applied to each indexer,
170 /// but it is never emitted, instead a DefaultMember attribute is attached
173 public override void DefineContainerMembers()
175 base.DefineContainerMembers ();
177 string class_indexer_name = null;
180 // If there's both an explicit and an implicit interface implementation, the
181 // explicit one actually implements the interface while the other one is just
182 // a normal indexer. See bug #37714.
185 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
186 foreach (Indexer i in this) {
187 if (i.InterfaceType != null) {
188 if (seen_normal_indexers)
189 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
193 seen_normal_indexers = true;
195 if (class_indexer_name == null) {
196 class_indexer_name = i.ShortName;
200 if (i.ShortName != class_indexer_name)
201 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");
204 if (class_indexer_name != null)
205 IndexerName = class_indexer_name;
208 public override void Emit ()
212 if (!seen_normal_indexers)
215 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
216 container.TypeBuilder.SetCustomAttribute (cb);
220 public class OperatorArrayList: MemberCoreArrayList
222 TypeContainer container;
224 public OperatorArrayList (TypeContainer container)
226 this.container = container;
230 // Operator pair checking
235 public Type ret_type;
236 public Type type1, type2;
238 public Operator.OpType ot;
240 public OperatorEntry (int f, Operator o)
244 ret_type = o.OperatorMethod.ReturnType;
245 Type [] pt = o.OperatorMethod.ParameterTypes;
252 public override int GetHashCode ()
254 return ret_type.GetHashCode ();
257 public override bool Equals (object o)
259 OperatorEntry other = (OperatorEntry) o;
261 if (other.ret_type != ret_type)
263 if (other.type1 != type1)
265 if (other.type2 != type2)
272 // Checks that some operators come in pairs:
278 // They are matched based on the return type and the argument types
280 void CheckPairedOperators ()
282 Hashtable pairs = new Hashtable (null, null);
283 Operator true_op = null;
284 Operator false_op = null;
285 bool has_equality_or_inequality = false;
287 // Register all the operators we care about.
288 foreach (Operator op in this){
291 // Skip erroneous code.
292 if (op.OperatorMethod == null)
295 switch (op.OperatorType){
296 case Operator.OpType.Equality:
298 has_equality_or_inequality = true;
300 case Operator.OpType.Inequality:
302 has_equality_or_inequality = true;
305 case Operator.OpType.True:
308 case Operator.OpType.False:
312 case Operator.OpType.GreaterThan:
314 case Operator.OpType.LessThan:
317 case Operator.OpType.GreaterThanOrEqual:
319 case Operator.OpType.LessThanOrEqual:
325 OperatorEntry oe = new OperatorEntry (reg, op);
327 object o = pairs [oe];
331 oe = (OperatorEntry) o;
336 if (true_op != null){
337 if (false_op == null)
338 Report.Error (216, true_op.Location, "operator true requires a matching operator false");
339 } else if (false_op != null)
340 Report.Error (216, false_op.Location, "operator false requires a matching operator true");
343 // Look for the mistakes.
345 foreach (DictionaryEntry de in pairs){
346 OperatorEntry oe = (OperatorEntry) de.Key;
353 case Operator.OpType.Equality:
356 case Operator.OpType.Inequality:
359 case Operator.OpType.GreaterThan:
362 case Operator.OpType.LessThan:
365 case Operator.OpType.GreaterThanOrEqual:
368 case Operator.OpType.LessThanOrEqual:
372 Report.Error (216, oe.op.Location,
373 "The operator `" + oe.op + "' requires a matching operator `" + s + "' to also be defined");
376 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
377 if (container.Methods == null || !container.Methods.HasEquals)
378 Report.Warning (660, container.Location, "'{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
380 if (container.Methods == null || !container.Methods.HasGetHashCode)
381 Report.Warning (661, container.Location, "'{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
385 public override void DefineContainerMembers ()
387 base.DefineContainerMembers ();
388 CheckPairedOperators ();
393 // Whether this is a struct, class or interface
394 public readonly Kind Kind;
396 // Holds a list of classes and structures
399 // Holds the list of properties
400 MemberCoreArrayList properties;
402 // Holds the list of enumerations
403 MemberCoreArrayList enums;
405 // Holds the list of delegates
406 MemberCoreArrayList delegates;
408 // Holds the list of constructors
409 protected MemberCoreArrayList instance_constructors;
411 // Holds the list of fields
412 MemberCoreArrayList fields;
414 // Holds a list of fields that have initializers
415 protected ArrayList initialized_fields;
417 // Holds a list of static fields that have initializers
418 protected ArrayList initialized_static_fields;
420 // Holds the list of constants
421 MemberCoreArrayList constants;
424 MemberCoreArrayList interfaces;
426 // Holds the methods.
427 MethodArrayList methods;
430 protected MemberCoreArrayList events;
432 // Holds the indexers
433 IndexerArrayList indexers;
435 // Holds the operators
436 MemberCoreArrayList operators;
438 // Holds the iterators
441 // Holds the parts of a partial class;
445 // Pointers to the default constructor and the default static constructor
447 protected Constructor default_constructor;
448 protected Constructor default_static_constructor;
451 // Whether we have at least one non-static field
453 bool have_nonstatic_fields = false;
456 // This one is computed after we can distinguish interfaces
457 // from classes from the arraylist `type_bases'
459 string base_class_name;
462 ArrayList type_bases;
464 bool members_defined;
465 bool members_defined_ok;
467 // The interfaces we implement.
468 protected Type [] ifaces;
469 protected Type ptype;
471 // The base member cache and our member cache
472 MemberCache base_cache;
473 MemberCache member_cache;
475 public const string DefaultIndexerName = "Item";
477 // This is used to catch recursive definitions in declarations.
478 protected bool InTransit;
480 public TypeContainer (NamespaceEntry ns, TypeContainer parent, MemberName name,
481 Attributes attrs, Kind kind, Location l)
482 : base (ns, parent, name, attrs, l)
484 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
485 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
489 types = new ArrayList ();
491 base_class_name = null;
494 public bool AddToMemberContainer (MemberCore symbol)
496 return AddToContainer (symbol, symbol.Name);
499 bool AddToTypeContainer (DeclSpace ds)
501 // Parent == null ==> this == RootContext.Tree.Types
502 return AddToContainer (ds, (Parent == null) ? ds.Name : ds.Basename);
505 public void AddConstant (Const constant)
507 if (!AddToMemberContainer (constant))
510 if (constants == null)
511 constants = new MemberCoreArrayList ();
513 constants.Add (constant);
516 public void AddEnum (Mono.CSharp.Enum e)
518 if (!AddToTypeContainer (e))
522 enums = new MemberCoreArrayList ();
527 public void AddClassOrStruct (TypeContainer c)
529 if (!AddToTypeContainer (c))
535 public void AddDelegate (Delegate d)
537 if (!AddToTypeContainer (d))
540 if (delegates == null)
541 delegates = new MemberCoreArrayList ();
546 public void AddMethod (Method method)
548 if (!AddToMemberContainer (method))
552 methods = new MethodArrayList (this);
554 if (method.MemberName.Left != null)
555 methods.Insert (0, method);
557 methods.Add (method);
560 public void AddConstructor (Constructor c)
562 if (c.Name != Basename) {
563 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
566 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
569 if (default_static_constructor != null) {
570 Report.SymbolRelatedToPreviousError (default_static_constructor);
571 Report.Error (111, c.Location, Error111, Name, c.Name);
575 default_static_constructor = c;
578 if (default_constructor != null) {
579 Report.SymbolRelatedToPreviousError (default_constructor);
580 Report.Error (111, c.Location, Error111, c.Location, Name, c.Name);
583 default_constructor = c;
586 if (instance_constructors == null)
587 instance_constructors = new MemberCoreArrayList ();
589 instance_constructors.Add (c);
593 internal static string Error111 {
595 return "Type '{0}' already defines a member called '{1}' with the same parameter types";
599 public void AddInterface (TypeContainer iface)
601 if (!AddToTypeContainer (iface))
604 if (interfaces == null) {
605 interfaces = new MemberCoreArrayList ();
608 interfaces.Add (iface);
611 public void AddField (FieldMember field)
613 if (!AddToMemberContainer (field))
617 fields = new MemberCoreArrayList ();
621 if (field.HasInitializer)
622 RegisterFieldForInitialization (field);
624 if ((field.ModFlags & Modifiers.STATIC) == 0)
625 have_nonstatic_fields = true;
628 public void AddProperty (Property prop)
630 if (!AddToMemberContainer (prop) ||
631 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
634 if (properties == null)
635 properties = new MemberCoreArrayList ();
637 if (prop.MemberName.Left != null)
638 properties.Insert (0, prop);
640 properties.Add (prop);
643 public void AddEvent (Event e)
645 if (!AddToMemberContainer (e))
648 if (e is EventProperty) {
649 if (!AddToMemberContainer (e.Add))
652 if (!AddToMemberContainer (e.Remove))
657 events = new MemberCoreArrayList ();
664 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
666 public void AddIndexer (Indexer i)
668 if (indexers == null)
669 indexers = new IndexerArrayList (this);
671 if (i.IsExplicitImpl)
672 indexers.Insert (0, i);
677 public void AddOperator (Operator op)
679 if (!AddToMemberContainer (op))
682 if (operators == null)
683 operators = new OperatorArrayList (this);
688 public void AddIterator (Iterator i)
690 if (iterators == null)
691 iterators = new ArrayList ();
696 public void AddType (TypeContainer tc)
701 public void AddPart (ClassPart part)
704 parts = new ArrayList ();
709 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
711 if (a.Type == TypeManager.default_member_type) {
712 if (Indexers != null) {
713 Report.Error (646, a.Location,
714 "Cannot specify the DefaultMember attribute on" +
715 " a type containing an indexer");
720 base.ApplyAttributeBuilder (a, cb);
723 public override AttributeTargets AttributeTargets {
727 return AttributeTargets.Class;
729 return AttributeTargets.Struct;
731 return AttributeTargets.Interface;
733 throw new NotSupportedException ();
738 public ArrayList Types {
744 public MethodArrayList Methods {
750 public ArrayList Constants {
756 public ArrayList Interfaces {
762 public ArrayList Iterators {
770 return base_class_name;
774 public ArrayList Bases {
784 public ArrayList Fields {
790 public ArrayList InstanceConstructors {
792 return instance_constructors;
796 public ArrayList Properties {
802 public ArrayList Events {
808 public ArrayList Enums {
814 public ArrayList Indexers {
820 public ArrayList Operators {
826 public ArrayList Delegates {
832 public ArrayList Parts {
838 protected override TypeAttributes TypeAttr {
840 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
844 public string IndexerName {
846 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
850 public virtual void RegisterFieldForInitialization (FieldMember field)
852 if ((field.ModFlags & Modifiers.STATIC) != 0){
853 if (initialized_static_fields == null)
854 initialized_static_fields = new ArrayList ();
856 initialized_static_fields.Add (field);
858 if (initialized_fields == null)
859 initialized_fields = new ArrayList ();
861 initialized_fields.Add (field);
866 // Emits the instance field initializers
868 public virtual bool EmitFieldInitializers (EmitContext ec)
871 Expression instance_expr;
874 fields = initialized_static_fields;
875 instance_expr = null;
877 fields = initialized_fields;
878 instance_expr = new This (Location.Null).Resolve (ec);
884 foreach (FieldMember f in fields){
885 Expression e = f.GetInitializerExpression (ec);
889 Location l = f.Location;
890 FieldExpr fe = new FieldExpr (f.FieldBuilder, l, true);
891 fe.InstanceExpression = instance_expr;
892 ExpressionStatement a = new Assign (fe, e, l);
894 a = a.ResolveStatement (ec);
898 Constant c = e as Constant;
900 if (c.IsDefaultValue)
904 a.EmitStatement (ec);
911 // Defines the default constructors
913 protected void DefineDefaultConstructor (bool is_static)
917 // The default constructor is public
918 // If the class is abstract, the default constructor is protected
919 // The default static constructor is private
921 int mods = Modifiers.PUBLIC;
923 mods = Modifiers.STATIC | Modifiers.PRIVATE;
924 else if ((ModFlags & Modifiers.ABSTRACT) != 0)
925 mods = Modifiers.PROTECTED;
927 TypeContainer constructor_parent = this;
929 constructor_parent = (TypeContainer) Parts [0];
931 c = new Constructor (constructor_parent, Basename, mods,
932 Parameters.EmptyReadOnlyParameters,
933 new ConstructorBaseInitializer (
934 null, Parameters.EmptyReadOnlyParameters,
940 c.Block = new ToplevelBlock (null, Location);
945 /// The pending methods that need to be implemented
946 // (interfaces or abstract methods)
948 public PendingImplementation Pending;
950 public abstract PendingImplementation GetPendingImplementations ();
952 TypeExpr[] GetPartialBases (out TypeExpr base_class)
954 ArrayList ifaces = new ArrayList ();
957 Location base_loc = Location.Null;
959 foreach (ClassPart part in parts) {
960 TypeExpr new_base_class;
961 TypeExpr[] new_ifaces;
963 new_ifaces = part.GetClassBases (out new_base_class);
964 if (new_ifaces == null && new_base_class != null)
967 if ((base_class != null) && (new_base_class != null) &&
968 !base_class.Equals (new_base_class)) {
969 Report.Error (263, part.Location,
970 "Partial declarations of `{0}' must " +
971 "not specify different base classes",
974 if (!Location.IsNull (base_loc))
975 Report.LocationOfPreviousError (base_loc);
980 if ((base_class == null) && (new_base_class != null)) {
981 base_class = new_base_class;
982 base_loc = part.Location;
985 if (new_ifaces == null)
988 foreach (TypeExpr iface in new_ifaces) {
990 foreach (TypeExpr old_iface in ifaces) {
991 if (old_iface.Equals (iface)) {
1002 TypeExpr[] retval = new TypeExpr [ifaces.Count];
1003 ifaces.CopyTo (retval, 0);
1007 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1011 int count = Bases.Count;
1012 int start = 0, i, j;
1014 if (Kind == Kind.Class){
1015 TypeExpr name = ResolveBaseTypeExpr (
1016 (Expression) Bases [0], false, Location);
1022 if (!name.IsInterface) {
1023 // base_class could be a class, struct, enum, delegate.
1024 // This is validated in GetClassBases.
1030 TypeExpr [] ifaces = new TypeExpr [count-start];
1032 for (i = start, j = 0; i < count; i++, j++){
1033 TypeExpr resolved = ResolveBaseTypeExpr ((Expression) Bases [i], false, Location);
1034 if (resolved == null) {
1038 ifaces [j] = resolved;
1045 /// This function computes the Base class and also the
1046 /// list of interfaces that the class or struct @c implements.
1048 /// The return value is an array (might be null) of
1049 /// interfaces implemented (as Types).
1051 /// The @base_class argument is set to the base object or null
1052 /// if this is `System.Object'.
1054 TypeExpr [] GetClassBases (out TypeExpr base_class)
1061 ifaces = GetPartialBases (out base_class);
1062 else if (Bases == null){
1066 ifaces = GetNormalBases (out base_class);
1071 if ((base_class != null) && (Kind == Kind.Class)){
1073 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
1074 Report.Error (1521, base_class.Location, "Invalid base type");
1078 if (base_class.IsSealed){
1079 Report.SymbolRelatedToPreviousError (base_class.Type);
1080 if (base_class.Type.IsAbstract) {
1081 Report.Error (709, Location, "'{0}': Cannot derive from static class", GetSignatureForError ());
1083 Report.Error (509, Location, "'{0}': Cannot derive from sealed class", GetSignatureForError ());
1088 if (!base_class.CanInheritFrom ()){
1089 Report.Error (644, Location,
1090 "`{0}' cannot inherit from special class `{1}'",
1091 Name, base_class.Name);
1095 if (!base_class.AsAccessible (this, ModFlags)) {
1096 Report.SymbolRelatedToPreviousError (base_class.Type);
1097 Report.Error (60, Location, "Inconsistent accessibility: base class '{0}' is less accessible than class '{1}'",
1098 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
1102 if (base_class != null)
1103 base_class_name = base_class.Name;
1108 int count = ifaces != null ? ifaces.Length : 0;
1110 for (i = 0; i < count; i++) {
1111 TypeExpr iface = (TypeExpr) ifaces [i];
1113 if (!iface.IsInterface) {
1114 if (Kind != Kind.Class) {
1115 // TODO: location of symbol related ....
1116 Error_TypeInListIsNotInterface (Location, iface.FullName);
1118 else if (base_class != null)
1119 Report.Error (1721, Location,
1120 "In Class `{0}', `{1}' is not an interface, and a base class has already been defined",
1123 Report.Error (1722, Location,
1124 "In Class `{0}', `{1}' is not " +
1125 "an interface, a base class must be listed first", Name, iface.Name);
1130 for (int x = 0; x < i; x++) {
1131 if (iface.Equals (ifaces [x])) {
1132 Report.Error (528, Location,
1133 "`{0}' is already listed in " +
1134 "interface list", iface.Name);
1139 if ((Kind == Kind.Interface) &&
1140 !iface.AsAccessible (Parent, ModFlags)) {
1141 Report.Error (61, Location,
1142 "Inconsistent accessibility: base " +
1143 "interface `{0}' is less accessible " +
1144 "than interface `{1}'", iface.Name,
1152 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1154 Report.Error (527, loc, "'{0}': type in interface list is not an interface", type);
1158 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1160 public override TypeBuilder DefineType ()
1162 if (TypeBuilder != null)
1167 TypeExpr[] iface_exprs = GetClassBases (out base_type);
1168 if (iface_exprs == null && base_type != null) {
1173 if (base_type == null) {
1174 if (Kind == Kind.Class){
1175 if (RootContext.StdLib)
1176 base_type = TypeManager.system_object_expr;
1177 else if (Name != "System.Object")
1178 base_type = TypeManager.system_object_expr;
1179 } else if (Kind == Kind.Struct) {
1181 // If we are compiling our runtime,
1182 // and we are defining ValueType, then our
1183 // base is `System.Object'.
1185 if (!RootContext.StdLib && Name == "System.ValueType")
1186 base_type = TypeManager.system_object_expr;
1188 base_type = TypeManager.system_valuetype_expr;
1192 if ((Kind == Kind.Struct) && TypeManager.value_type == null)
1193 throw new Exception ();
1195 TypeAttributes type_attributes = TypeAttr;
1197 if (base_type != null) {
1198 // FIXME: I think this should be ...ResolveType (Parent.EmitContext).
1199 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1200 ptype = base_type.ResolveType (TypeResolveEmitContext);
1201 if (ptype == null) {
1209 if (TypeManager.NamespaceClash (Name, Location)) {
1214 ModuleBuilder builder = CodeGen.Module.Builder;
1215 TypeBuilder = builder.DefineType (
1216 Name, type_attributes, ptype, null);
1219 TypeBuilder builder = Parent.TypeBuilder;
1220 if (builder == null) {
1225 TypeBuilder = builder.DefineNestedType (
1226 Basename, type_attributes, ptype, null);
1229 catch (ArgumentException) {
1230 Report.RuntimeMissingSupport (Location, "static classes");
1235 if (Parts != null) {
1237 foreach (ClassPart part in Parts) {
1238 part.TypeBuilder = TypeBuilder;
1240 part.ec = new EmitContext (part, Mono.CSharp.Location.Null, null, null, ModFlags);
1241 part.ec.ContainerType = TypeBuilder;
1245 ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
1246 ec.ContainerType = TypeBuilder;
1249 // add interfaces that were not added at type creation
1250 if (iface_exprs != null) {
1251 // FIXME: I think this should be ...ExpandInterfaces (Parent.EmitContext, ...).
1252 // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
1253 TypeResolveEmitContext.ContainerType = TypeBuilder;
1254 ifaces = TypeManager.ExpandInterfaces (TypeResolveEmitContext, iface_exprs);
1255 if (ifaces == null) {
1260 foreach (Type itype in ifaces)
1261 TypeBuilder.AddInterfaceImplementation (itype);
1263 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1266 TypeManager.AddUserType (Name, TypeBuilder, this);
1268 if (!(this is Iterator))
1269 RootContext.RegisterOrder (this);
1273 if (!DefineNestedTypes ()) {
1280 protected virtual bool DefineNestedTypes ()
1282 if (Interfaces != null) {
1283 foreach (TypeContainer iface in Interfaces)
1284 if (iface.DefineType () == null)
1288 if (Types != null) {
1289 foreach (TypeContainer tc in Types)
1290 if (tc.DefineType () == null)
1294 if (Delegates != null) {
1295 foreach (Delegate d in Delegates)
1296 if (d.DefineType () == null)
1300 if (Enums != null) {
1301 foreach (Enum en in Enums)
1302 if (en.DefineType () == null)
1309 static void Error_KeywordNotAllowed (Location loc)
1311 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
1315 /// Populates our TypeBuilder with fields and methods
1317 public override bool DefineMembers (TypeContainer container)
1319 if (members_defined)
1320 return members_defined_ok;
1322 members_defined_ok = DoDefineMembers ();
1323 members_defined = true;
1325 return members_defined_ok;
1328 bool DoDefineMembers ()
1331 if ((ModFlags & Modifiers.NEW) != 0)
1332 Error_KeywordNotAllowed (Location);
1334 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1335 if (conflict_symbol == null) {
1336 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1337 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1339 if ((ModFlags & Modifiers.NEW) == 0) {
1340 Report.SymbolRelatedToPreviousError (conflict_symbol);
1341 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError ());
1346 DefineContainerMembers (constants);
1347 DefineContainerMembers (fields);
1349 if ((Kind == Kind.Class) && !(this is ClassPart)){
1350 if ((instance_constructors == null) &&
1351 !(this is StaticClass)) {
1352 if (default_constructor == null)
1353 DefineDefaultConstructor (false);
1356 if (initialized_static_fields != null &&
1357 default_static_constructor == null)
1358 DefineDefaultConstructor (true);
1361 if (Kind == Kind.Struct){
1363 // Structs can not have initialized instance
1366 if (initialized_static_fields != null &&
1367 default_static_constructor == null)
1368 DefineDefaultConstructor (true);
1370 if (initialized_fields != null)
1371 ReportStructInitializedInstanceError ();
1374 Pending = GetPendingImplementations ();
1376 if (parts != null) {
1377 foreach (ClassPart part in parts) {
1378 if (!part.DefineMembers (this))
1384 // Constructors are not in the defined_names array
1386 DefineContainerMembers (instance_constructors);
1388 if (default_static_constructor != null)
1389 default_static_constructor.Define ();
1391 DefineContainerMembers (properties);
1392 DefineContainerMembers (events);
1393 DefineContainerMembers (indexers);
1394 DefineContainerMembers (methods);
1395 DefineContainerMembers (operators);
1396 DefineContainerMembers (enums);
1397 DefineContainerMembers (delegates);
1400 if (!(this is ClassPart))
1401 member_cache = new MemberCache (this);
1404 if (parts != null) {
1405 foreach (ClassPart part in parts)
1406 part.member_cache = member_cache;
1409 if (iterators != null) {
1410 foreach (Iterator iterator in iterators) {
1411 if (iterator.DefineType () == null)
1415 foreach (Iterator iterator in iterators) {
1416 if (!iterator.DefineMembers (this))
1424 void ReportStructInitializedInstanceError ()
1426 string n = TypeBuilder.FullName;
1428 foreach (Field f in initialized_fields){
1431 "`" + n + "." + f.Name + "': can not have " +
1432 "instance field initializers in structs");
1436 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1439 mcal.DefineContainerMembers ();
1442 public override bool Define ()
1444 if (parts != null) {
1445 foreach (ClassPart part in parts) {
1446 if (!part.Define ())
1454 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1456 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1460 /// This function is based by a delegate to the FindMembers routine
1462 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1468 /// This filter is used by FindMembers, and we just keep
1469 /// a global for the filter to `AlwaysAccept'
1471 static MemberFilter accepting_filter;
1474 static TypeContainer ()
1476 accepting_filter = new MemberFilter (AlwaysAccept);
1479 public MethodInfo[] GetMethods ()
1481 ArrayList members = new ArrayList ();
1483 DefineMembers (null);
1485 if (methods != null) {
1486 int len = methods.Count;
1487 for (int i = 0; i < len; i++) {
1488 Method m = (Method) methods [i];
1490 members.Add (m.MethodBuilder);
1494 if (operators != null) {
1495 int len = operators.Count;
1496 for (int i = 0; i < len; i++) {
1497 Operator o = (Operator) operators [i];
1499 members.Add (o.OperatorMethodBuilder);
1503 if (properties != null) {
1504 int len = properties.Count;
1505 for (int i = 0; i < len; i++) {
1506 Property p = (Property) properties [i];
1508 if (p.GetBuilder != null)
1509 members.Add (p.GetBuilder);
1510 if (p.SetBuilder != null)
1511 members.Add (p.SetBuilder);
1515 if (indexers != null) {
1516 int len = indexers.Count;
1517 for (int i = 0; i < len; i++) {
1518 Indexer ix = (Indexer) indexers [i];
1520 if (ix.GetBuilder != null)
1521 members.Add (ix.GetBuilder);
1522 if (ix.SetBuilder != null)
1523 members.Add (ix.SetBuilder);
1527 if (events != null) {
1528 int len = events.Count;
1529 for (int i = 0; i < len; i++) {
1530 Event e = (Event) events [i];
1532 if (e.AddBuilder != null)
1533 members.Add (e.AddBuilder);
1534 if (e.RemoveBuilder != null)
1535 members.Add (e.RemoveBuilder);
1539 MethodInfo[] retMethods = new MethodInfo [members.Count];
1540 members.CopyTo (retMethods, 0);
1544 // Indicated whether container has StructLayout attribute set Explicit
1545 public virtual bool HasExplicitLayout {
1551 public override Type FindNestedType (string name)
1553 ArrayList [] lists = { types, enums, delegates, interfaces };
1555 for (int j = 0; j < lists.Length; ++j) {
1556 ArrayList list = lists [j];
1560 int len = list.Count;
1561 for (int i = 0; i < len; ++i) {
1562 DeclSpace ds = (DeclSpace) list [i];
1563 if (ds.Basename == name) {
1565 return ds.TypeBuilder;
1573 private void FindMembers_NestedTypes (int modflags,
1574 BindingFlags bf, MemberFilter filter, object criteria,
1575 ref ArrayList members)
1577 ArrayList [] lists = { types, enums, delegates, interfaces };
1579 for (int j = 0; j < lists.Length; ++j) {
1580 ArrayList list = lists [j];
1584 int len = list.Count;
1585 for (int i = 0; i < len; i++) {
1586 DeclSpace ds = (DeclSpace) list [i];
1588 if ((ds.ModFlags & modflags) == 0)
1591 TypeBuilder tb = ds.TypeBuilder;
1593 if (!(criteria is string) || ds.Basename.Equals (criteria))
1594 tb = ds.DefineType ();
1597 if (tb != null && (filter (tb, criteria) == true)) {
1598 if (members == null)
1599 members = new ArrayList ();
1608 /// This method returns the members of this type just like Type.FindMembers would
1609 /// Only, we need to use this for types which are _being_ defined because MS'
1610 /// implementation can't take care of that.
1613 // FIXME: return an empty static array instead of null, that cleans up
1614 // some code and is consistent with some coding conventions I just found
1618 // Notice that in various cases we check if our field is non-null,
1619 // something that would normally mean that there was a bug elsewhere.
1621 // The problem happens while we are defining p-invoke methods, as those
1622 // will trigger a FindMembers, but this happens before things are defined
1624 // Since the whole process is a no-op, it is fine to check for null here.
1626 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1627 MemberFilter filter, object criteria)
1629 ArrayList members = null;
1632 if ((bf & BindingFlags.Public) != 0)
1633 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1635 if ((bf & BindingFlags.NonPublic) != 0)
1636 modflags |= Modifiers.PRIVATE;
1638 int static_mask = 0, static_flags = 0;
1639 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1640 case BindingFlags.Static:
1641 static_mask = static_flags = Modifiers.STATIC;
1644 case BindingFlags.Instance:
1645 static_mask = Modifiers.STATIC;
1650 static_mask = static_flags = 0;
1654 Timer.StartTimer (TimerType.TcFindMembers);
1657 filter = accepting_filter;
1659 if ((mt & MemberTypes.Field) != 0) {
1660 if (fields != null) {
1661 int len = fields.Count;
1662 for (int i = 0; i < len; i++) {
1663 FieldMember f = (FieldMember) fields [i];
1665 if ((f.ModFlags & modflags) == 0)
1667 if ((f.ModFlags & static_mask) != static_flags)
1670 FieldBuilder fb = f.FieldBuilder;
1671 if (fb != null && filter (fb, criteria) == true) {
1672 if (members == null)
1673 members = new ArrayList ();
1680 if (constants != null) {
1681 int len = constants.Count;
1682 for (int i = 0; i < len; i++) {
1683 Const con = (Const) constants [i];
1685 if ((con.ModFlags & modflags) == 0)
1687 if ((con.ModFlags & static_mask) != static_flags)
1690 FieldBuilder fb = con.FieldBuilder;
1693 fb = con.FieldBuilder;
1695 if (fb != null && filter (fb, criteria) == true) {
1696 if (members == null)
1697 members = new ArrayList ();
1705 if ((mt & MemberTypes.Method) != 0) {
1706 if (methods != null) {
1707 int len = methods.Count;
1708 for (int i = 0; i < len; i++) {
1709 Method m = (Method) methods [i];
1711 if ((m.ModFlags & modflags) == 0)
1713 if ((m.ModFlags & static_mask) != static_flags)
1716 MethodBuilder mb = m.MethodBuilder;
1718 if (mb != null && filter (mb, criteria) == true) {
1719 if (members == null)
1720 members = new ArrayList ();
1727 if (operators != null) {
1728 int len = operators.Count;
1729 for (int i = 0; i < len; i++) {
1730 Operator o = (Operator) operators [i];
1732 if ((o.ModFlags & modflags) == 0)
1734 if ((o.ModFlags & static_mask) != static_flags)
1737 MethodBuilder ob = o.OperatorMethodBuilder;
1738 if (ob != null && filter (ob, criteria) == true) {
1739 if (members == null)
1740 members = new ArrayList ();
1747 if (properties != null) {
1748 int len = properties.Count;
1749 for (int i = 0; i < len; i++) {
1750 Property p = (Property) properties [i];
1752 if ((p.ModFlags & modflags) == 0)
1754 if ((p.ModFlags & static_mask) != static_flags)
1760 if (b != null && filter (b, criteria) == true) {
1761 if (members == null)
1762 members = new ArrayList ();
1768 if (b != null && filter (b, criteria) == true) {
1769 if (members == null)
1770 members = new ArrayList ();
1777 if (indexers != null) {
1778 int len = indexers.Count;
1779 for (int i = 0; i < len; i++) {
1780 Indexer ix = (Indexer) indexers [i];
1782 if ((ix.ModFlags & modflags) == 0)
1784 if ((ix.ModFlags & static_mask) != static_flags)
1790 if (b != null && filter (b, criteria) == true) {
1791 if (members == null)
1792 members = new ArrayList ();
1798 if (b != null && filter (b, criteria) == true) {
1799 if (members == null)
1800 members = new ArrayList ();
1808 if ((mt & MemberTypes.Event) != 0) {
1809 if (events != null) {
1810 int len = events.Count;
1811 for (int i = 0; i < len; i++) {
1812 Event e = (Event) events [i];
1814 if ((e.ModFlags & modflags) == 0)
1816 if ((e.ModFlags & static_mask) != static_flags)
1819 MemberInfo eb = e.EventBuilder;
1820 if (eb != null && filter (eb, criteria) == true) {
1821 if (members == null)
1822 members = new ArrayList ();
1824 members.Add (e.EventBuilder);
1830 if ((mt & MemberTypes.Property) != 0){
1831 if (properties != null) {
1832 int len = properties.Count;
1833 for (int i = 0; i < len; i++) {
1834 Property p = (Property) properties [i];
1836 if ((p.ModFlags & modflags) == 0)
1838 if ((p.ModFlags & static_mask) != static_flags)
1841 MemberInfo pb = p.PropertyBuilder;
1842 if (pb != null && filter (pb, criteria) == true) {
1843 if (members == null)
1844 members = new ArrayList ();
1846 members.Add (p.PropertyBuilder);
1851 if (indexers != null) {
1852 int len = indexers.Count;
1853 for (int i = 0; i < len; i++) {
1854 Indexer ix = (Indexer) indexers [i];
1856 if ((ix.ModFlags & modflags) == 0)
1858 if ((ix.ModFlags & static_mask) != static_flags)
1861 MemberInfo ib = ix.PropertyBuilder;
1862 if (ib != null && filter (ib, criteria) == true) {
1863 if (members == null)
1864 members = new ArrayList ();
1866 members.Add (ix.PropertyBuilder);
1872 if ((mt & MemberTypes.NestedType) != 0)
1873 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1875 if ((mt & MemberTypes.Constructor) != 0){
1876 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1877 int len = instance_constructors.Count;
1878 for (int i = 0; i < len; i++) {
1879 Constructor c = (Constructor) instance_constructors [i];
1881 ConstructorBuilder cb = c.ConstructorBuilder;
1882 if (cb != null && filter (cb, criteria) == true) {
1883 if (members == null)
1884 members = new ArrayList ();
1891 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1892 ConstructorBuilder cb =
1893 default_static_constructor.ConstructorBuilder;
1895 if (cb != null && filter (cb, criteria) == true) {
1896 if (members == null)
1897 members = new ArrayList ();
1905 // Lookup members in base if requested.
1907 if ((bf & BindingFlags.DeclaredOnly) == 0) {
1908 if (TypeBuilder.BaseType != null) {
1909 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1910 if (list.Count > 0) {
1911 if (members == null)
1912 members = new ArrayList ();
1914 members.AddRange (list);
1917 if (ifaces != null) {
1918 foreach (Type base_type in ifaces) {
1919 MemberList list = TypeContainer.FindMembers (base_type, mt, bf, filter, criteria);
1921 if (list.Count > 0) {
1922 if (members == null)
1923 members = new ArrayList ();
1924 members.AddRange (list);
1930 Timer.StopTimer (TimerType.TcFindMembers);
1932 if (members == null)
1933 return MemberList.Empty;
1935 return new MemberList (members);
1938 public override MemberCache MemberCache {
1940 return member_cache;
1944 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1945 MemberFilter filter, object criteria)
1947 DeclSpace ds = TypeManager.LookupDeclSpace (t);
1950 return ds.FindMembers (mt, bf, filter, criteria);
1952 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1957 // FindMethods will look for methods not only in the type `t', but in
1958 // any interfaces implemented by the type.
1960 public static MethodInfo [] FindMethods (Type t, BindingFlags bf,
1961 MemberFilter filter, object criteria)
1967 /// Emits the values for the constants
1969 public void EmitConstants ()
1971 if (constants != null)
1972 foreach (Const con in constants)
1977 void CheckMemberUsage (MemberCoreArrayList al, string member_type)
1982 foreach (MemberCore mc in al) {
1983 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
1987 Report.Warning (169, mc.Location, "The private {0} '{1}' is never used", member_type, mc.GetSignatureForError ());
1992 public virtual void VerifyMembers ()
1995 // Check for internal or private fields that were never assigned
1997 if (RootContext.WarningLevel >= 3) {
1998 CheckMemberUsage (properties, "property");
1999 CheckMemberUsage (methods, "method");
2000 CheckMemberUsage (constants, "constant");
2002 if (fields != null){
2003 foreach (FieldMember f in fields) {
2004 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2008 Report.Warning (169, f.Location, "The private field '{0}' is never used", f.GetSignatureForError ());
2013 // Only report 649 on level 4
2015 if (RootContext.WarningLevel < 4)
2018 if ((f.status & Field.Status.ASSIGNED) != 0)
2021 Report.Warning (649, f.Location, "Field '{0}' is never assigned to, and will always have its default value '{1}'", f.GetSignatureForError (), "");
2028 /// Emits the code, this step is performed after all
2029 /// the types, enumerations, constructors
2031 public void EmitType ()
2033 if (OptAttributes != null)
2034 OptAttributes.Emit (ec, this);
2037 // Structs with no fields need to have at least one byte.
2038 // The right thing would be to set the PackingSize in a DefineType
2039 // but there are no functions that allow interfaces *and* the size to
2043 if ((Kind == Kind.Struct) && !have_nonstatic_fields){
2044 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2045 FieldAttributes.Private);
2047 if (HasExplicitLayout){
2048 object [] ctor_args = new object [1];
2051 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2052 TypeManager.field_offset_attribute_ctor, ctor_args);
2053 fb.SetCustomAttribute (cba);
2059 if (instance_constructors != null) {
2060 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsCompliaceRequired (this)) {
2061 bool has_compliant_args = false;
2063 foreach (Constructor c in instance_constructors) {
2066 if (has_compliant_args)
2069 has_compliant_args = c.HasCompliantArgs;
2071 if (!has_compliant_args)
2072 Report.Error (3015, Location, "'{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2074 foreach (Constructor c in instance_constructors)
2079 // Can not continue if constants are broken
2081 if (Report.Errors > 0)
2084 if (default_static_constructor != null)
2085 default_static_constructor.Emit ();
2087 if (methods != null)
2088 foreach (Method m in methods)
2091 if (operators != null)
2092 foreach (Operator o in operators)
2095 if (properties != null)
2096 foreach (Property p in properties)
2099 if (indexers != null){
2104 foreach (FieldMember f in fields)
2107 if (events != null){
2108 foreach (Event e in Events)
2112 if (delegates != null) {
2113 foreach (Delegate d in Delegates) {
2118 if (enums != null) {
2119 foreach (Enum e in enums) {
2124 if (parts != null) {
2125 foreach (ClassPart part in parts)
2129 if ((Pending != null) && !(this is ClassPart))
2130 if (Pending.VerifyPendingMethods ())
2133 if (iterators != null)
2134 foreach (Iterator iterator in iterators)
2135 iterator.EmitType ();
2137 // if (types != null)
2138 // foreach (TypeContainer tc in types)
2142 public override void CloseType ()
2144 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2148 caching_flags |= Flags.CloseTypeCreated;
2149 TypeBuilder.CreateType ();
2150 } catch (TypeLoadException){
2152 // This is fine, the code still created the type
2154 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2155 // Console.WriteLine (e.Message);
2157 Console.WriteLine ("In type: " + Name);
2162 foreach (Enum en in Enums)
2166 foreach (TypeContainer tc in Types)
2167 if (tc.Kind == Kind.Struct)
2170 foreach (TypeContainer tc in Types)
2171 if (tc.Kind != Kind.Struct)
2175 if (Delegates != null)
2176 foreach (Delegate d in Delegates)
2179 if (Iterators != null)
2180 foreach (Iterator i in Iterators)
2188 initialized_fields = null;
2189 initialized_static_fields = null;
2198 default_constructor = null;
2199 default_static_constructor = null;
2201 OptAttributes = null;
2204 member_cache = null;
2207 // TODO: make it obsolete and use GetSignatureForError
2208 public string MakeName (string n)
2210 return "`" + Name + "." + n + "'";
2214 // Performs the validation on a Method's modifiers (properties have
2215 // the same properties).
2217 public bool MethodModifiersValid (MemberCore mc)
2219 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2220 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2221 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2223 int flags = mc.ModFlags;
2226 // At most one of static, virtual or override
2228 if ((flags & Modifiers.STATIC) != 0){
2229 if ((flags & vao) != 0){
2230 Report.Error (112, mc.Location, "static method '{0}' can not be marked as virtual, abstract or override",
2231 GetSignatureForError ());
2236 if (Kind == Kind.Struct){
2237 if ((flags & va) != 0){
2238 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2243 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2244 Report.Error (113, mc.Location, "'{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ());
2249 // If the declaration includes the abstract modifier, then the
2250 // declaration does not include static, virtual or extern
2252 if ((flags & Modifiers.ABSTRACT) != 0){
2253 if ((flags & Modifiers.EXTERN) != 0){
2255 180, mc.Location, "'{0}' can not be both abstract and extern", mc.GetSignatureForError ());
2259 if ((flags & Modifiers.SEALED) != 0) {
2260 Report.Error (502, mc.Location, "'{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2264 if ((flags & Modifiers.VIRTUAL) != 0){
2265 Report.Error (503, mc.Location, "'{0}' can not be both abstract and virtual", mc.GetSignatureForError ());
2269 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2270 Report.Error (513, mc.Location, "'{0}' is abstract but its container class is not", mc.GetSignatureForError ());
2275 if ((flags & Modifiers.PRIVATE) != 0){
2276 if ((flags & vao) != 0){
2277 Report.Error (621, mc.Location, "'{0}' virtual or abstract members can not be private", mc.GetSignatureForError ());
2282 if ((flags & Modifiers.SEALED) != 0){
2283 if ((flags & Modifiers.OVERRIDE) == 0){
2284 Report.Error (238, mc.Location, "'{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2292 public bool UserDefinedStaticConstructor {
2294 return default_static_constructor != null;
2298 public Constructor DefaultStaticConstructor {
2299 get { return default_static_constructor; }
2302 protected override bool VerifyClsCompliance (DeclSpace ds)
2304 if (!base.VerifyClsCompliance (ds))
2309 Type base_type = TypeBuilder.BaseType;
2310 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2311 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2314 if (!Parent.IsClsCompliaceRequired (ds)) {
2315 Report.Error (3018, Location, "'{0}' cannot be marked as CLS-Compliant because it is a member of non CLS-Compliant type '{1}'",
2316 GetSignatureForError (), Parent.GetSignatureForError ());
2323 /// Checks whether container name is CLS Compliant
2325 void VerifyClsName ()
2327 Hashtable base_members = base_cache == null ?
2329 base_cache.GetPublicMembers ();
2330 Hashtable this_members = new Hashtable ();
2332 foreach (DictionaryEntry entry in defined_names) {
2333 MemberCore mc = (MemberCore)entry.Value;
2334 if (!mc.IsClsCompliaceRequired (this))
2337 string name = (string)entry.Key;
2338 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2340 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2341 object found = base_members [lcase];
2342 if (found == null) {
2343 found = this_members [lcase];
2344 if (found == null) {
2345 this_members.Add (lcase, mc);
2350 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2353 if (found is MemberInfo) {
2354 if (basename == ((MemberInfo)found).Name)
2356 Report.SymbolRelatedToPreviousError ((MemberInfo)found);
2358 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2360 Report.Error (3005, mc.Location, "Identifier '{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2366 /// Performs checks for an explicit interface implementation. First it
2367 /// checks whether the `interface_type' is a base inteface implementation.
2368 /// Then it checks whether `name' exists in the interface type.
2370 public virtual bool VerifyImplements (Type interface_type, string full,
2371 string name, Location loc)
2375 if (ifaces != null){
2376 foreach (Type t in ifaces){
2377 if (t == interface_type){
2385 Report.Error (540, loc, "`{0}': containing class does not implement interface `{1}'",
2386 full, interface_type.FullName);
2393 protected override void VerifyObsoleteAttribute()
2395 CheckUsageOfObsoleteAttribute (ptype);
2400 foreach (Type iface in ifaces) {
2401 CheckUsageOfObsoleteAttribute (iface);
2410 string IMemberContainer.Name {
2416 Type IMemberContainer.Type {
2422 MemberCache IMemberContainer.MemberCache {
2424 return member_cache;
2428 bool IMemberContainer.IsInterface {
2430 return Kind == Kind.Interface;
2434 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2436 return FindMembers (mt, bf | BindingFlags.DeclaredOnly, null, null);
2440 // Generates xml doc comments (if any), and if required,
2441 // handle warning report.
2443 internal override void GenerateDocComment (DeclSpace ds)
2445 DocUtil.GenerateTypeDocComment (this, ds);
2448 public override string DocCommentHeader {
2449 get { return "T:"; }
2452 public virtual MemberCache BaseCache {
2454 if (base_cache != null)
2456 if (TypeBuilder.BaseType != null)
2457 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2458 if (TypeBuilder.IsInterface)
2459 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2465 public class PartialContainer : TypeContainer {
2467 public readonly Namespace Namespace;
2468 public readonly int OriginalModFlags;
2469 public readonly int AllowedModifiers;
2470 public readonly TypeAttributes DefaultTypeAttributes;
2472 static PartialContainer Create (NamespaceEntry ns, TypeContainer parent,
2473 MemberName member_name, int mod_flags, Kind kind,
2476 PartialContainer pc;
2477 DeclSpace ds = RootContext.Tree.GetDecl (member_name);
2479 pc = ds as PartialContainer;
2483 260, ds.Location, "Missing partial modifier " +
2484 "on declaration of type `{0}'; another " +
2485 "partial implementation of this type exists",
2486 member_name.GetPartialName());
2488 Report.LocationOfPreviousError (loc);
2492 if (pc.Kind != kind) {
2494 261, loc, "Partial declarations of `{0}' " +
2495 "must be all classes, all structs or " +
2496 "all interfaces", member_name.GetPartialName ());
2500 if (pc.OriginalModFlags != mod_flags) {
2502 262, loc, "Partial declarations of `{0}' " +
2503 "have conflicting accessibility modifiers",
2504 member_name.GetPartialName ());
2511 if (parent is ClassPart)
2512 parent = ((ClassPart) parent).PartialContainer;
2514 pc = new PartialContainer (ns.NS, parent, member_name, mod_flags, kind, loc);
2515 RootContext.Tree.RecordDecl (ns.NS, member_name, pc);
2517 if (kind == Kind.Interface)
2518 parent.AddInterface (pc);
2519 else if (kind == Kind.Class || kind == Kind.Struct)
2520 parent.AddClassOrStruct (pc);
2522 throw new InvalidOperationException ();
2527 public static ClassPart CreatePart (NamespaceEntry ns, TypeContainer parent,
2528 MemberName name, int mod, Attributes attrs,
2529 Kind kind, Location loc)
2531 PartialContainer pc = Create (ns, parent, name, mod, kind, loc);
2533 // An error occured; create a dummy container, but don't
2535 pc = new PartialContainer (ns.NS, parent, name, mod, kind, loc);
2538 ClassPart part = new ClassPart (ns, pc, parent, mod, attrs, kind, loc);
2543 protected PartialContainer (Namespace ns, TypeContainer parent,
2544 MemberName name, int mod, Kind kind, Location l)
2545 : base (null, parent, name, null, kind, l)
2547 this.Namespace = ns;
2551 AllowedModifiers = Class.AllowedModifiers;
2552 DefaultTypeAttributes = Class.DefaultTypeAttributes;
2556 AllowedModifiers = Struct.AllowedModifiers;
2557 DefaultTypeAttributes = Struct.DefaultTypeAttributes;
2560 case Kind.Interface:
2561 AllowedModifiers = Interface.AllowedModifiers;
2562 DefaultTypeAttributes = Interface.DefaultTypeAttributes;
2566 throw new InvalidOperationException ();
2570 if (parent.Parent == null)
2571 accmods = Modifiers.INTERNAL;
2573 accmods = Modifiers.PRIVATE;
2575 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2576 this.OriginalModFlags = mod;
2579 public override PendingImplementation GetPendingImplementations ()
2581 return PendingImplementation.GetPendingImplementations (this);
2584 protected override TypeAttributes TypeAttr {
2586 return base.TypeAttr | DefaultTypeAttributes;
2591 public class ClassPart : TypeContainer, IMemberContainer {
2592 public readonly PartialContainer PartialContainer;
2593 public readonly bool IsPartial;
2595 public ClassPart (NamespaceEntry ns, PartialContainer pc, TypeContainer parent,
2596 int mod, Attributes attrs, Kind kind, Location l)
2597 : base (ns, parent, pc.MemberName, attrs, kind, l)
2599 this.PartialContainer = pc;
2600 this.IsPartial = true;
2603 if (parent == null || parent == RootContext.Tree.Types)
2604 accmods = Modifiers.INTERNAL;
2606 accmods = Modifiers.PRIVATE;
2608 this.ModFlags = Modifiers.Check (pc.AllowedModifiers, mod, accmods, l);
2611 public override PendingImplementation GetPendingImplementations ()
2613 return PartialContainer.Pending;
2616 public override bool VerifyImplements (Type interface_type, string full,
2617 string name, Location loc)
2619 return PartialContainer.VerifyImplements (
2620 interface_type, full, name, loc);
2624 public override void RegisterFieldForInitialization (FieldMember field)
2626 PartialContainer.RegisterFieldForInitialization (field);
2629 public override bool EmitFieldInitializers (EmitContext ec)
2631 return PartialContainer.EmitFieldInitializers (ec);
2634 public override Type FindNestedType (string name)
2636 return PartialContainer.FindNestedType (name);
2639 public override MemberCache BaseCache {
2641 return PartialContainer.BaseCache;
2645 public override TypeBuilder DefineType ()
2647 throw new InternalErrorException ("Should not get here");
2652 public abstract class ClassOrStruct : TypeContainer {
2653 bool has_explicit_layout = false;
2654 ListDictionary declarative_security;
2656 public ClassOrStruct (NamespaceEntry ns, TypeContainer parent,
2657 MemberName name, Attributes attrs, Kind kind,
2659 : base (ns, parent, name, attrs, kind, l)
2663 public override PendingImplementation GetPendingImplementations ()
2665 return PendingImplementation.GetPendingImplementations (this);
2668 public override bool HasExplicitLayout {
2670 return has_explicit_layout;
2674 public override void VerifyMembers ()
2676 base.VerifyMembers ();
2678 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2679 foreach (Event e in events){
2681 Report.Warning (67, e.Location, "The event '{0}' is never used", e.GetSignatureForError ());
2686 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2688 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2689 if (declarative_security == null)
2690 declarative_security = new ListDictionary ();
2692 a.ExtractSecurityPermissionSet (declarative_security);
2696 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit)
2697 has_explicit_layout = true;
2699 base.ApplyAttributeBuilder (a, cb);
2702 public override void Emit()
2706 if (declarative_security != null) {
2707 foreach (DictionaryEntry de in declarative_security) {
2708 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2715 /// Class handles static classes declaration
2717 public sealed class StaticClass: Class {
2718 public StaticClass (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2719 Attributes attrs, Location l)
2720 : base (ns, parent, name, mod, attrs, l)
2722 if (RootContext.Version == LanguageVersion.ISO_1) {
2723 Report.FeatureIsNotStandardized (l, "static classes");
2727 protected override int AllowedModifiersProp {
2729 return Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE |
2730 Modifiers.STATIC | Modifiers.UNSAFE;
2734 protected override void DefineContainerMembers (MemberCoreArrayList list)
2739 foreach (MemberCore m in list) {
2740 if (m is Operator) {
2741 Report.Error (715, m.Location, "'{0}': static classes cannot contain user-defined operators", m.GetSignatureForError (this));
2745 if ((m.ModFlags & Modifiers.PROTECTED) != 0)
2746 Report.Warning (628, 4, m.Location, "'{0}': new protected member declared in static class", m.GetSignatureForError (this));
2749 Report.Error (720, m.Location, "'{0}': cannot declare indexers in a static class", m.GetSignatureForError (this));
2753 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2756 if (m is Constructor) {
2757 Report.Error (710, m.Location, "'{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2761 if (m is Destructor) {
2762 Report.Error (711, m.Location, "'{0}': Static class cannot contain destructor", GetSignatureForError ());
2766 Report.Error (708, m.Location, "'{0}': cannot declare instance members in a static class", m.GetSignatureForError (this));
2769 base.DefineContainerMembers (list);
2772 public override TypeBuilder DefineType()
2774 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2775 Report.Error (441, Location, "'{0}': a class cannot be both static and sealed", GetSignatureForError ());
2779 TypeBuilder tb = base.DefineType ();
2783 if (ptype != TypeManager.object_type) {
2784 Report.Error (713, Location, "Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object", GetSignatureForError (), TypeManager.CSharpName (ptype));
2788 if (ifaces != null) {
2789 foreach (Type t in ifaces)
2790 Report.SymbolRelatedToPreviousError (t);
2791 Report.Error (714, Location, "'{0}': static classes cannot implement interfaces", GetSignatureForError ());
2796 protected override TypeAttributes TypeAttr {
2798 return base.TypeAttr | TypeAttributes.Abstract | TypeAttributes.Sealed;
2803 public class Class : ClassOrStruct {
2804 // TODO: remove this and use only AllowedModifiersProp to fix partial classes bugs
2805 public const int AllowedModifiers =
2808 Modifiers.PROTECTED |
2809 Modifiers.INTERNAL |
2811 Modifiers.ABSTRACT |
2815 bool WasTransitError;
2817 public Class (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
2818 Attributes attrs, Location l)
2819 : base (ns, parent, name, attrs, Kind.Class, l)
2821 this.ModFlags = mod;
2824 virtual protected int AllowedModifiersProp {
2826 return AllowedModifiers;
2830 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2832 if (a.Type == TypeManager.attribute_usage_type) {
2833 if (ptype != TypeManager.attribute_type && !ptype.IsSubclassOf (TypeManager.attribute_type) &&
2834 TypeBuilder.FullName != "System.Attribute") {
2835 Report.Error (641, a.Location, "Attribute '{0}' is only valid on classes derived from System.Attribute", a.Name);
2839 if (a.Type == TypeManager.conditional_attribute_type &&
2840 !(ptype == TypeManager.attribute_type || ptype.IsSubclassOf (TypeManager.attribute_type))) {
2841 Report.Error (1689, a.Location, "Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2845 if (AttributeTester.IsAttributeExcluded (a.Type))
2848 base.ApplyAttributeBuilder (a, cb);
2851 public const TypeAttributes DefaultTypeAttributes =
2852 TypeAttributes.AutoLayout | TypeAttributes.Class;
2854 public override TypeBuilder DefineType()
2857 if (WasTransitError)
2859 throw new CircularDepException (this);
2862 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2863 Report.Error (418, Location, "'{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2867 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2868 ModFlags = Modifiers.Check (AllowedModifiersProp, ModFlags, accmods, Location);
2871 return base.DefineType ();
2873 catch (CircularDepException e) {
2874 Report.SymbolRelatedToPreviousError (e.Container);
2875 Report.Error (146, Location, "Circular base class dependency involving '{0}' and '{1}'",
2876 GetSignatureForError (), e.Container.GetSignatureForError ());
2877 WasTransitError = true;
2882 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2883 /// Valid only for attribute classes.
2884 public bool IsExcluded ()
2886 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2887 return (caching_flags & Flags.Excluded) != 0;
2889 caching_flags &= ~Flags.Excluded_Undetected;
2891 if (OptAttributes == null)
2894 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
2899 foreach (Attribute a in attrs) {
2900 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
2901 if (RootContext.AllDefines.Contains (condition))
2905 caching_flags |= Flags.Excluded;
2910 // FIXME: How do we deal with the user specifying a different
2913 protected override TypeAttributes TypeAttr {
2915 return base.TypeAttr | DefaultTypeAttributes;
2920 public class Struct : ClassOrStruct {
2922 // Modifiers allowed in a struct declaration
2924 public const int AllowedModifiers =
2927 Modifiers.PROTECTED |
2928 Modifiers.INTERNAL |
2932 public Struct (NamespaceEntry ns, TypeContainer parent, MemberName name,
2933 int mod, Attributes attrs, Location l)
2934 : base (ns, parent, name, attrs, Kind.Struct, l)
2938 if (parent.Parent == null)
2939 accmods = Modifiers.INTERNAL;
2941 accmods = Modifiers.PRIVATE;
2943 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
2945 this.ModFlags |= Modifiers.SEALED;
2948 public const TypeAttributes DefaultTypeAttributes =
2949 TypeAttributes.SequentialLayout |
2950 TypeAttributes.Sealed |
2951 TypeAttributes.BeforeFieldInit;
2954 // FIXME: Allow the user to specify a different set of attributes
2955 // in some cases (Sealed for example is mandatory for a class,
2956 // but what SequentialLayout can be changed
2958 protected override TypeAttributes TypeAttr {
2960 return base.TypeAttr | DefaultTypeAttributes;
2964 public override TypeBuilder DefineType()
2968 throw new CircularDepException (this);
2972 return base.DefineType ();
2974 catch (CircularDepException e) {
2976 Report.SymbolRelatedToPreviousError (this);
2977 Error_TypeInListIsNotInterface (e.Container.Location, GetSignatureForError ());
2986 public class Interface : TypeContainer, IMemberContainer {
2988 bool WasTransitError;
2991 /// Modifiers allowed in a class declaration
2993 public const int AllowedModifiers =
2996 Modifiers.PROTECTED |
2997 Modifiers.INTERNAL |
3001 public Interface (NamespaceEntry ns, TypeContainer parent, MemberName name, int mod,
3002 Attributes attrs, Location l)
3003 : base (ns, parent, name, attrs, Kind.Interface, l)
3007 if (parent.Parent == null)
3008 accmods = Modifiers.INTERNAL;
3010 accmods = Modifiers.PRIVATE;
3012 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, l);
3015 public override PendingImplementation GetPendingImplementations ()
3020 public const TypeAttributes DefaultTypeAttributes =
3021 TypeAttributes.AutoLayout |
3022 TypeAttributes.Abstract |
3023 TypeAttributes.Interface;
3025 protected override TypeAttributes TypeAttr {
3027 return base.TypeAttr | DefaultTypeAttributes;
3031 public override TypeBuilder DefineType()
3034 if (WasTransitError)
3036 throw new CircularDepException (this);
3040 return base.DefineType ();
3042 catch (CircularDepException e) {
3043 Report.SymbolRelatedToPreviousError (e.Container);
3044 Report.Error (529, Location, "Inherited interface '{0}' causes a cycle in the interface hierarchy of '{1}'",
3045 e.Container.GetSignatureForError (), GetSignatureForError ());
3046 WasTransitError = true;
3051 protected override bool VerifyClsCompliance (DeclSpace ds)
3053 if (!base.VerifyClsCompliance (ds))
3056 if (ifaces != null) {
3057 foreach (Type t in ifaces) {
3058 if (AttributeTester.IsClsCompliant (t))
3061 Report.SymbolRelatedToPreviousError (t);
3062 Report.Warning (3027, 1, Location, "'{0}' is not CLS-compliant because base interface '{1}' is not CLS-compliant",
3063 GetSignatureForError (), TypeManager.CSharpName (t));
3071 public abstract class MethodCore : MemberBase {
3072 public readonly Parameters Parameters;
3073 protected ToplevelBlock block;
3076 // Parameters, cached for semantic analysis.
3078 protected InternalParameters parameter_info;
3079 protected Type [] parameter_types;
3081 // Whether this is an operator method.
3082 public bool IsOperator;
3085 // The method we're overriding if this is an override method.
3087 protected MethodInfo base_method = null;
3089 static string[] attribute_targets = new string [] { "method", "return" };
3091 public MethodCore (TypeContainer parent, Expression type, int mod,
3092 int allowed_mod, bool is_interface, MemberName name,
3093 Attributes attrs, Parameters parameters, Location loc)
3094 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name,
3097 Parameters = parameters;
3098 IsInterface = is_interface;
3102 // Returns the System.Type array for the parameters of this method
3104 public Type [] ParameterTypes {
3106 return parameter_types;
3110 public InternalParameters ParameterInfo
3113 return parameter_info;
3117 public ToplevelBlock Block {
3127 protected override bool CheckBase ()
3129 if (!base.CheckBase ())
3132 // Check whether arguments were correct.
3133 if (!DoDefineParameters ())
3136 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3142 // Is null for System.Object while compiling corlib and base interfaces
3143 if (Parent.BaseCache == null) {
3144 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3145 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3150 Type base_ret_type = null;
3151 base_method = FindOutBaseMethod (Parent, ref base_ret_type);
3153 // method is override
3154 if (base_method != null) {
3156 if (!CheckMethodAgainstBase ())
3159 if ((ModFlags & Modifiers.NEW) == 0) {
3160 if (MemberType != TypeManager.TypeToCoreType (base_ret_type)) {
3161 Report.SymbolRelatedToPreviousError (base_method);
3162 if (this is PropertyBase) {
3163 Report.Error (1715, Location, "'{0}': type must be '{1}' to match overridden member '{2}'",
3164 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3167 Report.Error (508, Location, GetSignatureForError (Parent) + ": cannot " +
3168 "change return type when overriding inherited member");
3173 if (base_method.IsAbstract && !IsInterface) {
3174 Report.SymbolRelatedToPreviousError (base_method);
3175 Report.Error (533, Location, "'{0}' hides inherited abstract member", GetSignatureForError (Parent));
3180 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3181 Report.Error (561, Location, "'{0}': cannot override '{1}' because it is a special compiler-generated method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (base_method));
3185 if (RootContext.WarningLevel > 2) {
3186 if (Name == "Equals" && parameter_types.Length == 1 && parameter_types [0] == TypeManager.object_type)
3187 Parent.Methods.HasEquals = true;
3188 else if (Name == "GetHashCode" && parameter_types.Length == 0)
3189 Parent.Methods.HasGetHashCode = true;
3192 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3193 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3195 EmitContext ec = new EmitContext (this.Parent, this.Parent, Location, null, null, ModFlags, false);
3196 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type, ec)) {
3197 Report.SymbolRelatedToPreviousError (base_method);
3198 Report.Warning (672, 1, Location, "Member '{0}' overrides obsolete member. Add the Obsolete attribute to '{0}'", GetSignatureForError (Parent));
3205 MemberInfo conflict_symbol = Parent.FindBaseMemberWithSameName (Name, !(this is Property));
3206 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3207 if (conflict_symbol != null) {
3208 Report.SymbolRelatedToPreviousError (conflict_symbol);
3209 if (this is PropertyBase)
3210 Report.Error (544, Location, "'{0}': cannot override because '{1}' is not a property", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3212 Report.Error (505, Location, "'{0}': cannot override because '{1}' is not a method", GetSignatureForError (Parent), TypeManager.GetFullNameSignature (conflict_symbol));
3214 Report.Error (115, Location, "'{0}': no suitable methods found to override", GetSignatureForError (Parent));
3218 if (conflict_symbol == null) {
3219 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3220 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
3225 if ((ModFlags & Modifiers.NEW) == 0) {
3226 if (this is Method && conflict_symbol is MethodBase)
3229 Report.SymbolRelatedToPreviousError (conflict_symbol);
3230 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3238 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3239 // that have been defined.
3241 // `name' is the user visible name for reporting errors (this is used to
3242 // provide the right name regarding method names and properties)
3244 bool CheckMethodAgainstBase ()
3248 // TODO: replace with GetSignatureForError
3249 string name = base_method.DeclaringType.Name + "." + base_method.Name;
3251 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3252 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3254 506, Location, Parent.MakeName (Name) +
3255 ": cannot override inherited member `" +
3256 name + "' because it is not " +
3257 "virtual, abstract or override");
3261 // Now we check that the overriden method is not final
3263 if (base_method.IsFinal) {
3264 Report.SymbolRelatedToPreviousError (base_method);
3265 Report.Error (239, Location, "'{0}': cannot override inherited member '{1}' because it is sealed",
3266 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3270 // Check that the permissions are not being changed
3272 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3273 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3275 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3276 Error_CannotChangeAccessModifiers (Parent, base_method, name);
3281 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3282 ModFlags |= Modifiers.NEW;
3283 Report.SymbolRelatedToPreviousError (base_method);
3284 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3285 if (RootContext.WarningLevel >= 2)
3286 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));
3288 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
3294 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3296 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3298 // when overriding protected internal, the method can be declared
3299 // protected internal only within the same assembly
3302 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3303 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3305 // assemblies differ - report an error
3309 } else if (thisp != base_classp) {
3311 // same assembly, but other attributes differ - report an error
3316 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3318 // if it's not "protected internal", it must be "protected"
3322 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3324 // protected within the same assembly - an error
3327 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3328 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3330 // protected ok, but other attributes differ - report an error
3336 return (thisp == base_classp);
3340 void Error_CannotChangeAccessModifiers (TypeContainer parent, MethodInfo base_method, string name)
3343 // FIXME: report the old/new permissions?
3346 507, Location, parent.MakeName (Name) +
3347 ": can't change the access modifiers when overriding inherited " +
3348 "member `" + name + "'");
3351 protected static string Error722 {
3353 return "'{0}': static types cannot be used as return types";
3358 /// For custom member duplication search in a container
3360 protected abstract bool CheckForDuplications ();
3363 /// Gets base method and its return type
3365 protected abstract MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type);
3367 protected virtual bool DoDefineParameters ()
3369 EmitContext ec = Parent.EmitContext;
3371 throw new InternalErrorException ("DoDefineParameters invoked too early");
3373 bool old_unsafe = ec.InUnsafe;
3374 ec.InUnsafe = InUnsafe;
3375 // Check if arguments were correct
3376 parameter_types = Parameters.GetParameterInfo (ec);
3377 ec.InUnsafe = old_unsafe;
3379 if ((parameter_types == null) ||
3380 !CheckParameters (Parent, parameter_types))
3383 parameter_info = new InternalParameters (parameter_types, Parameters);
3385 Parameter array_param = Parameters.ArrayParameter;
3386 if ((array_param != null) &&
3387 (!array_param.ParameterType.IsArray ||
3388 (array_param.ParameterType.GetArrayRank () != 1))) {
3389 Report.Error (225, Location, "params parameter has to be a single dimensional array");
3396 public override string[] ValidAttributeTargets {
3398 return attribute_targets;
3402 protected override bool VerifyClsCompliance (DeclSpace ds)
3404 if (!base.VerifyClsCompliance (ds)) {
3405 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly (ds) && ds.IsClsCompliaceRequired (ds)) {
3406 Report.Error (3011, Location, "'{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3411 if (Parameters.HasArglist) {
3412 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3415 if (!AttributeTester.IsClsCompliant (MemberType)) {
3416 if (this is PropertyBase)
3417 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3418 GetSignatureForError ());
3420 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant",
3421 GetSignatureForError ());
3424 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
3429 protected bool IsDuplicateImplementation (MethodCore method)
3431 if ((method == this) || (method.Name != Name))
3434 Type[] param_types = method.ParameterTypes;
3435 if (param_types == null)
3438 if (param_types.Length != ParameterTypes.Length)
3441 for (int i = 0; i < param_types.Length; i++)
3442 if (param_types [i] != ParameterTypes [i])
3445 // TODO: make operator compatible with MethodCore to avoid this
3446 if (this is Operator && method is Operator) {
3447 if (MemberType != method.MemberType)
3452 // Try to report 663: method only differs on out/ref
3454 ParameterData info = ParameterInfo;
3455 ParameterData other_info = method.ParameterInfo;
3456 for (int i = 0; i < info.Count; i++){
3457 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3458 Report.Error (663, Location, "Overload method only differs in parameter modifier");
3463 Report.SymbolRelatedToPreviousError (method);
3464 if (this is Operator && method is Operator)
3465 Report.Error (557, Location, "Duplicate user-defined conversion in type '{0}'", Parent.Name);
3467 Report.Error (111, Location, TypeContainer.Error111, Parent.Name, Name);
3471 public override bool IsUsed
3482 // Returns a string that represents the signature for this
3483 // member which should be used in XML documentation.
3485 public override string GetDocCommentName (DeclSpace ds)
3487 return DocUtil.GetMethodDocCommentName (this, ds);
3491 // Raised (and passed an XmlElement that contains the comment)
3492 // when GenerateDocComment is writing documentation expectedly.
3494 // FIXME: with a few effort, it could be done with XmlReader,
3495 // that means removal of DOM use.
3497 internal override void OnGenerateDocComment (DeclSpace ds, XmlElement el)
3499 DocUtil.OnMethodGenerateDocComment (this, ds, el);
3503 // Represents header string for documentation comment.
3505 public override string DocCommentHeader {
3506 get { return "M:"; }
3509 protected override void VerifyObsoleteAttribute()
3511 base.VerifyObsoleteAttribute ();
3513 if (parameter_types == null)
3516 foreach (Type type in parameter_types) {
3517 CheckUsageOfObsoleteAttribute (type);
3522 public class SourceMethod : ISourceMethod
3524 TypeContainer container;
3527 protected SourceMethod (TypeContainer container, MethodBase builder,
3528 ISourceFile file, Location start, Location end)
3530 this.container = container;
3531 this.builder = builder;
3533 CodeGen.SymbolWriter.OpenMethod (
3534 file, this, start.Row, 0, end.Row, 0);
3537 public string Name {
3538 get { return builder.Name; }
3541 public int NamespaceID {
3542 get { return container.NamespaceEntry.SymbolFileID; }
3547 if (builder is MethodBuilder)
3548 return ((MethodBuilder) builder).GetToken ().Token;
3549 else if (builder is ConstructorBuilder)
3550 return ((ConstructorBuilder) builder).GetToken ().Token;
3552 throw new NotSupportedException ();
3556 public void CloseMethod ()
3558 if (CodeGen.SymbolWriter != null)
3559 CodeGen.SymbolWriter.CloseMethod ();
3562 public static SourceMethod Create (TypeContainer parent,
3563 MethodBase builder, Block block)
3565 if (CodeGen.SymbolWriter == null)
3570 Location start_loc = block.StartLocation;
3571 if (Location.IsNull (start_loc))
3574 Location end_loc = block.EndLocation;
3575 if (Location.IsNull (end_loc))
3578 ISourceFile file = start_loc.SourceFile;
3582 return new SourceMethod (
3583 parent, builder, file, start_loc, end_loc);
3587 public class Method : MethodCore, IIteratorContainer, IMethodData {
3588 public MethodBuilder MethodBuilder;
3589 public MethodData MethodData;
3590 ReturnParameter return_attributes;
3591 ListDictionary declarative_security;
3594 /// Modifiers allowed in a class declaration
3596 const int AllowedModifiers =
3599 Modifiers.PROTECTED |
3600 Modifiers.INTERNAL |
3605 Modifiers.OVERRIDE |
3606 Modifiers.ABSTRACT |
3608 Modifiers.METHOD_YIELDS |
3611 const int AllowedInterfaceModifiers =
3612 Modifiers.NEW | Modifiers.UNSAFE;
3615 // return_type can be "null" for VOID values.
3617 public Method (TypeContainer ds, Expression return_type, int mod, bool is_iface,
3618 MemberName name, Parameters parameters, Attributes attrs,
3620 : base (ds, return_type, mod,
3621 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3622 is_iface, name, attrs, parameters, l)
3626 public override AttributeTargets AttributeTargets {
3628 return AttributeTargets.Method;
3632 public override string GetSignatureForError()
3634 if (MethodBuilder == null) {
3635 return GetSignatureForError (Parent);
3637 return TypeManager.CSharpSignature (MethodBuilder);
3641 /// Use this method when MethodBuilder is null
3643 public override string GetSignatureForError (TypeContainer tc)
3645 // TODO: get params from somewhere
3646 if (parameter_info == null)
3647 return base.GetSignatureForError (tc);
3649 // TODO: move to parameters
3650 System.Text.StringBuilder args = new System.Text.StringBuilder ();
3651 if (parameter_info.Parameters.FixedParameters != null) {
3652 for (int i = 0; i < parameter_info.Parameters.FixedParameters.Length; ++i) {
3653 Parameter p = parameter_info.Parameters.FixedParameters [i];
3654 args.Append (p.GetSignatureForError ());
3656 if (i < parameter_info.Parameters.FixedParameters.Length - 1)
3661 return String.Concat (base.GetSignatureForError (tc), "(", args.ToString (), ")");
3664 void DuplicateEntryPoint (MethodInfo b, Location location)
3668 "Program `" + CodeGen.FileName +
3669 "' has more than one entry point defined: `" +
3670 TypeManager.CSharpSignature(b) + "'");
3673 public bool IsEntryPoint (MethodBuilder b, InternalParameters pinfo)
3675 if (b.ReturnType != TypeManager.void_type &&
3676 b.ReturnType != TypeManager.int32_type)
3679 if (pinfo.Count == 0)
3682 if (pinfo.Count > 1)
3685 Type t = pinfo.ParameterType(0);
3687 (t.GetArrayRank() == 1) &&
3688 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3689 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3695 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3697 if (a.Target == AttributeTargets.ReturnValue) {
3698 if (return_attributes == null)
3699 return_attributes = new ReturnParameter (MethodBuilder, Location);
3701 return_attributes.ApplyAttributeBuilder (a, cb);
3705 if (a.Type == TypeManager.methodimpl_attr_type &&
3706 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3707 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3710 if (a.Type == TypeManager.dllimport_type) {
3711 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3712 if ((ModFlags & extern_static) != extern_static) {
3713 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3719 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3720 if (declarative_security == null)
3721 declarative_security = new ListDictionary ();
3722 a.ExtractSecurityPermissionSet (declarative_security);
3726 if (a.Type == TypeManager.conditional_attribute_type) {
3727 if (IsOperator || IsExplicitImpl) {
3728 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
3732 if (ReturnType != TypeManager.void_type) {
3733 Report.Error (578, Location, "Conditional not valid on '{0}' because its return type is not void", GetSignatureForError ());
3737 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3738 Report.Error (243, Location, "Conditional not valid on '{0}' because it is an override method", GetSignatureForError ());
3743 Report.Error (582, Location, "Conditional not valid on interface members");
3747 if (MethodData.IsImplementing) {
3748 Report.Error (629, Location, "Conditional member '{0}' cannot implement interface member", GetSignatureForError ());
3752 for (int i = 0; i < parameter_info.Count; ++i) {
3753 if ((parameter_info.ParameterModifier (i) & Parameter.Modifier.OUT) != 0) {
3754 Report.Error (685, Location, "Conditional method '{0}' cannot have an out parameter", GetSignatureForError ());
3760 MethodBuilder.SetCustomAttribute (cb);
3763 protected override bool CheckForDuplications ()
3765 ArrayList ar = Parent.Methods;
3767 int arLen = ar.Count;
3769 for (int i = 0; i < arLen; i++) {
3770 Method m = (Method) ar [i];
3771 if (IsDuplicateImplementation (m))
3776 ar = Parent.Properties;
3778 for (int i = 0; i < ar.Count; ++i) {
3779 PropertyBase pb = (PropertyBase) ar [i];
3780 if (pb.AreAccessorsDuplicateImplementation (this))
3785 ar = Parent.Indexers;
3787 for (int i = 0; i < ar.Count; ++i) {
3788 PropertyBase pb = (PropertyBase) ar [i];
3789 if (pb.AreAccessorsDuplicateImplementation (this))
3796 for (int i = 0; i < ar.Count; ++i) {
3797 Event ev = (Event) ar [i];
3798 if (ev.AreAccessorsDuplicateImplementation (this))
3809 public override bool Define ()
3814 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3815 Error1599 (Location, ReturnType);
3823 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3825 MethodData = new MethodData (this, ParameterInfo, ModFlags, flags, this);
3827 if (!MethodData.Define (Parent))
3830 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3831 Name == "Finalize" && !(this is Destructor)) {
3832 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3836 // Setup iterator if we are one
3838 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3839 Iterator iterator = new Iterator (
3840 Parent, Name, MemberType,
3841 ParameterInfo, ModFlags, block, Location);
3843 if (!iterator.DefineIterator ())
3846 block = iterator.Block;
3849 MethodBuilder = MethodData.MethodBuilder;
3852 // This is used to track the Entry Point,
3854 if (Name == "Main" &&
3855 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3856 (RootContext.MainClass == null ||
3857 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3858 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3859 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3860 md.SetMemberIsUsed ();
3862 if (RootContext.EntryPoint == null) {
3863 RootContext.EntryPoint = MethodBuilder;
3864 RootContext.EntryPointLocation = Location;
3866 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3867 DuplicateEntryPoint (MethodBuilder, Location);
3870 if (RootContext.WarningLevel >= 4)
3871 Report.Warning (28, Location, "'{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3875 if (MemberType.IsAbstract && MemberType.IsSealed) {
3876 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3886 public override void Emit ()
3888 MethodData.Emit (Parent, this);
3891 if (declarative_security != null) {
3892 foreach (DictionaryEntry de in declarative_security) {
3893 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3901 public static void Error1599 (Location loc, Type t)
3903 Report.Error (1599, loc, "Method or delegate cannot return type '{0}'", TypeManager.CSharpName (t));
3906 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
3908 MethodInfo mi = (MethodInfo) container.BaseCache.FindMemberToOverride (
3909 container.TypeBuilder, Name, ParameterTypes, false);
3914 base_ret_type = mi.ReturnType;
3918 public override bool MarkForDuplicationCheck ()
3920 caching_flags |= Flags.TestMethodDuplication;
3924 protected override bool VerifyClsCompliance(DeclSpace ds)
3926 if (!base.VerifyClsCompliance (ds))
3929 if (parameter_types.Length > 0) {
3930 ArrayList al = (ArrayList)ds.MemberCache.Members [Name];
3932 ds.MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3939 void IIteratorContainer.SetYields ()
3941 ModFlags |= Modifiers.METHOD_YIELDS;
3944 #region IMethodData Members
3946 public CallingConventions CallingConventions {
3948 CallingConventions cc = Parameters.GetCallingConvention ();
3949 if (Parameters.HasArglist)
3950 block.HasVarargs = true;
3953 if ((ModFlags & Modifiers.STATIC) == 0)
3954 cc |= CallingConventions.HasThis;
3956 // FIXME: How is `ExplicitThis' used in C#?
3962 public Type ReturnType {
3968 public MemberName MethodName {
3974 public new Location Location {
3976 return base.Location;
3980 protected override bool CheckBase() {
3981 if (!base.CheckBase ())
3984 // TODO: Destructor should derive from MethodCore
3985 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3986 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3987 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3994 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
3996 return new EmitContext (
3997 tc, Parent, Location, ig, ReturnType, ModFlags, false);
4000 public ObsoleteAttribute GetObsoleteAttribute ()
4002 return GetObsoleteAttribute (Parent);
4006 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4008 public bool IsExcluded (EmitContext ec)
4010 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4011 return (caching_flags & Flags.Excluded) != 0;
4013 caching_flags &= ~Flags.Excluded_Undetected;
4015 if (base_method == null) {
4016 if (OptAttributes == null)
4019 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type, ec);
4024 foreach (Attribute a in attrs) {
4025 string condition = a.GetConditionalAttributeValue (Parent.EmitContext);
4026 if (RootContext.AllDefines.Contains (condition))
4030 caching_flags |= Flags.Excluded;
4034 IMethodData md = TypeManager.GetMethod (base_method);
4036 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4037 caching_flags |= Flags.Excluded;
4043 if (md.IsExcluded (ec)) {
4044 caching_flags |= Flags.Excluded;
4053 public abstract class ConstructorInitializer {
4054 ArrayList argument_list;
4055 protected ConstructorInfo base_constructor;
4056 Parameters parameters;
4059 public ConstructorInitializer (ArrayList argument_list, Parameters parameters,
4062 this.argument_list = argument_list;
4063 this.parameters = parameters;
4067 public ArrayList Arguments {
4069 return argument_list;
4073 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4075 Expression base_constructor_group;
4079 ec.CurrentBlock = block;
4081 if (argument_list != null){
4082 foreach (Argument a in argument_list){
4083 if (!a.Resolve (ec, loc))
4087 ec.CurrentBlock = null;
4089 if (this is ConstructorBaseInitializer) {
4090 if (ec.ContainerType.BaseType == null)
4093 t = ec.ContainerType.BaseType;
4094 if (ec.ContainerType.IsValueType) {
4095 Report.Error (522, loc,
4096 "structs cannot call base class constructors");
4100 t = ec.ContainerType;
4102 base_constructor_group = Expression.MemberLookup (
4103 ec, t, ".ctor", MemberTypes.Constructor,
4104 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4107 if (base_constructor_group == null){
4109 base_constructor_group = Expression.MemberLookup (
4110 ec, t, null, t, ".ctor", MemberTypes.Constructor,
4111 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4115 int errors = Report.Errors;
4116 if (base_constructor_group != null)
4117 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4118 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4121 if (base_constructor == null) {
4122 if (errors == Report.Errors)
4123 Report.Error (1501, loc, "Can not find a constructor for this argument list");
4128 Report.Error (122, loc, "`{0}' is inaccessible due to its protection level",
4129 TypeManager.CSharpSignature (base_constructor));
4130 base_constructor = null;
4134 if (base_constructor == caller_builder){
4135 Report.Error (516, loc, "Constructor `{0}' can not call itself", TypeManager.CSharpSignature (caller_builder));
4142 public void Emit (EmitContext ec)
4144 if (base_constructor != null){
4145 ec.Mark (loc, false);
4147 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4149 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4154 public class ConstructorBaseInitializer : ConstructorInitializer {
4155 public ConstructorBaseInitializer (ArrayList argument_list, Parameters pars, Location l) :
4156 base (argument_list, pars, l)
4161 public class ConstructorThisInitializer : ConstructorInitializer {
4162 public ConstructorThisInitializer (ArrayList argument_list, Parameters pars, Location l) :
4163 base (argument_list, pars, l)
4168 public class Constructor : MethodCore, IMethodData {
4169 public ConstructorBuilder ConstructorBuilder;
4170 public ConstructorInitializer Initializer;
4171 ListDictionary declarative_security;
4174 // Modifiers allowed for a constructor.
4176 public const int AllowedModifiers =
4178 Modifiers.PROTECTED |
4179 Modifiers.INTERNAL |
4185 bool has_compliant_args = false;
4187 // The spec claims that static is not permitted, but
4188 // my very own code has static constructors.
4190 public Constructor (TypeContainer ds, string name, int mod, Parameters args,
4191 ConstructorInitializer init, Location l)
4192 : base (ds, null, mod, AllowedModifiers, false, new MemberName (name),
4198 public override string GetSignatureForError()
4200 if (ConstructorBuilder == null)
4201 return GetSignatureForError (Parent);
4203 return TypeManager.CSharpSignature (ConstructorBuilder);
4206 public bool HasCompliantArgs {
4208 return has_compliant_args;
4212 public override AttributeTargets AttributeTargets {
4214 return AttributeTargets.Constructor;
4220 // Returns true if this is a default constructor
4222 public bool IsDefault ()
4224 if ((ModFlags & Modifiers.STATIC) != 0)
4225 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4226 (Parameters.ArrayParameter == null ? true : Parameters.Empty);
4229 return (Parameters.FixedParameters == null ? true : Parameters.Empty) &&
4230 (Parameters.ArrayParameter == null ? true : Parameters.Empty) &&
4231 (Initializer is ConstructorBaseInitializer) &&
4232 (Initializer.Arguments == null);
4235 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4237 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4238 if (declarative_security == null) {
4239 declarative_security = new ListDictionary ();
4241 a.ExtractSecurityPermissionSet (declarative_security);
4245 ConstructorBuilder.SetCustomAttribute (cb);
4248 protected override bool CheckForDuplications ()
4250 ArrayList ar = Parent.InstanceConstructors;
4252 int arLen = ar.Count;
4254 for (int i = 0; i < arLen; i++) {
4255 Constructor m = (Constructor) ar [i];
4256 if (IsDuplicateImplementation (m))
4263 protected override bool CheckBase ()
4265 // Check whether arguments were correct.
4266 if (!DoDefineParameters ())
4269 // TODO: skip the rest for generated ctor
4270 if ((ModFlags & Modifiers.STATIC) != 0)
4273 if (!CheckForDuplications ())
4276 if (Parent.Kind == Kind.Struct) {
4277 if (ParameterTypes.Length == 0) {
4278 Report.Error (568, Location,
4279 "Structs can not contain explicit parameterless " +
4284 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4285 Report.Error (666, Location, "Protected member in struct declaration");
4290 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4291 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4298 // Creates the ConstructorBuilder
4300 public override bool Define ()
4302 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4303 MethodAttributes.SpecialName);
4305 if ((ModFlags & Modifiers.STATIC) != 0) {
4306 ca |= MethodAttributes.Static | MethodAttributes.Private;
4308 ca |= MethodAttributes.HideBySig;
4310 if ((ModFlags & Modifiers.PUBLIC) != 0)
4311 ca |= MethodAttributes.Public;
4312 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4313 if ((ModFlags & Modifiers.INTERNAL) != 0)
4314 ca |= MethodAttributes.FamORAssem;
4316 ca |= MethodAttributes.Family;
4317 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4318 ca |= MethodAttributes.Assembly;
4319 else if (IsDefault ())
4320 ca |= MethodAttributes.Public;
4322 ca |= MethodAttributes.Private;
4325 // Check if arguments were correct.
4329 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4330 ca, CallingConventions,
4333 if ((ModFlags & Modifiers.UNSAFE) != 0)
4334 ConstructorBuilder.InitLocals = false;
4336 TypeManager.AddMethod (ConstructorBuilder, this);
4339 // HACK because System.Reflection.Emit is lame
4341 TypeManager.RegisterMethod (ConstructorBuilder, ParameterInfo, ParameterTypes);
4349 public override void Emit ()
4351 EmitContext ec = CreateEmitContext (null, null);
4354 // extern methods have no bodies
4356 if ((ModFlags & Modifiers.EXTERN) != 0) {
4357 if ((block != null) && ((ModFlags & Modifiers.EXTERN) != 0)) {
4359 179, Location, "External constructor `" +
4360 TypeManager.CSharpSignature (ConstructorBuilder) +
4361 "' can not have a body");
4364 } else if (block == null) {
4366 501, Location, "Constructor `" +
4367 TypeManager.CSharpSignature (ConstructorBuilder) +
4368 "' must declare a body since it is not marked extern");
4372 // If this is a non-static `struct' constructor and doesn't have any
4373 // initializer, it must initialize all of the struct's fields.
4374 if ((Parent.Kind == Kind.Struct) &&
4375 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4376 Block.AddThisVariable (Parent, Location);
4379 block.ResolveMeta (ec, ParameterInfo);
4381 if ((ModFlags & Modifiers.STATIC) == 0){
4382 if (Parent.Kind == Kind.Class && Initializer == null)
4383 Initializer = new ConstructorBaseInitializer (
4384 null, Parameters.EmptyReadOnlyParameters, Location);
4388 // Spec mandates that Initializers will not have
4392 if ((Initializer != null) &&
4393 !Initializer.Resolve (ConstructorBuilder, block, ec))
4395 ec.IsStatic = false;
4398 Parameters.LabelParameters (ec, ConstructorBuilder);
4400 SourceMethod source = SourceMethod.Create (
4401 Parent, ConstructorBuilder, block);
4404 // Classes can have base initializers and instance field initializers.
4406 if (Parent.Kind == Kind.Class){
4407 if ((ModFlags & Modifiers.STATIC) == 0){
4410 // If we use a "this (...)" constructor initializer, then
4411 // do not emit field initializers, they are initialized in the other constructor
4413 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4414 Parent.EmitFieldInitializers (ec);
4417 if (Initializer != null) {
4418 if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute (Parent) != null)
4419 ec.TestObsoleteMethodUsage = false;
4421 Initializer.Emit (ec);
4424 if ((ModFlags & Modifiers.STATIC) != 0)
4425 Parent.EmitFieldInitializers (ec);
4427 if (OptAttributes != null)
4428 OptAttributes.Emit (ec, this);
4430 ec.EmitTopBlock (block, ParameterInfo, Location);
4433 source.CloseMethod ();
4437 if (declarative_security != null) {
4438 foreach (DictionaryEntry de in declarative_security) {
4439 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4446 // Is never override
4447 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
4452 protected override bool VerifyClsCompliance (DeclSpace ds)
4454 if (!base.VerifyClsCompliance (ds) || !IsExposedFromAssembly (ds)) {
4458 if (parameter_types.Length > 0) {
4459 ArrayList al = (ArrayList)ds.MemberCache.Members [".ctor"];
4461 ds.MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4463 if (ds.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4464 foreach (Type param in parameter_types) {
4465 if (param.IsArray) {
4471 has_compliant_args = true;
4475 #region IMethodData Members
4477 public System.Reflection.CallingConventions CallingConventions {
4479 CallingConventions cc = Parameters.GetCallingConvention ();
4481 if (Parent.Kind == Kind.Class)
4482 if ((ModFlags & Modifiers.STATIC) == 0)
4483 cc |= CallingConventions.HasThis;
4485 // FIXME: How is `ExplicitThis' used in C#?
4491 public new Location Location {
4493 return base.Location;
4497 public MemberName MethodName {
4503 public Type ReturnType {
4509 public EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig)
4511 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4512 return new EmitContext (Parent, Location, ig_, null, ModFlags, true);
4515 public ObsoleteAttribute GetObsoleteAttribute ()
4517 return GetObsoleteAttribute (Parent);
4520 public bool IsExcluded(EmitContext ec)
4529 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4531 public interface IMethodData
4533 CallingConventions CallingConventions { get; }
4534 Location Location { get; }
4535 MemberName MethodName { get; }
4536 Type[] ParameterTypes { get; }
4537 Type ReturnType { get; }
4539 Attributes OptAttributes { get; }
4540 ToplevelBlock Block { get; }
4542 EmitContext CreateEmitContext (TypeContainer tc, ILGenerator ig);
4543 ObsoleteAttribute GetObsoleteAttribute ();
4544 string GetSignatureForError (TypeContainer tc);
4545 bool IsExcluded (EmitContext ec);
4546 bool IsClsCompliaceRequired (DeclSpace ds);
4547 void SetMemberIsUsed ();
4551 // Encapsulates most of the Method's state
4553 public class MethodData {
4555 readonly IMethodData method;
4558 // The return type of this method
4560 public readonly InternalParameters ParameterInfo;
4563 // Are we implementing an interface ?
4565 public bool IsImplementing = false;
4570 protected MemberBase member;
4571 protected int modifiers;
4572 protected MethodAttributes flags;
4574 MethodBuilder builder = null;
4575 public MethodBuilder MethodBuilder {
4581 public MethodData (MemberBase member, InternalParameters parameters,
4582 int modifiers, MethodAttributes flags, IMethodData method)
4584 this.member = member;
4585 this.ParameterInfo = parameters;
4586 this.modifiers = modifiers;
4589 this.method = method;
4592 public bool Define (TypeContainer container)
4594 MethodInfo implementing = null;
4596 string name = method.MethodName.Name;
4597 string method_name = name;
4599 Type[] ParameterTypes = method.ParameterTypes;
4601 if (container.Pending != null){
4602 if (member is Indexer) // TODO: test it, but it should work without this IF
4603 implementing = container.Pending.IsInterfaceIndexer (
4604 member.InterfaceType, method.ReturnType, ParameterInfo);
4606 implementing = container.Pending.IsInterfaceMethod (
4607 member.InterfaceType, name, method.ReturnType, ParameterInfo);
4609 if (member.InterfaceType != null){
4610 if (implementing == null){
4611 if (member is PropertyBase) {
4612 Report.Error (550, method.Location, "'{0}' is an accessor not found in interface member '{1}'",
4613 method.GetSignatureForError (container), member.Name);
4616 Report.Error (539, method.Location,
4617 "'{0}' in explicit interface declaration is not a member of interface", member.GetSignatureForError () );
4621 if (implementing.IsSpecialName && !((member is PropertyBase || member is EventProperty))) {
4622 Report.SymbolRelatedToPreviousError (implementing);
4623 Report.Error (683, method.Location, "'{0}' explicit method implementation cannot implement '{1}' because it is an accessor",
4624 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4627 method_name = member.InterfaceType.FullName + "." + name;
4629 if (implementing != null && method is AbstractPropertyEventMethod && !implementing.IsSpecialName) {
4630 Report.SymbolRelatedToPreviousError (implementing);
4631 Report.Error (686, method.Location, "Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation",
4632 method.GetSignatureForError (container), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4639 // For implicit implementations, make sure we are public, for
4640 // explicit implementations, make sure we are private.
4642 if (implementing != null){
4644 // Setting null inside this block will trigger a more
4645 // verbose error reporting for missing interface implementations
4647 // The "candidate" function has been flagged already
4648 // but it wont get cleared
4650 if (member.IsExplicitImpl){
4651 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4652 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4653 implementing = null;
4655 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4656 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4658 // If this is an interface method implementation,
4659 // check for public accessibility
4661 implementing = null;
4662 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4663 // We may never be private.
4664 implementing = null;
4665 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4667 // We may be protected if we're overriding something.
4669 implementing = null;
4674 // Static is not allowed
4676 if ((modifiers & Modifiers.STATIC) != 0){
4677 implementing = null;
4678 Modifiers.Error_InvalidModifier (method.Location, "static");
4683 // If implementing is still valid, set flags
4685 if (implementing != null){
4687 // When implementing interface methods, set NewSlot
4688 // unless, we are overwriting a method.
4690 if (implementing.DeclaringType.IsInterface){
4691 if ((modifiers & Modifiers.OVERRIDE) == 0)
4692 flags |= MethodAttributes.NewSlot;
4695 MethodAttributes.Virtual |
4696 MethodAttributes.HideBySig;
4698 // Set Final unless we're virtual, abstract or already overriding a method.
4699 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4700 flags |= MethodAttributes.Final;
4702 IsImplementing = true;
4705 EmitContext ec = method.CreateEmitContext (container, null);
4707 DefineMethodBuilder (ec, container, method_name, ParameterTypes);
4709 if (builder == null)
4712 if ((modifiers & Modifiers.UNSAFE) != 0)
4713 builder.InitLocals = false;
4715 if (IsImplementing){
4717 // clear the pending implemntation flag
4719 if (member is Indexer) {
4720 container.Pending.ImplementIndexer (
4721 member.InterfaceType, builder, method.ReturnType,
4722 ParameterInfo, member.IsExplicitImpl);
4724 container.Pending.ImplementMethod (
4725 member.InterfaceType, name, method.ReturnType,
4726 ParameterInfo, member.IsExplicitImpl);
4728 if (member.IsExplicitImpl)
4729 container.TypeBuilder.DefineMethodOverride (
4730 builder, implementing);
4734 TypeManager.RegisterMethod (builder, ParameterInfo, ParameterTypes);
4735 TypeManager.AddMethod (builder, method);
4742 /// Create the MethodBuilder for the method
4744 void DefineMethodBuilder (EmitContext ec, TypeContainer container, string method_name, Type[] ParameterTypes)
4746 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4748 if ((modifiers & extern_static) == extern_static) {
4750 if (method.OptAttributes != null) {
4751 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type, ec);
4752 if (dllimport_attribute != null) {
4753 flags |= MethodAttributes.PinvokeImpl;
4754 builder = dllimport_attribute.DefinePInvokeMethod (
4755 ec, container.TypeBuilder, method_name, flags,
4756 method.ReturnType, ParameterTypes);
4762 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4763 // We are more strict than Microsoft and report CS0626 like error
4764 if (method.OptAttributes == null ||
4765 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type, ec)) {
4766 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));
4771 builder = container.TypeBuilder.DefineMethod (
4772 method_name, flags, method.CallingConventions,
4773 method.ReturnType, ParameterTypes);
4779 public void Emit (TypeContainer container, Attributable kind)
4782 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4783 ec = method.CreateEmitContext (container, builder.GetILGenerator ());
4785 ec = method.CreateEmitContext (container, null);
4787 if (method.GetObsoleteAttribute () != null || container.GetObsoleteAttribute (container) != null)
4788 ec.TestObsoleteMethodUsage = false;
4790 Location loc = method.Location;
4791 Attributes OptAttributes = method.OptAttributes;
4793 if (OptAttributes != null)
4794 OptAttributes.Emit (ec, kind);
4796 if (member is MethodCore)
4797 ((MethodCore) member).Parameters.LabelParameters (ec, MethodBuilder);
4799 ToplevelBlock block = method.Block;
4802 // abstract or extern methods have no bodies
4804 if ((modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0){
4809 // abstract or extern methods have no bodies.
4811 if ((modifiers & Modifiers.ABSTRACT) != 0)
4813 500, method.Location, "Abstract method `" +
4814 TypeManager.CSharpSignature (builder) +
4815 "' can not have a body");
4817 if ((modifiers & Modifiers.EXTERN) != 0)
4819 179, method.Location, "External method `" +
4820 TypeManager.CSharpSignature (builder) +
4821 "' can not have a body");
4827 // Methods must have a body unless they're extern or abstract
4829 if (block == null) {
4831 501, method.Location, "Method `" +
4832 TypeManager.CSharpSignature (builder) +
4833 "' must declare a body since it is not marked " +
4834 "abstract or extern");
4838 SourceMethod source = SourceMethod.Create (
4839 container, MethodBuilder, method.Block);
4842 // Handle destructors specially
4844 // FIXME: This code generates buggy code
4846 if (member is Destructor)
4847 EmitDestructor (ec, block);
4849 ec.EmitTopBlock (block, ParameterInfo, loc);
4852 source.CloseMethod ();
4855 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4857 ILGenerator ig = ec.ig;
4859 Label finish = ig.DefineLabel ();
4861 block.SetDestructor ();
4863 ig.BeginExceptionBlock ();
4864 ec.ReturnLabel = finish;
4865 ec.HasReturnLabel = true;
4866 ec.EmitTopBlock (block, null, method.Location);
4868 // ig.MarkLabel (finish);
4869 ig.BeginFinallyBlock ();
4871 if (ec.ContainerType.BaseType != null) {
4872 Expression member_lookup = Expression.MemberLookup (
4873 ec, ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4874 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4876 if (member_lookup != null){
4877 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4879 ig.Emit (OpCodes.Ldarg_0);
4880 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4884 ig.EndExceptionBlock ();
4885 //ig.MarkLabel (ec.ReturnLabel);
4886 ig.Emit (OpCodes.Ret);
4890 // Should derive from MethodCore
4891 public class Destructor : Method {
4893 public Destructor (TypeContainer ds, Expression return_type, int mod,
4894 string name, Parameters parameters, Attributes attrs,
4896 : base (ds, return_type, mod, false, new MemberName (name),
4897 parameters, attrs, l)
4900 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4902 if (a.Type == TypeManager.conditional_attribute_type) {
4903 Report.Error (577, Location, "Conditional not valid on '{0}' because it is a destructor, operator, or explicit interface implementation", GetSignatureForError ());
4907 base.ApplyAttributeBuilder (a, cb);
4911 abstract public class MemberBase : MemberCore {
4912 public Expression Type;
4914 public MethodAttributes flags;
4916 protected readonly int explicit_mod_flags;
4919 // The "short" name of this property / indexer / event. This is the
4920 // name without the explicit interface.
4922 public string ShortName {
4923 get { return MemberName.Name; }
4925 SetMemberName (new MemberName (MemberName.Left, value));
4930 // The type of this property / indexer / event
4933 public Type MemberType {
4935 if (member_type == null && Type != null) {
4936 EmitContext ec = Parent.EmitContext;
4937 bool old_unsafe = ec.InUnsafe;
4938 ec.InUnsafe = InUnsafe;
4939 Type = Type.ResolveAsTypeTerminal (ec, false);
4940 ec.InUnsafe = old_unsafe;
4942 member_type = Type == null ? null : Type.Type;
4949 // Whether this is an interface member.
4951 public bool IsInterface;
4954 // If true, this is an explicit interface implementation
4956 public bool IsExplicitImpl;
4959 // The interface type we are explicitly implementing
4961 public Type InterfaceType = null;
4964 // The constructor is only exposed to our children
4966 protected MemberBase (TypeContainer parent, Expression type, int mod,
4967 int allowed_mod, int def_mod, MemberName name,
4968 Attributes attrs, Location loc)
4969 : base (parent, name, attrs, loc)
4971 explicit_mod_flags = mod;
4973 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, loc);
4974 IsExplicitImpl = (MemberName.Left != null);
4977 protected virtual bool CheckBase ()
4979 if ((ModFlags & Modifiers.PROTECTED) != 0 && Parent.Kind == Kind.Struct) {
4980 Report.Error (666, Location, "Protected member in struct declaration");
4984 if ((RootContext.WarningLevel >= 4) &&
4985 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
4986 ((ModFlags & Modifiers.PROTECTED) != 0) &&
4987 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
4988 Report.Warning (628, Location, "'{0}': new protected member declared in sealed class", GetSignatureForError (Parent));
4993 protected virtual bool CheckParameters (DeclSpace ds, Type [] parameters)
4997 foreach (Type partype in parameters){
4998 if (partype == TypeManager.void_type) {
5000 1547, Location, "Keyword 'void' cannot " +
5001 "be used in this context");
5005 if (partype.IsPointer){
5008 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
5012 if (ds.AsAccessible (partype, ModFlags))
5015 if (this is Indexer)
5016 Report.Error (55, Location,
5017 "Inconsistent accessibility: parameter type `" +
5018 TypeManager.CSharpName (partype) + "' is less " +
5019 "accessible than indexer `" + Name + "'");
5020 else if ((this is Method) && ((Method) this).IsOperator)
5021 Report.Error (57, Location,
5022 "Inconsistent accessibility: parameter type `" +
5023 TypeManager.CSharpName (partype) + "' is less " +
5024 "accessible than operator `" + Name + "'");
5026 Report.Error (51, Location,
5027 "Inconsistent accessibility: parameter type `" +
5028 TypeManager.CSharpName (partype) + "' is less " +
5029 "accessible than method `" + Name + "'");
5036 protected virtual bool DoDefine ()
5038 EmitContext ec = Parent.EmitContext;
5040 throw new InternalErrorException ("MemberBase.DoDefine called too early");
5043 throw new InternalErrorException ();
5046 ModFlags = Modifiers.PUBLIC |
5047 Modifiers.ABSTRACT |
5048 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5050 flags = MethodAttributes.Public |
5051 MethodAttributes.Abstract |
5052 MethodAttributes.HideBySig |
5053 MethodAttributes.NewSlot |
5054 MethodAttributes.Virtual;
5056 if (!Parent.MethodModifiersValid (this))
5059 flags = Modifiers.MethodAttr (ModFlags);
5062 if (MemberType == null)
5065 if ((Parent.ModFlags & Modifiers.SEALED) != 0){
5066 if ((ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0){
5067 Report.Error (549, Location, "Virtual method can not be contained in sealed class");
5072 // verify accessibility
5073 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5074 Report.SymbolRelatedToPreviousError (MemberType);
5075 if (this is Property)
5076 Report.Error (53, Location,
5077 "Inconsistent accessibility: property type `" +
5078 TypeManager.CSharpName (MemberType) + "' is less " +
5079 "accessible than property `" + GetSignatureForError () + "'");
5080 else if (this is Indexer)
5081 Report.Error (54, Location,
5082 "Inconsistent accessibility: indexer return type `" +
5083 TypeManager.CSharpName (MemberType) + "' is less " +
5084 "accessible than indexer `" + Name + "'");
5085 else if (this is MethodCore) {
5086 if (this is Operator)
5087 Report.Error (56, Location,
5088 "Inconsistent accessibility: return type `" +
5089 TypeManager.CSharpName (MemberType) + "' is less " +
5090 "accessible than operator `" + Name + "'");
5092 Report.Error (50, Location,
5093 "Inconsistent accessibility: return type `" +
5094 TypeManager.CSharpName (MemberType) + "' is less " +
5095 "accessible than method `" + Name + "'");
5097 Report.Error (52, Location,
5098 "Inconsistent accessibility: field type `" +
5099 TypeManager.CSharpName (MemberType) + "' is less " +
5100 "accessible than field `" + Name + "'");
5105 if (MemberType.IsPointer && !UnsafeOK (Parent))
5108 if (IsExplicitImpl) {
5109 Expression expr = MemberName.Left.GetTypeExpression (Location);
5110 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
5114 InterfaceType = texpr.ResolveType (ec);
5116 if (!InterfaceType.IsInterface) {
5117 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5121 if (!Parent.VerifyImplements (InterfaceType, ShortName, Name, Location))
5124 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5130 public override string GetSignatureForError (TypeContainer tc)
5132 return String.Concat (tc.Name, '.', base.GetSignatureForError (tc));
5135 protected bool IsTypePermitted ()
5137 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5138 Report.Error (610, Location, "Field or property cannot be of type '{0}'", TypeManager.CSharpName (MemberType));
5144 protected override bool VerifyClsCompliance(DeclSpace ds)
5146 if (base.VerifyClsCompliance (ds)) {
5150 if (IsInterface && HasClsCompliantAttribute && ds.IsClsCompliaceRequired (ds)) {
5151 Report.Error (3010, Location, "'{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5156 protected override void VerifyObsoleteAttribute()
5158 CheckUsageOfObsoleteAttribute (MemberType);
5163 // Fields and Events both generate FieldBuilders, we use this to share
5164 // their common bits. This is also used to flag usage of the field
5166 abstract public class FieldBase : MemberBase {
5167 public FieldBuilder FieldBuilder;
5168 public Status status;
5171 public enum Status : byte {
5173 HAS_OFFSET = 4 // Used by FieldMember.
5176 static string[] attribute_targets = new string [] { "field" };
5179 /// Symbol with same name in base class/struct
5181 public MemberInfo conflict_symbol;
5184 // The constructor is only exposed to our children
5186 protected FieldBase (TypeContainer parent, Expression type, int mod,
5187 int allowed_mod, MemberName name, object init,
5188 Attributes attrs, Location loc)
5189 : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE,
5195 public override AttributeTargets AttributeTargets {
5197 return AttributeTargets.Field;
5201 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5203 if (a.Type == TypeManager.marshal_as_attr_type) {
5204 UnmanagedMarshal marshal = a.GetMarshal (this);
5205 if (marshal != null) {
5206 FieldBuilder.SetMarshal (marshal);
5211 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5212 a.Error_InvalidSecurityParent ();
5216 FieldBuilder.SetCustomAttribute (cb);
5220 // Whether this field has an initializer.
5222 public bool HasInitializer {
5224 return init != null;
5228 protected readonly Object init;
5231 Expression init_expr;
5232 bool init_expr_initialized = false;
5235 // Resolves and returns the field initializer.
5237 public Expression GetInitializerExpression (EmitContext ec)
5239 if (init_expr_initialized)
5243 if (init is Expression)
5244 e = (Expression) init;
5246 e = new ArrayCreation (Type, "", (ArrayList)init, Location);
5248 EmitContext parent_ec = Parent.EmitContext;
5250 bool old_is_static = parent_ec.IsStatic;
5251 parent_ec.IsStatic = ec.IsStatic;
5252 parent_ec.IsFieldInitializer = true;
5253 e = e.DoResolve (parent_ec);
5254 parent_ec.IsFieldInitializer = false;
5255 parent_ec.IsStatic = old_is_static;
5258 init_expr_initialized = true;
5263 protected override bool CheckBase ()
5265 if (!base.CheckBase ())
5272 conflict_symbol = Parent.FindBaseMemberWithSameName (Name, false);
5273 if (conflict_symbol == null) {
5274 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5275 Report.Warning (109, Location, "The member '{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError (Parent));
5280 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5281 Report.SymbolRelatedToPreviousError (conflict_symbol);
5282 Report.Warning (108, Location, "The keyword new is required on '{0}' because it hides inherited member", GetSignatureForError (Parent));
5288 public override string GetSignatureForError ()
5290 if (FieldBuilder == null) {
5291 return base.GetSignatureForError (Parent);
5293 return TypeManager.GetFullNameSignature (FieldBuilder);
5296 protected virtual bool IsFieldClsCompliant {
5298 if (FieldBuilder == null)
5301 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5305 public override string[] ValidAttributeTargets {
5307 return attribute_targets;
5311 protected override bool VerifyClsCompliance (DeclSpace ds)
5313 if (!base.VerifyClsCompliance (ds))
5316 if (!IsFieldClsCompliant) {
5317 Report.Error (3003, Location, "Type of '{0}' is not CLS-compliant", GetSignatureForError ());
5323 public void SetAssigned ()
5325 status |= Status.ASSIGNED;
5329 public abstract class FieldMember: FieldBase
5331 protected FieldMember (TypeContainer parent, Expression type, int mod,
5332 int allowed_mod, MemberName name, object init, Attributes attrs, Location loc)
5333 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, init, attrs, loc)
5335 if ((mod & Modifiers.ABSTRACT) != 0)
5336 Report.Error (681, loc, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5339 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5341 if (a.Type == TypeManager.field_offset_attribute_type)
5343 status |= Status.HAS_OFFSET;
5345 if (!Parent.HasExplicitLayout) {
5346 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5350 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5351 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5357 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5358 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5363 base.ApplyAttributeBuilder (a, cb);
5367 public override bool Define()
5369 EmitContext ec = Parent.EmitContext;
5371 throw new InternalErrorException ("FieldMember.Define called too early");
5373 if (MemberType == null)
5376 if (MemberType == TypeManager.void_type) {
5377 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5384 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5385 Report.Error (52, Location,
5386 "Inconsistent accessibility: field type `" +
5387 TypeManager.CSharpName (MemberType) + "' is less " +
5388 "accessible than field `" + Name + "'");
5392 if (!IsTypePermitted ())
5395 if (MemberType.IsPointer && !UnsafeOK (Parent))
5401 public override void Emit ()
5403 if (OptAttributes != null) {
5404 EmitContext ec = new EmitContext (Parent, Location, null, FieldBuilder.FieldType, ModFlags);
5405 OptAttributes.Emit (ec, this);
5408 if (Parent.HasExplicitLayout && ((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0) {
5409 Report.Error (625, Location, "'{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5416 // Represents header string for documentation comment.
5418 public override string DocCommentHeader {
5419 get { return "F:"; }
5423 interface IFixedBuffer
5425 FieldInfo Element { get; }
5426 Type ElementType { get; }
5429 public class FixedFieldExternal: IFixedBuffer
5431 FieldInfo element_field;
5433 public FixedFieldExternal (FieldInfo fi)
5435 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5438 #region IFixedField Members
5440 public FieldInfo Element {
5442 return element_field;
5446 public Type ElementType {
5448 return element_field.FieldType;
5456 /// Fixed buffer implementation
5458 public class FixedField: FieldMember, IFixedBuffer
5460 public const string FixedElementName = "FixedElementField";
5461 static int GlobalCounter = 0;
5462 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5463 static FieldInfo[] fi;
5465 TypeBuilder fixed_buffer_type;
5466 FieldBuilder element;
5467 Expression size_expr;
5470 const int AllowedModifiers =
5473 Modifiers.PROTECTED |
5474 Modifiers.INTERNAL |
5477 public FixedField (TypeContainer parent, Expression type, int mod, string name,
5478 Expression size_expr, Attributes attrs, Location loc):
5479 base (parent, type, mod, AllowedModifiers, new MemberName (name), null, attrs, loc)
5481 if (RootContext.Version == LanguageVersion.ISO_1)
5482 Report.FeatureIsNotStandardized (loc, "fixed sized buffers");
5484 this.size_expr = size_expr;
5487 public override bool Define()
5490 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5491 Report.Warning (-23, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5494 if (Parent.Kind != Kind.Struct) {
5495 Report.Error (1642, Location, "Fixed buffer fields may only be members of structs");
5499 if (!base.Define ())
5502 if (!TypeManager.IsPrimitiveType (MemberType)) {
5503 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");
5507 Expression e = size_expr.Resolve (Parent.EmitContext);
5511 Constant c = e as Constant;
5513 Report.Error (133, Location, "The expression being assigned to '{0}' must be constant", GetSignatureForError ());
5517 IntConstant buffer_size_const = c.ToInt (Location);
5518 if (buffer_size_const == null)
5521 buffer_size = buffer_size_const.Value;
5523 if (buffer_size <= 0) {
5524 Report.Error (1665, Location, "Fixed sized buffer '{0}' must have a length greater than zero", GetSignatureForError ());
5528 int type_size = Expression.GetTypeSize (MemberType);
5530 if (buffer_size > int.MaxValue / type_size) {
5531 Report.Error (1664, Location, "Fixed sized buffer of length '{0}' and type '{1}' exceeded 2^31 limit",
5532 buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5536 buffer_size *= type_size;
5539 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5541 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5542 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5543 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5544 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5546 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5547 TypeManager.RegisterFieldBase (FieldBuilder, this);
5552 public override void Emit()
5555 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5557 object[] fi_val = new object[1];
5558 fi_val [0] = buffer_size;
5560 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5561 ctor_args, fi, fi_val);
5562 fixed_buffer_type.SetCustomAttribute (cab);
5565 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5566 FieldBuilder.SetCustomAttribute (cab);
5571 protected override bool IsFieldClsCompliant {
5577 #region IFixedField Members
5579 public FieldInfo Element {
5585 public Type ElementType {
5595 // The Field class is used to represents class/struct fields during parsing.
5597 public class Field : FieldMember {
5599 // Modifiers allowed in a class declaration
5601 const int AllowedModifiers =
5604 Modifiers.PROTECTED |
5605 Modifiers.INTERNAL |
5608 Modifiers.VOLATILE |
5612 public Field (TypeContainer parent, Expression type, int mod, string name,
5613 Object expr_or_array_init, Attributes attrs, Location loc)
5614 : base (parent, type, mod, AllowedModifiers, new MemberName (name),
5615 expr_or_array_init, attrs, loc)
5619 public override bool Define ()
5621 if (!base.Define ())
5624 if (RootContext.WarningLevel > 1){
5625 Type ptype = Parent.TypeBuilder.BaseType;
5627 // ptype is only null for System.Object while compiling corlib.
5629 TypeContainer.FindMembers (
5630 ptype, MemberTypes.Method,
5631 BindingFlags.Public |
5632 BindingFlags.Static | BindingFlags.Instance,
5633 System.Type.FilterName, Name);
5637 if ((ModFlags & Modifiers.VOLATILE) != 0){
5638 if (!MemberType.IsClass){
5639 Type vt = MemberType;
5641 if (TypeManager.IsEnumType (vt))
5642 vt = TypeManager.EnumToUnderlying (MemberType);
5644 if (!((vt == TypeManager.bool_type) ||
5645 (vt == TypeManager.sbyte_type) ||
5646 (vt == TypeManager.byte_type) ||
5647 (vt == TypeManager.short_type) ||
5648 (vt == TypeManager.ushort_type) ||
5649 (vt == TypeManager.int32_type) ||
5650 (vt == TypeManager.uint32_type) ||
5651 (vt == TypeManager.char_type) ||
5652 (vt == TypeManager.float_type) ||
5653 (!vt.IsValueType))){
5655 677, Location, Parent.MakeName (Name) +
5656 " A volatile field can not be of type `" +
5657 TypeManager.CSharpName (vt) + "'");
5662 if ((ModFlags & Modifiers.READONLY) != 0){
5665 "A field can not be both volatile and readonly");
5670 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5672 if (Parent.Kind == Kind.Struct &&
5673 ((fa & FieldAttributes.Static) == 0) &&
5674 MemberType == Parent.TypeBuilder &&
5675 !TypeManager.IsBuiltinType (MemberType)){
5676 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5677 "' causes a cycle in the structure layout");
5682 FieldBuilder = Parent.TypeBuilder.DefineField (
5683 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5685 TypeManager.RegisterFieldBase (FieldBuilder, this);
5687 catch (ArgumentException) {
5688 Report.Warning (-24, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5695 protected override bool VerifyClsCompliance (DeclSpace ds)
5697 if (!base.VerifyClsCompliance (ds))
5700 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5701 Report.Warning (3026, 1, Location, "CLS-compliant field '{0}' cannot be volatile", GetSignatureForError ());
5709 // `set' and `get' accessors are represented with an Accessor.
5711 public class Accessor {
5713 // Null if the accessor is empty, or a Block if not
5715 public const int AllowedModifiers =
5717 Modifiers.PROTECTED |
5718 Modifiers.INTERNAL |
5721 public ToplevelBlock Block;
5722 public Attributes Attributes;
5723 public Location Location;
5724 public int ModFlags;
5726 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5731 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5736 // Ooouh Martin, templates are missing here.
5737 // When it will be possible move here a lot of child code and template method type.
5738 public abstract class AbstractPropertyEventMethod: MemberCore, IMethodData {
5739 protected MethodData method_data;
5740 protected ToplevelBlock block;
5741 protected ListDictionary declarative_security;
5743 // The accessor are created event if they are not wanted.
5744 // But we need them because their names are reserved.
5745 // Field says whether accessor will be emited or not
5746 public readonly bool IsDummy;
5748 protected readonly string prefix;
5750 ReturnParameter return_attributes;
5752 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5753 : base (null, SetupName (prefix, member), null, member.Location)
5755 this.prefix = prefix;
5759 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5761 : base (null, SetupName (prefix, member),
5762 accessor.Attributes, accessor.Location)
5764 this.prefix = prefix;
5765 this.block = accessor.Block;
5768 static MemberName SetupName (string prefix, MemberBase member)
5770 return new MemberName (member.MemberName.Left, prefix + member.ShortName);
5773 public void UpdateName (MemberBase member)
5775 SetMemberName (SetupName (prefix, member));
5778 #region IMethodData Members
5780 public ToplevelBlock Block {
5790 public CallingConventions CallingConventions {
5792 return CallingConventions.Standard;
5796 public bool IsExcluded (EmitContext ec)
5801 public MemberName MethodName {
5807 public abstract ObsoleteAttribute GetObsoleteAttribute ();
5808 public abstract Type[] ParameterTypes { get; }
5809 public abstract Type ReturnType { get; }
5810 public abstract EmitContext CreateEmitContext(TypeContainer tc, ILGenerator ig);
5814 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5816 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5817 a.Type == TypeManager.conditional_attribute_type) {
5818 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 ());
5822 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5823 if (declarative_security == null)
5824 declarative_security = new ListDictionary ();
5825 a.ExtractSecurityPermissionSet (declarative_security);
5829 if (a.Target == AttributeTargets.Method) {
5830 method_data.MethodBuilder.SetCustomAttribute (cb);
5834 if (a.Target == AttributeTargets.ReturnValue) {
5835 if (return_attributes == null)
5836 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5838 return_attributes.ApplyAttributeBuilder (a, cb);
5842 ApplyToExtraTarget (a, cb);
5845 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5847 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5850 public override bool Define()
5852 throw new NotSupportedException ();
5855 public virtual void Emit (TypeContainer container)
5857 EmitMethod (container);
5859 if (declarative_security != null) {
5860 foreach (DictionaryEntry de in declarative_security) {
5861 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5868 protected virtual void EmitMethod (TypeContainer container)
5870 method_data.Emit (container, this);
5873 public override bool IsClsCompliaceRequired(DeclSpace ds)
5878 public bool IsDuplicateImplementation (MethodCore method)
5880 if (Name != method.Name)
5883 Type[] param_types = method.ParameterTypes;
5885 if (param_types.Length != ParameterTypes.Length)
5888 for (int i = 0; i < param_types.Length; i++)
5889 if (param_types [i] != ParameterTypes [i])
5892 Report.SymbolRelatedToPreviousError (method);
5893 Report.Error (111, Location, TypeContainer.Error111, method.Parent.GetSignatureForError (), Name);
5897 public override bool IsUsed
5907 public new Location Location {
5909 return base.Location;
5914 // Represents header string for documentation comment.
5916 public override string DocCommentHeader {
5917 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5920 protected override void VerifyObsoleteAttribute()
5927 // Properties and Indexers both generate PropertyBuilders, we use this to share
5928 // their common bits.
5930 abstract public class PropertyBase : MethodCore {
5932 public class GetMethod: PropertyMethod
5934 static string[] attribute_targets = new string [] { "method", "return" };
5936 public GetMethod (MethodCore method):
5937 base (method, "get_")
5941 public GetMethod (MethodCore method, Accessor accessor):
5942 base (method, accessor, "get_")
5946 public override MethodBuilder Define(TypeContainer container)
5948 base.Define (container);
5950 method_data = new MethodData (method, method.ParameterInfo, ModFlags, flags, this);
5952 if (!method_data.Define (container))
5955 return method_data.MethodBuilder;
5958 public override string GetSignatureForError (TypeContainer tc)
5960 return String.Concat (base.GetSignatureForError (tc), ".get");
5963 public override Type ReturnType {
5965 return method.MemberType;
5969 public override string[] ValidAttributeTargets {
5971 return attribute_targets;
5976 public class SetMethod: PropertyMethod {
5978 static string[] attribute_targets = new string [] { "method", "param", "return" };
5979 ImplicitParameter param_attr;
5981 public SetMethod (MethodCore method):
5982 base (method, "set_")
5986 public SetMethod (MethodCore method, Accessor accessor):
5987 base (method, accessor, "set_")
5991 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5993 if (a.Target == AttributeTargets.Parameter) {
5994 if (param_attr == null)
5995 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
5997 param_attr.ApplyAttributeBuilder (a, cb);
6001 base.ApplyAttributeBuilder (a, cb);
6004 protected virtual InternalParameters GetParameterInfo (EmitContext ec)
6006 Parameter [] parms = new Parameter [1];
6007 parms [0] = new Parameter (method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
6008 Parameters parameters = new Parameters (parms, null);
6010 bool old_unsafe = ec.InUnsafe;
6011 ec.InUnsafe = InUnsafe;
6012 Type [] types = parameters.GetParameterInfo (ec);
6013 ec.InUnsafe = old_unsafe;
6015 return new InternalParameters (types, parameters);
6018 public override MethodBuilder Define (TypeContainer container)
6020 if (container.EmitContext == null)
6021 throw new InternalErrorException ("SetMethod.Define called too early");
6023 base.Define (container);
6025 method_data = new MethodData (method, GetParameterInfo (container.EmitContext), ModFlags, flags, this);
6027 if (!method_data.Define (container))
6030 return method_data.MethodBuilder;
6033 public override string GetSignatureForError (TypeContainer tc)
6035 return String.Concat (base.GetSignatureForError (tc), ".set");
6038 public override Type[] ParameterTypes {
6040 return new Type[] { method.MemberType };
6044 public override Type ReturnType {
6046 return TypeManager.void_type;
6050 public override string[] ValidAttributeTargets {
6052 return attribute_targets;
6057 static string[] attribute_targets = new string [] { "property" };
6059 public abstract class PropertyMethod: AbstractPropertyEventMethod
6061 protected readonly MethodCore method;
6062 protected MethodAttributes flags;
6064 public PropertyMethod (MethodCore method, string prefix)
6065 : base (method, prefix)
6067 this.method = method;
6068 Parent = method.Parent;
6071 public PropertyMethod (MethodCore method, Accessor accessor,
6073 : base (method, accessor, prefix)
6075 this.method = method;
6076 Parent = method.Parent;
6077 this.ModFlags = accessor.ModFlags;
6079 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6080 Report.FeatureIsNotStandardized (Location, "accessor modifiers");
6084 public override AttributeTargets AttributeTargets {
6086 return AttributeTargets.Method;
6090 public override bool IsClsCompliaceRequired(DeclSpace ds)
6092 return method.IsClsCompliaceRequired (ds);
6095 public InternalParameters ParameterInfo
6098 return method_data.ParameterInfo;
6102 public virtual MethodBuilder Define (TypeContainer container)
6105 // Check for custom access modifier
6107 if (ModFlags == 0) {
6108 ModFlags = method.ModFlags;
6109 flags = method.flags;
6111 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6112 Report.Error (442, Location, "{0}': abstract properties cannot have private accessors", GetSignatureForError (container));
6115 CheckModifiers (container, ModFlags);
6116 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6117 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6118 flags = Modifiers.MethodAttr (ModFlags);
6119 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6126 public bool HasCustomAccessModifier
6129 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6133 public override Type[] ParameterTypes {
6135 return TypeManager.NoTypes;
6139 public override EmitContext CreateEmitContext (TypeContainer tc,
6142 return new EmitContext (
6143 tc, method.Parent, method.Location, ig, ReturnType,
6144 method.ModFlags, false);
6147 public override ObsoleteAttribute GetObsoleteAttribute ()
6149 return method.GetObsoleteAttribute (method.Parent);
6152 public override string GetSignatureForError (TypeContainer tc)
6154 return String.Concat (tc.Name, '.', method.Name);
6157 void CheckModifiers (TypeContainer container, int modflags)
6160 int mflags = method.ModFlags & Modifiers.Accessibility;
6162 if ((mflags & Modifiers.PUBLIC) != 0) {
6163 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6165 else if ((mflags & Modifiers.PROTECTED) != 0) {
6166 if ((mflags & Modifiers.INTERNAL) != 0)
6167 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6169 flags |= Modifiers.PRIVATE;
6171 else if ((mflags & Modifiers.INTERNAL) != 0)
6172 flags |= Modifiers.PRIVATE;
6174 if ((mflags == modflags) || (modflags & (~flags)) != 0)
6175 Report.Error (273, Location, "{0}: accessibility modifier must be more restrictive than the property or indexer",
6176 GetSignatureForError (container));
6179 public override bool MarkForDuplicationCheck ()
6181 caching_flags |= Flags.TestMethodDuplication;
6187 public PropertyMethod Get, Set;
6188 public PropertyBuilder PropertyBuilder;
6189 public MethodBuilder GetBuilder, SetBuilder;
6191 protected EmitContext ec;
6193 public PropertyBase (TypeContainer ds, Expression type, int mod_flags,
6194 int allowed_mod, bool is_iface, MemberName name,
6195 Parameters parameters, Attributes attrs,
6197 : base (ds, type, mod_flags, allowed_mod, is_iface, name,
6198 attrs, parameters, loc)
6202 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6204 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6205 a.Error_InvalidSecurityParent ();
6209 PropertyBuilder.SetCustomAttribute (cb);
6212 public override AttributeTargets AttributeTargets {
6214 return AttributeTargets.Property;
6218 public override bool Define ()
6223 if (!IsTypePermitted ())
6229 protected override bool DoDefine ()
6231 if (!base.DoDefine ())
6235 // Accessors modifiers check
6237 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6238 Report.Error (274, Location, "'{0}': cannot specify accessibility modifiers for both accessors of the property or indexer.",
6239 GetSignatureForError ());
6243 if ((Get.IsDummy || Set.IsDummy)
6244 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6245 Report.Error (276, Location,
6246 "'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor.",
6247 GetSignatureForError ());
6251 if (MemberType.IsAbstract && MemberType.IsSealed) {
6252 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6256 ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
6260 public override string GetSignatureForError()
6262 if (PropertyBuilder == null)
6263 return GetSignatureForError (Parent);
6265 return TypeManager.CSharpSignature (PropertyBuilder, false);
6268 protected override bool CheckForDuplications ()
6270 ArrayList ar = Parent.Indexers;
6272 int arLen = ar.Count;
6274 for (int i = 0; i < arLen; i++) {
6275 Indexer m = (Indexer) ar [i];
6276 if (IsDuplicateImplementation (m))
6281 ar = Parent.Properties;
6283 int arLen = ar.Count;
6285 for (int i = 0; i < arLen; i++) {
6286 Property m = (Property) ar [i];
6287 if (IsDuplicateImplementation (m))
6295 // TODO: rename to Resolve......
6296 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
6298 PropertyInfo base_property = container.BaseCache.FindMemberToOverride (
6299 container.TypeBuilder, Name, ParameterTypes, true) as PropertyInfo;
6301 if (base_property == null)
6304 base_ret_type = base_property.PropertyType;
6305 MethodInfo get_accessor = base_property.GetGetMethod (true);
6306 MethodInfo set_accessor = base_property.GetSetMethod (true);
6307 MethodAttributes get_accessor_access, set_accessor_access;
6309 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6310 if (Get != null && !Get.IsDummy && get_accessor == null) {
6311 Report.SymbolRelatedToPreviousError (base_property);
6312 Report.Error (545, Location, "'{0}': cannot override because '{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6315 if (Set != null && !Set.IsDummy && set_accessor == null) {
6316 Report.SymbolRelatedToPreviousError (base_property);
6317 Report.Error (546, Location, "'{0}': cannot override because '{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6322 // Check base class accessors access
6324 get_accessor_access = set_accessor_access = 0;
6325 if ((ModFlags & Modifiers.NEW) == 0) {
6326 if (get_accessor != null) {
6327 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6328 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6330 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6331 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6332 GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6335 if (set_accessor != null) {
6336 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6337 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6339 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6340 Report.Error (507, Location, "'{0}' can't change the access modifiers when overriding inherited member '{1}'",
6341 GetSignatureForError (container), TypeManager.GetFullNameSignature (base_property));
6346 // Get the less restrictive access
6348 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6351 public override void Emit ()
6354 // The PropertyBuilder can be null for explicit implementations, in that
6355 // case, we do not actually emit the ".property", so there is nowhere to
6356 // put the attribute
6358 if (PropertyBuilder != null && OptAttributes != null)
6359 OptAttributes.Emit (ec, this);
6371 /// Tests whether accessors are not in collision with some method (CS0111)
6373 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6375 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6378 public override bool IsUsed
6384 return Get.IsUsed | Set.IsUsed;
6388 protected override void SetMemberName (MemberName new_name)
6390 base.SetMemberName (new_name);
6392 Get.UpdateName (this);
6393 Set.UpdateName (this);
6396 public override string[] ValidAttributeTargets {
6398 return attribute_targets;
6403 // Represents header string for documentation comment.
6405 public override string DocCommentHeader {
6406 get { return "P:"; }
6410 public class Property : PropertyBase, IIteratorContainer {
6411 const int AllowedModifiers =
6414 Modifiers.PROTECTED |
6415 Modifiers.INTERNAL |
6419 Modifiers.OVERRIDE |
6420 Modifiers.ABSTRACT |
6423 Modifiers.METHOD_YIELDS |
6426 const int AllowedInterfaceModifiers =
6429 public Property (TypeContainer ds, Expression type, int mod, bool is_iface,
6430 MemberName name, Attributes attrs, Accessor get_block,
6431 Accessor set_block, Location loc)
6432 : base (ds, type, mod,
6433 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6434 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs,
6437 if (get_block == null)
6438 Get = new GetMethod (this);
6440 Get = new GetMethod (this, get_block);
6442 if (set_block == null)
6443 Set = new SetMethod (this);
6445 Set = new SetMethod (this, set_block);
6448 public override bool Define ()
6450 if (!base.Define ())
6456 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6460 GetBuilder = Get.Define (Parent);
6461 if (GetBuilder == null)
6465 // Setup iterator if we are one
6467 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
6468 Iterator iterator = new Iterator (
6469 Parent, "get", MemberType,
6471 ModFlags, Get.Block, Location);
6473 if (!iterator.DefineIterator ())
6475 Get.Block = iterator.Block;
6480 SetBuilder = Set.Define (Parent);
6481 if (SetBuilder == null)
6484 SetBuilder.DefineParameter (1, ParameterAttributes.None, "value");
6487 // FIXME - PropertyAttributes.HasDefault ?
6489 PropertyAttributes prop_attr = PropertyAttributes.None;
6491 prop_attr |= PropertyAttributes.RTSpecialName |
6492 PropertyAttributes.SpecialName;
6494 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6495 Name, prop_attr, MemberType, null);
6498 PropertyBuilder.SetGetMethod (GetBuilder);
6501 PropertyBuilder.SetSetMethod (SetBuilder);
6503 TypeManager.RegisterProperty (PropertyBuilder, GetBuilder, SetBuilder);
6507 public void SetYields ()
6509 ModFlags |= Modifiers.METHOD_YIELDS;
6514 /// Gigantic workaround for lameness in SRE follows :
6515 /// This class derives from EventInfo and attempts to basically
6516 /// wrap around the EventBuilder so that FindMembers can quickly
6517 /// return this in it search for members
6519 public class MyEventBuilder : EventInfo {
6522 // We use this to "point" to our Builder which is
6523 // not really a MemberInfo
6525 EventBuilder MyBuilder;
6528 // We "catch" and wrap these methods
6530 MethodInfo raise, remove, add;
6532 EventAttributes attributes;
6533 Type declaring_type, reflected_type, event_type;
6538 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6540 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6542 // And now store the values in our own fields.
6544 declaring_type = type_builder;
6546 reflected_type = type_builder;
6548 attributes = event_attr;
6551 this.event_type = event_type;
6555 // Methods that you have to override. Note that you only need
6556 // to "implement" the variants that take the argument (those are
6557 // the "abstract" methods, the others (GetAddMethod()) are
6560 public override MethodInfo GetAddMethod (bool nonPublic)
6565 public override MethodInfo GetRemoveMethod (bool nonPublic)
6570 public override MethodInfo GetRaiseMethod (bool nonPublic)
6576 // These methods make "MyEventInfo" look like a Builder
6578 public void SetRaiseMethod (MethodBuilder raiseMethod)
6580 raise = raiseMethod;
6581 MyBuilder.SetRaiseMethod (raiseMethod);
6584 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6586 remove = removeMethod;
6587 MyBuilder.SetRemoveOnMethod (removeMethod);
6590 public void SetAddOnMethod (MethodBuilder addMethod)
6593 MyBuilder.SetAddOnMethod (addMethod);
6596 public void SetCustomAttribute (CustomAttributeBuilder cb)
6598 MyBuilder.SetCustomAttribute (cb);
6601 public override object [] GetCustomAttributes (bool inherit)
6603 // FIXME : There's nothing which can be seemingly done here because
6604 // we have no way of getting at the custom attribute objects of the
6609 public override object [] GetCustomAttributes (Type t, bool inherit)
6611 // FIXME : Same here !
6615 public override bool IsDefined (Type t, bool b)
6620 public override EventAttributes Attributes {
6626 public override string Name {
6632 public override Type DeclaringType {
6634 return declaring_type;
6638 public override Type ReflectedType {
6640 return reflected_type;
6644 public Type EventType {
6650 public void SetUsed ()
6652 if (my_event != null) {
6653 my_event.status = FieldBase.Status.ASSIGNED;
6654 my_event.SetMemberIsUsed ();
6660 /// For case when event is declared like property (with add and remove accessors).
6662 public class EventProperty: Event {
6664 static string[] attribute_targets = new string [] { "event", "property" };
6666 public EventProperty (TypeContainer parent, Expression type, int mod_flags,
6667 bool is_iface, MemberName name, Object init,
6668 Attributes attrs, Accessor add, Accessor remove,
6670 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6672 Add = new AddDelegateMethod (this, add);
6673 Remove = new RemoveDelegateMethod (this, remove);
6675 // For this event syntax we don't report error CS0067
6676 // because it is hard to do it.
6680 public override string[] ValidAttributeTargets {
6682 return attribute_targets;
6688 /// Event is declared like field.
6690 public class EventField: Event {
6692 static string[] attribute_targets = new string [] { "event", "field", "method" };
6693 static string[] attribute_targets_interface = new string[] { "event", "method" };
6695 public EventField (TypeContainer parent, Expression type, int mod_flags,
6696 bool is_iface, MemberName name, Object init,
6697 Attributes attrs, Location loc)
6698 : base (parent, type, mod_flags, is_iface, name, init, attrs, loc)
6700 Add = new AddDelegateMethod (this);
6701 Remove = new RemoveDelegateMethod (this);
6704 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6706 if (a.Target == AttributeTargets.Field) {
6707 FieldBuilder.SetCustomAttribute (cb);
6711 if (a.Target == AttributeTargets.Method) {
6712 Add.ApplyAttributeBuilder (a, cb);
6713 Remove.ApplyAttributeBuilder (a, cb);
6717 base.ApplyAttributeBuilder (a, cb);
6720 public override string[] ValidAttributeTargets {
6722 return IsInterface ? attribute_targets_interface : attribute_targets;
6727 public abstract class Event : FieldBase {
6729 protected sealed class AddDelegateMethod: DelegateMethod
6732 public AddDelegateMethod (Event method):
6733 base (method, "add_")
6737 public AddDelegateMethod (Event method, Accessor accessor):
6738 base (method, accessor, "add_")
6742 protected override MethodInfo DelegateMethodInfo {
6744 return TypeManager.delegate_combine_delegate_delegate;
6750 protected sealed class RemoveDelegateMethod: DelegateMethod
6752 public RemoveDelegateMethod (Event method):
6753 base (method, "remove_")
6757 public RemoveDelegateMethod (Event method, Accessor accessor):
6758 base (method, accessor, "remove_")
6762 protected override MethodInfo DelegateMethodInfo {
6764 return TypeManager.delegate_remove_delegate_delegate;
6770 public abstract class DelegateMethod: AbstractPropertyEventMethod
6772 protected readonly Event method;
6773 ImplicitParameter param_attr;
6775 static string[] attribute_targets = new string [] { "method", "param", "return" };
6777 public DelegateMethod (Event method, string prefix)
6778 : base (method, prefix)
6780 this.method = method;
6783 public DelegateMethod (Event method, Accessor accessor, string prefix)
6784 : base (method, accessor, prefix)
6786 this.method = method;
6789 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6791 if (a.Target == AttributeTargets.Parameter) {
6792 if (param_attr == null)
6793 param_attr = new ImplicitParameter (method_data.MethodBuilder, method.Location);
6795 param_attr.ApplyAttributeBuilder (a, cb);
6799 base.ApplyAttributeBuilder (a, cb);
6802 public override AttributeTargets AttributeTargets {
6804 return AttributeTargets.Method;
6808 public override bool IsClsCompliaceRequired(DeclSpace ds)
6810 return method.IsClsCompliaceRequired (ds);
6813 public MethodBuilder Define (TypeContainer container, InternalParameters ip)
6815 method_data = new MethodData (method, ip, method.ModFlags,
6816 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6818 if (!method_data.Define (container))
6821 MethodBuilder mb = method_data.MethodBuilder;
6822 mb.DefineParameter (1, ParameterAttributes.None, "value");
6827 protected override void EmitMethod (TypeContainer tc)
6829 if (block != null) {
6830 base.EmitMethod (tc);
6834 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6837 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6838 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6840 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6841 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6842 ig.Emit (OpCodes.Ldsfld, field_info);
6843 ig.Emit (OpCodes.Ldarg_0);
6844 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6845 ig.Emit (OpCodes.Castclass, method.MemberType);
6846 ig.Emit (OpCodes.Stsfld, field_info);
6848 ig.Emit (OpCodes.Ldarg_0);
6849 ig.Emit (OpCodes.Ldarg_0);
6850 ig.Emit (OpCodes.Ldfld, field_info);
6851 ig.Emit (OpCodes.Ldarg_1);
6852 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6853 ig.Emit (OpCodes.Castclass, method.MemberType);
6854 ig.Emit (OpCodes.Stfld, field_info);
6856 ig.Emit (OpCodes.Ret);
6859 protected abstract MethodInfo DelegateMethodInfo { get; }
6861 public override Type[] ParameterTypes {
6863 return new Type[] { method.MemberType };
6867 public override Type ReturnType {
6869 return TypeManager.void_type;
6873 public override EmitContext CreateEmitContext (TypeContainer tc,
6876 return new EmitContext (
6877 tc, method.Parent, Location, ig, ReturnType,
6878 method.ModFlags, false);
6881 public override string GetSignatureForError (TypeContainer tc)
6883 return String.Concat (tc.Name, '.', method.Name);
6886 public override ObsoleteAttribute GetObsoleteAttribute ()
6888 return method.GetObsoleteAttribute (method.Parent);
6891 public override string[] ValidAttributeTargets {
6893 return attribute_targets;
6899 const int AllowedModifiers =
6902 Modifiers.PROTECTED |
6903 Modifiers.INTERNAL |
6908 Modifiers.OVERRIDE |
6912 const int AllowedInterfaceModifiers =
6915 public DelegateMethod Add, Remove;
6916 public MyEventBuilder EventBuilder;
6917 public MethodBuilder AddBuilder, RemoveBuilder;
6919 public Event (TypeContainer parent, Expression type, int mod_flags,
6920 bool is_iface, MemberName name, Object init, Attributes attrs,
6922 : base (parent, type, mod_flags,
6923 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6924 name, init, attrs, loc)
6926 IsInterface = is_iface;
6929 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6931 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6932 a.Error_InvalidSecurityParent ();
6936 EventBuilder.SetCustomAttribute (cb);
6939 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6941 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6944 public override AttributeTargets AttributeTargets {
6946 return AttributeTargets.Event;
6950 public override bool Define ()
6952 EventAttributes e_attr;
6953 e_attr = EventAttributes.None;
6958 if (init != null && ((ModFlags & Modifiers.ABSTRACT) != 0)){
6959 Report.Error (74, Location, "'" + Parent.Name + "." + Name +
6960 "': abstract event can not have an initializer");
6964 if (!MemberType.IsSubclassOf (TypeManager.delegate_type)) {
6965 Report.Error (66, Location, "'" + Parent.Name + "." + Name +
6966 "' : event must be of a delegate type");
6970 EmitContext ec = Parent.EmitContext;
6972 throw new InternalErrorException ("Event.Define called too early?");
6973 bool old_unsafe = ec.InUnsafe;
6974 ec.InUnsafe = InUnsafe;
6976 Parameter [] parms = new Parameter [1];
6977 parms [0] = new Parameter (Type, "value", Parameter.Modifier.NONE, null, Location);
6978 Parameters parameters = new Parameters (parms, null);
6979 Type [] types = parameters.GetParameterInfo (ec);
6980 InternalParameters ip = new InternalParameters (types, parameters);
6982 ec.InUnsafe = old_unsafe;
6988 // Now define the accessors
6991 AddBuilder = Add.Define (Parent, ip);
6992 if (AddBuilder == null)
6995 RemoveBuilder = Remove.Define (Parent, ip);
6996 if (RemoveBuilder == null)
6999 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
7001 if (Add.Block == null && Remove.Block == null && !IsInterface) {
7002 FieldBuilder = Parent.TypeBuilder.DefineField (
7004 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7005 TypeManager.RegisterPrivateFieldOfEvent (
7006 (EventInfo) EventBuilder, FieldBuilder);
7007 TypeManager.RegisterFieldBase (FieldBuilder, this);
7010 EventBuilder.SetAddOnMethod (AddBuilder);
7011 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7013 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
7017 protected override bool CheckBase ()
7019 if (!base.CheckBase ())
7022 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
7023 if (!(conflict_symbol is EventInfo)) {
7024 Report.SymbolRelatedToPreviousError (conflict_symbol);
7025 Report.Error (72, Location, "Event '{0}' can override only event", GetSignatureForError (Parent));
7033 public override void Emit ()
7035 if (OptAttributes != null) {
7036 EmitContext ec = new EmitContext (
7037 Parent, Location, null, MemberType, ModFlags);
7038 OptAttributes.Emit (ec, this);
7042 Remove.Emit (Parent);
7047 public override string GetSignatureForError ()
7049 if (EventBuilder == null)
7050 return base.GetSignatureForError (Parent);
7052 return TypeManager.GetFullNameSignature (EventBuilder);
7056 // Represents header string for documentation comment.
7058 public override string DocCommentHeader {
7059 get { return "E:"; }
7064 public class Indexer : PropertyBase {
7066 class GetIndexerMethod: GetMethod
7068 public GetIndexerMethod (MethodCore method):
7073 public GetIndexerMethod (MethodCore method, Accessor accessor):
7074 base (method, accessor)
7078 // TODO: one GetSignatureForError is enough (reuse Parent member)
7079 public override string GetSignatureForError (TypeContainer tc)
7081 string core = base.GetSignatureForError (tc);
7082 return core.Replace (TypeContainer.DefaultIndexerName,
7083 String.Format ("this[{0}]", TypeManager.CSharpName (ParameterTypes)));
7086 public override Type[] ParameterTypes {
7088 return method.ParameterTypes;
7093 class SetIndexerMethod: SetMethod
7095 readonly Parameters parameters;
7097 public SetIndexerMethod (MethodCore method):
7102 public SetIndexerMethod (MethodCore method, Parameters parameters, Accessor accessor):
7103 base (method, accessor)
7105 this.parameters = parameters;
7108 public override Type[] ParameterTypes {
7110 int top = method.ParameterTypes.Length;
7111 Type [] set_pars = new Type [top + 1];
7112 method.ParameterTypes.CopyTo (set_pars, 0);
7113 set_pars [top] = method.MemberType;
7118 protected override InternalParameters GetParameterInfo (EmitContext ec)
7120 Parameter [] fixed_parms = parameters.FixedParameters;
7122 if (fixed_parms == null){
7123 throw new Exception ("We currently do not support only array arguments in an indexer at: " + method.Location);
7124 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7125 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7127 // Here is the problem: the `value' parameter has
7128 // to come *after* the array parameter in the declaration
7130 // X (object [] x, Type value)
7133 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7134 // BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
7138 Parameter [] tmp = new Parameter [fixed_parms.Length + 1];
7140 fixed_parms.CopyTo (tmp, 0);
7141 tmp [fixed_parms.Length] = new Parameter (
7142 method.Type, "value", Parameter.Modifier.NONE, null, method.Location);
7144 Parameters set_formal_params = new Parameters (tmp, null);
7145 Type [] types = set_formal_params.GetParameterInfo (ec);
7147 return new InternalParameters (types, set_formal_params);
7152 const int AllowedModifiers =
7155 Modifiers.PROTECTED |
7156 Modifiers.INTERNAL |
7160 Modifiers.OVERRIDE |
7165 const int AllowedInterfaceModifiers =
7169 public Indexer (TypeContainer ds, Expression type, MemberName name, int mod,
7170 bool is_iface, Parameters parameters, Attributes attrs,
7171 Accessor get_block, Accessor set_block, Location loc)
7172 : base (ds, type, mod,
7173 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7174 is_iface, name, parameters, attrs, loc)
7176 if (get_block == null)
7177 Get = new GetIndexerMethod (this);
7179 Get = new GetIndexerMethod (this, get_block);
7181 if (set_block == null)
7182 Set = new SetIndexerMethod (this);
7184 Set = new SetIndexerMethod (this, parameters, set_block);
7187 public override bool Define ()
7189 PropertyAttributes prop_attr =
7190 PropertyAttributes.RTSpecialName |
7191 PropertyAttributes.SpecialName;
7193 if (!base.Define ())
7196 if (MemberType == TypeManager.void_type) {
7197 Report.Error (620, Location, "Indexers cannot have void type");
7201 if (OptAttributes != null) {
7202 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type, ec);
7203 if (indexer_attr != null) {
7204 // Remove the attribute from the list because it is not emitted
7205 OptAttributes.Attrs.Remove (indexer_attr);
7207 ShortName = indexer_attr.GetIndexerAttributeValue (ec);
7209 if (IsExplicitImpl) {
7210 Report.Error (415, indexer_attr.Location,
7211 "The 'IndexerName' attribute is valid only on an " +
7212 "indexer that is not an explicit interface member declaration");
7216 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7217 Report.Error (609, indexer_attr.Location,
7218 "Cannot set the 'IndexerName' attribute on an indexer marked override");
7222 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7223 Report.Error (633, indexer_attr.Location,
7224 "The argument to the 'IndexerName' attribute must be a valid identifier");
7230 if (InterfaceType != null) {
7231 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7232 if (base_IndexerName != Name)
7233 ShortName = base_IndexerName;
7236 if (!Parent.AddToMemberContainer (this) ||
7237 !Parent.AddToMemberContainer (Get) || !Parent.AddToMemberContainer (Set))
7243 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7245 GetBuilder = Get.Define (Parent);
7246 if (GetBuilder == null)
7251 SetBuilder = Set.Define (Parent);
7252 if (SetBuilder == null)
7257 // Now name the parameters
7259 Parameter [] p = Parameters.FixedParameters;
7261 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7262 Report.Error (631, Location, "ref and out are not valid in this context");
7268 for (i = 0; i < p.Length; ++i) {
7270 GetBuilder.DefineParameter (
7271 i + 1, p [i].Attributes, p [i].Name);
7274 SetBuilder.DefineParameter (
7275 i + 1, p [i].Attributes, p [i].Name);
7279 SetBuilder.DefineParameter (
7280 i + 1, ParameterAttributes.None, "value");
7282 if (i != ParameterTypes.Length) {
7283 Parameter array_param = Parameters.ArrayParameter;
7285 SetBuilder.DefineParameter (
7286 i + 1, array_param.Attributes, array_param.Name);
7290 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7291 Name, prop_attr, MemberType, ParameterTypes);
7294 PropertyBuilder.SetGetMethod (GetBuilder);
7297 PropertyBuilder.SetSetMethod (SetBuilder);
7299 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7304 public override string GetSignatureForError ()
7306 if (PropertyBuilder == null)
7307 return GetSignatureForError (Parent);
7309 return TypeManager.CSharpSignature (PropertyBuilder, true);
7312 public override string GetSignatureForError(TypeContainer tc)
7314 return String.Concat (tc.Name, ".this[", Parameters.FixedParameters [0].TypeName.ToString (), ']');
7317 public override bool MarkForDuplicationCheck ()
7319 caching_flags |= Flags.TestMethodDuplication;
7325 public class Operator : MethodCore, IIteratorContainer {
7327 const int AllowedModifiers =
7333 public enum OpType : byte {
7343 // Unary and Binary operators
7366 // Implicit and Explicit
7371 public readonly OpType OperatorType;
7372 public MethodBuilder OperatorMethodBuilder;
7374 public Method OperatorMethod;
7376 static string[] attribute_targets = new string [] { "method", "return" };
7378 public Operator (TypeContainer parent, OpType type, Expression ret_type,
7379 int mod_flags, Parameters parameters,
7380 ToplevelBlock block, Attributes attrs, Location loc)
7381 : base (parent, ret_type, mod_flags, AllowedModifiers, false,
7382 new MemberName ("op_" + type), attrs, parameters, loc)
7384 OperatorType = type;
7388 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7390 OperatorMethod.ApplyAttributeBuilder (a, cb);
7393 public override AttributeTargets AttributeTargets {
7395 return AttributeTargets.Method;
7399 protected override bool CheckForDuplications()
7401 ArrayList ar = Parent.Operators;
7403 int arLen = ar.Count;
7405 for (int i = 0; i < arLen; i++) {
7406 Operator o = (Operator) ar [i];
7407 if (IsDuplicateImplementation (o))
7412 ar = Parent.Methods;
7414 int arLen = ar.Count;
7416 for (int i = 0; i < arLen; i++) {
7417 Method m = (Method) ar [i];
7418 if (IsDuplicateImplementation (m))
7426 public override bool Define ()
7429 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7430 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7431 Report.Error (558, Location, "User defined operators '{0}' must be declared static and public", GetSignatureForError (Parent));
7438 if (MemberType == TypeManager.void_type) {
7439 Report.Error (590, Location, "User-defined operators cannot return void");
7443 OperatorMethod = new Method (
7444 Parent, Type, ModFlags, false, MemberName,
7445 Parameters, OptAttributes, Location);
7447 OperatorMethod.Block = Block;
7448 OperatorMethod.IsOperator = true;
7449 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7450 OperatorMethod.Define ();
7452 if (OperatorMethod.MethodBuilder == null)
7455 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7457 parameter_types = OperatorMethod.ParameterTypes;
7458 Type declaring_type = OperatorMethodBuilder.DeclaringType;
7459 Type return_type = OperatorMethod.ReturnType;
7460 Type first_arg_type = parameter_types [0];
7465 // Rules for conversion operators
7467 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7468 if (first_arg_type == return_type && first_arg_type == declaring_type){
7471 "User-defined conversion cannot take an object of the " +
7472 "enclosing type and convert to an object of the enclosing" +
7477 if (first_arg_type != declaring_type && return_type != declaring_type){
7480 "User-defined conversion must convert to or from the " +
7485 if (first_arg_type == TypeManager.object_type ||
7486 return_type == TypeManager.object_type){
7489 "User-defined conversion cannot convert to or from " +
7494 if (first_arg_type.IsInterface || return_type.IsInterface){
7497 "User-defined conversion cannot convert to or from an " +
7502 if (first_arg_type.IsSubclassOf (return_type)
7503 || return_type.IsSubclassOf (first_arg_type)){
7504 if (declaring_type.IsSubclassOf (return_type)) {
7505 Report.Error (553, Location, "'{0}' : user defined conversion to/from base class", GetSignatureForError ());
7508 Report.Error (554, Location, "'{0}' : user defined conversion to/from derived class", GetSignatureForError ());
7511 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7512 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7513 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");
7516 } else if (Parameters.FixedParameters.Length == 1) {
7517 // Checks for Unary operators
7519 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7520 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7521 Report.Error (448, Location,
7522 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7525 if (first_arg_type != declaring_type) {
7527 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7532 if (first_arg_type != declaring_type){
7535 "The parameter of a unary operator must be the " +
7540 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7541 if (return_type != TypeManager.bool_type){
7544 "The return type of operator True or False " +
7551 // Checks for Binary operators
7553 if (first_arg_type != declaring_type &&
7554 parameter_types [1] != declaring_type){
7557 "One of the parameters of a binary operator must " +
7558 "be the containing type");
7566 public override void Emit ()
7569 // abstract or extern methods have no bodies
7571 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7574 OperatorMethod.Emit ();
7578 // Operator cannot be override
7579 protected override MethodInfo FindOutBaseMethod (TypeContainer container, ref Type base_ret_type)
7584 public static string GetName (OpType ot)
7587 case OpType.LogicalNot:
7589 case OpType.OnesComplement:
7591 case OpType.Increment:
7593 case OpType.Decrement:
7599 case OpType.Addition:
7601 case OpType.Subtraction:
7603 case OpType.UnaryPlus:
7605 case OpType.UnaryNegation:
7607 case OpType.Multiply:
7609 case OpType.Division:
7611 case OpType.Modulus:
7613 case OpType.BitwiseAnd:
7615 case OpType.BitwiseOr:
7617 case OpType.ExclusiveOr:
7619 case OpType.LeftShift:
7621 case OpType.RightShift:
7623 case OpType.Equality:
7625 case OpType.Inequality:
7627 case OpType.GreaterThan:
7629 case OpType.LessThan:
7631 case OpType.GreaterThanOrEqual:
7633 case OpType.LessThanOrEqual:
7635 case OpType.Implicit:
7637 case OpType.Explicit:
7643 public override string GetSignatureForError (TypeContainer tc)
7645 StringBuilder sb = new StringBuilder ();
7646 sb.AppendFormat ("{0}.operator {1} {2}({3}", tc.Name, GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type),
7647 Parameters.FixedParameters [0].GetSignatureForError ());
7649 if (Parameters.FixedParameters.Length > 1) {
7651 sb.Append (Parameters.FixedParameters [1].GetSignatureForError ());
7654 return sb.ToString ();
7657 public override string GetSignatureForError ()
7662 public override bool MarkForDuplicationCheck ()
7664 caching_flags |= Flags.TestMethodDuplication;
7668 public override string ToString ()
7670 if (OperatorMethod == null)
7673 Type return_type = OperatorMethod.ReturnType;
7674 Type [] param_types = OperatorMethod.ParameterTypes;
7676 if (Parameters.FixedParameters.Length == 1)
7677 return String.Format (
7678 "{0} operator {1}({2})",
7679 TypeManager.CSharpName (return_type),
7680 GetName (OperatorType),
7683 return String.Format (
7684 "{0} operator {1}({2}, {3})",
7685 TypeManager.CSharpName (return_type),
7686 GetName (OperatorType),
7687 param_types [0], param_types [1]);
7690 public override string[] ValidAttributeTargets {
7692 return attribute_targets;
7696 public void SetYields ()
7698 ModFlags |= Modifiers.METHOD_YIELDS;
7703 // This is used to compare method signatures
7705 struct MethodSignature {
7707 public Type RetType;
7708 public Type [] Parameters;
7711 /// This delegate is used to extract methods which have the
7712 /// same signature as the argument
7714 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7716 public MethodSignature (string name, Type ret_type, Type [] parameters)
7721 if (parameters == null)
7722 Parameters = TypeManager.NoTypes;
7724 Parameters = parameters;
7727 public override string ToString ()
7730 if (Parameters.Length != 0){
7731 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7732 for (int i = 0; i < Parameters.Length; i++){
7733 sb.Append (Parameters [i]);
7734 if (i+1 < Parameters.Length)
7737 pars = sb.ToString ();
7740 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7743 public override int GetHashCode ()
7745 return Name.GetHashCode ();
7748 public override bool Equals (Object o)
7750 MethodSignature other = (MethodSignature) o;
7752 if (other.Name != Name)
7755 if (other.RetType != RetType)
7758 if (Parameters == null){
7759 if (other.Parameters == null)
7764 if (other.Parameters == null)
7767 int c = Parameters.Length;
7768 if (other.Parameters.Length != c)
7771 for (int i = 0; i < c; i++)
7772 if (other.Parameters [i] != Parameters [i])
7778 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7780 MethodSignature sig = (MethodSignature) filter_criteria;
7782 if (m.Name != sig.Name)
7786 MethodInfo mi = m as MethodInfo;
7787 PropertyInfo pi = m as PropertyInfo;
7790 ReturnType = mi.ReturnType;
7791 else if (pi != null)
7792 ReturnType = pi.PropertyType;
7797 // we use sig.RetType == null to mean `do not check the
7798 // method return value.
7800 if (sig.RetType != null)
7801 if (ReturnType != sig.RetType)
7806 args = TypeManager.GetArgumentTypes (mi);
7808 args = TypeManager.GetArgumentTypes (pi);
7809 Type [] sigp = sig.Parameters;
7811 if (args.Length != sigp.Length)
7814 for (int i = args.Length; i > 0; ){
7816 if (args [i] != sigp [i])