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;
46 using Mono.CompilerServices.SymbolWriter;
48 namespace Mono.CSharp {
58 /// This is the base class for structs and classes.
60 public abstract class TypeContainer : DeclSpace, IMemberContainer {
62 public class MemberCoreArrayList: ArrayList
65 /// Defines the MemberCore objects that are in this array
67 public virtual void DefineContainerMembers ()
69 foreach (MemberCore mc in this) {
74 public virtual void Emit ()
76 foreach (MemberCore mc in this)
81 public class MethodArrayList : MemberCoreArrayList
89 CachedMethods cached_method;
90 TypeContainer container;
92 public MethodArrayList (TypeContainer container)
94 this.container = container;
98 /// Method container contains Equals method
100 public bool HasEquals {
102 cached_method |= CachedMethods.Equals;
106 return (cached_method & CachedMethods.Equals) != 0;
111 /// Method container contains GetHashCode method
113 public bool HasGetHashCode {
115 cached_method |= CachedMethods.GetHashCode;
119 return (cached_method & CachedMethods.GetHashCode) != 0;
123 public override void DefineContainerMembers ()
125 base.DefineContainerMembers ();
127 if (HasEquals && !HasGetHashCode) {
128 Report.Warning (659, 3, container.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", container.GetSignatureForError ());
134 public sealed class IndexerArrayList : MemberCoreArrayList
137 /// The indexer name for this container
139 public string IndexerName = DefaultIndexerName;
141 bool seen_normal_indexers = false;
143 TypeContainer container;
145 public IndexerArrayList (TypeContainer container)
147 this.container = container;
151 /// Defines the indexers, and also verifies that the IndexerNameAttribute in the
152 /// class is consistent. Either it is `Item' or it is the name defined by all the
153 /// indexers with the `IndexerName' attribute.
155 /// Turns out that the IndexerNameAttribute is applied to each indexer,
156 /// but it is never emitted, instead a DefaultMember attribute is attached
159 public override void DefineContainerMembers()
161 base.DefineContainerMembers ();
163 string class_indexer_name = null;
166 // If there's both an explicit and an implicit interface implementation, the
167 // explicit one actually implements the interface while the other one is just
168 // a normal indexer. See bug #37714.
171 // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
172 foreach (Indexer i in this) {
173 if (i.InterfaceType != null) {
174 if (seen_normal_indexers)
175 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
179 seen_normal_indexers = true;
181 if (class_indexer_name == null) {
182 class_indexer_name = i.ShortName;
186 if (i.ShortName != class_indexer_name)
187 Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
190 if (class_indexer_name != null)
191 IndexerName = class_indexer_name;
194 public override void Emit ()
198 if (!seen_normal_indexers)
201 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
202 container.TypeBuilder.SetCustomAttribute (cb);
206 public class OperatorArrayList: MemberCoreArrayList
208 TypeContainer container;
210 public OperatorArrayList (TypeContainer container)
212 this.container = container;
216 // Operator pair checking
221 public Type ret_type;
222 public Type type1, type2;
224 public Operator.OpType ot;
226 public OperatorEntry (int f, Operator o)
230 ret_type = o.OperatorMethod.ReturnType;
231 Type [] pt = o.OperatorMethod.ParameterTypes;
238 public override int GetHashCode ()
240 return ret_type.GetHashCode ();
243 public override bool Equals (object o)
245 OperatorEntry other = (OperatorEntry) o;
247 if (other.ret_type != ret_type)
249 if (other.type1 != type1)
251 if (other.type2 != type2)
258 // Checks that some operators come in pairs:
264 // They are matched based on the return type and the argument types
266 void CheckPairedOperators ()
268 IDictionary pairs = new HybridDictionary ();
269 Operator true_op = null;
270 Operator false_op = null;
271 bool has_equality_or_inequality = false;
273 // Register all the operators we care about.
274 foreach (Operator op in this){
277 // Skip erroneous code.
278 if (op.OperatorMethod == null)
281 switch (op.OperatorType){
282 case Operator.OpType.Equality:
284 has_equality_or_inequality = true;
286 case Operator.OpType.Inequality:
288 has_equality_or_inequality = true;
291 case Operator.OpType.True:
294 case Operator.OpType.False:
298 case Operator.OpType.GreaterThan:
300 case Operator.OpType.LessThan:
303 case Operator.OpType.GreaterThanOrEqual:
305 case Operator.OpType.LessThanOrEqual:
311 OperatorEntry oe = new OperatorEntry (reg, op);
313 object o = pairs [oe];
317 oe = (OperatorEntry) o;
322 if (true_op != null){
323 if (false_op == null)
324 Report.Error (216, true_op.Location, "The operator `{0}' requires a matching operator `false' to also be defined",
325 true_op.GetSignatureForError ());
326 } else if (false_op != null)
327 Report.Error (216, false_op.Location, "The operator `{0}' requires a matching operator `true' to also be defined",
328 false_op.GetSignatureForError ());
331 // Look for the mistakes.
333 foreach (DictionaryEntry de in pairs){
334 OperatorEntry oe = (OperatorEntry) de.Key;
341 case Operator.OpType.Equality:
344 case Operator.OpType.Inequality:
347 case Operator.OpType.GreaterThan:
350 case Operator.OpType.LessThan:
353 case Operator.OpType.GreaterThanOrEqual:
356 case Operator.OpType.LessThanOrEqual:
360 Report.Error (216, oe.op.Location,
361 "The operator `{0}' requires a matching operator `{1}' to also be defined",
362 oe.op.GetSignatureForError (), s);
365 if (has_equality_or_inequality && (RootContext.WarningLevel > 2)) {
366 if (container.Methods == null || !container.Methods.HasEquals)
367 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
369 if (container.Methods == null || !container.Methods.HasGetHashCode)
370 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
374 public override void DefineContainerMembers ()
376 base.DefineContainerMembers ();
377 CheckPairedOperators ();
382 // Whether this is a struct, class or interface
383 public readonly Kind Kind;
385 // Holds a list of classes and structures
386 protected ArrayList types;
388 // Holds the list of properties
389 MemberCoreArrayList properties;
391 // Holds the list of enumerations
392 MemberCoreArrayList enums;
394 // Holds the list of delegates
395 MemberCoreArrayList delegates;
397 // Holds the list of constructors
398 protected MemberCoreArrayList instance_constructors;
400 // Holds the list of fields
401 MemberCoreArrayList fields;
403 // Holds a list of fields that have initializers
404 protected ArrayList initialized_fields;
406 // Holds a list of static fields that have initializers
407 protected ArrayList initialized_static_fields;
409 // Holds the list of constants
410 MemberCoreArrayList constants;
413 MemberCoreArrayList interfaces;
415 // Holds the methods.
416 MethodArrayList methods;
419 protected MemberCoreArrayList events;
421 // Holds the indexers
422 IndexerArrayList indexers;
424 // Holds the operators
425 MemberCoreArrayList operators;
427 // Holds the iterators
431 // Pointers to the default constructor and the default static constructor
433 Constructor default_constructor;
434 Constructor default_static_constructor;
437 // Points to the first non-static field added to the container.
439 // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
440 // and the first one's as good as any.
442 FieldBase first_nonstatic_field = null;
445 // This one is computed after we can distinguish interfaces
446 // from classes from the arraylist `type_bases'
449 TypeExpr[] iface_exprs;
451 ArrayList type_bases;
453 bool members_defined;
454 bool members_defined_ok;
456 // The interfaces we implement.
457 protected Type[] ifaces;
459 // The base member cache and our member cache
460 MemberCache base_cache;
461 MemberCache member_cache;
463 public const string DefaultIndexerName = "Item";
466 GenericTypeParameterBuilder[] gen_params;
468 public TypeContainer PartialContainer;
469 ArrayList partial_parts;
472 /// The pending methods that need to be implemented
473 // (interfaces or abstract methods)
475 PendingImplementation pending;
477 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
478 Attributes attrs, Kind kind)
479 : base (ns, parent, name, attrs)
481 if (parent != null && parent != RootContext.Tree.Types && parent.NamespaceEntry != ns)
482 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
485 this.PartialContainer = this;
488 public bool AddToMemberContainer (MemberCore symbol)
490 return AddToContainer (symbol, symbol.MemberName.MethodName);
493 protected virtual bool AddToTypeContainer (DeclSpace ds)
495 return AddToContainer (ds, ds.Basename);
498 public void AddConstant (Const constant)
500 if (!AddToMemberContainer (constant))
503 if (constants == null)
504 constants = new MemberCoreArrayList ();
506 constants.Add (constant);
509 public void AddEnum (Mono.CSharp.Enum e)
511 if (!AddToTypeContainer (e))
515 enums = new MemberCoreArrayList ();
520 public bool AddClassOrStruct (TypeContainer c)
522 if (!AddToTypeContainer (c))
526 types = new ArrayList (2);
528 RootContext.Tree.RecordDecl (c.NamespaceEntry.NS, c.MemberName, c);
533 public virtual TypeContainer AddPartial (TypeContainer nextPart)
535 return AddPartial (nextPart, nextPart.Basename);
538 protected TypeContainer AddPartial (TypeContainer nextPart, string name)
540 nextPart.ModFlags |= Modifiers.PARTIAL;
541 TypeContainer tc = defined_names [name] as TypeContainer;
544 if (nextPart is Interface)
545 AddInterface (nextPart);
547 AddClassOrStruct (nextPart);
551 if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
552 Report.SymbolRelatedToPreviousError (tc);
553 Error_MissingPartialModifier (nextPart);
557 if (tc.Kind != nextPart.Kind) {
558 Report.SymbolRelatedToPreviousError (tc);
559 Report.Error (261, nextPart.Location,
560 "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
561 nextPart.GetSignatureForError ());
565 if ((tc.ModFlags & Modifiers.Accessibility) != (nextPart.ModFlags & Modifiers.Accessibility)) {
566 Report.SymbolRelatedToPreviousError (tc);
567 Report.Error (262, nextPart.Location,
568 "Partial declarations of `{0}' have conflicting accessibility modifiers",
569 nextPart.GetSignatureForError ());
573 if (tc.partial_parts == null)
574 tc.partial_parts = new ArrayList (1);
576 tc.ModFlags |= nextPart.ModFlags;
577 if (nextPart.attributes != null) {
578 if (tc.attributes == null)
579 tc.attributes = nextPart.attributes;
581 tc.attributes.AddAttributes (nextPart.attributes.Attrs);
584 nextPart.PartialContainer = tc;
585 tc.partial_parts.Add (nextPart);
589 public void AddDelegate (Delegate d)
591 if (!AddToTypeContainer (d))
594 if (delegates == null)
595 delegates = new MemberCoreArrayList ();
600 public void AddMethod (Method method)
602 if (!AddToMemberContainer (method))
606 methods = new MethodArrayList (this);
608 if (method.MemberName.Left != null)
609 methods.Insert (0, method);
611 methods.Add (method);
615 // Do not use this method: use AddMethod.
617 // This is only used by iterators.
619 public void AppendMethod (Method method)
621 if (!AddToMemberContainer (method))
625 methods = new MethodArrayList (this);
627 methods.Add (method);
630 public void AddConstructor (Constructor c)
632 if (c.Name != MemberName.Name) {
633 Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
636 bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
639 if (default_static_constructor != null) {
640 Report.SymbolRelatedToPreviousError (default_static_constructor);
641 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
645 default_static_constructor = c;
648 if (default_constructor != null) {
649 Report.SymbolRelatedToPreviousError (default_constructor);
650 Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
653 default_constructor = c;
656 if (instance_constructors == null)
657 instance_constructors = new MemberCoreArrayList ();
659 instance_constructors.Add (c);
663 internal static string Error111 {
665 return "`{0}' is already defined. Rename this member or use different parameter types";
669 public bool AddInterface (TypeContainer iface)
671 if (!AddToTypeContainer (iface))
674 if (interfaces == null) {
675 interfaces = new MemberCoreArrayList ();
678 RootContext.Tree.RecordDecl (iface.NamespaceEntry.NS, iface.MemberName, iface);
679 interfaces.Add (iface);
683 public void AddField (FieldMember field)
685 if (!AddToMemberContainer (field))
689 fields = new MemberCoreArrayList ();
693 if ((field.ModFlags & Modifiers.STATIC) != 0)
696 if (first_nonstatic_field == null) {
697 first_nonstatic_field = field;
701 if (Kind == Kind.Struct &&
702 first_nonstatic_field.Parent != field.Parent &&
703 RootContext.WarningLevel >= 3) {
704 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
705 Report.Warning (282, 3, field.Location,
706 "struct instance field `{0}' found in different declaration from instance field `{1}'",
707 field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
711 public void AddProperty (Property prop)
713 if (!AddToMemberContainer (prop) ||
714 !AddToMemberContainer (prop.Get) || !AddToMemberContainer (prop.Set))
717 if (properties == null)
718 properties = new MemberCoreArrayList ();
720 if (prop.MemberName.Left != null)
721 properties.Insert (0, prop);
723 properties.Add (prop);
726 public void AddEvent (Event e)
728 if (!AddToMemberContainer (e))
731 if (e is EventProperty) {
732 if (!AddToMemberContainer (e.Add))
735 if (!AddToMemberContainer (e.Remove))
740 events = new MemberCoreArrayList ();
746 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
748 public void AddIndexer (Indexer i)
750 if (indexers == null)
751 indexers = new IndexerArrayList (this);
753 if (i.IsExplicitImpl)
754 indexers.Insert (0, i);
759 public void AddOperator (Operator op)
761 if (!AddToMemberContainer (op))
764 if (operators == null)
765 operators = new OperatorArrayList (this);
770 public void AddIterator (Iterator i)
772 if (iterators == null)
773 iterators = new ArrayList ();
778 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
780 if (a.Type == TypeManager.default_member_type) {
781 if (Indexers != null) {
782 Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
787 base.ApplyAttributeBuilder (a, cb);
790 public override AttributeTargets AttributeTargets {
792 throw new NotSupportedException ();
796 public ArrayList Types {
802 public MethodArrayList Methods {
808 public ArrayList Constants {
814 public ArrayList Interfaces {
820 public ArrayList Iterators {
826 protected Type BaseType {
828 return TypeBuilder.BaseType;
832 public ArrayList Bases {
842 public ArrayList Fields {
848 public ArrayList InstanceConstructors {
850 return instance_constructors;
854 public ArrayList Properties {
860 public ArrayList Events {
866 public ArrayList Enums {
872 public ArrayList Indexers {
878 public ArrayList Operators {
884 public ArrayList Delegates {
890 protected override TypeAttributes TypeAttr {
892 return Modifiers.TypeAttr (ModFlags, this) | base.TypeAttr;
896 public string IndexerName {
898 return indexers == null ? DefaultIndexerName : indexers.IndexerName;
902 public bool IsComImport {
904 if (OptAttributes == null)
907 return OptAttributes.Contains (TypeManager.comimport_attr_type);
911 public virtual void RegisterFieldForInitialization (FieldBase field)
913 if ((field.ModFlags & Modifiers.STATIC) != 0){
914 if (initialized_static_fields == null)
915 initialized_static_fields = new ArrayList (4);
917 initialized_static_fields.Add (field);
919 if (initialized_fields == null)
920 initialized_fields = new ArrayList (4);
922 initialized_fields.Add (field);
927 // Emits the instance field initializers
929 public bool EmitFieldInitializers (EmitContext ec)
934 fields = initialized_static_fields;
936 fields = initialized_fields;
942 foreach (FieldBase f in fields) {
943 f.EmitInitializer (ec);
949 // Defines the default constructors
951 protected void DefineDefaultConstructor (bool is_static)
953 // The default instance constructor is public
954 // If the class is abstract, the default constructor is protected
955 // The default static constructor is private
959 if (initialized_static_fields == null || default_static_constructor != null)
961 mods = Modifiers.STATIC | Modifiers.PRIVATE;
963 if (instance_constructors != null)
966 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
969 Constructor c = new Constructor (this, MemberName.Name, mods,
970 Parameters.EmptyReadOnlyParameters,
971 new GeneratedBaseInitializer (Location),
975 c.Block = new ToplevelBlock (null, Location);
978 public override string DocComment {
990 public PendingImplementation PendingImplementations {
991 get { return pending; }
994 public override bool GetClsCompliantAttributeValue ()
996 if (PartialContainer != this)
997 return PartialContainer.GetClsCompliantAttributeValue ();
999 return base.GetClsCompliantAttributeValue ();
1002 TypeExpr[] GetNormalBases (out TypeExpr base_class)
1008 int count = Bases.Count;
1009 int start = 0, i, j;
1011 if (Kind == Kind.Class){
1012 TypeExpr name = ((Expression) Bases [0]).ResolveAsBaseTerminal (this, false);
1018 if (!name.IsInterface) {
1019 // base_class could be a class, struct, enum, delegate.
1020 // This is validated in GetClassBases.
1026 TypeExpr [] ifaces = new TypeExpr [count-start];
1028 for (i = start, j = 0; i < count; i++, j++){
1029 TypeExpr resolved = ((Expression) Bases [i]).ResolveAsTypeTerminal (this, false);
1030 if (resolved == null) {
1034 ifaces [j] = resolved;
1037 return ifaces.Length == 0 ? null : ifaces;
1041 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
1043 ArrayList ifaces = new ArrayList (0);
1044 if (iface_exprs != null)
1045 ifaces.AddRange (iface_exprs);
1047 foreach (TypeContainer part in partial_parts) {
1048 TypeExpr new_base_class;
1049 TypeExpr[] new_ifaces = part.GetClassBases (out new_base_class);
1050 if (new_base_class != TypeManager.system_object_expr) {
1051 if (base_class == TypeManager.system_object_expr)
1052 base_class = new_base_class;
1054 if (new_base_class != null && !new_base_class.Equals (base_class)) {
1055 Report.SymbolRelatedToPreviousError (base_class.Location, "");
1056 Report.Error (263, part.Location,
1057 "Partial declarations of `{0}' must not specify different base classes",
1058 part.GetSignatureForError ());
1065 if (new_ifaces == null)
1068 foreach (TypeExpr iface in new_ifaces) {
1069 if (ifaces.Contains (iface))
1076 if (ifaces.Count == 0)
1079 return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
1083 /// This function computes the Base class and also the
1084 /// list of interfaces that the class or struct @c implements.
1086 /// The return value is an array (might be null) of
1087 /// interfaces implemented (as Types).
1089 /// The @base_class argument is set to the base object or null
1090 /// if this is `System.Object'.
1092 public virtual TypeExpr [] GetClassBases (out TypeExpr base_class)
1094 TypeExpr[] ifaces = GetNormalBases (out base_class);
1099 int count = ifaces.Length;
1101 for (int i = 0; i < count; i++) {
1102 TypeExpr iface = (TypeExpr) ifaces [i];
1104 if (!iface.IsInterface) {
1105 if (Kind != Kind.Class) {
1106 // TODO: location of symbol related ....
1107 Error_TypeInListIsNotInterface (Location, iface.FullName);
1109 else if (base_class != null)
1110 Report.Error (1721, Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
1111 GetSignatureForError (), base_class.GetSignatureForError (), iface.GetSignatureForError ());
1113 Report.Error (1722, Location, "`{0}': Base class `{1}' must be specified as first",
1114 GetSignatureForError (), iface.GetSignatureForError ());
1119 for (int x = 0; x < i; x++) {
1120 if (iface.Equals (ifaces [x])) {
1121 Report.Error (528, Location,
1122 "`{0}' is already listed in " +
1123 "interface list", iface.GetSignatureForError ());
1128 if ((Kind == Kind.Interface) &&
1129 !iface.AsAccessible (Parent, ModFlags)) {
1130 Report.Error (61, Location,
1131 "Inconsistent accessibility: base " +
1132 "interface `{0}' is less accessible " +
1133 "than interface `{1}'", iface.Name,
1141 bool CheckGenericInterfaces (Type[] ifaces)
1143 ArrayList already_checked = new ArrayList ();
1145 for (int i = 0; i < ifaces.Length; i++) {
1146 Type iface = ifaces [i];
1147 foreach (Type t in already_checked) {
1151 Type[] infered = new Type [CountTypeParameters];
1152 if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, infered, null))
1155 Report.Error (695, Location,
1156 "`{0}' cannot implement both `{1}' and `{2}' " +
1157 "because they may unify for some type parameter substitutions",
1158 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
1159 TypeManager.CSharpName (t));
1163 already_checked.Add (iface);
1171 protected void Error_TypeInListIsNotInterface (Location loc, string type)
1173 Report.Error (527, loc, "Type `{0}' in interface list is not an interface", type);
1176 bool DefineTypeBuilder ()
1180 if (TypeManager.NamespaceClash (Name, Location)) {
1184 ModuleBuilder builder = CodeGen.Module.Builder;
1185 Type default_parent = null;
1186 if (Kind == Kind.Struct)
1187 default_parent = TypeManager.value_type;
1188 TypeBuilder = builder.DefineType (
1189 Name, TypeAttr, default_parent, null);
1191 TypeBuilder builder = Parent.TypeBuilder;
1193 TypeBuilder = builder.DefineNestedType (
1194 Basename, TypeAttr, null, null);
1196 } catch (ArgumentException) {
1197 Report.RuntimeMissingSupport (Location, "static classes");
1201 TypeManager.AddUserType (this);
1204 string[] param_names = new string [TypeParameters.Length];
1205 for (int i = 0; i < TypeParameters.Length; i++)
1206 param_names [i] = TypeParameters [i].Name;
1208 gen_params = TypeBuilder.DefineGenericParameters (param_names);
1210 int offset = CountTypeParameters - CurrentTypeParameters.Length;
1211 for (int i = offset; i < gen_params.Length; i++)
1212 CurrentTypeParameters [i - offset].Define (gen_params [i]);
1215 iface_exprs = GetClassBases (out base_type);
1216 if (partial_parts != null) {
1217 iface_exprs = GetNormalPartialBases (ref base_type);
1221 // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
1222 // which in turn should have called DefineType()s on base types if necessary.
1224 // None of the code below should trigger DefineType()s on classes that we depend on.
1225 // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1227 // Let's do it as soon as possible, since code below can call DefineType() on classes
1228 // that depend on us to be populated before they are.
1230 if (!(this is Iterator))
1231 RootContext.RegisterOrder (this);
1233 if (base_type != null) {
1234 if (IsGeneric && TypeManager.IsAttributeType (base_type.Type)) {
1235 Report.Error (698, base_type.Location,
1236 "A generic type cannot derive from `{0}' " +
1237 "because it is an attribute class",
1242 TypeBuilder.SetParent (base_type.Type);
1244 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1245 if (obsolete_attr != null && !IsInObsoleteScope) {
1246 AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1250 if (!CheckRecursiveDefinition (this)) {
1254 // add interfaces that were not added at type creation
1255 if (iface_exprs != null) {
1256 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1257 if (ifaces == null) {
1261 foreach (Type itype in ifaces)
1262 TypeBuilder.AddInterfaceImplementation (itype);
1264 if (!CheckGenericInterfaces (ifaces)) {
1268 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1271 if (this is Iterator && !ResolveType ()) {
1279 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1281 public override TypeBuilder DefineType ()
1283 if (TypeBuilder != null)
1289 if (!DefineTypeBuilder ()) {
1294 if (partial_parts != null) {
1295 foreach (TypeContainer part in partial_parts)
1296 part.TypeBuilder = TypeBuilder;
1299 DefineNestedTypes ();
1304 Constraints [] constraints;
1305 public override void SetParameterInfo (ArrayList constraints_list)
1307 if (PartialContainer == this) {
1308 base.SetParameterInfo (constraints_list);
1312 if (constraints_list == null)
1315 constraints = new Constraints [PartialContainer.CountCurrentTypeParameters];
1317 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1318 for (int i = 0; i < constraints.Length; i++) {
1319 foreach (Constraints constraint in constraints_list) {
1320 if (constraint.TypeParameter == current_params [i].Name) {
1321 constraints [i] = constraint;
1328 bool UpdateTypeParameterConstraints ()
1331 TypeParameter[] current_params = PartialContainer.CurrentTypeParameters;
1333 if (constraints == null)
1336 for (int i = 0; i < current_params.Length; i++) {
1337 if (!current_params [i].UpdateConstraints (this, constraints [i])) {
1338 Report.Error (265, Location, "Partial declarations of `{0}' have " +
1339 "inconsistent constraints for type parameter `{1}'.",
1340 MemberName.GetTypeName (), current_params [i].Name);
1348 public bool ResolveType ()
1350 if ((base_type != null) &&
1351 (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1359 if (PartialContainer != this)
1360 throw new InternalErrorException ();
1362 TypeExpr current_type = null;
1364 foreach (TypeParameter type_param in CurrentTypeParameters) {
1365 if (!type_param.Resolve (this)) {
1371 if (partial_parts != null) {
1372 foreach (TypeContainer part in partial_parts) {
1373 if (!part.UpdateTypeParameterConstraints ()) {
1380 foreach (TypeParameter type_param in TypeParameters) {
1381 if (!type_param.DefineType (this)) {
1387 current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
1389 foreach (TypeParameter type_param in TypeParameters)
1390 if (!type_param.CheckDependencies ()) {
1395 if (current_type != null) {
1396 current_type = current_type.ResolveAsTypeTerminal (this, false);
1397 if (current_type == null) {
1402 CurrentType = current_type.Type;
1408 protected virtual bool DefineNestedTypes ()
1410 if (Interfaces != null) {
1411 foreach (TypeContainer iface in Interfaces)
1412 if (iface.DefineType () == null)
1416 if (Types != null) {
1417 foreach (TypeContainer tc in Types)
1418 if (tc.DefineType () == null)
1422 if (Delegates != null) {
1423 foreach (Delegate d in Delegates)
1424 if (d.DefineType () == null)
1428 if (Enums != null) {
1429 foreach (Enum en in Enums)
1430 if (en.DefineType () == null)
1437 TypeContainer InTransit;
1439 protected bool CheckRecursiveDefinition (TypeContainer tc)
1441 if (InTransit != null) {
1442 Report.SymbolRelatedToPreviousError (this);
1443 if (this is Interface)
1445 529, tc.Location, "Inherited interface `{0}' causes a " +
1446 "cycle in the interface hierarchy of `{1}'",
1447 GetSignatureForError (), tc.GetSignatureForError ());
1450 146, tc.Location, "Circular base class dependency " +
1451 "involving `{0}' and `{1}'",
1452 tc.GetSignatureForError (), GetSignatureForError ());
1458 if (BaseType != null) {
1459 Type t = TypeManager.DropGenericTypeArguments (BaseType);
1460 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1461 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1465 if (iface_exprs != null) {
1466 foreach (TypeExpr iface in iface_exprs) {
1467 Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1468 TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1469 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1478 public static void Error_KeywordNotAllowed (Location loc)
1480 Report.Error (1530, loc, "Keyword `new' is not allowed on namespace elements");
1484 /// Populates our TypeBuilder with fields and methods
1486 public override bool DefineMembers ()
1488 if (members_defined)
1489 return members_defined_ok;
1491 if (!base.DefineMembers ())
1494 members_defined_ok = DoDefineMembers ();
1495 members_defined = true;
1497 return members_defined_ok;
1500 public virtual void DefineDefaultConstructor ()
1504 protected virtual bool DoDefineMembers ()
1506 if (iface_exprs != null) {
1507 foreach (TypeExpr iface in iface_exprs) {
1508 ConstructedType ct = iface as ConstructedType;
1509 if ((ct != null) && !ct.CheckConstraints (this))
1514 if (base_type != null) {
1515 ConstructedType ct = base_type as ConstructedType;
1516 if ((ct != null) && !ct.CheckConstraints (this))
1521 MemberInfo conflict_symbol = Parent.MemberCache.FindMemberWithSameName (Basename, false, TypeBuilder);
1522 if (conflict_symbol == null) {
1523 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0))
1524 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1526 if ((ModFlags & Modifiers.NEW) == 0) {
1527 Report.SymbolRelatedToPreviousError (conflict_symbol);
1528 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1529 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1534 DefineContainerMembers (constants);
1535 DefineContainerMembers (fields);
1537 DefineDefaultConstructor ();
1539 if (Kind == Kind.Struct || Kind == Kind.Class) {
1540 pending = PendingImplementation.GetPendingImplementations (this);
1544 // Constructors are not in the defined_names array
1546 DefineContainerMembers (instance_constructors);
1548 if (default_static_constructor != null)
1549 default_static_constructor.Define ();
1551 DefineContainerMembers (properties);
1552 DefineContainerMembers (events);
1553 DefineContainerMembers (indexers);
1554 DefineContainerMembers (methods);
1555 DefineContainerMembers (operators);
1556 DefineContainerMembers (enums);
1557 DefineContainerMembers (delegates);
1559 if (CurrentType != null) {
1560 GenericType = CurrentType;
1565 member_cache = new MemberCache (this);
1566 if (partial_parts != null) {
1567 foreach (TypeContainer part in partial_parts)
1568 part.member_cache = member_cache;
1571 if (iterators != null) {
1572 foreach (Iterator iterator in iterators) {
1573 if (iterator.DefineType () == null)
1577 foreach (Iterator iterator in iterators) {
1578 if (!iterator.DefineMembers ())
1586 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1589 mcal.DefineContainerMembers ();
1592 public override bool Define ()
1594 if (iterators != null) {
1595 foreach (Iterator iterator in iterators) {
1596 if (!iterator.Define ())
1604 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1606 return BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1610 /// This function is based by a delegate to the FindMembers routine
1612 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1618 /// This filter is used by FindMembers, and we just keep
1619 /// a global for the filter to `AlwaysAccept'
1621 static MemberFilter accepting_filter;
1624 static TypeContainer ()
1626 accepting_filter = new MemberFilter (AlwaysAccept);
1629 public MethodInfo[] GetMethods ()
1631 ArrayList members = new ArrayList ();
1635 if (methods != null) {
1636 int len = methods.Count;
1637 for (int i = 0; i < len; i++) {
1638 Method m = (Method) methods [i];
1640 members.Add (m.MethodBuilder);
1644 if (operators != null) {
1645 int len = operators.Count;
1646 for (int i = 0; i < len; i++) {
1647 Operator o = (Operator) operators [i];
1649 members.Add (o.OperatorMethodBuilder);
1653 if (properties != null) {
1654 int len = properties.Count;
1655 for (int i = 0; i < len; i++) {
1656 Property p = (Property) properties [i];
1658 if (p.GetBuilder != null)
1659 members.Add (p.GetBuilder);
1660 if (p.SetBuilder != null)
1661 members.Add (p.SetBuilder);
1665 if (indexers != null) {
1666 int len = indexers.Count;
1667 for (int i = 0; i < len; i++) {
1668 Indexer ix = (Indexer) indexers [i];
1670 if (ix.GetBuilder != null)
1671 members.Add (ix.GetBuilder);
1672 if (ix.SetBuilder != null)
1673 members.Add (ix.SetBuilder);
1677 if (events != null) {
1678 int len = events.Count;
1679 for (int i = 0; i < len; i++) {
1680 Event e = (Event) events [i];
1682 if (e.AddBuilder != null)
1683 members.Add (e.AddBuilder);
1684 if (e.RemoveBuilder != null)
1685 members.Add (e.RemoveBuilder);
1689 MethodInfo[] retMethods = new MethodInfo [members.Count];
1690 members.CopyTo (retMethods, 0);
1694 // Indicated whether container has StructLayout attribute set Explicit
1695 public bool HasExplicitLayout {
1697 return (caching_flags & Flags.HasExplicitLayout) != 0;
1700 caching_flags |= Flags.HasExplicitLayout;
1704 public override Type FindNestedType (string name)
1706 if (PartialContainer != this)
1707 return PartialContainer.FindNestedType (name);
1709 ArrayList [] lists = { types, enums, delegates, interfaces };
1711 for (int j = 0; j < lists.Length; ++j) {
1712 ArrayList list = lists [j];
1716 int len = list.Count;
1717 for (int i = 0; i < len; ++i) {
1718 DeclSpace ds = (DeclSpace) list [i];
1719 if (ds.Basename == name) {
1720 return ds.DefineType ();
1728 private void FindMembers_NestedTypes (int modflags,
1729 BindingFlags bf, MemberFilter filter, object criteria,
1730 ref ArrayList members)
1732 ArrayList [] lists = { types, enums, delegates, interfaces };
1734 for (int j = 0; j < lists.Length; ++j) {
1735 ArrayList list = lists [j];
1739 int len = list.Count;
1740 for (int i = 0; i < len; i++) {
1741 DeclSpace ds = (DeclSpace) list [i];
1743 if ((ds.ModFlags & modflags) == 0)
1746 TypeBuilder tb = ds.TypeBuilder;
1748 if (!(criteria is string) || ds.Basename.Equals (criteria))
1749 tb = ds.DefineType ();
1752 if (tb != null && (filter (tb, criteria) == true)) {
1753 if (members == null)
1754 members = new ArrayList ();
1763 /// This method returns the members of this type just like Type.FindMembers would
1764 /// Only, we need to use this for types which are _being_ defined because MS'
1765 /// implementation can't take care of that.
1768 // FIXME: return an empty static array instead of null, that cleans up
1769 // some code and is consistent with some coding conventions I just found
1773 // Notice that in various cases we check if our field is non-null,
1774 // something that would normally mean that there was a bug elsewhere.
1776 // The problem happens while we are defining p-invoke methods, as those
1777 // will trigger a FindMembers, but this happens before things are defined
1779 // Since the whole process is a no-op, it is fine to check for null here.
1781 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1782 MemberFilter filter, object criteria)
1784 ArrayList members = null;
1787 if ((bf & BindingFlags.Public) != 0)
1788 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1790 if ((bf & BindingFlags.NonPublic) != 0)
1791 modflags |= Modifiers.PRIVATE;
1793 int static_mask = 0, static_flags = 0;
1794 switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1795 case BindingFlags.Static:
1796 static_mask = static_flags = Modifiers.STATIC;
1799 case BindingFlags.Instance:
1800 static_mask = Modifiers.STATIC;
1805 static_mask = static_flags = 0;
1809 Timer.StartTimer (TimerType.TcFindMembers);
1812 filter = accepting_filter;
1814 if ((mt & MemberTypes.Field) != 0) {
1815 if (fields != null) {
1816 int len = fields.Count;
1817 for (int i = 0; i < len; i++) {
1818 FieldMember f = (FieldMember) fields [i];
1820 if ((f.ModFlags & modflags) == 0)
1822 if ((f.ModFlags & static_mask) != static_flags)
1825 FieldBuilder fb = f.FieldBuilder;
1826 if (fb != null && filter (fb, criteria) == true) {
1827 if (members == null)
1828 members = new ArrayList ();
1835 if (constants != null) {
1836 int len = constants.Count;
1837 for (int i = 0; i < len; i++) {
1838 Const con = (Const) constants [i];
1840 if ((con.ModFlags & modflags) == 0)
1842 if ((con.ModFlags & static_mask) != static_flags)
1845 FieldBuilder fb = con.FieldBuilder;
1848 fb = con.FieldBuilder;
1850 if (fb != null && filter (fb, criteria) == true) {
1851 if (members == null)
1852 members = new ArrayList ();
1860 if ((mt & MemberTypes.Method) != 0) {
1861 if (methods != null) {
1862 int len = methods.Count;
1863 for (int i = 0; i < len; i++) {
1864 Method m = (Method) methods [i];
1866 if ((m.ModFlags & modflags) == 0)
1868 if ((m.ModFlags & static_mask) != static_flags)
1871 MethodBuilder mb = m.MethodBuilder;
1873 if (mb != null && filter (mb, criteria) == true) {
1874 if (members == null)
1875 members = new ArrayList ();
1882 if (operators != null) {
1883 int len = operators.Count;
1884 for (int i = 0; i < len; i++) {
1885 Operator o = (Operator) operators [i];
1887 if ((o.ModFlags & modflags) == 0)
1889 if ((o.ModFlags & static_mask) != static_flags)
1892 MethodBuilder ob = o.OperatorMethodBuilder;
1893 if (ob != null && filter (ob, criteria) == true) {
1894 if (members == null)
1895 members = new ArrayList ();
1902 if (properties != null) {
1903 int len = properties.Count;
1904 for (int i = 0; i < len; i++) {
1905 Property p = (Property) properties [i];
1907 if ((p.ModFlags & modflags) == 0)
1909 if ((p.ModFlags & static_mask) != static_flags)
1915 if (b != null && filter (b, criteria) == true) {
1916 if (members == null)
1917 members = new ArrayList ();
1923 if (b != null && filter (b, criteria) == true) {
1924 if (members == null)
1925 members = new ArrayList ();
1932 if (indexers != null) {
1933 int len = indexers.Count;
1934 for (int i = 0; i < len; i++) {
1935 Indexer ix = (Indexer) indexers [i];
1937 if ((ix.ModFlags & modflags) == 0)
1939 if ((ix.ModFlags & static_mask) != static_flags)
1945 if (b != null && filter (b, criteria) == true) {
1946 if (members == null)
1947 members = new ArrayList ();
1953 if (b != null && filter (b, criteria) == true) {
1954 if (members == null)
1955 members = new ArrayList ();
1963 if ((mt & MemberTypes.Event) != 0) {
1964 if (events != null) {
1965 int len = events.Count;
1966 for (int i = 0; i < len; i++) {
1967 Event e = (Event) events [i];
1969 if ((e.ModFlags & modflags) == 0)
1971 if ((e.ModFlags & static_mask) != static_flags)
1974 MemberInfo eb = e.EventBuilder;
1975 if (eb != null && filter (eb, criteria) == true) {
1976 if (members == null)
1977 members = new ArrayList ();
1979 members.Add (e.EventBuilder);
1985 if ((mt & MemberTypes.Property) != 0){
1986 if (properties != null) {
1987 int len = properties.Count;
1988 for (int i = 0; i < len; i++) {
1989 Property p = (Property) properties [i];
1991 if ((p.ModFlags & modflags) == 0)
1993 if ((p.ModFlags & static_mask) != static_flags)
1996 MemberInfo pb = p.PropertyBuilder;
1997 if (pb != null && filter (pb, criteria) == true) {
1998 if (members == null)
1999 members = new ArrayList ();
2001 members.Add (p.PropertyBuilder);
2006 if (indexers != null) {
2007 int len = indexers.Count;
2008 for (int i = 0; i < len; i++) {
2009 Indexer ix = (Indexer) indexers [i];
2011 if ((ix.ModFlags & modflags) == 0)
2013 if ((ix.ModFlags & static_mask) != static_flags)
2016 MemberInfo ib = ix.PropertyBuilder;
2017 if (ib != null && filter (ib, criteria) == true) {
2018 if (members == null)
2019 members = new ArrayList ();
2021 members.Add (ix.PropertyBuilder);
2027 if ((mt & MemberTypes.NestedType) != 0)
2028 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
2030 if ((mt & MemberTypes.Constructor) != 0){
2031 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
2032 int len = instance_constructors.Count;
2033 for (int i = 0; i < len; i++) {
2034 Constructor c = (Constructor) instance_constructors [i];
2036 ConstructorBuilder cb = c.ConstructorBuilder;
2037 if (cb != null && filter (cb, criteria) == true) {
2038 if (members == null)
2039 members = new ArrayList ();
2046 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
2047 ConstructorBuilder cb =
2048 default_static_constructor.ConstructorBuilder;
2050 if (cb != null && filter (cb, criteria) == true) {
2051 if (members == null)
2052 members = new ArrayList ();
2060 // Lookup members in base if requested.
2062 if ((bf & BindingFlags.DeclaredOnly) == 0) {
2063 if (TypeBuilder.BaseType != null) {
2064 MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
2065 if (list.Count > 0) {
2066 if (members == null)
2067 members = new ArrayList ();
2069 members.AddRange (list);
2075 Timer.StopTimer (TimerType.TcFindMembers);
2077 if (members == null)
2078 return MemberList.Empty;
2080 return new MemberList (members);
2083 public override MemberCache MemberCache {
2085 return member_cache;
2089 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
2090 MemberFilter filter, object criteria)
2092 DeclSpace ds = TypeManager.LookupDeclSpace (t);
2095 return ds.FindMembers (mt, bf, filter, criteria);
2097 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
2101 /// Emits the values for the constants
2103 public void EmitConstants ()
2105 if (constants != null)
2106 foreach (Const con in constants)
2111 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
2116 foreach (MemberCore mc in al) {
2117 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2121 Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2126 public virtual void VerifyMembers ()
2129 // Check for internal or private fields that were never assigned
2131 if (RootContext.WarningLevel >= 3) {
2132 CheckMemberUsage (properties, "property");
2133 CheckMemberUsage (methods, "method");
2134 CheckMemberUsage (constants, "constant");
2136 if (fields != null){
2137 foreach (FieldMember f in fields) {
2138 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2142 if ((f.caching_flags & Flags.IsAssigned) == 0)
2143 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2146 const int error_code = 414;
2148 const int error_code = 169;
2150 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2151 f.GetSignatureForError ());
2157 // Only report 649 on level 4
2159 if (RootContext.WarningLevel < 4)
2162 if ((f.caching_flags & Flags.IsAssigned) != 0)
2165 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2166 f.GetSignatureForError (), f.Type.Type.IsValueType ? Activator.CreateInstance (f.Type.Type).ToString() : "null");
2172 // TODO: move to ClassOrStruct
2173 void EmitConstructors ()
2175 if (instance_constructors == null)
2178 if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2179 bool has_compliant_args = false;
2181 foreach (Constructor c in instance_constructors) {
2184 if (has_compliant_args)
2187 has_compliant_args = c.HasCompliantArgs;
2189 if (!has_compliant_args)
2190 Report.Error (3015, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2192 foreach (Constructor c in instance_constructors)
2198 /// Emits the code, this step is performed after all
2199 /// the types, enumerations, constructors
2201 public virtual void EmitType ()
2203 if (OptAttributes != null)
2204 OptAttributes.Emit ();
2207 int offset = CountTypeParameters - CurrentTypeParameters.Length;
2208 for (int i = offset; i < gen_params.Length; i++)
2209 CurrentTypeParameters [i - offset].EmitAttributes ();
2213 // Structs with no fields need to have at least one byte.
2214 // The right thing would be to set the PackingSize in a DefineType
2215 // but there are no functions that allow interfaces *and* the size to
2219 if (Kind == Kind.Struct && first_nonstatic_field == null){
2220 FieldBuilder fb = TypeBuilder.DefineField ("$PRIVATE$", TypeManager.byte_type,
2221 FieldAttributes.Private);
2223 if (HasExplicitLayout){
2224 object [] ctor_args = new object [1];
2227 CustomAttributeBuilder cba = new CustomAttributeBuilder (
2228 TypeManager.field_offset_attribute_ctor, ctor_args);
2229 fb.SetCustomAttribute (cba);
2235 EmitConstructors ();
2237 // Can not continue if constants are broken
2239 if (Report.Errors > 0)
2242 if (default_static_constructor != null)
2243 default_static_constructor.Emit ();
2245 if (methods != null){
2246 foreach (Method m in methods)
2250 if (operators != null)
2251 foreach (Operator o in operators)
2254 if (properties != null)
2255 foreach (Property p in properties)
2258 if (indexers != null){
2263 foreach (FieldMember f in fields)
2266 if (events != null){
2267 foreach (Event e in Events)
2271 if (delegates != null) {
2272 foreach (Delegate d in Delegates) {
2277 if (enums != null) {
2278 foreach (Enum e in enums) {
2283 if (pending != null)
2284 if (pending.VerifyPendingMethods ())
2287 if (iterators != null)
2288 foreach (Iterator iterator in iterators)
2289 iterator.EmitType ();
2292 public override void CloseType ()
2294 if ((caching_flags & Flags.CloseTypeCreated) != 0)
2298 caching_flags |= Flags.CloseTypeCreated;
2299 TypeBuilder.CreateType ();
2300 } catch (TypeLoadException){
2302 // This is fine, the code still created the type
2304 // Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2305 // Console.WriteLine (e.Message);
2307 Console.WriteLine ("In type: " + Name);
2312 foreach (Enum en in Enums)
2316 foreach (TypeContainer tc in Types)
2317 if (tc.Kind == Kind.Struct)
2320 foreach (TypeContainer tc in Types)
2321 if (tc.Kind != Kind.Struct)
2325 if (Delegates != null)
2326 foreach (Delegate d in Delegates)
2329 if (Iterators != null)
2330 foreach (Iterator i in Iterators)
2338 initialized_fields = null;
2339 initialized_static_fields = null;
2347 default_constructor = null;
2348 default_static_constructor = null;
2350 OptAttributes = null;
2353 member_cache = null;
2357 // Performs the validation on a Method's modifiers (properties have
2358 // the same properties).
2360 public bool MethodModifiersValid (MemberCore mc)
2362 const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2363 const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2364 const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2366 int flags = mc.ModFlags;
2369 // At most one of static, virtual or override
2371 if ((flags & Modifiers.STATIC) != 0){
2372 if ((flags & vao) != 0){
2373 Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2374 mc.GetSignatureForError ());
2379 if (Kind == Kind.Struct){
2380 if ((flags & va) != 0){
2381 Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2386 if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2387 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2388 mc.GetSignatureForError ());
2393 // If the declaration includes the abstract modifier, then the
2394 // declaration does not include static, virtual or extern
2396 if ((flags & Modifiers.ABSTRACT) != 0){
2397 if ((flags & Modifiers.EXTERN) != 0){
2399 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2403 if ((flags & Modifiers.SEALED) != 0) {
2404 Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2408 if ((flags & Modifiers.VIRTUAL) != 0){
2409 Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2413 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2414 Report.Error (513, mc.Location, "`{0}' is abstract but it is contained in nonabstract class", mc.GetSignatureForError ());
2419 if ((flags & Modifiers.PRIVATE) != 0){
2420 if ((flags & vao) != 0){
2421 Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2426 if ((flags & Modifiers.SEALED) != 0){
2427 if ((flags & Modifiers.OVERRIDE) == 0){
2428 Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2436 public bool UserDefinedStaticConstructor {
2438 return default_static_constructor != null;
2442 public Constructor DefaultStaticConstructor {
2443 get { return default_static_constructor; }
2446 protected override bool VerifyClsCompliance ()
2448 if (!base.VerifyClsCompliance ())
2453 Type base_type = TypeBuilder.BaseType;
2454 if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2455 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2458 if (!Parent.IsClsComplianceRequired ()) {
2459 Report.Error (3018, Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
2460 GetSignatureForError (), Parent.GetSignatureForError ());
2467 /// Checks whether container name is CLS Compliant
2469 void VerifyClsName ()
2471 Hashtable base_members = base_cache == null ?
2473 base_cache.GetPublicMembers ();
2474 Hashtable this_members = new Hashtable ();
2476 foreach (DictionaryEntry entry in defined_names) {
2477 MemberCore mc = (MemberCore)entry.Value;
2478 if (!mc.IsClsComplianceRequired ())
2481 string name = (string) entry.Key;
2482 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2484 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2485 object found = base_members [lcase];
2486 if (found == null) {
2487 found = this_members [lcase];
2488 if (found == null) {
2489 this_members.Add (lcase, mc);
2494 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2497 if (found is MemberInfo) {
2498 if (basename == ((MemberInfo) found).Name)
2500 Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2502 Report.SymbolRelatedToPreviousError ((MemberCore) found);
2504 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2510 /// Performs checks for an explicit interface implementation. First it
2511 /// checks whether the `interface_type' is a base inteface implementation.
2512 /// Then it checks whether `name' exists in the interface type.
2514 public virtual bool VerifyImplements (MemberBase mb)
2516 if (ifaces != null) {
2517 foreach (Type t in ifaces){
2518 if (t == mb.InterfaceType)
2523 Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2524 Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2525 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2529 public void Mark_HasEquals ()
2531 Methods.HasEquals = true;
2534 public void Mark_HasGetHashCode ()
2536 Methods.HasGetHashCode = true;
2543 string IMemberContainer.Name {
2549 Type IMemberContainer.Type {
2555 MemberCache IMemberContainer.MemberCache {
2557 return member_cache;
2561 bool IMemberContainer.IsInterface {
2563 return Kind == Kind.Interface;
2567 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2569 BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2571 if (GenericType != null)
2572 return TypeManager.FindMembers (GenericType, mt, new_bf,
2575 return FindMembers (mt, new_bf, null, null);
2579 // Generates xml doc comments (if any), and if required,
2580 // handle warning report.
2582 internal override void GenerateDocComment (DeclSpace ds)
2584 DocUtil.GenerateTypeDocComment (this, ds);
2587 public override string DocCommentHeader {
2588 get { return "T:"; }
2591 public virtual MemberCache BaseCache {
2593 if (base_cache != null)
2595 if (TypeBuilder.BaseType != null)
2596 base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2597 if (TypeBuilder.IsInterface)
2598 base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2605 public abstract class ClassOrStruct : TypeContainer {
2606 ListDictionary declarative_security;
2608 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2609 MemberName name, Attributes attrs, Kind kind)
2610 : base (ns, parent, name, attrs, kind)
2614 protected override bool AddToContainer (MemberCore symbol, string name)
2616 if (name == MemberName.Name) {
2617 if (symbol is TypeParameter) {
2618 Report.Error (694, symbol.Location,
2619 "Type parameter `{0}' has same name as " +
2620 "containing type, or method", name);
2624 Report.SymbolRelatedToPreviousError (this);
2625 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2626 symbol.GetSignatureForError ());
2630 return base.AddToContainer (symbol, name);
2633 public override void DefineDefaultConstructor ()
2635 DefineDefaultConstructor (true);
2638 public override void VerifyMembers ()
2640 base.VerifyMembers ();
2642 if ((events != null) && (RootContext.WarningLevel >= 3)) {
2643 foreach (Event e in events){
2644 if ((e.caching_flags & Flags.IsAssigned) == 0)
2645 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2650 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2652 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
2653 if (declarative_security == null)
2654 declarative_security = new ListDictionary ();
2656 a.ExtractSecurityPermissionSet (declarative_security);
2660 if (a.Type == TypeManager.struct_layout_attribute_type && a.GetLayoutKindValue () == LayoutKind.Explicit) {
2661 HasExplicitLayout = true;
2664 base.ApplyAttributeBuilder (a, cb);
2667 public override void Emit()
2671 if (declarative_security != null) {
2672 foreach (DictionaryEntry de in declarative_security) {
2673 TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2680 // TODO: should be sealed
2681 public class Class : ClassOrStruct {
2682 const int AllowedModifiers =
2685 Modifiers.PROTECTED |
2686 Modifiers.INTERNAL |
2688 Modifiers.ABSTRACT |
2693 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2695 : base (ns, parent, name, attrs, Kind.Class)
2697 int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2698 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2700 if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2701 Report.FeatureIsNotStandardized (Location, "static classes");
2705 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2707 if (a.Type == TypeManager.attribute_usage_type) {
2708 if (BaseType != TypeManager.attribute_type && !BaseType.IsSubclassOf (TypeManager.attribute_type) &&
2709 TypeBuilder.FullName != "System.Attribute") {
2710 Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2714 if (a.Type == TypeManager.conditional_attribute_type &&
2715 !(BaseType == TypeManager.attribute_type || BaseType.IsSubclassOf (TypeManager.attribute_type))) {
2716 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2720 if (AttributeTester.IsAttributeExcluded (a.Type))
2723 base.ApplyAttributeBuilder (a, cb);
2726 public override AttributeTargets AttributeTargets {
2728 return AttributeTargets.Class;
2732 protected override void DefineContainerMembers (MemberCoreArrayList list)
2738 base.DefineContainerMembers (list);
2742 foreach (MemberCore m in list) {
2743 if (m is Operator) {
2744 Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2748 if (m is Destructor) {
2749 Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2753 if ((m.ModFlags & Modifiers.PROTECTED) != 0) {
2754 Report.Error (1057, m.Location, "`{0}': Static classes cannot contain protected members", m.GetSignatureForError ());
2759 Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2763 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2766 if (m is Constructor) {
2767 Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2771 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2774 base.DefineContainerMembers (list);
2777 public override void DefineDefaultConstructor ()
2780 DefineDefaultConstructor (false);
2782 base.DefineDefaultConstructor ();
2785 public override TypeBuilder DefineType ()
2787 if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2788 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2792 if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2793 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2797 return base.DefineType ();
2800 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2802 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2804 if (base_class == null) {
2805 if (RootContext.StdLib)
2806 base_class = TypeManager.system_object_expr;
2807 else if (Name != "System.Object")
2808 base_class = TypeManager.system_object_expr;
2810 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2812 689, base_class.Location,
2813 "Cannot derive from `{0}' because it is a type parameter",
2814 base_class.GetSignatureForError ());
2818 if (base_class.Type.IsArray || base_class.Type.IsPointer) {
2819 Report.Error (1521, base_class.Location, "Invalid base type");
2823 if (base_class.IsSealed){
2824 Report.SymbolRelatedToPreviousError (base_class.Type);
2825 if (base_class.Type.IsAbstract) {
2826 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2827 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2829 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2830 GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2835 if (!base_class.CanInheritFrom ()){
2836 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2837 GetSignatureForError (), base_class.GetSignatureForError ());
2841 if (!base_class.AsAccessible (this, ModFlags)) {
2842 Report.SymbolRelatedToPreviousError (base_class.Type);
2843 Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2844 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2849 if (base_class != TypeManager.system_object_expr) {
2850 Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2851 GetSignatureForError (), base_class.GetSignatureForError ());
2855 if (ifaces != null) {
2856 foreach (TypeExpr t in ifaces)
2857 Report.SymbolRelatedToPreviousError (t.Type);
2858 Report.Error (714, Location, "`{0}': static classes cannot implement interfaces", GetSignatureForError ());
2865 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2866 /// Valid only for attribute classes.
2867 public bool IsExcluded ()
2869 if ((caching_flags & Flags.Excluded_Undetected) == 0)
2870 return (caching_flags & Flags.Excluded) != 0;
2872 caching_flags &= ~Flags.Excluded_Undetected;
2874 if (OptAttributes == null)
2877 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2882 foreach (Attribute a in attrs) {
2883 string condition = a.GetConditionalAttributeValue ();
2884 if (RootContext.AllDefines.Contains (condition))
2888 caching_flags |= Flags.Excluded;
2894 return (ModFlags & Modifiers.STATIC) != 0;
2899 // FIXME: How do we deal with the user specifying a different
2902 protected override TypeAttributes TypeAttr {
2904 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2906 ta |= TypeAttributes.Abstract | TypeAttributes.Sealed;
2912 public sealed class Struct : ClassOrStruct {
2914 // Modifiers allowed in a struct declaration
2916 const int AllowedModifiers =
2919 Modifiers.PROTECTED |
2920 Modifiers.INTERNAL |
2924 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2925 int mod, Attributes attrs)
2926 : base (ns, parent, name, attrs, Kind.Struct)
2930 if (parent.Parent == null)
2931 accmods = Modifiers.INTERNAL;
2933 accmods = Modifiers.PRIVATE;
2935 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2937 this.ModFlags |= Modifiers.SEALED;
2940 public override AttributeTargets AttributeTargets {
2942 return AttributeTargets.Struct;
2946 const TypeAttributes DefaultTypeAttributes =
2947 TypeAttributes.SequentialLayout |
2948 TypeAttributes.Sealed |
2949 TypeAttributes.BeforeFieldInit;
2952 public override TypeExpr[] GetClassBases (out TypeExpr base_class)
2954 TypeExpr[] ifaces = base.GetClassBases (out base_class);
2956 // If we are compiling our runtime,
2957 // and we are defining ValueType, then our
2958 // base is `System.Object'.
2960 if (base_class == null) {
2961 if (!RootContext.StdLib && Name == "System.ValueType")
2962 base_class = TypeManager.system_object_expr;
2964 base_class = TypeManager.system_valuetype_expr;
2971 // FIXME: Allow the user to specify a different set of attributes
2972 // in some cases (Sealed for example is mandatory for a class,
2973 // but what SequentialLayout can be changed
2975 protected override TypeAttributes TypeAttr {
2977 return base.TypeAttr | DefaultTypeAttributes;
2981 public override void RegisterFieldForInitialization (FieldBase field)
2983 if ((field.ModFlags & Modifiers.STATIC) == 0) {
2984 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2985 field.GetSignatureForError ());
2988 base.RegisterFieldForInitialization (field);
2996 public sealed class Interface : TypeContainer, IMemberContainer {
2999 /// Modifiers allowed in a class declaration
3001 public const int AllowedModifiers =
3004 Modifiers.PROTECTED |
3005 Modifiers.INTERNAL |
3009 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3011 : base (ns, parent, name, attrs, Kind.Interface)
3015 if (parent.Parent == null)
3016 accmods = Modifiers.INTERNAL;
3018 accmods = Modifiers.PRIVATE;
3020 this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3023 public override AttributeTargets AttributeTargets {
3025 return AttributeTargets.Interface;
3029 const TypeAttributes DefaultTypeAttributes =
3030 TypeAttributes.AutoLayout |
3031 TypeAttributes.Abstract |
3032 TypeAttributes.Interface;
3034 protected override TypeAttributes TypeAttr {
3036 return base.TypeAttr | DefaultTypeAttributes;
3040 protected override bool VerifyClsCompliance ()
3042 if (!base.VerifyClsCompliance ())
3045 if (ifaces != null) {
3046 foreach (Type t in ifaces) {
3047 if (AttributeTester.IsClsCompliant (t))
3050 Report.SymbolRelatedToPreviousError (t);
3051 Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3052 GetSignatureForError (), TypeManager.CSharpName (t));
3060 public abstract class MethodCore : MemberBase {
3061 public readonly Parameters Parameters;
3062 protected ToplevelBlock block;
3064 // Whether this is an operator method.
3065 public Operator IsOperator;
3068 // The method we're overriding if this is an override method.
3070 protected MethodInfo base_method = null;
3072 static string[] attribute_targets = new string [] { "method", "return" };
3074 public MethodCore (DeclSpace parent, GenericMethod generic,
3075 Expression type, int mod, int allowed_mod, bool is_iface,
3076 MemberName name, Attributes attrs, Parameters parameters)
3077 : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3080 Parameters = parameters;
3081 IsInterface = is_iface;
3085 // Returns the System.Type array for the parameters of this method
3087 public Type [] ParameterTypes {
3089 return Parameters.Types;
3093 public Parameters ParameterInfo
3100 public ToplevelBlock Block {
3110 public void SetYields ()
3112 ModFlags |= Modifiers.METHOD_YIELDS;
3115 protected override bool CheckBase ()
3117 if (!base.CheckBase ())
3120 // Check whether arguments were correct.
3121 if (!DoDefineParameters ())
3124 if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
3130 // Is null for System.Object while compiling corlib and base interfaces
3131 if (ParentContainer.BaseCache == null) {
3132 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3133 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3138 Type base_ret_type = null;
3139 if (IsOperator == null)
3140 base_method = FindOutBaseMethod (ref base_ret_type);
3142 // method is override
3143 if (base_method != null) {
3145 if (!CheckMethodAgainstBase ())
3148 if ((ModFlags & Modifiers.NEW) == 0) {
3149 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_ret_type))) {
3150 Report.SymbolRelatedToPreviousError (base_method);
3151 if (this is PropertyBase) {
3152 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3153 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3156 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3157 GetSignatureForError (), TypeManager.CSharpName (base_ret_type), TypeManager.CSharpSignature (base_method));
3162 if (base_method.IsAbstract && !IsInterface) {
3163 Report.SymbolRelatedToPreviousError (base_method);
3164 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3165 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3170 if (base_method.IsSpecialName && !(this is PropertyBase)) {
3171 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3175 if (Name == "Equals" && Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type)
3176 ParentContainer.Mark_HasEquals ();
3177 else if (Name == "GetHashCode" && Parameters.Empty)
3178 ParentContainer.Mark_HasGetHashCode ();
3180 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3181 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3183 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3184 Report.SymbolRelatedToPreviousError (base_method);
3185 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3186 GetSignatureForError (), TypeManager.CSharpSignature (base_method) );
3193 MemberInfo conflict_symbol = ParentContainer.FindBaseMemberWithSameName (Name, !(this is Property));
3194 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3195 if (conflict_symbol != null) {
3196 Report.SymbolRelatedToPreviousError (conflict_symbol);
3197 if (this is PropertyBase)
3198 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3200 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3202 Report.Error (115, Location, "`{0}': no suitable method found to override", GetSignatureForError ());
3206 if (conflict_symbol == null) {
3207 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
3208 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3213 if ((ModFlags & Modifiers.NEW) == 0) {
3214 if (this is Method && conflict_symbol is MethodBase)
3217 Report.SymbolRelatedToPreviousError (conflict_symbol);
3218 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3219 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3226 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3227 // that have been defined.
3229 // `name' is the user visible name for reporting errors (this is used to
3230 // provide the right name regarding method names and properties)
3232 bool CheckMethodAgainstBase ()
3236 if ((ModFlags & Modifiers.OVERRIDE) != 0){
3237 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3238 Report.Error (506, Location,
3239 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3240 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3244 // Now we check that the overriden method is not final
3246 if (base_method.IsFinal) {
3247 Report.SymbolRelatedToPreviousError (base_method);
3248 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3249 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3253 // Check that the permissions are not being changed
3255 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3256 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3258 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3259 Error_CannotChangeAccessModifiers (base_method, base_classp, null);
3264 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0 && Name != "Finalize") {
3265 ModFlags |= Modifiers.NEW;
3266 Report.SymbolRelatedToPreviousError (base_method);
3267 if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3268 Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
3269 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3271 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3272 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3279 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3281 if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3283 // when overriding protected internal, the method can be declared
3284 // protected internal only within the same assembly
3287 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3288 if (Parent.TypeBuilder.Assembly != base_method.DeclaringType.Assembly){
3290 // assemblies differ - report an error
3294 } else if (thisp != base_classp) {
3296 // same assembly, but other attributes differ - report an error
3301 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3303 // if it's not "protected internal", it must be "protected"
3307 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3309 // protected within the same assembly - an error
3312 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) !=
3313 (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3315 // protected ok, but other attributes differ - report an error
3321 return (thisp == base_classp);
3325 public bool CheckAbstractAndExtern (bool has_block)
3327 if (ParentContainer.Kind == Kind.Interface)
3331 if ((ModFlags & Modifiers.EXTERN) != 0) {
3332 Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
3333 GetSignatureForError ());
3337 if ((ModFlags & Modifiers.ABSTRACT) != 0) {
3338 Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
3339 GetSignatureForError ());
3343 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
3344 Report.Error (501, Location, "`{0}' must declare a body because it is not marked abstract or extern",
3345 GetSignatureForError ());
3353 protected void Error_CannotChangeAccessModifiers (MemberInfo base_method, MethodAttributes ma, string suffix)
3355 Report.SymbolRelatedToPreviousError (base_method);
3356 string base_name = TypeManager.GetFullNameSignature (base_method);
3357 string this_name = GetSignatureForError ();
3358 if (suffix != null) {
3359 base_name += suffix;
3360 this_name += suffix;
3363 Report.Error (507, Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3364 this_name, Modifiers.GetDescription (ma), base_name);
3367 protected static string Error722 {
3369 return "`{0}': static types cannot be used as return types";
3374 /// For custom member duplication search in a container
3376 protected abstract bool CheckForDuplications ();
3379 /// Gets base method and its return type
3381 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3383 protected bool DoDefineParameters ()
3385 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3387 // Check if arguments were correct
3388 if (!Parameters.Resolve (rc))
3391 return CheckParameters (ParameterTypes);
3394 bool CheckParameters (Type [] parameters)
3398 foreach (Type partype in parameters){
3399 if (partype == TypeManager.void_type) {
3401 1547, Location, "Keyword 'void' cannot " +
3402 "be used in this context");
3406 if (partype.IsPointer){
3407 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (partype), Location))
3411 if (ds.AsAccessible (partype, ModFlags))
3414 if (this is Indexer)
3415 Report.Error (55, Location,
3416 "Inconsistent accessibility: parameter type `" +
3417 TypeManager.CSharpName (partype) + "' is less " +
3418 "accessible than indexer `" + GetSignatureForError () + "'");
3419 else if ((this is Method) && ((Method) this).IsOperator != null)
3420 Report.Error (57, Location,
3421 "Inconsistent accessibility: parameter type `" +
3422 TypeManager.CSharpName (partype) + "' is less " +
3423 "accessible than operator `" + GetSignatureForError () + "'");
3425 Report.Error (51, Location,
3426 "Inconsistent accessibility: parameter type `" +
3427 TypeManager.CSharpName (partype) + "' is less " +
3428 "accessible than method `" + GetSignatureForError () + "'");
3435 public override string[] ValidAttributeTargets {
3437 return attribute_targets;
3441 protected override bool VerifyClsCompliance ()
3443 if (!base.VerifyClsCompliance ()) {
3444 if ((ModFlags & Modifiers.ABSTRACT) != 0 && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3445 Report.Error (3011, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3450 if (Parameters.HasArglist) {
3451 Report.Error (3000, Location, "Methods with variable arguments are not CLS-compliant");
3454 if (!AttributeTester.IsClsCompliant (MemberType)) {
3455 if (this is PropertyBase)
3456 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant",
3457 GetSignatureForError ());
3459 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant",
3460 GetSignatureForError ());
3463 Parameters.VerifyClsCompliance ();
3468 protected bool IsDuplicateImplementation (MethodCore method)
3470 if (method == this || !(method.MemberName.Equals (MemberName)))
3473 Type[] param_types = method.ParameterTypes;
3474 // This never happen. Rewrite this as Equal
3475 if (param_types == null && ParameterTypes == null)
3477 if (param_types == null || ParameterTypes == null)
3480 if (param_types.Length != ParameterTypes.Length)
3483 if (method.Parameters.HasArglist != Parameters.HasArglist)
3488 for (int i = 0; i < param_types.Length; i++) {
3489 if (param_types [i] != ParameterTypes [i])
3493 if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
3496 // TODO: make operator compatible with MethodCore to avoid this
3497 if (this is Operator && method is Operator) {
3498 if (MemberType != method.MemberType)
3504 // Try to report 663: method only differs on out/ref
3506 Parameters info = ParameterInfo;
3507 Parameters other_info = method.ParameterInfo;
3508 for (int i = 0; i < info.Count; i++){
3510 if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
3511 Report.SymbolRelatedToPreviousError (method);
3512 Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
3513 GetSignatureForError ());
3516 Console.WriteLine ("Method is: {0} {1}", method.Location, method);
3517 Console.WriteLine ("this is: {0} {1}", Location, this);
3521 Report.SymbolRelatedToPreviousError (method);
3522 if (this is Operator && method is Operator)
3523 Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
3525 Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
3533 public override bool IsUsed {
3534 get { return IsExplicitImpl || base.IsUsed; }
3538 // Returns a string that represents the signature for this
3539 // member which should be used in XML documentation.
3541 public override string GetDocCommentName (DeclSpace ds)
3543 return DocUtil.GetMethodDocCommentName (this, ds);
3547 // Raised (and passed an XmlElement that contains the comment)
3548 // when GenerateDocComment is writing documentation expectedly.
3550 // FIXME: with a few effort, it could be done with XmlReader,
3551 // that means removal of DOM use.
3553 internal override void OnGenerateDocComment (XmlElement el)
3555 DocUtil.OnMethodGenerateDocComment (this, el);
3559 // Represents header string for documentation comment.
3561 public override string DocCommentHeader {
3562 get { return "M:"; }
3567 public class SourceMethod : ISourceMethod
3572 protected SourceMethod (DeclSpace parent, MethodBase builder,
3573 ISourceFile file, Location start, Location end)
3575 this.parent = parent;
3576 this.builder = builder;
3578 CodeGen.SymbolWriter.OpenMethod (file, this, start.Row, start.Column, end.Row, start.Column);
3581 public string Name {
3582 get { return builder.Name; }
3585 public int NamespaceID {
3586 get { return parent.NamespaceEntry.SymbolFileID; }
3591 if (builder is MethodBuilder)
3592 return ((MethodBuilder) builder).GetToken ().Token;
3593 else if (builder is ConstructorBuilder)
3594 return ((ConstructorBuilder) builder).GetToken ().Token;
3596 throw new NotSupportedException ();
3600 public void CloseMethod ()
3602 if (CodeGen.SymbolWriter != null)
3603 CodeGen.SymbolWriter.CloseMethod ();
3606 public static SourceMethod Create (DeclSpace parent, MethodBase builder, Block block)
3608 if (CodeGen.SymbolWriter == null)
3613 Location start_loc = block.StartLocation;
3614 if (start_loc.IsNull)
3617 Location end_loc = block.EndLocation;
3621 ISourceFile file = start_loc.SourceFile;
3625 return new SourceMethod (
3626 parent, builder, file, start_loc, end_loc);
3630 public class Method : MethodCore, IIteratorContainer, IMethodData {
3631 public MethodBuilder MethodBuilder;
3632 public MethodData MethodData;
3633 ReturnParameter return_attributes;
3634 ListDictionary declarative_security;
3637 /// Modifiers allowed in a class declaration
3639 const int AllowedModifiers =
3642 Modifiers.PROTECTED |
3643 Modifiers.INTERNAL |
3648 Modifiers.OVERRIDE |
3649 Modifiers.ABSTRACT |
3651 Modifiers.METHOD_YIELDS |
3654 const int AllowedInterfaceModifiers =
3655 Modifiers.NEW | Modifiers.UNSAFE;
3658 // return_type can be "null" for VOID values.
3660 public Method (DeclSpace parent, GenericMethod generic,
3661 Expression return_type, int mod, bool is_iface,
3662 MemberName name, Parameters parameters, Attributes attrs)
3663 : base (parent, generic, return_type, mod,
3664 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
3665 is_iface, name, attrs, parameters)
3669 public override AttributeTargets AttributeTargets {
3671 return AttributeTargets.Method;
3675 public override string GetSignatureForError()
3677 if (IsOperator != null)
3678 return IsOperator.GetSignatureForError ();
3680 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
3683 void DuplicateEntryPoint (MethodInfo b, Location location)
3687 "Program `" + CodeGen.FileName +
3688 "' has more than one entry point defined: `" +
3689 TypeManager.CSharpSignature(b) + "'");
3692 bool IsEntryPoint (MethodBuilder b, Parameters pinfo)
3694 if (b.ReturnType != TypeManager.void_type &&
3695 b.ReturnType != TypeManager.int32_type)
3698 if (pinfo.Count == 0)
3701 if (pinfo.Count > 1)
3704 Type t = pinfo.ParameterType(0);
3706 (t.GetArrayRank() == 1) &&
3707 (TypeManager.GetElementType(t) == TypeManager.string_type) &&
3708 (pinfo.ParameterModifier(0) == Parameter.Modifier.NONE))
3714 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3716 if (a.Target == AttributeTargets.ReturnValue) {
3717 if (return_attributes == null)
3718 return_attributes = new ReturnParameter (MethodBuilder, Location);
3720 return_attributes.ApplyAttributeBuilder (a, cb);
3724 if (a.Type == TypeManager.methodimpl_attr_type &&
3725 (a.GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0) {
3726 MethodBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall | MethodImplAttributes.Runtime);
3729 if (a.Type == TypeManager.dllimport_type) {
3730 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3731 if ((ModFlags & extern_static) != extern_static) {
3732 Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3738 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
3739 if (declarative_security == null)
3740 declarative_security = new ListDictionary ();
3741 a.ExtractSecurityPermissionSet (declarative_security);
3745 if (a.Type == TypeManager.conditional_attribute_type) {
3746 if (IsOperator != null || IsExplicitImpl) {
3747 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3748 GetSignatureForError ());
3752 if (ReturnType != TypeManager.void_type) {
3753 Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
3757 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3758 Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
3763 Report.Error (582, Location, "Conditional not valid on interface members");
3767 if (MethodData.implementing != null) {
3768 Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
3769 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
3773 for (int i = 0; i < ParameterInfo.Count; ++i) {
3774 if ((ParameterInfo.ParameterModifier (i) & Parameter.Modifier.OUTMASK) != 0) {
3775 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
3781 MethodBuilder.SetCustomAttribute (cb);
3784 protected override bool CheckForDuplications ()
3786 ArrayList ar = ParentContainer.Methods;
3788 int arLen = ar.Count;
3790 for (int i = 0; i < arLen; i++) {
3791 Method m = (Method) ar [i];
3792 if (IsDuplicateImplementation (m))
3797 ar = ParentContainer.Properties;
3799 for (int i = 0; i < ar.Count; ++i) {
3800 PropertyBase pb = (PropertyBase) ar [i];
3801 if (pb.AreAccessorsDuplicateImplementation (this))
3806 ar = ParentContainer.Indexers;
3808 for (int i = 0; i < ar.Count; ++i) {
3809 PropertyBase pb = (PropertyBase) ar [i];
3810 if (pb.AreAccessorsDuplicateImplementation (this))
3815 ar = ParentContainer.Events;
3817 for (int i = 0; i < ar.Count; ++i) {
3818 Event ev = (Event) ar [i];
3819 if (ev.AreAccessorsDuplicateImplementation (this))
3830 public override bool Define ()
3832 if (!DoDefineBase ())
3835 MethodBuilder mb = null;
3836 if (GenericMethod != null) {
3837 string method_name = MemberName.Name;
3839 if (IsExplicitImpl) {
3840 method_name = TypeManager.CSharpName (InterfaceType) +
3844 mb = Parent.TypeBuilder.DefineMethod (method_name, flags);
3846 if (!GenericMethod.Define (mb))
3853 if (!CheckAbstractAndExtern (block != null))
3856 if (RootContext.StdLib && (ReturnType == TypeManager.arg_iterator_type || ReturnType == TypeManager.typed_reference_type)) {
3857 Error1599 (Location, ReturnType);
3864 if (IsOperator != null)
3865 flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
3867 MethodData = new MethodData (this, ModFlags, flags, this, mb, GenericMethod, base_method);
3869 if (!MethodData.Define (ParentContainer))
3872 if (ReturnType == TypeManager.void_type && ParameterTypes.Length == 0 &&
3873 Name == "Finalize" && !(this is Destructor)) {
3874 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
3878 // Setup iterator if we are one
3880 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
3881 Iterator iterator = new Iterator (
3882 this, Parent, GenericMethod, ModFlags);
3884 if (!iterator.DefineIterator ())
3888 MethodBuilder = MethodData.MethodBuilder;
3891 // This is used to track the Entry Point,
3893 if (Name == "Main" &&
3894 ((ModFlags & Modifiers.STATIC) != 0) && RootContext.NeedsEntryPoint &&
3895 (RootContext.MainClass == null ||
3896 RootContext.MainClass == Parent.TypeBuilder.FullName)){
3897 if (IsEntryPoint (MethodBuilder, ParameterInfo)) {
3898 IMethodData md = TypeManager.GetMethod (MethodBuilder);
3899 md.SetMemberIsUsed ();
3901 if (RootContext.EntryPoint == null) {
3902 if (Parent.IsGeneric){
3903 Report.Error (-201, Location,
3904 "Entry point can not be defined in a generic class");
3907 RootContext.EntryPoint = MethodBuilder;
3908 RootContext.EntryPointLocation = Location;
3910 DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
3911 DuplicateEntryPoint (MethodBuilder, Location);
3914 if (RootContext.WarningLevel >= 4)
3915 Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point", TypeManager.CSharpSignature(MethodBuilder));
3919 if (MemberType.IsAbstract && MemberType.IsSealed) {
3920 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3930 public override void Emit ()
3932 MethodData.Emit (Parent);
3935 if (declarative_security != null) {
3936 foreach (DictionaryEntry de in declarative_security) {
3937 MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3945 public static void Error1599 (Location loc, Type t)
3947 Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
3950 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
3952 MethodInfo mi = (MethodInfo) ParentContainer.BaseCache.FindMemberToOverride (
3953 Parent.TypeBuilder, Name, ParameterTypes, GenericMethod, false);
3958 base_ret_type = mi.ReturnType;
3962 public override bool MarkForDuplicationCheck ()
3964 caching_flags |= Flags.TestMethodDuplication;
3968 protected override bool VerifyClsCompliance ()
3970 if (!base.VerifyClsCompliance ())
3973 if (ParameterInfo.Count > 0) {
3974 ArrayList al = (ArrayList)ParentContainer.MemberCache.Members [Name];
3976 MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
3982 #region IMethodData Members
3984 public CallingConventions CallingConventions {
3986 CallingConventions cc = Parameters.CallingConvention;
3987 if (Parameters.HasArglist)
3988 block.HasVarargs = true;
3991 if ((ModFlags & Modifiers.STATIC) == 0)
3992 cc |= CallingConventions.HasThis;
3994 // FIXME: How is `ExplicitThis' used in C#?
4000 public Type ReturnType {
4006 public MemberName MethodName {
4012 public new Location Location {
4014 return base.Location;
4018 protected override bool CheckBase() {
4019 if (!base.CheckBase ())
4022 // TODO: Destructor should derive from MethodCore
4023 if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
4024 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
4025 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
4032 public EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
4034 EmitContext ec = new EmitContext (this,
4035 tc, this.ds, Location, ig, ReturnType, ModFlags, false);
4037 Iterator iterator = tc as Iterator;
4038 if (iterator != null)
4039 ec.CurrentAnonymousMethod = iterator.Host;
4045 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
4047 public bool IsExcluded ()
4049 if ((caching_flags & Flags.Excluded_Undetected) == 0)
4050 return (caching_flags & Flags.Excluded) != 0;
4052 caching_flags &= ~Flags.Excluded_Undetected;
4054 if (base_method == null) {
4055 if (OptAttributes == null)
4058 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
4063 foreach (Attribute a in attrs) {
4064 string condition = a.GetConditionalAttributeValue ();
4065 if (RootContext.AllDefines.Contains (condition))
4069 caching_flags |= Flags.Excluded;
4073 IMethodData md = TypeManager.GetMethod (base_method);
4075 if (AttributeTester.IsConditionalMethodExcluded (base_method)) {
4076 caching_flags |= Flags.Excluded;
4082 if (md.IsExcluded ()) {
4083 caching_flags |= Flags.Excluded;
4089 GenericMethod IMethodData.GenericMethod {
4091 return GenericMethod;
4098 public abstract class ConstructorInitializer {
4099 ArrayList argument_list;
4100 protected ConstructorInfo base_constructor;
4103 public ConstructorInitializer (ArrayList argument_list, Location loc)
4105 this.argument_list = argument_list;
4109 public ArrayList Arguments {
4111 return argument_list;
4115 public bool Resolve (ConstructorBuilder caller_builder, Block block, EmitContext ec)
4117 Expression base_constructor_group;
4121 ec.CurrentBlock = block;
4123 if (argument_list != null){
4124 foreach (Argument a in argument_list){
4125 if (!a.Resolve (ec, loc))
4129 ec.CurrentBlock = null;
4131 if (this is ConstructorBaseInitializer) {
4132 if (ec.ContainerType.BaseType == null)
4135 t = ec.ContainerType.BaseType;
4136 if (ec.ContainerType.IsValueType) {
4137 Report.Error (522, loc,
4138 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4142 t = ec.ContainerType;
4144 base_constructor_group = Expression.MemberLookup (
4145 ec.ContainerType, t, ".ctor", MemberTypes.Constructor,
4146 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4149 if (base_constructor_group == null){
4151 base_constructor_group = Expression.MemberLookup (
4152 t, null, t, ".ctor", MemberTypes.Constructor,
4153 BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4157 int errors = Report.Errors;
4158 if (base_constructor_group != null)
4159 base_constructor = (ConstructorInfo) Invocation.OverloadResolve (
4160 ec, (MethodGroupExpr) base_constructor_group, argument_list,
4163 if (base_constructor == null) {
4164 if (errors == Report.Errors)
4165 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpSignature (caller_builder),
4166 argument_list == null ? 0 : argument_list.Count);
4171 Expression.ErrorIsInaccesible (loc, TypeManager.CSharpSignature (base_constructor));
4172 base_constructor = null;
4176 if (base_constructor == caller_builder){
4177 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4184 public virtual void Emit (EmitContext ec)
4186 if (base_constructor != null){
4187 ec.Mark (loc, false);
4189 Invocation.EmitCall (ec, true, true, null, base_constructor, argument_list, loc);
4191 Invocation.EmitCall (ec, true, false, ec.GetThis (loc), base_constructor, argument_list, loc);
4196 public class ConstructorBaseInitializer : ConstructorInitializer {
4197 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4198 base (argument_list, l)
4203 class GeneratedBaseInitializer: ConstructorBaseInitializer {
4204 public GeneratedBaseInitializer (Location loc):
4210 public class ConstructorThisInitializer : ConstructorInitializer {
4211 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4212 base (argument_list, l)
4217 public class Constructor : MethodCore, IMethodData {
4218 public ConstructorBuilder ConstructorBuilder;
4219 public ConstructorInitializer Initializer;
4220 ListDictionary declarative_security;
4223 // Modifiers allowed for a constructor.
4225 public const int AllowedModifiers =
4227 Modifiers.PROTECTED |
4228 Modifiers.INTERNAL |
4234 bool has_compliant_args = false;
4236 // The spec claims that static is not permitted, but
4237 // my very own code has static constructors.
4239 public Constructor (DeclSpace parent, string name, int mod, Parameters args,
4240 ConstructorInitializer init, Location loc)
4241 : base (parent, null, null, mod, AllowedModifiers, false,
4242 new MemberName (name, loc), null, args)
4247 public bool HasCompliantArgs {
4248 get { return has_compliant_args; }
4251 public override AttributeTargets AttributeTargets {
4252 get { return AttributeTargets.Constructor; }
4257 // Returns true if this is a default constructor
4259 public bool IsDefault ()
4261 if ((ModFlags & Modifiers.STATIC) != 0)
4262 return Parameters.Empty;
4264 return Parameters.Empty &&
4265 (Initializer is ConstructorBaseInitializer) &&
4266 (Initializer.Arguments == null);
4269 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4271 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
4272 if (declarative_security == null) {
4273 declarative_security = new ListDictionary ();
4275 a.ExtractSecurityPermissionSet (declarative_security);
4279 ConstructorBuilder.SetCustomAttribute (cb);
4282 protected override bool CheckForDuplications ()
4284 ArrayList ar = ParentContainer.InstanceConstructors;
4286 int arLen = ar.Count;
4288 for (int i = 0; i < arLen; i++) {
4289 Constructor m = (Constructor) ar [i];
4290 if (IsDuplicateImplementation (m))
4297 protected override bool CheckBase ()
4299 // Check whether arguments were correct.
4300 if (!DoDefineParameters ())
4303 // TODO: skip the rest for generated ctor
4304 if ((ModFlags & Modifiers.STATIC) != 0)
4307 if (!CheckForDuplications ())
4310 if (ParentContainer.Kind == Kind.Struct) {
4311 if (ParameterTypes.Length == 0) {
4312 Report.Error (568, Location,
4313 "Structs cannot contain explicit parameterless constructors");
4317 if ((ModFlags & Modifiers.PROTECTED) != 0) {
4318 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
4323 if ((RootContext.WarningLevel >= 4) && ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.PROTECTED) != 0)) {
4324 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
4331 // Creates the ConstructorBuilder
4333 public override bool Define ()
4335 if (ConstructorBuilder != null)
4338 MethodAttributes ca = (MethodAttributes.RTSpecialName |
4339 MethodAttributes.SpecialName);
4341 if ((ModFlags & Modifiers.STATIC) != 0){
4342 ca |= MethodAttributes.Static | MethodAttributes.Private;
4344 ca |= MethodAttributes.HideBySig;
4346 if ((ModFlags & Modifiers.PUBLIC) != 0)
4347 ca |= MethodAttributes.Public;
4348 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4349 if ((ModFlags & Modifiers.INTERNAL) != 0)
4350 ca |= MethodAttributes.FamORAssem;
4352 ca |= MethodAttributes.Family;
4353 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4354 ca |= MethodAttributes.Assembly;
4355 else if (IsDefault ())
4356 ca |= MethodAttributes.Public;
4358 ca |= MethodAttributes.Private;
4361 if (!CheckAbstractAndExtern (block != null))
4364 // Check if arguments were correct.
4368 ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4369 ca, CallingConventions,
4372 if ((ModFlags & Modifiers.UNSAFE) != 0)
4373 ConstructorBuilder.InitLocals = false;
4375 if (ParentContainer.IsComImport) {
4376 if (!IsDefault ()) {
4377 Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4378 Parent.GetSignatureForError ());
4381 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4384 TypeManager.AddMethod (ConstructorBuilder, this);
4392 public override void Emit ()
4394 EmitContext ec = CreateEmitContext (null, null);
4396 // If this is a non-static `struct' constructor and doesn't have any
4397 // initializer, it must initialize all of the struct's fields.
4398 if ((ParentContainer.Kind == Kind.Struct) &&
4399 ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4400 Block.AddThisVariable (Parent, Location);
4402 if (block != null) {
4403 if (!block.ResolveMeta (ec, ParameterInfo))
4407 if ((ModFlags & Modifiers.STATIC) == 0){
4408 if (ParentContainer.Kind == Kind.Class && Initializer == null)
4409 Initializer = new GeneratedBaseInitializer (Location);
4413 // Spec mandates that Initializers will not have
4417 if ((Initializer != null) &&
4418 !Initializer.Resolve (ConstructorBuilder, block, ec))
4420 ec.IsStatic = false;
4423 Parameters.ApplyAttributes (ConstructorBuilder);
4425 SourceMethod source = SourceMethod.Create (
4426 Parent, ConstructorBuilder, block);
4429 // Classes can have base initializers and instance field initializers.
4431 if (ParentContainer.Kind == Kind.Class){
4432 if ((ModFlags & Modifiers.STATIC) == 0){
4435 // If we use a "this (...)" constructor initializer, then
4436 // do not emit field initializers, they are initialized in the other constructor
4438 if (!(Initializer != null && Initializer is ConstructorThisInitializer))
4439 ParentContainer.EmitFieldInitializers (ec);
4442 if (Initializer != null) {
4443 Initializer.Emit (ec);
4446 if ((ModFlags & Modifiers.STATIC) != 0)
4447 ParentContainer.EmitFieldInitializers (ec);
4449 if (OptAttributes != null)
4450 OptAttributes.Emit ();
4452 ec.EmitTopBlock (this, block);
4455 source.CloseMethod ();
4459 if (declarative_security != null) {
4460 foreach (DictionaryEntry de in declarative_security) {
4461 ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4468 // Is never override
4469 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4474 public override string GetSignatureForError()
4476 return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4479 protected override bool VerifyClsCompliance ()
4481 if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4485 if (ParameterInfo.Count > 0) {
4486 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4488 MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4490 if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
4491 foreach (Type param in ParameterTypes) {
4492 if (param.IsArray) {
4498 has_compliant_args = true;
4502 #region IMethodData Members
4504 public System.Reflection.CallingConventions CallingConventions {
4506 CallingConventions cc = Parameters.CallingConvention;
4508 if (ParentContainer.Kind == Kind.Class)
4509 if ((ModFlags & Modifiers.STATIC) == 0)
4510 cc |= CallingConventions.HasThis;
4512 // FIXME: How is `ExplicitThis' used in C#?
4518 public new Location Location {
4520 return base.Location;
4524 public MemberName MethodName {
4530 public Type ReturnType {
4536 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4538 ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4539 return new EmitContext (this, Parent, Location, ig_, null, ModFlags, true);
4542 public bool IsExcluded()
4547 GenericMethod IMethodData.GenericMethod {
4557 /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4559 public interface IMethodData
4561 CallingConventions CallingConventions { get; }
4562 Location Location { get; }
4563 MemberName MethodName { get; }
4564 Type ReturnType { get; }
4565 GenericMethod GenericMethod { get; }
4566 Parameters ParameterInfo { get; }
4568 Attributes OptAttributes { get; }
4569 ToplevelBlock Block { get; set; }
4571 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4572 ObsoleteAttribute GetObsoleteAttribute ();
4573 string GetSignatureForError ();
4575 bool IsClsComplianceRequired ();
4576 void SetMemberIsUsed ();
4580 // Encapsulates most of the Method's state
4582 public class MethodData {
4584 readonly IMethodData method;
4586 public readonly GenericMethod GenericMethod;
4589 // Are we implementing an interface ?
4591 public MethodInfo implementing;
4596 protected MemberBase member;
4597 protected int modifiers;
4598 protected MethodAttributes flags;
4599 protected Type declaring_type;
4600 protected MethodInfo parent_method;
4602 MethodBuilder builder = null;
4603 public MethodBuilder MethodBuilder {
4609 public Type DeclaringType {
4611 return declaring_type;
4615 public MethodData (MemberBase member,
4616 int modifiers, MethodAttributes flags, IMethodData method)
4618 this.member = member;
4619 this.modifiers = modifiers;
4622 this.method = method;
4625 public MethodData (MemberBase member,
4626 int modifiers, MethodAttributes flags,
4627 IMethodData method, MethodBuilder builder,
4628 GenericMethod generic, MethodInfo parent_method)
4629 : this (member, modifiers, flags, method)
4631 this.builder = builder;
4632 this.GenericMethod = generic;
4633 this.parent_method = parent_method;
4636 public bool Define (DeclSpace parent)
4638 string name = method.MethodName.Basename;
4639 string method_name = method.MethodName.FullName;
4641 TypeContainer container = ((TypeContainer) parent).PartialContainer;
4643 PendingImplementation pending = container.PendingImplementations;
4644 if (pending != null){
4645 if (member is Indexer) // TODO: test it, but it should work without this IF
4646 implementing = pending.IsInterfaceIndexer (
4647 member.InterfaceType, method.ReturnType, method.ParameterInfo);
4649 implementing = pending.IsInterfaceMethod (
4650 member.InterfaceType, name, method.ReturnType, method.ParameterInfo);
4652 if (member.InterfaceType != null){
4653 if (implementing == null){
4654 if (member is PropertyBase) {
4655 Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4656 method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4657 member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4660 Report.Error (539, method.Location,
4661 "`{0}.{1}' in explicit interface declaration is not a member of interface",
4662 TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4666 if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4667 Report.SymbolRelatedToPreviousError (implementing);
4668 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4669 member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4673 method_name = TypeManager.GetFullName (member.InterfaceType) +
4676 if (implementing != null) {
4677 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4678 if (prop_method != null) {
4679 if (!implementing.IsSpecialName) {
4680 Report.SymbolRelatedToPreviousError (implementing);
4681 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4682 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4685 PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4686 if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4687 Report.SymbolRelatedToPreviousError (implementing);
4688 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4689 method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4698 // For implicit implementations, make sure we are public, for
4699 // explicit implementations, make sure we are private.
4701 if (implementing != null){
4703 // Setting null inside this block will trigger a more
4704 // verbose error reporting for missing interface implementations
4706 // The "candidate" function has been flagged already
4707 // but it wont get cleared
4709 if (member.IsExplicitImpl){
4710 if ((modifiers & (Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0){
4711 Modifiers.Error_InvalidModifier (method.Location, "public, virtual or abstract");
4712 implementing = null;
4714 } else if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public){
4715 if (TypeManager.IsInterfaceType (implementing.DeclaringType)){
4717 // If this is an interface method implementation,
4718 // check for public accessibility
4720 implementing = null;
4721 } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4722 // We may never be private.
4723 implementing = null;
4724 } else if ((modifiers & Modifiers.OVERRIDE) == 0){
4726 // We may be protected if we're overriding something.
4728 implementing = null;
4733 // Static is not allowed
4735 if ((modifiers & Modifiers.STATIC) != 0){
4736 implementing = null;
4741 // If implementing is still valid, set flags
4743 if (implementing != null){
4745 // When implementing interface methods, set NewSlot
4746 // unless, we are overwriting a method.
4748 if (implementing.DeclaringType.IsInterface){
4749 if ((modifiers & Modifiers.OVERRIDE) == 0)
4750 flags |= MethodAttributes.NewSlot;
4753 MethodAttributes.Virtual |
4754 MethodAttributes.HideBySig;
4756 // Set Final unless we're virtual, abstract or already overriding a method.
4757 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
4758 flags |= MethodAttributes.Final;
4761 EmitContext ec = method.CreateEmitContext (container, null);
4763 DefineMethodBuilder (container, method_name, method.ParameterInfo.Types);
4765 if (builder == null)
4768 if (container.CurrentType != null)
4769 declaring_type = container.CurrentType;
4771 declaring_type = container.TypeBuilder;
4773 if ((modifiers & Modifiers.UNSAFE) != 0)
4774 builder.InitLocals = false;
4776 if (implementing != null){
4778 // clear the pending implemntation flag
4780 if (member is Indexer) {
4781 pending.ImplementIndexer (
4782 member.InterfaceType, builder, method.ReturnType,
4783 method.ParameterInfo, member.IsExplicitImpl);
4785 pending.ImplementMethod (
4786 member.InterfaceType, name, method.ReturnType,
4787 method.ParameterInfo, member.IsExplicitImpl);
4789 if (member.IsExplicitImpl)
4790 container.TypeBuilder.DefineMethodOverride (
4791 builder, implementing);
4795 TypeManager.AddMethod (builder, method);
4797 if (GenericMethod != null) {
4798 bool is_override = member.IsExplicitImpl |
4799 ((modifiers & Modifiers.OVERRIDE) != 0);
4801 if (implementing != null)
4802 parent_method = implementing;
4804 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
4813 /// Create the MethodBuilder for the method
4815 void DefineMethodBuilder (TypeContainer container, string method_name, Type[] ParameterTypes)
4817 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
4819 if ((modifiers & extern_static) == extern_static) {
4821 if (method.OptAttributes != null) {
4822 Attribute dllimport_attribute = method.OptAttributes.Search (TypeManager.dllimport_type);
4823 if (dllimport_attribute != null) {
4824 flags |= MethodAttributes.PinvokeImpl;
4825 builder = dllimport_attribute.DefinePInvokeMethod (
4826 container.TypeBuilder, method_name, flags,
4827 method.ReturnType, ParameterTypes);
4833 // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
4834 // We are more strict than Microsoft and report CS0626 like error
4835 if (method.OptAttributes == null ||
4836 !method.OptAttributes.Contains (TypeManager.methodimpl_attr_type)) {
4837 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",
4838 method.GetSignatureForError ());
4843 if (builder == null) {
4844 builder = container.TypeBuilder.DefineMethod (
4845 method_name, flags, method.CallingConventions,
4846 method.ReturnType, ParameterTypes);
4850 builder.SetGenericMethodSignature (
4851 flags, method.CallingConventions,
4852 method.ReturnType, ParameterTypes);
4859 public void Emit (DeclSpace parent)
4862 if ((flags & MethodAttributes.PinvokeImpl) == 0)
4863 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
4865 ec = method.CreateEmitContext (parent, null);
4867 method.ParameterInfo.ApplyAttributes (MethodBuilder);
4869 Attributes OptAttributes = method.OptAttributes;
4871 if (OptAttributes != null)
4872 OptAttributes.Emit ();
4874 if (GenericMethod != null)
4875 GenericMethod.EmitAttributes ();
4877 ToplevelBlock block = method.Block;
4879 SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
4882 // Handle destructors specially
4884 // FIXME: This code generates buggy code
4886 if (member is Destructor)
4887 EmitDestructor (ec, block);
4889 ec.EmitTopBlock (method, block);
4892 source.CloseMethod ();
4895 void EmitDestructor (EmitContext ec, ToplevelBlock block)
4897 ILGenerator ig = ec.ig;
4899 Label finish = ig.DefineLabel ();
4901 block.SetDestructor ();
4903 ig.BeginExceptionBlock ();
4904 ec.ReturnLabel = finish;
4905 ec.HasReturnLabel = true;
4906 ec.EmitTopBlock (method, block);
4908 // ig.MarkLabel (finish);
4909 ig.BeginFinallyBlock ();
4911 if (ec.ContainerType.BaseType != null) {
4912 Expression member_lookup = Expression.MemberLookup (
4913 ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
4914 "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
4916 if (member_lookup != null){
4917 MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
4919 ig.Emit (OpCodes.Ldarg_0);
4920 ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
4924 ig.EndExceptionBlock ();
4925 //ig.MarkLabel (ec.ReturnLabel);
4926 ig.Emit (OpCodes.Ret);
4930 // TODO: Should derive from MethodCore
4931 public class Destructor : Method {
4933 public Destructor (DeclSpace parent, Expression return_type, int mod,
4934 string name, Parameters parameters, Attributes attrs,
4936 : base (parent, null, return_type, mod, false, new MemberName (name, l),
4940 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
4942 if (a.Type == TypeManager.conditional_attribute_type) {
4943 Report.Error (577, Location, "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
4944 GetSignatureForError ());
4948 base.ApplyAttributeBuilder (a, cb);
4951 public override string GetSignatureForError ()
4953 return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
4958 abstract public class MemberBase : MemberCore {
4959 public Expression Type;
4961 public MethodAttributes flags;
4962 public readonly DeclSpace ds;
4963 public readonly GenericMethod GenericMethod;
4965 protected readonly int explicit_mod_flags;
4968 // The "short" name of this property / indexer / event. This is the
4969 // name without the explicit interface.
4971 public string ShortName {
4972 get { return MemberName.Name; }
4973 set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
4976 public TypeContainer ParentContainer {
4977 get { return ((TypeContainer) Parent).PartialContainer; }
4981 // The type of this property / indexer / event
4983 protected Type member_type;
4984 public Type MemberType {
4986 if (member_type == null && Type != null) {
4987 IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
4988 Type = Type.ResolveAsTypeTerminal (rc, false);
4990 member_type = Type.Type;
4998 // Whether this is an interface member.
5000 public bool IsInterface;
5003 // If true, this is an explicit interface implementation
5005 public bool IsExplicitImpl;
5008 // The interface type we are explicitly implementing
5010 public Type InterfaceType = null;
5013 // The constructor is only exposed to our children
5015 protected MemberBase (DeclSpace parent, GenericMethod generic,
5016 Expression type, int mod, int allowed_mod, int def_mod,
5017 MemberName name, Attributes attrs)
5018 : base (parent, name, attrs)
5020 this.ds = generic != null ? generic : (DeclSpace) parent;
5021 explicit_mod_flags = mod;
5023 ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5024 IsExplicitImpl = (MemberName.Left != null);
5025 GenericMethod = generic;
5026 if (GenericMethod != null)
5027 GenericMethod.ModFlags = ModFlags;
5030 protected virtual bool CheckBase ()
5032 if ((ModFlags & Modifiers.PROTECTED) != 0 && ParentContainer.Kind == Kind.Struct) {
5033 Report.Error (666, Location, "`{0}': new protected member declared in struct", GetSignatureForError ());
5037 if ((RootContext.WarningLevel >= 4) &&
5038 ((Parent.ModFlags & Modifiers.SEALED) != 0) &&
5039 ((ModFlags & Modifiers.PROTECTED) != 0) &&
5040 ((ModFlags & Modifiers.OVERRIDE) == 0) && (Name != "Finalize")) {
5041 Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class", GetSignatureForError ());
5046 protected virtual bool DoDefineBase ()
5049 throw new InternalErrorException ();
5052 ModFlags = Modifiers.PUBLIC |
5053 Modifiers.ABSTRACT |
5054 Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
5056 flags = MethodAttributes.Public |
5057 MethodAttributes.Abstract |
5058 MethodAttributes.HideBySig |
5059 MethodAttributes.NewSlot |
5060 MethodAttributes.Virtual;
5062 if (!ParentContainer.MethodModifiersValid (this))
5065 flags = Modifiers.MethodAttr (ModFlags);
5068 if (IsExplicitImpl) {
5069 Expression expr = MemberName.Left.GetTypeExpression ();
5070 TypeExpr iface_texpr = expr.ResolveAsTypeTerminal (this, false);
5071 if (iface_texpr == null)
5074 InterfaceType = iface_texpr.Type;
5076 if (!InterfaceType.IsInterface) {
5077 Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5081 if (!ParentContainer.VerifyImplements (this))
5084 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5090 protected virtual bool DoDefine ()
5092 if (MemberType == null)
5095 if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5096 (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
5097 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5098 GetSignatureForError (), Parent.GetSignatureForError ());
5102 // verify accessibility
5103 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5104 Report.SymbolRelatedToPreviousError (MemberType);
5105 if (this is Property)
5106 Report.Error (53, Location,
5107 "Inconsistent accessibility: property type `" +
5108 TypeManager.CSharpName (MemberType) + "' is less " +
5109 "accessible than property `" + GetSignatureForError () + "'");
5110 else if (this is Indexer)
5111 Report.Error (54, Location,
5112 "Inconsistent accessibility: indexer return type `" +
5113 TypeManager.CSharpName (MemberType) + "' is less " +
5114 "accessible than indexer `" + GetSignatureForError () + "'");
5115 else if (this is MethodCore) {
5116 if (this is Operator)
5117 Report.Error (56, Location,
5118 "Inconsistent accessibility: return type `" +
5119 TypeManager.CSharpName (MemberType) + "' is less " +
5120 "accessible than operator `" + GetSignatureForError () + "'");
5122 Report.Error (50, Location,
5123 "Inconsistent accessibility: return type `" +
5124 TypeManager.CSharpName (MemberType) + "' is less " +
5125 "accessible than method `" + GetSignatureForError () + "'");
5127 Report.Error (52, Location,
5128 "Inconsistent accessibility: field type `" +
5129 TypeManager.CSharpName (MemberType) + "' is less " +
5130 "accessible than field `" + GetSignatureForError () + "'");
5135 if (IsExplicitImpl) {
5136 Expression expr = MemberName.Left.GetTypeExpression ();
5137 TypeExpr texpr = expr.ResolveAsTypeTerminal (this, false);
5141 InterfaceType = texpr.Type;
5143 if (!InterfaceType.IsInterface) {
5144 Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
5148 if (!ParentContainer.VerifyImplements (this))
5151 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
5157 protected bool IsTypePermitted ()
5159 if (MemberType == TypeManager.arg_iterator_type || MemberType == TypeManager.typed_reference_type) {
5160 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5166 protected override bool VerifyClsCompliance()
5168 if (base.VerifyClsCompliance ()) {
5172 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
5173 Report.Error (3010, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
5181 // Fields and Events both generate FieldBuilders, we use this to share
5182 // their common bits. This is also used to flag usage of the field
5184 abstract public class FieldBase : MemberBase {
5185 public FieldBuilder FieldBuilder;
5186 public Status status;
5187 protected Expression initializer;
5190 public enum Status : byte {
5191 HAS_OFFSET = 4 // Used by FieldMember.
5194 static string[] attribute_targets = new string [] { "field" };
5197 /// Symbol with same name in base class/struct
5199 public MemberInfo conflict_symbol;
5201 protected FieldBase (DeclSpace parent, Expression type, int mod,
5202 int allowed_mod, MemberName name, Attributes attrs)
5203 : base (parent, null, type, mod, allowed_mod, Modifiers.PRIVATE,
5208 public override AttributeTargets AttributeTargets {
5210 return AttributeTargets.Field;
5214 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5216 if (a.Type == TypeManager.marshal_as_attr_type) {
5217 UnmanagedMarshal marshal = a.GetMarshal (this);
5218 if (marshal != null) {
5219 FieldBuilder.SetMarshal (marshal);
5224 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
5225 a.Error_InvalidSecurityParent ();
5229 FieldBuilder.SetCustomAttribute (cb);
5232 public void EmitInitializer (EmitContext ec)
5234 // Replace DeclSpace because of partial classes
5235 ec.DeclContainer = DeclContainer;
5237 ec.IsFieldInitializer = true;
5238 initializer = initializer.Resolve (ec);
5239 ec.IsFieldInitializer = false;
5240 if (initializer == null)
5242 FieldExpr fe = new FieldExpr (FieldBuilder, Location, true);
5243 if ((ModFlags & Modifiers.STATIC) == 0)
5244 fe.InstanceExpression = new This (Location).Resolve (ec);
5246 ExpressionStatement a = new Assign (fe, initializer, Location);
5248 a = a.ResolveStatement (ec);
5252 Constant c = initializer as Constant;
5253 if (c != null && CanElideInitializer (c))
5256 a.EmitStatement (ec);
5259 bool CanElideInitializer (Constant c)
5261 if (MemberType == c.Type)
5262 return c.IsDefaultValue;
5264 if (c.Type == TypeManager.null_type)
5270 protected override bool CheckBase ()
5272 if (!base.CheckBase ())
5279 conflict_symbol = ParentContainer.FindBaseMemberWithSameName (Name, false);
5280 if (conflict_symbol == null) {
5281 if ((RootContext.WarningLevel >= 4) && ((ModFlags & Modifiers.NEW) != 0)) {
5282 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5287 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5288 Report.SymbolRelatedToPreviousError (conflict_symbol);
5289 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5290 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5296 public Expression Initializer {
5298 if (value != null) {
5299 this.initializer = value;
5300 ParentContainer.RegisterFieldForInitialization (this);
5305 protected virtual bool IsFieldClsCompliant {
5307 if (FieldBuilder == null)
5310 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5314 public override string[] ValidAttributeTargets {
5316 return attribute_targets;
5320 protected override bool VerifyClsCompliance ()
5322 if (!base.VerifyClsCompliance ())
5325 if (!IsFieldClsCompliant) {
5326 Report.Error (3003, Location, "Type of `{0}' is not CLS-compliant", GetSignatureForError ());
5332 public void SetAssigned ()
5334 caching_flags |= Flags.IsAssigned;
5338 public abstract class FieldMember : FieldBase
5340 protected FieldMember (DeclSpace parent, Expression type, int mod,
5341 int allowed_mod, MemberName name, Attributes attrs)
5342 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, name, attrs)
5344 if ((mod & Modifiers.ABSTRACT) != 0)
5345 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5348 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5350 if (a.Type == TypeManager.field_offset_attribute_type)
5352 status |= Status.HAS_OFFSET;
5354 if (!ParentContainer.HasExplicitLayout) {
5355 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5359 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5360 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5365 if (a.Type == TypeManager.fixed_buffer_attr_type) {
5366 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5370 base.ApplyAttributeBuilder (a, cb);
5373 public override bool Define()
5375 if (MemberType == null || Type == null)
5378 if (MemberType == TypeManager.void_type) {
5379 Report.Error (1547, Location, "Keyword 'void' cannot be used in this context");
5386 if (!Parent.AsAccessible (MemberType, ModFlags)) {
5387 Report.Error (52, Location,
5388 "Inconsistent accessibility: field type `" +
5389 TypeManager.CSharpName (MemberType) + "' is less " +
5390 "accessible than field `" + GetSignatureForError () + "'");
5394 if (!IsTypePermitted ())
5400 public override void Emit ()
5402 if (OptAttributes != null) {
5403 OptAttributes.Emit ();
5406 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & Modifiers.STATIC) == 0 && ParentContainer.HasExplicitLayout) {
5407 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.", GetSignatureForError ());
5414 // Represents header string for documentation comment.
5416 public override string DocCommentHeader {
5417 get { return "F:"; }
5421 interface IFixedBuffer
5423 FieldInfo Element { get; }
5424 Type ElementType { get; }
5427 public class FixedFieldExternal: IFixedBuffer
5429 FieldInfo element_field;
5431 public FixedFieldExternal (FieldInfo fi)
5433 element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5436 #region IFixedField Members
5438 public FieldInfo Element {
5440 return element_field;
5444 public Type ElementType {
5446 return element_field.FieldType;
5454 /// Fixed buffer implementation
5456 public class FixedField : FieldMember, IFixedBuffer
5458 public const string FixedElementName = "FixedElementField";
5459 static int GlobalCounter = 0;
5460 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5461 static FieldInfo[] fi;
5463 TypeBuilder fixed_buffer_type;
5464 FieldBuilder element;
5465 Expression size_expr;
5468 const int AllowedModifiers =
5471 Modifiers.PROTECTED |
5472 Modifiers.INTERNAL |
5475 public FixedField (DeclSpace parent, Expression type, int mod, string name,
5476 Expression size_expr, Attributes attrs, Location loc):
5477 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5479 if (RootContext.Version == LanguageVersion.ISO_1)
5480 Report.FeatureIsNotStandardized (loc, "fixed size buffers");
5482 this.size_expr = size_expr;
5485 public override bool Define()
5488 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) != 0)
5489 Report.Warning (-23, 1, Location, "Only private or internal fixed sized buffers are supported by .NET 1.x");
5492 if (ParentContainer.Kind != Kind.Struct) {
5493 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5494 GetSignatureForError ());
5498 if (!base.Define ())
5501 if (!TypeManager.IsPrimitiveType (MemberType)) {
5502 Report.Error (1663, Location, "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
5503 GetSignatureForError ());
5507 EmitContext ec = new EmitContext (this, Parent, Location, null, null, ModFlags);
5508 Constant c = size_expr.ResolveAsConstant (ec, this);
5512 IntConstant buffer_size_const = c.ToInt (Location);
5513 if (buffer_size_const == null)
5516 buffer_size = buffer_size_const.Value;
5518 if (buffer_size <= 0) {
5519 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5523 int type_size = Expression.GetTypeSize (MemberType);
5525 if (buffer_size > int.MaxValue / type_size) {
5526 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5527 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5531 buffer_size *= type_size;
5534 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5536 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
5537 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5538 element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5539 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5541 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5542 TypeManager.RegisterFieldBase (FieldBuilder, this);
5547 public override void Emit()
5550 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5552 object[] fi_val = new object[1];
5553 fi_val [0] = buffer_size;
5555 CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5556 ctor_args, fi, fi_val);
5557 fixed_buffer_type.SetCustomAttribute (cab);
5559 cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object[] { MemberType, buffer_size } );
5560 FieldBuilder.SetCustomAttribute (cab);
5564 protected override bool IsFieldClsCompliant {
5570 #region IFixedField Members
5572 public FieldInfo Element {
5578 public Type ElementType {
5588 // The Field class is used to represents class/struct fields during parsing.
5590 public class Field : FieldMember {
5592 // Modifiers allowed in a class declaration
5594 const int AllowedModifiers =
5597 Modifiers.PROTECTED |
5598 Modifiers.INTERNAL |
5601 Modifiers.VOLATILE |
5605 public Field (DeclSpace parent, Expression type, int mod, string name,
5606 Attributes attrs, Location loc)
5607 : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
5612 public override bool Define ()
5614 if (!base.Define ())
5617 if (RootContext.WarningLevel > 1){
5618 Type ptype = Parent.TypeBuilder.BaseType;
5620 // ptype is only null for System.Object while compiling corlib.
5622 TypeContainer.FindMembers (
5623 ptype, MemberTypes.Method,
5624 BindingFlags.Public |
5625 BindingFlags.Static | BindingFlags.Instance,
5626 System.Type.FilterName, Name);
5630 if ((ModFlags & Modifiers.VOLATILE) != 0){
5631 if (!MemberType.IsClass){
5632 Type vt = MemberType;
5634 if (TypeManager.IsEnumType (vt))
5635 vt = TypeManager.EnumToUnderlying (MemberType);
5637 if (!((vt == TypeManager.bool_type) ||
5638 (vt == TypeManager.sbyte_type) ||
5639 (vt == TypeManager.byte_type) ||
5640 (vt == TypeManager.short_type) ||
5641 (vt == TypeManager.ushort_type) ||
5642 (vt == TypeManager.int32_type) ||
5643 (vt == TypeManager.uint32_type) ||
5644 (vt == TypeManager.char_type) ||
5645 (vt == TypeManager.float_type) ||
5646 (!vt.IsValueType))){
5647 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5648 GetSignatureForError (), TypeManager.CSharpName (vt));
5653 if ((ModFlags & Modifiers.READONLY) != 0){
5654 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5655 GetSignatureForError ());
5660 FieldAttributes fa = Modifiers.FieldAttr (ModFlags);
5662 if (ParentContainer.Kind == Kind.Struct &&
5663 ((fa & FieldAttributes.Static) == 0) &&
5664 MemberType == Parent.TypeBuilder &&
5665 !TypeManager.IsBuiltinType (MemberType)){
5666 Report.Error (523, Location, "Struct member `" + Parent.Name + "." + Name +
5667 "' causes a cycle in the structure layout");
5672 FieldBuilder = Parent.TypeBuilder.DefineField (
5673 Name, MemberType, Modifiers.FieldAttr (ModFlags));
5675 TypeManager.RegisterFieldBase (FieldBuilder, this);
5677 catch (ArgumentException) {
5678 Report.Warning (-24, 1, Location, "The Microsoft runtime is unable to use [void|void*] as a field type, try using the Mono runtime.");
5685 protected override bool VerifyClsCompliance ()
5687 if (!base.VerifyClsCompliance ())
5690 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5691 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5699 // `set' and `get' accessors are represented with an Accessor.
5701 public class Accessor : IIteratorContainer {
5703 // Null if the accessor is empty, or a Block if not
5705 public const int AllowedModifiers =
5707 Modifiers.PROTECTED |
5708 Modifiers.INTERNAL |
5711 public ToplevelBlock Block;
5712 public Attributes Attributes;
5713 public Location Location;
5714 public int ModFlags;
5717 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Location loc)
5722 ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5725 public void SetYields ()
5731 // Ooouh Martin, templates are missing here.
5732 // When it will be possible move here a lot of child code and template method type.
5733 public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5734 protected MethodData method_data;
5735 protected ToplevelBlock block;
5736 protected ListDictionary declarative_security;
5738 // The accessor are created event if they are not wanted.
5739 // But we need them because their names are reserved.
5740 // Field says whether accessor will be emited or not
5741 public readonly bool IsDummy;
5743 protected readonly string prefix;
5745 ReturnParameter return_attributes;
5747 public AbstractPropertyEventMethod (MemberBase member, string prefix)
5748 : base (member.Parent, SetupName (prefix, member, member.Location), null)
5750 this.prefix = prefix;
5754 public AbstractPropertyEventMethod (MemberBase member, Accessor accessor,
5756 : base (member.Parent, SetupName (prefix, member, accessor.Location),
5757 accessor.Attributes)
5759 this.prefix = prefix;
5760 this.block = accessor.Block;
5763 static MemberName SetupName (string prefix, MemberBase member, Location loc)
5765 return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
5768 public void UpdateName (MemberBase member)
5770 SetMemberName (SetupName (prefix, member, Location));
5773 #region IMethodData Members
5775 public ToplevelBlock Block {
5785 public CallingConventions CallingConventions {
5787 return CallingConventions.Standard;
5791 public bool IsExcluded ()
5796 GenericMethod IMethodData.GenericMethod {
5802 public MemberName MethodName {
5808 public Type[] ParameterTypes {
5810 return ParameterInfo.Types;
5814 public abstract Parameters ParameterInfo { get ; }
5815 public abstract Type ReturnType { get; }
5816 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
5820 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5822 if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
5823 a.Type == TypeManager.conditional_attribute_type) {
5824 Report.Error (1667, a.Location,
5825 "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
5826 TypeManager.CSharpName (a.Type), a.GetValidTargets ());
5830 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (false)) {
5831 if (declarative_security == null)
5832 declarative_security = new ListDictionary ();
5833 a.ExtractSecurityPermissionSet (declarative_security);
5837 if (a.Target == AttributeTargets.Method) {
5838 method_data.MethodBuilder.SetCustomAttribute (cb);
5842 if (a.Target == AttributeTargets.ReturnValue) {
5843 if (return_attributes == null)
5844 return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
5846 return_attributes.ApplyAttributeBuilder (a, cb);
5850 ApplyToExtraTarget (a, cb);
5853 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
5855 System.Diagnostics.Debug.Fail ("You forgot to define special attribute target handling");
5858 public override bool Define()
5860 throw new NotSupportedException ();
5863 public virtual void Emit (DeclSpace parent)
5865 EmitMethod (parent);
5867 if (declarative_security != null) {
5868 foreach (DictionaryEntry de in declarative_security) {
5869 method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
5876 protected virtual void EmitMethod (DeclSpace parent)
5878 method_data.Emit (parent);
5881 public override bool IsClsComplianceRequired()
5886 public bool IsDuplicateImplementation (MethodCore method)
5888 if (!MemberName.Equals (method.MemberName))
5891 Type[] param_types = method.ParameterTypes;
5893 if (param_types.Length != ParameterTypes.Length)
5896 for (int i = 0; i < param_types.Length; i++)
5897 if (param_types [i] != ParameterTypes [i])
5900 Report.SymbolRelatedToPreviousError (method);
5901 Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
5905 public override bool IsUsed
5915 public new Location Location {
5917 return base.Location;
5922 // Represents header string for documentation comment.
5924 public override string DocCommentHeader {
5925 get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
5931 // Properties and Indexers both generate PropertyBuilders, we use this to share
5932 // their common bits.
5934 abstract public class PropertyBase : MethodCore {
5936 public class GetMethod : PropertyMethod
5938 static string[] attribute_targets = new string [] { "method", "return" };
5940 public GetMethod (MethodCore method):
5941 base (method, "get_")
5945 public GetMethod (MethodCore method, Accessor accessor):
5946 base (method, accessor, "get_")
5950 public override MethodBuilder Define (DeclSpace parent)
5952 base.Define (parent);
5954 method_data = new MethodData (method, ModFlags, flags, this);
5956 if (!method_data.Define (parent))
5959 return method_data.MethodBuilder;
5962 public override Type ReturnType {
5964 return method.MemberType;
5968 public override Parameters ParameterInfo {
5970 return Parameters.EmptyReadOnlyParameters;
5974 public override string[] ValidAttributeTargets {
5976 return attribute_targets;
5981 public class SetMethod : PropertyMethod {
5983 static string[] attribute_targets = new string [] { "method", "param", "return" };
5984 ImplicitParameter param_attr;
5985 protected Parameters parameters;
5987 public SetMethod (MethodCore method):
5988 base (method, "set_")
5992 public SetMethod (MethodCore method, Accessor accessor):
5993 base (method, accessor, "set_")
5997 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
5999 if (a.Target == AttributeTargets.Parameter) {
6000 if (param_attr == null)
6001 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6003 param_attr.ApplyAttributeBuilder (a, cb);
6007 base.ApplyAttributeBuilder (a, cb);
6010 public override Parameters ParameterInfo {
6016 protected virtual void DefineParameters ()
6018 parameters = new Parameters (
6019 new Parameter[] { new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, Location) },
6020 new Type[] { method.MemberType });
6023 public override MethodBuilder Define (DeclSpace parent)
6025 DefineParameters ();
6029 base.Define (parent);
6031 method_data = new MethodData (method, ModFlags, flags, this);
6033 if (!method_data.Define (parent))
6036 return method_data.MethodBuilder;
6039 public override Type ReturnType {
6041 return TypeManager.void_type;
6045 public override string[] ValidAttributeTargets {
6047 return attribute_targets;
6052 static string[] attribute_targets = new string [] { "property" };
6054 public abstract class PropertyMethod : AbstractPropertyEventMethod
6056 protected readonly MethodCore method;
6057 protected MethodAttributes flags;
6060 public PropertyMethod (MethodCore method, string prefix)
6061 : base (method, prefix)
6063 this.method = method;
6066 public PropertyMethod (MethodCore method, Accessor accessor,
6068 : base (method, accessor, prefix)
6070 this.method = method;
6071 this.ModFlags = accessor.ModFlags;
6072 yields = accessor.Yields;
6074 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6075 Report.FeatureIsNotStandardized (Location, "access modifiers on properties");
6079 public override AttributeTargets AttributeTargets {
6081 return AttributeTargets.Method;
6085 public override bool IsClsComplianceRequired ()
6087 return method.IsClsComplianceRequired ();
6090 public virtual MethodBuilder Define (DeclSpace parent)
6092 if (!method.CheckAbstractAndExtern (block != null))
6095 TypeContainer container = ((TypeContainer) parent).PartialContainer;
6098 // Check for custom access modifier
6100 if (ModFlags == 0) {
6101 ModFlags = method.ModFlags;
6102 flags = method.flags;
6104 if (container.Kind == Kind.Interface)
6105 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6106 GetSignatureForError ());
6108 if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6109 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6112 CheckModifiers (ModFlags);
6113 ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6114 ModFlags |= Modifiers.PROPERTY_CUSTOM;
6115 flags = Modifiers.MethodAttr (ModFlags);
6116 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6120 // Setup iterator if we are one
6123 Iterator iterator = new Iterator (this, Parent as TypeContainer, null, ModFlags);
6125 if (!iterator.DefineIterator ())
6132 public bool HasCustomAccessModifier
6135 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6139 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6141 return new EmitContext (method,
6142 ds, method.ds, method.Location, ig, ReturnType,
6143 method.ModFlags, false);
6146 public override ObsoleteAttribute GetObsoleteAttribute ()
6148 return method.GetObsoleteAttribute ();
6151 public override string GetSignatureForError()
6153 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6156 void CheckModifiers (int modflags)
6159 int mflags = method.ModFlags & Modifiers.Accessibility;
6161 if ((mflags & Modifiers.PUBLIC) != 0) {
6162 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6164 else if ((mflags & Modifiers.PROTECTED) != 0) {
6165 if ((mflags & Modifiers.INTERNAL) != 0)
6166 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6168 flags |= Modifiers.PRIVATE;
6170 else if ((mflags & Modifiers.INTERNAL) != 0)
6171 flags |= Modifiers.PRIVATE;
6173 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6174 Report.Error (273, Location,
6175 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6176 GetSignatureForError (), method.GetSignatureForError ());
6180 public override bool MarkForDuplicationCheck ()
6182 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 (DeclSpace parent, Expression type, int mod_flags,
6194 int allowed_mod, bool is_iface, MemberName name,
6195 Parameters parameters, Attributes attrs)
6196 : base (parent, null, type, mod_flags, allowed_mod, is_iface, name,
6201 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6203 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6204 a.Error_InvalidSecurityParent ();
6208 PropertyBuilder.SetCustomAttribute (cb);
6211 public override AttributeTargets AttributeTargets {
6213 return AttributeTargets.Property;
6217 public override bool Define ()
6222 if (!IsTypePermitted ())
6228 protected override bool DoDefine ()
6230 if (!base.DoDefine ())
6234 // Accessors modifiers check
6236 if (Get.ModFlags != 0 && Set.ModFlags != 0) {
6237 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6238 GetSignatureForError ());
6242 if ((Get.IsDummy || Set.IsDummy)
6243 && (Get.ModFlags != 0 || Set.ModFlags != 0) && (ModFlags & Modifiers.OVERRIDE) == 0) {
6244 Report.Error (276, Location,
6245 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6246 GetSignatureForError ());
6250 if (MemberType.IsAbstract && MemberType.IsSealed) {
6251 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6255 ec = new EmitContext (this, Parent, Location, null, MemberType, ModFlags);
6259 protected override bool CheckForDuplications ()
6261 ArrayList ar = ParentContainer.Indexers;
6263 int arLen = ar.Count;
6265 for (int i = 0; i < arLen; i++) {
6266 Indexer m = (Indexer) ar [i];
6267 if (IsDuplicateImplementation (m))
6272 ar = ParentContainer.Properties;
6274 int arLen = ar.Count;
6276 for (int i = 0; i < arLen; i++) {
6277 Property m = (Property) ar [i];
6278 if (IsDuplicateImplementation (m))
6286 // TODO: rename to Resolve......
6287 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6289 PropertyInfo base_property = ParentContainer.BaseCache.FindMemberToOverride (
6290 Parent.TypeBuilder, Name, ParameterTypes, null, true) as PropertyInfo;
6292 if (base_property == null)
6295 base_ret_type = base_property.PropertyType;
6296 MethodInfo get_accessor = base_property.GetGetMethod (true);
6297 MethodInfo set_accessor = base_property.GetSetMethod (true);
6298 MethodAttributes get_accessor_access, set_accessor_access;
6300 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
6301 if (Get != null && !Get.IsDummy && get_accessor == null) {
6302 Report.SymbolRelatedToPreviousError (base_property);
6303 Report.Error (545, Location, "`{0}.get': cannot override because `{1}' does not have an overridable get accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6306 if (Set != null && !Set.IsDummy && set_accessor == null) {
6307 Report.SymbolRelatedToPreviousError (base_property);
6308 Report.Error (546, Location, "`{0}.set': cannot override because `{1}' does not have an overridable set accessor", GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6313 // Check base class accessors access
6316 // TODO: rewrite to reuse Get|Set.CheckAccessModifiers and share code there
6317 get_accessor_access = set_accessor_access = 0;
6318 if ((ModFlags & Modifiers.NEW) == 0) {
6319 if (get_accessor != null) {
6320 MethodAttributes get_flags = Modifiers.MethodAttr (Get.ModFlags != 0 ? Get.ModFlags : ModFlags);
6321 get_accessor_access = (get_accessor.Attributes & MethodAttributes.MemberAccessMask);
6323 if (!Get.IsDummy && !CheckAccessModifiers (get_flags & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6324 Error_CannotChangeAccessModifiers (get_accessor, get_accessor_access, ".get");
6327 if (set_accessor != null) {
6328 MethodAttributes set_flags = Modifiers.MethodAttr (Set.ModFlags != 0 ? Set.ModFlags : ModFlags);
6329 set_accessor_access = (set_accessor.Attributes & MethodAttributes.MemberAccessMask);
6331 if (!Set.IsDummy && !CheckAccessModifiers (set_flags & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6332 Error_CannotChangeAccessModifiers (set_accessor, set_accessor_access, ".set");
6337 // Get the less restrictive access
6339 return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6342 public override void Emit ()
6345 // The PropertyBuilder can be null for explicit implementations, in that
6346 // case, we do not actually emit the ".property", so there is nowhere to
6347 // put the attribute
6349 if (PropertyBuilder != null && OptAttributes != null)
6350 OptAttributes.Emit ();
6362 /// Tests whether accessors are not in collision with some method (CS0111)
6364 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6366 return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6369 public override bool IsUsed
6375 return Get.IsUsed | Set.IsUsed;
6379 protected override void SetMemberName (MemberName new_name)
6381 base.SetMemberName (new_name);
6383 Get.UpdateName (this);
6384 Set.UpdateName (this);
6387 public override string[] ValidAttributeTargets {
6389 return attribute_targets;
6394 // Represents header string for documentation comment.
6396 public override string DocCommentHeader {
6397 get { return "P:"; }
6401 public class Property : PropertyBase {
6402 const int AllowedModifiers =
6405 Modifiers.PROTECTED |
6406 Modifiers.INTERNAL |
6410 Modifiers.OVERRIDE |
6411 Modifiers.ABSTRACT |
6414 Modifiers.METHOD_YIELDS |
6417 const int AllowedInterfaceModifiers =
6420 public Property (DeclSpace parent, Expression type, int mod, bool is_iface,
6421 MemberName name, Attributes attrs, Accessor get_block,
6423 : base (parent, type, mod,
6424 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6425 is_iface, name, Parameters.EmptyReadOnlyParameters, attrs)
6427 if (get_block == null)
6428 Get = new GetMethod (this);
6430 Get = new GetMethod (this, get_block);
6432 if (set_block == null)
6433 Set = new SetMethod (this);
6435 Set = new SetMethod (this, set_block);
6438 public override bool Define ()
6440 if (!DoDefineBase ())
6443 if (!base.Define ())
6449 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6452 GetBuilder = Get.Define (Parent);
6453 if (GetBuilder == null)
6457 SetBuilder = Set.Define (Parent);
6459 if (SetBuilder == null)
6463 // FIXME - PropertyAttributes.HasDefault ?
6465 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6466 MemberName.ToString (), PropertyAttributes.None, MemberType, null);
6469 PropertyBuilder.SetGetMethod (GetBuilder);
6472 PropertyBuilder.SetSetMethod (SetBuilder);
6474 TypeManager.RegisterProperty (PropertyBuilder, this);
6480 /// Gigantic workaround for lameness in SRE follows :
6481 /// This class derives from EventInfo and attempts to basically
6482 /// wrap around the EventBuilder so that FindMembers can quickly
6483 /// return this in it search for members
6485 public class MyEventBuilder : EventInfo {
6488 // We use this to "point" to our Builder which is
6489 // not really a MemberInfo
6491 EventBuilder MyBuilder;
6494 // We "catch" and wrap these methods
6496 MethodInfo raise, remove, add;
6498 EventAttributes attributes;
6499 Type declaring_type, reflected_type, event_type;
6504 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6506 MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6508 // And now store the values in our own fields.
6510 declaring_type = type_builder;
6512 reflected_type = type_builder;
6514 attributes = event_attr;
6517 this.event_type = event_type;
6521 // Methods that you have to override. Note that you only need
6522 // to "implement" the variants that take the argument (those are
6523 // the "abstract" methods, the others (GetAddMethod()) are
6526 public override MethodInfo GetAddMethod (bool nonPublic)
6531 public override MethodInfo GetRemoveMethod (bool nonPublic)
6536 public override MethodInfo GetRaiseMethod (bool nonPublic)
6542 // These methods make "MyEventInfo" look like a Builder
6544 public void SetRaiseMethod (MethodBuilder raiseMethod)
6546 raise = raiseMethod;
6547 MyBuilder.SetRaiseMethod (raiseMethod);
6550 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6552 remove = removeMethod;
6553 MyBuilder.SetRemoveOnMethod (removeMethod);
6556 public void SetAddOnMethod (MethodBuilder addMethod)
6559 MyBuilder.SetAddOnMethod (addMethod);
6562 public void SetCustomAttribute (CustomAttributeBuilder cb)
6564 MyBuilder.SetCustomAttribute (cb);
6567 public override object [] GetCustomAttributes (bool inherit)
6569 // FIXME : There's nothing which can be seemingly done here because
6570 // we have no way of getting at the custom attribute objects of the
6575 public override object [] GetCustomAttributes (Type t, bool inherit)
6577 // FIXME : Same here !
6581 public override bool IsDefined (Type t, bool b)
6586 public override EventAttributes Attributes {
6592 public override string Name {
6598 public override Type DeclaringType {
6600 return declaring_type;
6604 public override Type ReflectedType {
6606 return reflected_type;
6610 public Type EventType {
6616 public void SetUsed ()
6618 if (my_event != null) {
6619 my_event.SetAssigned ();
6620 my_event.SetMemberIsUsed ();
6626 /// For case when event is declared like property (with add and remove accessors).
6628 public class EventProperty: Event {
6630 static string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6632 public EventProperty (DeclSpace parent, Expression type, int mod_flags,
6633 bool is_iface, MemberName name,
6634 Attributes attrs, Accessor add, Accessor remove)
6635 : base (parent, type, mod_flags, is_iface, name, attrs)
6637 Add = new AddDelegateMethod (this, add);
6638 Remove = new RemoveDelegateMethod (this, remove);
6640 // For this event syntax we don't report error CS0067
6641 // because it is hard to do it.
6645 public override string[] ValidAttributeTargets {
6647 return attribute_targets;
6653 /// Event is declared like field.
6655 public class EventField : Event {
6657 static string[] attribute_targets = new string [] { "event", "field", "method" };
6658 static string[] attribute_targets_interface = new string[] { "event", "method" };
6660 public EventField (DeclSpace parent, Expression type, int mod_flags,
6661 bool is_iface, MemberName name,
6663 : base (parent, type, mod_flags, is_iface, name, attrs)
6665 Add = new AddDelegateMethod (this);
6666 Remove = new RemoveDelegateMethod (this);
6669 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6671 if (a.Target == AttributeTargets.Field) {
6672 FieldBuilder.SetCustomAttribute (cb);
6676 if (a.Target == AttributeTargets.Method) {
6677 Add.ApplyAttributeBuilder (a, cb);
6678 Remove.ApplyAttributeBuilder (a, cb);
6682 base.ApplyAttributeBuilder (a, cb);
6685 public override bool Define()
6687 if (!base.Define ())
6690 if (initializer != null) {
6691 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
6692 Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
6693 GetSignatureForError ());
6701 public override string[] ValidAttributeTargets {
6703 return IsInterface ? attribute_targets_interface : attribute_targets;
6708 public abstract class Event : FieldBase {
6710 protected sealed class AddDelegateMethod: DelegateMethod
6713 public AddDelegateMethod (Event method):
6714 base (method, "add_")
6718 public AddDelegateMethod (Event method, Accessor accessor):
6719 base (method, accessor, "add_")
6723 protected override MethodInfo DelegateMethodInfo {
6725 return TypeManager.delegate_combine_delegate_delegate;
6731 protected sealed class RemoveDelegateMethod: DelegateMethod
6733 public RemoveDelegateMethod (Event method):
6734 base (method, "remove_")
6738 public RemoveDelegateMethod (Event method, Accessor accessor):
6739 base (method, accessor, "remove_")
6743 protected override MethodInfo DelegateMethodInfo {
6745 return TypeManager.delegate_remove_delegate_delegate;
6751 public abstract class DelegateMethod : AbstractPropertyEventMethod
6753 protected readonly Event method;
6754 ImplicitParameter param_attr;
6756 static string[] attribute_targets = new string [] { "method", "param", "return" };
6758 public DelegateMethod (Event method, string prefix)
6759 : base (method, prefix)
6761 this.method = method;
6764 public DelegateMethod (Event method, Accessor accessor, string prefix)
6765 : base (method, accessor, prefix)
6767 this.method = method;
6770 protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6772 if (a.Target == AttributeTargets.Parameter) {
6773 if (param_attr == null)
6774 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6776 param_attr.ApplyAttributeBuilder (a, cb);
6780 base.ApplyAttributeBuilder (a, cb);
6783 public override AttributeTargets AttributeTargets {
6785 return AttributeTargets.Method;
6789 public override bool IsClsComplianceRequired ()
6791 return method.IsClsComplianceRequired ();
6794 public MethodBuilder Define (DeclSpace parent)
6796 method_data = new MethodData (method, method.ModFlags,
6797 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
6799 if (!method_data.Define (parent))
6802 MethodBuilder mb = method_data.MethodBuilder;
6803 ParameterInfo.ApplyAttributes (mb);
6808 protected override void EmitMethod (DeclSpace parent)
6810 if (block != null) {
6811 base.EmitMethod (parent);
6815 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
6818 ILGenerator ig = method_data.MethodBuilder.GetILGenerator ();
6819 FieldInfo field_info = (FieldInfo)method.FieldBuilder;
6821 method_data.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Synchronized);
6822 if ((method.ModFlags & Modifiers.STATIC) != 0) {
6823 ig.Emit (OpCodes.Ldsfld, field_info);
6824 ig.Emit (OpCodes.Ldarg_0);
6825 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6826 ig.Emit (OpCodes.Castclass, method.MemberType);
6827 ig.Emit (OpCodes.Stsfld, field_info);
6829 ig.Emit (OpCodes.Ldarg_0);
6830 ig.Emit (OpCodes.Ldarg_0);
6831 ig.Emit (OpCodes.Ldfld, field_info);
6832 ig.Emit (OpCodes.Ldarg_1);
6833 ig.Emit (OpCodes.Call, DelegateMethodInfo);
6834 ig.Emit (OpCodes.Castclass, method.MemberType);
6835 ig.Emit (OpCodes.Stfld, field_info);
6837 ig.Emit (OpCodes.Ret);
6840 protected abstract MethodInfo DelegateMethodInfo { get; }
6842 public override Type ReturnType {
6844 return TypeManager.void_type;
6848 public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6850 return new EmitContext (
6851 ds, method.Parent, Location, ig, ReturnType,
6852 method.ModFlags, false);
6855 public override ObsoleteAttribute GetObsoleteAttribute ()
6857 return method.GetObsoleteAttribute ();
6860 public override string[] ValidAttributeTargets {
6862 return attribute_targets;
6866 public override Parameters ParameterInfo {
6868 return method.parameters;
6875 const int AllowedModifiers =
6878 Modifiers.PROTECTED |
6879 Modifiers.INTERNAL |
6884 Modifiers.OVERRIDE |
6888 const int AllowedInterfaceModifiers =
6891 public DelegateMethod Add, Remove;
6892 public MyEventBuilder EventBuilder;
6893 public MethodBuilder AddBuilder, RemoveBuilder;
6894 Parameters parameters;
6896 protected Event (DeclSpace parent, Expression type, int mod_flags,
6897 bool is_iface, MemberName name, Attributes attrs)
6898 : base (parent, type, mod_flags,
6899 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
6902 IsInterface = is_iface;
6905 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6907 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
6908 a.Error_InvalidSecurityParent ();
6912 EventBuilder.SetCustomAttribute (cb);
6915 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6917 return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
6920 public override AttributeTargets AttributeTargets {
6922 return AttributeTargets.Event;
6926 public override bool Define ()
6928 EventAttributes e_attr;
6929 e_attr = EventAttributes.None;
6931 if (!DoDefineBase ())
6937 if (!TypeManager.IsDelegateType (MemberType)) {
6938 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
6942 parameters = new Parameters (
6943 new Parameter[] { new Parameter (MemberType, "value", Parameter.Modifier.NONE, null, Location) },
6944 new Type[] { MemberType } );
6950 // Now define the accessors
6953 AddBuilder = Add.Define (Parent);
6954 if (AddBuilder == null)
6957 RemoveBuilder = Remove.Define (Parent);
6958 if (RemoveBuilder == null)
6961 EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, e_attr, MemberType);
6963 if (Add.Block == null && Remove.Block == null && !IsInterface) {
6964 FieldBuilder = Parent.TypeBuilder.DefineField (
6966 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
6967 TypeManager.RegisterPrivateFieldOfEvent (
6968 (EventInfo) EventBuilder, FieldBuilder);
6969 TypeManager.RegisterFieldBase (FieldBuilder, this);
6972 EventBuilder.SetAddOnMethod (AddBuilder);
6973 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
6975 TypeManager.RegisterEvent (EventBuilder, AddBuilder, RemoveBuilder);
6979 protected override bool CheckBase ()
6981 if (!base.CheckBase ())
6984 if (conflict_symbol != null && (ModFlags & Modifiers.NEW) == 0) {
6985 if (!(conflict_symbol is EventInfo)) {
6986 Report.SymbolRelatedToPreviousError (conflict_symbol);
6987 Report.Error (72, Location, "Event `{0}' can override only event", GetSignatureForError ());
6995 public override void Emit ()
6997 if (OptAttributes != null) {
6998 OptAttributes.Emit ();
7002 Remove.Emit (Parent);
7007 public override string GetSignatureForError ()
7009 return base.GetSignatureForError ();
7013 // Represents header string for documentation comment.
7015 public override string DocCommentHeader {
7016 get { return "E:"; }
7021 public class Indexer : PropertyBase, IIteratorContainer {
7023 class GetIndexerMethod : GetMethod
7025 public GetIndexerMethod (MethodCore method):
7030 public GetIndexerMethod (MethodCore method, Accessor accessor):
7031 base (method, accessor)
7035 public override Parameters ParameterInfo {
7037 return method.ParameterInfo;
7042 class SetIndexerMethod: SetMethod
7044 public SetIndexerMethod (MethodCore method):
7049 public SetIndexerMethod (MethodCore method, Accessor accessor):
7050 base (method, accessor)
7054 protected override void DefineParameters ()
7056 parameters = Parameters.MergeGenerated (method.Parameters,
7057 new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
7061 const int AllowedModifiers =
7064 Modifiers.PROTECTED |
7065 Modifiers.INTERNAL |
7069 Modifiers.OVERRIDE |
7074 const int AllowedInterfaceModifiers =
7078 // Are we implementing an interface ?
7080 public Indexer (DeclSpace parent, Expression type, MemberName name, int mod,
7081 bool is_iface, Parameters parameters, Attributes attrs,
7082 Accessor get_block, Accessor set_block)
7083 : base (parent, type, mod,
7084 is_iface ? AllowedInterfaceModifiers : AllowedModifiers,
7085 is_iface, name, parameters, attrs)
7087 if (get_block == null)
7088 Get = new GetIndexerMethod (this);
7090 Get = new GetIndexerMethod (this, get_block);
7092 if (set_block == null)
7093 Set = new SetIndexerMethod (this);
7095 Set = new SetIndexerMethod (this, set_block);
7098 public override bool Define ()
7100 if (!DoDefineBase ())
7103 if (!base.Define ())
7106 if (MemberType == TypeManager.void_type) {
7107 Report.Error (620, Location, "Indexers cannot have void type");
7111 if (OptAttributes != null) {
7112 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7113 if (indexer_attr != null) {
7114 // Remove the attribute from the list because it is not emitted
7115 OptAttributes.Attrs.Remove (indexer_attr);
7117 ShortName = indexer_attr.GetIndexerAttributeValue ();
7119 if (IsExplicitImpl) {
7120 Report.Error (415, indexer_attr.Location,
7121 "The `IndexerName' attribute is valid only on an " +
7122 "indexer that is not an explicit interface member declaration");
7126 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7127 Report.Error (609, indexer_attr.Location,
7128 "Cannot set the `IndexerName' attribute on an indexer marked override");
7132 if (!Tokenizer.IsValidIdentifier (ShortName)) {
7133 Report.Error (633, indexer_attr.Location,
7134 "The argument to the `IndexerName' attribute must be a valid identifier");
7140 if (InterfaceType != null) {
7141 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7142 if (base_IndexerName != Name)
7143 ShortName = base_IndexerName;
7146 if (!ParentContainer.AddToMemberContainer (this) ||
7147 !ParentContainer.AddToMemberContainer (Get) || !ParentContainer.AddToMemberContainer (Set))
7153 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7155 GetBuilder = Get.Define (Parent);
7156 if (GetBuilder == null)
7160 // Setup iterator if we are one
7162 if ((ModFlags & Modifiers.METHOD_YIELDS) != 0){
7163 Iterator iterator = new Iterator (
7164 Get, Parent, null, ModFlags);
7166 if (!iterator.DefineIterator ())
7171 SetBuilder = Set.Define (Parent);
7173 if (SetBuilder == null)
7178 // Now name the parameters
7180 Parameter [] p = Parameters.FixedParameters;
7182 // TODO: should be done in parser and it needs to do cycle
7183 if ((p [0].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
7184 Report.Error (631, Location, "ref and out are not valid in this context");
7189 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7190 Name, PropertyAttributes.None, MemberType, ParameterTypes);
7193 PropertyBuilder.SetGetMethod (GetBuilder);
7196 PropertyBuilder.SetSetMethod (SetBuilder);
7198 TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, ParameterTypes);
7203 public override string GetSignatureForError ()
7205 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7206 if (MemberName.Left != null) {
7208 sb.Append (MemberName.Left);
7211 sb.Append (".this");
7212 sb.Append (Parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7213 return sb.ToString ();
7216 public override bool MarkForDuplicationCheck ()
7218 caching_flags |= Flags.TestMethodDuplication;
7223 public class Operator : MethodCore, IIteratorContainer {
7225 const int AllowedModifiers =
7231 public enum OpType : byte {
7241 // Unary and Binary operators
7264 // Implicit and Explicit
7268 // Just because of enum
7272 public readonly OpType OperatorType;
7273 public MethodBuilder OperatorMethodBuilder;
7275 public Method OperatorMethod;
7277 static string[] attribute_targets = new string [] { "method", "return" };
7279 public Operator (DeclSpace parent, OpType type, Expression ret_type,
7280 int mod_flags, Parameters parameters,
7281 ToplevelBlock block, Attributes attrs, Location loc)
7282 : base (parent, null, ret_type, mod_flags, AllowedModifiers, false,
7283 new MemberName ("op_" + type, loc), attrs, parameters)
7285 OperatorType = type;
7289 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7291 OperatorMethod.ApplyAttributeBuilder (a, cb);
7294 public override AttributeTargets AttributeTargets {
7296 return AttributeTargets.Method;
7300 protected override bool CheckForDuplications ()
7302 ArrayList ar = ParentContainer.Operators;
7304 int arLen = ar.Count;
7306 for (int i = 0; i < arLen; i++) {
7307 Operator o = (Operator) ar [i];
7308 if (IsDuplicateImplementation (o))
7313 ar = ParentContainer.Methods;
7315 int arLen = ar.Count;
7317 for (int i = 0; i < arLen; i++) {
7318 Method m = (Method) ar [i];
7319 if (IsDuplicateImplementation (m))
7327 public override bool Define ()
7329 const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7330 if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7331 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7338 if (MemberType == TypeManager.void_type) {
7339 Report.Error (590, Location, "User-defined operators cannot return void");
7343 OperatorMethod = new Method (
7344 Parent, null, Type, ModFlags, false, MemberName,
7345 Parameters, OptAttributes);
7347 OperatorMethod.Block = Block;
7348 OperatorMethod.IsOperator = this;
7349 OperatorMethod.flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7350 OperatorMethod.Define ();
7352 if (OperatorMethod.MethodBuilder == null)
7355 OperatorMethodBuilder = OperatorMethod.MethodBuilder;
7357 Type[] parameter_types = OperatorMethod.ParameterTypes;
7358 Type declaring_type = OperatorMethod.MethodData.DeclaringType;
7359 Type return_type = OperatorMethod.ReturnType;
7360 Type first_arg_type = parameter_types [0];
7365 // Rules for conversion operators
7367 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7368 if (first_arg_type == return_type && first_arg_type == declaring_type){
7369 Report.Error (555, Location,
7370 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7374 if (first_arg_type != declaring_type && return_type != declaring_type){
7377 "User-defined conversion must convert to or from the " +
7382 if (first_arg_type.IsInterface || return_type.IsInterface){
7383 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7384 GetSignatureForError ());
7388 if (first_arg_type.IsSubclassOf (return_type) || return_type.IsSubclassOf (first_arg_type)) {
7389 if (declaring_type.IsSubclassOf (return_type) || declaring_type.IsSubclassOf (first_arg_type)) {
7390 Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from base class",
7391 GetSignatureForError ());
7394 Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from derived class",
7395 GetSignatureForError ());
7398 } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7399 if (first_arg_type != declaring_type || parameter_types [1] != TypeManager.int32_type) {
7400 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");
7403 } else if (Parameters.Count == 1) {
7404 // Checks for Unary operators
7406 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7407 if (return_type != declaring_type && !return_type.IsSubclassOf (declaring_type)) {
7408 Report.Error (448, Location,
7409 "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7412 if (first_arg_type != declaring_type) {
7414 559, Location, "The parameter type for ++ or -- operator must be the containing type");
7419 if (first_arg_type != declaring_type){
7422 "The parameter of a unary operator must be the " +
7427 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7428 if (return_type != TypeManager.bool_type){
7431 "The return type of operator True or False " +
7438 // Checks for Binary operators
7440 if (first_arg_type != declaring_type &&
7441 parameter_types [1] != declaring_type){
7444 "One of the parameters of a binary operator must " +
7445 "be the containing type");
7453 public override void Emit ()
7456 // abstract or extern methods have no bodies
7458 if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7461 OperatorMethod.Emit ();
7465 // Operator cannot be override
7466 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7471 public static string GetName (OpType ot)
7474 case OpType.LogicalNot:
7476 case OpType.OnesComplement:
7478 case OpType.Increment:
7480 case OpType.Decrement:
7486 case OpType.Addition:
7488 case OpType.Subtraction:
7490 case OpType.UnaryPlus:
7492 case OpType.UnaryNegation:
7494 case OpType.Multiply:
7496 case OpType.Division:
7498 case OpType.Modulus:
7500 case OpType.BitwiseAnd:
7502 case OpType.BitwiseOr:
7504 case OpType.ExclusiveOr:
7506 case OpType.LeftShift:
7508 case OpType.RightShift:
7510 case OpType.Equality:
7512 case OpType.Inequality:
7514 case OpType.GreaterThan:
7516 case OpType.LessThan:
7518 case OpType.GreaterThanOrEqual:
7520 case OpType.LessThanOrEqual:
7522 case OpType.Implicit:
7524 case OpType.Explicit:
7530 public static OpType GetOperatorType (string name)
7532 if (name.StartsWith ("op_")){
7533 for (int i = 0; i < Unary.oper_names.Length; ++i) {
7534 if (Unary.oper_names [i] == name)
7538 for (int i = 0; i < Binary.oper_names.Length; ++i) {
7539 if (Binary.oper_names [i] == name)
7546 public override string GetSignatureForError ()
7548 StringBuilder sb = new StringBuilder ();
7549 if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7550 sb.AppendFormat ("{0}.{1} operator {2}", Parent.GetSignatureForError (), GetName (OperatorType), Type.Type == null ? Type.ToString () : TypeManager.CSharpName (Type.Type));
7553 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7556 sb.Append (Parameters.GetSignatureForError ());
7557 return sb.ToString ();
7560 public override bool MarkForDuplicationCheck ()
7562 caching_flags |= Flags.TestMethodDuplication;
7566 public override string[] ValidAttributeTargets {
7568 return attribute_targets;
7574 // This is used to compare method signatures
7576 struct MethodSignature {
7578 public Type RetType;
7579 public Type [] Parameters;
7582 /// This delegate is used to extract methods which have the
7583 /// same signature as the argument
7585 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7587 public MethodSignature (string name, Type ret_type, Type [] parameters)
7592 if (parameters == null)
7593 Parameters = Type.EmptyTypes;
7595 Parameters = parameters;
7598 public override string ToString ()
7601 if (Parameters.Length != 0){
7602 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
7603 for (int i = 0; i < Parameters.Length; i++){
7604 sb.Append (Parameters [i]);
7605 if (i+1 < Parameters.Length)
7608 pars = sb.ToString ();
7611 return String.Format ("{0} {1} ({2})", RetType, Name, pars);
7614 public override int GetHashCode ()
7616 return Name.GetHashCode ();
7619 public override bool Equals (Object o)
7621 MethodSignature other = (MethodSignature) o;
7623 if (other.Name != Name)
7626 if (other.RetType != RetType)
7629 if (Parameters == null){
7630 if (other.Parameters == null)
7635 if (other.Parameters == null)
7638 int c = Parameters.Length;
7639 if (other.Parameters.Length != c)
7642 for (int i = 0; i < c; i++)
7643 if (other.Parameters [i] != Parameters [i])
7649 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
7651 MethodSignature sig = (MethodSignature) filter_criteria;
7653 if (m.Name != sig.Name)
7657 MethodInfo mi = m as MethodInfo;
7658 PropertyInfo pi = m as PropertyInfo;
7661 ReturnType = mi.ReturnType;
7662 else if (pi != null)
7663 ReturnType = pi.PropertyType;
7668 // we use sig.RetType == null to mean `do not check the
7669 // method return value.
7671 if (sig.RetType != null)
7672 if (ReturnType != sig.RetType)
7677 args = TypeManager.GetParameterData (mi).Types;
7679 args = TypeManager.GetArgumentTypes (pi);
7680 Type [] sigp = sig.Parameters;
7682 if (args.Length != sigp.Length)
7685 for (int i = args.Length; i > 0; ){
7687 if (args [i] != sigp [i])